qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
248,350
<p>The windows installed on my machine has the locale <code>en_AU</code> and that's what JasperReports uses. I already tried changing the locale of all users, including the Administrator but it still uses <code>en_AU</code>.</p> <p>How can I change that locale? Is it possible to change the <code>REPORT_LOCALE</code> parameter on my report?</p>
[ { "answer_id": 772406, "author": "waxwing", "author_id": 90566, "author_profile": "https://Stackoverflow.com/users/90566", "pm_score": 6, "selected": false, "text": "REPORT_LOCALE InputStream reportTemplate = getReportTemplate();\nJRDataSource dataSource = getDataSource();\n\njava.util.Map parameters = getParameters();\njava.util.Locale locale = new Locale( \"en\", \"US\" );\nparameters.put( JRParameter.REPORT_LOCALE, locale );\n\nJasperFillManager.fillReport( reportTemplate, parameters, dataSource );\n" }, { "answer_id": 65848996, "author": "siom", "author_id": 2833924, "author_profile": "https://Stackoverflow.com/users/2833924", "pm_score": 0, "selected": false, "text": "JasperFillManager java -Duser.language=de -Duser.country=CH ...\n" }, { "answer_id": 69773254, "author": "Jan Bodnar", "author_id": 2008247, "author_profile": "https://Stackoverflow.com/users/2008247", "pm_score": 0, "selected": false, "text": "net.sf.jasperreports.default.locale jasperreports.properties" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16020/" ]
248,351
<p>I want to create a javascript badge that displays a list of links. We host the javascript on our domain. Other sites can put an empty div tag on their page and at the bottom a reference to our javascript that would render the content in the div tag. How do you implement something like this?</p>
[ { "answer_id": 248379, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<div id=\"mywidget\"></div>\n <script type=\"text/javascript\" src=\"http://yourdomain.com/mywidget.js\"></script>\n <script type=\"text/javascript\">\n document.body.onload = loadYourWidget();\n</script>\n" }, { "answer_id": 248392, "author": "Gabe Hollombe", "author_id": 30632, "author_profile": "https://Stackoverflow.com/users/30632", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\" src=\"http://yourdomain.com/mywidget.js\"></script>\n <div id=\"mywidget\"></div> document.getElementById('mywidget').innerHTML = \"<a href=''>LinkOne</a> <a href=''>LinkTwo</a>\";\n" }, { "answer_id": 248451, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 3, "selected": false, "text": "<script id=\"my-script\" src=\"http://example.com/my-script.js\"></script>\n var scriptTag, myDiv;\nscriptTag = document.getElementById('my-script');\nmyDiv = document.createElement('DIV');\nmyDiv.innerHTML = '<p>Wow, cool!</p>';\nscriptTag.parentNode.replaceChild(myDiv, scriptTag);\n" }, { "answer_id": 248514, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 1, "selected": false, "text": "document.write <script type=\"text/javascript\" src=\"http://domain.com/badge.js\"></script>\n var links = [\n '<a href=\"#\">One</a>',\n '<a href=\"#\">Two</a>', \n '<a href=\"#\">Three</a>'\n];\n\ndocument.write(\"<div>\" + links.join(\", \") + \"</div>\");\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3784/" ]
248,353
<p>I'm busy with an asignment where i have to make a graphical interface for a simple program. But i'm strugling with the layout.</p> <p>This is the idea:<br> <img src="https://i.stack.imgur.com/a3Xk7.png" alt="Layout Example" title="Layout Example"></p> <p>What is the easiest way to accomplish such a layout?</p> <p>And what method do you use to make layouts in java. Just code it, or use an IDE like netbeans?</p>
[ { "answer_id": 248435, "author": "bmeck", "author_id": 12781, "author_profile": "https://Stackoverflow.com/users/12781", "pm_score": 3, "selected": true, "text": "Container(BorderLayout)\n{\n @NORTH\n Container(BorderLayout)\n {\n @NORTH\n Label(Instruction);\n @CENTER\n Container(GridLayout(2,1))\n {\n Container(GirdLayout(2,2))\n {\n Label() TextField()\n Label() TextField() \n }\n Container(GirdLayout(2,2))\n {\n Label() TextField()\n Label() TextField()\n }\n }\n @SOUTH\n Container(FlowLayout())\n {\n JButton() //shaded thing?\n }\n }\n @CENTER\n {\n JTable\n }\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20261/" ]
248,362
<p>I am trying to build a dropdown list for a winform interop, and I am creating the dropdown in code. However, I have a problem getting the data to bind based on the DataTemplate I specify.</p> <p>What am I missing?</p> <pre><code>drpCreditCardNumberWpf = new ComboBox(); DataTemplate cardLayout = new DataTemplate {DataType = typeof (CreditCardPayment)}; StackPanel sp = new StackPanel { Orientation = System.Windows.Controls.Orientation.Vertical }; TextBlock cardHolder = new TextBlock {ToolTip = "Card Holder Name"}; cardHolder.SetBinding(TextBlock.TextProperty, "BillToName"); sp.Children.Add(cardHolder); TextBlock cardNumber = new TextBlock {ToolTip = "Credit Card Number"}; cardNumber.SetBinding(TextBlock.TextProperty, "SafeNumber"); sp.Children.Add(cardNumber); TextBlock notes = new TextBlock {ToolTip = "Notes"}; notes.SetBinding(TextBlock.TextProperty, "Notes"); sp.Children.Add(notes); cardLayout.Resources.Add(sp, null); drpCreditCardNumberWpf.ItemTemplate = cardLayout; </code></pre>
[ { "answer_id": 248638, "author": "Donnelle", "author_id": 28074, "author_profile": "https://Stackoverflow.com/users/28074", "pm_score": 8, "selected": true, "text": "ItemsSource drpCreditCardNumberWpf //create the data template\nDataTemplate cardLayout = new DataTemplate();\ncardLayout.DataType = typeof(CreditCardPayment);\n\n//set up the stack panel\nFrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackPanel));\nspFactory.Name = \"myComboFactory\";\nspFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);\n\n//set up the card holder textblock\nFrameworkElementFactory cardHolder = new FrameworkElementFactory(typeof(TextBlock));\ncardHolder.SetBinding(TextBlock.TextProperty, new Binding(\"BillToName\"));\ncardHolder.SetValue(TextBlock.ToolTipProperty, \"Card Holder Name\");\nspFactory.AppendChild(cardHolder);\n\n//set up the card number textblock\nFrameworkElementFactory cardNumber = new FrameworkElementFactory(typeof(TextBlock));\ncardNumber.SetBinding(TextBlock.TextProperty, new Binding(\"SafeNumber\"));\ncardNumber.SetValue(TextBlock.ToolTipProperty, \"Credit Card Number\");\nspFactory.AppendChild(cardNumber);\n\n//set up the notes textblock\nFrameworkElementFactory notes = new FrameworkElementFactory(typeof(TextBlock));\nnotes.SetBinding(TextBlock.TextProperty, new Binding(\"Notes\"));\nnotes.SetValue(TextBlock.ToolTipProperty, \"Notes\");\nspFactory.AppendChild(notes);\n\n//set the visual tree of the data template\ncardLayout.VisualTree = spFactory;\n\n//set the item template to be our shiny new data template\ndrpCreditCardNumberWpf.ItemTemplate = cardLayout;\n ToolTip TextBlock" }, { "answer_id": 38211618, "author": "a_a", "author_id": 5975828, "author_profile": "https://Stackoverflow.com/users/5975828", "pm_score": 0, "selected": false, "text": "FrameworkElementFactory UserControl FrameworkElementFactory UserControl let buildView()=StackPanel()\n//Build it with natural code\ntype MyView()=inherit UserControl(Content=buildView())\nlet factory=FrameworkElementFactory(typeof<MyView>)\nlet template=DataTemplate(VisualTree=factory)\nlet list=ItemsControl(ItemsSource=makeData(),ItemTemplate=template)\n" }, { "answer_id": 57461040, "author": "Pavlo Datsiuk", "author_id": 2214916, "author_profile": "https://Stackoverflow.com/users/2214916", "pm_score": 3, "selected": false, "text": "var ms = new MemoryStream(Encoding.UTF8.GetBytes(@\"<DataTemplate xmlns=\"\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\"\n xmlns:x=\"\"http://schemas.microsoft.com/winfx/2006/xaml\"\" \n xmlns:c=\"\"clr-namespace:MyApp.Converters;assembly=MyApp\"\">\n <DataTemplate.Resources>\n <c:MyConverter x:Key=\"\"MyConverter\"\"/>\n </DataTemplate.Resources>\n <TextBlock Text=\"\"{Binding ., Converter={StaticResource MyConverter}}\"\"/>\n </DataTemplate>\"));\nvar template = (DataTemplate)XamlReader.Load(ms);\n\nvar cb = new ComboBox { };\n//Set the data template\ncb.ItemTemplate = template;\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
248,396
<p>I am writing a batch file script using Windows command and want to change each occurrence of some blank space with "," What is the simplest way to do that? </p>
[ { "answer_id": 248487, "author": "Jeremy", "author_id": 3657, "author_profile": "https://Stackoverflow.com/users/3657", "pm_score": 1, "selected": false, "text": "sed -e \"s/ /,/\" infile.txt >outfile.txt\n" }, { "answer_id": 248805, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 3, "selected": true, "text": "one two three four\n @echo off\nsetlocal\nfor /F \"tokens=* delims= \" %%a in (%1) do @set data=%%a\necho %data: =,%\nendlocal\n C:\\>SpaceToComma.bat data.txt\none,two,three,four\n one two three four\nfive six seven\n @echo off\nsetlocal\nfor /F \"tokens=* delims= \" %%a in (%1) do @call :processaline %%a\nendlocal\ngoto :eof\n:processaline\nsetlocal\nset data=%*\necho %data: =,%\nendlocal\ngoto:eof\n C:\\>SpaceToComma.bat data.txt\none,two,three,four\nfive,six,seven\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32565/" ]
248,400
<p>I have a range of random numbers. The range is actually determined by the user but it will be up to 1000 integers. They are placed in this:</p> <pre><code>vector&lt;int&gt; n </code></pre> <p>and the values are inserted like this:</p> <pre><code>srand(1); for (i = 0; i &lt; n; i++) v[i] = rand() % n; </code></pre> <p>I'm creating a separate function to find all the non-prime values. Here is what I have now, but I know it's completely wrong as I get both prime and composite in the series.</p> <pre><code>void sieve(vector&lt;int&gt; v, int n) { int i,j; for(i = 2; i &lt;= n; i++) { cout &lt;&lt; i &lt;&lt; " % "; for(j = 0; j &lt;= n; j++) { if(i % v[j] == 0) cout &lt;&lt; v[j] &lt;&lt; endl; } } } </code></pre> <p>This method typically worked when I just had a series of numbers from 0-1000, but it doesn't seem to be working now when I have numbers out of order and duplicates. Is there a better method to find non-prime numbers in a vector? I'm tempted to just create another vector, fill it with n numbers and just find the non-primes that way, but would that be inefficient?</p> <p>Okay, since the range is from 0-1000 I am wondering if it's easier to just create vector with 0-n sorted, and then using a sieve to find the primes, is this getting any closer?</p> <pre><code>void sieve(vector&lt;int&gt; v, BST&lt;int&gt; t, int n) { vector&lt;int&gt; v_nonPrime(n); int i,j; for(i = 2; i &lt; n; i++) v_nonPrime[i] = i; for(i = 2; i &lt; n; i++) { for(j = i + 1; j &lt; n; j++) { if(v_nonPrime[i] % j == 0) cout &lt;&lt; v_nonPrime[i] &lt;&lt; endl; } } } </code></pre>
[ { "answer_id": 248436, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 1, "selected": false, "text": "O(n) O(max_element) O(1000) == O(1)" }, { "answer_id": 248479, "author": "Jeremy", "author_id": 3657, "author_profile": "https://Stackoverflow.com/users/3657", "pm_score": 4, "selected": true, "text": "if(i % v[j] == 0)\n cout << v[j] << endl;\n if(v[j] % i == 0)\n" }, { "answer_id": 248528, "author": "MaDDoG", "author_id": 18317, "author_profile": "https://Stackoverflow.com/users/18317", "pm_score": 0, "selected": false, "text": "vector<int> inputNumbers;\n\n// First, find all the prime numbers from 1 to n\nbool isPrime[n+1] = {true};\nisPrime[0]= false;\nisPrime[1]= false;\nfor (int i = 2; i <= sqrt(n); i++)\n{\n if (!isPrime[i])\n continue;\n for (int j = 2; j <= n/i; j++)\n isPrime[i*j] = false;\n}\n\n// Check the input array for non-prime numbers\nfor (int i = 0; i < inputNumbers.size(); i++)\n{\n int thisNumber = inputNumbers[i];\n // Vet the input to make sure we won't blow our isPrime array\n if ((0<= thisNumber) && (thisNumber <=n))\n {\n // Prints out non-prime numbers\n if (!isPrime[thisNumber])\n cout<< thisNumber;\n }\n}\n" }, { "answer_id": 248660, "author": "Jamie", "author_id": 22748, "author_profile": "https://Stackoverflow.com/users/22748", "pm_score": 0, "selected": false, "text": "i % v[j] v[j] % i void sieve(vector<int> v, int n) {\n int i,j;\n\n for(j = 0; j <= n; j++) {\n cout << v[j] << \": \";\n\n for(i = 2; i < v[j]; i++) {\n if(v[j] % i == 0) {\n cout << \"is divisible by \" << i << endl;\n break;\n }\n }\n\n if (i == v[j]) {\n cout << \"is prime.\" << endl;\n }\n }\n}\n v[j] v[j]" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28392/" ]
248,405
<p>I have some thread-related questions, assuming the following code. Please ignore the possible inefficiency of the code, I'm only interested in the thread part.</p> <pre><code>//code without thread use public static int getNextPrime(int from) { int nextPrime = from+1; boolean superPrime = false; while(!superPrime) { boolean prime = true; for(int i = 2;i &lt nextPrime;i++) { if(nextPrime % i == 0) { prime = false; } } if(prime) { superPrime = true; } else { nextPrime++; } } return nextPrime; } public static void main(String[] args) { int primeStart = 5; ArrayList list = new ArrayList(); for(int i = 0;i &lt 10000;i++) { list.add(primeStart); primeStart = getNextPrime(primeStart); } } </code></pre> <p>If I'm running the code like this and it takes about 56 seconds. If, however, I have the following code (as an alternative):</p> <pre><code>public class PrimeRunnable implements Runnable { private int from; private int lastPrime; public PrimeRunnable(int from) { this.from = from; } public boolean isPrime(int number) { for(int i = 2;i &lt from;i++) { if((number % i) == 0) { return false; } } lastPrime = number; return true; } public int getLastPrime() { return lastPrime; } public void run() { while(!isPrime(++from)) ; } } public static void main(String[] args) { int primeStart = 5; ArrayList list = new ArrayList(); for(int i = 0;i &lt 10000;i++) { PrimeRunnable pr = new PrimeRunnable(primeStart); Thread t = new Thread(pr); t.start(); t.join(); primeStart = pr.getLastPrime(); list.add(primeStart); } } </code></pre> <p>The whole operation takes about 7 seconds. I am almost certain that even though I only create one thread at a time, a thread doesn't always finish when another is created. Is that right? I am also curious: why is the operation ending so fast?</p> <p>When I'm joining a thread, do other threads keep running in the background, or is the joined thread the only one that's running?</p>
[ { "answer_id": 248482, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 2, "selected": false, "text": " private static int currentPrime;\npublic static void main(String[] args) throws InterruptedException {\n for (currentPrime = 0; currentPrime < 10000; currentPrime++) {\n Thread t = new Thread(new Runnable() {\n public void run() {\n getNextPrime(currentPrime);\n }});\n t.run();\n t.join();\n }\n}\n" }, { "answer_id": 248547, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 2, "selected": false, "text": "for(int i = 2;i < nextPrime;i++) {\n if(nextPrime % i == 0) {\n prime = false;\n }\n}\n for(int i = 2;i < from;i++) {\n if((number % i) == 0) {\n return false;\n }\n}\n for(int i = 2;i < nextPrime;i++) {\n if(nextPrime % i == 0) {\n prime = false;\n break;\n }\n}\n" }, { "answer_id": 249019, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 3, "selected": true, "text": "public static void main(String[] args) {\n int primeStart = 5;\n\n // Make thread-safe list for adding results to\n List list = Collections.synchronizedList(new ArrayList());\n\n // Pull thread pool count out into a value so you can easily change it\n int threadCount = 10000;\n Thread[] threads = new Thread[threadCount];\n\n // Start all threads\n for(int i = 0;i < threadCount;i++) {\n // Pass list to each Runnable here\n // Also, I added +i here as I think the intention is \n // to test 10000 possible numbers>5 for primeness - \n // was testing 5 in all loops\n PrimeRunnable pr = new PrimeRunnable(primeStart+i, list);\n Thread[i] threads = new Thread(pr);\n threads[i].start(); // thread is now running in parallel\n }\n\n // All threads now running in parallel\n\n // Then wait for all threads to complete\n for(int i=0; i<threadCount; i++) {\n threads[i].join();\n }\n}\n public class PrimeRunnable implements Runnable { \n private int from;\n private List results; // shared but thread-safe\n\n public PrimeRunnable(int from, List results) {\n this.from = from;\n this.results = results;\n }\n\n public void isPrime(int number) {\n for(int i = 2;i < from;i++) {\n if((number % i) == 0) {\n return;\n }\n }\n // found prime, add to shared results\n this.results.add(number);\n }\n\n public void run() {\n isPrime(from); // don't increment, just check one number\n } \n}\n public static void main(String[] args) {\n int primeStart = 5;\n\n // Make thread-safe list for adding results to\n List list = Collections.synchronizedList(new ArrayList());\n\n int threadCount = 16; // Experiment with this to find best on your machine\n ExecutorService exec = Executors.newFixedThreadPool(threadCount);\n\n int workCount = 10000; // See how # of work is now separate from # of threads?\n for(int i = 0;i < workCount;i++) {\n // submit work to the svc for execution across the thread pool \n exec.execute(new PrimeRunnable(primeStart+i, list));\n }\n\n // Wait for all tasks to be done or timeout to go off\n exec.awaitTermination(1, TimeUnit.DAYS);\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
248,421
<p>I have discovered through trial and error that the MATLAB engine function is not completely thread safe.</p> <p>Does anyone know the rules?</p> <p>Discovered through trial and error:</p> <p>On Windows, the connection to MATLAB is via COM, so the COM Apartment threading rules apply. All calls must occur in the same thread, but multiple connections can occur in multiple threads as long as each connection is isolated.</p> <p>From the answers below, it seems that this is not the case on UNIX, where calls can be made from multiple threads as long as the calls are made serially.</p>
[ { "answer_id": 1716487, "author": "8888q8888", "author_id": 180866, "author_profile": "https://Stackoverflow.com/users/180866", "pm_score": 0, "selected": false, "text": "engOpenSingleUse engOpen" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3657/" ]
248,425
<p>I want to checkout, and then update as necessary, the <a href="http://code.djangoproject.com/" rel="nofollow noreferrer">Django Subversion trunk</a> on a Mac OS X Leopard 10.5.5 machine. </p> <p>I am only interested in having updated Django code on my Mac. I am not interested in contributing patches to the Django project. I do not need the Subversion history for the Django trunk.</p> <p>I plan to use Git as the DVCS/SCM for all of my personal projects.</p> <hr> <p><strong>What is the best practice for keeping my Mac updated with the latest Django trunk and why?</strong></p> <p>I am new to Git so understanding why you chose your option will be very helpful.</p> <p><p></p> <ol> <li><p>Use Subversion 1.4.4 installed on my Mac: svn co <a href="http://code.djangoproject.com/svn/django/trunk/" rel="nofollow noreferrer">http://code.djangoproject.com/svn/django/trunk/</a>. Essentially using Subversion to fetch Subversion repos and Git for my personal projects. </p></li> <li><p>Use Git SVN to fetch the <a href="http://code.djangoproject.com/svn/django/trunk/" rel="nofollow noreferrer">Django Subversion repo</a>. Instructions on how to do this for a Git newbie? </p></li> <li><p>Use Git to fetch a <a href="http://spinlock.ch/pub/git/?p=django/django.git;a=summary" rel="nofollow noreferrer">Git mirror of the Django repo</a>. I'm a little concerned that the mirror might go away in the future, but I'm willing to use it if it's the best option.</p></li> </ol>
[ { "answer_id": 248443, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 5, "selected": true, "text": "git-svn" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32558/" ]
248,437
<p>Is it possible in ASP.NET to take a string containing some HTML and make ASP.NET to parse it and create a Control for me? For example:</p> <pre><code>string rawHTML = "&lt;table&gt;&lt;td&gt;&lt;td&gt;Cell&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;"; HTMLTable table = MagicClass.ParseTable(rawHTML); </code></pre> <p>I know that this is a bad thing to do but I am in the unfortunate situation that this is really the only way I can achieve what I need (as I cannot modify this particular coworker's code).</p> <p>Also, I know that LiteralControl allows you to have a control with arbitrary HTML in it, but unfortunately I need to have them converted to proper control.</p> <p>Unfortunately, HTMLTable does not support the InnerHTML property. I need to preserve the HTML tree exactly as it is, so I cannot put it into a <code>&lt;div&gt;</code> tag.</p> <p>Thanks.</p>
[ { "answer_id": 248542, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "this.ParseControl(\"<table><tr><td>Cell</td></tr></table>\")\n Control\n LiteralControl\n this.ParseControl(\"<table runat=\\\"server\\\"><tr><td>Cell</td></tr></table>\")\n Control\n HtmlTable\n HtmlTableRow\n HtmlTableCell\n LiteralControl\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954/" ]
248,459
<p>We are deploying our ASP.NET 3.5 app to a production server for beta testing.</p> <p>Each page is secured using SSL.</p> <p>On our homepage (default.aspx) we have web services which populate flash objects.</p> <p>I am getting an error:</p> <p>The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.</p> <p>Also, when using firefox, receive the Windows Login pop up screen.</p> <p>Does anyone have any clue what or why this is happening?</p> <p>Much thanks!</p>
[ { "answer_id": 248936, "author": "JTew", "author_id": 25372, "author_profile": "https://Stackoverflow.com/users/25372", "pm_score": 1, "selected": false, "text": "request.Username = \"xyz\"\nrequest.Password = \"***\"\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23576/" ]
248,470
<p>I'm writing a script to remove some build artifacts older than 1 week. </p> <p>The files have names in the form <em>artifact-1.1-200810391018.exe</em>.</p> <p>How do I go about removing only the files that are greater than 1 week old, excluding the time in hours and minutes at the end of the date-time-stamp?</p> <p>Currently it is removing all of the files in the directory.</p> <pre><code>#!/bin/sh NIGHTLY_LOCATIONS=( "/foo" "/bar" ) ARTIFACT_PREFIX="artifact-*-" NUM_TO_KEEP=7 for home in $(seq 0 $((${#NIGHTLY_LOCATIONS[@]} - 1))); do echo "Removing artifacts for" ${NIGHTLY_LOCATIONS[$location]} for file in `find ${NIGHTLY_LOCATIONS[$location]} -name "$ARTIFACT_PREFIX*"`; do keep=true for day in $(seq 0 $((${NUM_TO_KEEP} - 1))); do date=`date --date="$day days ago" +%Y%m%d` echo $(basename $file ".exe") " = " $ARTIFACT_PREFIX$date if [ "$(basename $file ".exe")" != "$ARTIFACT_PREFIX$date" ]; then keep=false fi done if [ !$keep ]; then echo "Removing file" rm -f $file fi done done </code></pre>
[ { "answer_id": 248485, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "find /path/to/files -name \"artifact*\" -type f -mtime +7 -exec rm {} \\;\n" }, { "answer_id": 248490, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "find \"${NIGHTLY_LOCATIONS}\" -name $ARTIFACT_PREFIX -type f -mtime +7 -delete\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18340/" ]
248,478
<p>I am writing a custom session handler in PHP and trying to make the methods defined in session_set_save_handler private.</p> <pre><code>session_set_save_handler( array('Session','open'), array('Session','close'), array('Session','read'), array('Session','write'), array('Session','destroy'), array('Session','gc') ); </code></pre> <p>For example I can set the open function to be private without any errors, but when I make the write method private it barks at me.</p> <blockquote> <p>Fatal error: Call to private method Session::write() from context '' in Unknown on line 0</p> </blockquote> <p>I was just wondering if this was a bug or there is a way around this. Barring that I can certainly just make it public, but I'd rather not. There was a post from last year on php.net eluding to a similar thing, but just want to know if anyone had any ideas. Does it really matter? I am using PHP 5.2.0 on my development box, but could certainly upgrade. </p>
[ { "answer_id": 1561578, "author": "fentie", "author_id": 189275, "author_profile": "https://Stackoverflow.com/users/189275", "pm_score": 0, "selected": false, "text": "$session = new Session();\nsession_set_save_handler(\n array($session,'open'),\n array($session,'close'),\n array($session,'read'),\n array($session,'write'),\n array($session,'destroy'),\n array($session,'gc')\n);\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28714/" ]
248,501
<p>I am using MS SQL Server 2005, I have dates stored in epoch time (starting 1970) I need to create a statement that will affect any record that has not been updated in the last 24 hours.</p>
[ { "answer_id": 248524, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 1, "selected": false, "text": "Select DateDiff(Second, '19700101', GetDate()) Select Columns\nFrom Table\nWhere EpochColumn Between DateDiff(Second, '19700101', GetDate()) And DateDiff(Second, '19700101, GetDate()-1)\n" }, { "answer_id": 248543, "author": "Gabe Hollombe", "author_id": 30632, "author_profile": "https://Stackoverflow.com/users/30632", "pm_score": 3, "selected": true, "text": "SELECT DATEDIFF(s,'19700101 05:00:00:000',GETUTCDATE())\n SELECT DATEDIFF(s,'19700101 05:00:00:000', DATEADD(DAY, -1, GETUTCDATE()))\n DECLARE @24_hours_ago AS INT\nSELECT @24_hours_ago = DATEDIFF(s,'19700101 05:00:00:000', DATEADD(DAY, -1, GETUTCDATE()))\n\nUPDATE table SET col = value WHERE last_updated < @24_hours_ago\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32579/" ]
248,502
<p>I want to run a background task that reads input from a TextReader and processes it a line at a time. I want the background task to block until the user types some text into a field and clicks the submit button. Is there some flavour of TextReader that will block until text is available and lets you somehow add more text to the underlying source?</p> <p>I thought that a StreamReader and StreamWriter pointing to the same MemoryStream might work, but it doesn't seem to. The StreamReader sees that the MemoryStream is empty at the start, and never checks again.</p> <p>I realize that it would be easier to write a ProcessLine() method and call it whenever the user clicks the submit button. However, I'm trying to design a plug-in architecture, and I'd like the plug ins to look like old-fashioned console apps with an input stream and an output stream. I want the plug in's input stream to just block until the user clicks the submit button with some input text.</p>
[ { "answer_id": 248700, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 4, "selected": true, "text": " public class BlockingStream: Stream\n {\n private readonly Stream _stream;\n\n public BlockingStream(Stream stream)\n {\n if(!stream.CanSeek)\n throw new ArgumentException(\"Stream must support seek\", \"stream\");\n _stream = stream;\n }\n\n public override void Flush()\n {\n lock (_stream)\n {\n _stream.Flush();\n Monitor.Pulse(_stream);\n }\n }\n\n public override long Seek(long offset, SeekOrigin origin)\n {\n lock (_stream)\n {\n long res = _stream.Seek(offset, origin);\n Monitor.Pulse(_stream);\n return res;\n }\n }\n\n public override void SetLength(long value)\n {\n lock (_stream)\n {\n _stream.SetLength(value);\n Monitor.Pulse(_stream);\n }\n }\n\n public override int Read(byte[] buffer, int offset, int count)\n {\n lock (_stream)\n {\n do\n {\n int read = _stream.Read(buffer, offset, count);\n if (read > 0)\n return read;\n Monitor.Wait(_stream);\n } while (true);\n }\n }\n\n public override void Write(byte[] buffer, int offset, int count)\n {\n lock (_stream)\n {\n long currentPosition = _stream.Position;\n _stream.Position = _stream.Length;\n _stream.Write(buffer, offset, count);\n _stream.Position = currentPosition;\n Monitor.Pulse(_stream);\n }\n }\n\n public override bool CanRead\n {\n get\n {\n lock (_stream)\n {\n return _stream.CanRead;\n }\n }\n }\n\n public override bool CanSeek\n {\n get\n {\n lock (_stream)\n {\n return _stream.CanSeek;\n }\n }\n }\n\n public override bool CanWrite\n {\n get\n {\n lock (_stream)\n {\n return _stream.CanWrite;\n }\n }\n }\n\n public override long Length\n {\n get\n {\n lock (_stream)\n {\n return _stream.Length;\n }\n }\n }\n\n public override long Position\n {\n get\n {\n lock (_stream)\n {\n return _stream.Position;\n }\n }\n set\n {\n lock (_stream)\n {\n _stream.Position = value;\n Monitor.Pulse(_stream);\n }\n }\n }\n }\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ]
248,527
<p>I am working on a windows service that polls for a connection to a network enabled devices every 15 seconds. If the service is not able to connect to a device, it throws an exception and tries again in 15 seconds. All of this works great.</p> <p>But, lets say one of the devices is down for a day or more. I am filling up my exception log with the same exception every 15 seconds. Is there a standard way to prevent an exception from being written to the event log if the exception being thrown hasn't changed in the last x number of hours?</p>
[ { "answer_id": 362715, "author": "Matt Jacobsen", "author_id": 15608, "author_profile": "https://Stackoverflow.com/users/15608", "pm_score": 0, "selected": false, "text": " int count = 0;\n while (true)\n {\n try\n {\n AttemptStuff()\n }\n catch (Exception ex)\n {\n if(count < 10)\n {\n EventLog.WriteEntry(\"my service\", ex.ToString(), EventLogEntryType.Error);\n count++;\n }\n }\n }\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
248,534
<p><strong>Question</strong></p> <p>I have an application written in Java. It is designed to run on a Linux box standalone. I am trying to spawn a new <em>firefox</em> window. However, <em>firefox</em> never opens. It always has a shell exit code of 1. I can run this same code with <em>gnome-terminal</em> and it opens fine.</p> <p><strong>Background</strong></p> <p>So, here is its initialization process:</p> <ol> <li>Start X "Xorg :1 -br -terminate -dpms -quiet vt7"</li> <li>Start Window Manager "metacity --display=:1 --replace"</li> <li>Configure resources "xrdb -merge /etc/X11/Xresources"</li> <li>Become a daemon and disconnect from controlling terminal</li> </ol> <p>Once the program is up an running, there is a button the user can click that should spawn a firefox window. Here is my code to do that. Remember X is running on display :1.</p> <p><strong>Code</strong></p> <pre><code> public boolean openBrowser() { try { Process oProc = Runtime.getRuntime().exec( "/usr/bin/firefox --display=:1" ); int bExit = oProc.waitFor(); // This is always 1 for some reason return true; } catch ( Exception e ) { oLogger.log( Level.WARNING, "Open Browser", e ); return false; } } </code></pre>
[ { "answer_id": 248552, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 3, "selected": false, "text": " if (Desktop.isDesktopSupported()) {\n Desktop desktop = Desktop.getDesktop();\n if (desktop.isSupported(Desktop.Action.BROWSE)) {\n try {\n desktop.browse(new URI(\"http://localhost\"));\n }\n catch(IOException ioe) {\n ioe.printStackTrace();\n }\n catch(URISyntaxException use) {\n use.printStackTrace();\n }\n }\n }\n" }, { "answer_id": 248607, "author": "Zarkonnen", "author_id": 15255, "author_profile": "https://Stackoverflow.com/users/15255", "pm_score": 2, "selected": false, "text": "new BrowserLauncher().openURLinBrowser(\"http://www.google.com\");\n" }, { "answer_id": 249168, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 3, "selected": true, "text": "ProcessBuilder pb = new ProcessBuilder(\"myCommand\", \"myArg1\", \"myArg2\");\nMap<String, String> env = pb.environment();\nenv.put(\"VAR1\", \"myValue\");\nenv.remove(\"OTHERVAR\");\nenv.put(\"VAR2\", env.get(\"VAR1\") + \"suffix\");\npb.directory(\"myDir\");\nProcess p = pb.start();\n" }, { "answer_id": 9247555, "author": "kta", "author_id": 539023, "author_profile": "https://Stackoverflow.com/users/539023", "pm_score": 0, "selected": false, "text": "try {\n String url = \"http://www.google.com\";\n java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));\n} catch (java.io.IOException e) {\n System.out.println(e.getMessage());\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29773/" ]
248,535
<p>How can you find out the number of active users when you're using a StateServer? Also is it possible to query the StateServer and retrieve the contents in the Session State? </p> <p>I know that this is all possible if you use SqlServer for a backing store, but I want them to be in memory.</p>
[ { "answer_id": 248674, "author": "Doug Wilson", "author_id": 32588, "author_profile": "https://Stackoverflow.com/users/32588", "pm_score": 1, "selected": true, "text": "StringBuilder builder = new StringBuilder();\nforeach ( String key in Session.Contents ) {\n builder.AppendFormat(\"{0}: {1}<br />\", key, Session[key]);\n}\nResponse.Write(builder.ToString());\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16628/" ]
248,545
<p>I have a listbox, and I have the following ItemTemplate for it:</p> <pre><code>&lt;DataTemplate x:Key="ScenarioItemTemplate"&gt; &lt;Border Margin="5,0,5,0" Background="#FF3C3B3B" BorderBrush="#FF797878" BorderThickness="2" CornerRadius="5"&gt; &lt;DockPanel&gt; &lt;DockPanel DockPanel.Dock="Top" Margin="0,2,0,0"&gt; &lt;Button HorizontalAlignment="Left" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /&gt; &lt;Label Content="{Binding Path=Name}" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="white" /&gt; &lt;Label HorizontalAlignment="Right" Background="#FF3C3B3B" Content="X" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /&gt; &lt;/DockPanel&gt; &lt;ContentControl Name="designerContent" Visibility="Collapsed" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"&gt; &lt;/ContentControl&gt; &lt;/DockPanel&gt; &lt;/Border&gt; &lt;/DataTemplate&gt; </code></pre> <p>As you can see the ContentControl has Visibility set to collapsed.</p> <p>I need to define a trigger that causes the Visibility to be set to "Visible"</p> <p>when the ListItem is selected, but I can't figure it out.</p> <p>Any ideas? </p> <p>UPDATE: Of course I could simply duplicate the DataTemplate and add triggers to the ListBox in question to use either one or the other, but I want to prevent duplicating this code.</p>
[ { "answer_id": 248581, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 8, "selected": true, "text": "<ContentControl \n x:Name=\"designerContent\"\n MinHeight=\"100\"\n Margin=\"2,0,2,2\"\n Content=\"{Binding Path=DesignerInstance}\"\n Background=\"#FF999898\">\n <ContentControl.Style>\n <Style TargetType=\"{x:Type ContentControl}\">\n <Setter Property=\"Visibility\" Value=\"Collapsed\"/>\n <Style.Triggers>\n <DataTrigger\n Binding=\"{Binding\n RelativeSource={RelativeSource\n Mode=FindAncestor,\n AncestorType={x:Type ListBoxItem}},\n Path=IsSelected}\"\n Value=\"True\">\n <Setter Property=\"Visibility\" Value=\"Visible\"/>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </ContentControl.Style>\n</ContentControl>\n <DataTemplate x:Key=\"ScenarioItemTemplate\">\n <DataTemplate.Triggers>\n <DataTrigger\n Binding=\"{Binding\n RelativeSource={RelativeSource\n Mode=FindAncestor,\n AncestorType={x:Type ListBoxItem}},\n Path=IsSelected}\"\n Value=\"True\">\n <Setter\n TargetName=\"designerContent\"\n Property=\"Visibility\"\n Value=\"Visible\"/>\n </DataTrigger>\n </DataTemplate.Triggers>\n\n ...\n</DataTemplate>\n" }, { "answer_id": 248628, "author": "TimothyP", "author_id": 28149, "author_profile": "https://Stackoverflow.com/users/28149", "pm_score": 2, "selected": false, "text": "<ContentControl.Style>\n<Style TargetType=\"{x:Type ContentControl}\">\n <Setter Property=\"Visibility\" Value=\"Collapsed\"/>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}\" Value=\"True\">\n <Setter Property=\"Visibility\" Value=\"Visible\"/>\n </DataTrigger>\n <DataTrigger Binding=\"{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}\" Value=\"False\">\n <Setter Property=\"Visibility\" Value=\"Collapsed\"/>\n </DataTrigger>\n </Style.Triggers>\n</Style>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
248,557
<pre><code>// goal: update Address record identified by "id", with new data in "colVal" string cstr = ConnectionApi.GetSqlConnectionString("SwDb"); // get connection str using (DataContext db = new DataContext(cstr)) { Address addr = (from a in db.GetTable&lt;Address&gt;() where a.Id == id select a).Single&lt;Address&gt;(); addr.AddressLine1 = colValue.Trim(); db.SubmitChanges(); // this seems to have no effect!!! } </code></pre> <p>In the debugger, addr has all the current values from the db table, and I can verify that AddressLine1 is changed just before I call db.SubmitChanges()... SQL Profiler shows only a "reset connection" when the SubmitChanges line executes. Anyone got a clue why this isn't working? THANKS!</p>
[ { "answer_id": 248591, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 1, "selected": false, "text": "string cstr = ConnectionApi.GetSqlConnectionString(\"SwDb\"); // get connection str\nusing (DataContext db = new DataContext(cstr)) \n{ \n Address addr = (from a in db.Address where a.Id == id select a).Single(); \n addr.AddressLine1 = colValue.Trim(); \n db.SubmitChanges(); // this seems to have no effect!!!\n}\n db.Log = Console.Out;\n" }, { "answer_id": 250822, "author": "Steve L", "author_id": 32584, "author_profile": "https://Stackoverflow.com/users/32584", "pm_score": 1, "selected": false, "text": "[Table(Name = \"Addresses\")]\npublic class Address\n{\n [Column(Name = \"Id\",IsPrimaryKey=true)]\n public int Id { get; set; }\n [Column(Name = \"AddressLine1\")]\n public string AddressLine1 { get; set; }\n ...\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32584/" ]
248,562
<p>I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I'm using the code snippet given below . Is this the accepted way? </p> <p>I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO. Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead? </p> <pre><code> @RequestMapping(method = RequestMethod.GET) public ModelAndView showResults(final HttpServletRequest request...) { final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName(); ... } </code></pre>
[ { "answer_id": 253395, "author": "Pavel Rodionov", "author_id": 29487, "author_profile": "https://Stackoverflow.com/users/29487", "pm_score": 2, "selected": false, "text": "public class SomeService {\n private String principal;\n @Principal\n public setPrincipal(String principal){\n this.principal=principal;\n }\n}\n" }, { "answer_id": 480503, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": false, "text": "/**\n* Returns the domain User object for the currently logged in user, or null\n* if no User is logged in.\n* \n* @return User object for the currently logged in user, or null if no User\n* is logged in.\n*/\npublic static User getCurrentUser() {\n\n Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal()\n\n if (principal instanceof MyUserDetails) return ((MyUserDetails) principal).getUser();\n\n // principal object is either null or represents anonymous user -\n // neither of which our domain User object can represent - so return null\n return null;\n}\n\n\n/**\n * Utility method to determine if the current user is logged in /\n * authenticated.\n * <p>\n * Equivalent of calling:\n * <p>\n * <code>getCurrentUser() != null</code>\n * \n * @return if user is logged in\n */\npublic static boolean isLoggedIn() {\n return getCurrentUser() != null;\n}\n" }, { "answer_id": 885168, "author": "Scott Bale", "author_id": 2495576, "author_profile": "https://Stackoverflow.com/users/2495576", "pm_score": 6, "selected": false, "text": "SecurityContextHolder SecurityContextHolder public interface SecurityContextFacade {\n\n SecurityContext getContext();\n\n void setContext(SecurityContext securityContext);\n\n}\n public class FooController {\n\n private final SecurityContextFacade securityContextFacade;\n\n public FooController(SecurityContextFacade securityContextFacade) {\n this.securityContextFacade = securityContextFacade;\n }\n\n public void doSomething(){\n SecurityContext context = securityContextFacade.getContext();\n // do something w/ context\n }\n\n}\n public class FooControllerTest {\n\n private FooController controller;\n private SecurityContextFacade mockSecurityContextFacade;\n private SecurityContext mockSecurityContext;\n\n @Before\n public void setUp() throws Exception {\n mockSecurityContextFacade = mock(SecurityContextFacade.class);\n mockSecurityContext = mock(SecurityContext.class);\n stub(mockSecurityContextFacade.getContext()).toReturn(mockSecurityContext);\n controller = new FooController(mockSecurityContextFacade);\n }\n\n @Test\n public void testDoSomething() {\n controller.doSomething();\n verify(mockSecurityContextFacade).getContext();\n }\n\n}\n public class SecurityContextHolderFacade implements SecurityContextFacade {\n\n public SecurityContext getContext() {\n return SecurityContextHolder.getContext();\n }\n\n public void setContext(SecurityContext securityContext) {\n SecurityContextHolder.setContext(securityContext);\n }\n\n}\n <bean id=\"myController\" class=\"com.foo.FooController\">\n ...\n <constructor-arg index=\"1\">\n <bean class=\"com.foo.SecurityContextHolderFacade\">\n </constructor-arg>\n</bean>\n SecurityContextHolder SecurityContextHolder SecurityContextHolderStrategy SecurityContextHolderStrategy SecurityContextHolder ThreadLocalSecurityContextHolderStrategy SecurityContext ThreadLocal SecurityContext ThreadLocal" }, { "answer_id": 2563189, "author": "Dan", "author_id": 307215, "author_profile": "https://Stackoverflow.com/users/307215", "pm_score": 3, "selected": false, "text": "request.getRemoteUser();\n" }, { "answer_id": 3200513, "author": "digz6666", "author_id": 386213, "author_profile": "https://Stackoverflow.com/users/386213", "pm_score": 4, "selected": false, "text": "import javax.servlet.http.HttpServletRequest;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.servlet.support.RequestContext;\n\nimport foo.Form;\n\n@Controller\n@RequestMapping(value=\"/welcome\")\npublic class IndexController {\n\n @RequestMapping(method=RequestMethod.GET)\n public String getCreateForm(Model model, HttpServletRequest request) {\n\n if(request.getUserPrincipal() != null) {\n String loginName = request.getUserPrincipal().getName();\n System.out.println(\"loginName : \" + loginName );\n }\n\n model.addAttribute(\"form\", new Form());\n return \"welcome\";\n }\n}\n" }, { "answer_id": 5351828, "author": "tsunade21", "author_id": 598327, "author_profile": "https://Stackoverflow.com/users/598327", "pm_score": 9, "selected": true, "text": " @RequestMapping(method = RequestMethod.GET) \n public ModelAndView showResults(final HttpServletRequest request, Principal principal) {\n\n final String currentUser = principal.getName();\n\n }\n" }, { "answer_id": 8441306, "author": "Mark", "author_id": 656962, "author_profile": "https://Stackoverflow.com/users/656962", "pm_score": 2, "selected": false, "text": "import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.userdetails.User;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\n\n @Controller\n public class KnoteController {\n @RequestMapping(method = RequestMethod.GET)\n public java.lang.String list(Model uiModel, UsernamePasswordAuthenticationToken authToken) {\n\n if (authToken instanceof UsernamePasswordAuthenticationToken) {\n user = (User) authToken.getPrincipal();\n }\n ...\n\n }\n" }, { "answer_id": 9763427, "author": "Brad Parks", "author_id": 26510, "author_profile": "https://Stackoverflow.com/users/26510", "pm_score": 5, "selected": false, "text": "<%@ taglib prefix=\"security\" uri=\"http://www.springframework.org/security/tags\" %>\n <security:authorize access=\"isAuthenticated()\">\n logged in as <security:authentication property=\"principal.username\" /> \n</security:authorize>\n\n<security:authorize access=\"! isAuthenticated()\">\n not logged in\n</security:authorize>\n" }, { "answer_id": 17381820, "author": "Valknut", "author_id": 2000539, "author_profile": "https://Stackoverflow.com/users/2000539", "pm_score": -1, "selected": false, "text": "default-target-url @RequestMapping(value = \"/monitoring\", method = RequestMethod.GET)\npublic ModelAndView getMonitoringPage(Model model, final HttpServletRequest request) {\n showRequestLog(\"monitoring\");\n\n\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n String userName = authentication.getName();\n //create a new session\n HttpSession session = request.getSession(true);\n session.setAttribute(\"username\", userName);\n\n return new ModelAndView(catalogPath + \"monitoring\");\n}\n <@security.authorize ifAnyGranted=\"ROLE_ADMIN, ROLE_USER\">\n<p style=\"padding-right: 20px;\">Logged in as ${username!\"Anonymous\" }</p>\n</@security.authorize> \n" }, { "answer_id": 22823381, "author": "Farm", "author_id": 286588, "author_profile": "https://Stackoverflow.com/users/286588", "pm_score": 3, "selected": false, "text": "@RequestMapping(method = RequestMethod.GET) \npublic String currentUserNameByPrincipal(Principal principal) {\n return principal.getName();\n}\n @RequestMapping(method = RequestMethod.GET)\npublic String currentUserNameByAuthentication(Authentication authentication) {\n return authentication.getName();\n}\n @RequestMapping(method = RequestMethod.GET) \npublic String currentUserByHTTPRequest(HttpServletRequest request) {\n return request.getUserPrincipal().getName();\n\n}\n public ModelAndView someRequestHandler(@ActiveUser User activeUser) {\n ...\n}\n" }, { "answer_id": 31735844, "author": "EliuX", "author_id": 3233398, "author_profile": "https://Stackoverflow.com/users/3233398", "pm_score": 1, "selected": false, "text": "@AuthenticationPrincipal @Controller @ControllerAdvicer @ControllerAdvice\npublic class ControllerAdvicer\n{\n private static final Logger LOGGER = LoggerFactory.getLogger(ControllerAdvicer.class);\n\n\n @ModelAttribute(\"userActive\")\n public UserActive currentUser(@AuthenticationPrincipal UserActive currentUser)\n {\n return currentUser;\n }\n}\n UserActive org.springframework.security.core.userdetails.User public class UserActive extends org.springframework.security.core.userdetails.User\n{\n\n private final User user;\n\n public UserActive(User user)\n {\n super(user.getUsername(), user.getPasswordHash(), user.getGrantedAuthorities());\n this.user = user;\n }\n\n //More functions\n}\n" }, { "answer_id": 33628957, "author": "Imrank", "author_id": 1164714, "author_profile": "https://Stackoverflow.com/users/1164714", "pm_score": 1, "selected": false, "text": "Principal" }, { "answer_id": 37446096, "author": "matsev", "author_id": 303598, "author_profile": "https://Stackoverflow.com/users/303598", "pm_score": 4, "selected": false, "text": "@AuthenticationPrincipal @RequestMapping(method = RequestMethod.GET)\npublic ModelAndView showResults(@AuthenticationPrincipal CustomUser currentUser, HttpServletRequest request) {\n String currentUsername = currentUser.getUsername();\n // ...\n}\n CustomUser UserDetails UserDetailsService" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495576/" ]
248,569
<p>Is this possible? I want to have the To:, Body, and an Attachment all pre-populated so all the user has to do is click send. Thanks!</p>
[ { "answer_id": 248598, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 7, "selected": true, "text": "ipm.note outlook.exe /c ipm.note\n outlook.exe /c ipm.note /m someone@microsoft.com\n outlook.exe /c ipm.note /a filename\n outlook.exe /c ipm.note /m someone@microsoft.com&subject=test%20subject&body=test%20body\n outlook.exe /c ipm.note /m \"someone@microsoft.com&subject=test%20subject&body=test%20body\"\n outlook.exe /c ipm.note /m \"someone@microsoft.com?subject=test\"\n & ?" }, { "answer_id": 413774, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "Set olApp = CreateObject(\"Outlook.Application\")\nSet olMsg = olApp.CreateItem(0)\n\nWith olMsg\n .To = \"test@testing.com\"\n '.CC = \"cc@testing.com\"\n '.BCC = \"bcc@testing.com\"\n .Subject = \"Subject\"\n .Body = \"Body\"\n .Attachments.Add \"C:\\path\\to\\attachment\\test.txt\" \n\n .Display\nEnd With\n" }, { "answer_id": 9059255, "author": "Dial-IN", "author_id": 1177312, "author_profile": "https://Stackoverflow.com/users/1177312", "pm_score": 3, "selected": false, "text": "/m outlook.exe /c ipm.note /m \"someone@microsoft.com&subject=test%20subject&body=test%20body\" /a test.txt\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
248,580
<p>I'm having a problem, creating a fixed-size overall panel for a touchscreen GUI application that has to take up the entire screen. In a nutshell, the touchscreen is 800 x 600 pixels, and therefore I want the main GUI panel to be that size.</p> <p>When I start a new GUI project in NetBeans, I set the properties of the main panel for min/max/preferred size to 800 x 600, and the panel within the 'Design' view changes size. However, when I launch the app, it is resized to the original default size.</p> <p>Adding this code after initComponents() does not help:</p> <pre><code>this.mainPanel.setSize(new Dimension(800,600)); this.mainPanel.setMaximumSize(new Dimension(800,600)); this.mainPanel.setMinimumSize(new Dimension(800,600)); this.mainPanel.repaint(); </code></pre> <p>I've peeked into all of the resource files and cannot seem to find values that would override these (which seems somewhat impossible anyway, given that I'm setting them after initComponents() does its work). I'm using the FreeDesign layout, because I wanted complete control over where I put things.</p> <p>I suspect the layout manager is resizing things based upon how many widgets I have on the screen, because different prototyped screens come in at differing sizes. </p> <p>Help is appreciated!</p>
[ { "answer_id": 249459, "author": "Peter", "author_id": 26483, "author_profile": "https://Stackoverflow.com/users/26483", "pm_score": 0, "selected": false, "text": "protected void growBig()\n {\n int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;\n int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;\n Rectangle rectangle = getFrame().getBounds();\n rectangle.setSize(screenWidth, screenHeight);\n getFrame().setBounds(0, 0, screenWidth, screenHeight);\n getFrame().setSize(screenWidth, screenHeight);\n getFrame().doLayout();\n getFrame().validate();\n updateUI();\n }\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
248,589
<p>Are there any plugins/tools available to go through the classpath of an eclipse project (or workspace) and highlight any unused jars?</p>
[ { "answer_id": 5323467, "author": "Raphael Jolivet", "author_id": 254061, "author_profile": "https://Stackoverflow.com/users/254061", "pm_score": 5, "selected": false, "text": "mvn dependency:analyze\n" }, { "answer_id": 31583033, "author": "bobbel", "author_id": 3082272, "author_profile": "https://Stackoverflow.com/users/3082272", "pm_score": 3, "selected": false, "text": "java -Xmx512m -jar tattletale.jar ~/myjavaproject/mydistribution output\n" }, { "answer_id": 68480324, "author": "Chamith", "author_id": 9147619, "author_profile": "https://Stackoverflow.com/users/9147619", "pm_score": 0, "selected": false, "text": "<build>\n<plugins>\n <plugin>\n <artifactId>maven-dependency-plugin</artifactId>\n <version>3.1.2</version>\n </plugin>\n</plugins>\n</build>\n plugins {\n id \"ca.cutterslade.analyze\" version \"1.7.1\"\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/943/" ]
248,603
<p>Anyone have a good resource or provide a sample of a natural order sort in C# for an <code>FileInfo</code> array? I am implementing the <code>IComparer</code> interface in my sorts.</p>
[ { "answer_id": 248613, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 8, "selected": true, "text": "IComparer [DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\nprivate static extern int StrCmpLogicalW(string psz1, string psz2);\n [SuppressUnmanagedCodeSecurity]\ninternal static class SafeNativeMethods\n{\n [DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\n public static extern int StrCmpLogicalW(string psz1, string psz2);\n}\n\npublic sealed class NaturalStringComparer : IComparer<string>\n{\n public int Compare(string a, string b)\n {\n return SafeNativeMethods.StrCmpLogicalW(a, b);\n }\n}\n\npublic sealed class NaturalFileInfoNameComparer : IComparer<FileInfo>\n{\n public int Compare(FileInfo a, FileInfo b)\n {\n return SafeNativeMethods.StrCmpLogicalW(a.Name, b.Name);\n }\n}\n" }, { "answer_id": 1466808, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 3, "selected": false, "text": "OrderBy IComparer var items = new List<MyItem>();\n\n// fill items\n\nvar sorted = items.OrderBy(item => item.Name, new NaturalStringComparer());\n" }, { "answer_id": 2433501, "author": "James McCormack", "author_id": 71906, "author_profile": "https://Stackoverflow.com/users/71906", "pm_score": 5, "selected": false, "text": "public class NaturalSortComparer<T> : IComparer<string>, IDisposable\n{\n private bool isAscending;\n\n public NaturalSortComparer(bool inAscendingOrder = true)\n {\n this.isAscending = inAscendingOrder;\n }\n\n #region IComparer<string> Members\n\n public int Compare(string x, string y)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n\n #region IComparer<string> Members\n\n int IComparer<string>.Compare(string x, string y)\n {\n if (x == y)\n return 0;\n\n string[] x1, y1;\n\n if (!table.TryGetValue(x, out x1))\n {\n x1 = Regex.Split(x.Replace(\" \", \"\"), \"([0-9]+)\");\n table.Add(x, x1);\n }\n\n if (!table.TryGetValue(y, out y1))\n {\n y1 = Regex.Split(y.Replace(\" \", \"\"), \"([0-9]+)\");\n table.Add(y, y1);\n }\n\n int returnVal;\n\n for (int i = 0; i < x1.Length && i < y1.Length; i++)\n {\n if (x1[i] != y1[i])\n {\n returnVal = PartCompare(x1[i], y1[i]);\n return isAscending ? returnVal : -returnVal;\n }\n }\n\n if (y1.Length > x1.Length)\n {\n returnVal = 1;\n }\n else if (x1.Length > y1.Length)\n { \n returnVal = -1; \n }\n else\n {\n returnVal = 0;\n }\n\n return isAscending ? returnVal : -returnVal;\n }\n\n private static int PartCompare(string left, string right)\n {\n int x, y;\n if (!int.TryParse(left, out x))\n return left.CompareTo(right);\n\n if (!int.TryParse(right, out y))\n return left.CompareTo(right);\n\n return x.CompareTo(y);\n }\n\n #endregion\n\n private Dictionary<string, string[]> table = new Dictionary<string, string[]>();\n\n public void Dispose()\n {\n table.Clear();\n table = null;\n }\n}\n" }, { "answer_id": 7048016, "author": "J.D.", "author_id": 542821, "author_profile": "https://Stackoverflow.com/users/542821", "pm_score": 5, "selected": false, "text": "public static int CompareNatural(string strA, string strB) {\n return CompareNatural(strA, strB, CultureInfo.CurrentCulture, CompareOptions.IgnoreCase);\n}\n\npublic static int CompareNatural(string strA, string strB, CultureInfo culture, CompareOptions options) {\n CompareInfo cmp = culture.CompareInfo;\n int iA = 0;\n int iB = 0;\n int softResult = 0;\n int softResultWeight = 0;\n while (iA < strA.Length && iB < strB.Length) {\n bool isDigitA = Char.IsDigit(strA[iA]);\n bool isDigitB = Char.IsDigit(strB[iB]);\n if (isDigitA != isDigitB) {\n return cmp.Compare(strA, iA, strB, iB, options);\n }\n else if (!isDigitA && !isDigitB) {\n int jA = iA + 1;\n int jB = iB + 1;\n while (jA < strA.Length && !Char.IsDigit(strA[jA])) jA++;\n while (jB < strB.Length && !Char.IsDigit(strB[jB])) jB++;\n int cmpResult = cmp.Compare(strA, iA, jA - iA, strB, iB, jB - iB, options);\n if (cmpResult != 0) {\n // Certain strings may be considered different due to \"soft\" differences that are\n // ignored if more significant differences follow, e.g. a hyphen only affects the\n // comparison if no other differences follow\n string sectionA = strA.Substring(iA, jA - iA);\n string sectionB = strB.Substring(iB, jB - iB);\n if (cmp.Compare(sectionA + \"1\", sectionB + \"2\", options) ==\n cmp.Compare(sectionA + \"2\", sectionB + \"1\", options))\n {\n return cmp.Compare(strA, iA, strB, iB, options);\n }\n else if (softResultWeight < 1) {\n softResult = cmpResult;\n softResultWeight = 1;\n }\n }\n iA = jA;\n iB = jB;\n }\n else {\n char zeroA = (char)(strA[iA] - (int)Char.GetNumericValue(strA[iA]));\n char zeroB = (char)(strB[iB] - (int)Char.GetNumericValue(strB[iB]));\n int jA = iA;\n int jB = iB;\n while (jA < strA.Length && strA[jA] == zeroA) jA++;\n while (jB < strB.Length && strB[jB] == zeroB) jB++;\n int resultIfSameLength = 0;\n do {\n isDigitA = jA < strA.Length && Char.IsDigit(strA[jA]);\n isDigitB = jB < strB.Length && Char.IsDigit(strB[jB]);\n int numA = isDigitA ? (int)Char.GetNumericValue(strA[jA]) : 0;\n int numB = isDigitB ? (int)Char.GetNumericValue(strB[jB]) : 0;\n if (isDigitA && (char)(strA[jA] - numA) != zeroA) isDigitA = false;\n if (isDigitB && (char)(strB[jB] - numB) != zeroB) isDigitB = false;\n if (isDigitA && isDigitB) {\n if (numA != numB && resultIfSameLength == 0) {\n resultIfSameLength = numA < numB ? -1 : 1;\n }\n jA++;\n jB++;\n }\n }\n while (isDigitA && isDigitB);\n if (isDigitA != isDigitB) {\n // One number has more digits than the other (ignoring leading zeros) - the longer\n // number must be larger\n return isDigitA ? 1 : -1;\n }\n else if (resultIfSameLength != 0) {\n // Both numbers are the same length (ignoring leading zeros) and at least one of\n // the digits differed - the first difference determines the result\n return resultIfSameLength;\n }\n int lA = jA - iA;\n int lB = jB - iB;\n if (lA != lB) {\n // Both numbers are equivalent but one has more leading zeros\n return lA > lB ? -1 : 1;\n }\n else if (zeroA != zeroB && softResultWeight < 2) {\n softResult = cmp.Compare(strA, iA, 1, strB, iB, 1, options);\n softResultWeight = 2;\n }\n iA = jA;\n iB = jB;\n }\n }\n if (iA < strA.Length || iB < strB.Length) {\n return iA < strA.Length ? 1 : -1;\n }\n else if (softResult != 0) {\n return softResult;\n }\n return 0;\n}\n Comparison<string> string[] files = Directory.GetFiles(@\"C:\\\");\nArray.Sort(files, CompareNatural);\n IComparer<string> public class CustomComparer<T> : IComparer<T> {\n private Comparison<T> _comparison;\n\n public CustomComparer(Comparison<T> comparison) {\n _comparison = comparison;\n }\n\n public int Compare(T x, T y) {\n return _comparison(x, y);\n }\n}\n string[] files = Directory.EnumerateFiles(@\"C:\\\")\n .OrderBy(f => f, new CustomComparer<string>(CompareNatural))\n .ToArray();\n Func<string, string> expand = (s) => { int o; while ((o = s.IndexOf('\\\\')) != -1) { int p = o + 1;\n int z = 1; while (s[p] == '0') { z++; p++; } int c = Int32.Parse(s.Substring(p, z));\n s = s.Substring(0, o) + new string(s[o - 1], c) + s.Substring(p + z); } return s; };\nstring encodedFileNames =\n \"KDEqLW4xMiotbjEzKjAwMDFcMDY2KjAwMlwwMTcqMDA5XDAxNyowMlwwMTcqMDlcMDE3KjEhKjEtISox\" +\n \"LWEqMS4yNT8xLjI1KjEuNT8xLjUqMSoxXDAxNyoxXDAxOCoxXDAxOSoxXDA2NioxXDA2NyoxYSoyXDAx\" +\n \"NyoyXDAxOCo5XDAxNyo5XDAxOCo5XDA2Nio9MSphMDAxdGVzdDAxKmEwMDF0ZXN0aW5nYTBcMzEqYTAw\" +\n \"Mj9hMDAyIGE/YTAwMiBhKmEwMDIqYTAwMmE/YTAwMmEqYTAxdGVzdGluZ2EwMDEqYTAxdnNmcyphMSph\" +\n \"MWEqYTF6KmEyKmIwMDAzcTYqYjAwM3E0KmIwM3E1KmMtZSpjZCpjZipmIDEqZipnP2cgMT9oLW4qaG8t\" +\n \"bipJKmljZS1jcmVhbT9pY2VjcmVhbT9pY2VjcmVhbS0/ajBcNDE/ajAwMWE/ajAxP2shKmsnKmstKmsx\" +\n \"KmthKmxpc3QqbTAwMDNhMDA1YSptMDAzYTAwMDVhKm0wMDNhMDA1Km0wMDNhMDA1YSpuMTIqbjEzKm8t\" +\n \"bjAxMypvLW4xMipvLW40P28tbjQhP28tbjR6P28tbjlhLWI1Km8tbjlhYjUqb24wMTMqb24xMipvbjQ/\" +\n \"b240IT9vbjR6P29uOWEtYjUqb245YWI1Km/CrW4wMTMqb8KtbjEyKnAwMCpwMDEqcDAxwr0hKnAwMcK9\" +\n \"KnAwMcK9YSpwMDHCvcK+KnAwMipwMMK9KnEtbjAxMypxLW4xMipxbjAxMypxbjEyKnItMDAhKnItMDAh\" +\n \"NSpyLTAwIe+8lSpyLTAwYSpyLe+8kFwxIS01KnIt77yQXDEhLe+8lSpyLe+8kFwxISpyLe+8kFwxITUq\" +\n \"ci3vvJBcMSHvvJUqci3vvJBcMWEqci3vvJBcMyE1KnIwMCEqcjAwLTUqcjAwLjUqcjAwNSpyMDBhKnIw\" +\n \"NSpyMDYqcjQqcjUqctmg2aYqctmkKnLZpSpy27Dbtipy27Qqctu1KnLfgN+GKnLfhCpy34UqcuClpuCl\" +\n \"rCpy4KWqKnLgpasqcuCnpuCnrCpy4KeqKnLgp6sqcuCppuCprCpy4KmqKnLgqasqcuCrpuCrrCpy4Kuq\" +\n \"KnLgq6sqcuCtpuCtrCpy4K2qKnLgrasqcuCvpuCvrCpy4K+qKnLgr6sqcuCxpuCxrCpy4LGqKnLgsasq\" +\n \"cuCzpuCzrCpy4LOqKnLgs6sqcuC1puC1rCpy4LWqKnLgtasqcuC5kOC5lipy4LmUKnLguZUqcuC7kOC7\" +\n \"lipy4LuUKnLgu5UqcuC8oOC8pipy4LykKnLgvKUqcuGBgOGBhipy4YGEKnLhgYUqcuGCkOGClipy4YKU\" +\n \"KnLhgpUqcuGfoOGfpipy4Z+kKnLhn6UqcuGgkOGglipy4aCUKnLhoJUqcuGlhuGljCpy4aWKKnLhpYsq\" +\n \"cuGnkOGnlipy4aeUKnLhp5UqcuGtkOGtlipy4a2UKnLhrZUqcuGusOGutipy4a60KnLhrrUqcuGxgOGx\" +\n \"hipy4bGEKnLhsYUqcuGxkOGxlipy4bGUKnLhsZUqcuqYoFwx6pilKnLqmKDqmKUqcuqYoOqYpipy6pik\" +\n \"KnLqmKUqcuqjkOqjlipy6qOUKnLqo5UqcuqkgOqkhipy6qSEKnLqpIUqcuqpkOqplipy6qmUKnLqqZUq\" +\n \"cvCQkqAqcvCQkqUqcvCdn5gqcvCdn50qcu+8kFwxISpy77yQXDEt77yVKnLvvJBcMS7vvJUqcu+8kFwx\" +\n \"YSpy77yQXDHqmKUqcu+8kFwx77yO77yVKnLvvJBcMe+8lSpy77yQ77yVKnLvvJDvvJYqcu+8lCpy77yV\" +\n \"KnNpKnPEsSp0ZXN02aIqdGVzdNmi2aAqdGVzdNmjKnVBZS0qdWFlKnViZS0qdUJlKnVjZS0xw6kqdWNl\" +\n \"McOpLSp1Y2Uxw6kqdWPDqS0xZSp1Y8OpMWUtKnVjw6kxZSp3ZWlhMSp3ZWlhMip3ZWlzczEqd2Vpc3My\" +\n \"KndlaXoxKndlaXoyKndlacOfMSp3ZWnDnzIqeSBhMyp5IGE0KnknYTMqeSdhNCp5K2EzKnkrYTQqeS1h\" +\n \"Myp5LWE0KnlhMyp5YTQqej96IDA1MD96IDIxP3ohMjE/ejIwP3oyMj96YTIxP3rCqTIxP1sxKl8xKsKt\" +\n \"bjEyKsKtbjEzKsSwKg==\";\nstring[] fileNames = Encoding.UTF8.GetString(Convert.FromBase64String(encodedFileNames))\n .Replace(\"*\", \".txt?\").Split(new[] { \"?\" }, StringSplitOptions.RemoveEmptyEntries)\n .Select(n => expand(n)).ToArray();\n" }, { "answer_id": 11624488, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 4, "selected": false, "text": "void Main()\n{\n new[] {\"a4\",\"a3\",\"a2\",\"a10\",\"b5\",\"b4\",\"b400\",\"1\",\"C1d\",\"c1d2\"}.OrderBy(x => x, new NaturalStringComparer()).Dump();\n}\n\npublic class NaturalStringComparer : IComparer<string>\n{\n private static readonly Regex _re = new Regex(@\"(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)\", RegexOptions.Compiled);\n\n public int Compare(string x, string y)\n {\n x = x.ToLower();\n y = y.ToLower();\n if(string.Compare(x, 0, y, 0, Math.Min(x.Length, y.Length)) == 0)\n {\n if(x.Length == y.Length) return 0;\n return x.Length < y.Length ? -1 : 1;\n }\n var a = _re.Split(x);\n var b = _re.Split(y);\n int i = 0;\n while(true)\n {\n int r = PartCompare(a[i], b[i]);\n if(r != 0) return r;\n ++i;\n }\n }\n\n private static int PartCompare(string x, string y)\n {\n int a, b;\n if(int.TryParse(x, out a) && int.TryParse(y, out b))\n return a.CompareTo(b);\n return x.CompareTo(y);\n }\n}\n 1\na2\na3\na4\na10\nb4\nb5\nb400\nC1d\nc1d2\n" }, { "answer_id": 11720793, "author": "Matthew Horsley", "author_id": 1562837, "author_profile": "https://Stackoverflow.com/users/1562837", "pm_score": 6, "selected": false, "text": "public static IOrderedEnumerable<T> OrderByAlphaNumeric<T>(this IEnumerable<T> source, Func<T, string> selector)\n{\n int max = source\n .SelectMany(i => Regex.Matches(selector(i), @\"\\d+\").Cast<Match>().Select(m => (int?)m.Value.Length))\n .Max() ?? 0;\n\n return source.OrderBy(i => Regex.Replace(selector(i), @\"\\d+\", m => m.Value.PadLeft(max, '0')));\n}\n int? .Max() InvalidOperationException" }, { "answer_id": 15560295, "author": "Eric Liprandi", "author_id": 80280, "author_profile": "https://Stackoverflow.com/users/80280", "pm_score": 0, "selected": false, "text": "\"Test 1-1-1 something\"\n\"Test 1-2-3 something\"\n...\n OrderBy() public static class EnumerableExtensions\n{\n // set up the regex parser once and for all\n private static readonly Regex Regex = new Regex(@\"\\d+|\\D+\", RegexOptions.Compiled | RegexOptions.Singleline);\n\n // stateless comparer can be built once\n private static readonly AggregateComparer Comparer = new AggregateComparer();\n\n public static IEnumerable<T> OrderByNatural<T>(this IEnumerable<T> source, Func<T, string> selector)\n {\n // first extract string from object using selector\n // then extract digit and non-digit groups\n Func<T, IEnumerable<IComparable>> splitter =\n s => Regex.Matches(selector(s))\n .Cast<Match>()\n .Select(m => Char.IsDigit(m.Value[0]) ? (IComparable) int.Parse(m.Value) : m.Value);\n return source.OrderBy(splitter, Comparer);\n }\n\n /// <summary>\n /// This comparer will compare two lists of objects against each other\n /// </summary>\n /// <remarks>Objects in each list are compare to their corresponding elements in the other\n /// list until a difference is found.</remarks>\n private class AggregateComparer : IComparer<IEnumerable<IComparable>>\n {\n public int Compare(IEnumerable<IComparable> x, IEnumerable<IComparable> y)\n {\n return\n x.Zip(y, (a, b) => new {a, b}) // walk both lists\n .Select(pair => pair.a.CompareTo(pair.b)) // compare each object\n .FirstOrDefault(result => result != 0); // until a difference is found\n }\n }\n}\n \"\\d+|\\D+\"" }, { "answer_id": 22323356, "author": "Michael Parker", "author_id": 1554346, "author_profile": "https://Stackoverflow.com/users/1554346", "pm_score": 5, "selected": false, "text": " public static IEnumerable<T> OrderByNatural<T>(this IEnumerable<T> items, Func<T, string> selector, StringComparer stringComparer = null)\n {\n var regex = new Regex(@\"\\d+\", RegexOptions.Compiled);\n\n int maxDigits = items\n .SelectMany(i => regex.Matches(selector(i)).Cast<Match>().Select(digitChunk => (int?)digitChunk.Value.Length))\n .Max() ?? 0;\n\n return items.OrderBy(i => regex.Replace(selector(i), match => match.Value.PadLeft(maxDigits, '0')), stringComparer ?? StringComparer.CurrentCulture);\n }\n var sortedEmployees = employees.OrderByNatural(emp => emp.Name);\n" }, { "answer_id": 26004132, "author": "Voxpire", "author_id": 2203880, "author_profile": "https://Stackoverflow.com/users/2203880", "pm_score": 1, "selected": false, "text": " private static readonly Regex _NaturalOrderExpr = new Regex(@\"\\d+\", RegexOptions.Compiled);\n\n public static IEnumerable<TSource> OrderByNatural<TSource, TKey>(\n this IEnumerable<TSource> source, Func<TSource, TKey> selector)\n {\n int max = 0;\n\n var selection = source.Select(\n o =>\n {\n var v = selector(o);\n var s = v != null ? v.ToString() : String.Empty;\n\n if (!String.IsNullOrWhiteSpace(s))\n {\n var mc = _NaturalOrderExpr.Matches(s);\n\n if (mc.Count > 0)\n {\n max = Math.Max(max, mc.Cast<Match>().Max(m => m.Value.Length));\n }\n }\n\n return new\n {\n Key = o,\n Value = s\n };\n }).ToList();\n\n return\n selection.OrderBy(\n o =>\n String.IsNullOrWhiteSpace(o.Value) ? o.Value : _NaturalOrderExpr.Replace(o.Value, m => m.Value.PadLeft(max, '0')))\n .Select(o => o.Key);\n }\n\n public static IEnumerable<TSource> OrderByDescendingNatural<TSource, TKey>(\n this IEnumerable<TSource> source, Func<TSource, TKey> selector)\n {\n int max = 0;\n\n var selection = source.Select(\n o =>\n {\n var v = selector(o);\n var s = v != null ? v.ToString() : String.Empty;\n\n if (!String.IsNullOrWhiteSpace(s))\n {\n var mc = _NaturalOrderExpr.Matches(s);\n\n if (mc.Count > 0)\n {\n max = Math.Max(max, mc.Cast<Match>().Max(m => m.Value.Length));\n }\n }\n\n return new\n {\n Key = o,\n Value = s\n };\n }).ToList();\n\n return\n selection.OrderByDescending(\n o =>\n String.IsNullOrWhiteSpace(o.Value) ? o.Value : _NaturalOrderExpr.Replace(o.Value, m => m.Value.PadLeft(max, '0')))\n .Select(o => o.Key);\n }\n" }, { "answer_id": 40290779, "author": "Picsonald", "author_id": 6014732, "author_profile": "https://Stackoverflow.com/users/6014732", "pm_score": 4, "selected": false, "text": "public static IEnumerable<string> AlphanumericSort(this IEnumerable<string> me)\n{\n return me.OrderBy(x => Regex.Replace(x, @\"\\d+\", m => m.Value.PadLeft(50, '0')));\n}\n List<string> test = new List<string>() { \"The 1st\", \"The 12th\", \"The 2nd\" };\ntest = test.AlphanumericSort();\n Original | Regex Replace | The | Returned\n List | Apply PadLeft | Sorting | List\n | | |\n \"The 1st\" | \"The 001st\" | \"The 001st\" | \"The 1st\"\n \"The 12th\" | \"The 012th\" | \"The 002nd\" | \"The 2nd\"\n \"The 2nd\" | \"The 002nd\" | \"The 012th\" | \"The 12th\"\n Alphabetical Sorting | Alphanumeric Sorting\n |\n \"Page 21, Line 42\" | \"Page 3, Line 7\"\n \"Page 21, Line 5\" | \"Page 3, Line 32\"\n \"Page 3, Line 32\" | \"Page 21, Line 5\"\n \"Page 3, Line 7\" | \"Page 21, Line 42\"\n" }, { "answer_id": 41168219, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 3, "selected": false, "text": "internal sealed class NaturalStringComparer : IComparer<string>\n{\n public static NaturalStringComparer Instance { get; } = new NaturalStringComparer();\n\n public int Compare(string x, string y)\n {\n // sort nulls to the start\n if (x == null)\n return y == null ? 0 : -1;\n if (y == null)\n return 1;\n\n var ix = 0;\n var iy = 0;\n\n while (true)\n {\n // sort shorter strings to the start\n if (ix >= x.Length)\n return iy >= y.Length ? 0 : -1;\n if (iy >= y.Length)\n return 1;\n\n var cx = x[ix];\n var cy = y[iy];\n\n int result;\n if (char.IsDigit(cx) && char.IsDigit(cy))\n result = CompareInteger(x, y, ref ix, ref iy);\n else\n result = cx.CompareTo(y[iy]);\n\n if (result != 0)\n return result;\n\n ix++;\n iy++;\n }\n }\n\n private static int CompareInteger(string x, string y, ref int ix, ref int iy)\n {\n var lx = GetNumLength(x, ix);\n var ly = GetNumLength(y, iy);\n\n // shorter number first (note, doesn't handle leading zeroes)\n if (lx != ly)\n return lx.CompareTo(ly);\n\n for (var i = 0; i < lx; i++)\n {\n var result = x[ix++].CompareTo(y[iy++]);\n if (result != 0)\n return result;\n }\n\n return 0;\n }\n\n private static int GetNumLength(string s, int i)\n {\n var length = 0;\n while (i < s.Length && char.IsDigit(s[i++]))\n length++;\n return length;\n }\n}\n 01 2 public class NumericStringComparerTests\n{\n [Fact]\n public void OrdersCorrectly()\n {\n AssertEqual(\"\", \"\");\n AssertEqual(null, null);\n AssertEqual(\"Hello\", \"Hello\");\n AssertEqual(\"Hello123\", \"Hello123\");\n AssertEqual(\"123\", \"123\");\n AssertEqual(\"123Hello\", \"123Hello\");\n\n AssertOrdered(\"\", \"Hello\");\n AssertOrdered(null, \"Hello\");\n AssertOrdered(\"Hello\", \"Hello1\");\n AssertOrdered(\"Hello123\", \"Hello124\");\n AssertOrdered(\"Hello123\", \"Hello133\");\n AssertOrdered(\"Hello123\", \"Hello223\");\n AssertOrdered(\"123\", \"124\");\n AssertOrdered(\"123\", \"133\");\n AssertOrdered(\"123\", \"223\");\n AssertOrdered(\"123\", \"1234\");\n AssertOrdered(\"123\", \"2345\");\n AssertOrdered(\"0\", \"1\");\n AssertOrdered(\"123Hello\", \"124Hello\");\n AssertOrdered(\"123Hello\", \"133Hello\");\n AssertOrdered(\"123Hello\", \"223Hello\");\n AssertOrdered(\"123Hello\", \"1234Hello\");\n }\n\n private static void AssertEqual(string x, string y)\n {\n Assert.Equal(0, NaturalStringComparer.Instance.Compare(x, y));\n Assert.Equal(0, NaturalStringComparer.Instance.Compare(y, x));\n }\n\n private static void AssertOrdered(string x, string y)\n {\n Assert.Equal(-1, NaturalStringComparer.Instance.Compare(x, y));\n Assert.Equal( 1, NaturalStringComparer.Instance.Compare(y, x));\n }\n}\n" }, { "answer_id": 47400729, "author": "Tom Pažourek", "author_id": 108374, "author_profile": "https://Stackoverflow.com/users/108374", "pm_score": 2, "selected": false, "text": "StringComparer StringComparer.CurrentCulture.WithNaturalSort() StringComparer.OrdinalIgnoreCase.WithNaturalSort() IComparer<string> OrderBy OrderByDescending ThenBy ThenByDescending SortedSet<string> Install-Package NaturalSort.Extension\n public static class StringComparerNaturalSortExtension\n{\n public static IComparer<string> WithNaturalSort(this StringComparer stringComparer) => new NaturalSortComparer(stringComparer);\n\n private class NaturalSortComparer : IComparer<string>\n {\n public NaturalSortComparer(StringComparer stringComparer)\n {\n _stringComparer = stringComparer;\n }\n\n private readonly StringComparer _stringComparer;\n private static readonly Regex NumberSequenceRegex = new Regex(@\"(\\d+)\", RegexOptions.Compiled | RegexOptions.CultureInvariant);\n private static string[] Tokenize(string s) => s == null ? new string[] { } : NumberSequenceRegex.Split(s);\n private static ulong ParseNumberOrZero(string s) => ulong.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var result) ? result : 0;\n\n public int Compare(string s1, string s2)\n {\n var tokens1 = Tokenize(s1);\n var tokens2 = Tokenize(s2);\n\n var zipCompare = tokens1.Zip(tokens2, TokenCompare).FirstOrDefault(x => x != 0);\n if (zipCompare != 0)\n return zipCompare;\n\n var lengthCompare = tokens1.Length.CompareTo(tokens2.Length);\n return lengthCompare;\n }\n \n private int TokenCompare(string token1, string token2)\n {\n var number1 = ParseNumberOrZero(token1);\n var number2 = ParseNumberOrZero(token2);\n\n var numberCompare = number1.CompareTo(number2);\n if (numberCompare != 0)\n return numberCompare;\n\n var stringCompare = _stringComparer.Compare(token1, token2);\n return stringCompare;\n }\n }\n}\n" }, { "answer_id": 49982177, "author": "mshsayem", "author_id": 152349, "author_profile": "https://Stackoverflow.com/users/152349", "pm_score": 2, "selected": false, "text": "var alphaStrings = new List<string>() { \"10\",\"2\",\"3\",\"4\",\"50\",\"11\",\"100\",\"a12\",\"b12\" };\nvar orderedString = alphaStrings.OrderBy(g => new Tuple<int, string>(g.ToCharArray().All(char.IsDigit)? int.Parse(g) : int.MaxValue, g));\n// Order Now: [\"2\",\"3\",\"4\",\"10\",\"11\",\"50\",\"100\",\"a12\",\"b12\"]\n" }, { "answer_id": 52318194, "author": "Oliver", "author_id": 284741, "author_profile": "https://Stackoverflow.com/users/284741", "pm_score": 2, "selected": false, "text": "IComparer private class NaturalStringComparer : IComparer<string>\n{\n public int Compare(string left, string right)\n {\n int max = new[] { left, right }\n .SelectMany(x => Regex.Matches(x, @\"\\d+\").Cast<Match>().Select(y => (int?)y.Value.Length))\n .Max() ?? 0;\n\n var leftPadded = Regex.Replace(left, @\"\\d+\", m => m.Value.PadLeft(max, '0'));\n var rightPadded = Regex.Replace(right, @\"\\d+\", m => m.Value.PadLeft(max, '0'));\n\n return string.Compare(leftPadded, rightPadded);\n }\n}\n" }, { "answer_id": 53323586, "author": "girishkatta9", "author_id": 2501245, "author_profile": "https://Stackoverflow.com/users/2501245", "pm_score": -1, "selected": false, "text": "var imageNameList = new DirectoryInfo(@\"C:\\Temp\\Images\").GetFiles(\"*.png\").Select(x =>x.Name.Substring(0, x.Name.Length - 4)).ToList();\nimageNameList.Sort();\n" }, { "answer_id": 58328837, "author": "Kelly Elton", "author_id": 222054, "author_profile": "https://Stackoverflow.com/users/222054", "pm_score": 1, "selected": false, "text": "public class NaturalStringComparer : IComparer<string>\n{\n public static NaturalStringComparer Instance { get; } = new NaturalStringComparer();\n\n public int Compare(string x, string y) {\n const int LeftIsSmaller = -1;\n const int RightIsSmaller = 1;\n const int Equal = 0;\n\n var leftString = x;\n var rightString = y;\n\n var stringComparer = CultureInfo.CurrentCulture.CompareInfo;\n\n int rightIndex;\n int leftIndex;\n\n for (leftIndex = 0, rightIndex = 0;\n leftIndex < leftString.Length && rightIndex < rightString.Length;\n leftIndex++, rightIndex++) {\n var leftChar = leftString[leftIndex];\n var rightChar = rightString[leftIndex];\n\n var leftIsNumber = char.IsNumber(leftChar);\n var rightIsNumber = char.IsNumber(rightChar);\n\n if (!leftIsNumber && !rightIsNumber) {\n var result = stringComparer.Compare(leftString, leftIndex, 1, rightString, leftIndex, 1);\n if (result != 0) return result;\n } else if (leftIsNumber && !rightIsNumber) {\n return LeftIsSmaller;\n } else if (!leftIsNumber && rightIsNumber) {\n return RightIsSmaller;\n } else {\n var leftNumberLength = NumberLength(leftString, leftIndex, out var leftNumber);\n var rightNumberLength = NumberLength(rightString, rightIndex, out var rightNumber);\n\n if (leftNumberLength < rightNumberLength) {\n return LeftIsSmaller;\n } else if (leftNumberLength > rightNumberLength) {\n return RightIsSmaller;\n } else {\n if(leftNumber < rightNumber) {\n return LeftIsSmaller;\n } else if(leftNumber > rightNumber) {\n return RightIsSmaller;\n }\n }\n }\n }\n\n if (leftString.Length < rightString.Length) {\n return LeftIsSmaller;\n } else if(leftString.Length > rightString.Length) {\n return RightIsSmaller;\n }\n\n return Equal;\n }\n\n public int NumberLength(string str, int offset, out int number) {\n if (string.IsNullOrWhiteSpace(str)) throw new ArgumentNullException(nameof(str));\n if (offset >= str.Length) throw new ArgumentOutOfRangeException(nameof(offset), offset, \"Offset must be less than the length of the string.\");\n\n var currentOffset = offset;\n\n var curChar = str[currentOffset];\n\n if (!char.IsNumber(curChar))\n throw new ArgumentException($\"'{curChar}' is not a number.\", nameof(offset));\n\n int length = 1;\n\n var numberString = string.Empty;\n\n for (currentOffset = offset + 1;\n currentOffset < str.Length;\n currentOffset++, length++) {\n\n curChar = str[currentOffset];\n numberString += curChar;\n\n if (!char.IsNumber(curChar)) {\n number = int.Parse(numberString);\n\n return length;\n }\n }\n\n number = int.Parse(numberString);\n\n return length;\n }\n}\n" }, { "answer_id": 66354540, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 3, "selected": false, "text": "public class NaturalSortStringComparer : IComparer<string>\n{\n public static NaturalSortStringComparer Ordinal { get; } = new NaturalSortStringComparer(StringComparison.Ordinal);\n public static NaturalSortStringComparer OrdinalIgnoreCase { get; } = new NaturalSortStringComparer(StringComparison.OrdinalIgnoreCase);\n public static NaturalSortStringComparer CurrentCulture { get; } = new NaturalSortStringComparer(StringComparison.CurrentCulture);\n public static NaturalSortStringComparer CurrentCultureIgnoreCase { get; } = new NaturalSortStringComparer(StringComparison.CurrentCultureIgnoreCase);\n public static NaturalSortStringComparer InvariantCulture { get; } = new NaturalSortStringComparer(StringComparison.InvariantCulture);\n public static NaturalSortStringComparer InvariantCultureIgnoreCase { get; } = new NaturalSortStringComparer(StringComparison.InvariantCultureIgnoreCase);\n\n private readonly StringComparison _comparison;\n\n public NaturalSortStringComparer(StringComparison comparison)\n {\n _comparison = comparison;\n }\n\n public int Compare(string x, string y)\n {\n // Let string.Compare handle the case where x or y is null\n if (x is null || y is null)\n return string.Compare(x, y, _comparison);\n\n var xSegments = GetSegments(x);\n var ySegments = GetSegments(y);\n\n while (xSegments.MoveNext() && ySegments.MoveNext())\n {\n int cmp;\n\n // If they're both numbers, compare the value\n if (xSegments.CurrentIsNumber && ySegments.CurrentIsNumber)\n {\n var xValue = long.Parse(xSegments.Current);\n var yValue = long.Parse(ySegments.Current);\n cmp = xValue.CompareTo(yValue);\n if (cmp != 0)\n return cmp;\n }\n // If x is a number and y is not, x is \"lesser than\" y\n else if (xSegments.CurrentIsNumber)\n {\n return -1;\n }\n // If y is a number and x is not, x is \"greater than\" y\n else if (ySegments.CurrentIsNumber)\n {\n return 1;\n }\n\n // OK, neither are number, compare the segments as text\n cmp = xSegments.Current.CompareTo(ySegments.Current, _comparison);\n if (cmp != 0)\n return cmp;\n }\n\n // At this point, either all segments are equal, or one string is shorter than the other\n\n // If x is shorter, it's \"lesser than\" y\n if (x.Length < y.Length)\n return -1;\n // If x is longer, it's \"greater than\" y\n if (x.Length > y.Length)\n return 1;\n\n // If they have the same length, they're equal\n return 0;\n }\n\n private static StringSegmentEnumerator GetSegments(string s) => new StringSegmentEnumerator(s);\n\n private struct StringSegmentEnumerator\n {\n private readonly string _s;\n private int _start;\n private int _length;\n\n public StringSegmentEnumerator(string s)\n {\n _s = s;\n _start = -1;\n _length = 0;\n CurrentIsNumber = false;\n }\n\n public ReadOnlySpan<char> Current => _s.AsSpan(_start, _length);\n \n public bool CurrentIsNumber { get; private set; }\n\n public bool MoveNext()\n {\n var currentPosition = _start >= 0\n ? _start + _length\n : 0;\n\n if (currentPosition >= _s.Length)\n return false;\n\n int start = currentPosition;\n bool isFirstCharDigit = Char.IsDigit(_s[currentPosition]);\n\n while (++currentPosition < _s.Length && Char.IsDigit(_s[currentPosition]) == isFirstCharDigit)\n {\n }\n\n _start = start;\n _length = currentPosition - start;\n CurrentIsNumber = isFirstCharDigit;\n\n return true;\n }\n }\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
248,615
<p>I have a private const int defined in a C# class. I want compilation to fail with an error if the value of this int mod 3 != 0. How can I accomplish this?</p>
[ { "answer_id": 248637, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": -1, "selected": false, "text": "if (MY_CONST % 3 != 0) { int compilerError = 1 / 0; }\n" }, { "answer_id": 248645, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "int pointless = 1 / (MY_CONST % 3);\n" }, { "answer_id": 248657, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": true, "text": "int compilerError = 1 / (MY_CONST % 3 == 0 ? 1 : 0);\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
248,617
<p>I'm wondering if it is possible to add methods in main program to an existing class defined in header file. For example: There is <code>class CFun</code> defined in file <code>CFun.hpp</code>, but in our <code>party.cpp</code> we want to add a method <code>void hello() {cout &lt;&lt; "hello" &lt;&lt; endl;};</code>without editing <code>CFun.hpp</code></p> <p>Obviously (unfortunately) construction:</p> <pre><code>#include "CFun.hpp" class CFun { public: void hello() {cout &lt;&lt; "hello" &lt;&lt; endl;}; }; </code></pre> <p>doesn't work returning an error <code>Multiple declaration for 'CFun'</code></p> <p>Is it possible to make it work without class inheritance?</p>
[ { "answer_id": 248643, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": true, "text": "void Hello(CFun &fun)\n{\n cout << \"hello\" << endl;\n}\n" }, { "answer_id": 248644, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 2, "selected": false, "text": "CFun hello()" }, { "answer_id": 248671, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 1, "selected": false, "text": "void GoodBye() #define GoodBye() Hello() { cout << \"hello\" << endl; } void GoodBye()\n#include \"CFun.hpp\"\n#undef GoodBye\n" }, { "answer_id": 324915, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "class Party : class CFun\n Party p;\np.hello();\n" }, { "answer_id": 7432448, "author": "Tamzin Blake", "author_id": 650551, "author_profile": "https://Stackoverflow.com/users/650551", "pm_score": 2, "selected": false, "text": "#include \"CFun.hpp\"\n\nclass CFun2 : public CFun\n{\n public:\n void hello() {cout << \"hello\" << endl;};\n};\n CFun2 CFun" }, { "answer_id": 14435792, "author": "Timo", "author_id": 1996572, "author_profile": "https://Stackoverflow.com/users/1996572", "pm_score": 3, "selected": false, "text": "#define CFun CLessFun\n#include \"CFun.hpp\"\n#undef CFun\n\nclass CFun : CLessFun\n{\n public:\n void hello() {cout << \"hello\" << endl;};\n};\n CMoreFun.hpp CFun.hpp" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32312/" ]
248,667
<p>Objective: take a UIImage, crop out a square in the middle, change size of square to 320x320 pixels, slice up the image into 16 80x80 images, save the 16 images in an array.</p> <p>Here's my code:</p> <pre><code>CGImageRef originalImage, resizedImage, finalImage, tmp; float imgWidth, imgHeight, diff; UIImage *squareImage, *playImage; NSMutableArray *tileImgArray; int r, c; originalImage = [image CGImage]; imgWidth = image.size.width; imgHeight = image.size.height; diff = fabs(imgWidth - imgHeight); if(imgWidth &gt; imgHeight){ resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(floor(diff/2), 0, imgHeight, imgHeight)); }else{ resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(0, floor(diff/2), imgWidth, imgWidth)); } CGImageRelease(originalImage); squareImage = [UIImage imageWithCGImage:resizedImage]; if(squareImage.size.width != squareImage.size.height){ NSLog(@"image cutout error!"); //*code to return to main menu of app, irrelevant here }else{ float newDim = squareImage.size.width; if(newDim != 320.0){ CGSize finalSize = CGSizeMake(320.0, 320.0); UIGraphicsBeginImageContext(finalSize); [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)]; playImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }else{ playImage = squareImage; } } finalImage = [playImage CGImage]; tileImgArray = [NSMutableArray arrayWithCapacity:0]; for(int i = 0; i &lt; 16; i++){ r = i/4; c = i%4; //* tmp = CGImageCreateWithImageInRect(finalImage, CGRectMake(c*tileSize, r*tileSize, tileSize, tileSize)); [tileImgArray addObject:[UIImage imageWithCGImage:tmp]]; } </code></pre> <p>The code works correctly when the original (the variable image) has its smaller dimension either bigger or smaller than 320 pixels. When it's exactly 320, the resulting 80x80 images are almost entirely black, some with a few pixels at the edges that may (I can't really tell) be from the original image.</p> <p>I tested by displaying the full image both directly:</p> <pre><code>[UIImage imageWithCGImage:finalImage]; </code></pre> <p>And indirectly:</p> <pre><code>[UIImage imageWithCGImage:CGImageCreateWithImageInRect(finalImage, CGRectMake(0, 0, 320, 320))]; </code></pre> <p>In both cases, the display worked. The problems only arise when I attempt to slice out some part of the image.</p>
[ { "answer_id": 249174, "author": "executor21", "author_id": 30952, "author_profile": "https://Stackoverflow.com/users/30952", "pm_score": 4, "selected": true, "text": "if(newDim != 320.0){\n CGSize finalSize = CGSizeMake(320.0, 320.0);\n UIGraphicsBeginImageContext(finalSize);\n [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)];\n playImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n}else{\n CGSize finalSize = CGSizeMake(320.0, 320.0);\n UIGraphicsBeginImageContext(finalSize);\n [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)];\n playImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n}\n" }, { "answer_id": 962447, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "// cut the given image into a grid of equally sized smaller images\n// this assumes that the image can be equally divided in the requested increments\n// the images will be stored in the return array in [row][column] order\n+ (TwoDimensionalArray *) chopImageIntoGrid : (UIImage *) originalImage : (int) numberOfRows : (int) numberOfColumns\n{ \n// figure out the size of our tiles\nint tileWidth = originalImage.size.width / numberOfColumns;\nint tileHeight = originalImage.size.height / numberOfRows;\n\n// create our return array\nTwoDimensionalArray * toReturn = [[TwoDimensionalArray alloc] initWithBounds : numberOfRows \n : numberOfColumns];\n\n// get a CGI image version of our image\nCGImageRef cgVersionOfOriginal = [originalImage CGImage];\n\n// loop to chop up each row\nfor(int row = 0; row < numberOfRows ; row++){\n // loop to chop up each individual piece by column\n for (int column = 0; column < numberOfColumns; column++)\n {\n CGImageRef tempImage = \n CGImageCreateWithImageInRect(cgVersionOfOriginal, \n CGRectMake(column * tileWidth, \n row * tileHeight, \n tileWidth, \n tileHeight));\n [toReturn setObjectAt : row : column : [UIImage imageWithCGImage:tempImage]];\n }\n}\n\n// now return the set of images we created\nreturn [toReturn autorelease];\n}\n\n// this method resizes an image to the requested dimentions\n// be a bit careful when using this method, since the resize will not respect\n// the proportions of the image\n+ (UIImage *) resize : (UIImage *) originalImage : (int) newWidth : (int) newHeight\n{ \n// translate the image to the new size\nCGSize newSize = CGSizeMake(newWidth, newHeight); // the new size we want the image to be\nUIGraphicsBeginImageContext(newSize); // downside: this can't go on a background thread, I'm told\n[originalImage drawInRect : CGRectMake(0, 0, newSize.width, newSize.height)];\nUIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); // get our new image\nUIGraphicsEndImageContext();\n\n// return our brand new image\nreturn newImage;\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30952/" ]
248,668
<p>I've been trying to code a Perl script to substitute some text on all source files of my project. I'm in need of something like:</p> <pre><code>perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" *.{cs,aspx,ascx} </code></pre> <p>But that parses <strong>all</strong> the files of a directory <strong>recursively</strong>.</p> <p>I just started a script:</p> <pre><code>use File::Find::Rule; use strict; my @files = (File::Find::Rule-&gt;file()-&gt;name('*.cs','*.aspx','*.ascx')-&gt;in('.')); foreach my $f (@files){ if ($f =~ s/thisgoesout/thisgoesin/gi) { # In-place file editing, or something like that } } </code></pre> <p>But now I'm stuck. Is there a simple way to edit all files in place using Perl?</p> <p>Please note that I don't need to keep a copy of every modified file; I'm have 'em all subversioned =)</p> <p><strong>Update</strong>: I tried this on <a href="http://en.wikipedia.org/wiki/Cygwin" rel="nofollow noreferrer">Cygwin</a>,</p> <pre><code>perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" {*,*/*,*/*/*}.{cs,aspx,ascx </code></pre> <p>But it looks like my arguments list exploded to the maximum size allowed. In fact, I'm getting very strange errors on Cygwin...</p>
[ { "answer_id": 248680, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "find find . -name '*.{cs,aspx,ascx}' | xargs perl -p -i.bak -e \"s/thisgoesout/thisgoesin/gi\"\n xargs xargs find find . | grep -E '(cs|aspx|ascx)$' | xargs ...\n xargs -i" }, { "answer_id": 248779, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 2, "selected": false, "text": "foreach my $f (@files){\n if ($f =~ s/thisgoesout/thisgoesin/gi) {\n #inplace file editing, or something like that\n }\n}\n foreach my $f (@files){\n open my $in, '<', $f;\n open my $out, '>', \"$f.out\";\n while (my $line = <$in>){\n chomp $line;\n $line =~ s/thisgoesout/thisgoesin/gi\n print $out \"$line\\n\";\n }\n}\n chomp chomp print $out \"$line\\n\"; print $out $line; open my $out, '>', \"$f.out\"; open my $out, '>', undef;" }, { "answer_id": 248781, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 3, "selected": false, "text": " # In this example, we wish to replace \n # the word 'foo' with the word 'bar' in several files, \n # with no risk of ending up with the replacement done \n # in some files but not in others.\n\n use File::Transaction::Atomic;\n\n my $ft = File::Transaction::Atomic->new;\n\n eval {\n foreach my $file (@list_of_file_names) {\n $ft->linewise_rewrite($file, sub {\n s#\\bfoo\\b#bar#g;\n });\n }\n };\n\n if ($@) {\n $ft->revert;\n die \"update aborted: $@\";\n }\n else {\n $ft->commit;\n }\n" }, { "answer_id": 248832, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": true, "text": "@ARGV *ARGV <> $^I -i use File::Find::Rule;\nuse strict;\n\n@ARGV = (File::Find::Rule->file()->name('*.cs', '*.aspx', '*.ascx')->in('.'));\n$^I = '.bak'; # or set `-i` in the #! line or on the command-line\n\nwhile (<>) {\n s/thisgoesout/thisgoesin/gi;\n print;\n}\n undef $/; <>" }, { "answer_id": 252140, "author": "Seiti", "author_id": 27959, "author_profile": "https://Stackoverflow.com/users/27959", "pm_score": 1, "selected": false, "text": "use File::Find::Rule;\nuse strict;\n\nsub ReplaceText {\n my $regex = shift;\n my $replace = shift;\n\n @ARGV = (File::Find::Rule->file()->name('*.cs','*.aspx','*.ascx')->in('.'));\n $^I = '.bak';\n while (<>) {\n s/$regex/$replace->()/gie;\n print;\n }\n}\n\nReplaceText qr/some(crazy)regexp/, sub { \"some $1 text\" };\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27959/" ]
248,683
<p>I want to do a select in MySql that combines several columns... something like this pseudocode:</p> <pre><code>SELECT payment1_paid AND payment2_paid AS paid_in_full FROM denormalized_payments WHERE payment1_type = 'check'; </code></pre> <p><strong>Edit</strong>: payment1_paid and payment2_paid are booleans.</p> <p>I can't use any other language for this particular problem than MySql.</p> <p>Thanks for any help!</p> <p><strong>Edit</strong>: Sorry to everybody who gave me suggestions for summing and concatenating, but I've voted those early answers up because they're useful anyway. And <strong>thanks</strong> to everybody for your incredibly quick answers!</p>
[ { "answer_id": 248685, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 2, "selected": false, "text": "Select CONCAT(payment1_paid, payment2_paid) as paid_in_full \nfrom denormalized_payments \nwhere payment1_type = 'check';\n" }, { "answer_id": 248689, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "select concat(payment1_paid, payment2_paid) as paid_in_full\nfrom denormalized_payments where payment1_type = 'check';\n select payment1_paid + payment2_paid as paid_in_full\nfrom denormalized_payments where payment1_type = 'check';\n select payment1_paid && payment2_paid as paid_in_full\nfrom denormalized_payments where payment1_type = 'check';\n" }, { "answer_id": 248691, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 1, "selected": false, "text": "SELECT CONCAT(ColumnA, ColumnB) AS ColumnZ\nFROM Table\n" }, { "answer_id": 248697, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "SELECT IF(payment1_paid = 1 AND payment2_paid = 1, 1, 0) AS paid_in_fill" }, { "answer_id": 248705, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 4, "selected": true, "text": "Select (payment1_paid && payment2_paid) as paid_in_full \nfrom denormalized_payments \nwhere payment1_type = 'check';\n" }, { "answer_id": 248762, "author": "dshaw", "author_id": 32595, "author_profile": "https://Stackoverflow.com/users/32595", "pm_score": 0, "selected": false, "text": "select (payment1_paid && payment2_paid) as paid_in_full\nfrom denormalized_payments where payment1_type = 'check';\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
248,688
<p>Just wondering if there are any good server-side libraries for AJAX (prefer JSON rather then XML but anything is good) for classic ASP (VBScript)...</p> <p>Rather not reinvent the wheel if it's already working and debugged.</p> <p>Cheers, Gaspard</p> <p>EDIT: Server-side ASP VBScript... I have already seen many javascript client side libraries.</p>
[ { "answer_id": 250987, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "function fetch(elelment,cmd,id) {\n //general purpose AJAX function\n $(elelment).innerHTML='Loading...<br /><img src=\"/images/spinner.gif\">'\n now = new Date()\n url = 'http://..../Ajax.asp?CMD='+cmd+'&ID='+pid+'&now='+now\n new Ajax.Updater(elelment, url, { method: 'get' });\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32601/" ]
248,693
<p>I just came onto a project with a pretty huge code base. </p> <p>I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic. </p> <pre><code> if (!!variable &amp;&amp; (!!api.lookup("some-string"))) { do_some_stuff(); } </code></pre> <p>I know these guys are intelligent programmers, it's obvious they aren't doing this by accident. </p> <p>I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value. </p> <p>Is this correct, or am I missing something?</p>
[ { "answer_id": 248703, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 4, "selected": false, "text": "!!" }, { "answer_id": 248732, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 0, "selected": false, "text": "variable api.call" }, { "answer_id": 248747, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "true TRUE if (api.lookup(\"some-string\") == true) {...} bool bool (some_variable != 0)" }, { "answer_id": 249305, "author": "Tom Barta", "author_id": 29839, "author_profile": "https://Stackoverflow.com/users/29839", "pm_score": 6, "selected": false, "text": "#define likely(cond) (__builtin_expect(!!(cond), 1))\n#define unlikely(cond) (__builtin_expect(!!(cond), 0))\n __builtin_expect long bool cond !!" }, { "answer_id": 253151, "author": "RobH", "author_id": 25488, "author_profile": "https://Stackoverflow.com/users/25488", "pm_score": 3, "selected": false, "text": "int _tmain(int argc, _TCHAR* argv[])\n{\n int foo = 5;\n bool bar = foo;\n bool baz = !!foo;\n return 0;\n}\n" }, { "answer_id": 25495721, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 2, "selected": false, "text": "!! if(condition) condition double, int, void* bool int256 int256 x = foo();\nif (x) ...\n x if (x) x int (int) x x if (x) x ! !x x if (!!x)" }, { "answer_id": 27261422, "author": "KarlU", "author_id": 766527, "author_profile": "https://Stackoverflow.com/users/766527", "pm_score": 3, "selected": false, "text": "#define TRUE 1 #define FALSE 0 bool !num_value bool true num_value == 0 false !!num_value bool false num_value == 0 true num_value bool static_cast<bool>(num_value) (num_value != FALSE) !!num_value" }, { "answer_id": 40001799, "author": "kgf3JfUtW", "author_id": 3927314, "author_profile": "https://Stackoverflow.com/users/3927314", "pm_score": 1, "selected": false, "text": "operator bool // operator bool version\nclass Testable {\n bool ok_;\n public:\n explicit Testable(bool b = true) : ok_(b) {}\n\n operator bool() const { // use bool conversion operator\n return ok_;\n }\n};\n Testable test;\nif (test) {\n std::cout << \"Yes, test is working!\\n\";\n}\nelse { \n std::cout << \"No, test is not working!\\n\";\n}\n operator bool test << 1; int i = test operator! bool operator!() const { // use operator!\n return !ok_;\n}\n Testable Testable test;\nif (!!test) {\n std::cout << \"Yes, test is working!\\n\";\n}\nif (!test) {\n std::cout << \"No, test is not working!\\n\";\n}\n if (!!test)" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
248,719
<p>We are a group of students doing our Master degree in field of computer science.</p> <p>This semester we should do a Software engineering project according to the following bottom explanation.</p> <p>we should exactly act and report as a real Software engineering Team.</p> <p>I have been chosen as a project manager of this group, I am good in writing java codes but I don't have the experience of doing the project manager task, any way I have to do my best to do this project with my group members as good as possible.</p> <p>The problem is this that I need to deal with different levels of knowledge but all the members should participate in implementation part.</p> <p>I will be pleased if some one guide me how to do this project and how to manage this group, and where to start? how to encourage the members, and how to do my plans in practice?</p> <p>please have a look to the explanation and help me what technology do I need to chose for this project?</p> <h2>Project Explanation</h2> <p>projects should be implemented as so called web applications. Because of the MVC requirements this is more than a server-client architecture – we call this (at least) a three-tier architecture.</p> <p>The view should be created dynamic on clients' request. Therefor the content has to be computed by the server (server side). Inside of the view there should not exist any type of source code (like “scriplets”, Java Code, etc.) besides the markup language.</p> <p>This should ensure that the view can be created by web designers where the content is in the responsibility of programmers.</p> <p>Vice versa the source code should not contain any markup languages (like HTML).</p> <p>To store information (make persistent) the system should use a database. But there should not exist database specific queries inside of the source code – because then the sources are very dependent of the usage of exactly this database. System should work with an object relational mapper to map the stored information from database on special type of objects (beans).</p> <p>All configuration like database, entities, configuration, initialization should be realized using XML files (or similar ways like e.g, annotations), so that changes don't require recompilation of the system's sources.</p> <p>Technologies available (suggestions):</p> <pre><code> J2EE: JSP, Servlets, JSP EL, JSTL, JSF, Facelets, Custom JSF Components, Custom Facelets TagLibs, JUnit (unit testing) Persistence: Hibernate, JDO IDE: Eclipse, NetBeans Servlet Container: Apache Tomcat </code></pre>
[ { "answer_id": 251140, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " (A) Administrative Staff Exchange\n (B) Scientific Employee Exchange\n (C) Student Exchange\n (D) Public Exchange\n\n Universities can get registered to participate in that platform by sending a corresponding request\n to administration of that platform (e.g. MoHE). After an university has become member of that\n platform, students, employees and administration staff can register themselves as member of\n that university with the related role (student, employee or administrative staff).\n The content that is accessible for members than depends on their role. So, students can't access\n content that is tagged as employee content – and so on. Content that is tagged as public is accessible for members of all roles.\n Content inside of that platform can mean two different things.\n\n (A) Forum (Discussions on topics)\n (B) Wiki (Best practices)\n\n So besides the topic, Wiki pages and Forum topics have to be categorized to administration,\n employee, student or public content.\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
248,721
<p>I need to have a single instance application (as per this <a href="https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application#19326">answer</a>), but it needs to be deployed via click once.</p> <p>The problem is that I require that click once doesn't automatically detect an update an attempt to load a newer version while the application is running. If it is running, then I need the other instance to be made active. Usually, when selecting a Click Once link, the very first thing it does is attempt to find an update. I want to intercept this and check for an already running instance <strong>prior</strong> to launching the normal update process.</p> <p>Does anyone know how this is possible within a Click Once deployment scenario?</p>
[ { "answer_id": 322984, "author": "ping", "author_id": 41206, "author_profile": "https://Stackoverflow.com/users/41206", "pm_score": 6, "selected": true, "text": "namespace ClickOnceDemo\n{\n static class Program\n {\n /// summary>\n /// The main entry point for the application.\n /// /summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault( false );\n bool ok;\n var m = new System.Threading.Mutex( true, \"Application\", out ok );\n if ( !ok )\n {\n MessageBox.Show( \"Another instance is already running.\", ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString() );\n return;\n }\n Application.Run( new UpdateProgress() );\n }\n }\n}\n namespace ClickOnceDemo\n{\npublic partial class UpdateProgress : Form\n {\n public UpdateProgress()\n {\n InitializeComponent();\n Text = \"Checking for updates...\";\n\n ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;\n ad.CheckForUpdateCompleted += OnCheckForUpdateCompleted;\n ad.CheckForUpdateProgressChanged += OnCheckForUpdateProgressChanged;\n\n ad.CheckForUpdateAsync();\n }\n\n private void OnCheckForUpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)\n {\n lblStatus.Text = String.Format( \"Downloading: {0}. {1:D}K of {2:D}K downloaded.\", GetProgressString( e.State ), e.BytesCompleted / 1024, e.BytesTotal / 1024 );\n progressBar1.Value = e.ProgressPercentage;\n }\n\n string GetProgressString( DeploymentProgressState state )\n {\n if ( state == DeploymentProgressState.DownloadingApplicationFiles )\n {\n return \"application files\";\n }\n if ( state == DeploymentProgressState.DownloadingApplicationInformation )\n {\n return \"application manifest\";\n }\n return \"deployment manifest\";\n }\n\n private void OnCheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)\n {\n if ( e.Error != null )\n {\n MessageBox.Show( \"ERROR: Could not retrieve new version of the application. Reason: \\n\" + e.Error.Message + \"\\nPlease report this error to the system administrator.\" );\n return;\n }\n if ( e.Cancelled )\n {\n MessageBox.Show( \"The update was cancelled.\" );\n }\n\n // Ask the user if they would like to update the application now.\n if ( e.UpdateAvailable )\n {\n if ( !e.IsUpdateRequired )\n {\n long updateSize = e.UpdateSizeBytes;\n DialogResult dr = MessageBox.Show( string.Format(\"An update ({0}K) is available. Would you like to update the application now?\", updateSize/1024), \"Update Available\", MessageBoxButtons.OKCancel );\n if ( DialogResult.OK == dr )\n {\n BeginUpdate();\n }\n }\n else\n {\n MessageBox.Show( \"A mandatory update is available for your application. We will install the update now, after which we will save all of your in-progress data and restart your application.\" );\n BeginUpdate();\n }\n }\n else\n {\n ShowMainForm();\n }\n }\n\n // Show the main application form\n private void ShowMainForm()\n {\n MainForm mainForm = new MainForm ();\n mainForm.Show();\n Hide();\n }\n\n private void BeginUpdate()\n {\n Text = \"Downloading update...\";\n ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;\n ad.UpdateCompleted += ad_UpdateCompleted;\n ad.UpdateProgressChanged += ad_UpdateProgressChanged;\n\n ad.UpdateAsync();\n }\n\n void ad_UpdateProgressChanged( object sender, DeploymentProgressChangedEventArgs e )\n {\n String progressText = String.Format( \"{0:D}K out of {1:D}K downloaded - {2:D}% complete\", e.BytesCompleted / 1024, e.BytesTotal / 1024, e.ProgressPercentage );\n progressBar1.Value = e.ProgressPercentage;\n lblStatus.Text = progressText;\n }\n\n void ad_UpdateCompleted( object sender, AsyncCompletedEventArgs e )\n {\n if ( e.Cancelled )\n {\n MessageBox.Show( \"The update of the application's latest version was cancelled.\" );\n return;\n }\n if ( e.Error != null )\n {\n MessageBox.Show( \"ERROR: Could not install the latest version of the application. Reason: \\n\" + e.Error.Message + \"\\nPlease report this error to the system administrator.\" );\n return;\n }\n\n DialogResult dr = MessageBox.Show( \"The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)\", \"Restart Application\", MessageBoxButtons.OKCancel );\n if ( DialogResult.OK == dr )\n {\n Application.Restart();\n }\n else\n {\n ShowMainForm();\n }\n }\n }\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2918/" ]
248,738
<p>I have some user controls that I'm loading in SharePoint and I would prefer to have all those styles contained in an external style sheet. What's the best way to link to an external stylesheet in CSS?</p> <p>Thanks.</p>
[ { "answer_id": 249711, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 1, "selected": false, "text": "protected override void OnPreRender(EventArgs e)\n {\n const string stylesheet = \"YourStylesheet.css\";\n if (!Page.IsClientScriptBlockRegistered(stylesheet))\n {\n Page.RegisterClientScriptBlock(stylesheet, \n string.Format(@\"<link href=\"\"{0}/{1}\"\" rel=\"\"stylesheet\"\"/>\",\n this.ClassResourcePath, stylesheet));\n }\n base.OnPreRender(e);\n }\n" }, { "answer_id": 250782, "author": "Abs", "author_id": 1245, "author_profile": "https://Stackoverflow.com/users/1245", "pm_score": 0, "selected": false, "text": "theWeb" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
248,753
<p>This is the sequel to <a href="https://stackoverflow.com/questions/248683/how-can-i-do-boolean-logic-on-two-columns-in-mysql">this question</a>.</p> <p>I would like to combine three columns into one on a MySql select. The first two columns are boolean and the third is a string, which is sometimes null. This causes strange results:</p> <pre><code>Select *, (payment1_paid &amp;&amp; ((payment2_paid || payment2_type ="none"))) as paid_in_full from payments </code></pre> <p><strong>Note:</strong> <code>payment1_paid</code> is boolean, <code>payment2_paid</code> is boolean, <code>payment2_type</code> is varchar.</p> <p><strong>Note:</strong> Please ignore how ridiculous the structure of this table is. Behind every piece of bad code there is a long explanation :)</p> <p><strong>Edit:</strong> Null is not interesting to me for the varchar value. I only want to know if it's really "none."</p> <p>Thanks in advance for your help!</p>
[ { "answer_id": 248763, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "(payment_paid IS NULL || payment2_type = \"none\")" }, { "answer_id": 248764, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 1, "selected": false, "text": "Select *, \n (payment1_paid && ((payment2_paid || coalesce(payment2_type,\"null\") =\"none\"))) \n as paid_in_full \nfrom payments\n" }, { "answer_id": 248791, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 4, "selected": true, "text": "Select *, \n (payment1_paid && ((payment2_paid || (payment_type IS NOT NULL && payment_type=\"none\"))) \n as paid_in_full \nfrom payments\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
248,754
<p>Back in the earlier days of the internet I remember that in certain browsers, every time you downloaded an image or a file, the URL of where that file was downloaded from would be written into that file's properties (I guess the summary tab?). I think Netscape v2 did this if I remember correctly.</p> <p>I really miss that kind of functionality as every once in a while I'll run into a neat little program stored somewhere in the depths of my hard drive and wonder where I got it from originally.</p> <p>I googled around but I'm not quite sure what terms to use to describe what I'm looking for. So I'm wondering if anyone knows of a Firefox plug-in or something similar that would do this?</p>
[ { "answer_id": 248846, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "download.com_utils_compression_ABCD32.exe\n" }, { "answer_id": 248871, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 0, "selected": false, "text": "http://example.com/foo ~/Desktop/foo foo" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1582/" ]
248,760
<p>I'm not much of a Visual Basic person, but I am tasked with maintaining an old VB6 app. Whenever I check out a file, the editor will replace a bunch of the uppercase variable names with lowercase automatically. How can I make this stop!? I don't want to have to change them all back, and it's a pain to have these changes show up in SourceSafe "Differences" when I'm trying to locate the REAL differences.</p> <p>It is changing it automatically in the definition, too: <code>Dim C as Control</code> becomes <code>Dim c as Control</code>. <code>Dim X&amp;</code> becomes <code>Dim x&amp;</code>. But it doesn't do it all the time; for example, three lines down from <code>Dim x&amp;</code>, there's a <code>Dim Y&amp;</code>, uppercase, which it did not change. Why's it do this to me?</p>
[ { "answer_id": 32582712, "author": "Marko", "author_id": 5337356, "author_profile": "https://Stackoverflow.com/users/5337356", "pm_score": 0, "selected": false, "text": "Public Enum myEnum\n VALUE 'Will be corrected to: Value\n VALUE1 'Will not be corrected\n VALUE_ 'Will not be corrected\nEnd Enum \n" }, { "answer_id": 35040894, "author": "Marcus Mangelsdorf", "author_id": 2822719, "author_profile": "https://Stackoverflow.com/users/2822719", "pm_score": 5, "selected": false, "text": "cOrrectCAse #If False Then\n Dim CorrectCase\n#End If\n Range.Row Range.row row" }, { "answer_id": 51803120, "author": "Steve Roberts", "author_id": 10213247, "author_profile": "https://Stackoverflow.com/users/10213247", "pm_score": 0, "selected": false, "text": "Enum eRowDepths\n BD = 1\n CF = 1\n Separator = 1\n Header = 3\n subTotal = 2\nEnd Enum\n Enum eRowDepths\n BD = 1\n CF = 1\n SEPARATO = 1\n HEADE = 3\n SUBTOTA = 2\nEnd Enum\n 'insert 3 rows\n iSubTotalPlaceHolder = i \n rows(ActiveSheet.Range(rangeDMirrorSubTotals).Cells.Count + _\n Header _\n & \":\" _\n & ActiveSheet.Range(rangeDMirrorSubTotals).Cells.Count + _\n Header + _\n subTotal + _\n Separator).Insert\n Dim fred as Integer\nfred = SEPARATO + HEADE + SUBTOTA\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32613/" ]
248,761
<p>Hopefully I can do the problem justice, because it was too difficult to summarise it in the title! (suggestions are welcome in the comments)</p> <p>Right, so here's my table:</p> <pre><code>Tasks task_id (number) job_id (number) to_do_by_date (date) task_name (varchar / text) status (number) completed_date (date) </code></pre> <p>for arguments sake let's make the values of status:</p> <pre><code>1 = New 2 = InProgress 3 = Done </code></pre> <p>and what I'm having trouble trying to do is create a query that pulls back all of the tasks:</p> <ul> <li>where any of the tasks for a <code>job_id</code> have a <code>status</code> &lt;> Done <ul> <li>except where all tasks for a <code>job_id</code> are are done, but one or more tasks have a <code>completed_date</code> of today</li> </ul></li> <li>ordered by the <code>to_be_done_by</code> date, but grouping all of the job_id tasks together <ul> <li>so the <code>job_id</code> with the next `to_do_by_date' task is shown first</li> </ul></li> </ul> <p>some information about the data:</p> <ul> <li>a <code>job_id</code> can have an arbitrary number of tasks</li> </ul> <p><br /> <strong>Here's an example of the output I'm trying to get:</strong></p> <pre><code>task_id job_id to_do_by_date task_name status completed_date 1 1 yesterday - 3 yesterday 2 1 today - 3 today 3 2 now - 3 today 4 2 2 hours time - 2 {null} 5 2 4 hours time - 2 {null} 6 2 tomorrow - 1 {null} 7 3 3 hours time - 2 {null} 8 3 tomorrow - 1 {null} 9 3 tomorrow - 1 {null} </code></pre> <p><br /> I'm using Oracle 10g, so answers for Oracle or ANSI SQL, or a hint for how to approach this would be ideal, and I can create Views or wrap this in a Stored Procedure to offload logic from the application if your solution calls for it.</p> <p><br /> here's a sql script that will create the example test data shown above:</p> <pre><code>create table tasks (task_id number, job_id number, to_do_by_date date, task_name varchar2(50), status number, completed_date date); insert into tasks values (0,0,sysdate -2, 'Job 0, Task 1 - dont return!', 3, sysdate -2); insert into tasks values (1,1,sysdate -1, 'Job 1, Task 1', 3, sysdate -1); insert into tasks values (2,1,sysdate -2/24, 'Job 1, Task 2', 3, sysdate -2/24); insert into tasks values (3,2,sysdate, 'Job 2, Task 1', 3, sysdate); insert into tasks values (4,2,sysdate +2/24, 'Job 2, Task 2', 2, null); insert into tasks values (5,2,sysdate +4/24, 'Job 2, Task 3', 2, null); insert into tasks values (6,2,sysdate +1, 'Job 2, Task 4', 1, null); insert into tasks values (7,3,sysdate +3/24, 'Job 3, Task 1', 2, null); insert into tasks values (8,3,sysdate +1, 'Job 3, Task 2', 1, null); insert into tasks values (9,3,sysdate +1, 'Job 3, Task 3', 1, null); commit; </code></pre> <p><br /> Many, many thanks for your help :o)</p>
[ { "answer_id": 248831, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 0, "selected": false, "text": "SQL> ed\nWrote file afiedt.buf\n\n 1 select task_id, job_id, to_do_by_date, task_name, status, completed_date\n 2 from tasks t1\n 3 where not exists( select 1\n 4 from tasks t2\n 5 where t1.job_id = t2.job_id\n 6 and t2.status = 3)\n 7 or ((not exists( select 1\n 8 from tasks t3\n 9 where t1.job_id = t3.job_id\n 10 and t3.status != 3))\n 11 and\n 12 exists (select 1\n 13 from tasks t4\n 14 where t1.job_id = t4.job_id\n 15 and trunc(t4.completed_date) = trunc(sysdate)))\n 16* order by job_id, to_do_by_date\nSQL> /\n\n TASK_ID JOB_ID TO_DO_BY_ TASK_NAME STATUS COMPLETED\n---------- ---------- --------- --------------- ---------- ---------\n 1 1 28-OCT-08 Job 1, Task 1 3 28-OCT-08\n 2 1 29-OCT-08 Job 1, Task 2 3 29-OCT-08\n 7 3 29-OCT-08 Job 3, Task 1 2\n 8 3 30-OCT-08 Job 3, Task 2 1\n 9 3 30-OCT-08 Job 3, Task 3 1\n" }, { "answer_id": 248833, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "SELECT Tasks.*\nFROM Tasks\nJOIN (\n --Undone\n SELECT Job_Id\n FROM Tasks\n WHERE\n Status <> 3\n UNION\n --Done today\n SELECT Job_Id\n FROM Tasks\n WHERE\n Status = 3\n AND Completed_Date = TODAY()\n) as UndoneOrDoneToday ON\n Tasks.Job_Id = UndoneOrDoneToday.Job_Id\nJOIN (\n SELECT Job_Id, MIN(to_do_by_date) as NextToDoByDate\n FROM Tasks\n GROUP BY Job_id\n) as NextJob ON\n Tasks.Job_Id = NextJob.Job_id\nORDER BY\n NextJob.NextToDoByDate, \n Tasks.Job_Id, --If NextToDoByDate isn't unique, this should order jobs together\n Tasks.to_do_by_date, --This may not be needed, but would put eg., task 7 due today higher than task 6 due tomorrow\n Tasks.Task_Id --this should be last\n" }, { "answer_id": 248844, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 3, "selected": true, "text": "SELECT \n task_id, job_id, to_do_by_date, task_name, status, completed_date\nFROM\n Tasks\nWHERE\n job_id IN (\n SELECT job_id \n FROM Tasks \n WHERE status <> 'Done' \n GROUP BY job_id)\n OR\n job_id IN (\n SELECT job_id \n FROM Tasks \n WHERE status = 'Done' AND completed_date = 'Today'\n AND job_id NOT IN (SELECT job_id FROM Tasks WHERE status <> 'Done' GROUP BY job_id)\n GROUP BY job_id)\nORDER BY\n job_id, to_do_by_date\n" }, { "answer_id": 248886, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "select * from\n(\nselect t.*,\n min(status) over (partition by job_id) min_status_over_job,\n max(status) over (partition by job_id) max_status_over_job,\n sum(case when trunc(completed_date) = trunc(sysdate)-1 then 1 else 0 end) \n over (partition by job_id) num_complete_yest\nfrom tasks t\n)\nwhere max_status_over_job < 3\n or (min_status_over_job = 3 and num_complete_yest > 0)\n/\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
248,768
<p>I am trying to to walk though the tree of PdfItem objects in an existing PDF document using PDFSharp in c#. </p> <p>I want to create a hierarchy of all the objects as I go along -- similar to what the "PDF Explorer" example does -- but I want it to be a tree instead of a flat list of all the objects.</p> <p>The root node is document.Internals.Catalog. And I want to to walk down through all the document.Internals.Catalog.Elements until I have visited every element.</p> <p>One of the problems I run into is that there are circular references in the tree and I can't figure out how to detect them.</p> <p>Any code samples out there?</p>
[ { "answer_id": 1732265, "author": "Brian Low", "author_id": 46039, "author_profile": "https://Stackoverflow.com/users/46039", "pm_score": 4, "selected": true, "text": "public class PDFParser\n{\n /// BT = Beginning of a text object operator\n /// ET = End of a text object operator\n /// Td move to the start of next line\n /// 5 Ts = superscript\n /// -5 Ts = subscript\n\n #region Fields\n\n #region _numberOfCharsToKeep\n /// <summary>\n /// The number of characters to keep, when extracting text.\n /// </summary>\n private static int _numberOfCharsToKeep = 15;\n #endregion\n\n #endregion\n\n\n\n #region ExtractTextFromPDFBytes\n /// <summary>\n /// This method processes an uncompressed Adobe (text) object\n /// and extracts text.\n /// </summary>\n /// <param name=\"input\">uncompressed</param>\n /// <returns></returns>\n public string ExtractTextFromPDFBytes(byte[] input)\n {\n if (input == null || input.Length == 0) return \"\";\n\n try\n {\n string resultString = \"\";\n\n // Flag showing if we are we currently inside a text object\n bool inTextObject = false;\n\n // Flag showing if the next character is literal\n // e.g. '\\\\' to get a '\\' character or '\\(' to get '('\n bool nextLiteral = false;\n\n // () Bracket nesting level. Text appears inside ()\n int bracketDepth = 0;\n\n // Keep previous chars to get extract numbers etc.:\n char[] previousCharacters = new char[_numberOfCharsToKeep];\n for (int j = 0; j < _numberOfCharsToKeep; j++) previousCharacters[j] = ' ';\n\n\n for (int i = 0; i < input.Length; i++)\n {\n char c = (char)input[i];\n\n if (inTextObject)\n {\n // Position the text\n if (bracketDepth == 0)\n {\n if (CheckToken(new string[] { \"TD\", \"Td\" }, previousCharacters))\n {\n resultString += \"\\n\\r\";\n }\n else\n {\n if (CheckToken(new string[] { \"'\", \"T*\", \"\\\"\" }, previousCharacters))\n {\n resultString += \"\\n\";\n }\n else\n {\n if (CheckToken(new string[] { \"Tj\" }, previousCharacters))\n {\n resultString += \" \";\n }\n }\n }\n }\n\n // End of a text object, also go to a new line.\n if (bracketDepth == 0 &&\n CheckToken(new string[] { \"ET\" }, previousCharacters))\n {\n\n inTextObject = false;\n resultString += \" \";\n }\n else\n {\n // Start outputting text\n if ((c == '(') && (bracketDepth == 0) && (!nextLiteral))\n {\n bracketDepth = 1;\n }\n else\n {\n // Stop outputting text\n if ((c == ')') && (bracketDepth == 1) && (!nextLiteral))\n {\n bracketDepth = 0;\n }\n else\n {\n // Just a normal text character:\n if (bracketDepth == 1)\n {\n // Only print out next character no matter what.\n // Do not interpret.\n if (c == '\\\\' && !nextLiteral)\n {\n nextLiteral = true;\n }\n else\n {\n if (((c >= ' ') && (c <= '~')) ||\n ((c >= 128) && (c < 255)))\n {\n resultString += c.ToString();\n }\n\n nextLiteral = false;\n }\n }\n }\n }\n }\n }\n\n // Store the recent characters for\n // when we have to go back for a checking\n for (int j = 0; j < _numberOfCharsToKeep - 1; j++)\n {\n previousCharacters[j] = previousCharacters[j + 1];\n }\n previousCharacters[_numberOfCharsToKeep - 1] = c;\n\n // Start of a text object\n if (!inTextObject && CheckToken(new string[] { \"BT\" }, previousCharacters))\n {\n inTextObject = true;\n }\n }\n return resultString;\n }\n catch\n {\n return \"\";\n }\n }\n #endregion\n\n #region CheckToken\n /// <summary>\n /// Check if a certain 2 character token just came along (e.g. BT)\n /// </summary>\n /// <param name=\"search\">the searched token</param>\n /// <param name=\"recent\">the recent character array</param>\n /// <returns></returns>\n private bool CheckToken(string[] tokens, char[] recent)\n {\n foreach (string token in tokens)\n {\n if (token.Length > 1)\n {\n if ((recent[_numberOfCharsToKeep - 3] == token[0]) &&\n (recent[_numberOfCharsToKeep - 2] == token[1]) &&\n ((recent[_numberOfCharsToKeep - 1] == ' ') ||\n (recent[_numberOfCharsToKeep - 1] == 0x0d) ||\n (recent[_numberOfCharsToKeep - 1] == 0x0a)) &&\n ((recent[_numberOfCharsToKeep - 4] == ' ') ||\n (recent[_numberOfCharsToKeep - 4] == 0x0d) ||\n (recent[_numberOfCharsToKeep - 4] == 0x0a))\n )\n {\n return true;\n }\n }\n else\n {\n return false;\n }\n\n }\n return false;\n }\n #endregion\n}\n public override String ExtractText()\n {\n String outputText = \"\";\n try\n {\n PdfDocument inputDocument = PdfReader.Open(this._sDirectory + this._sFileName, PdfDocumentOpenMode.ReadOnly);\n\n foreach (PdfPage page in inputDocument.Pages)\n {\n for (int index = 0; index < page.Contents.Elements.Count; index++)\n {\n\n PdfDictionary.PdfStream stream = page.Contents.Elements.GetDictionary(index).Stream;\n outputText += new PDFParser().ExtractTextFromPDFBytes(stream.Value);\n }\n }\n\n }\n catch (Exception e)\n {\n PDF_ParseException oEx = new PDF_ParseException(this, e);\n oEx.Log();\n oEx.ToPdf(this._sDirectoryException);\n }\n return outputText;\n }\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
248,769
<p>I currently use Notepad++ for most of my development. I have been checking out other, more full-featured options and would like to switch (I'm in particular a fan of Aptana so far) but there is one thing about Notepad++ that I really like and I haven't been able to get so far. </p> <p>My current workflow is something like this: <a href="http://evanalyze.com/images/workflow" rel="nofollow noreferrer">Workflow</a> (I tried to embed this image and it showed up in previews but not in the post, sorry) <a href="http://evanalyze.com/images/workflow.jpg" rel="nofollow noreferrer">Workflow http://evanalyze.com/images/workflow.jpg</a></p> <p>The process is this:</p> <ol> <li>Download file from web server</li> <li>Make edits in NP++</li> <li>Save (this automatically saves a local copy in my default directory, which is also the folder I have setup using Subversion with Tourtise SVN)</li> <li>When I want to commit a change to SVN, go through the local folder that has an up to date copy</li> </ol> <p>What I can't figure out how to do with Aptana is automatically store a local copy of a file I download from my server, edit and save back to the server. Is there some way to do this? If so, that would solve my problem immediately.</p> <p>Other options would be a suggestion for a better way to manage the relationship between my server, my editor and my SVN repository. I know Aptana can access my SVN repository too. Is there an easy way to commit changes from within Aptana when I want to (which means I could take Tourtise out of the equation I guess)?</p> <p>Any suggestions appreciated. Thanks.</p>
[ { "answer_id": 248944, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": true, "text": "export checkout .svn" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30098/" ]
248,789
<p>So I'm reading The Art &amp; Science of Javascript, which is a good book, and it has a good section on JSONP. I've been reading all I can about it today, and even looking through every question here on StackOverflow. JSONP is a great idea, but it only seems to resolve the "Same Origin Problem" for <i>getting</i> data, but doesn't address it for <i>changing</i> data. </p> <p>Did I just miss all the blogs that talked about this, or is JSONP <strong>not</strong> the solution I was hoping for?</p>
[ { "answer_id": 248813, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 3, "selected": true, "text": "<script src=\"http://myserver.com/getjson?customer=232&callback=jsonp543354\" type=\"text/javascript\">\n</script>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31307/" ]
248,799
<p>As far as I know there's no way to hint the c# compiler to inline a particular function and I guess it's like that by design.</p> <p>I also think that not letting the programmer to specify what to inline and what not is generally a good idea, as it would imply that you think you're smarter than the JIT compiler (my respects to those who actually are), but, what if I wanted to specify that a critical portion of code needs to be extremely fast at any cost, no matter how to achieve it on the target machine? As of yet you can't do such a thing and I wonder if both the c# language and the JIT will ever support this feature.</p> <p>In my case, I know what the target machine is, and I know that function inlining will help improve the performance. This leaves me thinking that the only way to enforce function inlining is getting to know under what circumstances the JIT will do it but I don't think that's a good idea either,</p> <p>Any light on the subject would be much appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 248939, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 2, "selected": false, "text": "if(performance < ACCEPTABLE){\n if(profiler.showsAffectOfMethodCallOverhead() && seriouslyWeDoubleChecked()){\n if(runtimeContext.isReallyStableAndNotProneToChange() && weNeedToGetThisThingBatOutOfHellFast()){\n return thisIsOneOfTheFewTimesWhenANativeExternalFunctionMayBeWorthIt();\n }\n }\n }\n return dontWorryAboutIt();\n" }, { "answer_id": 13877039, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 3, "selected": true, "text": "[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
248,821
<p>I committed a bunch of files (dozens of files in different folders) by accident. What is the easiest, cleanest (and safest!) way to 'undo' that commit without having to delete the files from my working directory?</p>
[ { "answer_id": 248850, "author": "jcoby", "author_id": 2884, "author_profile": "https://Stackoverflow.com/users/2884", "pm_score": 4, "selected": false, "text": "svn merge -r1123:1122 <url of your working copy>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
248,824
<p>I have a program that needs to run as a normal user most of the time, but once in a while I need to stop and start a service. How do I go about making a program that runs as a normal user most of the time but elevates into administrator mode for some function?</p>
[ { "answer_id": 304300, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 2, "selected": false, "text": "private void elevateCurrentProcess()\n{\n ProcessStartInfo startInfo = new ProcessStartInfo();\n startInfo.UseShellExecute = true;\n startInfo.WorkingDirectory = Environment.CurrentDirectory; \n startInfo.FileName = Application.ExecutablePath;\n startInfo.Verb = \"runas\";\n\n try\n {\n Process p = Process.Start(startInfo);\n }\n catch\n {\n // User didn't allow UAC\n return;\n }\n Application.Exit();\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22835/" ]
248,830
<p>Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.</p> <p>Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:</p> <pre><code>def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation </code></pre> <p>(Please don't care about inefficiency, this is only an example.)</p> <p>Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:</p> <pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation </code></pre> <p>This code does <em>not</em> work (the function behaves like an empty generator).</p> <p>Am I missing something? Is there a way to turn the above recursive algorithm into a generator <em>without replacing it with an iterative one</em>?</p>
[ { "answer_id": 248854, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 8, "selected": true, "text": "def getPermutations(string, prefix=\"\"):\n if len(string) == 1:\n yield prefix + string\n else:\n for i in xrange(len(string)):\n for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]):\n yield perm\n def getPermutations(string):\n if len(string) == 1:\n yield string\n else:\n for i in xrange(len(string)):\n for perm in getPermutations(string[:i] + string[i+1:]):\n yield string[i] + perm\n" }, { "answer_id": 248857, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": false, "text": "def getPermutations(string, prefix=\"\"):\n if len(string) == 1:\n yield prefix + string \n else:\n for i in range(len(string)):\n getPermutations(string[:i]+string[i+1:], prefix+string[i]) # <-----\n" }, { "answer_id": 252199, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": false, "text": "len(string) from types import GeneratorType\n\ndef flatten(*stack):\n stack = list(stack)\n while stack:\n try: x = stack[0].next()\n except StopIteration:\n stack.pop(0)\n continue\n if isinstance(x, GeneratorType): stack.insert(0, x)\n else: yield x\n\ndef _getPermutations(string, prefix=\"\"):\n if len(string) == 1: yield prefix + string\n else: yield (_getPermutations(string[:i]+string[i+1:], prefix+string[i])\n for i in range(len(string)))\n\ndef getPermutations(string): return flatten(_getPermutations(string))\n\nfor permutation in getPermutations(\"abcd\"): print permutation\n flatten yield yield yield from def getPermutations(string, prefix=\"\"):\n if len(string) == 1:\n yield prefix + string\n else:\n for i in range(len(string)):\n yield from getPermutations(string[:i]+string[i+1:], prefix+string[i])\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770/" ]
248,838
<p>I need to write an extension method on a byte[]. Is that possible?</p>
[ { "answer_id": 248843, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 1, "selected": false, "text": "byte[]" }, { "answer_id": 248866, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": true, "text": "public static class Extensions\n{\n public static void Method(this byte[] current)\n {\n\n }\n}\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
248,859
<p>I have a VBS script that currently writes to a logfile. This script can be kicked off my multiple simultaneous processes so now I'm worried about concurrency.</p> <p>I'm currently using <code>FileSystemObject</code> to open and write to this file. Does FSO support exclusive file access?</p>
[ { "answer_id": 387855, "author": "mrTomahawk", "author_id": 47621, "author_profile": "https://Stackoverflow.com/users/47621", "pm_score": 0, "selected": false, "text": "set objFile = objFSO.OpenTextFile(\"somefile.txt\",8,True)\nobjFSO.WriteLine \"jfdskfdkls\"\nobjFSO.Close\n'something something\nset objFile = objFSO.OpenTextFile(\"somefile.txt\",8,True)\nobjFSO.WriteLine \"gfdgfdgfd\"\nobjFSO.Close\n'something else\nset objFile = objFSO.OpenTextFile(\"somefile.txt\",8,True)\nobjFSO.WriteLine \"ddsgfgdfsgdfs\"\nobjFSO.Close\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
248,864
<p>I have a MySQL database table with a couple thousand rows. The table is setup like so:</p> <p><code>id | text</code></p> <p>The <code>id</code> column is an auto-incrementing integer, and the <code>text</code> column is a 200-character varchar.</p> <p>Say I have the following rows:</p> <p><code>3 | I think I'll have duck tonight</code></p> <p><code>4 | Maybe the chicken will be alright</code></p> <p><code>5 | I have a pet duck now, awesome!</code></p> <p><code>6 | I love duck</code></p> <p>Then the list I'm wanting to generate might be something like:</p> <ul> <li>3 occurrences of 'duck'</li> <li>3 occurrences of 'I'</li> <li>2 occurrences of 'have'</li> <li>1 occurrences of 'chicken'</li> <li>.etc .etc</li> </ul> <p>Plus, I'll probably want to maintain a list of substrings to ignore from the list, like 'I', 'will' and 'have. It's important to note that I do not know what people will post.</p> <p>I do not have a list of words that I want to monitor, I just want to find the most common substrings. I'll then filter out any erroneous substrings that are not interesting from the list manually by editing the query.</p> <p>Can anyone suggest the best way to do this? Thanks everyone!</p>
[ { "answer_id": 249366, "author": "rwired", "author_id": 17492, "author_profile": "https://Stackoverflow.com/users/17492", "pm_score": 3, "selected": true, "text": "myisam_ftdump -c yourtablename 1 >wordfreq.dump\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326176/" ]
248,900
<p>When I press the standard Ctrl + E, C (an other variants) in VS2008 whilst editing a CSS file, it says that command is not available. How do I setup a shortcut to apply a plain old /* */ comment to selected text in VS? Thanks</p>
[ { "answer_id": 249339, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 4, "selected": true, "text": "Imports System\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module CommentCSS\n Sub CommentCSS()\n Dim selection As TextSelection\n selection = DTE.ActiveDocument.Selection\n\n Dim selectedText As String\n selectedText = selection.Text\n\n If selectedText.Length > 0 Then\n selection.Text = \"/*\" + selectedText + \"*/\"\n End If\n End Sub\nEnd Module\n" }, { "answer_id": 1080342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Sub CommentCSS()\n DTE.ActiveDocument.Selection.StartOfLine(VsStartOfLineOptions.VsStartOfLineOptionsFirstText)\n DTE.ActiveDocument.Selection.Text = \"/*\"\n DTE.ActiveDocument.Selection.EndOfLine()\n DTE.ActiveDocument.Selection.Text = \"*/\"\nEnd Sub\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692/" ]
248,903
<p>Is there any way to determine if an object is a generic list? I'm not going to know the type of the list, I just know it's a list. How can I determine that?</p>
[ { "answer_id": 248915, "author": "Andrew Theken", "author_id": 32238, "author_profile": "https://Stackoverflow.com/users/32238", "pm_score": 2, "selected": false, "text": "if(yourList.GetType().IsGenericType)\n{\n var genericTypeParams = yourList.GetType().GetGenericArguments;\n //do something interesting with the types..\n}\n" }, { "answer_id": 248918, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 6, "selected": true, "text": "List<int> myList = new List<int>();\n\nConsole.Write(myList.GetType().IsGenericType && myList is IEnumerable);\n" }, { "answer_id": 248922, "author": "Nathan Baulch", "author_id": 8799, "author_profile": "https://Stackoverflow.com/users/8799", "pm_score": 3, "selected": false, "text": "static Type GetGenericCollectionItemType(Type type)\n{\n if (type.IsGenericType)\n {\n var args = type.GetGenericArguments();\n if (args.Length == 1 &&\n typeof(ICollection<>).MakeGenericType(args).IsAssignableFrom(type))\n {\n return args[0];\n }\n }\n return null;\n}\n class PersonCollection : List<Person> {}\n static Type GetGenericCollectionItemType(Type type)\n{\n return type.GetInterfaces()\n .Where(face => face.IsGenericType &&\n face.GetGenericTypeDefinition() == typeof(ICollection<>))\n .Select(face => face.GetGenericArguments()[0])\n .FirstOrDefault();\n}\n" }, { "answer_id": 250239, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "public class MyClass<T> : IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator()\n {\n return null;\n }\n}\n" }, { "answer_id": 35539113, "author": "Stanislav Trifan", "author_id": 1653988, "author_profile": "https://Stackoverflow.com/users/1653988", "pm_score": 2, "selected": false, "text": "private static bool IsList(object value)\n{\n var type = value.GetType();\n var targetType = typeof (IList<>);\n return type.GetInterfaces().Any(i => i.IsGenericType \n && i.GetGenericTypeDefinition() == targetType);\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137/" ]
248,911
<p>I have a single HW interface I want to use from two applications (processes) on the same workstation. The HW requires a single initialization call then either app uses the same function (in the same library) to do many transactions with the HW. </p> <p>So each app should act like this:</p> <pre><code>main() // I don't know if another app already init'ed the HW ret = hw_init_lock(non-blocking) if ret = OK // no one else has done this, I have to init_hw() else //someone else has already init'ed the HW, I gotta make sure it stays that way //as long as I'm alive increment_hw_init_ref_counter() hw_trans_lock(blocking) hw_trans() hw_trans_unlock() .... //exit app, uninit hw if we are last out ret = decrement_hw_init_ref_counter() if ret == 0 uninit_hw() exit(0) </code></pre> <p>What is the mechanism I can use in the lock and reference count calls that is shared between two applications? I'm thinking named pipes i.e. mkfifo(). </p>
[ { "answer_id": 249400, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 2, "selected": false, "text": "mutex_enter(m);\nwhile (! condition) {\n cond_wait(m, c); // drop mutex lock; wait on cv; reacquire mutex\n}\n//processing related to condition\nmutex_exit(m);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23961/" ]
248,923
<p>Solution<br/> -- WorkflowProject<br/> &nbsp;&nbsp;-- Workflow1<br/> &nbsp;&nbsp;-- Workflow2<br/> -- WebProject (WAP)<br/> &nbsp;&nbsp;-- App_Data<br/> &nbsp;&nbsp;&nbsp;&nbsp;-- MyDatabase.vdb3<br/> &nbsp;&nbsp;-- MyWebService.asmx<br/> &nbsp;&nbsp;-- Web.Config<br/></p> <p>Ok, so.. that's the basic "outline" of the project. The database, is stored in the website, and is a VistaDB database (this could also be an MSAccess or SQLite Database). In the website, I could code against the database. I might have |DataDirectory| in my connection string.</p> <p>The WORKFLOW project is separate from the Website. The MyWebService.asmx is a "stub" for calling the Workflow based web service. </p> <p><strong><em>How</strong> do I open the database in the website <strong>App_Data</strong> directory ? Right now, I have the value hardcoded (i.e., @"E:\datadirectory\database.vdb3"), but this is not preferred and would only work on my development machine.</em></p> <p>I can't even pass in the location of the database, since the webservice (the .asmx file) is only 1 line, and is stub code for getting the caller into the workflow. I'm really at a loss as how to proceed.</p> <p>Solution ? Best practices ? Links ?</p>
[ { "answer_id": 249400, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 2, "selected": false, "text": "mutex_enter(m);\nwhile (! condition) {\n cond_wait(m, c); // drop mutex lock; wait on cv; reacquire mutex\n}\n//processing related to condition\nmutex_exit(m);\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27472/" ]
248,938
<p>I am looking to parse a URL to obtain a collection of the querystring parameters in Java. To be clear, I need to parse a given URL(or string value of a URL object), not the URL from a servlet request. </p> <p>It looks as if the <code>javax.servlet.http.HttpUtils.parseQueryString</code> method would be the obvious choice, but it has been deprecated.</p> <p>Is there an alternative method that I am missing, or has it just been deprecated without an equivalent replacement/enhanced function?</p>
[ { "answer_id": 249774, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 0, "selected": false, "text": "java.net.URLDecoder#decodeURL(String,String)" }, { "answer_id": 249781, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 3, "selected": true, "text": "http://www.example.com?param1=value1&param2=value2&param1=value3\n" }, { "answer_id": 59140594, "author": "Richard", "author_id": 565319, "author_profile": "https://Stackoverflow.com/users/565319", "pm_score": 0, "selected": false, "text": "fun splitQuery(url: URL): Map<String, List<String?>> = url.query?.let {\n it.split(\"&\").map {\n it.split(\"=\").let {\n Pair(it[0], it.getOrNull(1))\n }\n }.groupBy({ it.first }, {\n it.second\n })\n } ?: emptyMap()\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14419/" ]
248,949
<p>We have a character LCD (www.cloverlcd.com/pdf/S6A0069.pdf) that we got to work in 8 bit mode. However, now we are trying to get it to work in 4 bit mode but it doesn't seem to be displaying anything. I think the function set instruction isn't been written. Can somebody please check if I am approaching this the right way? I'll post my 8 bit code (which is working) and my 4 bit code (which I'm trying to get to work)</p> <pre> //8 bit working COMPortC(0x3C); //function set Delay1KTCYx(10); COMPortC(0x0F); //Turn on display and configure cursor settings Delay1KTCYx(10); COMPortC(0x01); //clear display Delay1KTCYx(10); COMPortC(0x06); //increment mode and increment direction (entry mode set) Delay1KTCYx(10); COMPortC(0x02); //Return Home //4 bit COMPortC(0x20); //function set Delay1KTCYx(10); COMPortC(0x20); //function set Delay1KTCYx(10); COMPortC(0x80); //function set Delay1KTCYx(10); COMPortC(0x00); //Turn on display and configure cursor settings Delay1KTCYx(10); COMPortC(0xF0); //Turn on display and configure cursor settings Delay1KTCYx(10); </pre>
[ { "answer_id": 249541, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 1, "selected": false, "text": "COMPortCWithoutBusy(0x02); //function set first nibble \nDelay1KTCYx(10);\nCOMPortCWithoutBusy(0x02); //function set second nibble \nDelay1KTCYx(10);\nBusyEnable();\nDelay1KTCYx(10);\n...\n" }, { "answer_id": 799357, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "void initlcd(void)\n{\n delayms(20); // Wait for LCD to power up ( >15ms )\n RS=0; // Set RS low for instruction \n write4(3); // Set interface to 8 bits \n delayms(5); // Wait for LCD execute instruction ( >4.1ms )\n write4(3); // Set interface to 8 bits \n delayms(1); // Wait for LCD execute instruction ( >100us )\n write4(3); // Set interface to 8 bits \n delayms(5); // Wait for LCD execute instruction (At this point \n // we could actually start using the busy flag) \n write4(2); // Set the display to 4 bit interface \n delayms(5); // Wait for LCD execute instruction \n write8(0x28); // Set the display to two line and ???\n delayms(5); // Wait for LCD execute instruction \n write8(6); // ???\n delayms(5); // Wait for LCD execute instruction \n write8(1); // Clear the LCD\n delayms(5); // Wait for LCD execute instruction\n write8(0xf); // ???\n delayms(5); // Wait for LCD execute instruction\n return;\n}\n void write8(uns8 byte)\n{\n uns8 nibble;\n nibble = (byte & 0xf0) >> 4; // Rotate the high 4 bits (7-4) of byte into bits (3-0) of nibble\n write4(nibble); // Write the high 4 bits to the LCD\n nibble = byte & 0xf; // Copy the low four bits of byte into the low four bits of nibble\n write4(nibble); // Write the low 4 bits to the LCD\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
248,952
<p>Imagine that you are handed a new book everyday from an author. The book is a work in progress. He does not tell you what he has changed or added.</p> <p>Your job is to identify the changes and additions, and pass ONLY these along to the publisher (who does not have time to read the entire book everyday)</p> <p>For the purposes of this problem, the book is comprised of 1m lines of ascii text and growing (actually a MySQL backup file).</p> <p>My current idea is to make a secure hash (SHA256 for example) of each line (1k Chars) and store it on HD. Since the hash is only 32bytes the file is only 32MB.</p> <p>Then when we get the next file tomorrow, we go through it line by line, creating a new hash for each line and comparing it to the hash from the previous day.</p> <p>When the process is finished we overwrite the hash file ready for the next day.</p> <p>The comparison uses a binary search method of string compare ( > &lt; operands) This returns a result in an average of four iterations.</p> <p>I have not coded a btree index solution yet, but how would you tackle this?</p>
[ { "answer_id": 248995, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "diff" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
248,961
<p>I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code:</p> <pre><code> using (SqlCommand cmd = new SqlCommand(reportDataSource, new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year; cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start; cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end; cmd.Connection.Open(); DataSet dset = new DataSet(); new SqlDataAdapter(cmd).Fill(dset); this.gridDataSource.DataSource = dset.Tables[0]; } </code></pre> <p>This seems to work but is there any point in this since as far as I can tell I would still need to enclose this in a try catch block to catch unforseen errors e.g. sql server down. Am I missing something?</p> <p>As far as I can currently see it just stops me closing and disposing of cmd but there will be more lines of code due to the try catch still being needed.</p>
[ { "answer_id": 248984, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": true, "text": "using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))\nusing (SqlCommand cmd = new SqlCommand(reportDataSource, con))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Connection.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n }\n" }, { "answer_id": 248996, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 6, "selected": false, "text": "SqlConnection conn = null;\nSqlCommand cmd = null;\n\ntry\n{\n conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString)\n cmd = new SqlCommand(reportDataSource, conn);\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n\n conn.Open(); //opens connection\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n}\ncatch(Exception ex)\n{\n Logger.Log(ex);\n throw;\n}\nfinally\n{\n if(conn != null)\n conn.Dispose();\n\n if(cmd != null)\n cmd.Dispose();\n}\n SqlConnection conn = null;\nSqlCommand cmd = null;\n\nusing(conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString),\n cmd = new SqlCommand(reportDataSource, conn)\n{\n conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString);\n cmd = new SqlCommand(reportDataSource, conn);\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n}\ncatch(Exception ex)\n{\n Logger.Log(ex);\n throw;\n}\n" }, { "answer_id": 249139, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "using (MyDisposable blah = new MyDisposable())\n{\n int.Parse(\"!\"); // <- calls \"Dispose\" after the error.\n\n return; // <-- calls Dispose before returning.\n}\n" }, { "answer_id": 249176, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 3, "selected": false, "text": "using (SqlCommand cmd = new SqlCommand(...))\n{\n try\n {\n /* call stored procedure */\n }\n catch (SqlException ex)\n {\n /* handles the exception. does not rethrow the exception */\n }\n}\n SqlCommand cmd = new SqlCommand(...)\ntry\n{\n /* call stored procedure */\n}\ncatch (SqlException ex)\n{\n /* handles the exception and does not ignore it */\n}\nfinally\n{\n if (cmd!=null) cmd.Dispose();\n}\n" }, { "answer_id": 249242, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "using try catch finally using try finally IDisposable try finally Dispose using using using" }, { "answer_id": 3471218, "author": "John Saunders", "author_id": 76337, "author_profile": "https://Stackoverflow.com/users/76337", "pm_score": 0, "selected": false, "text": "SqlDataAdapter using using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))\nusing (SqlCommand cmd = new SqlCommand(reportDataSource, con))\n{\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n con.Open();\n\n DataSet dset = new DataSet();\n using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))\n {\n adapter.Fill(dset);\n }\n this.gridDataSource.DataSource = dset.Tables[0];\n}\n" }, { "answer_id": 6432498, "author": "Rick", "author_id": 809328, "author_profile": "https://Stackoverflow.com/users/809328", "pm_score": 2, "selected": false, "text": "using (...MyDisposableObj...)\n{\n\n ... use MyDisposableObj ...\n\ncatch (exception)\n\n ... handle exception ...\n\n}\n\nit could even have an optional \"finally\" clause to cleanup anything other than the \"MyDisposableObj\" allocated at the beginning of the \"using\" statement... like:\n\nusing (...MyDisposableObj...)\n{\n\n ... use MyDisposableObj ...\n ... open a file or db connection ...\n\ncatch (exception)\n\n ... handle exception ...\n\nfinally\n\n ... close the file or db connection ...\n\n}\n MyDisposableObj using" }, { "answer_id": 31089141, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 0, "selected": false, "text": "using (SqlConnection conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))\nusing (SqlCommand cmd = new SqlCommand(reportDataSource, conn))\n{\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Connection.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n}\n try\n{\n using (SqlConnection conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))\n using (SqlCommand cmd = new SqlCommand(reportDataSource, conn))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Connection.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n }\n}\ncatch (RelevantException ex)\n{\n // ...handling...\n}\n conn cmd using SqlConnection conn = null;\nSqlCommand cmd = null;\ntry\n{\n conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString);\n cmd = new SqlCommand(reportDataSource, conn);\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Connection.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n}\ncatch (RelevantException ex)\n{\n // ...handling...\n}\nfinally\n{\n if (cmd != null)\n {\n try\n {\n cmd.Dispose();\n }\n catch { }\n cmd = null;\n }\n if (conn != null)\n {\n try\n {\n conn.Dispose();\n }\n catch { }\n conn = null;\n }\n}\n// And note that `cmd` and `conn` are still in scope here, even though they're useless\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
248,973
<p>I'd like to stick a class down in my folder hierarchy. The scenario is too trivial to warrant it's own project or separate website. However, I hate to clutter my top-level App_Code with something that's used by a tiny corner of the site.</p> <p>Is there a way in web.config to include another file or folder in the compilation process?</p>
[ { "answer_id": 249005, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 1, "selected": true, "text": "<configuration>\n <system.web>\n <compilation>\n <assemblies>\n <add assembly=\"<AssemblyName>, Version=<Version>, Culture=<Culture>, PublicKeyToken=<PublicKeyToken>\"/>\n </assemblies>\n </compilation>\n </system.web>\n</configuration>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
248,982
<p>I have an app which could benefit from the user being able to choose to set an image as the wallpaper (the background image on the "slide to unlock" screen). </p> <p>Is there a way for non-jailbreak third-party apps to do this? A search for "wallpaper" in the iPhone documentation returns nothing. </p>
[ { "answer_id": 249005, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 1, "selected": true, "text": "<configuration>\n <system.web>\n <compilation>\n <assemblies>\n <add assembly=\"<AssemblyName>, Version=<Version>, Culture=<Culture>, PublicKeyToken=<PublicKeyToken>\"/>\n </assemblies>\n </compilation>\n </system.web>\n</configuration>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27951/" ]
248,983
<p>I have databound a listbox to a simple custom object collection. Next, I added a button to remove the selected item from the object collection. The problem is that when certain items are removed and the listbox is showing the vertical scroll bar, the scrollbar appears to reset to a new position, although what I really think is happening is that the control is repainting.</p> <p>The folowing code sample demonstrates the problem. Add this code to a form, making sure that the vertical scrollbar appears. Select an item in the middle of the collection so that the scrollbar is centered and press the remove button. When the control repaints, the items and scrollbar are in a different position. I would like for the listbox to behave as it would with non-databound items. Am I better off not using databinding, or is there a solution that allows me to keep the contol bound?</p> <p>Thanks.</p> <pre><code>public partial class Form1 : Form { private BindingList&lt;ItemData&gt; m_bList = new BindingList&lt;ItemData&gt;(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { for (int i = 0; i &lt; 50; i++) { m_bList.Add(new ItemData("Name " + i.ToString(), i)); } this.listBox1.DisplayMember = "Name"; this.listBox1.DataSource = m_bList; } private void btnRemove_Click(object sender, EventArgs e) { m_bList.Remove(listBox1.SelectedItem as ItemData); } } public class ItemData { public string Name { get; set; } public int Position { get; set; } public ItemData(string name, int position) { Name = name; Position = position; } } </code></pre>
[ { "answer_id": 249076, "author": "bioskope", "author_id": 29414, "author_profile": "https://Stackoverflow.com/users/29414", "pm_score": 0, "selected": false, "text": " private void btnRemove_Click(object sender, EventArgs e)\n {\n int s = listBox1.SelectedIndex;\n m_bList.Remove(listBox1.SelectedItem as ItemData);\n listBox1.Refresh();\n listBox1.SelectedIndex = s;\n }\n" }, { "answer_id": 253109, "author": "Lee", "author_id": 13943, "author_profile": "https://Stackoverflow.com/users/13943", "pm_score": 2, "selected": false, "text": " private void btnRemove_Click(object sender,EventArgs e)\n {\n int topIndex = listBox1.TopIndex;\n\n m_bList.Remove(listBox1.SelectedItem as ItemData);\n\n if(listBox1.Items.Count>topIndex)\n listBox1.TopIndex = topIndex;\n }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
248,985
<p>I'm writing an application that does async loading of images onto the screen. I have it set up to be NOT concurrent (that is, it spawns a thread and executes them one at a time), so I've only overridden the <code>[NSOperation main]</code> function in my NSOperation subclass. </p> <p>Anyway, so when I add all of these operations, I want to be able later to access the queued operations to change their priorities. Unfortunately, whenever I call <code>-[NSOperationQueue operations]</code>, all I get back is an empty array. The best part is that after putting in some console print statements, threads are still in the queue and executing (indicated by prints) despite the array being empty! </p> <p>What gives? I also took a look at theadcount just to make sure they're all not executing at once and that does not appear to be the case. </p> <p>Any ideas? Pulling my hair out on this one.</p> <p>EDIT: Also worth mentioning that the same code provides a full array when run in the simulator :(</p>
[ { "answer_id": 608484, "author": "Dave Lee", "author_id": 73429, "author_profile": "https://Stackoverflow.com/users/73429", "pm_score": 3, "selected": false, "text": "-operations [self->data->lock lock];\nNSString* copy = [[self->data->operations copy] autorelease];\n[self->data->lock unlock];\nreturn copy;\n -autorelease nil data _NSOperationQueueData NSRecursiveLock* lock;\nNSArray* operations;\n -operations NSOperationQueue [super operations] nil #if TARGET_OS_IPHONE\n\n#import <objc/runtime.h>\n\n@interface _DLOperationQueueData : NSObject {\n@public\n id lock; // <NSLocking>\n NSArray* operations;\n}\n@end\n@implementation _DLOperationQueueData; @end\n\n@interface _DLOperationQueueFix : NSObject {\n@public\n _DLOperationQueueData* data;\n}\n@end\n@implementation _DLOperationQueueFix; @end\n\n#endif\n\n\n@implementation DLOperationQueue\n\n#if TARGET_OS_IPHONE\n\n-(NSArray*) operations\n{\n NSArray* operations = [super operations];\n if (operations != nil) {\n return operations;\n }\n\n _DLOperationQueueFix* fix = (_DLOperationQueueFix*) self;\n _DLOperationQueueData* data = fix->data;\n\n if (strcmp(class_getName([data class]), \"_NSOperationQueueData\") != 0) {\n // this hack knows only the structure of _NSOperationQueueData\n // anything else, bail\n return operations;\n }\n if ([data->lock conformsToProtocol: @protocol(NSLocking)] == NO) {\n return operations; // not a lock, bail\n }\n\n [data->lock lock];\n operations = [[data->operations copy] autorelease];\n [data->lock unlock];\n return operations; // you forgot something, Apple.\n}\n\n#endif\n\n@end\n @interface DLOperationQueue : NSOperationQueue {}\n#if TARGET_OS_IPHONE\n-(NSArray*) operations;\n#endif\n@end\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28019/" ]
248,989
<p>I have some code that raises <code>PropertyChanged</code> events and I would like to be able to unit test that the events are being raised correctly.</p> <p>The code that is raising the events is like</p> <pre><code>public class MyClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } public string MyProperty { set { if (_myProperty != value) { _myProperty = value; NotifyPropertyChanged("MyProperty"); } } } } </code></pre> <p>I get a nice green test from the following code in my unit tests, that uses delegates:</p> <pre><code>[TestMethod] public void Test_ThatMyEventIsRaised() { string actual = null; MyClass myClass = new MyClass(); myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { actual = e.PropertyName; }; myClass.MyProperty = "testing"; Assert.IsNotNull(actual); Assert.AreEqual("MyProperty", actual); } </code></pre> <p>However, if I then try and chain the setting of properties together like so:</p> <pre><code>public string MyProperty { set { if (_myProperty != value) { _myProperty = value; NotifyPropertyChanged("MyProperty"); MyOtherProperty = "SomeValue"; } } } public string MyOtherProperty { set { if (_myOtherProperty != value) { _myOtherProperty = value; NotifyPropertyChanged("MyOtherProperty"); } } } </code></pre> <p>My test for the event fails - the event that it captures is the event for the MyOtherProperty.</p> <p>I'm pretty sure the event fires, my UI reacts like it does, but my delegate only captures the last event to fire.</p> <p>So I'm wondering:<br> 1. Is my method of testing events correct?<br> 2. Is my method of raising <em>chained</em> events correct? </p>
[ { "answer_id": 249042, "author": "Andrew Stapleton", "author_id": 28506, "author_profile": "https://Stackoverflow.com/users/28506", "pm_score": 9, "selected": true, "text": "[TestMethod]\npublic void Test_ThatMyEventIsRaised()\n{\n List<string> receivedEvents = new List<string>();\n MyClass myClass = new MyClass();\n\n myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)\n {\n receivedEvents.Add(e.PropertyName);\n };\n\n myClass.MyProperty = \"testing\";\n Assert.AreEqual(2, receivedEvents.Count);\n Assert.AreEqual(\"MyProperty\", receivedEvents[0]);\n Assert.AreEqual(\"MyOtherProperty\", receivedEvents[1]);\n}\n" }, { "answer_id": 2698702, "author": "Tim Lloyd", "author_id": 189516, "author_profile": "https://Stackoverflow.com/users/189516", "pm_score": 5, "selected": false, "text": "var publisher = new PropertyChangedEventPublisher();\n\nAction test = () =>\n{\n publisher.X = 1;\n publisher.Y = 2;\n};\n\nvar expectedSequence = new[] { \"X\", \"Y\" };\n\nEventMonitor.Assert(test, publisher, expectedSequence);\n" }, { "answer_id": 4370949, "author": "Damir Arh", "author_id": 197913, "author_profile": "https://Stackoverflow.com/users/197913", "pm_score": 3, "selected": false, "text": "[TestMethod]\npublic void Test_ThatMyEventIsRaised()\n{\n Dictionary<string, int> receivedEvents = new Dictionary<string, int>();\n MyClass myClass = new MyClass();\n\n myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)\n {\n if (receivedEvents.ContainsKey(e.PropertyName))\n receivedEvents[e.PropertyName]++;\n else\n receivedEvents.Add(e.PropertyName, 1);\n };\n\n myClass.MyProperty = \"testing\";\n Assert.IsTrue(receivedEvents.ContainsKey(\"MyProperty\"));\n Assert.AreEqual(1, receivedEvents[\"MyProperty\"]);\n Assert.IsTrue(receivedEvents.ContainsKey(\"MyOtherProperty\"));\n Assert.AreEqual(1, receivedEvents[\"MyOtherProperty\"]);\n}\n" }, { "answer_id": 18216715, "author": "Samuel", "author_id": 2416394, "author_profile": "https://Stackoverflow.com/users/2416394", "pm_score": 4, "selected": false, "text": "[Test]\npublic void Test_Notify_Property_Changed_Fired()\n{\n var p = new Project();\n\n var tracer = new INCPTracer();\n\n // One event\n tracer.With(p).CheckThat(() => p.Active = true).RaisedEvent(() => p.Active);\n\n // Two events in exact order\n tracer.With(p).CheckThat(() => p.Path = \"test\").RaisedEvent(() => p.Path).RaisedEvent(() => p.Active);\n}\n" }, { "answer_id": 33972226, "author": "nico", "author_id": 5615318, "author_profile": "https://Stackoverflow.com/users/5615318", "pm_score": 1, "selected": false, "text": "private void AssertPropertyChanged<T>(T instance, Action<T> actionPropertySetter, string expectedPropertyName) where T : INotifyPropertyChanged\n {\n string actual = null;\n instance.PropertyChanged += delegate (object sender, PropertyChangedEventArgs e)\n {\n actual = e.PropertyName;\n };\n actionPropertySetter.Invoke(instance);\n Assert.IsNotNull(actual);\n Assert.AreEqual(propertyName, actual);\n }\n [TestMethod()]\npublic void Event_UserName_PropertyChangedWillBeFired()\n{\n var user = new User();\n AssertPropertyChanged(user, (x) => x.UserName = \"Bob\", \"UserName\");\n}\n" }, { "answer_id": 34786740, "author": "WhileTrueSleep", "author_id": 2294294, "author_profile": "https://Stackoverflow.com/users/2294294", "pm_score": 1, "selected": false, "text": "using System.ComponentModel;\nusing System.Linq;\n\n/// <summary>\n/// Check if every property respons to INotifyPropertyChanged with the correct property name\n/// </summary>\npublic static class NotificationTester\n {\n public static object GetPropertyValue(object src, string propName)\n {\n return src.GetType().GetProperty(propName).GetValue(src, null);\n }\n\n public static bool Verify<T>(T inputClass) where T : INotifyPropertyChanged\n {\n var properties = inputClass.GetType().GetProperties().Where(x => x.CanWrite);\n var index = 0;\n\n var matchedName = 0;\n inputClass.PropertyChanged += (o, e) =>\n {\n if (properties.ElementAt(index).Name == e.PropertyName)\n {\n matchedName++;\n }\n\n index++;\n };\n\n foreach (var item in properties)\n { \n // use setter of property\n item.SetValue(inputClass, GetPropertyValue(inputClass, item.Name));\n }\n\n return matchedName == properties.Count();\n }\n }\n [TestMethod]\npublic void EveryWriteablePropertyImplementsINotifyPropertyChangedCorrect()\n{\n var viewModel = new TestMyClassWithINotifyPropertyChangedInterface();\n Assert.AreEqual(true, NotificationTester.Verify(viewModel));\n}\n using System.ComponentModel;\n\npublic class TestMyClassWithINotifyPropertyChangedInterface : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected void NotifyPropertyChanged(string name)\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(name));\n }\n }\n\n private int id;\n\n public int Id\n {\n get { return id; }\n set { id = value;\n NotifyPropertyChanged(\"Id\");\n }\n }\n}\n" }, { "answer_id": 42299063, "author": "Mr.B", "author_id": 1002613, "author_profile": "https://Stackoverflow.com/users/1002613", "pm_score": 0, "selected": false, "text": "public static class NotifyPropertyChangedExtensions\n{\n private static bool _isFired = false;\n private static string _propertyName;\n\n public static void NotifyPropertyChangedVerificationSettingUp(this INotifyPropertyChanged notifyPropertyChanged,\n string propertyName)\n {\n _isFired = false;\n _propertyName = propertyName;\n notifyPropertyChanged.PropertyChanged += OnPropertyChanged;\n }\n\n private static void OnPropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == _propertyName)\n {\n _isFired = true;\n }\n }\n\n public static bool IsNotifyPropertyChangedFired(this INotifyPropertyChanged notifyPropertyChanged)\n {\n _propertyName = null;\n notifyPropertyChanged.PropertyChanged -= OnPropertyChanged;\n return _isFired;\n }\n}\n [Fact]\n public void FilesRenameViewModel_Rename_Apply_Execute_Verify_NotifyPropertyChanged_If_Succeeded_Through_Extension_Test()\n {\n // Arrange\n _filesViewModel.FolderPath = ConstFolderFakeName;\n _filesViewModel.OldNameToReplace = \"Testing\";\n //After the command's execution OnPropertyChanged for _filesViewModel.AllFilesFiltered should be raised\n _filesViewModel.NotifyPropertyChangedVerificationSettingUp(nameof(_filesViewModel.AllFilesFiltered));\n //Act\n _filesViewModel.ApplyRenamingCommand.Execute(null);\n // Assert\n Assert.True(_filesViewModel.IsNotifyPropertyChangedFired());\n\n }\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2660/" ]
248,990
<p>I have a table like as follows:</p> <pre> SoftwareName Count Country Project 15 Canada Visio 12 Canada Project 10 USA Visio 5 USA </pre> <p>How do I query it to give me a summary like...</p> <pre> SoftwareName Canada USA Total Project 15 10 25 Visio 12 5 17 </pre> <p>How to do in T-SQL?</p>
[ { "answer_id": 249020, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "SELECT SoftwareName, \n SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada,\n SUM( CASE Country WHEN 'USA' THEN [Count] ELSE 0 END ) AS USA,\n SUM( [Count] ) AS Total\nFROM [Table] \nGROUP BY SoftwareName;\n" }, { "answer_id": 249272, "author": "MarlonRibunal", "author_id": 10385, "author_profile": "https://Stackoverflow.com/users/10385", "pm_score": 2, "selected": false, "text": "SELECT Softwarename, Canada, USA, Canada + USA As TOTAL from SoftwareDemo \nPIVOT \n (\n SUM([Count])\n FOR Country\n IN (Canada, USA)\n ) AS x\n\n\nSoftwarename Canada USA TOTAL\n-------------------------------------------------- ----------- ----------- -----------\nProject 15 10 25\nVisio 12 5 17\n\n(2 row(s) affected)\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31026/" ]
248,998
<p>This is really weird... When I open the following simple HTML document in Internet Explorer 7.0.5730.11 (on Windows Server 2003 Web Edition SP2)</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;p&gt;+&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>it shows me a totally blank page. FWIW, this is just a trivial "repro" sample. In real HTML documents, I observed other, even more bizzarre effects caused by presense of the "plus" character that follows a tag.</p> <p><strong>NB:</strong> The problem appears to be extremely ittermittent. Most of the time it does work properly (i.e. displays the "plus" character), and I still can't find any way to reproduce this problem at will.</p> <p>Some additional details based on recent comments:</p> <ul> <li><p>There was no server involved. I was opening a file on disk (i.e. used <strong>file://</strong> protocol).</p></li> <li><p>The file did not contain anything except five lines shown above. No document type declarations, no character encodings, no nothings.</p></li> </ul> <p>Looks like a bug in IE. Did anybody encounter the same or similar problem?</p> <p><strong>NB:</strong> I appreciate all the responses received so far, but neither of respondednts encountered this problem. Something tells me that 99.(9)% of StackOverflow audience will not be able to reproduce it. :-)</p>
[ { "answer_id": 249040, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 1, "selected": false, "text": "<html>\n <body>\n <p>&#43;</p>\n </body>\n</html>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31415/" ]
249,009
<p>I mean other than using it when required for functions, classes, if, while, switch, try-catch.</p> <p>I didn't know that it could be done like <a href="https://stackoverflow.com/questions/241088/what-do-curly-braces-by-themselves-mean-in-java">this until I saw this SO question</a>.</p> <p>In the above link, Eli mentioned that "They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up."</p> <p>What other uses are there besides those mentioned? </p> <p>Is it a good idea to use curly braces to limit the scope of your variables and expand the scope only if required (working on a "need-to-access" basis)? Or is it actually silly? </p> <p>How about using scopes just so that you can use the same variable names in different scopes but in the same bigger scope? Or is it a better practise to reuse the same variable (if you want to use the same variable name) and save on deallocating and allocating (I think some compilers can optimise on this?)? Or is it better to use different variable names altogether?</p>
[ { "answer_id": 249014, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 7, "selected": true, "text": "void myfunction()\n{\n {\n // Open serial port\n SerialPort port(\"COM1\", 9600);\n port.doTransfer(data);\n } // Serial port gets closed here.\n\n for(int i = 0; i < data.size(); i++)\n doProcessData(data[i]);\n etc...\n}\n" }, { "answer_id": 249029, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 4, "selected": false, "text": "switch (x) {\n case 0:\n int i = 0;\n foo(i);\n break;\n case 1:\n int i = 1;\n bar(i);\n break;\n}\n switch (x) {\n case 0:\n {\n int i = 0;\n foo(i);\n }\n break;\n case 1:\n {\n int i = 1;\n bar(i);\n }\n break;\n}\n" }, { "answer_id": 250161, "author": "Marcin", "author_id": 22724, "author_profile": "https://Stackoverflow.com/users/22724", "pm_score": 4, "selected": false, "text": "void MyClass::Somefun()\n{\n //do some stuff\n {\n // example imlementation that has a mutex passed into a lock object:\n scopedMutex lockObject(m_mutex); \n\n // protected code here\n\n } // mutex is unlocked here\n // more code here\n}\n" }, { "answer_id": 250187, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 4, "selected": false, "text": "#if defined( UNIX )\n if( some unix-specific condition )\n#endif\n {\n // This code should always run on Windows but \n // only if the above condition holds on unix\n }\n #if defined( UNIX )\n if( some unix-specific condition ) {\n#endif\n // This code should always run on Windows but \n // only if the above condition holds on unix\n#if defined( UNIX )\n }\n#endif\n" }, { "answer_id": 255538, "author": "piyo", "author_id": 28524, "author_profile": "https://Stackoverflow.com/users/28524", "pm_score": 1, "selected": false, "text": "/// c++ code\n/// references to boost::test\nBOOST_TEST_CASE( curly_brace )\n{\n // init\n MyClass instance_to_test( \"initial\", TestCase::STUFF ); {\n instance_to_test.permutate(42u);\n instance_to_test.rotate_left_face();\n instance_to_test.top_gun();\n }\n { // test check\n const uint8_t kEXP_FAP_BOOST = 240u;\n BOOST_CHECK_EQUAL( instance_to_test.get_fap_boost(), kEXP_FAP_BOOST);\n }\n}\n" }, { "answer_id": 256060, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 2, "selected": false, "text": "// yuk!\nsome code\n{\nscoped code\n}\nmore code\n\n// also yuk!\nsome code\n/* do xyz */ {\n scoped code\n }\nsome more code\n\n// this I like\nsome code\nDoXyz: {\n scoped code\n }\nsome more code\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646/" ]
249,010
<p>cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;</p> <p>in this method</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; </code></pre> <p>but I can only see it when I select that cell otherwise it's not visible.and it work perfectly when background is white. I am sure that I need to set a property, but I don't know which property I need to change to make this thing work.</p> <p>thanks in advance.</p> <p>cheers.</p>
[ { "answer_id": 2598410, "author": "John Dell'Aera", "author_id": 311711, "author_profile": "https://Stackoverflow.com/users/311711", "pm_score": 1, "selected": false, "text": "@property (nonatomic,retain) UILabel *backgroundLabel;\n\nUILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];\nlabel.backgroundColor = [UIColor orangeColor]; \nself.backgroundLabel = label;\n[self.contentView addSubview:label];\n[label release];\n\nCGRect labelRect = CGRectOffset(contentRect,0, 0);\nlabelRect.size.height = contentRect.size.height - 1; // show white line\nlabelRect.size.width = contentRect.size.width + 50; // cover arrow tip background\nbackgroundLabel.frame = labelRect; \nbackgroundLabel.highlightedTextColor = [UIColor whiteColor];\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ]
249,022
<p>I have an method which save files to the internet, it works but just slow. Then I'd like to make the user interface more smooth, so I create an NSThread to handle the slow task. </p> <p>I am seeing a list of errors like:</p> <pre><code>_NSAutoreleaseNoPool(): Object 0x18a140 of class NSCFString autoreleased with no pool in place - just leaking </code></pre> <p>Without NSThread, I call the method like:</p> <pre><code>[self save:self.savedImg]; </code></pre> <p>And I used the following to use NSThread to call the method:</p> <pre><code>NSThread* thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(save:) object:self.savedImg]; [thread1 start]; </code></pre> <p>Thanks. </p>
[ { "answer_id": 249083, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 3, "selected": false, "text": "- (void) save:(id)arg {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n\n //Existing code\n\n [pool drain];\n}\n" }, { "answer_id": 249224, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 2, "selected": false, "text": "BOOL done = NO;\n\nNSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n[NSRunLoop currentRunLoop];\n\n// Start the HTTP connection here. When it's completed,\n// you could stop the run loop and then the thread will end.\n\ndo {\n SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);\n if ((result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished)) {\n done = YES;\n }\n} while (!done);\n\n[pool release];\n" }, { "answer_id": 249250, "author": "keremk", "author_id": 29475, "author_profile": "https://Stackoverflow.com/users/29475", "pm_score": 5, "selected": true, "text": "+ sendSynchronousRequest:returningResponse:error:\n - (void) beginSaving {\n // This is your UI thread. Call this API from your UI.\n // Below spins of another thread for the selector \"save\"\n [NSThread detachNewThreadSelector:@selector(save:) toTarget:self withObject:nil]; \n\n}\n\n- (void) save {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; \n\n // ... calculate your post request...\n // Initialize your NSUrlResponse and NSError\n\n NSUrlConnection *conn = [NSUrlConnection sendSyncronousRequest:postRequest:&response error:&error];\n // Above statement blocks until you get the response, but you are in another thread so you \n // are not blocking UI. \n\n // I am assuming you have a delegate with selector saveCommitted to be called back on the\n // UI thread.\n if ( [delegate_ respondsToSelector:@selector(saveCommitted)] ) {\n // Make sure you are calling back your UI on the UI thread as below:\n [delegate_ performSelectorOnMainThread:@selector(saveCommitted) withObject:nil waitUntilDone:NO];\n }\n\n [pool release];\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32096/" ]
249,027
<p>I would like to implement a command line interface for a Java application. This wouldn't be too difficult to do, except I would like the command line program to affect the state of another Java GUI program. So for example, I could type:</p> <pre><code>java CliMain arg1 arg2 </code></pre> <p>And another running GUI instance would perform an appropriate action.</p> <p>What is the easiest way of implementing something like this?</p>
[ { "answer_id": 249036, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "localhost" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
249,047
<p>Does anyone know a good SMTP/IMAP server library for C#?</p> <p>I only found some long abandoned projects.</p> <hr> <p>Only <strong>SERVER SIDE</strong> libraries, please no more posts about client libs.</p> <p>Thanks, Fionn</p>
[ { "answer_id": 249052, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": -1, "selected": false, "text": "System.Net.Mail SharpMimeTools" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21566/" ]
249,066
<p>I just want to know how to validate (or clean) user input in ASP.NET MVC so that an HttpRequestValidationException will not be thrown regardless of the values submitted. For example, with a text input, if the user inputs <code>&lt;BR/&gt;</code>, it will cause an exception and the Yellow Screen of Death will be shown. I don't want that. I want to catch the exception and to make visible an user friendly error in the current view, preferably with the controls loaded with the same values submitted. </p> <p>I have found this <a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="noreferrer">http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html</a>, but it is useless for my purpose. Also, I have found this <a href="http://msdn.microsoft.com/en-us/library/aa973813.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa973813.aspx</a> and tried to put inside a model binder but I couldn't make to work.</p>
[ { "answer_id": 552107, "author": "user66787", "author_id": 66787, "author_profile": "https://Stackoverflow.com/users/66787", "pm_score": 6, "selected": true, "text": "[ValidateInput(false)]\npublic ActionResult create()\n{\n // ...method body\n}\n <system.web><httpRuntime requestValidationMode=\"2.0\" /></system.web>" }, { "answer_id": 2380618, "author": "JoshNaro", "author_id": 7423, "author_profile": "https://Stackoverflow.com/users/7423", "pm_score": 2, "selected": false, "text": "[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]\npublic class ExceptionHandlerAttribute : FilterAttribute, IExceptionFilter {\n\nprivate HandleErrorAttribute attribute = new HandleErrorAttribute();\n\npublic ExceptionHandlerAttribute() {\n this.ExceptionType = typeof(Exception);\n this.Order = 1;\n}\n\npublic string View {\n get {\n return attribute.View;\n }\n set {\n attribute.View = value;\n }\n}\n\npublic Type ExceptionType {\n get {\n return attribute.ExceptionType;\n }\n set {\n attribute.ExceptionType = value;\n }\n}\n\npublic void OnException(ExceptionContext filterContext) {\n if (this.ExceptionType.IsInstanceOfType(filterContext.Exception)) {\n string controller = (string)filterContext.RouteData.Values[\"controller\"];\n string action = (string)filterContext.RouteData.Values[\"action\"];\n if (controller == null)\n controller = String.Empty;\n\n if (action == null)\n action = String.Empty;\n\n HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controller, action);\n ViewResult result = new ViewResult();\n result.ViewName = this.View;\n result.MasterName = String.Empty;\n result.ViewData = new ViewDataDictionary<HandleErrorInfo>(model);\n\n result.TempData = filterContext.Controller.TempData;\n filterContext.Result = result;\n\n filterContext.ExceptionHandled = true;\n filterContext.HttpContext.Response.Clear();\n filterContext.HttpContext.Response.StatusCode = 500;\n }\n}\n" }, { "answer_id": 4959927, "author": "Kevin Southworth", "author_id": 422176, "author_profile": "https://Stackoverflow.com/users/422176", "pm_score": 4, "selected": false, "text": "[AllowHtml] Sanitizer.GetSafeHtmlFragment(mymodel.Description) [AllowHtml]" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32173/" ]
249,074
<p>I'm sure there are a million posts about this out there, but surprisingly I'm having trouble finding something. </p> <p>I have a simple script where I want to set the onClick handler for an <code>&lt;A&gt;</code> link on initialization of the page.</p> <p>When I run this I <strong>immediately</strong> get a 'foo' alert box where I expected to only get an alert when I click on the link.</p> <p>What stupid thing am I doing wrong? (I've tried click= and onClick=)...</p> <pre><code>&lt;script language="javascript"&gt; function init(){ document.getElementById("foo").click = new function() { alert('foo'); }; } &lt;/script&gt; &lt;body onload="init()"&gt; &lt;a id="foo" href=#&gt;Click to run foo&lt;/a&gt; &lt;/body&gt; </code></pre> <hr> <p><strong>Edit:</strong> I changed my accepted answer to a jQuery answer. The answer by '<a href="https://stackoverflow.com/questions/249074/how-to-change-onclick-handler-dynamically/249093#249093">Már Örlygsson</a>' is technically the correct answer to my original question (<code>click</code> should be <code>onclick</code> and <code>new</code> should be removed) but I <strong>strongly discourage</strong> anyone from using 'document.getElementById(...) directly in their code - and to use <a href="http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery" rel="noreferrer">jQuery</a> instead.</p>
[ { "answer_id": 249084, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": "document.getElementById(\"foo\").onclick = function (){alert('foo');};\n" }, { "answer_id": 249091, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 6, "selected": true, "text": "$('#foo').click(function() { alert('foo'); });\n $('#foo').click(function() { alert('foo'); return false; });\n" }, { "answer_id": 249093, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 5, "selected": false, "text": ".onclick document.getElementById(\"foo\").onclick = function () {\n alert('foo'); // do your stuff\n return false; // <-- to suppress the default link behaviour\n};\n" }, { "answer_id": 249504, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "document.getElementById(\"foo\").onclick = function (event){alert('foo');};\n $('#foo').click(function(event) { alert('foo'); }\n" }, { "answer_id": 724160, "author": "blak3r", "author_id": 67268, "author_profile": "https://Stackoverflow.com/users/67268", "pm_score": 1, "selected": false, "text": "<script>\n YAHOO.util.Event.onDOMReady(function() { \n document.getElementById(\"foo\").onclick = function (){alert('foo');};\n });\n</script>\n" }, { "answer_id": 1953270, "author": "Selin Ebeci", "author_id": 237657, "author_profile": "https://Stackoverflow.com/users/237657", "pm_score": 4, "selected": false, "text": "var submitButton = document.getElementById('submitButton');\nsubmitButton.setAttribute('onclick', 'alert(\"hello\");');\n" }, { "answer_id": 2453957, "author": "Web Development Guy", "author_id": 294707, "author_profile": "https://Stackoverflow.com/users/294707", "pm_score": 0, "selected": false, "text": "<script>\n YAHOO.util.Event.onDOMReady(function() { \n Dom.get(\"foo\").onclick = function (){alert('foo');};\n });\n</script>\n" }, { "answer_id": 5920918, "author": "yuttadhammo", "author_id": 560092, "author_profile": "https://Stackoverflow.com/users/560092", "pm_score": 4, "selected": false, "text": "document.getElementById(\"space1\").onclick = new Function(\"lrgWithInfo('\"+myVar+\"')\");\n document.getElementById(\"space1\").onclick = new Function(\"lrgWithInfo('13')\");\n" }, { "answer_id": 10019638, "author": "lamarant", "author_id": 613536, "author_profile": "https://Stackoverflow.com/users/613536", "pm_score": 0, "selected": false, "text": "$(element).unbind().bind( 'click' , function(){ alert('!') } ); \n" }, { "answer_id": 10744345, "author": "Steven Lu", "author_id": 340947, "author_profile": "https://Stackoverflow.com/users/340947", "pm_score": 0, "selected": false, "text": "document.getElementById(\"foo\").click = new function() { alert('foo'); }; #foo" }, { "answer_id": 14333699, "author": "Eric", "author_id": 1979125, "author_profile": "https://Stackoverflow.com/users/1979125", "pm_score": 3, "selected": false, "text": ".click new function(){} function name () {code}\n\n... = function() {code} // known as anonymous function or function literal\n\n... = new Function(\"code\") // Function Object\n new function() = function(){alert();}\n = new Function(\"alert();\");\n new Function() function(){} new Function()" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
249,085
<p>My situation: I have several components, which sometimes have changes to them, and are shared across a lot of different projects. Each project puts these in a subfolder called /depends. The depends holds a bunch of svn externals for all of our common components.</p> <p>svn:externals is causing me a lot of time and pain.</p> <ul> <li>Show log on the project root folder will not show changes for svn:external folders (yet funny enough commit and update will work with svn:externals)</li> <li>When you branch, the svn:externals are not branched.</li> <li>Because of no branching on svn:externals, any change usually breaks the trunk.</li> <li>Tags do not freeze their externals. This really defeats the purpose of tagging. </li> </ul> <p>Remember that I have several projects (Let's say 10 for this discussion each using the same externals), so keeping normal committed directories for each project would cost me a lot of merging time. </p> <p>Is there a better alternative for my situation?</p>
[ { "answer_id": 249146, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 5, "selected": true, "text": "svn:externals HEAD trunk" }, { "answer_id": 249529, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "svn:externals svncopy.pl" }, { "answer_id": 250740, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 3, "selected": false, "text": "svn:externals svn:externals svn:externals" }, { "answer_id": 6668921, "author": "kostmo", "author_id": 105137, "author_profile": "https://Stackoverflow.com/users/105137", "pm_score": 0, "selected": false, "text": "svncopy.pl svn:externals" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
249,087
<p>I'm trying to convert some strings that are in French Canadian and basically, I'd like to be able to take out the French accent marks in the letters while keeping the letter. (E.g. convert <code>é</code> to <code>e</code>, so <code>crème brûlée</code> would become <code>creme brulee</code>)</p> <p>What is the best method for achieving this?</p>
[ { "answer_id": 249126, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 10, "selected": true, "text": "static string RemoveDiacritics(string text) \n{\n var normalizedString = text.Normalize(NormalizationForm.FormD);\n var stringBuilder = new StringBuilder(capacity: normalizedString.Length);\n\n for (int i = 0; i < normalizedString.Length; i++)\n {\n char c = normalizedString[i];\n var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);\n if (unicodeCategory != UnicodeCategory.NonSpacingMark)\n {\n stringBuilder.Append(c);\n }\n }\n\n return stringBuilder\n .ToString()\n .Normalize(NormalizationForm.FormC);\n}\n" }, { "answer_id": 780800, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 5, "selected": false, "text": "public static string NormalizeStringForUrl(string name)\n{\n String normalizedString = name.Normalize(NormalizationForm.FormD);\n StringBuilder stringBuilder = new StringBuilder();\n\n foreach (char c in normalizedString)\n {\n switch (CharUnicodeInfo.GetUnicodeCategory(c))\n {\n case UnicodeCategory.LowercaseLetter:\n case UnicodeCategory.UppercaseLetter:\n case UnicodeCategory.DecimalDigitNumber:\n stringBuilder.Append(c);\n break;\n case UnicodeCategory.SpaceSeparator:\n case UnicodeCategory.ConnectorPunctuation:\n case UnicodeCategory.DashPunctuation:\n stringBuilder.Append('_');\n break;\n }\n }\n string result = stringBuilder.ToString();\n return String.Join(\"_\", result.Split(new char[] { '_' }\n , StringSplitOptions.RemoveEmptyEntries)); // remove duplicate underscores\n}\n" }, { "answer_id": 2086575, "author": "azrafe7", "author_id": 1158913, "author_profile": "https://Stackoverflow.com/users/1158913", "pm_score": 8, "selected": false, "text": "string accentedStr;\nbyte[] tempBytes;\ntempBytes = System.Text.Encoding.GetEncoding(\"ISO-8859-8\").GetBytes(accentedStr);\nstring asciiStr = System.Text.Encoding.UTF8.GetString(tempBytes);\n" }, { "answer_id": 3353225, "author": "Stefanos Michanetzis", "author_id": 404544, "author_profile": "https://Stackoverflow.com/users/404544", "pm_score": 2, "selected": false, "text": "Public Function RemoveDiacritics(ByVal s As String)\n Dim normalizedString As String\n Dim stringBuilder As New StringBuilder\n normalizedString = s.Normalize(NormalizationForm.FormD)\n Dim i As Integer\n Dim c As Char\n For i = 0 To normalizedString.Length - 1\n c = normalizedString(i)\n If CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark Then\n stringBuilder.Append(c)\n End If\n Next\n Return stringBuilder.ToString()\nEnd Function\n" }, { "answer_id": 13155469, "author": "realbart", "author_id": 1677285, "author_profile": "https://Stackoverflow.com/users/1677285", "pm_score": 4, "selected": false, "text": "using System.Linq;\nusing System.Text;\nusing System.Globalization;\n\n// namespace here\npublic static class Utility\n{\n public static string RemoveDiacritics(this string str)\n {\n if (null == str) return null;\n var chars =\n from c in str.Normalize(NormalizationForm.FormD).ToCharArray()\n let uc = CharUnicodeInfo.GetUnicodeCategory(c)\n where uc != UnicodeCategory.NonSpacingMark\n select c;\n\n var cleanStr = new string(chars.ToArray()).Normalize(NormalizationForm.FormC);\n\n return cleanStr;\n }\n\n // or, alternatively\n public static string RemoveDiacritics2(this string str)\n {\n if (null == str) return null;\n var chars = str\n .Normalize(NormalizationForm.FormD)\n .ToCharArray()\n .Where(c=> CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)\n .ToArray();\n\n return new string(chars).Normalize(NormalizationForm.FormC);\n }\n}\n" }, { "answer_id": 16350657, "author": "giacomelli", "author_id": 956886, "author_profile": "https://Stackoverflow.com/users/956886", "pm_score": 1, "selected": false, "text": " public static string RemoveAccents(this string source)\n {\n //8 bit characters \n byte[] b = Encoding.GetEncoding(1251).GetBytes(source);\n\n // 7 bit characters\n string t = Encoding.ASCII.GetString(b);\n Regex re = new Regex(\"[^a-zA-Z0-9]=-_/\");\n string c = re.Replace(t, \" \");\n return c;\n }\n" }, { "answer_id": 18002273, "author": "Heyjee", "author_id": 1978167, "author_profile": "https://Stackoverflow.com/users/1978167", "pm_score": 2, "selected": false, "text": "//Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter 'é' is substituted by an 'e'\npublic string RemoveDiacritics(string s)\n{\n string normalizedString = null;\n StringBuilder stringBuilder = new StringBuilder();\n normalizedString = s.Normalize(NormalizationForm.FormD);\n int i = 0;\n char c = '\\0';\n\n for (i = 0; i <= normalizedString.Length - 1; i++)\n {\n c = normalizedString[i];\n if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)\n {\n stringBuilder.Append(c);\n }\n }\n\n return stringBuilder.ToString().ToLower();\n}\n 'Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter \"é\" is substituted by an \"e\"'\nPublic Function RemoveDiacritics(ByVal s As String) As String\n Dim normalizedString As String\n Dim stringBuilder As New StringBuilder\n normalizedString = s.Normalize(NormalizationForm.FormD)\n Dim i As Integer\n Dim c As Char\n\n For i = 0 To normalizedString.Length - 1\n c = normalizedString(i)\n If CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark Then\n stringBuilder.Append(c)\n End If\n Next\n Return stringBuilder.ToString().ToLower()\nEnd Function\n" }, { "answer_id": 20837592, "author": "Mino", "author_id": 2470786, "author_profile": "https://Stackoverflow.com/users/2470786", "pm_score": 1, "selected": false, "text": "using MMLib.RapidPrototyping.Generators;\npublic void ExtensionsExample()\n{\n string target = \"aácčeéií\";\n Assert.AreEqual(\"aacceeii\", target.RemoveDiacritics());\n} \n" }, { "answer_id": 30981339, "author": "Tratak", "author_id": 2062118, "author_profile": "https://Stackoverflow.com/users/2062118", "pm_score": 1, "selected": false, "text": "Imports System.Text\nImports System.Globalization\n\n Public Function DECODE(ByVal x As String) As String\n Dim sb As New StringBuilder\n For Each c As Char In x.Normalize(NormalizationForm.FormD).Where(Function(a) CharUnicodeInfo.GetUnicodeCategory(a) <> UnicodeCategory.NonSpacingMark) \n sb.Append(c)\n Next\n Return sb.ToString()\n End Function\n" }, { "answer_id": 34228877, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(text)); å 00E5 0061 030A a a" }, { "answer_id": 34272324, "author": "CIRCLE", "author_id": 2011284, "author_profile": "https://Stackoverflow.com/users/2011284", "pm_score": 5, "selected": false, "text": "convert_accented_characters($str) using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic static class Strings\n{\n static Dictionary<string, string> foreign_characters = new Dictionary<string, string>\n {\n { \"äæǽ\", \"ae\" },\n { \"öœ\", \"oe\" },\n { \"ü\", \"ue\" },\n { \"Ä\", \"Ae\" },\n { \"Ü\", \"Ue\" },\n { \"Ö\", \"Oe\" },\n { \"ÀÁÂÃÄÅǺĀĂĄǍΑΆẢẠẦẪẨẬẰẮẴẲẶА\", \"A\" },\n { \"àáâãåǻāăąǎªαάảạầấẫẩậằắẵẳặа\", \"a\" },\n { \"Б\", \"B\" },\n { \"б\", \"b\" },\n { \"ÇĆĈĊČ\", \"C\" },\n { \"çćĉċč\", \"c\" },\n { \"Д\", \"D\" },\n { \"д\", \"d\" },\n { \"ÐĎĐΔ\", \"Dj\" },\n { \"ðďđδ\", \"dj\" },\n { \"ÈÉÊËĒĔĖĘĚΕΈẼẺẸỀẾỄỂỆЕЭ\", \"E\" },\n { \"èéêëēĕėęěέεẽẻẹềếễểệеэ\", \"e\" },\n { \"Ф\", \"F\" },\n { \"ф\", \"f\" },\n { \"ĜĞĠĢΓГҐ\", \"G\" },\n { \"ĝğġģγгґ\", \"g\" },\n { \"ĤĦ\", \"H\" },\n { \"ĥħ\", \"h\" },\n { \"ÌÍÎÏĨĪĬǏĮİΗΉΊΙΪỈỊИЫ\", \"I\" },\n { \"ìíîïĩīĭǐįıηήίιϊỉịиыї\", \"i\" },\n { \"Ĵ\", \"J\" },\n { \"ĵ\", \"j\" },\n { \"ĶΚК\", \"K\" },\n { \"ķκк\", \"k\" },\n { \"ĹĻĽĿŁΛЛ\", \"L\" },\n { \"ĺļľŀłλл\", \"l\" },\n { \"М\", \"M\" },\n { \"м\", \"m\" },\n { \"ÑŃŅŇΝН\", \"N\" },\n { \"ñńņňʼnνн\", \"n\" },\n { \"ÒÓÔÕŌŎǑŐƠØǾΟΌΩΏỎỌỒỐỖỔỘỜỚỠỞỢО\", \"O\" },\n { \"òóôõōŏǒőơøǿºοόωώỏọồốỗổộờớỡởợо\", \"o\" },\n { \"П\", \"P\" },\n { \"п\", \"p\" },\n { \"ŔŖŘΡР\", \"R\" },\n { \"ŕŗřρр\", \"r\" },\n { \"ŚŜŞȘŠΣС\", \"S\" },\n { \"śŝşșšſσςс\", \"s\" },\n { \"ȚŢŤŦτТ\", \"T\" },\n { \"țţťŧт\", \"t\" },\n { \"ÙÚÛŨŪŬŮŰŲƯǓǕǗǙǛŨỦỤỪỨỮỬỰУ\", \"U\" },\n { \"ùúûũūŭůűųưǔǖǘǚǜυύϋủụừứữửựу\", \"u\" },\n { \"ÝŸŶΥΎΫỲỸỶỴЙ\", \"Y\" },\n { \"ýÿŷỳỹỷỵй\", \"y\" },\n { \"В\", \"V\" },\n { \"в\", \"v\" },\n { \"Ŵ\", \"W\" },\n { \"ŵ\", \"w\" },\n { \"ŹŻŽΖЗ\", \"Z\" },\n { \"źżžζз\", \"z\" },\n { \"ÆǼ\", \"AE\" },\n { \"ß\", \"ss\" },\n { \"IJ\", \"IJ\" },\n { \"ij\", \"ij\" },\n { \"Œ\", \"OE\" },\n { \"ƒ\", \"f\" },\n { \"ξ\", \"ks\" },\n { \"π\", \"p\" },\n { \"β\", \"v\" },\n { \"μ\", \"m\" },\n { \"ψ\", \"ps\" },\n { \"Ё\", \"Yo\" },\n { \"ё\", \"yo\" },\n { \"Є\", \"Ye\" },\n { \"є\", \"ye\" },\n { \"Ї\", \"Yi\" },\n { \"Ж\", \"Zh\" },\n { \"ж\", \"zh\" },\n { \"Х\", \"Kh\" },\n { \"х\", \"kh\" },\n { \"Ц\", \"Ts\" },\n { \"ц\", \"ts\" },\n { \"Ч\", \"Ch\" },\n { \"ч\", \"ch\" },\n { \"Ш\", \"Sh\" },\n { \"ш\", \"sh\" },\n { \"Щ\", \"Shch\" },\n { \"щ\", \"shch\" },\n { \"ЪъЬь\", \"\" },\n { \"Ю\", \"Yu\" },\n { \"ю\", \"yu\" },\n { \"Я\", \"Ya\" },\n { \"я\", \"ya\" },\n };\n\n public static char RemoveDiacritics(this char c){\n foreach(KeyValuePair<string, string> entry in foreign_characters)\n {\n if(entry.Key.IndexOf (c) != -1)\n {\n return entry.Value[0];\n }\n }\n return c;\n }\n\n public static string RemoveDiacritics(this string s) \n {\n //StringBuilder sb = new StringBuilder ();\n string text = \"\";\n\n\n foreach (char c in s)\n {\n int len = text.Length;\n\n foreach(KeyValuePair<string, string> entry in foreign_characters)\n {\n if(entry.Key.IndexOf (c) != -1)\n {\n text += entry.Value;\n break;\n }\n }\n\n if (len == text.Length) {\n text += c; \n }\n }\n return text;\n }\n}\n // for strings\n\"crème brûlée\".RemoveDiacritics (); // creme brulee\n\n// for chars\n\"Ã\"[0].RemoveDiacritics (); // A\n" }, { "answer_id": 38779892, "author": "Sergio Cabral", "author_id": 1396511, "author_profile": "https://Stackoverflow.com/users/1396511", "pm_score": 4, "selected": false, "text": "System.Text.Encoding.GetEncodings() string text = \"Você está numa situação lamentável\";\n\nstring textEncode = System.Web.HttpUtility.UrlEncode(text, Encoding.GetEncoding(\"iso-8859-7\"));\n//result: \"Voce+esta+numa+situacao+lamentavel\"\n\nstring textDecode = System.Web.HttpUtility.UrlDecode(textEncode);\n//result: \"Voce esta numa situacao lamentavel\"\n public string RemoveAcentuation(string text)\n{\n return\n System.Web.HttpUtility.UrlDecode(\n System.Web.HttpUtility.UrlEncode(\n text, Encoding.GetEncoding(\"iso-8859-7\")));\n}\n Encoding.GetEncoding(\"iso-8859-7\") Encoding.GetEncoding(28597)" }, { "answer_id": 42068811, "author": "EricBDev", "author_id": 6579566, "author_profile": "https://Stackoverflow.com/users/6579566", "pm_score": 3, "selected": false, "text": " public static string ConvertWesternEuropeanToASCII(this string str)\n {\n return Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(str));\n }\n public static string LatinizeGermanCharacters(this string str)\n {\n StringBuilder sb = new StringBuilder(str.Length);\n foreach (char c in str)\n {\n switch (c)\n {\n case 'ä':\n sb.Append(\"ae\");\n break;\n case 'ö':\n sb.Append(\"oe\");\n break;\n case 'ü':\n sb.Append(\"ue\");\n break;\n case 'Ä':\n sb.Append(\"Ae\");\n break;\n case 'Ö':\n sb.Append(\"Oe\");\n break;\n case 'Ü':\n sb.Append(\"Ue\");\n break;\n case 'ß':\n sb.Append(\"ss\");\n break;\n default:\n sb.Append(c);\n break;\n }\n }\n return sb.ToString();\n }\n public static string RemoveSpace(this string str)\n {\n return str.Replace(\" \", string.Empty);\n }\n public static string LatinizeAndConvertToASCII(this string str, bool keepSpace = false)\n {\n str = str.LatinizeGermanCharacters().ConvertWesternEuropeanToASCII(); \n return keepSpace ? str : str.RemoveSpace();\n }\n [TestMethod()]\n public void LatinizeAndConvertToASCIITest()\n {\n string europeanStr = \"Bonjour ça va? C'est l'été! Ich möchte ä Ä á à â ê é è ë Ë É ï Ï î í ì ó ò ô ö Ö Ü ü ù ú û Û ý Ý ç Ç ñ Ñ\";\n string expected = \"Bonjourcava?C'estl'ete!IchmoechteaeAeaaaeeeeEEiIiiiooooeOeUeueuuuUyYcCnN\";\n string actual = europeanStr.LatinizeAndConvertToASCII();\n Assert.AreEqual(expected, actual);\n }\n" }, { "answer_id": 42234063, "author": "Siavash Mortazavi", "author_id": 1854557, "author_profile": "https://Stackoverflow.com/users/1854557", "pm_score": 1, "selected": false, "text": "public static class StringExtensions\n{\n public static string RemoveDiacritics(this string text)\n {\n const string SINGLEBYTE_LATIN_ASCII_ENCODING = \"ISO-8859-8\";\n\n if (string.IsNullOrEmpty(text))\n {\n return string.Empty;\n }\n\n return Encoding.ASCII.GetString(\n Encoding.GetEncoding(SINGLEBYTE_LATIN_ASCII_ENCODING).GetBytes(text));\n }\n}\n" }, { "answer_id": 55669972, "author": "Adrian", "author_id": 5958655, "author_profile": "https://Stackoverflow.com/users/5958655", "pm_score": -1, "selected": false, "text": "public static class Lucene\n{\n // source: https://raw.githubusercontent.com/apache/lucenenet/master/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/ASCIIFoldingFilter.cs\n // idea: https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net (scroll down, search for lucene by Alexander)\n public static string latinizeLucene(string arg)\n {\n char[] argChar = arg.ToCharArray();\n\n // latinizeLuceneImpl can expand one char up to four chars - e.g. Þ to TH, or æ to ae, or in fact ⑽ to (10)\n char[] resultChar = new String(' ', arg.Length * 4).ToCharArray();\n\n int outputPos = Lucene.latinizeLuceneImpl(argChar, 0, ref resultChar, 0, arg.Length);\n\n string ret = new string(resultChar);\n ret = ret.Substring(0, outputPos);\n\n return ret;\n }\n\n /// <summary>\n /// Converts characters above ASCII to their ASCII equivalents. For example,\n /// accents are removed from accented characters. \n /// <para/>\n /// @lucene.internal\n /// </summary>\n /// <param name=\"input\"> The characters to fold </param>\n /// <param name=\"inputPos\"> Index of the first character to fold </param>\n /// <param name=\"output\"> The result of the folding. Should be of size >= <c>length * 4</c>. </param>\n /// <param name=\"outputPos\"> Index of output where to put the result of the folding </param>\n /// <param name=\"length\"> The number of characters to fold </param>\n /// <returns> length of output </returns>\n private static int latinizeLuceneImpl(char[] input, int inputPos, ref char[] output, int outputPos, int length)\n {\n int end = inputPos + length;\n for (int pos = inputPos; pos < end; ++pos)\n {\n char c = input[pos];\n\n // Quick test: if it's not in range then just keep current character\n if (c < '\\u0080')\n {\n output[outputPos++] = c;\n }\n else\n {\n switch (c)\n {\n case '\\u00C0': // À [LATIN CAPITAL LETTER A WITH GRAVE]\n case '\\u00C1': // Á [LATIN CAPITAL LETTER A WITH ACUTE]\n case '\\u00C2': //  [LATIN CAPITAL LETTER A WITH CIRCUMFLEX]\n case '\\u00C3': // à [LATIN CAPITAL LETTER A WITH TILDE]\n case '\\u00C4': // Ä [LATIN CAPITAL LETTER A WITH DIAERESIS]\n case '\\u00C5': // Å [LATIN CAPITAL LETTER A WITH RING ABOVE]\n case '\\u0100': // Ā [LATIN CAPITAL LETTER A WITH MACRON]\n case '\\u0102': // Ă [LATIN CAPITAL LETTER A WITH BREVE]\n case '\\u0104': // Ą [LATIN CAPITAL LETTER A WITH OGONEK]\n case '\\u018F': // Ə http://en.wikipedia.org/wiki/Schwa [LATIN CAPITAL LETTER SCHWA]\n case '\\u01CD': // Ǎ [LATIN CAPITAL LETTER A WITH CARON]\n case '\\u01DE': // Ǟ [LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]\n case '\\u01E0': // Ǡ [LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON]\n case '\\u01FA': // Ǻ [LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE]\n case '\\u0200': // Ȁ [LATIN CAPITAL LETTER A WITH DOUBLE GRAVE]\n case '\\u0202': // Ȃ [LATIN CAPITAL LETTER A WITH INVERTED BREVE]\n case '\\u0226': // Ȧ [LATIN CAPITAL LETTER A WITH DOT ABOVE]\n case '\\u023A': // Ⱥ [LATIN CAPITAL LETTER A WITH STROKE]\n case '\\u1D00': // ᴀ [LATIN LETTER SMALL CAPITAL A]\n case '\\u1E00': // Ḁ [LATIN CAPITAL LETTER A WITH RING BELOW]\n case '\\u1EA0': // Ạ [LATIN CAPITAL LETTER A WITH DOT BELOW]\n case '\\u1EA2': // Ả [LATIN CAPITAL LETTER A WITH HOOK ABOVE]\n case '\\u1EA4': // Ấ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE]\n case '\\u1EA6': // Ầ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE]\n case '\\u1EA8': // Ẩ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE]\n case '\\u1EAA': // Ẫ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE]\n case '\\u1EAC': // Ậ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW]\n case '\\u1EAE': // Ắ [LATIN CAPITAL LETTER A WITH BREVE AND ACUTE]\n case '\\u1EB0': // Ằ [LATIN CAPITAL LETTER A WITH BREVE AND GRAVE]\n case '\\u1EB2': // Ẳ [LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE]\n case '\\u1EB4': // Ẵ [LATIN CAPITAL LETTER A WITH BREVE AND TILDE]\n case '\\u1EB6': // Ặ [LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW]\n case '\\u24B6': // Ⓐ [CIRCLED LATIN CAPITAL LETTER A]\n case '\\uFF21': // A [FULLWIDTH LATIN CAPITAL LETTER A]\n output[outputPos++] = 'A';\n break;\n case '\\u00E0': // à [LATIN SMALL LETTER A WITH GRAVE]\n case '\\u00E1': // á [LATIN SMALL LETTER A WITH ACUTE]\n case '\\u00E2': // â [LATIN SMALL LETTER A WITH CIRCUMFLEX]\n case '\\u00E3': // ã [LATIN SMALL LETTER A WITH TILDE]\n case '\\u00E4': // ä [LATIN SMALL LETTER A WITH DIAERESIS]\n case '\\u00E5': // å [LATIN SMALL LETTER A WITH RING ABOVE]\n case '\\u0101': // ā [LATIN SMALL LETTER A WITH MACRON]\n case '\\u0103': // ă [LATIN SMALL LETTER A WITH BREVE]\n case '\\u0105': // ą [LATIN SMALL LETTER A WITH OGONEK]\n case '\\u01CE': // ǎ [LATIN SMALL LETTER A WITH CARON]\n case '\\u01DF': // ǟ [LATIN SMALL LETTER A WITH DIAERESIS AND MACRON]\n case '\\u01E1': // ǡ [LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON]\n case '\\u01FB': // ǻ [LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE]\n case '\\u0201': // ȁ [LATIN SMALL LETTER A WITH DOUBLE GRAVE]\n case '\\u0203': // ȃ [LATIN SMALL LETTER A WITH INVERTED BREVE]\n case '\\u0227': // ȧ [LATIN SMALL LETTER A WITH DOT ABOVE]\n case '\\u0250': // ɐ [LATIN SMALL LETTER TURNED A]\n case '\\u0259': // ə [LATIN SMALL LETTER SCHWA]\n case '\\u025A': // ɚ [LATIN SMALL LETTER SCHWA WITH HOOK]\n case '\\u1D8F': // ᶏ [LATIN SMALL LETTER A WITH RETROFLEX HOOK]\n case '\\u1D95': // ᶕ [LATIN SMALL LETTER SCHWA WITH RETROFLEX HOOK]\n case '\\u1E01': // ạ [LATIN SMALL LETTER A WITH RING BELOW]\n case '\\u1E9A': // ả [LATIN SMALL LETTER A WITH RIGHT HALF RING]\n case '\\u1EA1': // ạ [LATIN SMALL LETTER A WITH DOT BELOW]\n case '\\u1EA3': // ả [LATIN SMALL LETTER A WITH HOOK ABOVE]\n case '\\u1EA5': // ấ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE]\n case '\\u1EA7': // ầ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE]\n case '\\u1EA9': // ẩ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE]\n case '\\u1EAB': // ẫ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE]\n case '\\u1EAD': // ậ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW]\n case '\\u1EAF': // ắ [LATIN SMALL LETTER A WITH BREVE AND ACUTE]\n case '\\u1EB1': // ằ [LATIN SMALL LETTER A WITH BREVE AND GRAVE]\n case '\\u1EB3': // ẳ [LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE]\n case '\\u1EB5': // ẵ [LATIN SMALL LETTER A WITH BREVE AND TILDE]\n case '\\u1EB7': // ặ [LATIN SMALL LETTER A WITH BREVE AND DOT BELOW]\n case '\\u2090': // ₐ [LATIN SUBSCRIPT SMALL LETTER A]\n case '\\u2094': // ₔ [LATIN SUBSCRIPT SMALL LETTER SCHWA]\n case '\\u24D0': // ⓐ [CIRCLED LATIN SMALL LETTER A]\n case '\\u2C65': // ⱥ [LATIN SMALL LETTER A WITH STROKE]\n case '\\u2C6F': // Ɐ [LATIN CAPITAL LETTER TURNED A]\n case '\\uFF41': // a [FULLWIDTH LATIN SMALL LETTER A]\n output[outputPos++] = 'a';\n break;\n case '\\uA732': // Ꜳ [LATIN CAPITAL LETTER AA]\n output[outputPos++] = 'A';\n output[outputPos++] = 'A';\n break;\n case '\\u00C6': // Æ [LATIN CAPITAL LETTER AE]\n case '\\u01E2': // Ǣ [LATIN CAPITAL LETTER AE WITH MACRON]\n case '\\u01FC': // Ǽ [LATIN CAPITAL LETTER AE WITH ACUTE]\n case '\\u1D01': // ᴁ [LATIN LETTER SMALL CAPITAL AE]\n output[outputPos++] = 'A';\n output[outputPos++] = 'E';\n break;\n case '\\uA734': // Ꜵ [LATIN CAPITAL LETTER AO]\n output[outputPos++] = 'A';\n output[outputPos++] = 'O';\n break;\n case '\\uA736': // Ꜷ [LATIN CAPITAL LETTER AU]\n output[outputPos++] = 'A';\n output[outputPos++] = 'U';\n break;\n\n // etc. etc. etc.\n // see link above for complete source code\n // \n // unfortunately, postings are limited, as in\n // \"Body is limited to 30000 characters; you entered 136098.\"\n\n [...]\n\n case '\\u2053': // ⁓ [SWUNG DASH]\n case '\\uFF5E': // ~ [FULLWIDTH TILDE]\n output[outputPos++] = '~';\n break;\n default:\n output[outputPos++] = c;\n break;\n }\n }\n }\n return outputPos;\n }\n}\n" }, { "answer_id": 56797567, "author": "Andy Raddatz", "author_id": 479701, "author_profile": "https://Stackoverflow.com/users/479701", "pm_score": 4, "selected": false, "text": "crème brûlée crme brle creme brulee var originalString = \"crème brûlée\";\nvar maxLength = originalString.Length; // limit output length as necessary\nvar foldedString = originalString.FoldToASCII(maxLength); \n// \"creme brulee\"\n /*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/// <summary>\n/// This class converts alphabetic, numeric, and symbolic Unicode characters\n/// which are not in the first 127 ASCII characters (the \"Basic Latin\" Unicode\n/// block) into their ASCII equivalents, if one exists.\n/// <para/>\n/// Characters from the following Unicode blocks are converted; however, only\n/// those characters with reasonable ASCII alternatives are converted:\n/// \n/// <ul>\n/// <item><description>C1 Controls and Latin-1 Supplement: <a href=\"http://www.unicode.org/charts/PDF/U0080.pdf\">http://www.unicode.org/charts/PDF/U0080.pdf</a></description></item>\n/// <item><description>Latin Extended-A: <a href=\"http://www.unicode.org/charts/PDF/U0100.pdf\">http://www.unicode.org/charts/PDF/U0100.pdf</a></description></item>\n/// <item><description>Latin Extended-B: <a href=\"http://www.unicode.org/charts/PDF/U0180.pdf\">http://www.unicode.org/charts/PDF/U0180.pdf</a></description></item>\n/// <item><description>Latin Extended Additional: <a href=\"http://www.unicode.org/charts/PDF/U1E00.pdf\">http://www.unicode.org/charts/PDF/U1E00.pdf</a></description></item>\n/// <item><description>Latin Extended-C: <a href=\"http://www.unicode.org/charts/PDF/U2C60.pdf\">http://www.unicode.org/charts/PDF/U2C60.pdf</a></description></item>\n/// <item><description>Latin Extended-D: <a href=\"http://www.unicode.org/charts/PDF/UA720.pdf\">http://www.unicode.org/charts/PDF/UA720.pdf</a></description></item>\n/// <item><description>IPA Extensions: <a href=\"http://www.unicode.org/charts/PDF/U0250.pdf\">http://www.unicode.org/charts/PDF/U0250.pdf</a></description></item>\n/// <item><description>Phonetic Extensions: <a href=\"http://www.unicode.org/charts/PDF/U1D00.pdf\">http://www.unicode.org/charts/PDF/U1D00.pdf</a></description></item>\n/// <item><description>Phonetic Extensions Supplement: <a href=\"http://www.unicode.org/charts/PDF/U1D80.pdf\">http://www.unicode.org/charts/PDF/U1D80.pdf</a></description></item>\n/// <item><description>General Punctuation: <a href=\"http://www.unicode.org/charts/PDF/U2000.pdf\">http://www.unicode.org/charts/PDF/U2000.pdf</a></description></item>\n/// <item><description>Superscripts and Subscripts: <a href=\"http://www.unicode.org/charts/PDF/U2070.pdf\">http://www.unicode.org/charts/PDF/U2070.pdf</a></description></item>\n/// <item><description>Enclosed Alphanumerics: <a href=\"http://www.unicode.org/charts/PDF/U2460.pdf\">http://www.unicode.org/charts/PDF/U2460.pdf</a></description></item>\n/// <item><description>Dingbats: <a href=\"http://www.unicode.org/charts/PDF/U2700.pdf\">http://www.unicode.org/charts/PDF/U2700.pdf</a></description></item>\n/// <item><description>Supplemental Punctuation: <a href=\"http://www.unicode.org/charts/PDF/U2E00.pdf\">http://www.unicode.org/charts/PDF/U2E00.pdf</a></description></item>\n/// <item><description>Alphabetic Presentation Forms: <a href=\"http://www.unicode.org/charts/PDF/UFB00.pdf\">http://www.unicode.org/charts/PDF/UFB00.pdf</a></description></item>\n/// <item><description>Halfwidth and Fullwidth Forms: <a href=\"http://www.unicode.org/charts/PDF/UFF00.pdf\">http://www.unicode.org/charts/PDF/UFF00.pdf</a></description></item>\n/// </ul>\n/// <para/>\n/// See: <a href=\"http://en.wikipedia.org/wiki/Latin_characters_in_Unicode\">http://en.wikipedia.org/wiki/Latin_characters_in_Unicode</a>\n/// <para/>\n/// For example, '&amp;agrave;' will be replaced by 'a'.\n/// </summary>\npublic static partial class StringExtensions\n{\n /// <summary>\n /// Converts characters above ASCII to their ASCII equivalents. For example,\n /// accents are removed from accented characters. \n /// </summary>\n /// <param name=\"input\"> The string of characters to fold </param>\n /// <param name=\"length\"> The length of the folded return string </param>\n /// <returns> length of output </returns>\n public static string FoldToASCII(this string input, int? length = null)\n {\n // See https://gist.github.com/andyraddatz/e6a396fb91856174d4e3f1bf2e10951c\n }\n}\n" }, { "answer_id": 63729084, "author": "Thomas", "author_id": 42659, "author_profile": "https://Stackoverflow.com/users/42659", "pm_score": 0, "selected": false, "text": "var updatedText = text.Normalize(NormalizationForm.FormD)\n .Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)\n .ToArray();\n Zuberbühler Zuberbuehler" }, { "answer_id": 67190157, "author": "aepot", "author_id": 12888024, "author_profile": "https://Stackoverflow.com/users/12888024", "pm_score": 2, "selected": false, "text": "Span StringBuilder static string RemoveDiacritics(string text) \n{\n ReadOnlySpan<char> normalizedString = text.Normalize(NormalizationForm.FormD);\n int i = 0;\n Span<char> span = text.Length < 1000\n ? stackalloc char[text.Length]\n : new char[text.Length];\n\n foreach (char c in normalizedString)\n {\n if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)\n span[i++] = c;\n }\n\n return new string(span).Normalize(NormalizationForm.FormC);\n}\n span[i++] = c switch\n{\n 'Ł' => 'L',\n 'ł' => 'l',\n _ => c\n};\n stackalloc new 1000 StackOverflowException" }, { "answer_id": 67569854, "author": "cdie", "author_id": 2743315, "author_profile": "https://Stackoverflow.com/users/2743315", "pm_score": 4, "selected": false, "text": "CharUnicodeInfo static string RemoveDiacritics(string text) \n{\n var normalizedString = text.Normalize(NormalizationForm.FormD);\n var stringBuilder = new StringBuilder();\n\n foreach (var c in normalizedString.EnumerateRunes())\n {\n var unicodeCategory = Rune.GetUnicodeCategory(c);\n if (unicodeCategory != UnicodeCategory.NonSpacingMark)\n {\n stringBuilder.Append(c);\n }\n }\n\n return stringBuilder.ToString().Normalize(NormalizationForm.FormC);\n}\n" }, { "answer_id": 72705782, "author": "Joshua Barker", "author_id": 3617346, "author_profile": "https://Stackoverflow.com/users/3617346", "pm_score": 2, "selected": false, "text": "Imports System.Text\nImports System.Text.RegularExpressions\n\nPublic MustInherit Class StringExtension\n Public Shared Function RemoveDiacritics(Text As String) As String\n Return New Regex(\"\\p{Mn}\", RegexOptions.Compiled).Replace(Text.Normalize(NormalizationForm.FormD), String.Empty)\n End Function\nEnd Class\n Private Shared Sub DoStuff()\n MsgBox(StringExtension.RemoveDiacritics(inputString))\n End Sub\n using System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace YourApplication\n{\n public abstract class StringExtension\n {\n public static string RemoveDiacritics(string Text)\n {\n return new Regex(@\"\\p{Mn}\", RegexOptions.Compiled).Replace(Text.Normalize(NormalizationForm.FormD), string.Empty);\n }\n }\n}\n private static void DoStuff()\n {\n MessageBox.Show(StringExtension.RemoveDiacritics(inputString));\n }\n äáčďěéíľľňôóřŕšťúůýž ÄÁČĎĚÉÍĽĽŇÔÓŘŔŠŤÚŮÝŽ ÖÜË łŁđĐ ţŢşŞçÇ øı aacdeeillnoorrstuuyz AACDEEILLNOORRSTUUYZ OUE łŁđĐ tTsScC øı CodePagesEncodingProvider" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/514/" ]
249,103
<p>So I just love it when my application is working great in Firefox, but then I open it in IE and... Nope, please try again.</p> <p>The issue I'm having is that I'm setting a CSS display property to either <code>none</code> or <code>table-cell</code> with JavaScript.</p> <p>I was initially using <code>display: block</code>, but Firefox was rendering it weird without the <code>table-cell</code> property.</p> <p>I would love to do this without adding a hack in the JavaScript to test for IE. Any suggestions?</p> <p>Thanks.</p>
[ { "answer_id": 249121, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 2, "selected": false, "text": "display: table(-cell/-row) display: inline-block display: block" }, { "answer_id": 645977, "author": "Jacco", "author_id": 22674, "author_profile": "https://Stackoverflow.com/users/22674", "pm_score": 6, "selected": true, "text": "display '' <script type=\"text/javascript\">\n<!--\nfunction toggle( elemntId ) {\n if (document.getElementById( elemntId ).style.display != 'none') {\n document.getElementById( elemntId ).style.display = 'none';\n } else {\n document.getElementById( elemntId ).style.display = '';\n }\n return true;\n}\n//-->\n</script>\n" }, { "answer_id": 1235847, "author": "Jonathan Hendler", "author_id": 135043, "author_profile": "https://Stackoverflow.com/users/135043", "pm_score": 3, "selected": false, "text": "*float: left; \n" }, { "answer_id": 4963526, "author": "andy magoon", "author_id": 612216, "author_profile": "https://Stackoverflow.com/users/612216", "pm_score": 6, "selected": false, "text": "$(document).ready(function(){\n if ($.browser.msie && $.browser.version == 7)\n {\n $(\".tablecell\").wrap(\"<td />\");\n $(\".tablerow\").wrap(\"<tr />\");\n $(\".table\").wrapInner(\"<table />\");\n }\n});\n <style>\n.table { display: table; }\n.tablerow { display: table-row; }\n.tablecell { display: table-cell; }\n</style>\n" }, { "answer_id": 6988609, "author": "risingfish", "author_id": 884832, "author_profile": "https://Stackoverflow.com/users/884832", "pm_score": 2, "selected": false, "text": "div.show-ib {\n display: inline-block;\n *zoom: 1;\n *display: inline;\n}\n" }, { "answer_id": 12320221, "author": "stack collision with heap", "author_id": 1630242, "author_profile": "https://Stackoverflow.com/users/1630242", "pm_score": 1, "selected": false, "text": " <div class=\"container\">\n <!--[if lt IE 8 ]><table><tr><![endif]--> \n <!--[if lt IE 8 ]><td><![endif]-->\n <div class=\"link\"><a href=\"en.html\">English</a></div>\n <!--[if lt IE 8 ]></td><![endif]-->\n <!--[if lt IE 8 ]><td><![endif]-->\n <div tabindex=\"0\" class=\"thumb\"><img src=\"pictures\\pic.jpg\" /></div>\n <!--[if lt IE 8 ]></td><![endif]-->\n <!--[if lt IE 8 ]><td><![endif]-->\n <div class=\"link\"><a href=\"de.html\">Deutsch</a></div>\n <!--[if lt IE 8 ]></td><![endif]-->\n <!--[if lt IE 8 ]></tr></table><![endif]-->\n</div> \n .link {\n display:table-cell;\n vertical-align:middle;\n }\n div.container {\n margin: 0 auto;\n display:table;\n }\n .thumb {\n display:table-cell;\n float: left;\n text-align: center;\n }\n" }, { "answer_id": 23745735, "author": "Phill Healey", "author_id": 619792, "author_profile": "https://Stackoverflow.com/users/619792", "pm_score": 0, "selected": false, "text": "display:inline-block; zoom: 1; *display: inline; display:table-cell;" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
249,110
<p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
[ { "answer_id": 249524, "author": "Adam", "author_id": 30084, "author_profile": "https://Stackoverflow.com/users/30084", "pm_score": 5, "selected": true, "text": "urlpatterns = patterns('',\n url(r'^browse/(?P<match>.+)/$', 'app.views.view', name='model_browse'),\n)\n\ndef view(request, match):\n pieces = match.split('/')\n # even indexed pieces are the names, odd are values\n ...\n" }, { "answer_id": 251253, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 2, "selected": false, "text": "... r'^browse/(?P<match>.+)/$' ...\n" }, { "answer_id": 19378600, "author": "Michael", "author_id": 1694500, "author_profile": "https://Stackoverflow.com/users/1694500", "pm_score": 0, "selected": false, "text": "store year month day urlpatterns = patterns('',\n url(r'^baseurl/location/(?P<store>.+)/sales/(?P<year>[0-9][0-9][0-9][0-9])-(?P<month>[0-9][0-9])-(?P<day>[0-9][0-9])/$', views.DailySalesAtLocationListAPIView.as_view(), name='daily-sales-at-location'),\n)\n (?P<store>.+) (?P<store>[0-9]+) location sales class DailySalesAtLocationListAPIView(generics.ListAPIView):\n def get(self, request, store, year, month, day):\n # here you can start using the values from the url\n print store\n print year\n print month\n print date\n\n # now start filtering your model\n" }, { "answer_id": 35575143, "author": "softwareplay", "author_id": 2595727, "author_profile": "https://Stackoverflow.com/users/2595727", "pm_score": 1, "selected": false, "text": "url(r'^my_app/(((list\\/)((\\w{1,})\\/(\\w{1,})\\/(\\w{1,3})\\/){1,10})+)$'" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32638/" ]
249,158
<p>First, a couple operating parameters:</p> <ul> <li>.NET development using Visual Studio 2005/2008</li> <li>TortoiseSVN client</li> </ul> <p>I've only primarily worked with Visual Source Safe and SourceGear Vault source control systems. In each, I map the root of the repository to a local working directory. For example:</p> <pre><code>$/ --&gt; C:\source </code></pre> <p>As long as the local directory exists, I've got my "working copy" (svn) or "working folder" (VSS) set up.</p> <p>To work on a new project that is already in the source code repository I need to "get the latest" (VSS) version of that project's directory.</p> <p>When I go into any child directory in the repository and "Get Latest" (i.e. svn checkout) the client will automatically create the complete directory hierarchy for me, mirroring the structure on my local disk. Thus when I get latest of</p> <pre><code>$/foo/bar/project1 </code></pre> <p>it is created on the drive at</p> <pre><code>C:\source\foo\bar\project1 </code></pre> <p>In subversion, when I check out a directory, I must specify the working copy directory location. If I want to properly mirror my working copy directory structure to match the repository I have to either manually construct every child directory in the path or do a checkout of the repository root to the working copy root, getting everything in the repository.</p> <p><strong>Is there a way to get a repository directory down in the hierarchy such that it will be created in a matching local working copy directory structure without all the manual intervention?</strong></p> <p>This isn't a problem with a small repository, but in most cases, I don't need a large percentage of the source repository. It's imperative that the physical structure is maintained in order for file references to projects and resources not to break. Plus the disk cost of SVN is twice the actual source size given all the working base copies of the files.</p> <p>I'm currently using Tortoise. Is it possible there are other SVN clients that will do what I'm looking for?</p>
[ { "answer_id": 249651, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 2, "selected": false, "text": "--sparse-checkout" }, { "answer_id": 250669, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 0, "selected": false, "text": "http://mysvn/svn/foo/bar/project1\n C:\\source\\foo\\bar\\project1\n ..\\..\\..\\bar\\foo\\project2\n C:\\source\\bar\\foo\\project2\n" }, { "answer_id": 341123, "author": "Jim T", "author_id": 7298, "author_profile": "https://Stackoverflow.com/users/7298", "pm_score": 0, "selected": false, "text": "http://mysvn/svn/foo/bar/project1 foo/bar/project1\nhttp://mysvn/svn/bar/foo/project2 bar/foo/project2\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5496/" ]
249,159
<p>I have a custom application with a simple app.config specifying SQL Server name and Database, I want to prompt the user on application install for application configuration items and then update the app.config file.</p> <p>I admit I'm totally new to setup projects and am looking for some guidance. Thank You Mark Koops</p>
[ { "answer_id": 319831, "author": "AndrewD", "author_id": 20151, "author_profile": "https://Stackoverflow.com/users/20151", "pm_score": 1, "selected": false, "text": "Public Shared Property AppConfigSetting(ByVal SettingName As String) As Object\n Get\n Return My.Settings.PropertyValues(SettingName)\n End Get\n Set(ByVal value As Object)\n Dim AppConfigFilename As String = String.Concat(System.Reflection.Assembly.GetExecutingAssembly.Location, \".config\")\n\n If (My.Computer.FileSystem.FileExists(AppConfigFilename)) Then\n Dim AppSettingXPath As String = String.Concat(\"/configuration/applicationSettings/\", My.Application.Info.AssemblyName, \".My.MySettings/setting[@name='\", SettingName, \"']/value\")\n\n Dim AppConfigXML As New System.Xml.XmlDataDocument\n With AppConfigXML\n .Load(AppConfigFilename)\n\n Dim DataNode As System.Xml.XmlNode = .SelectSingleNode(AppSettingXPath)\n\n If (DataNode Is Nothing) Then\n Throw New Xml.XmlException(String.Format(\"Application setting not found ({0})!\", AppSettingXPath))\n\n Else\n DataNode.InnerText = value.ToString\n End If\n\n .Save(AppConfigFilename)\n End With\n\n Else\n Throw New IO.FileNotFoundException(\"App.Config file not found!\", AppConfigFilename)\n End If\n\n End Set\nEnd Property\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,171
<p>I am working on a business problem in C#.NET. I have two classes, named C and W that will be instantiated independently at different times.</p> <p>An object of class C needs to contain references to 0 ... n objects of class W, i.e. a C object can contain up to n W objects.</p> <p>Each W object needs to contain a reference to exactly 1 object of class C, i.e. a W object is contained in one C object.</p> <p>An object of class C is usually instantiated first. At a later point, its W contents are discovered, and instantiated. At this later point, I need to cross reference the C and W objects to each other.</p> <p>What is a good design pattern for this? I actually have cases where I have three or four classes involved but we can talk about two classes to keep it simple.</p> <p>I was thinking of something simple like:</p> <pre><code>class C { public List&lt;W&gt; contentsW; } class W { public C containerC; } </code></pre> <p>This will work for the moment but I can foresee having to write a fair amount of code to keep track of all the references and their validity. I'd like to implement code down the road to do shallow refreshes of just the container and deep refreshes of all referenced classes. Are there any other approaches and what are their advantages?</p> <p>Edit on 11/3: Thanks to all for the good answers and good discussion. I finally chose jop's answer because that came closest to what I wanted to do, but the other answers also helped. Thanks again!</p>
[ { "answer_id": 249180, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "class C\n{\n private List<W> _contentsW;\n\n public List<W> Contents \n {\n get { return _contentsw; }\n }\n\n public void AddToContents(W content);\n {\n content.Container = this;\n _contentsW.Add(content);\n }\n}\n foreach (var w in _contentsW)\n{\n if (w.Container != this)\n {\n w.Container = this;\n }\n}\n" }, { "answer_id": 249187, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 2, "selected": false, "text": "class C\n{\n private List<W> _contents = new List<W>();\n public IEnumerable<W> Contents\n {\n get { return _contents; }\n }\n\n public void Add(W item)\n {\n item.C = this;\n _contents.Add(item);\n }\n}\n" }, { "answer_id": 249189, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 1, "selected": false, "text": "public void AddToContents(W content);\n{ \n if(content.Container!=null) content.Container.RemoveFromContents(content);\n content.Container = this;\n _contentsW.Add(content);\n}\n" }, { "answer_id": 249201, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "public class Parent {\n public string Name { get; set; }\n public IList<Child> Children { get { return ChildrenBidi; } set { ChildrenBidi.Set(value); } }\n private BidiChildList<Child, Parent> ChildrenBidi { get {\n return BidiChildList.Create(this, p => p._Children, c => c._Parent, (c, p) => c._Parent = p);\n } }\n internal IList<Child> _Children = new List<Child>();\n}\n\npublic class Child {\n public string Name { get; set; }\n public Parent Parent { get { return ParentBidi.Get(); } set { ParentBidi.Set(value); } }\n private BidiParent<Child, Parent> ParentBidi { get {\n return BidiParent.Create(this, p => p._Children, () => _Parent, p => _Parent = p);\n } }\n internal Parent _Parent = null;\n}\n BidiParent<C, P> BidiChildList<C, P> IList<C>" }, { "answer_id": 249202, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": true, "text": "class C\n{\n // Don't to expose this publicly so that \n // no one can get behind your back and change \n // anything\n private List<W> contentsW; \n\n public void Add(W theW)\n {\n theW.Container = this;\n }\n\n public void Remove(W theW)\n {\n theW.Container = null;\n }\n\n #region Only to be used by W\n internal void RemoveW(W theW)\n {\n // do nothing if C does not contain W\n if (!contentsW.Contains(theW))\n return; // or throw an exception if you consider this illegal\n contentsW.Remove(theW);\n }\n\n internal void AddW(W theW)\n {\n if (!contentW.Contains(theW))\n contentsW.Add(theW);\n }\n #endregion\n}\n\nclass W\n{\n private C containerC;\n\n public Container Container\n {\n get { return containerC; }\n set \n { \n if (containerC != null)\n containerC.RemoveW(this);\n containerC = value; \n if (containerC != null)\n containerC.AddW(this);\n }\n }\n}\n List<W> W1.Container = C1;\nW2.Container = C2;\n W2.Container = C1;\n W2.Container = null;\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18542/" ]
249,185
<p>I have a two-level hierarchy displayed in a WPF TreeView, but I only want the child nodes to be selectable - basically the top level nodes are for categorisation but shouldn't be selectable by themselves. </p> <p>Can I achieve this?</p> <p>Thanks...</p>
[ { "answer_id": 1187203, "author": "Rob Fonseca-Ensor", "author_id": 21433, "author_profile": "https://Stackoverflow.com/users/21433", "pm_score": 0, "selected": false, "text": "public class TreeViewItemHelper\n{\n public static bool GetIsSelectable(TreeViewItem obj)\n {\n return (bool)obj.GetValue(IsSelectableProperty);\n }\n\n public static void SetIsSelectable(TreeViewItem obj, bool value)\n {\n obj.SetValue(IsSelectableProperty, value);\n }\n\n public static readonly DependencyProperty IsSelectableProperty =\n DependencyProperty.RegisterAttached(\"IsSelectable\", typeof(bool), typeof(TreeViewItemHelper), new UIPropertyMetadata(true, IsSelectablePropertyChangedCallback));\n\n private static void IsSelectablePropertyChangedCallback(DependencyObject o, DependencyPropertyChangedEventArgs args)\n {\n TreeViewItem i = (TreeViewItem) o;\n i.Selected -= OnSelected;\n if(!GetIsSelectable(i))\n {\n i.Selected += OnSelected;\n }\n }\n\n private static void OnSelected(object sender, RoutedEventArgs args)\n {\n if(sender==args.Source)\n {\n TreeViewItem i = (TreeViewItem)sender;\n i.IsSelected = false;\n }\n }\n}\n" }, { "answer_id": 52870032, "author": "Ravid Goldenberg", "author_id": 2363706, "author_profile": "https://Stackoverflow.com/users/2363706", "pm_score": 0, "selected": false, "text": "<TreeView Name=\"MyTreeView>\n <TreeView.ItemContainerStyle>\n <Style TargetType=\"{x:Type TreeViewItem}\">\n <Style.Triggers>\n <Trigger Property=\"HasItems\" Value=\"true\">\n <Setter Property=\"Focusable\" Value=\"False\" />\n </Trigger>\n </Style.Triggers>\n </Style>\n </TreeView.ItemContainerStyle>\n</TreeView>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14537/" ]
249,188
<p>What's the most elegant way of implementing a DropDownList in <code>ASP.NET</code> that is editable without using 3rd party components.</p> <p>As a last resort I will probably try using a <code>TextBox</code> with an <code>AutoCompleteExtender</code> with an image to 'drop down' the list; or a <code>TextBox</code> overlapping a HTML Select with some JavaScript to fill values from the Select to the <code>TextBox</code>. But I'm really hoping there is a more terse and maintainable solution.</p> <p>Thanks in advance.</p>
[ { "answer_id": 1592106, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 3, "selected": false, "text": "<script language=\"javascript\" type=\"text/javascript\">\n\nfunction DisplayText()\n{\n var textboxId = '<% = txtDisplay.ClientID %>';\n var comboBoxId = '<% = ddSelect.ClientID %>';\n document.getElementById(textboxId).value = document.getElementById(comboBoxId).value;\n document.getElementById(textboxId).focus();\n}\n</script> \n\n<asp:TextBox style=\"width:120px;position:absolute\" ID=\"txtDisplay\" runat=\"server\"></asp:TextBox>\n\n<asp:DropDownList ID=\"ddSelect\" style=\"width:140px\" runat=\"server\"> \n <asp:ListItem Value=\"test1\" >test1</asp:ListItem> \n <asp:ListItem Value=\"test2\">test2</asp:ListItem> \n</asp:DropDownList>\n protected void Page_Load(object sender, EventArgs e)\n{\n ddSelect.Attributes.Add(\"onChange\", \"DisplayText();\");\n}\n function DisplayText_<% = ClientID %>(){...}\n /// ...\nddSelect.Attributes.Add(\"onChange\", \"DisplayText_\" + ClientID + \"();\");\n///..\n" }, { "answer_id": 4961218, "author": "Carlos", "author_id": 611897, "author_profile": "https://Stackoverflow.com/users/611897", "pm_score": 1, "selected": false, "text": "ajaxToolkit:ComboBox ID=ComboBox1 runat=server AutoPostBack=False \n DropDownStyle=DropDown AutoCompleteMode=Suggest \n CaseSensitive=False ItemInsertLocation=\"OrdinalText\" \n" }, { "answer_id": 42574573, "author": "ArthurG", "author_id": 5915783, "author_profile": "https://Stackoverflow.com/users/5915783", "pm_score": 2, "selected": false, "text": "<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head runat=\"server\">\n <title></title>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"></script>\n\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\" rel=\"stylesheet\" />\n <link href=\"https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\" rel=\"stylesheet\" />\n\n <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src=\"https://code.jquery.com/ui/1.11.4/jquery-ui.js\"></script>\n <link href=\"https://jqueryui.com/resources/demos/style.css\" rel=\"stylesheet\" />\n <style>\n .custom-combobox {\n position: relative;\n display: inline-block;\n }\n .custom-combobox-toggle {\n position: absolute;\n top: 0;\n bottom: 0;\n margin-left: -1px;\n padding: 0;\n }\n .custom-combobox-input {\n margin: 0;\n padding: 5px 10px;\n }\n .ui-state-default,\n .ui-widget-content .ui-state-default,\n .ui-widget-header .ui-state-default {\n border: 1px solid #421D1D;\n background: #ffffff url(\"images/ui-bg_glass_75_e6e6e6_1x400.png\") 50% 50% repeat-x !important;\n font-weight: normal;\n color: #555555;\n }\n /* Corner radius */\n .ui-corner-all,\n .ui-corner-top,\n .ui-corner-left,\n .ui-corner-tl {\n border-top-left-radius: 0px !important;\n }\n .ui-corner-all,\n .ui-corner-top,\n .ui-corner-right,\n .ui-corner-tr {\n border-top-right-radius: 0px !important;\n }\n .ui-corner-all,\n .ui-corner-bottom,\n .ui-corner-left,\n .ui-corner-bl {\n border-bottom-left-radius: 0px !important;\n }\n .ui-corner-all,\n .ui-corner-bottom,\n .ui-corner-right,\n .ui-corner-br {\n border-bottom-right-radius: 0px !important;\n }\n </style>\n <script>\n (function($) {\n $.widget(\"custom.combobox\", {\n _create: function() {\n this.wrapper = $(\"<span>\")\n .addClass(\"custom-combobox\")\n .insertAfter(this.element);\n\n this.element.hide();\n this._createAutocomplete();\n this._createShowAllButton();\n },\n\n _createAutocomplete: function() {\n var selected = this.element.children(\":selected\"),\n value = selected.val() ? selected.text() : \"\";\n\n this.input = $(\"<input>\")\n .appendTo(this.wrapper)\n .val(value)\n .attr(\"title\", \"\")\n .addClass(\"custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left\")\n .autocomplete({\n delay: 0,\n minLength: 0,\n source: $.proxy(this, \"_source\")\n })\n .tooltip({\n tooltipClass: \"ui-state-highlight\"\n });\n\n this._on(this.input, {\n autocompleteselect: function(event, ui) {\n ui.item.option.selected = true;\n this._trigger(\"select\", event, {\n item: ui.item.option\n });\n },\n\n autocompletechange: \"_removeIfInvalid\"\n });\n },\n\n _createShowAllButton: function() {\n var input = this.input,\n wasOpen = false;\n\n $(\"<a>\")\n .attr(\"tabIndex\", -1)\n .attr(\"title\", \"Show All Items\")\n .tooltip()\n .appendTo(this.wrapper)\n .button({\n icons: {\n primary: \"ui-icon-triangle-1-s\"\n\n },\n text: false\n })\n .removeClass(\"ui-corner-all\")\n .addClass(\"custom-combobox-toggle ui-corner-right\")\n .mousedown(function() {\n wasOpen = input.autocomplete(\"widget\").is(\":visible\");\n })\n .click(function() {\n input.focus();\n\n // Close if already visible\n if (wasOpen) {\n return;\n }\n\n // Pass empty string as value to search for, displaying all results\n input.autocomplete(\"search\", \"\");\n });\n },\n\n _source: function(request, response) {\n var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), \"i\");\n response(this.element.children(\"option\").map(function() {\n var text = $(this).text();\n if (this.value && (!request.term || matcher.test(text)))\n return {\n label: text,\n value: text,\n option: this\n };\n }));\n },\n\n _removeIfInvalid: function(event, ui) {\n\n // Selected an item, nothing to do\n if (ui.item) {\n return;\n }\n\n // Search for a match (case-insensitive)\n var value = this.input.val(),\n valueLowerCase = value.toLowerCase(),\n valid = false;\n this.element.children(\"option\").each(function() {\n if ($(this).text().toLowerCase() === valueLowerCase) {\n this.selected = valid = true;\n return false;\n }\n });\n\n // Found a match, nothing to do\n if (valid) {\n return;\n }\n\n // Remove invalid value\n this.input\n .val(\"\")\n .attr(\"title\", value + \" didn't match any item\")\n .tooltip(\"open\");\n this.element.val(\"\");\n this._delay(function() {\n this.input.tooltip(\"close\").attr(\"title\", \"\");\n }, 2500);\n this.input.autocomplete(\"instance\").term = \"\";\n },\n\n _destroy: function() {\n this.wrapper.remove();\n this.element.show();\n }\n });\n })(jQuery);\n\n $(function() {\n $(\"#combobox\").combobox();\n $(\"#toggle\").click(function() {\n $(\"#combobox\").toggle();\n });\n });\n </script>\n</head>\n\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <div class=\"ui-widget\">\n <select id=\"combobox\" class=\"form-control\">\n <option value=\"\">Select your option</option>\n <option value=\"Apple\">Apple</option>\n <option value=\"Banana\">Banana</option>\n <option value=\"Cherry\">Cherry</option>\n <option value=\"Date\">Date</option>\n <option value=\"Fig\">Fig</option>\n <option value=\"Grape\">Grape</option>\n <option value=\"Kiwi\">Kiwi</option>\n <option value=\"Mango\">Mango</option>\n <option value=\"Orange\">Orange</option>\n <option value=\"Pumpkin\">Pumpkin</option>\n <option value=\"Strawberry\">Strawberry</option>\n <option value=\"Tomato\">Tomato</option>\n <option value=\"Watermelon\">Watermelon</option>\n </select>\n </div>\n\n </div>\n </form>\n</body>\n\n</html>" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ]
249,192
<p>How can you programmatically tell an HTML <code>select</code> to drop down (for example, due to mouseover)?</p>
[ { "answer_id": 249219, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "<select onMouseOut=\"this.size=1;\" onMouseOver=\"this.size=this.length;\">\n <option>1</option>\n <option>2</option>\n <option>3</option>\n <option>4</option>\n <option>5</option>\n</select>" }, { "answer_id": 5093671, "author": "sproketboy", "author_id": 53069, "author_profile": "https://Stackoverflow.com/users/53069", "pm_score": 2, "selected": false, "text": "<button id=\"optionsButton\" style=\"position:absolute;top:10px;left:10px;height:22px;width:100px;z-index:10\" onclick=\"doClick()\">OPTIONS</button>\n<select id=\"optionsSelect\" style=\"position:absolute;top:10px;left:10px;height:20px;width:100px;z-index:9\">\n <option>ABC</option>\n <option>DEF</option>\n <option>GHI</option>\n <option>JKL</option>\n</select>\n<script type=\"text/javascript\">\n function doClick() {\n optionsSelect.focus();\n var WshShell = new ActiveXObject(\"WScript.Shell\");\n WshShell.SendKeys(\"%{DOWN}\");\n }\n</script>\n" }, { "answer_id": 10125485, "author": "Rob3C", "author_id": 6343, "author_profile": "https://Stackoverflow.com/users/6343", "pm_score": 0, "selected": false, "text": "$('#cboSomething')[0].size = 3;\n$('#cboSomething')[0].focus();\n" }, { "answer_id": 10136523, "author": "Xavier Ho", "author_id": 319952, "author_profile": "https://Stackoverflow.com/users/319952", "pm_score": 7, "selected": false, "text": "<select> <option> document.createEvent() .dispatchEvent() <select id=\"dropdown\">\n <option value=\"Red\">Red</option>\n <option value=\"Green\">Green</option>\n <option value=\"Blue\">Blue</option>\n</select>\n<br>\n<button id=\"fire\" type=\"button\" onclick=\"runThis()\">Show dropdown items</button>​\n // <select> element displays its options on mousedown, not click.\nshowDropdown = function (element) {\n var event;\n event = document.createEvent('MouseEvents');\n event.initMouseEvent('mousedown', true, true, window);\n element.dispatchEvent(event);\n};\n\n// This isn't magic.\nwindow.runThis = function () { \n var dropdown = document.getElementById('dropdown');\n showDropdown(dropdown);\n};\n" }, { "answer_id": 19913859, "author": "Paulo Roberto Rosa", "author_id": 2319589, "author_profile": "https://Stackoverflow.com/users/2319589", "pm_score": 2, "selected": false, "text": "ExpandSelect(MySelect)\n" }, { "answer_id": 22906784, "author": "Hemant_Negi", "author_id": 2488550, "author_profile": "https://Stackoverflow.com/users/2488550", "pm_score": 3, "selected": false, "text": "<select id=\"dropdown\">\n <option value=\"Red\">Red</option>\n <option value=\"Green\">Green</option>\n <option value=\"Blue\">Blue</option>\n</select>\n<br>\n<button id=\"fire\" type=\"button\" >Show dropdown items</button>\n var is_visible=false; \n\n$(document).ready(function(){\n\n $('#fire').click(function (e) { \n var element = document.getElementById('dropdown');\n\n\n if(is_visible){is_visible=false; return;}\n is_visible = true;\n\n var event;\n event = document.createEvent('MouseEvents');\n event.initMouseEvent('mousedown', true, true, window);\n element.dispatchEvent(event);\n\n /* can be added for i.e. compatiblity.\n optionsSelect.focus();\n var WshShell = new ActiveXObject(\"WScript.Shell\");\n WshShell.SendKeys(\"%{DOWN}\");\n */\n e.stopPropagation();\n return false;\n});\n\n\n$(document).click(function(){is_visible=false; });\n});\n" }, { "answer_id": 39635285, "author": "Asim K T", "author_id": 4015856, "author_profile": "https://Stackoverflow.com/users/4015856", "pm_score": 6, "selected": false, "text": "mousedown dispatchEvent" }, { "answer_id": 50378960, "author": "Rafael Umbelino", "author_id": 5480181, "author_profile": "https://Stackoverflow.com/users/5480181", "pm_score": 5, "selected": false, "text": "<select> opacity: 0; <select> <select> select{\n opacity: 0;\n position: absolute;\n} <select>\n <option>option 1</option>\n <option>option 2</option>\n <option>option 3</option>\n</select>\n<button>click</button>" }, { "answer_id": 59301461, "author": "Kasra Ebrahimi", "author_id": 11967384, "author_profile": "https://Stackoverflow.com/users/11967384", "pm_score": 0, "selected": false, "text": "$('#target-select').select2('open');\n" }, { "answer_id": 68036061, "author": "Caleb Hillary", "author_id": 9523121, "author_profile": "https://Stackoverflow.com/users/9523121", "pm_score": 2, "selected": false, "text": "var SelectionWrapper = function(element, maxSize, selectCb) {\n\n var preventDefault = function(e) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n var isOpen = false;\n\n var open = function() {\n if (!isOpen) {\n element.size = maxSize;\n // Remove prevent default so that user will be able to select the option\n // Check why we prevent it in the first place below\n element.removeEventListener('mousedown', preventDefault);\n // We focus so that we can close on blur.\n element.focus();\n isOpen = true;\n }\n };\n\n var close = function() {\n if (isOpen) {\n element.size = 1;\n // Prevent default so that the default select box open behaviour is muted.\n element.addEventListener('mousedown', preventDefault);\n isOpen = false;\n }\n };\n\n // For the reason above\n element.addEventListener('mousedown', preventDefault);\n\n // So that clicking elsewhere closes the box\n element.addEventListener('blur', close);\n\n // Toggle when click\n element.addEventListener('click', function(e) {\n if (isOpen) {\n close();\n // Call ballback if present\n if(selectCb) {\n selectCb(element.value);\n }\n } else {\n open();\n }\n });\n\n\n return {\n open: open,\n close: close\n };\n};\n\n// Usage\nvar selectionWrapper = SelectionWrapper(document.getElementById(\"select_element\"), 7, function(value) {\n var para = document.createElement(\"DIV\");\n para.textContent = \"Selected option: \" + value;\n document.getElementById(\"result\").appendChild(para);\n});\n\ndocument.getElementById(\"trigger\").addEventListener('click', function() {\n selectionWrapper.open();\n});\n" }, { "answer_id": 69569729, "author": "Mykola Uspalenko", "author_id": 8413306, "author_profile": "https://Stackoverflow.com/users/8413306", "pm_score": 1, "selected": false, "text": "<div>DIV example: <select id=\"dropdownDiv\">\n <option value=\"Alpha\">Alpha</option>\n <option value=\"Beta\">Beta</option>\n <option value=\"Gamma\">Gamma</option>\n </select>\n</div>\n\n<table id='tab1'>\n<tr><td>Empty Cell</td></tr>\n<tr><td> <select id=\"dropdown1\">\n <option value=\"Red\">Red</option>\n <option value=\"Green\">Green</option>\n <option value=\"Blue\">Blue</option>\n </select>\n</td>\n<tr><td><select id=\"dropdown2\">\n<option value=\"1\">1</option><option value=\"2\">2</option><option value=\"3\">3</option><option value=\"4\">4</option><option value=\"5\">5</option><option value=\"6\">6</option><option value=\"7\">7</option><option value=\"8\">8</option><option value=\"9\">9</option><option value=\"10\">10</option><option value=\"11\">11</option><option value=\"12\">12</option><option value=\"13\">13</option><option value=\"14\">14</option><option value=\"15\">15</option><option value=\"15\">1</option><option value=\"16\">16</option><option value=\"17\">17</option><option value=\"18\">18</option><option value=\"19\">19</option><option value=\"20\">20</option><option value=\"21\">21</option></select>\n</td></tr>\n<tr><td>Empty Cell</td></tr></table>\n<br><button id=\"fire\" type=\"button\" onclick=\"openDropdown('dropdownDiv', this)\" >Show dropdownDiv items</button>\n<button id=\"fire\" type=\"button\" onclick=\"openDropdown('dropdown1', this)\" >Show dropdown1 items</button>\n<button id=\"fire\" type=\"button\" onclick=\"openDropdown('dropdown2', this)\" >Show dropdown2 items</button>\n var lastClosedElem = null;\n var maxItemsInDropDown = 12;\n function openDropdown(elementId, opener)\n {\n if (lastClosedElem !== null && lastClosedElem === opener)\n {\n lastClosedElem = null;\n return;\n }\n lastClosedElem = opener;\n \n function down()\n {\n var $this = $(this);\n\n var td = $this.closest('td,div');\n if (td && td.length > 0)\n td.height(td.height());\n\n var pos = $this.offset();\n var len = $this.find(\"option\").length;\n if (len > 1 && len < maxItemsInDropDown)\n {\n $this.addClass('no-scroll');\n $this.addClass('noArrow');\n }\n else if (len > maxItemsInDropDown)\n {\n len = maxItemsInDropDown;\n }\n\n $this.css(\"position\", \"absolute\");\n\n var _zIndex = $this.css(\"zIndex\");\n if (!_zIndex)\n _zIndex = 'auto';\n $this.attr(\"_zIndex\", _zIndex);\n $this.css(\"zIndex\", 9999);\n\n $this.attr(\"size\", len); // open dropdown\n $this.unbind(\"focus\", down);\n $this.focus();\n }\n\n var up = function()\n {\n var $this = $(this);\n $this.css(\"position\", \"static\");\n $this.attr(\"size\", \"1\");\n $this.removeClass('no-scroll');\n $this.removeClass('noArrow');\n\n var _zIndex = $this.attr(\"zIndex\");\n if (_zIndex)\n {\n $this.css(\"zIndex\", _zIndex);\n }\n $this.unbind(\"blur\", up);\n $this.unbind(\"click\", upClick);\n $this.focus();\n }\n\n function upClick(e)\n {\n up.call(this);\n lastClosedElem = null;\n }\n\n $(\"#\" + elementId).focus(down).blur(up).click(upClick).trigger('focus');\n }\n .no-scroll { cursor: pointer;}\n.no-scroll::-webkit-scrollbar {display:none;}\n.no-scroll::-moz-scrollbar {display:none;}\n.no-scroll::-o-scrollbar {display:none;}\n.no-scroll::-google-ms-scrollbar {display:none;}\n.no-scroll::-khtml-scrollbar {display:none;}\n\n\n.noArrow {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n padding-left: 3px;\n padding-right: 3px;\n}\n\n\n/* Cosmetic styles */\n#tab1 tbody tr:nth-child(even) > td, div\n{ background: linear-gradient( 180deg, #efefef 1%, #eeeeee 15%, #e2e2e2 85%); \n}\n \n#tab1 tbody tr td\n{ padding: 4px; \n}\n \n#tab1\n{ border: 1px solid silver; \n}\n" }, { "answer_id": 72014137, "author": "Jeroen Bellemans", "author_id": 4118983, "author_profile": "https://Stackoverflow.com/users/4118983", "pm_score": -1, "selected": false, "text": "<span onclick=\"openDropdown();\">Open dropdown</span>\n <select class=\"dropdown\">\n <option value=\"A\">Value A</option>\n <option value=\"B\">Value B</option>\n <option value=\"C\">Value C</option>\n</select>\n document.querySelector('.dropdown').focus();\n" }, { "answer_id": 72780752, "author": "Nayteruz", "author_id": 12478599, "author_profile": "https://Stackoverflow.com/users/12478599", "pm_score": -1, "selected": false, "text": "let elSelected = null;\nfunction bindSelectClick(el){\n if(el.target !== elSelected){\n $(elSelected).trigger('blur');\n $(document).unbind('click', bindSelectClick)\n }\n}\n\n$('select.shared_date').on('focus', function (){\n // do something\n elSelected = this;\n $(document).on('click', bindSelectClick)\n\n}).on('blur', function (){\n // do something\n}).on('change', function (){\n // do something\n})\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
249,200
<p>I need a webserver to serve up very simple POST/GET requests as JSON. I don't need MVC, Rails, Django. I need something that takes up very little memory, preferrably around 5K per reqeust. The webserver will talk to backend services like Scribe using Facebook Thrift. Each http request will also access a SQLLite database, one for each user and user's data do not overlap. It will serve up static html files as well as the json webservice.</p> <p>I am considering the following:</p> <ul> <li>Njinx with PHP,</li> <li>Kepler from Lua,</li> <li>rolling my own with libevent or libev perhaps calling out to Lua, or</li> <li>MochiWeb.</li> </ul> <p>Which of these options are best and what other options are out there? I can use PHP, python, or Lua for basic scripting and even could do basic C. I am leaning towards some sort of Erlang solution.</p>
[ { "answer_id": 12701985, "author": "valenok", "author_id": 49889, "author_profile": "https://Stackoverflow.com/users/49889", "pm_score": 2, "selected": false, "text": "#define MAX_REQUEST_SIZE 16384" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
249,222
<p>I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as <code>Console</code>.</p> <p>For example, if I want to add an extension to <code>Console</code>, called '<code>WriteBlueLine</code>', so that I can go:</p> <pre><code>Console.WriteBlueLine(&quot;This text is blue&quot;); </code></pre> <p>I tried this by adding a local, public static method, with <code>Console</code> as a '<code>this</code>' parameter... but no dice!</p> <pre><code>public static class Helpers { public static void WriteBlueLine(this Console c, string text) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(text); Console.ResetColor(); } } </code></pre> <p>This didn't add a '<code>WriteBlueLine</code>' method to <code>Console</code>... am I doing it wrong? Or asking for the impossible?</p>
[ { "answer_id": 249234, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": false, "text": "this ." }, { "answer_id": 309414, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 9, "selected": true, "text": "ConfigurationManager public static class ConfigurationManagerWrapper\n {\n public static ConfigurationSection GetSection( string name )\n {\n return ConfigurationManager.GetSection( name );\n }\n\n .....\n\n public static ConfigurationSection GetWidgetSection()\n {\n return GetSection( \"widgets\" );\n }\n }\n" }, { "answer_id": 435617, "author": "Tom Deloford", "author_id": 53541, "author_profile": "https://Stackoverflow.com/users/53541", "pm_score": 6, "selected": false, "text": "AreEqual(x1,x2)" }, { "answer_id": 2018165, "author": "Pag Sun", "author_id": 161849, "author_profile": "https://Stackoverflow.com/users/161849", "pm_score": 4, "selected": false, "text": "using CLRConsole = System.Console;\n\nnamespace ExtensionMethodsDemo\n{\n public static class Console\n {\n public static void WriteLine(string value)\n {\n CLRConsole.WriteLine(value);\n }\n\n public static void WriteBlueLine(string value)\n {\n System.ConsoleColor currentColor = CLRConsole.ForegroundColor;\n\n CLRConsole.ForegroundColor = System.ConsoleColor.Blue;\n CLRConsole.WriteLine(value);\n\n CLRConsole.ForegroundColor = currentColor;\n }\n\n public static System.ConsoleKeyInfo ReadKey(bool intercept)\n {\n return CLRConsole.ReadKey(intercept);\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n try\n {\n Console.WriteBlueLine(\"This text is blue\"); \n }\n catch (System.Exception ex)\n {\n Console.WriteLine(ex.Message);\n Console.WriteLine(ex.StackTrace);\n }\n\n Console.WriteLine(\"Press any key to continue...\");\n Console.ReadKey(true);\n }\n }\n}\n" }, { "answer_id": 3718699, "author": "Tenaka", "author_id": 448533, "author_profile": "https://Stackoverflow.com/users/448533", "pm_score": -1, "selected": false, "text": "Console myConsole = null;\nmyConsole.WriteBlueLine(\"my blue line\");\n\npublic static class Helpers {\n public static void WriteBlueLine(this Console c, string text)\n {\n Console.ForegroundColor = ConsoleColor.Blue;\n Console.WriteLine(text);\n Console.ResetColor();\n }\n}\n" }, { "answer_id": 5451709, "author": "Mr. Obnoxious", "author_id": 679260, "author_profile": "https://Stackoverflow.com/users/679260", "pm_score": 7, "selected": false, "text": "public static class Extensions\n{\n public static T Create<T>(this T @this)\n where T : class, new()\n {\n return Utility<T>.Create();\n }\n}\n\npublic static class Utility<T>\n where T : class, new()\n{\n static Utility()\n {\n Create = Expression.Lambda<Func<T>>(Expression.New(typeof(T).GetConstructor(Type.EmptyTypes))).Compile();\n }\n public static Func<T> Create { get; private set; }\n}\n var ds1 = (null as DataSet).Create(); // as oppose to DataSet.Create()\n // or\n DataSet ds2 = null;\n ds2 = ds2.Create();\n\n // using some of the techniques above you could have this:\n (null as Console).WriteBlueLine(...); // as oppose to Console.WriteBlueLine(...)\n" }, { "answer_id": 8825516, "author": "Brian Griffin", "author_id": 1143998, "author_profile": "https://Stackoverflow.com/users/1143998", "pm_score": 3, "selected": false, "text": "System.Collections.ArrayList _al = new System.Collections.ArrayList();\nSystem.Collections.ArrayList _al2 = (System.Collections.ArrayList)System.Activator.CreateInstance(typeof(System.Collections.ArrayList));\n .locals init ([0] class [mscorlib]System.Collections.ArrayList _al,\n [1] class [mscorlib]System.Collections.ArrayList _al2)\n IL_0001: newobj instance void [mscorlib]System.Collections.ArrayList::.ctor()\n IL_0006: stloc.0\n IL_0007: ldtoken [mscorlib]System.Collections.ArrayList\n IL_000c: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)\n IL_0011: call object [mscorlib]System.Activator::CreateInstance(class [mscorlib]System.Type)\n IL_0016: castclass [mscorlib]System.Collections.ArrayList\n IL_001b: stloc.1\n" }, { "answer_id": 26831158, "author": "Black Dog", "author_id": 4232349, "author_profile": "https://Stackoverflow.com/users/4232349", "pm_score": 1, "selected": false, "text": "public class DataSet : System.Data.DataSet\n{\n public static void SpecialMethod() { }\n}\n public static class Console\n{ \n public static void WriteLine(String x)\n { System.Console.WriteLine(x); }\n\n public static void WriteBlueLine(String x)\n {\n System.Console.ForegroundColor = ConsoleColor.Blue;\n System.Console.Write(.x); \n }\n}\n public static void WriteLine(String x)\n { System.Console.WriteLine(x.Replace(\"Fck\",\"****\")); }\n public static void WriteLine(String x)\n {\n System.Console.ForegroundColor = ConsoleColor.Blue;\n System.Console.WriteLine(x); \n }\n" }, { "answer_id": 33843065, "author": "André C. Andersen", "author_id": 604048, "author_profile": "https://Stackoverflow.com/users/604048", "pm_score": 2, "selected": false, "text": "ConfigurationManager ... public static class ConfigurationManagerWrapper\n{\n public static NameValueCollection AppSettings\n {\n get { return ConfigurationManager.AppSettings; }\n }\n\n public static ConnectionStringSettingsCollection ConnectionStrings\n {\n get { return ConfigurationManager.ConnectionStrings; }\n }\n\n public static object GetSection(string sectionName)\n {\n return ConfigurationManager.GetSection(sectionName);\n }\n\n public static Configuration OpenExeConfiguration(string exePath)\n {\n return ConfigurationManager.OpenExeConfiguration(exePath);\n }\n\n public static Configuration OpenMachineConfiguration()\n {\n return ConfigurationManager.OpenMachineConfiguration();\n }\n\n public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel)\n {\n return ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel);\n }\n\n public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)\n {\n return ConfigurationManager.OpenMappedMachineConfiguration(fileMap);\n }\n\n public static void RefreshSection(string sectionName)\n {\n ConfigurationManager.RefreshSection(sectionName);\n }\n}\n" }, { "answer_id": 44237464, "author": "Wouter", "author_id": 4491768, "author_profile": "https://Stackoverflow.com/users/4491768", "pm_score": 1, "selected": false, "text": "public static class YoutTypeExtensionExample\n{\n public static void Example()\n {\n ((YourType)null).ExtensionMethod();\n }\n}\n public static class YourTypeExtension\n{\n public static void ExtensionMethod(this YourType x) { }\n}\n public class YourType { }\n" }, { "answer_id": 44311302, "author": "Adel G.Eibesh", "author_id": 2533597, "author_profile": "https://Stackoverflow.com/users/2533597", "pm_score": 5, "selected": false, "text": "public static class Helpers\n{\n public static void WriteLine(this ConsoleColor color, string text)\n {\n Console.ForegroundColor = color;\n Console.WriteLine(text);\n Console.ResetColor();\n }\n}\n ConsoleColor.Cyan.WriteLine(\"voilà\");\n" }, { "answer_id": 51805734, "author": "Douglas Potesta", "author_id": 8309567, "author_profile": "https://Stackoverflow.com/users/8309567", "pm_score": 2, "selected": false, "text": "using FooConsole = System.Console;\n\npublic static class Console\n{\n public static void WriteBlueLine(string text)\n {\n FooConsole.ForegroundColor = ConsoleColor.Blue;\n FooConsole.WriteLine(text);\n FooConsole.ResetColor();\n }\n}\n using FooConsole = System.Console;\n\npublic static class Console\n{\n public static void WriteBlueLine(string text)\n {\n FooConsole.ForegroundColor = ConsoleColor.Blue;\n FooConsole.WriteLine(text);\n FooConsole.ResetColor();\n }\n public static void WriteLine(string text)\n {\n FooConsole.WriteLine(text);\n }\n...etc.\n}\n" }, { "answer_id": 70163411, "author": "Gourav", "author_id": 17547632, "author_profile": "https://Stackoverflow.com/users/17547632", "pm_score": 0, "selected": false, "text": "public static class ConfigurationManagerWrapper\n {\n public static ConfigurationSection GetSection( string name )\n {\n return ConfigurationManager.GetSection( name );\n }\n\n .....\n\n public static ConfigurationSection GetWidgetSection()\n {\n return GetSection( \"widgets\" );\n }\n }\n" }, { "answer_id": 70903871, "author": "Amal K", "author_id": 11455105, "author_profile": "https://Stackoverflow.com/users/11455105", "pm_score": 0, "selected": false, "text": "Console Write() WriteLine() Console.Out.Write() Console.Out.WriteLine() Out TextWriter TextWriter public static class ConsoleTextWriterExtensions\n{\n public static void WriteBlueLine(this TextWriter writer, string text)\n {\n Console.ForegroundColor = ConsoleColor.Blue;\n writer.WriteLine(text);\n Console.ResetColor();\n }\n\n public static void WriteUppercase(this TextWriter writer, string text)\n {\n writer.Write(text.ToUpper());\n }\n}\n Console.Out.WriteBlueLine();\n Console.Error TextWriter Console.Error Console.Error.WriteBlueLine();\n WriteTable() TextWriter using static Console Console. using static System.Console;\n\nOut.WriteBlueLine(\"A blue line\");\nError.WriteBlueLine(\"A blue line\");\n" }, { "answer_id": 71372621, "author": "Clark Kent", "author_id": 8680581, "author_profile": "https://Stackoverflow.com/users/8680581", "pm_score": 1, "selected": false, "text": "using System;\n\nnamespace HelloWorld\n{\n public static class console_extensions {\n public static void EXTENSION(this object item) {\n System.Console.WriteLine(\"HELLO THERE!\");\n }\n }\n \n public class Program\n {\n public static void Main(string[] args)\n {\n Console.WriteLine(\"Hello, World!\");\n Console.EXTENSION();\n ((Console)null).EXTENSION();\n Console l = new Console();\n l.EXTENSION();\n }\n }\n}\n Compilation failed: 4 error(s), 0 warnings\n\nHelloWorld.cs(16,12): error CS0117: `System.Console' does not contain a definition for `EXTENSION'\n/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)\nHelloWorld.cs(17,5): error CS0716: Cannot convert to static type `System.Console'\nHelloWorld.cs(18,4): error CS0723: `l': cannot declare variables of static types\n/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)\nHelloWorld.cs(18,16): error CS0712: Cannot create an instance of the static class `System.Console'\n/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)\n null using System;\n\nnamespace HelloWorld\n{\n public static class static_extensions {\n public static void print(this object item, int data = 0) {\n Console.WriteLine(\"EXT: I AM A STATIC EXTENSION!\");\n Console.WriteLine(\"EXT: MY ITEM IS: \" + item);\n Console.WriteLine(\"EXT: MY DATA IS: \" + data);\n string i;\n if (item == null) {\n i = \"null\";\n } else {\n i = item.GetType().Name;\n }\n Console.WriteLine(\"EXT: MY TYPE IS: \" + i + \"\\n\");\n }\n }\n\n public class Program\n {\n \n public static void Main(string[] args)\n {\n // an extension method can be\n // called directly\n // (null is an instance)\n static_extensions.print(null);\n\n // an extension method can also be\n // called directly with arguments\n // (null is an instance)\n static_extensions.print(null, 1);\n \n // an extension method can also be\n // called as part of an instance\n int x = 0; // initialize int\n x.print();\n \n // an extension method can also be\n // called as part of an instance\n // and with data\n int x2 = 0; // initialize int\n x2.print(2);\n \n // an extension method can also be\n // called directly from null\n // since `null` is an instance\n ((string)null).print();\n \n // an extension method can also be\n // called directly from null\n // and with data\n // since `null` is an instance\n ((string)null).print(4);\n }\n }\n}\n EXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: \nEXT: MY DATA IS: 0\nEXT: MY TYPE IS: null\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: \nEXT: MY DATA IS: 1\nEXT: MY TYPE IS: null\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: 0\nEXT: MY DATA IS: 0\nEXT: MY TYPE IS: Int32\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: 0\nEXT: MY DATA IS: 2\nEXT: MY TYPE IS: Int32\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: \nEXT: MY DATA IS: 0\nEXT: MY TYPE IS: null\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: \nEXT: MY DATA IS: 4\nEXT: MY TYPE IS: null\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49/" ]
249,251
<p>I found a list of iPhone supported font here<br> <a href="http://daringfireball.net/misc/2007/07/iphone-osx-fonts" rel="nofollow noreferrer">http://daringfireball.net/misc/2007/07/iphone-osx-fonts</a></p> <p>But I just wanted to confirm that, can we use all this fonts in application, or we are restricted to some class of fonts.</p>
[ { "answer_id": 4191797, "author": "rajesh", "author_id": 466768, "author_profile": "https://Stackoverflow.com/users/466768", "pm_score": 5, "selected": false, "text": "NSArray *familyNames = [UIFont familyNames];\n\nfor( NSString *familyName in familyNames ){\n printf( \"Family: %s \\n\", [familyName UTF8String] );\n\n NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];\n for( NSString *fontName in fontNames ){\n printf( \"\\tFont: %s \\n\", [fontName UTF8String] );\n\n }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ]
249,253
<p>I have a script to extract certain data from a much bigger table, with one field in particular changing regularly, e.g.</p> <pre><code>SELECT CASE @Flag WHEN 1 THEN t.field1 WHEN 2 THEN t.field2 WHEN 3 THEN t.field3 END as field, ...[A bunch of other fields] FROM table t </code></pre> <p>However, the issue is now I want to do other processing on the data. I'm trying to figure out the most effective method. I need to have some way of getting the flag through, so I know I'm talking about data sliced by the right field.</p> <p>One possible solution I was playing around with a bit (mostly to see what would happen) is to dump the contents of the script into a table function which has the flag passed to it, and then use a SELECT query on the results of the function. I've managed to get it to work, but it's significantly slower than...</p> <p>The obvious solution, and probably the most efficient use of processor cycles: to create a series of cache tables, one for each of the three flag values. However, the problem then is to find some way of extracting the data from the right cache table to perform the calculation. The obvious, though incorrect, response would be something like</p> <pre><code>SELECT CASE @Flag WHEN 1 THEN table1.field WHEN 2 THEN table2.field WHEN 3 THEN table3.field END as field, ...[The various calculated fields] FROM table1, table2, table3 </code></pre> <p>Unfortunately, as is obvious, this creates a massive cross join - which is not my intended result at all.</p> <p>Does anyone know how to turn that cross join into an "Only look at x table"? (Without use of Dynamic SQL, which makes things hard to deal with?) Or an alternative solution, that's still reasonably speedy?</p> <p>EDIT: Whether it's a good reason or not, the idea I was trying to implement was to not have three largely identical queries, that differ only by table - which would then have to be edited identically whenever a change is made to the logic. Which is why I've avoided the "Have the flag entirely separate" thing thus far...</p>
[ { "answer_id": 249313, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "@Flag" }, { "answer_id": 249344, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "AND @flag = 1\n" }, { "answer_id": 555527, "author": "Margaret", "author_id": 27290, "author_profile": "https://Stackoverflow.com/users/27290", "pm_score": 1, "selected": true, "text": "SELECT CASE @Flag WHEN 1 THEN t.field1 WHEN 2 THEN t.field2 WHEN 3 \n THEN t.field3 END as field,\n [A bunch of other fields],\n @Flag as flag\nFROM table t\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27290/" ]
249,256
<p>I was browsing the <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a> question and thought I would try out one of the features I was unfamiliar with. Unfortunately I use Visual Studio 2005 and the feature in question was introduced later. Is there a good list for new features in C# 3.0 (Visual Studio 2008) vs. C# 2.0 (Visual Studio 2005)? </p>
[ { "answer_id": 249300, "author": "Matt Ephraim", "author_id": 22291, "author_profile": "https://Stackoverflow.com/users/22291", "pm_score": 4, "selected": true, "text": "Person person = new Person();\nperson.Name = \"John Smith\";\n Person person = new Person() { Name = \"John Smith\" };\n List<string> list = new List<string> { \"foo\", \"bar\" }; \n people.Where(delegate(person) { return person.Age >= 21;);\n people.Where(person => person.Age >= 21 );\n public static class StringUtilities\n{\n public static string Pluralize(this word)\n {\n ...\n }\n}\n string word = \"person\";\nword.Pluralize(); // Returns \"people\"\n var book = new { Title: \"...\", Cost: \"...\" };\n" }, { "answer_id": 249380, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 2, "selected": false, "text": "public int Id { get; set; }\n private int _id;\npublic int Id {\n get { return _id; }\n set { _id = value; }\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ]
249,262
<pre><code>'''use Jython''' import shutil print dir(shutil) </code></pre> <p>There is no, shutil.move, how does one move a file with Jython? and while we at it, how does one delete a file with Jython?</p>
[ { "answer_id": 249279, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 3, "selected": true, "text": "os.rename() os.unlink() shutil" }, { "answer_id": 250933, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 1, "selected": false, "text": "shutil.py" }, { "answer_id": 2334425, "author": "David Zhang", "author_id": 281251, "author_profile": "https://Stackoverflow.com/users/281251", "pm_score": 0, "selected": false, "text": "f1 = File(filename_old)\nf1.nameTo(File(filename_new))\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21537/" ]
249,266
<p>I have a large xml document that needs to be processed 100 records at a time</p> <p>It is being done within a Windows Service written in c#. </p> <p>The structure is as follows :</p> <pre><code>&lt;docket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="docket.xsd"&gt; &lt;order&gt; &lt;Date&gt;2008-10-13&lt;/Date&gt; &lt;orderNumber&gt;050758023&lt;/orderNumber&gt; &lt;ParcelID/&gt; &lt;CustomerName&gt;sddsf&lt;/CustomerName&gt; &lt;DeliveryName&gt;dsfd&lt;/DeliveryName&gt; &lt;Address1&gt;sdf&lt;/Address1&gt; &lt;Address2&gt;sdfsdd&lt;/Address2&gt; &lt;Address3&gt;sdfdsfdf&lt;/Address3&gt; &lt;Address4&gt;dffddf&lt;/Address4&gt; &lt;PostCode/&gt; &lt;/order&gt; &lt;order&gt; &lt;Date&gt;2008-10-13&lt;/Date&gt; &lt;orderNumber&gt;050758023&lt;/orderNumber&gt; &lt;ParcelID/&gt; &lt;CustomerName&gt;sddsf&lt;/CustomerName&gt; &lt;DeliveryName&gt;dsfd&lt;/DeliveryName&gt; &lt;Address1&gt;sdf&lt;/Address1&gt; &lt;Address2&gt;sdfsdd&lt;/Address2&gt; &lt;Address3&gt;sdfdsfdf&lt;/Address3&gt; &lt;Address4&gt;dffddf&lt;/Address4&gt; &lt;PostCode/&gt; &lt;/order&gt; ..... ..... &lt;/docket&gt; </code></pre> <p>There could be thousands of orders in a docket.</p> <p>I need to chop this into 100 element chunks</p> <p>However each of the 100 orders still need to be wrapped with the parent "docket" node and have the same namespace etc</p> <p>is this possible? </p>
[ { "answer_id": 249310, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 1, "selected": false, "text": " public List<XDocument> ChunkDocket(XDocument docket, int chunkSize)\n {\n var newDockets = new List<XDocument>();\n var d = new XDocument(docket);\n var orders = d.Root.Elements(\"order\");\n XDocument newDocket = null;\n\n do\n {\n newDocket = new XDocument(new XElement(\"docket\"));\n var chunk = orders.Take(chunkSize);\n newDocket.Root.Add(chunk);\n chunk.Remove();\n newDockets.Add(newDocket);\n } while (orders.Any());\n\n return newDockets;\n }\n" }, { "answer_id": 249408, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 4, "selected": true, "text": " public List<XmlDocument> ChunkDocket(XmlDocument docket, int chunkSize)\n {\n List<XmlDocument> newDockets = new List<XmlDocument>();\n // \n int orderCount = docket.SelectNodes(\"//docket/order\").Count;\n int chunkStart = 0;\n XmlDocument newDocket = null;\n XmlElement root = null;\n XmlNodeList chunk = null;\n\n while (chunkStart < orderCount)\n {\n newDocket = new XmlDocument();\n root = newDocket.CreateElement(\"docket\");\n newDocket.AppendChild(root);\n\n chunk = docket.SelectNodes(String.Format(\"//docket/order[position() > {0} and position() <= {1}]\", chunkStart, chunkStart + chunkSize));\n\n chunkStart += chunkSize;\n\n XmlNode targetNode = null;\n foreach (XmlNode c in chunk)\n {\n targetNode = newDocket.ImportNode(c, true);\n root.AppendChild(targetNode);\n }\n\n newDockets.Add(newDocket);\n } \n\n return newDockets;\n }\n" }, { "answer_id": 249435, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 0, "selected": false, "text": "XmlReader reader = XmlReader.Create(@\"c:\\foo\\Doket.xml\")\nwhile( reader.Read())\n{\n if(reader.LocalName == \"order\")\n {\n // read each child element and its value from the reader.\n // or you can deserialize the order element by using a XmlSerializer and Order class\n } \n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17194/" ]
249,281
<p>We seem to have a few developers here who think creating stored procedures that spit out HTML or Javascript code is a legitimate thing to do. In my mind this is the ultimate abuse of the separation of concerns model. Is doing something like this people have often seen people doing?</p>
[ { "answer_id": 249288, "author": "Matias Nino", "author_id": 17235, "author_profile": "https://Stackoverflow.com/users/17235", "pm_score": 0, "selected": false, "text": "\"<javascriptpopup>[outputuotputoutput]</javascriptpopup>\"\n \"<prettyfont>[outputuotputoutput]</prettyfont>\"\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
249,283
<p>I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the <strong>--no-site-packages</strong> option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.</p> <p>What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?</p>
[ { "answer_id": 249342, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 3, "selected": false, "text": "import sys\n\nsys.path.append(somepath)\n import site\n\nsite.addsitedir(sitedir, known_paths=None)\n" }, { "answer_id": 1670513, "author": "iElectric", "author_id": 133235, "author_profile": "https://Stackoverflow.com/users/133235", "pm_score": 6, "selected": true, "text": "$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv\n$ cd myvirtualenv\n$ source bin/activate\n$ cd lib/python2.6/\n$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/ \n$ ln -s /usr/lib/pymodules/python2.6/pygtk.pth \n$ ln -s /usr/lib/pymodules/python2.6/pygtk.py \n$ ln -s /usr/lib/pymodules/python2.6/cairo/\n$ python\n>>> import pygtk\n>>> import gtk\n" }, { "answer_id": 27471458, "author": "Anthon", "author_id": 1307905, "author_profile": "https://Stackoverflow.com/users/1307905", "pm_score": 0, "selected": false, "text": "tox deps:\n pytest\n ruamel.venvgtk\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
249,296
<p>Why don't we see C-like languages that allow for callables with polymorphism in the return type? I could see how the additional type inference would be a hurdle, but we have <a href="http://en.wikipedia.org/wiki/Type_inference" rel="nofollow noreferrer">plenty of languages</a> with full-fledged type inference systems (that work for varying levels of "work").</p> <p><strong>Edit:</strong> By return type polymorphism I mean overloading the function signature only in the return type. For example, C++ and Java only allow overloading in the type of the formal parameters, not in the return type.</p>
[ { "answer_id": 249341, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 2, "selected": false, "text": "double x = (double)foo();\n" }, { "answer_id": 249439, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "string s = foo(); //foo returns a string\ndouble x = foo(); //foo returns a double\nint i = foo(); //foo returns an integer\nfloat f = (float)(int)foo(); //call the int foo and convert to float\n Animal a = fooFactory(); //fooFactory returns an Animal\nPlant p = fooFactory(); //foofactory returns a Plant\n" }, { "answer_id": 249555, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": false, "text": "typedef char* pchar;\n\nclass MyType\n{\npublic:\n\n operator pchar() { return(ConvertToASCII()); }\n MyType& operator=(char* input) { ConvertFromASCII(input); return(*this); }\n\n pchar ConvertToASCII();\n void ConvertFromASCII(pchar ASCII);\n}\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
249,297
<p>Excuse me if I'm off on my terminology, I only have around 2.4 years of programming experience, mostly in .NET.</p> <p>Currently I'm one of two .NET developers in a mainframe shop, the other developer set the standards and is a great coder with a lot more experience plus a CS degree(I am 100% self taught). </p> <p>We use custom collections for every application, recently since .NET 2.0 I've got him using generics instead of ArrayLists, and eyeball performance they seem to do great. We developed an automated program that uses SQLDMO to connect to databases and will create the base Datalayer and business layers for any objects we'd like, plus it handles logical deletes et cetera. </p> <p>When performance is what you optimize for, when can you justify NOT using a custom collection and writing a custom sort for it? Currently we use hard coded sorts because everything we've seen is a good deal slower, since most other options use reflection or bloated datasets/LINQ(is it still as slow as it was a year ago compared to custom collections?).</p> <p>Does anyone else work strictly with custom generic collections instead of going the easy route? Is the performance sacrifice as significant as I have been led to believe? Being that I am still in my infant stages of my development career, I'd say the next logical step is for me to start benchmarking things myself, but I wanted to get the opinion of other professionals as well....So, how does everyone else do it? Am one of the only people who actually strictly use custom collections over the much quicker and easier to create solutions? </p> <p>All opinions would be greatly appreciated. </p> <p><strong>EDIT:</strong> Sorry about the terminology, I knew I would get something a little off. What I meant by custom collections was indeed, using custom classes, and a custom collection class that inherits List(Of T) and also implements IComparable to handle sorting.</p>
[ { "answer_id": 249487, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "class CustomerList : List<Customer>" }, { "answer_id": 250186, "author": "Darren C", "author_id": 32339, "author_profile": "https://Stackoverflow.com/users/32339", "pm_score": 1, "selected": false, "text": "public static class Extensions\n{\n public static Customer GetCustomerByName( this List<Customer> customers )\n {\n …\n return customer;\n }\n}\n\nvar customers = new List<Customer>();\ncustomers.Add( new Customer());\nvar customer = customers.GetCustomerByName( “Smith” );\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14045/" ]
249,301
<p>How do I take an efficient simple random sample in SQL? The database in question is running MySQL; my table is at least 200,000 rows, and I want a simple random sample of about 10,000.</p> <p>The &quot;obvious&quot; answer is to:</p> <pre><code>SELECT * FROM table ORDER BY RAND() LIMIT 10000 </code></pre> <p>For large tables, that's too slow: it calls <code>RAND()</code> for every row (which already puts it at O(n)), and sorts them, making it O(n lg n) at best. Is there a way to do this faster than O(n)?</p> <p><em>Note</em>: As Andrew Mao points out in the comments, If you're using this approach on SQL Server, you should use the T-SQL function <code>NEWID()</code>, because RAND() <a href="http://msdn.microsoft.com/en-us/library/ms177610.asp" rel="noreferrer">may return the same value for all rows</a>.</p> <p><em>EDIT: 5 YEARS LATER</em></p> <p>I ran into this problem again with a bigger table, and ended up using a version of @ignorant's solution, with two tweaks:</p> <ul> <li>Sample the rows to 2-5x my desired sample size, to cheaply <code>ORDER BY RAND()</code></li> <li>Save the result of <code>RAND()</code> to an indexed column on every insert/update. (If your data set isn't very update-heavy, you may need to find another way to keep this column fresh.)</li> </ul> <p>To take a 1000-item sample of a table, I count the rows and sample the result down to, on average, 10,000 rows with the the frozen_rand column:</p> <pre><code>SELECT COUNT(*) FROM table; -- Use this to determine rand_low and rand_high SELECT * FROM table WHERE frozen_rand BETWEEN %(rand_low)s AND %(rand_high)s ORDER BY RAND() LIMIT 1000 </code></pre> <p>(My actual implementation involves more work to make sure I don't undersample, and to manually wrap rand_high around, but the basic idea is &quot;randomly cut your N down to a few thousand.&quot;)</p> <p>While this makes some sacrifices, it allows me to sample the database down using an index scan, until it's small enough to <code>ORDER BY RAND()</code> again.</p>
[ { "answer_id": 249351, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": -1, "selected": false, "text": "SELECT * FROM table LIMIT 10000 OFFSET FLOOR(RAND() * 190000)\n" }, { "answer_id": 252563, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 6, "selected": true, "text": "\ncreate table RandomKeys (RandomKey int)\ncreate table RandomKeysAttempt (RandomKey int)\n\n-- generate m random keys between 1 and n\nfor i = 1 to m\n insert RandomKeysAttempt select rand()*n + 1\n\n-- eliminate duplicates\ninsert RandomKeys select distinct RandomKey from RandomKeysAttempt\n\n-- as long as we don't have enough, keep generating new keys,\n-- with luck (and m much less than n), this won't be necessary\nwhile count(RandomKeys) < m\n NextAttempt = rand()*n + 1\n if not exists (select * from RandomKeys where RandomKey = NextAttempt)\n insert RandomKeys select NextAttempt\n\n-- get our random rows\nselect *\nfrom RandomKeys r\njoin table t ON r.RandomKey = t.UniqueKey\n" }, { "answer_id": 10656932, "author": "David F Mayer", "author_id": 1382887, "author_profile": "https://Stackoverflow.com/users/1382887", "pm_score": 3, "selected": false, "text": "WHERE RAND() < 0.1 \n WHERE RAND() < 0.01 \n" }, { "answer_id": 14629551, "author": "ignorant", "author_id": 2029648, "author_profile": "https://Stackoverflow.com/users/2029648", "pm_score": 6, "selected": false, "text": "select * from table where rand() <= .3\n" }, { "answer_id": 18671107, "author": "KitKat", "author_id": 2626112, "author_profile": "https://Stackoverflow.com/users/2626112", "pm_score": 0, "selected": false, "text": "select *\nfrom table_name\nwhere _id in (4, 1, 2, 5, 3)\n \"(4, 1, 2, 5, 3)\" RAND() ArrayList<Integer> indices = new ArrayList<Integer>(rowsCount);\nfor (int i = 0; i < rowsCount; i++) {\n indices.add(i);\n}\nCollections.shuffle(indices);\nString inClause = indices.toString().replace('[', '(').replace(']', ')');\n indices" }, { "answer_id": 23400284, "author": "gatoatigrado", "author_id": 81636, "author_profile": "https://Stackoverflow.com/users/81636", "pm_score": 3, "selected": false, "text": "TABLESAMPLE" }, { "answer_id": 25774531, "author": "Muposat", "author_id": 3395374, "author_profile": "https://Stackoverflow.com/users/3395374", "pm_score": 3, "selected": false, "text": "ORDER BY RAND() SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 >= RAND()\n SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)\n ORDER BY RAND()" }, { "answer_id": 47440872, "author": "concat", "author_id": 3925507, "author_profile": "https://Stackoverflow.com/users/3925507", "pm_score": 0, "selected": false, "text": "m O(max(n, m lg n)) O(n) O(n) m [0:m-1] ϴ(m) SELECT ... WHERE id IN (<subarray>) O(m lg n) O(m lg n) O(m) n m lg n ids = sql.query('SELECT id FROM t')\nfor i in range(m):\n r = int(random() * (len(ids) - i))\n ids[i], ids[i + r] = ids[i + r], ids[i]\n\nresults = sql.query('SELECT * FROM t WHERE id IN (%s)' % ', '.join(ids[0:m-1])\n" }, { "answer_id": 60458147, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "WITH IDS AS (\n SELECT ID\n FROM MYTABLE;\n)\n\nSELECT ID FROM IDS ORDER BY mt_random() LIMIT 3000\n" }, { "answer_id": 64368133, "author": "Northernlad", "author_id": 6835923, "author_profile": "https://Stackoverflow.com/users/6835923", "pm_score": 1, "selected": false, "text": "SELECT TOP 10000 * FROM table ORDER BY NEWID()\n" }, { "answer_id": 64612123, "author": "Zhanwen Chen", "author_id": 3853537, "author_profile": "https://Stackoverflow.com/users/3853537", "pm_score": 2, "selected": false, "text": "select distinct top 10000 customer_id from nielsen.dbo.customer TABLESAMPLE (20000 rows) REPEATABLE (123);\n (10000 rows) top TABLESAMPLE REPEATABLE (123)" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20760/" ]
249,312
<p>What does the following code do? A link to something in the PHP manual would also be nice.</p> <pre><code>if ($_SERVER['SERVER_PORT'] &lt;&gt; 443) { doSomething(); } </code></pre>
[ { "answer_id": 249315, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": true, "text": "false <> true // operator will evaluate expression as true\nfalse != true // operator will evaluate expression as true\n" }, { "answer_id": 249316, "author": "C. Broadbent", "author_id": 28859, "author_profile": "https://Stackoverflow.com/users/28859", "pm_score": 3, "selected": false, "text": "!=" }, { "answer_id": 249317, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "!=" }, { "answer_id": 249321, "author": "indyfromoz", "author_id": 32649, "author_profile": "https://Stackoverflow.com/users/32649", "pm_score": 2, "selected": false, "text": "$_SERVER['SERVER_PORT'] $_SERVER['SERVER_PORT'] <> 443 doSomething()" }, { "answer_id": 249345, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<> != < > $str1 <> $str2" }, { "answer_id": 249390, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 2, "selected": false, "text": "!= <>" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18285/" ]
249,314
<p>I was just watching a video on MSDN Channel 9 which can be found <a href="http://channel9.msdn.com/posts/Dan/Lucian-Wischik-and-Lisa-Feigenbaum-Whats-new-in-Visual-Basic-10/" rel="noreferrer">here</a>, about some of the new features in Visual Basic 10. Now I like most of the new features, some of which have been long awaited(auto properties and Collection Initializers), one that caught my eye was the multiline lambdas like in C#. </p> <p>In the video he used an example like this:</p> <pre><code>Dim scores = {10,20,30,40,50} Dim thread as new Threading.Thread(Sub() For Each o in scores console.writeline(o) Next End Sub) </code></pre> <p>Now I like VB in all it verbosity but I'm just a bit worried that writing sub...end sub inline could get a bit messy, I can see some merit in inlining when you are writing C# when you only have to use something like c => {....} and you can cut out a lot of code.</p> <p>What are your throughts of multiline lambdas in VB?</p> <p>Would you find them useful and where?</p>
[ { "answer_id": 249405, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 0, "selected": false, "text": "For i = 0 to 100\n '12 lines of code'\nNext\n Parallel.For( 0, 100, sub(i)\n '12 lines of code'\n End Sub )\n" }, { "answer_id": 249446, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " Private Sub SomeMethod()\n Dim SomeVariable as String = \"Some text.\"\n\n AddHandler SomeButton.Click, Sub()\n SomeVariable += \" Some more text\"\n MessageBox.Show(SomeVariable)\n End Sub\n Private Sub SomeMethodRunningInAnotherThread()\n Me.Dispatcher.Invoke(Normal, Sub()\n 'Do some other stuff '\n SomeTextBox.Text = \"Test\"\n End Sub)\n End Sub\n" }, { "answer_id": 249521, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "AddressOf x => f(x) Parallel.For" }, { "answer_id": 4005314, "author": "Erx_VB.NExT.Coder", "author_id": 220064, "author_profile": "https://Stackoverflow.com/users/220064", "pm_score": 2, "selected": false, "text": "With obj.class.methods\n\n .property = 1\n\n .attribute = 2\n\nEnd with\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
249,330
<p>I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository.</p> <p>I have a copy of the files on my local file system and I do an update to check if the files have changed since the last time the utility was run.</p> <p>I am at the point where I am translating the path names in SVN to the path names on my local copy.</p> <p>Currently I have written the following to do the job:</p> <pre><code>def formatPaths(self, paths): newPaths = list() for path in paths: path = path[len(self.basePath):] path = path.replace("/", "\\") newPaths.append(path) return newPaths </code></pre> <p>self.basePath would be something like "/trunk/project1" and I'm looking to just get the relative path of a subset of folders (I.e. folder1 under "/trunk/project1").</p> <p>Is this a good way to solve this problem or is there some magical function I missed?</p>
[ { "answer_id": 249444, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "baselen = len(self.basePath)\nfor path in paths:\n path = path[baselen:].replace(\"/\", \"\\\\\")\n newPaths.append(path)\nreturn newPaths\n baselen = len(self.basePath)\nreturn (path[baselen:].replace(\"/\", \"\\\\\") for path in paths)\n baselen" }, { "answer_id": 249650, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 3, "selected": true, "text": "baselen = len(self.basePath)\nreturn (path[baselen:].replace(\"/\", \"\\\\\") for path in paths)\n" }, { "answer_id": 249743, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": "easy_install anyvc from anyvc import Subversion\nvc = Subversion('/trunk')\n\nmodified = [f.relpath for f in vc.list() if f.state != 'clean']\n\nfor f in modified:\n print f.relpath # the relative path of the file to the source root\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804/" ]
249,346
<p>I am building a utility page for a web app that I am working on. I have an element that I want to use as a "console" of sorts.</p> <p>I get entries for the console via Ajax calls (using prototype's <code>Ajax.PeriodicalUpdater</code>).</p> <p>The problem I'm having is that when I insert new lines to the bottom of the "console", the scrollbar stays in the initial position (so I always see the top lines unless I manually scroll down).</p> <p>How can I make the scrollbar automatically stay at the bottom?</p> <p>I am using prototype for a few libraries that require it in this project, so I would prefer to stick with that or regular javascript if possible.</p> <p>Just as a note, I already tried this:</p> <pre><code>onComplete: function() { $('console').scrollTop = $('console').scrollHeight; } </code></pre> <p>It <em>almost</em> works, except that it is always "one step behind", and I can't see the most recent item.</p>
[ { "answer_id": 249349, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": true, "text": "new Ajax.PeriodicalUpdater(container, url, {\n onComplete: function() {\n (function() {\n container.scrollTop = container.scrollHeight;\n }).defer();\n }\n});\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12983/" ]
249,348
<p>I wrote this scheme code to compute one solution of the quadratic equation a<em>x2 + b</em>x + c = 0</p> <pre><code>(define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a))) </code></pre> <p>However, someone told me that this procedure is hard to understand. Why?</p> <p>What would a cleaned up version of this procedure look like? Please let me know why the new procedure would be easier to understand.</p> <p>Thanks</p>
[ { "answer_id": 249352, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "(define (solve-quadratic-equation a b c)\n (define disc (sqrt (- (* b b)\n (* 4.0 a c))))\n (/ (+ (- b) disc)\n (* 2.0 a)))\n (+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6)) (+ (* 3\n (+ (* 2 4)\n (+ 3 5)))\n (+ (- 10 7)\n 6))" }, { "answer_id": 249354, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 1, "selected": false, "text": " (define (solve-quadratic-equation a b c)\n (define square (x) (* x x) \n (define disc (sqrt (- (square b) (* 4.0 a c)))) \n (/ (+ (- b) disc) (* 2.0 a))))\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
249,350
<p>I have seen some declaration of a union inside a struct as follows. Example code given below.</p> <p>My questions is does it help in any memory savings(typical use for which a union is used for)? I do not see the benefit. </p> <pre><code>typedef struct { int x1; unsigned int x2; ourstruct1 ov1; ourstruct1 ov2; union { struct { mystruct1 v1; mystruct2 v2; mystruct3 v3; int* ctxSC; mystruct4 v4; Bool v5; Long v6; Long v7; Long v8; Long v9; }mystr; }; }structvar1; </code></pre> <p>-AD</p>
[ { "answer_id": 250453, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 0, "selected": false, "text": " structvar1 var1;\n var1.mystr.ctxSC = NULL; // compile error : structvar1 has no mystr member\n" }, { "answer_id": 251148, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "D3DMATRIX typedef struct _D3DMATRIX {\n union {\n struct {\n float _11, _12, _13, _14;\n float _21, _22, _23, _24;\n float _31, _32, _33, _34;\n float _41, _42, _43, _44;\n\n };\n float m[4][4];\n };\n} D3DMATRIX; myMat._12 myMat.m[0][1] myMat myMat.m[0][1]" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
249,357
<p>I am currently working on my first website. I have no idea where to start on the CSS page, or if there are any standards that I should be following.</p> <p>I would appreciate any links or first-hand advise.</p>
[ { "answer_id": 249387, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": true, "text": "div.red\n{\n color: red;\n}\n div.error\n{\n color: red;\n}\n" }, { "answer_id": 249518, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 2, "selected": false, "text": "#header .navigationElement a{color:red;} #footer .navigationElement a{color:black;}" }, { "answer_id": 251348, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 3, "selected": false, "text": "p {color:green;} p.sidenote {color: blue;} p#final {color: red;} <p style=\"color: orange;\"> p#final {color: inherit !important;}" }, { "answer_id": 251712, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 4, "selected": false, "text": "<ul id=\"nav\">\n <li class=\"navItem\"><span class=\"itemText\">Nav Item</span></li>\n <li class=\"navItem\"><span class=\"itemText\">Nav Item</span></li>\n</ul>\n\n#nav { }\n#nav .navItem { }\n#nav .itemText { }\n <ul id=\"nav\">\n <li><span>Nav Item</span></li>\n <li><span>Nav Item</span></li>\n</ul>\n\n#nav {}\n#nav li {}\n#nav li span {}\n" }, { "answer_id": 257604, "author": "codeinthehole", "author_id": 32640, "author_profile": "https://Stackoverflow.com/users/32640", "pm_score": 1, "selected": false, "text": "* { padding: 0; margin: 0; }\n" }, { "answer_id": 257663, "author": "Josh Hunt", "author_id": 2592, "author_profile": "https://Stackoverflow.com/users/2592", "pm_score": 2, "selected": false, "text": "*{margin:0;padding:0}iframe,a img,fieldset,form,table{border:0}h6,h5,h4,h3,h2,h1,caption,th,td{font-size:100%;font-weight:normal}dd,dt,li,dl,ol,ul{list-style:none}legend{color:#000}button,select,textarea,input{font:100% serif}table{border-collapse:collapse}caption,th,td{text-align:left}p, h1{margin:0;padding:0;bording:0}\n <div id=\"\"> <div class=\"\"> <div id=\"content\"> <div class=\"box\">" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]