qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
273,261
<p>I have an application where I accept a socket connection from a telnet client and put up a simple, keyboard driven character GUI.</p> <p>The telnet client, at least on Linux, defaults into line-at-a-time mode, so I always have to do <code>^]mode char</code> manually.</p> <p>A skim of the relevant RFCs suggests that if my application simply sent the characters <code>IAC DONT LINEMODE (\377\376\042)</code> as soon as the client connects, the client should be forced into character mode. However, it doesn't make any difference.</p> <p>What's the simplest bit of code that would do the job? Ideally just a string to be sent. My application can absorb whatever junk the client sends back.</p>
[ { "answer_id": 279271, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>For what it's worth, solved it myself.</p>\n\n<pre><code>// IAC WONT LINEMODE IAC WILL ECHO\n\nwrite(s,\"\\377\\375\\042\\377\\373\\001\",6);\n</code></pre>\n\n<p>gets the remote (at least telnet from an Xterm on a Linux box) into the right state.</p>\n" }, { "answer_id": 1068894, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Interesting. I had more luck sending</p>\n\n<pre><code>IAC WILL ECHO IAC WILL SUPPRESS_GO_AHEAD IAC WONT LINEMODE\n255 251 1 255 251 3 255 252 34\n</code></pre>\n\n<p>The IAC WONT LINEMODE seems to be redundant: my telnet client seems to get to the right state without it, but I left it in for completeness.</p>\n" }, { "answer_id": 37377884, "author": "h2g2bob", "author_id": 6368266, "author_profile": "https://Stackoverflow.com/users/6368266", "pm_score": 2, "selected": false, "text": "<p>Kevin's solution works great:</p>\n<pre><code>write(s,&quot;\\377\\375\\042\\377\\373\\001&quot;,6);\n</code></pre>\n<p>Although the comment is slightly wrong. It should say &quot;DO LINEMODE&quot;, not &quot;WONT LINEMODE&quot;, ie:</p>\n<pre><code>// IAC DO LINEMODE IAC WILL ECHO\n</code></pre>\n<p>(Source: <a href=\"https://www.rfc-editor.org/rfc/rfc854#page-14\" rel=\"nofollow noreferrer\">rfc854</a>)</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an application where I accept a socket connection from a telnet client and put up a simple, keyboard driven character GUI. The telnet client, at least on Linux, defaults into line-at-a-time mode, so I always have to do `^]mode char` manually. A skim of the relevant RFCs suggests that if my application simply sent the characters `IAC DONT LINEMODE (\377\376\042)` as soon as the client connects, the client should be forced into character mode. However, it doesn't make any difference. What's the simplest bit of code that would do the job? Ideally just a string to be sent. My application can absorb whatever junk the client sends back.
For what it's worth, solved it myself. ``` // IAC WONT LINEMODE IAC WILL ECHO write(s,"\377\375\042\377\373\001",6); ``` gets the remote (at least telnet from an Xterm on a Linux box) into the right state.
273,262
<p>I want to deal with the command line input in Ruby:</p> <pre><code>&gt; cat input.txt | myprog.rb &gt; myprog.rb &lt; input.txt &gt; myprog.rb arg1 arg2 arg3 ... </code></pre> <p>What is the best way to do it? In particular I want to deal with blank STDIN, and I hope for an elegant solution.</p> <pre><code>#!/usr/bin/env ruby STDIN.read.split("\n").each do |a| puts a end ARGV.each do |b| puts b end </code></pre>
[ { "answer_id": 273415, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 5, "selected": false, "text": "<p>I am not quite sure what you need, but I would use something like this:</p>\n\n<pre><code>#!/usr/bin/env ruby\n\nuntil ARGV.empty? do\n puts \"From arguments: #{ARGV.shift}\"\nend\n\nwhile a = gets\n puts \"From stdin: #{a}\"\nend\n</code></pre>\n\n<p>Note that because ARGV array is empty before first <code>gets</code>, Ruby won't try to interpret argument as text file from which to read (behaviour inherited from Perl).</p>\n\n<p>If stdin is empty or there is no arguments, nothing is printed.</p>\n\n<p>Few test cases:</p>\n\n<pre><code>$ cat input.txt | ./myprog.rb\nFrom stdin: line 1\nFrom stdin: line 2\n\n$ ./myprog.rb arg1 arg2 arg3\nFrom arguments: arg1\nFrom arguments: arg2\nFrom arguments: arg3\nhi!\nFrom stdin: hi!\n</code></pre>\n" }, { "answer_id": 273605, "author": "Magnus Holm", "author_id": 8791, "author_profile": "https://Stackoverflow.com/users/8791", "pm_score": 4, "selected": false, "text": "<p>Something like this perhaps?</p>\n\n<pre><code>#/usr/bin/env ruby\n\nif $stdin.tty?\n ARGV.each do |file|\n puts \"do something with this file: #{file}\"\n end\nelse\n $stdin.each_line do |line|\n puts \"do something with this line: #{line}\"\n end\nend\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt; cat input.txt | ./myprog.rb\ndo something with this line: this\ndo something with this line: is\ndo something with this line: a\ndo something with this line: test\n&gt; ./myprog.rb &lt; input.txt \ndo something with this line: this\ndo something with this line: is\ndo something with this line: a\ndo something with this line: test\n&gt; ./myprog.rb arg1 arg2 arg3\ndo something with this file: arg1\ndo something with this file: arg2\ndo something with this file: arg3\n</code></pre>\n" }, { "answer_id": 273841, "author": "Jonke", "author_id": 15638, "author_profile": "https://Stackoverflow.com/users/15638", "pm_score": 9, "selected": false, "text": "<p>Following are some things I found in my collection of obscure Ruby.</p>\n<p>So, in Ruby, a simple no-bells implementation of the Unix command <code>cat</code> would be:</p>\n<pre><code>#!/usr/bin/env ruby\nputs ARGF.read\n</code></pre>\n<p><a href=\"https://ruby-doc.org/core/ARGF.html\" rel=\"noreferrer\"><code>ARGF</code></a> is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.</p>\n<pre><code>ARGF.each_with_index do |line, idx|\n print ARGF.filename, &quot;:&quot;, idx, &quot;;&quot;, line\nend\n\n# print all the lines in every file passed via command line that contains login\nARGF.each do |line|\n puts line if line =~ /login/\nend\n</code></pre>\n<p>Thank goodness we didn’t get the diamond operator in Ruby, but we did get <code>ARGF</code> as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, <code>-i</code>) to every file mentioned on the command-line:</p>\n<pre><code>#!/usr/bin/env ruby -i\n\nHeader = DATA.read\n\nARGF.each_line do |e|\n puts Header if ARGF.pos - e.length == 0\n puts e\nend\n\n__END__\n#--\n# Copyright (C) 2007 Fancypants, Inc.\n#++\n</code></pre>\n<p>Credit to:</p>\n<ul>\n<li><a href=\"https://web.archive.org/web/20080725055721/http://www.oreillynet.com/ruby/blog/2007/04/trivial_scripting_with_ruby.html#comment-565558\" rel=\"noreferrer\">https://web.archive.org/web/20080725055721/http://www.oreillynet.com/ruby/blog/2007/04/trivial_scripting_with_ruby.html#comment-565558</a></li>\n<li><a href=\"http://blog.nicksieger.com/articles/2007/10/06/obscure-and-ugly-perlisms-in-ruby\" rel=\"noreferrer\">http://blog.nicksieger.com/articles/2007/10/06/obscure-and-ugly-perlisms-in-ruby</a></li>\n</ul>\n" }, { "answer_id": 5176247, "author": "Bill Caputo", "author_id": 642305, "author_profile": "https://Stackoverflow.com/users/642305", "pm_score": 5, "selected": false, "text": "<p>Ruby provides another way to handle STDIN: The -n flag. It treats your entire program as being inside a loop over STDIN, (including files passed as command line args). See e.g. the following 1-line script:</p>\n\n<pre><code>#!/usr/bin/env ruby -n\n\n#example.rb\n\nputs \"hello: #{$_}\" #prepend 'hello:' to each line from STDIN\n\n#these will all work:\n# ./example.rb &lt; input.txt\n# cat input.txt | ./example.rb\n# ./example.rb input.txt\n</code></pre>\n" }, { "answer_id": 11403762, "author": "SwiftMango", "author_id": 1270003, "author_profile": "https://Stackoverflow.com/users/1270003", "pm_score": 4, "selected": false, "text": "<pre><code>while STDIN.gets\n puts $_\nend\n\nwhile ARGF.gets\n puts $_\nend\n</code></pre>\n\n<p>This is inspired by Perl:</p>\n\n<pre><code>while(&lt;STDIN&gt;){\n print \"$_\\n\"\n}\n</code></pre>\n" }, { "answer_id": 34906353, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 1, "selected": false, "text": "<p>I'll add that in order to use <code>ARGF</code> with parameters, you need to clear <code>ARGV</code> before calling <code>ARGF.each</code>. This is because <code>ARGF</code> will treat anything in <code>ARGV</code> as a filename and read lines from there first.</p>\n\n<p>Here's an example 'tee' implementation:</p>\n\n<pre><code>File.open(ARGV[0], 'w') do |file|\n ARGV.clear\n\n ARGF.each do |line|\n puts line\n file.write(line)\n end\nend\n</code></pre>\n" }, { "answer_id": 36330607, "author": "wired00", "author_id": 629222, "author_profile": "https://Stackoverflow.com/users/629222", "pm_score": 1, "selected": false, "text": "<p>I do something like this : </p>\n\n<pre><code>all_lines = \"\"\nARGV.each do |line|\n all_lines &lt;&lt; line + \"\\n\"\nend\nputs all_lines\n</code></pre>\n" }, { "answer_id": 39999281, "author": "Howard Barina", "author_id": 4738062, "author_profile": "https://Stackoverflow.com/users/4738062", "pm_score": 0, "selected": false, "text": "<p>It seems most answers are assuming the arguments are filenames containing content to be cat'd to the stdin. Below everything is treated as just arguments. If STDIN is from the TTY, then it is ignored.</p>\n\n<pre><code>$ cat tstarg.rb\n\nwhile a=(ARGV.shift or (!STDIN.tty? and STDIN.gets) )\n puts a\nend\n</code></pre>\n\n<p>Either arguments or stdin can be empty or have data.</p>\n\n<pre><code>$ cat numbers \n1\n2\n3\n4\n5\n$ ./tstarg.rb a b c &lt; numbers\na\nb\nc\n1\n2\n3\n4\n5\n</code></pre>\n" }, { "answer_id": 40547608, "author": "Jose Alban", "author_id": 2600638, "author_profile": "https://Stackoverflow.com/users/2600638", "pm_score": 2, "selected": false, "text": "<p>Quick and simple:</p>\n\n<p><code>STDIN.gets.chomp == 'YES'</code></p>\n" }, { "answer_id": 62784122, "author": "Dorian", "author_id": 12544391, "author_profile": "https://Stackoverflow.com/users/12544391", "pm_score": 2, "selected": false, "text": "<p>You can also use <code>STDIN.each_line</code>, and <code>STDIN.each_line.to_a</code> to get it as an array.</p>\n<p>e.g.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>STDIN.each_line do |line|\n puts line\nend\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35580/" ]
I want to deal with the command line input in Ruby: ``` > cat input.txt | myprog.rb > myprog.rb < input.txt > myprog.rb arg1 arg2 arg3 ... ``` What is the best way to do it? In particular I want to deal with blank STDIN, and I hope for an elegant solution. ``` #!/usr/bin/env ruby STDIN.read.split("\n").each do |a| puts a end ARGV.each do |b| puts b end ```
Following are some things I found in my collection of obscure Ruby. So, in Ruby, a simple no-bells implementation of the Unix command `cat` would be: ``` #!/usr/bin/env ruby puts ARGF.read ``` [`ARGF`](https://ruby-doc.org/core/ARGF.html) is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN. ``` ARGF.each_with_index do |line, idx| print ARGF.filename, ":", idx, ";", line end # print all the lines in every file passed via command line that contains login ARGF.each do |line| puts line if line =~ /login/ end ``` Thank goodness we didn’t get the diamond operator in Ruby, but we did get `ARGF` as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, `-i`) to every file mentioned on the command-line: ``` #!/usr/bin/env ruby -i Header = DATA.read ARGF.each_line do |e| puts Header if ARGF.pos - e.length == 0 puts e end __END__ #-- # Copyright (C) 2007 Fancypants, Inc. #++ ``` Credit to: * <https://web.archive.org/web/20080725055721/http://www.oreillynet.com/ruby/blog/2007/04/trivial_scripting_with_ruby.html#comment-565558> * <http://blog.nicksieger.com/articles/2007/10/06/obscure-and-ugly-perlisms-in-ruby>
273,275
<p>Rails has an awesome way of looking up column names and expected datatypes from the DB, alleviating a lot of programming.</p> <p>I'm trying to build something like this in C#.NET, because we have large tables that are ever changing. I'll be adding parameters like so:</p> <pre><code>SqlParameter param = new SqlParameter("parametername", *SqlDbType.Int*); param.Direction = ParameterDirection.Input; param.Value = 0; comm.Parameters.Add(param); </code></pre> <p>Notice the SqlDbType. How can I get that? If I get DataColumns from the DataSet, all I can get is System types like System.string.</p>
[ { "answer_id": 273305, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 2, "selected": false, "text": "<p>why not just let ADO.NET detect it automatically:</p>\n\n<pre><code>SqlParameter param = new SqlParameter(\"parametername\", value);\n</code></pre>\n\n<p>'course, you don't actually need Direction, either:</p>\n\n<pre><code>comm.Parameters.Add(new SqlParameter(\"parametername\",value));\n</code></pre>\n\n<p>I'm kind of a fan of doing things in one line :)</p>\n" }, { "answer_id": 273317, "author": "Tinister", "author_id": 34715, "author_profile": "https://Stackoverflow.com/users/34715", "pm_score": 1, "selected": false, "text": "<p>For our project we query the <code>INFORMATION_SCHEMA</code> tables before we build our SQL statements. If you stick the value in <code>DATA_TYPE</code> from <code>INFORMATION_SCHEMA.COLUMNS</code> into an <code>Enum.Parse</code> that should give you the correct value.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25538/" ]
Rails has an awesome way of looking up column names and expected datatypes from the DB, alleviating a lot of programming. I'm trying to build something like this in C#.NET, because we have large tables that are ever changing. I'll be adding parameters like so: ``` SqlParameter param = new SqlParameter("parametername", *SqlDbType.Int*); param.Direction = ParameterDirection.Input; param.Value = 0; comm.Parameters.Add(param); ``` Notice the SqlDbType. How can I get that? If I get DataColumns from the DataSet, all I can get is System types like System.string.
why not just let ADO.NET detect it automatically: ``` SqlParameter param = new SqlParameter("parametername", value); ``` 'course, you don't actually need Direction, either: ``` comm.Parameters.Add(new SqlParameter("parametername",value)); ``` I'm kind of a fan of doing things in one line :)
273,283
<p>I just added printing capability to a web site using a style sheet (ie. @media print, etc.) and was wondering if I could use a similar method for adding support for mobile devices.</p> <p>If not, how do I detect a mobile device? My pages are C# (.aspx) and I'd like to scale back the pages for ease of use on a mobile device.</p> <p>Any advice for me?</p> <p>EDIT: My wife has a BlackBerry, so at a miminum I'd like to enable our company's web site for that.</p>
[ { "answer_id": 273289, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 4, "selected": true, "text": "<p>I'm not sure how the IPhone/iPod Touch declare themselves when requesting the stylesheet, but for most, using </p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n @media handheld\n {\n /* handheld styles */\n }\n&lt;/style&gt;\n</code></pre>\n\n<p>should do the trick. It works in the same way @media print does (or doesn't). </p>\n\n<p>For a complete list of media types, see <a href=\"http://www.w3.org/TR/CSS2/media.html\" rel=\"nofollow noreferrer\">here.</a></p>\n" }, { "answer_id": 273291, "author": "Mat Nadrofsky", "author_id": 26853, "author_profile": "https://Stackoverflow.com/users/26853", "pm_score": 1, "selected": false, "text": "<p>You'd want to have a look at the type of user agent you've got and see if it's a mobile device. The following code would be an example of this:</p>\n\n<pre><code>public static bool IsMobile(string userAgent)\n{\n userAgent = userAgent.ToLower();\n\n return userAgent.Contains(\"iphone\") |\n userAgent.Contains(\"ppc\") |\n userAgent.Contains(\"windows ce\") |\n userAgent.Contains(\"blackberry\") |\n userAgent.Contains(\"opera mini\") |\n userAgent.Contains(\"mobile\") |\n userAgent.Contains(\"palm\") |\n userAgent.Contains(\"portable\");\n}\n</code></pre>\n\n<p>That should work in most cases! This <a href=\"http://wurfl.sourceforge.net/\" rel=\"nofollow noreferrer\">link</a> might help you get more specific too.</p>\n" }, { "answer_id": 273384, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 2, "selected": false, "text": "<p>Mobile browsers are a real hodge-podge in terms of what they support, whether they follow the \"media\" attribute on your styles, etc.</p>\n\n<p>I would say aim for <a href=\"http://www.alistapart.com/articles/progressiveenhancementwithcss\" rel=\"nofollow noreferrer\">progressive enhancement</a> (that's one of a series of articles) and make sure that if the browser only understands plain HTML, your content is still viewable and in the right order - for example, you want your main content to appear before the sidebar in the code, since the main content is more important.</p>\n\n<p>A <a href=\"http://mobiforge.com/\" rel=\"nofollow noreferrer\">decent looking resource</a> was mentioned in the article above.</p>\n" }, { "answer_id": 273782, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 2, "selected": false, "text": "<p>You might want to use something like <a href=\"http://wurfl.sourceforge.net/\" rel=\"nofollow noreferrer\">WURFL</a>, which is a fairly nice database that knows a lot about devices and their user agents, if the other solutions do not work.</p>\n\n<p>And please, remember to reduce download sizes :)</p>\n" }, { "answer_id": 4770852, "author": "rgubby", "author_id": 396145, "author_profile": "https://Stackoverflow.com/users/396145", "pm_score": 0, "selected": false, "text": "<p>The best way of doing all of this is to do it at a server level.</p>\n\n<p>Use a web service to check whether the visitor is a mobile and deliver your output based on this. Use the same URL and perform the same business logic on your application - just change the view layer of your app.</p>\n\n<p>A great option is Wapple Architect (http://wapple.net) - it allows you to do these checks at a server level with some web services and then perform logic and add code if it's a mobile device.</p>\n\n<p>Definitely worth a look.</p>\n" }, { "answer_id": 16355358, "author": "Namratha", "author_id": 381699, "author_profile": "https://Stackoverflow.com/users/381699", "pm_score": 0, "selected": false, "text": "<p>Check this out! It's pretty cool! <a href=\"http://mobstac.com/developer/\" rel=\"nofollow\">http://mobstac.com/developer/</a></p>\n\n<p>The MobStac API platform is the fastest way to build and manage mobile sites! You get access to developer documentation and API keys.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20848/" ]
I just added printing capability to a web site using a style sheet (ie. @media print, etc.) and was wondering if I could use a similar method for adding support for mobile devices. If not, how do I detect a mobile device? My pages are C# (.aspx) and I'd like to scale back the pages for ease of use on a mobile device. Any advice for me? EDIT: My wife has a BlackBerry, so at a miminum I'd like to enable our company's web site for that.
I'm not sure how the IPhone/iPod Touch declare themselves when requesting the stylesheet, but for most, using ``` <style type="text/css"> @media handheld { /* handheld styles */ } </style> ``` should do the trick. It works in the same way @media print does (or doesn't). For a complete list of media types, see [here.](http://www.w3.org/TR/CSS2/media.html)
273,297
<p>Few of us would deny the awesomeness of debuggers, but to make it more useful, some tricks can be used. </p> <p>For example in Python, you can use <strong><em>pass</em></strong> to do absolutely nothing except to leave you room to put a break point and allow you to observe the values in the Watch window. </p> <p>In C#, I used to do <strong><em>GC.Collect()</em></strong>, but now I use <strong><em>if (false){}</em></strong></p> <p>What's your most playful dummy line?</p>
[ { "answer_id": 273303, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": true, "text": "<p>In C#, you can use this:</p>\n\n<pre><code>System.Diagnostics.Debugger.Break();\n</code></pre>\n\n<p>It will force a breakpoint.</p>\n" }, { "answer_id": 273304, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.assert.aspx\" rel=\"noreferrer\">Debug.Assert(true);</a>, which automatically gets compiled out of release builds.</p>\n" }, { "answer_id": 273322, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 2, "selected": false, "text": "<p>in gcc/g++:</p>\n\n<pre><code>assert(\"breakpoint\");\n</code></pre>\n\n<p>since any non-0/null value to an assert is taken as true.</p>\n\n<p>or even</p>\n\n<pre><code>__asm__(\"nop\");\n</code></pre>\n\n<p>at least I know there will be an instruction byte emitted for the breakpoint to occur on. ;)</p>\n" }, { "answer_id": 273457, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": 3, "selected": false, "text": "<pre><code>volatile int e = 9;\n</code></pre>\n\n<p>Volatile means the compiler won't remove it because I don't read the variable.\n'9' just so that it is non-zero. Zero is too common for my tastes.</p>\n" }, { "answer_id": 273471, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>Not very sophisticated, but functional.</p>\n\n<pre><code>bool bp;\n\nbp = true; //whereever I need to break.\n</code></pre>\n" }, { "answer_id": 273557, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 1, "selected": false, "text": "<p>In VB6, I use a colon, by itself. <code>:</code></p>\n" }, { "answer_id": 273577, "author": "Rossini", "author_id": 28281, "author_profile": "https://Stackoverflow.com/users/28281", "pm_score": 2, "selected": false, "text": "<p>I use</p>\n\n<pre><code>int x = 0;\n</code></pre>\n\n<p>I always make sure I remove this line when I'm done debugging.</p>\n" }, { "answer_id": 1270087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>In c++ I use</p>\n\n<pre><code>Sleep(0) \n</code></pre>\n\n<p>sometimes, or just find a variable that's used and assign it to itself: </p>\n\n<pre><code>i = i;\n</code></pre>\n" }, { "answer_id": 1270093, "author": "Noon Silk", "author_id": 154152, "author_profile": "https://Stackoverflow.com/users/154152", "pm_score": 2, "selected": false, "text": "<p>I've never written something specifically to break on, but if I did, I'd write</p>\n\n<pre><code>int moot;\n</code></pre>\n\n<p>I use this one when there is some required 'out' parameter that I don't care about but must provide.</p>\n" }, { "answer_id": 3927024, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 1, "selected": false, "text": "<p>True, it's strange that VS2010 debugger shifts breakpoints around if they are on an empty statement such as a semicolon. Despite what it looks like, in a debug build you can still generally put a breakpoint on an empty C# control block or semicolon, and it will get hit correctly. After being annoyed by this for a while, I just created this to use instead:</p>\n\n<pre><code>public static class Nop { public static void X() { } };\n</code></pre>\n\n<p>edit: To use it, put Nop.X() in your code...</p>\n" }, { "answer_id": 4543717, "author": "greatwolf", "author_id": 234175, "author_profile": "https://Stackoverflow.com/users/234175", "pm_score": 2, "selected": false, "text": "<p>For C/C++ I use </p>\n\n<pre><code>__asm int 3;\n</code></pre>\n\n<p>That will generate a breakpoint exception at that line of code which the debugger will catch. A caveat though is your program will crash with that exception if it's not being run inside a debugger.</p>\n" }, { "answer_id": 13511182, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 4, "selected": false, "text": "<p>In C#, in Visual Studio</p>\n\n<pre><code>{}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088/" ]
Few of us would deny the awesomeness of debuggers, but to make it more useful, some tricks can be used. For example in Python, you can use ***pass*** to do absolutely nothing except to leave you room to put a break point and allow you to observe the values in the Watch window. In C#, I used to do ***GC.Collect()***, but now I use ***if (false){}*** What's your most playful dummy line?
In C#, you can use this: ``` System.Diagnostics.Debugger.Break(); ``` It will force a breakpoint.
273,313
<p>What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.</p>
[ { "answer_id": 273351, "author": "dmo", "author_id": 1807, "author_profile": "https://Stackoverflow.com/users/1807", "pm_score": 2, "selected": false, "text": "<p>If you have a fixed number (75), you could create an array with 75 elements, then enumerate your list, moving the elements to randomized positions in the array. You can generate the mapping of list number to array index using the <a href=\"http://en.wikipedia.org/wiki/Knuth_shuffle\" rel=\"nofollow noreferrer\" title=\"Fisher-Yates shuffle\">Fisher-Yates shuffle</a>.</p>\n" }, { "answer_id": 273352, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 2, "selected": false, "text": "<p>I usually use:</p>\n\n<pre><code>var list = new List&lt;T&gt; ();\nfillList (list);\nvar randomizedList = new List&lt;T&gt; ();\nvar rnd = new Random ();\nwhile (list.Count != 0)\n{\n var index = rnd.Next (0, list.Count);\n randomizedList.Add (list [index]);\n list.RemoveAt (index);\n}\n</code></pre>\n" }, { "answer_id": 273355, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": -1, "selected": false, "text": "<p>A very simple approach to this kind of problem is to use a number of random element swap in the list.</p>\n\n<p>In pseudo-code this would look like this:</p>\n\n<pre><code>do \n r1 = randomPositionInList()\n r2 = randomPositionInList()\n swap elements at index r1 and index r2 \nfor a certain number of times\n</code></pre>\n" }, { "answer_id": 273666, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 4, "selected": false, "text": "<pre><code> public static List&lt;T&gt; Randomize&lt;T&gt;(List&lt;T&gt; list)\n {\n List&lt;T&gt; randomizedList = new List&lt;T&gt;();\n Random rnd = new Random();\n while (list.Count &gt; 0)\n {\n int index = rnd.Next(0, list.Count); //pick a random item from the master list\n randomizedList.Add(list[index]); //place it at the end of the randomized list\n list.RemoveAt(index);\n }\n return randomizedList;\n }\n</code></pre>\n" }, { "answer_id": 1262619, "author": "grenade", "author_id": 68115, "author_profile": "https://Stackoverflow.com/users/68115", "pm_score": 11, "selected": true, "text": "<p>Shuffle any <code>(I)List</code> with an extension method based on the <a href=\"http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\" rel=\"noreferrer\">Fisher-Yates shuffle</a>:</p>\n\n<pre><code>private static Random rng = new Random(); \n\npublic static void Shuffle&lt;T&gt;(this IList&lt;T&gt; list) \n{ \n int n = list.Count; \n while (n &gt; 1) { \n n--; \n int k = rng.Next(n + 1); \n T value = list[k]; \n list[k] = list[n]; \n list[n] = value; \n } \n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>List&lt;Product&gt; products = GetProducts();\nproducts.Shuffle();\n</code></pre>\n\n<p>The code above uses the much criticised System.Random method to select swap candidates. It's fast but not as random as it should be. If you need a better quality of randomness in your shuffles use the random number generator in System.Security.Cryptography like so:</p>\n\n<pre><code>using System.Security.Cryptography;\n...\npublic static void Shuffle&lt;T&gt;(this IList&lt;T&gt; list)\n{\n RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();\n int n = list.Count;\n while (n &gt; 1)\n {\n byte[] box = new byte[1];\n do provider.GetBytes(box);\n while (!(box[0] &lt; n * (Byte.MaxValue / n)));\n int k = (box[0] % n);\n n--;\n T value = list[k];\n list[k] = list[n];\n list[n] = value;\n }\n}\n</code></pre>\n\n<p>A simple comparison is available <a href=\"https://web.archive.org/web/20150801085341/http://blog.thijssen.ch/2010/02/when-random-is-too-consistent.html\" rel=\"noreferrer\">at this blog</a> (WayBack Machine).</p>\n\n<p>Edit: Since writing this answer a couple years back, many people have commented or written to me, to point out the big silly flaw in my comparison. They are of course right. There's nothing wrong with System.Random if it's used in the way it was intended. In my first example above, I instantiate the rng variable inside of the Shuffle method, which is asking for trouble if the method is going to be called repeatedly. Below is a fixed, full example based on a really useful comment received today from @weston here on SO.</p>\n\n<p>Program.cs:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace SimpleLottery\n{\n class Program\n {\n private static void Main(string[] args)\n {\n var numbers = new List&lt;int&gt;(Enumerable.Range(1, 75));\n numbers.Shuffle();\n Console.WriteLine(\"The winning numbers are: {0}\", string.Join(\", \", numbers.GetRange(0, 5)));\n }\n }\n\n public static class ThreadSafeRandom\n {\n [ThreadStatic] private static Random Local;\n\n public static Random ThisThreadsRandom\n {\n get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }\n }\n }\n\n static class MyExtensions\n {\n public static void Shuffle&lt;T&gt;(this IList&lt;T&gt; list)\n {\n int n = list.Count;\n while (n &gt; 1)\n {\n n--;\n int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);\n T value = list[k];\n list[k] = list[n];\n list[n] = value;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3456788, "author": "Denis", "author_id": 417022, "author_profile": "https://Stackoverflow.com/users/417022", "pm_score": 6, "selected": false, "text": "<p>Extension method for IEnumerable:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Randomize&lt;T&gt;(this IEnumerable&lt;T&gt; source)\n{\n Random rnd = new Random();\n return source.OrderBy&lt;T, int&gt;((item) =&gt; rnd.Next());\n}\n</code></pre>\n" }, { "answer_id": 4262134, "author": "user453230", "author_id": 453230, "author_profile": "https://Stackoverflow.com/users/453230", "pm_score": 9, "selected": false, "text": "<p>If we only need to shuffle items in a completely random order (just to mix the items in a list), I prefer this simple yet effective code that orders items by guid...</p>\n<pre><code>var shuffledcards = cards.OrderBy(a =&gt; Guid.NewGuid()).ToList();\n</code></pre>\n<hr />\n<p>As people have pointed out in the comments, GUIDs are not guaranteed to be random, so we should be using a real random number generator instead:</p>\n<pre><code>private static Random rng = new Random();\n...\nvar shuffledcards = cards.OrderBy(a =&gt; rng.Next()).ToList();\n</code></pre>\n" }, { "answer_id": 7913534, "author": "Jodrell", "author_id": 659190, "author_profile": "https://Stackoverflow.com/users/659190", "pm_score": 3, "selected": false, "text": "<p><strong>EDIT</strong>\nThe <code>RemoveAt</code> is a weakness in my previous version. This solution overcomes that.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(\n this IEnumerable&lt;T&gt; source,\n Random generator = null)\n{\n if (generator == null)\n {\n generator = new Random();\n }\n\n var elements = source.ToArray();\n for (var i = elements.Length - 1; i &gt;= 0; i--)\n {\n var swapIndex = generator.Next(i + 1);\n yield return elements[swapIndex];\n elements[swapIndex] = elements[i];\n }\n}\n</code></pre>\n\n<p>Note the optional <code>Random generator</code>, if the base framework implementation of <code>Random</code> is not thread-safe or cryptographically strong enough for your needs, you can inject your implementation into the operation.</p>\n\n<p><a href=\"https://stackoverflow.com/a/24648788/659190\">A suitable implementation for a thread-safe cryptographically strong <code>Random</code> implementation can be found in this answer.</a></p>\n\n<hr>\n\n<p><s>Here's an idea, extend IList in a (hopefully) efficient way.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IList&lt;T&gt; list)\n{\n var choices = Enumerable.Range(0, list.Count).ToList();\n var rng = new Random();\n for(int n = choices.Count; n &gt; 1; n--)\n {\n int k = rng.Next(n);\n yield return list[choices[k]];\n choices.RemoveAt(k);\n }\n\n yield return list[choices[0]];\n}\n</code></pre>\n\n<p></s></p>\n" }, { "answer_id": 14511104, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 0, "selected": false, "text": "<p>Here's an efficient Shuffler that returns a byte array of shuffled values. It never shuffles more than is needed. It can be restarted from where it previously left off. My actual implementation (not shown) is a MEF component that allows a user specified replacement shuffler.</p>\n\n<pre><code> public byte[] Shuffle(byte[] array, int start, int count)\n {\n int n = array.Length - start;\n byte[] shuffled = new byte[count];\n for(int i = 0; i &lt; count; i++, start++)\n {\n int k = UniformRandomGenerator.Next(n--) + start;\n shuffled[i] = array[k];\n array[k] = array[start];\n array[start] = shuffled[i];\n }\n return shuffled;\n }\n</code></pre>\n\n<p>`</p>\n" }, { "answer_id": 15688378, "author": "Christopher Stevenson", "author_id": 612512, "author_profile": "https://Stackoverflow.com/users/612512", "pm_score": -1, "selected": false, "text": "<p>Here's a thread-safe way to do this:</p>\n\n\n\n<pre><code>public static class EnumerableExtension\n{\n private static Random globalRng = new Random();\n\n [ThreadStatic]\n private static Random _rng;\n\n private static Random rng \n {\n get\n {\n if (_rng == null)\n {\n int seed;\n lock (globalRng)\n {\n seed = globalRng.Next();\n }\n _rng = new Random(seed);\n }\n return _rng;\n }\n }\n\n public static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; items)\n {\n return items.OrderBy (i =&gt; rng.Next());\n }\n}\n</code></pre>\n" }, { "answer_id": 20725319, "author": "Xelights", "author_id": 3126356, "author_profile": "https://Stackoverflow.com/users/3126356", "pm_score": 3, "selected": false, "text": "<p>If you don't mind using two <code>Lists</code>, then this is probably the easiest way to do it, but probably not the most efficient or unpredictable one: </p>\n\n<pre><code>List&lt;int&gt; xList = new List&lt;int&gt;() { 1, 2, 3, 4, 5 };\nList&lt;int&gt; deck = new List&lt;int&gt;();\n\nforeach (int xInt in xList)\n deck.Insert(random.Next(0, deck.Count + 1), xInt);\n</code></pre>\n" }, { "answer_id": 22668974, "author": "Shital Shah", "author_id": 207661, "author_profile": "https://Stackoverflow.com/users/207661", "pm_score": 7, "selected": false, "text": "<p>I'm bit surprised by all the clunky versions of this simple algorithm here. Fisher-Yates (or Knuth shuffle) is bit tricky but very compact. Why is it tricky? Because your need to pay attention to whether your random number generator <code>r(a,b)</code> returns value where <code>b</code> is inclusive or exclusive. I've also edited <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm\" rel=\"noreferrer\">Wikipedia description</a> so people don't blindly follow pseudocode there and create hard to detect bugs. For .Net, <code>Random.Next(a,b)</code> returns number exclusive of <code>b</code> so without further ado, here's how it can be implemented in C#/.Net:</p>\n\n<pre><code>public static void Shuffle&lt;T&gt;(this IList&lt;T&gt; list, Random rnd)\n{\n for(var i=list.Count; i &gt; 0; i--)\n list.Swap(0, rnd.Next(0, i));\n}\n\npublic static void Swap&lt;T&gt;(this IList&lt;T&gt; list, int i, int j)\n{\n var temp = list[i];\n list[i] = list[j];\n list[j] = temp;\n}\n</code></pre>\n\n<p><a href=\"https://dotnetfiddle.net/f7aG0o#\" rel=\"noreferrer\">Try this code</a>.</p>\n" }, { "answer_id": 24250251, "author": "sumit laddha", "author_id": 3746068, "author_profile": "https://Stackoverflow.com/users/3746068", "pm_score": -1, "selected": false, "text": "<pre><code> public Deck(IEnumerable&lt;Card&gt; initialCards) \n {\n cards = new List&lt;Card&gt;(initialCards);\n public void Shuffle() \n }\n {\n List&lt;Card&gt; NewCards = new List&lt;Card&gt;();\n while (cards.Count &gt; 0) \n {\n int CardToMove = random.Next(cards.Count);\n NewCards.Add(cards[CardToMove]);\n cards.RemoveAt(CardToMove);\n }\n cards = NewCards;\n }\n\npublic IEnumerable&lt;string&gt; GetCardNames() \n\n{\n string[] CardNames = new string[cards.Count];\n for (int i = 0; i &lt; cards.Count; i++)\n CardNames[i] = cards[i].Name;\n return CardNames;\n}\n\nDeck deck1;\nDeck deck2;\nRandom random = new Random();\n\npublic Form1() \n{\n\nInitializeComponent();\nResetDeck(1);\nResetDeck(2);\nRedrawDeck(1);\n RedrawDeck(2);\n\n}\n\n\n\n private void ResetDeck(int deckNumber) \n {\n if (deckNumber == 1) \n{\n int numberOfCards = random.Next(1, 11);\n deck1 = new Deck(new Card[] { });\n for (int i = 0; i &lt; numberOfCards; i++)\n deck1.Add(new Card((Suits)random.Next(4),(Values)random.Next(1, 14)));\n deck1.Sort();\n}\n\n\n else\n deck2 = new Deck();\n }\n\nprivate void reset1_Click(object sender, EventArgs e) {\nResetDeck(1);\nRedrawDeck(1);\n\n}\n\nprivate void shuffle1_Click(object sender, EventArgs e) \n{\n deck1.Shuffle();\n RedrawDeck(1);\n\n}\n\nprivate void moveToDeck1_Click(object sender, EventArgs e) \n{\n\n if (listBox2.SelectedIndex &gt;= 0)\n if (deck2.Count &gt; 0) {\n deck1.Add(deck2.Deal(listBox2.SelectedIndex));\n\n}\n\n RedrawDeck(1);\n RedrawDeck(2);\n\n}\n</code></pre>\n" }, { "answer_id": 25474564, "author": "Shehab Fawzy", "author_id": 1093516, "author_profile": "https://Stackoverflow.com/users/1093516", "pm_score": 2, "selected": false, "text": "<p>You can achieve that be using this simple extension method</p>\n\n<pre><code>public static class IEnumerableExtensions\n{\n\n public static IEnumerable&lt;t&gt; Randomize&lt;t&gt;(this IEnumerable&lt;t&gt; target)\n {\n Random r = new Random();\n\n return target.OrderBy(x=&gt;(r.Next()));\n } \n}\n</code></pre>\n\n<p>and you can use it by doing the following</p>\n\n<pre><code>// use this on any collection that implements IEnumerable!\n// List, Array, HashSet, Collection, etc\n\nList&lt;string&gt; myList = new List&lt;string&gt; { \"hello\", \"random\", \"world\", \"foo\", \"bar\", \"bat\", \"baz\" };\n\nforeach (string s in myList.Randomize())\n{\n Console.WriteLine(s);\n}\n</code></pre>\n" }, { "answer_id": 29580185, "author": "DavidMc", "author_id": 4556700, "author_profile": "https://Stackoverflow.com/users/4556700", "pm_score": -1, "selected": false, "text": "<p>Old post for sure, but I just use a GUID. </p>\n\n<pre><code>Items = Items.OrderBy(o =&gt; Guid.NewGuid().ToString()).ToList();\n</code></pre>\n\n<p>A GUID is always unique, and since it is regenerated every time the result changes each time. </p>\n" }, { "answer_id": 32666693, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 3, "selected": false, "text": "<p>This is my preferred method of a shuffle when it's desirable to not modify the original. It's a variant of the <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm\" rel=\"noreferrer\">Fisher–Yates \"inside-out\" algorithm</a> that works on any enumerable sequence (the length of <code>source</code> does not need to be known from start).</p>\n\n<pre><code>public static IList&lt;T&gt; NextList&lt;T&gt;(this Random r, IEnumerable&lt;T&gt; source)\n{\n var list = new List&lt;T&gt;();\n foreach (var item in source)\n {\n var i = r.Next(list.Count + 1);\n if (i == list.Count)\n {\n list.Add(item);\n }\n else\n {\n var temp = list[i];\n list[i] = item;\n list.Add(temp);\n }\n }\n return list;\n}\n</code></pre>\n\n<p>This algorithm can also be implemented by allocating a range from <code>0</code> to <code>length - 1</code> and randomly exhausting the indices by swapping the randomly chosen index with the last index until all indices have been chosen exactly once. This above code accomplishes the exact same thing but without the additional allocation. Which is pretty neat.</p>\n\n<p>With regards to the <code>Random</code> class it's a general purpose number generator (and If I was running a lottery I'd consider using something different). It also relies on a time based seed value by default. A small alleviation of the problem is to seed the <code>Random</code> class with the <code>RNGCryptoServiceProvider</code> or you could use the <code>RNGCryptoServiceProvider</code> in a method similar to this (see below) to generate uniformly chosen random double floating point values but running a lottery pretty much requires understanding randomness and the nature of the randomness source.</p>\n\n<pre><code>var bytes = new byte[8];\n_secureRng.GetBytes(bytes);\nvar v = BitConverter.ToUInt64(bytes, 0);\nreturn (double)v / ((double)ulong.MaxValue + 1);\n</code></pre>\n\n<p>The point of generating a random double (between 0 and 1 exclusively) is to use to scale to an integer solution. If you need to pick something from a list based on a random double <code>x</code> that's always going to be <code>0 &lt;= x &amp;&amp; x &lt; 1</code> is straight forward.</p>\n\n<pre><code>return list[(int)(x * list.Count)];\n</code></pre>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 46107526, "author": "Extragorey", "author_id": 6680521, "author_profile": "https://Stackoverflow.com/users/6680521", "pm_score": 1, "selected": false, "text": "<p>A simple modification of the <a href=\"https://stackoverflow.com/a/1262619/\">accepted answer</a> that returns a new list instead of working in-place, and accepts the more general <code>IEnumerable&lt;T&gt;</code> as many other Linq methods do.</p>\n\n<pre><code>private static Random rng = new Random();\n\n/// &lt;summary&gt;\n/// Returns a new list where the elements are randomly shuffled.\n/// Based on the Fisher-Yates shuffle, which has O(n) complexity.\n/// &lt;/summary&gt;\npublic static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; list) {\n var source = list.ToList();\n int n = source.Count;\n var shuffled = new List&lt;T&gt;(n);\n shuffled.AddRange(source);\n while (n &gt; 1) {\n n--;\n int k = rng.Next(n + 1);\n T value = shuffled[k];\n shuffled[k] = shuffled[n];\n shuffled[n] = value;\n }\n return shuffled;\n}\n</code></pre>\n" }, { "answer_id": 51606335, "author": "Andrey Kucher", "author_id": 10042064, "author_profile": "https://Stackoverflow.com/users/10042064", "pm_score": 4, "selected": false, "text": "<p>Idea is get anonymous object with item and random order and then reorder items by this order and return value:</p>\n\n<pre><code>var result = items.Select(x =&gt; new { value = x, order = rnd.Next() })\n .OrderBy(x =&gt; x.order).Select(x =&gt; x.value).ToList()\n</code></pre>\n" }, { "answer_id": 56836629, "author": "sultan s. alfaifi", "author_id": 7767814, "author_profile": "https://Stackoverflow.com/users/7767814", "pm_score": 1, "selected": false, "text": "<pre><code> List&lt;T&gt; OriginalList = new List&lt;T&gt;();\n List&lt;T&gt; TempList = new List&lt;T&gt;();\n Random random = new Random();\n int length = OriginalList.Count;\n int TempIndex = 0;\n\n while (length &gt; 0) {\n TempIndex = random.Next(0, length); // get random value between 0 and original length\n TempList.Add(OriginalList[TempIndex]); // add to temp list\n OriginalList.RemoveAt(TempIndex); // remove from original list\n length = OriginalList.Count; // get new list &lt;T&gt; length.\n }\n\n OriginalList = new List&lt;T&gt;();\n OriginalList = TempList; // copy all items from temp list to original list.\n</code></pre>\n" }, { "answer_id": 61982394, "author": "Ashokan Sivapragasam", "author_id": 6928056, "author_profile": "https://Stackoverflow.com/users/6928056", "pm_score": 2, "selected": false, "text": "<p>I have found an interesting solution online.</p>\n\n<p>Courtesy: <a href=\"https://improveandrepeat.com/2018/08/a-simple-way-to-shuffle-your-lists-in-c/\" rel=\"nofollow noreferrer\">https://improveandrepeat.com/2018/08/a-simple-way-to-shuffle-your-lists-in-c/</a></p>\n\n<p>var shuffled = myList.OrderBy(x => Guid.NewGuid()).ToList();</p>\n" }, { "answer_id": 63088730, "author": "JohnC", "author_id": 808815, "author_profile": "https://Stackoverflow.com/users/808815", "pm_score": 1, "selected": false, "text": "<p>Here is an implementation of the Fisher-Yates shuffle that allows specification of the number of elements to return; hence, it is not necessary to first sort the whole collection before taking your desired number of elements.</p>\n<p>The sequence of swapping elements is reversed from default; and proceeds from the first element to the last element, so that retrieving a subset of the collection yields the same (partial) sequence as shuffling the whole collection:</p>\n<pre><code>collection.TakeRandom(5).SequenceEqual(collection.Shuffle().Take(5)); // true\n</code></pre>\n<p>This algorithm is based on Durstenfeld's (modern) version of the <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm\" rel=\"nofollow noreferrer\">Fisher-Yates shuffle</a> on Wikipedia.</p>\n<pre><code>public static IList&lt;T&gt; TakeRandom&lt;T&gt;(this IEnumerable&lt;T&gt; collection, int count, Random random) =&gt; shuffle(collection, count, random);\npublic static IList&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; collection, Random random) =&gt; shuffle(collection, null, random);\nprivate static IList&lt;T&gt; shuffle&lt;T&gt;(IEnumerable&lt;T&gt; collection, int? take, Random random)\n{\n var a = collection.ToArray();\n var n = a.Length;\n if (take &lt;= 0 || take &gt; n) throw new ArgumentException(&quot;Invalid number of elements to return.&quot;);\n var end = take ?? n;\n for (int i = 0; i &lt; end; i++)\n {\n var j = random.Next(i, n);\n (a[i], a[j]) = (a[j], a[i]);\n }\n\n if (take.HasValue) return new ArraySegment&lt;T&gt;(a, 0, take.Value);\n return a;\n}\n</code></pre>\n" }, { "answer_id": 63348412, "author": "Garrison Becker", "author_id": 9068304, "author_profile": "https://Stackoverflow.com/users/9068304", "pm_score": 0, "selected": false, "text": "<p>Your question is how to <strong>randomize</strong> a list. This means:</p>\n<ol>\n<li>All unique combinations should be possible of happening</li>\n<li>All unique combinations should occur with the same distribution (AKA being non-biased).</li>\n</ol>\n<p>A large number of the answers posted for this question do NOT satisfy the two requirements above for being &quot;random&quot;.</p>\n<p>Here's a compact, non-biased pseudo-random function following the Fisher-Yates shuffle method.</p>\n<pre><code>public static void Shuffle&lt;T&gt;(this IList&lt;T&gt; list, Random rnd)\n{\n for (var i = list.Count-1; i &gt; 0; i--)\n {\n var randomIndex = rnd.Next(i + 1); //maxValue (i + 1) is EXCLUSIVE\n list.Swap(i, randomIndex); \n }\n}\n\npublic static void Swap&lt;T&gt;(this IList&lt;T&gt; list, int indexA, int indexB)\n{\n var temp = list[indexA];\n list[indexA] = list[indexB];\n list[indexB] = temp;\n}\n</code></pre>\n" }, { "answer_id": 63799666, "author": "Seva", "author_id": 6529286, "author_profile": "https://Stackoverflow.com/users/6529286", "pm_score": 2, "selected": false, "text": "<p>Just wanted to suggest a variant using an <code>IComparer&lt;T&gt;</code> and <code>List.Sort()</code>:</p>\n<pre><code>public class RandomIntComparer : IComparer&lt;int&gt;\n{\n private readonly Random _random = new Random();\n \n public int Compare(int x, int y)\n {\n return _random.Next(-1, 2);\n }\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>list.Sort(new RandomIntComparer());\n</code></pre>\n" }, { "answer_id": 64275044, "author": "Adrian Rus", "author_id": 497423, "author_profile": "https://Stackoverflow.com/users/497423", "pm_score": 2, "selected": false, "text": "<p>One can use the Shuffle extension methond from morelinq package, it works on IEnumerables</p>\n<blockquote>\n<p>install-package morelinq</p>\n</blockquote>\n<pre><code>using MoreLinq;\n... \nvar randomized = list.Shuffle();\n</code></pre>\n" }, { "answer_id": 64710349, "author": "Kannan K Mannadiar", "author_id": 10799923, "author_profile": "https://Stackoverflow.com/users/10799923", "pm_score": -1, "selected": false, "text": "<pre><code>private List&lt;GameObject&gt; ShuffleList(List&lt;GameObject&gt; ActualList) {\n\n\n List&lt;GameObject&gt; newList = ActualList;\n List&lt;GameObject&gt; outList = new List&lt;GameObject&gt;();\n\n int count = newList.Count;\n\n while (newList.Count &gt; 0) {\n\n int rando = Random.Range(0, newList.Count);\n\n outList.Add(newList[rando]);\n\n newList.RemoveAt(rando);\n\n \n\n }\n\n return (outList);\n\n}\n</code></pre>\n<p>usage :</p>\n<pre><code>List&lt;GameObject&gt; GetShuffle = ShuffleList(ActualList);\n</code></pre>\n" }, { "answer_id": 69220421, "author": "James Bateson", "author_id": 2768119, "author_profile": "https://Stackoverflow.com/users/2768119", "pm_score": 2, "selected": false, "text": "<p>You can make the Fisher-Yates shuffle more terse and expressive by using tuples for the swap.</p>\n<pre><code>private static readonly Random random = new Random();\n\npublic static void Shuffle&lt;T&gt;(this IList&lt;T&gt; list)\n{\n int n = list.Count;\n while (n &gt; 1)\n {\n n--;\n int k = random.Next(n + 1);\n (list[k], list[n]) = (list[n], list[k]);\n }\n}\n</code></pre>\n" }, { "answer_id": 71458345, "author": "Mark Cilia Vincenti", "author_id": 9945524, "author_profile": "https://Stackoverflow.com/users/9945524", "pm_score": 1, "selected": false, "text": "<p>We can use an extension method for List and use a thread-safe random generator combination.</p>\n<pre><code>public static class ListExtensions\n{\n public static void Shuffle&lt;T&gt;(this IList&lt;T&gt; list)\n {\n if (list == null) throw new ArgumentNullException(nameof(list));\n int n = list.Count;\n while (n &gt; 1)\n {\n n--;\n int k = ThreadSafeRandom.Next(n + 1);\n (list[n], list[k]) = (list[k], list[n]);\n }\n }\n}\n\ninternal class ThreadSafeRandom\n{\n private static readonly Random _global = new Random();\n private static readonly ThreadLocal&lt;Random&gt; _local = new ThreadLocal&lt;Random&gt;(() =&gt;\n {\n int seed;\n lock (_global)\n {\n seed = _global.Next();\n }\n return new Random(seed);\n });\n\n public static int Next(int maxValue)\n {\n return _local.Value.Next(maxValue);\n }\n}\n</code></pre>\n<p>I've packaged this on <a href=\"https://www.nuget.org/packages/ListShuffle\" rel=\"nofollow noreferrer\">NuGet</a> with the source code available on <a href=\"https://github.com/MarkCiliaVincenti/ListShuffle\" rel=\"nofollow noreferrer\">GitHub</a>.</p>\n" }, { "answer_id": 73947663, "author": "Gennadii Saltyshchak", "author_id": 1719383, "author_profile": "https://Stackoverflow.com/users/1719383", "pm_score": 1, "selected": false, "text": "<p>Implementation:</p>\n<pre><code>public static class ListExtensions\n{\n public static void Shuffle&lt;T&gt;(this IList&lt;T&gt; list, Random random)\n {\n for (var i = list.Count - 1; i &gt; 0; i--)\n {\n int indexToSwap = random.Next(i + 1);\n (list[indexToSwap], list[i]) = (list[i], list[indexToSwap]);\n }\n }\n}\n</code></pre>\n<p>Example:</p>\n<pre><code>var random = new Random();\nvar array = new [] { 1, 2, 3 };\narray.Shuffle(random);\nforeach (var item in array) {\n Console.WriteLine(item);\n}\n</code></pre>\n<p><a href=\"https://dotnetfiddle.net/MwVX7q\" rel=\"nofollow noreferrer\">Demonstration in .NET Fiddle</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35286/" ]
What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application.
Shuffle any `(I)List` with an extension method based on the [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle): ``` private static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } ``` Usage: ``` List<Product> products = GetProducts(); products.Shuffle(); ``` The code above uses the much criticised System.Random method to select swap candidates. It's fast but not as random as it should be. If you need a better quality of randomness in your shuffles use the random number generator in System.Security.Cryptography like so: ``` using System.Security.Cryptography; ... public static void Shuffle<T>(this IList<T> list) { RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); int n = list.Count; while (n > 1) { byte[] box = new byte[1]; do provider.GetBytes(box); while (!(box[0] < n * (Byte.MaxValue / n))); int k = (box[0] % n); n--; T value = list[k]; list[k] = list[n]; list[n] = value; } } ``` A simple comparison is available [at this blog](https://web.archive.org/web/20150801085341/http://blog.thijssen.ch/2010/02/when-random-is-too-consistent.html) (WayBack Machine). Edit: Since writing this answer a couple years back, many people have commented or written to me, to point out the big silly flaw in my comparison. They are of course right. There's nothing wrong with System.Random if it's used in the way it was intended. In my first example above, I instantiate the rng variable inside of the Shuffle method, which is asking for trouble if the method is going to be called repeatedly. Below is a fixed, full example based on a really useful comment received today from @weston here on SO. Program.cs: ``` using System; using System.Collections.Generic; using System.Threading; namespace SimpleLottery { class Program { private static void Main(string[] args) { var numbers = new List<int>(Enumerable.Range(1, 75)); numbers.Shuffle(); Console.WriteLine("The winning numbers are: {0}", string.Join(", ", numbers.GetRange(0, 5))); } } public static class ThreadSafeRandom { [ThreadStatic] private static Random Local; public static Random ThisThreadsRandom { get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); } } } static class MyExtensions { public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } } } ```
273,314
<p>For example, in <a href="http://homepages.cwi.nl/~paulv/papers/algorithmicstatistics.pdf" rel="noreferrer">http://homepages.cwi.nl/~paulv/papers/algorithmicstatistics.pdf</a> at the bottom of page 5 and top of page 6, he uses a plus/equal symbol and a similar plus/lessthan symbol. I can't figure out how to make that symbol, and I'd like to quote him.</p> <p>Any help?</p>
[ { "answer_id": 273338, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>Here's the list of <a href=\"http://web.ift.uib.no/Fysisk/Teori/KURS/WRK/TeX/symALL.html\" rel=\"nofollow noreferrer\">Latex Math Symbols</a>. I don't see the two from the PDF you linked to. Do you know what they mean? You might be able to find an equivalent in the Latex list.</p>\n" }, { "answer_id": 273394, "author": "Jim Keener", "author_id": 35338, "author_profile": "https://Stackoverflow.com/users/35338", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.ctan.org/tex-archive/info/symbols/comprehensive/symbols-a4.pdf\" rel=\"nofollow noreferrer\">The Comprehensive LaTeX Symbol List</a> (from <a href=\"http://www.ctan.org/tex-archive/info/symbols/comprehensive/\" rel=\"nofollow noreferrer\">here</a>) is a great resource, and start for questions like this. You could also contact the author, it's possible he did some LaTex voodoo (math accents and such) to get it to work.</p>\n\n<p>Best of luck.</p>\n\n<p>PS: isn't \\pm plus-minus, not plus-equals?</p>\n" }, { "answer_id": 273402, "author": "Noah", "author_id": 28035, "author_profile": "https://Stackoverflow.com/users/28035", "pm_score": 6, "selected": true, "text": "<p>Try <code>$\\stackrel{top}{bottom}$</code></p>\n\n<p>You'd want something like this:</p>\n\n<pre><code>$X \\stackrel{+}{=} Y$\n</code></pre>\n\n<p>This positions the plus sign above the equals sign. For example, the following code:</p>\n\n<pre><code>$K(x,y|z) \\stackrel{+}{=} K(x|z) \\stackrel{+}{&lt;} I(x:y|z)$\n</code></pre>\n\n<p>produces the following output:</p>\n\n<p><img src=\"https://i.stack.imgur.com/fbaAX.png\" alt=\"Equation including + sign over = sign\"></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35600/" ]
For example, in <http://homepages.cwi.nl/~paulv/papers/algorithmicstatistics.pdf> at the bottom of page 5 and top of page 6, he uses a plus/equal symbol and a similar plus/lessthan symbol. I can't figure out how to make that symbol, and I'd like to quote him. Any help?
Try `$\stackrel{top}{bottom}$` You'd want something like this: ``` $X \stackrel{+}{=} Y$ ``` This positions the plus sign above the equals sign. For example, the following code: ``` $K(x,y|z) \stackrel{+}{=} K(x|z) \stackrel{+}{<} I(x:y|z)$ ``` produces the following output: ![Equation including + sign over = sign](https://i.stack.imgur.com/fbaAX.png)
273,353
<p>Note: The examples below are C# but this problem should not be specific to any language in particular.</p> <p>So I am building an object domain using a variant of the <a href="http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx" rel="nofollow noreferrer">S# Architecture</a>. For those unfamiliar with it, and to save you some reading time the idea is simply that you have a Data Access Object Interface for each of your domain objects that is responsible for loading to/from the persistence layer. Everything that might ever need to load/save a given object then accepts that object's data access interface as a dependency. So for example we can have the following where a product will lazy load the customer that purchased it as needed:</p> <pre><code>public class Product { private ICustomerDao _customerDao; private Customer _customer; public Product(ICustomerDao customerDao) {_customerDao = customerDao;} public int ProductId {get; set;} public int CustomerId {get; set;} public Customer Customer { get{ if(_customer == null) _customer = _customerDao.GetById(CustomerId); return _customer; } } public interface ICustomerDao { public Customer GetById(int id); } </code></pre> <p>This is all well and good until you reach a situation where two objects need to be able to load each other. For example a many-to-one relationship where, as above, a product needs to be able to lazy load its customer, but also customer needs to be able to get a list of his products.</p> <pre><code>public class Customer { private IProductDao _productDao; private Product[] _products; public Customer(IProductDao productDao) {_productDao = productDao;} public int CustomerId {get; set;} public Product[] Products { get{ if(_products == null) _products = _productDao. GetAllForCustomer(this); return _products; } } public interface IProductDao { public Product[] GetAllForCustomer(Customer customer); } </code></pre> <p>I know that this is a really common situation but I am relatively new at this. My stumbling block is what to do when implementing the Data Access Objects. Because a Customer has a dependency on IProductDao, the CustomerDao implementation must also, however the vice versa is also true and ProductDao must take a dependency on ICustomerDao.</p> <pre><code>public class CustomerDao : ICustomerDao { private IProductDao _productDao; public CustomerDao(IProductDao productDao) {_productDao = productDao;} public Customer GetById(int id) { Customer c = new Customer(_customerDao); // Query the database and fill out CustomerId return c; } } public class ProductDao : IProductDao { private ICustomerDao _customerDao; public ProductDao (ICustomerDao customerDao) {_customerDao = customerDao;} public Product[] GetAllForCustomer(Customer customer) { // you get the idea } } </code></pre> <p>And here we have the problem. You cannot instantiate CustomerDao without an IProductDao and vice versa. My inversion of control container (Castle Windsor) hits the circular dependency and chokes.</p> <p>I have come up with a for-the-time-being solution which involves lazy loading the DAO objects themselves (I will post this as an answer) but I don't like it. What are the time-tested solutions to this problem?</p> <p><strong>EDIT:</strong> The above is a simplification of the architecture I'm actually using and I am not recommending someone actually pass DAOs to an object. A better implementation closer to what I am actually doing is similar to the way NHibernate works where the actual objects are very simple and the above are actually proxy objects which inherit and override the appropriate fields.</p>
[ { "answer_id": 273390, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 1, "selected": false, "text": "<p>The lazy loading should be managed by your persistance layer, not your repositories.</p>\n\n<p>Also your Customer and Product objects shouldn't have any references to the repositories, that just seems... wrong.</p>\n" }, { "answer_id": 273392, "author": "Chris Bilson", "author_id": 12934, "author_profile": "https://Stackoverflow.com/users/12934", "pm_score": 0, "selected": false, "text": "<p>You simply shouldn't have circular dependencies like this. It's just wrong.</p>\n\n<p>If you just need to be wrong for a little while to get over the hump, then try using a service locator: a class that knows about the container and resolves dependencies when they are used instead of when your DAO class is being instantiated.</p>\n\n<p>You might want to check out Oren Eini's service locator implementation in Rhino.Tools (it's a static class called IoC)</p>\n" }, { "answer_id": 273395, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 0, "selected": false, "text": "<p>My solution, and let me disclaim yet again that I am not a big fan of it is to have each of the data access objects lazy load the DAOs it depends on directly from the container. For simplicity's sake I make both the CustomerDao and ProductDao inherit from a BaseDao object and then implement it as follows:</p>\n\n<pre><code>public abstract class BaseDao() {\n private ICustomerDao _customerDao;\n protected ICustomerDao _CustomerDao {\n get {\n if(_customerDao == null) _customerDao = IoC.Container.Resolve&lt;ICustomerDao&gt;();\n return _customerDao;\n }\n private IProductDao _productDao;\n protected IProductDao _ProductDao {\n get {\n if(_productDao == null) _productDao = IoC.Container.Resolve&lt; IProductDao &gt;();\n return _productDao;\n }\n</code></pre>\n\n<p>}</p>\n\n<p>and then </p>\n\n<pre><code>public class CustomerDao : BaseDao, ICustomerDao {\n public Customer GetById(int id) {\n Customer c = new Customer(_CustomerDao);\n // Query the database and fill out CustomerId\n return c;\n }\n }\npublic class ProductDao : BaseDao, IProductDao {\n public Product[] GetAllForCustomer(Customer customer) {\n // use the base class's _ProductDao to instantiate Products\n }\n }\n</code></pre>\n\n<p>I don't like this because </p>\n\n<ul>\n<li>a) Each DAO now has a dependency on\nthe container </li>\n<li>b) You can no longer\ntell from the constructor who each\nDao depends on </li>\n<li>c) Either each DAO\n needs at least an implicit\n dependency on each other Dao if you\n use such a base class or you could\n move the lazy loading out of the\n base class but have to duplicate a\n great deal of code.</li>\n<li>d) Unit tests\n need to create and pre-fill the\n Container</li>\n</ul>\n" }, { "answer_id": 274144, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 2, "selected": true, "text": "<p>I just discovered a significantly better approach that works at least with Castle Windsor. By changing the data access object dependencies to properties rather than constructor dependencies Windsor will autofill them after instantiating each object fully.</p>\n\n<p>So the following works just fine:</p>\n\n<pre><code>public class CustomerDao : ICustomerDao {\n\n private IProductDao _productDao;\n\n public IProductDao ProductDao {\n get { return _productDao; }\n set { _productDao = value; }\n }\n public CustomerDao() { }\n public Customer GetById(int id) {\n Customer c = new Customer(_productDao);\n // Query the database and fill out CustomerId\n return c;\n }\n}\npublic class ProductDao : IProductDao {\n private ICustomerDao _customerDao;\n\n public ProductDao() { }\n\n public ICustomerDao CustomerDao {\n get { return _customerDao; }\n set { _customerDao = value; }\n }\n\n public Product[] GetAllForCustomer(Customer customer) {\n return null;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 291507, "author": "remotefacade", "author_id": 29091, "author_profile": "https://Stackoverflow.com/users/29091", "pm_score": 2, "selected": false, "text": "<p>As the other posters have suggested, you might want to rethink your architecture - it looks like you are making things hard on yourself.</p>\n\n<p>Also note:</p>\n\n<blockquote>\n <p>By changing the data access object\n dependencies to properties rather than\n constructor dependencies Windsor will\n autofill them after instantiating each\n object fully.</p>\n</blockquote>\n\n<p>Be careful. In doing this, you've basically told Windsor that these dependencies are optional (unlike dependencies injected via the constructor). This seems like a bad idea, unless these dependencies <strong>are</strong> truly optional. If Windsor can't fulfill a required dependency, you <em>want</em> it to puke.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Note: The examples below are C# but this problem should not be specific to any language in particular. So I am building an object domain using a variant of the [S# Architecture](http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx). For those unfamiliar with it, and to save you some reading time the idea is simply that you have a Data Access Object Interface for each of your domain objects that is responsible for loading to/from the persistence layer. Everything that might ever need to load/save a given object then accepts that object's data access interface as a dependency. So for example we can have the following where a product will lazy load the customer that purchased it as needed: ``` public class Product { private ICustomerDao _customerDao; private Customer _customer; public Product(ICustomerDao customerDao) {_customerDao = customerDao;} public int ProductId {get; set;} public int CustomerId {get; set;} public Customer Customer { get{ if(_customer == null) _customer = _customerDao.GetById(CustomerId); return _customer; } } public interface ICustomerDao { public Customer GetById(int id); } ``` This is all well and good until you reach a situation where two objects need to be able to load each other. For example a many-to-one relationship where, as above, a product needs to be able to lazy load its customer, but also customer needs to be able to get a list of his products. ``` public class Customer { private IProductDao _productDao; private Product[] _products; public Customer(IProductDao productDao) {_productDao = productDao;} public int CustomerId {get; set;} public Product[] Products { get{ if(_products == null) _products = _productDao. GetAllForCustomer(this); return _products; } } public interface IProductDao { public Product[] GetAllForCustomer(Customer customer); } ``` I know that this is a really common situation but I am relatively new at this. My stumbling block is what to do when implementing the Data Access Objects. Because a Customer has a dependency on IProductDao, the CustomerDao implementation must also, however the vice versa is also true and ProductDao must take a dependency on ICustomerDao. ``` public class CustomerDao : ICustomerDao { private IProductDao _productDao; public CustomerDao(IProductDao productDao) {_productDao = productDao;} public Customer GetById(int id) { Customer c = new Customer(_customerDao); // Query the database and fill out CustomerId return c; } } public class ProductDao : IProductDao { private ICustomerDao _customerDao; public ProductDao (ICustomerDao customerDao) {_customerDao = customerDao;} public Product[] GetAllForCustomer(Customer customer) { // you get the idea } } ``` And here we have the problem. You cannot instantiate CustomerDao without an IProductDao and vice versa. My inversion of control container (Castle Windsor) hits the circular dependency and chokes. I have come up with a for-the-time-being solution which involves lazy loading the DAO objects themselves (I will post this as an answer) but I don't like it. What are the time-tested solutions to this problem? **EDIT:** The above is a simplification of the architecture I'm actually using and I am not recommending someone actually pass DAOs to an object. A better implementation closer to what I am actually doing is similar to the way NHibernate works where the actual objects are very simple and the above are actually proxy objects which inherit and override the appropriate fields.
I just discovered a significantly better approach that works at least with Castle Windsor. By changing the data access object dependencies to properties rather than constructor dependencies Windsor will autofill them after instantiating each object fully. So the following works just fine: ``` public class CustomerDao : ICustomerDao { private IProductDao _productDao; public IProductDao ProductDao { get { return _productDao; } set { _productDao = value; } } public CustomerDao() { } public Customer GetById(int id) { Customer c = new Customer(_productDao); // Query the database and fill out CustomerId return c; } } public class ProductDao : IProductDao { private ICustomerDao _customerDao; public ProductDao() { } public ICustomerDao CustomerDao { get { return _customerDao; } set { _customerDao = value; } } public Product[] GetAllForCustomer(Customer customer) { return null; } } ```
273,354
<p>I am a big time user of using double quotes in PHP so that I can interpolate variables rather than concatenating strings. As a result, when I am generating HTML I often use single quotes for setting tag fields. For example:</p> <pre><code>$html = "&lt;input type='text' name='address' value='$address'&gt;"; </code></pre> <p>Now this is far more readable to me than either</p> <pre><code>$html = "&lt;input type=\"text\" name=\"address\" value=\"$address\"&gt;"; </code></pre> <p>or</p> <pre><code>$html = '&lt;input type="text" name="address" values="' . $address . '"&gt;' ; </code></pre> <p>From brief searches I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser. Thus I am wondering what browsers would have problems recognizing single quote HTML?</p>
[ { "answer_id": 273366, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": false, "text": "<p>This is similar to <a href=\"https://stackoverflow.com/questions/242766/when-did-single-quotes-in-html-become-so-popular\">When did single quotes in HTML become so popular?</a>. Single quotes around attributes in HTML are and always have been permitted by <a href=\"http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2\" rel=\"noreferrer\">the specification</a>. I don't think any browsers wouldn't understand them.</p>\n" }, { "answer_id": 273368, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "<p>I also tend to use single quotes in HTML and I have never experienced a problem.</p>\n" }, { "answer_id": 273373, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser</p>\n</blockquote>\n\n<p>That person is wrong.</p>\n" }, { "answer_id": 273430, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": -1, "selected": false, "text": "<p>Single Quotes are fine for HTML, but they don't make valid XHTML, which might be problematic if anybody was using a browser which supported only XHTML, but not HTML. I don't believe any such browsers exist, though there are probably some User-Agents out there that do require strict XHTML. </p>\n" }, { "answer_id": 273561, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": false, "text": "<p>Don't believe everything you see on Internet...<br>\nFunnily, I just answered something similar to somebody declaring single quotes are not valid in XHTML...</p>\n\n<p>Mmm, I look above while typing, and see that Adam N propagates the same belief. If he can back up his affirmation, I retract what I wrote... AFAIK, XML is agnostic and accepts both kinds of quote. I even tried and validated without problem an XHTML page with only single quotes.</p>\n" }, { "answer_id": 273604, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 6, "selected": false, "text": "<p>As noted by PhiLho, although there is a widely spread belief that single quotes are not allowed for attribute values, that belief is wrong.</p>\n\n<p>The <a href=\"http://www.w3.org/TR/REC-xml/#NT-AttValue\" rel=\"noreferrer\">XML standard</a> permits both single and double quotes around attribute values.</p>\n\n<p>The XHTML standard doesn't say anything to change this, but a related section which states that <a href=\"http://www.w3.org/TR/xhtml1/#h-4.4\" rel=\"noreferrer\">attribute values must be quoted</a> uses double quotes in the example, which has probably lead to this confusion. This example is merely pointing out that attribute values in XHTML must meet the minimum standard for attribute values in XML, which means they must be quoted (as opposed to plain HTML which doesn't care), but does not restrict you to either single or double quotes.</p>\n\n<p>Of course, it's always possible that you'll encounter a parser which isn't standards-compliant, but when that happens all bets are off anyway. So it's best to just stick to what the specification says. That's why we have specifications, after all.</p>\n" }, { "answer_id": 9718124, "author": "inteblio", "author_id": 371983, "author_profile": "https://Stackoverflow.com/users/371983", "pm_score": 3, "selected": false, "text": "<p>Only problem is data going into TEXT INPUT fields. Consider</p>\n<pre><code>&lt;input value='it's gonna break'/&gt;\n</code></pre>\n<p>Same with:</p>\n<pre><code>&lt;input value=&quot;i say - &quot;this is gonna be trouble&quot; &quot;/&gt;\n</code></pre>\n<p>You can't escape that, you have to use <a href=\"https://www.php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow noreferrer\"><code>htmlspecialchars</code></a>.</p>\n" }, { "answer_id": 16198937, "author": "mcandre", "author_id": 350106, "author_profile": "https://Stackoverflow.com/users/350106", "pm_score": -1, "selected": false, "text": "<p>... or just use heredocs. Then you don't need to worry about escaping anything but <code>END</code>.</p>\n" }, { "answer_id": 21870871, "author": "rchacko", "author_id": 3056160, "author_profile": "https://Stackoverflow.com/users/3056160", "pm_score": 1, "selected": false, "text": "<p>I used single quotes in HTML pages and embedded JavaScripts into it and its works fine. Tested in IE9, Chrome and Firefox - seems working fine. </p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;meta charset='utf-8'&gt;\n &lt;meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'&gt;\n &lt;title&gt;Bethanie Inc. data : geographically linked&lt;/title&gt;\n &lt;script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'&gt;&lt;/script&gt;\n &lt;script src='https://maps.googleapis.com/maps/api/js?v=3.11&amp;sensor=false' type='text/javascript'&gt;&lt;/script&gt;\n &lt;script type='text/javascript'&gt; \n // check DOM Ready\n $(document).ready(function() {\n // execute\n (function() {\n /////////////// Addresses ///////////////////\n var locations = new Array();\n var i = 0;\n locations[i++] = 'L,Riversea: Comp Site1 at Riversea,1 Wallace Lane Mosman Park WA 6012'\n locations[i++] = 'L,Wearne: Comp Site2 at Wearne,1 Gibney St Cottesloe WA 6011'\n locations[i++] = 'L,Beachside:Comp Site3 Beachside,629 Two Rocks Rd Yanchep WA 6035'\n\n /////// Addresses/////////\n var total_locations = i;\n i = 0;\n console.log('About to look up ' + total_locations + ' locations');\n // map options\n var options = {\n zoom: 10,\n center: new google.maps.LatLng(-31.982484, 115.789329),//Bethanie \n mapTypeId: google.maps.MapTypeId.ROADMAP,\n mapTypeControl: true\n };\n // init map\n console.log('Initialise map...');\n var map = new google.maps.Map(document.getElementById('map_canvas'), options);\n // use the Google API to translate addresses to GPS coordinates \n //(See Limits: https://developers.google.com/maps/documentation/geocoding/#Limits)\n var geocoder = new google.maps.Geocoder();\n if (geocoder) {\n console.log('Got a new instance of Google Geocoder object');\n // Call function 'createNextMarker' every second\n var myVar = window.setInterval(function(){createNextMarker()}, 700);\n function createNextMarker() {\n if (i &lt; locations.length) \n {\n var customer = locations[i];\n var parts = customer.split(','); // split line into parts (fields)\n var type= parts.splice(0,1); // type from location line (remove)\n var name = parts.splice(0,1); // name from location line(remove)\n var address =parts.join(','); // combine remaining parts\n console.log('Looking up ' + name + ' at address ' + address);\n geocoder.geocode({ 'address': address }, makeCallback(name, type));\n i++; // next location in list\n updateProgressBar(i / total_locations);\n\n\n } else \n {\n console.log('Ready looking up ' + i + ' addresses');\n window.clearInterval(myVar);\n }\n }\n\n function makeCallback(name,type) \n {\n var geocodeCallBack = function (results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n var longitude = results[0].geometry.location.lng();\n var latitude = results[0].geometry.location.lat();\n console.log('Received result: lat:' + latitude + ' long:' + longitude);\n var marker = new google.maps.Marker({\n position: new google.maps.LatLng(latitude, longitude),\n map: map,\n title: name + ' : ' + '\\r\\n' + results[0].formatted_address});// this is display in tool tip/ icon color\n if (type=='E') {marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')};\n</code></pre>\n" }, { "answer_id": 29123143, "author": "Gena Moroz", "author_id": 2739900, "author_profile": "https://Stackoverflow.com/users/2739900", "pm_score": -1, "selected": false, "text": "<p>Recently i've experienced a problem with Google Search optimization. If has a single quotes, it doesn't seem to crawl linked pages. </p>\n" }, { "answer_id": 55906574, "author": "connexo", "author_id": 3744304, "author_profile": "https://Stackoverflow.com/users/3744304", "pm_score": 3, "selected": false, "text": "<p>As I was looking to find information on this in a <strong>much more recent version of the specification</strong> and it took me quite some time to find it, here it is:</p>\n<p>From</p>\n<blockquote>\n<h1>HTML</h1>\n<h2>Living Standard — Last Updated 17 September 2021</h2>\n<p>[...]</p>\n<h3>13.1.2.3 Attributes</h3>\n<h4><strong>Single-quoted attribute value syntax</strong></h4>\n</blockquote>\n<blockquote>\n<p>The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character (').<br />\nIn the following example, the type attribute is given with the single-quoted attribute value syntax:</p>\n</blockquote>\n<blockquote>\n<pre><code>&lt;input type='checkbox'&gt;\n</code></pre>\n</blockquote>\n<blockquote>\n<p>If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.</p>\n</blockquote>\n<blockquote>\n<p><a href=\"https://html.spec.whatwg.org/#attributes-2\" rel=\"nofollow noreferrer\">https://html.spec.whatwg.org/#attributes-2</a></p>\n</blockquote>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am a big time user of using double quotes in PHP so that I can interpolate variables rather than concatenating strings. As a result, when I am generating HTML I often use single quotes for setting tag fields. For example: ``` $html = "<input type='text' name='address' value='$address'>"; ``` Now this is far more readable to me than either ``` $html = "<input type=\"text\" name=\"address\" value=\"$address\">"; ``` or ``` $html = '<input type="text" name="address" values="' . $address . '">' ; ``` From brief searches I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser. Thus I am wondering what browsers would have problems recognizing single quote HTML?
This is similar to [When did single quotes in HTML become so popular?](https://stackoverflow.com/questions/242766/when-did-single-quotes-in-html-become-so-popular). Single quotes around attributes in HTML are and always have been permitted by [the specification](http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2). I don't think any browsers wouldn't understand them.
273,356
<p>I have some pages on my site that are plain HTML pages, but I want to add some ASP .NET type functionality to these pages. My concern is that if I simple rename the .html page to .aspx that I will break links, and lose SEO, and so on.</p> <p>I would think there is a "best practice" for how to handle this situation.</p>
[ { "answer_id": 273362, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 0, "selected": false, "text": "<p>You could use ISAPI rewrite to redirect the .html urls to the .aspx urls. </p>\n\n<p>The idea here is that you rename all the existing pages to .aspx, but have all incoming requests handled as a permanent redirect (301) to the new .aspx pages. This means all incoming links to *.html will find the correct *.aspx page.</p>\n" }, { "answer_id": 273372, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": -1, "selected": false, "text": "<p>If the new ASP.NET functionalities is minor, I would recommend to include IFrames inside your HTML which links to the new created ASP.NET pages containing your minor dynamic changes.</p>\n" }, { "answer_id": 273397, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>If you control IIS - you could just map .HTML to the ASP.NET handler and run them as is. Or, map them to a custom HttpHandler and send a 301 code with the updated location.</p>\n" }, { "answer_id": 273403, "author": "Tim Boland", "author_id": 70, "author_profile": "https://Stackoverflow.com/users/70", "pm_score": -1, "selected": false, "text": "<p>Changing over to aspx should not break any SEO</p>\n" }, { "answer_id": 273411, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "<p>Create your new pages on aspx, and just serve 301 permanent redirects from the HTML pages.</p>\n\n<p>Search spiders are smart enough to realize the content has moved and will not penalize you.</p>\n\n<p>Both Google and Yahoo also say that they parse a meta-refresh with no delay as a 301 redirect, so just do something like this:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Moved to new URL: http://example.com/newurl&lt;/title&gt;\n&lt;meta http-equiv=\"refresh\" content=\"0; url=http://example.com/newurl\" /&gt;\n&lt;meta name=\"robots\" content=\"noindex,follow\" /&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;h1&gt;This page has been moved to http://example.com/newurl&lt;/h1&gt;\n&lt;p&gt;If your browser doesn't redirect you to the new location please &lt;a href=\"http://example.com/newurl\"&gt;&lt;b&gt;click here&lt;/b&gt;&lt;/a&gt;, sorry for the hassles!&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 273413, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>All this would work, but I think a lot depends on the content of the pages, the amount of programming you need to add to it, and the plans going forward. If they are valued by search engines, </p>\n\n<p>In general, however, I think your best bet would be to create new pages and 301 redirect the html pages to the .aspx pages. Alternatively, you could do a URL rewrite to display the .aspx page while leaving the URL the same, but that is not a very scalable solution.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23294/" ]
I have some pages on my site that are plain HTML pages, but I want to add some ASP .NET type functionality to these pages. My concern is that if I simple rename the .html page to .aspx that I will break links, and lose SEO, and so on. I would think there is a "best practice" for how to handle this situation.
Create your new pages on aspx, and just serve 301 permanent redirects from the HTML pages. Search spiders are smart enough to realize the content has moved and will not penalize you. Both Google and Yahoo also say that they parse a meta-refresh with no delay as a 301 redirect, so just do something like this: ``` <html> <head> <title>Moved to new URL: http://example.com/newurl</title> <meta http-equiv="refresh" content="0; url=http://example.com/newurl" /> <meta name="robots" content="noindex,follow" /> </head> <body> <h1>This page has been moved to http://example.com/newurl</h1> <p>If your browser doesn't redirect you to the new location please <a href="http://example.com/newurl"><b>click here</b></a>, sorry for the hassles!</p> </body> </html> ```
273,374
<p>So, if i have:</p> <pre><code>public class Sedan : Car { /// ... } public class Car : Vehicle, ITurn { [MyCustomAttribute(1)] public int TurningRadius { get; set; } } public abstract class Vehicle : ITurn { [MyCustomAttribute(2)] public int TurningRadius { get; set; } } public interface ITurn { [MyCustomAttribute(3)] int TurningRadius { get; set; } } </code></pre> <p>What magic can I use to do something like:</p> <pre><code>[Test] public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry() { var property = typeof(Sedan).GetProperty("TurningRadius"); var attributes = SomeMagic(property); Assert.AreEqual(attributes.Count, 3); } </code></pre> <hr> <p>Both </p> <pre><code>property.GetCustomAttributes(true); </code></pre> <p>And</p> <pre><code>Attribute.GetCustomAttributes(property, true); </code></pre> <p>Only return 1 attribute. The instance is the one built with MyCustomAttribute(1). This doesn't seem to work as expected.</p>
[ { "answer_id": 273414, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 2, "selected": false, "text": "<pre><code>object[] SomeMagic (PropertyInfo property)\n{\n return property.GetCustomAttributes(true);\n}\n</code></pre>\n\n<p>UPDATE:</p>\n\n<p>Since my above answer doesn't work why not to try something like this:</p>\n\n<pre><code>public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()\n{\n\n Assert.AreEqual(checkAttributeCount (typeof (Sedan), \"TurningRadious\"), 3);\n}\n\n\nint checkAttributeCount (Type type, string propertyName)\n{\n var attributesCount = 0;\n\n attributesCount += countAttributes (type, propertyName);\n while (type.BaseType != null)\n {\n type = type.BaseType;\n attributesCount += countAttributes (type, propertyName);\n }\n\n foreach (var i in type.GetInterfaces ())\n attributesCount += countAttributes (type, propertyName);\n return attributesCount;\n}\n\nint countAttributes (Type t, string propertyName)\n{\n var property = t.GetProperty (propertyName);\n if (property == null)\n return 0;\n return (property.GetCustomAttributes (false).Length);\n}\n</code></pre>\n" }, { "answer_id": 581305, "author": "Damien McGivern", "author_id": 68637, "author_profile": "https://Stackoverflow.com/users/68637", "pm_score": 2, "selected": true, "text": "<p>this is a framework issue. Interface attributes are ignored by GetCustomAttributes. see the comment on this blog post <a href=\"http://hyperthink.net/blog/getcustomattributes-gotcha/#comment-65\" rel=\"nofollow noreferrer\">http://hyperthink.net/blog/getcustomattributes-gotcha/#comment-65</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
So, if i have: ``` public class Sedan : Car { /// ... } public class Car : Vehicle, ITurn { [MyCustomAttribute(1)] public int TurningRadius { get; set; } } public abstract class Vehicle : ITurn { [MyCustomAttribute(2)] public int TurningRadius { get; set; } } public interface ITurn { [MyCustomAttribute(3)] int TurningRadius { get; set; } } ``` What magic can I use to do something like: ``` [Test] public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry() { var property = typeof(Sedan).GetProperty("TurningRadius"); var attributes = SomeMagic(property); Assert.AreEqual(attributes.Count, 3); } ``` --- Both ``` property.GetCustomAttributes(true); ``` And ``` Attribute.GetCustomAttributes(property, true); ``` Only return 1 attribute. The instance is the one built with MyCustomAttribute(1). This doesn't seem to work as expected.
this is a framework issue. Interface attributes are ignored by GetCustomAttributes. see the comment on this blog post <http://hyperthink.net/blog/getcustomattributes-gotcha/#comment-65>
273,410
<p>How can I find out the number of dimensions in an array in Classic ASP ( VBScript ) .</p> <p>I am being passed an Array with multiple dimensions but I only want to look at the last. Seems easy in other languages.</p>
[ { "answer_id": 273454, "author": "Bullines", "author_id": 27870, "author_profile": "https://Stackoverflow.com/users/27870", "pm_score": 4, "selected": true, "text": "<pre><code>Ubound(MySingleDimensionalArray, 2) ' Number of Array Elements\n\nUbound(MyMultiDimensionalArray, 1) ' Number of Columns\nUbound(MyMultiDimensionalArray, 2) ' Number of Rows\n</code></pre>\n" }, { "answer_id": 273582, "author": "feihtthief", "author_id": 320070, "author_profile": "https://Stackoverflow.com/users/320070", "pm_score": 2, "selected": false, "text": "<pre><code>function ArrayDimensions( theArray )\n dim Result,test\n Result = 0\n if isarray(theArray) then\n on error resume next\n do\n test = -2\n test = ubound(theArray,result+1)\n if test &gt; -2 then result = result + 1\n loop until test=-2\n on error goto 0\n end if\n ArrayDimensions = Result\nend function\n</code></pre>\n" }, { "answer_id": 1342049, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 2, "selected": false, "text": "<p>Similar approach to feihtthief's answer here as I assume this is what you want rather than the size of a specified dimension.</p>\n\n<pre><code>Function NumDimensions(arr)\n Dim dimensions : dimensions = 0\n On Error Resume Next\n Do While Err.number = 0\n dimensions = dimensions + 1\n UBound arr, dimensions\n Loop\n On Error Goto 0\n NumDimensions = dimensions - 1\nEnd Function\n</code></pre>\n\n<p>Then calling it as so:</p>\n\n<pre><code>Dim test(9, 5, 4, 3, 9, 1, 3, 5)\nNumDimensions(test)\n</code></pre>\n\n<p>will give you the value 8</p>\n\n<p>It's a bit crappy but it'll do what you asked.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
How can I find out the number of dimensions in an array in Classic ASP ( VBScript ) . I am being passed an Array with multiple dimensions but I only want to look at the last. Seems easy in other languages.
``` Ubound(MySingleDimensionalArray, 2) ' Number of Array Elements Ubound(MyMultiDimensionalArray, 1) ' Number of Columns Ubound(MyMultiDimensionalArray, 2) ' Number of Rows ```
273,425
<p>I have code that lets me select a single item in arange:</p> <pre><code> COleVariant vItems = cstrAddr; hr = AutoWrap( DISPATCH_PROPERTYGET, &amp;vCell, irange, L"Item", 2, COleVariant((short)(1)), COleVariant((short)(1))); if (FAILED(hr)) return hr; // Use the dispatch interface to select the cell COleVariant result; hr = AutoWrap( DISPATCH_METHOD, &amp;result, vCell.pdispVal, L"Select", 0); if (FAILED(hr)) return hr; </code></pre> <p>This works fine. However, I need to select all the cells in the range, but I haven't been able to find a way to specify this in the "get" call for the Item property. Tried using -1,-1... tried passing in a pair of bstr in the 2 variants, specifying a colon separated range of columns and a range of rows; also tried passing in a single parameter of a string of range specification. None worked.</p> <p><strong>Update</strong>: I have also tried </p> <pre><code>hr = iRange-&gt;Select(vResult); </code></pre> <p>This does return S_OK, but it does not select the range. Normally, I can't directly call the functions in the iRange struct; the result is a gpf or access violation -- so I have to use the autowrap function (to drive an Invoke call). I'm not surprised this call doesn't work. Hope I can get this working.... it's the last piece of this project.</p>
[ { "answer_id": 273426, "author": "jons911", "author_id": 34375, "author_profile": "https://Stackoverflow.com/users/34375", "pm_score": 2, "selected": false, "text": "<p>If you can't install AJAX extensions, you will have to manage the AJAX calls yourself. It's absolutely possible, since AJAX Extensions just wrap the meat of AJAX. Read up on XMLHttpRequest and you'll find many examples.</p>\n\n<p>Here's a good site with examples.\n<a href=\"http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest/examples\" rel=\"nofollow noreferrer\">http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest/examples</a></p>\n" }, { "answer_id": 273431, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "<p>You don't need to install the AJAX extensions into the server's GAC.</p>\n\n<p>You can locally reference System.Web.Extensions.dll from your applications BIN folder....I've done it half a dozen times.</p>\n\n<p>Copy that DLL to your projects local bin. Reference it from your project. Remember to deploy the DLL when you deploy, and you are set.</p>\n" }, { "answer_id": 273466, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>Note that most of AJAX is done on the client side (in the browser) in Javascript. </p>\n\n<p>While there are some server-side libraries to make responding to a AJAX query easier, for the most part they are unnecessary. Any server technology that can server a web page to a browser can handle an AJAX request just as well.</p>\n" }, { "answer_id": 273490, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>Theres always prototype and jQuery for AJAX calls. </p>\n\n<p>Both of which are perfectly valid for making Ajax calls to the server, despite Jonathan Hollands persistence (and his down-voting of everyone else's response) to the contrary. </p>\n\n<p><a href=\"http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx\" rel=\"nofollow noreferrer\">MS now packages jQuery with Visual Studio</a>, so there is no interoperability problem.</p>\n\n<p>Please remember that the server has no knowledge of controls created on the client side, and you will have to take the extra steps to persist any data (via ajax calls) to the server.</p>\n" }, { "answer_id": 273491, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 1, "selected": false, "text": "<p>Microsoft ASP.NET AJAX is not the only way to implement AJAX Functionality. <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> and <a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">Prototype</a> are two popular javascript libraries for working with AJAX, regardless of server platform.</p>\n\n<p>If you're tied 100% to Microsoft ASP.NET AJAX, then you may need to <a href=\"http://www.asp.net/ajax/\" rel=\"nofollow noreferrer\">download</a> it and install the DLL manually to your local project.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965047/" ]
I have code that lets me select a single item in arange: ``` COleVariant vItems = cstrAddr; hr = AutoWrap( DISPATCH_PROPERTYGET, &vCell, irange, L"Item", 2, COleVariant((short)(1)), COleVariant((short)(1))); if (FAILED(hr)) return hr; // Use the dispatch interface to select the cell COleVariant result; hr = AutoWrap( DISPATCH_METHOD, &result, vCell.pdispVal, L"Select", 0); if (FAILED(hr)) return hr; ``` This works fine. However, I need to select all the cells in the range, but I haven't been able to find a way to specify this in the "get" call for the Item property. Tried using -1,-1... tried passing in a pair of bstr in the 2 variants, specifying a colon separated range of columns and a range of rows; also tried passing in a single parameter of a string of range specification. None worked. **Update**: I have also tried ``` hr = iRange->Select(vResult); ``` This does return S\_OK, but it does not select the range. Normally, I can't directly call the functions in the iRange struct; the result is a gpf or access violation -- so I have to use the autowrap function (to drive an Invoke call). I'm not surprised this call doesn't work. Hope I can get this working.... it's the last piece of this project.
You don't need to install the AJAX extensions into the server's GAC. You can locally reference System.Web.Extensions.dll from your applications BIN folder....I've done it half a dozen times. Copy that DLL to your projects local bin. Reference it from your project. Remember to deploy the DLL when you deploy, and you are set.
273,433
<p>I've been Googling around for .htaccess redirection information, but nothing I find is quite what I'm looking for.</p> <p>Basically, I want a solution that will take a site example.com and allow you to enter URL's like:</p> <pre><code> 123.example.com ksdfkjds.example.com dsf38jif348.example.com </code></pre> <p>and this would redirect them to:</p> <pre><code> example.com/123 example.com/ksdfkjds example.com/dsf38jif348 </code></pre> <p>So basically accept any subdomain and automatically redirect to a folder on the root of the domain with the name of that subdomain.</p>
[ { "answer_id": 273456, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>Try something like this:</p>\n\n<pre><code># If we're not on http://example.com\nRewriteCond %{HTTP_HOST} .+\\.example.com\n\n# Add the host to the front of the URL and chain with the next rule\nRewriteRule ^(.*)$ ${HOST}$1 [C,QSA]\n\n# Make the host a directory\nRewriteRule ^(.*)\\.example\\.com(.*)$ http://example.com/$1$2 [QSA]\n</code></pre>\n\n<p>You don't say what should happen to <a href=\"http://foo.example.com/bar?moo\" rel=\"nofollow noreferrer\">http://foo.example.com/bar?moo</a> - I've made it go to <a href=\"http://example.com/foo/bar?moo\" rel=\"nofollow noreferrer\">http://example.com/foo/bar?moo</a>\nChange the last line if that's not what you want.</p>\n" }, { "answer_id": 487368, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 0, "selected": false, "text": "<p>If you just want them to be the entrance:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^([^.]+)\\.example\\.com$\nRewriteRule ^ http://example.com/%1 [L,R]\n</code></pre>\n\n<p>Otherwise:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^([^.]+)\\.example\\.com$\nRewriteRule ^ /%1%{REQUEST_URI} [L]\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've been Googling around for .htaccess redirection information, but nothing I find is quite what I'm looking for. Basically, I want a solution that will take a site example.com and allow you to enter URL's like: ``` 123.example.com ksdfkjds.example.com dsf38jif348.example.com ``` and this would redirect them to: ``` example.com/123 example.com/ksdfkjds example.com/dsf38jif348 ``` So basically accept any subdomain and automatically redirect to a folder on the root of the domain with the name of that subdomain.
Try something like this: ``` # If we're not on http://example.com RewriteCond %{HTTP_HOST} .+\.example.com # Add the host to the front of the URL and chain with the next rule RewriteRule ^(.*)$ ${HOST}$1 [C,QSA] # Make the host a directory RewriteRule ^(.*)\.example\.com(.*)$ http://example.com/$1$2 [QSA] ``` You don't say what should happen to <http://foo.example.com/bar?moo> - I've made it go to <http://example.com/foo/bar?moo> Change the last line if that's not what you want.
273,447
<p>I am using the .NET 3.5 SP1 framework and I've implemented URL routing in my application. I was getting javascript errors: </p> <p><code> Error: ASP.NET Ajax client-side framework failed to load.<br> Resource interpreted as script but transferred with MIME type text/html.<br> ReferenceError: Can't find variable: Sys </code></p> <p>Which I believe is because my routing is picking up the microsoft axd files and not properly sending down the javascript. I did some research and found that I could use <code>Routes.IgnoreRoute</code>, which should allow me to ignore the axd like below:</p> <pre><code>Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); </code></pre> <p>But, when I add that line to my Global.asax I get this error:</p> <p><code> CS1061: 'System.Web.Routing.RouteCollection' does not contain a definition for 'IgnoreRoute' and no extension method 'IgnoreRoute' accepting a first argument of type 'System.Web.Routing.RouteCollection' could be found (are you missing a using directive or an assembly reference?) </code></p> <p>I've got the <code>System.Web.Routing</code> namespace imported, any ideas?</p>
[ { "answer_id": 273470, "author": "Dan Esparza", "author_id": 19020, "author_profile": "https://Stackoverflow.com/users/19020", "pm_score": 1, "selected": false, "text": "<p>MapRoute and IgnoreRoute are extension methods in System.Web.Mvc --- do you have that assembly referenced properly?</p>\n" }, { "answer_id": 276036, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 6, "selected": true, "text": "<p>You don't need to reference ASP.NET MVC. You can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.routing.stoproutinghandler.aspx\" rel=\"noreferrer\">StopRoutingHandler</a> which implements IRouteHandler like so:</p>\n\n<pre><code>routes.Add(new Route(\"{resource}.axd/{*pathInfo}\", new StopRoutingHandler()));\n</code></pre>\n\n<p>This is part of .NET 3.5 SP1 and doesn't require MVC. The IgnoreRoutes method is a convenience extension method which is part of ASP.NET MVC.</p>\n" }, { "answer_id": 719842, "author": "Omenof", "author_id": 87410, "author_profile": "https://Stackoverflow.com/users/87410", "pm_score": 2, "selected": false, "text": "<p>I would just like to add that you also need to make sure the order of your IgnoreRoutes rule is in the the correct order otherwise your first route will be applied first and your IgnoreRoute will... well be ignored.</p>\n" }, { "answer_id": 7889659, "author": "Ed Graham", "author_id": 128193, "author_profile": "https://Stackoverflow.com/users/128193", "pm_score": 3, "selected": false, "text": "<p>An old question but in case it still helps anyone, this worked for me:</p>\n\n<pre><code>routes.Ignore(\"{resource}.axd/{*pathInfo}\");\n</code></pre>\n\n<p>The \"Ignore\" method exists, whereas in standard ASP.NET the \"IgnoreRoute\" method appears not to (i.e., not using MVC). This will achieve the same result as Haacked's code, but is slightly cleaner ...</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32854/" ]
I am using the .NET 3.5 SP1 framework and I've implemented URL routing in my application. I was getting javascript errors: `Error: ASP.NET Ajax client-side framework failed to load. Resource interpreted as script but transferred with MIME type text/html. ReferenceError: Can't find variable: Sys` Which I believe is because my routing is picking up the microsoft axd files and not properly sending down the javascript. I did some research and found that I could use `Routes.IgnoreRoute`, which should allow me to ignore the axd like below: ``` Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); ``` But, when I add that line to my Global.asax I get this error: `CS1061: 'System.Web.Routing.RouteCollection' does not contain a definition for 'IgnoreRoute' and no extension method 'IgnoreRoute' accepting a first argument of type 'System.Web.Routing.RouteCollection' could be found (are you missing a using directive or an assembly reference?)` I've got the `System.Web.Routing` namespace imported, any ideas?
You don't need to reference ASP.NET MVC. You can use the [StopRoutingHandler](http://msdn.microsoft.com/en-us/library/system.web.routing.stoproutinghandler.aspx) which implements IRouteHandler like so: ``` routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler())); ``` This is part of .NET 3.5 SP1 and doesn't require MVC. The IgnoreRoutes method is a convenience extension method which is part of ASP.NET MVC.
273,450
<p>Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I'm trying to figure out the best way to do that.</p> <p>There's this somewhat-related method in UIApplication:</p> <pre><code>[UIApplication sharedApplication].idleTimerDisabled; </code></pre> <p>It'd be nice if you instead had something like this:</p> <pre><code>NSTimeInterval timeElapsed = [UIApplication sharedApplication].idleTimeElapsed; </code></pre> <p>Then I could set up a timer and periodically check this value, and take some action when it exceeds a threshold.</p> <p>Hopefully that explains what I'm looking for. Has anyone tackled this issue already, or have any thoughts on how you would do it? Thanks.</p>
[ { "answer_id": 273656, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 2, "selected": false, "text": "<p>Ultimately you need to define what you consider to be idle - is idle the result of the user not touching the screen or is it the state of the system if no computing resources are being used? It is possible, in many applications, for the user to be doing something even if not actively interacting with the device through the touch screen. While the user is probably familiar with the concept of the device going to sleep and the notice that it will happen via screen dimming, it is not necessarily the case that they'll expect something to happen if they are idle - you need to be careful about what you would do. But going back to the original statement - if you consider the 1st case to be your definition, there is no really easy way to do this. You'd need to receive each touch event, passing it along on the responder chain as needed while noting the time it was received. That will give you some basis for making the idle calculation. If you consider the second case to be your definition, you can play with an NSPostWhenIdle notification to try and perform your logic at that time.</p>\n" }, { "answer_id": 309535, "author": "Mike McMaster", "author_id": 544, "author_profile": "https://Stackoverflow.com/users/544", "pm_score": 8, "selected": true, "text": "<p>Here's the answer I had been looking for:</p>\n\n<p>Have your application delegate subclass UIApplication. In the implementation file, override the sendEvent: method like so:</p>\n\n<pre><code>- (void)sendEvent:(UIEvent *)event {\n [super sendEvent:event];\n\n // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.\n NSSet *allTouches = [event allTouches];\n if ([allTouches count] &gt; 0) {\n // allTouches count only ever seems to be 1, so anyObject works here.\n UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;\n if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)\n [self resetIdleTimer];\n }\n}\n\n- (void)resetIdleTimer {\n if (idleTimer) {\n [idleTimer invalidate];\n [idleTimer release];\n }\n\n idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];\n}\n\n- (void)idleTimerExceeded {\n NSLog(@\"idle time exceeded\");\n}\n</code></pre>\n\n<p>where maxIdleTime and idleTimer are instance variables.</p>\n\n<p>In order for this to work, you also need to modify your main.m to tell UIApplicationMain to use your delegate class (in this example, AppDelegate) as the principal class:</p>\n\n<pre><code>int retVal = UIApplicationMain(argc, argv, @\"AppDelegate\", @\"AppDelegate\");\n</code></pre>\n" }, { "answer_id": 2639067, "author": "Brian King", "author_id": 98207, "author_profile": "https://Stackoverflow.com/users/98207", "pm_score": 4, "selected": false, "text": "<p>This thread was a great help, and I wrapped it up into a UIWindow subclass that sends out notifications. I chose notifications to make it a real loose coupling, but you can add a delegate easily enough.</p>\n\n<p>Here's the gist:</p>\n\n<p><a href=\"http://gist.github.com/365998\" rel=\"noreferrer\">http://gist.github.com/365998</a></p>\n\n<p>Also, the reason for the UIApplication subclass issue is that the NIB is setup to then create 2 UIApplication objects since it contains the application and the delegate. UIWindow subclass works great though.</p>\n" }, { "answer_id": 3580685, "author": "Roby", "author_id": 432468, "author_profile": "https://Stackoverflow.com/users/432468", "pm_score": 3, "selected": false, "text": "<p>Actually the subclassing idea works great. Just don't make your delegate the <code>UIApplication</code> subclass. Create another file that inherits from <code>UIApplication</code> (e.g. myApp). In IB set the class of the <code>fileOwner</code> object to <code>myApp</code> and in myApp.m implement the <code>sendEvent</code> method as above. In main.m do:</p>\n\n<pre><code>int retVal = UIApplicationMain(argc,argv,@\"myApp.m\",@\"myApp.m\")\n</code></pre>\n\n<p>et voilà!</p>\n" }, { "answer_id": 5269900, "author": "Chris Miles", "author_id": 78474, "author_profile": "https://Stackoverflow.com/users/78474", "pm_score": 7, "selected": false, "text": "<p>I have a variation of the idle timer solution which doesn't require subclassing UIApplication. It works on a specific UIViewController subclass, so is useful if you only have one view controller (like an interactive app or game may have) or only want to handle idle timeout in a specific view controller.</p>\n\n<p>It also does not re-create the NSTimer object every time the idle timer is reset. It only creates a new one if the timer fires.</p>\n\n<p>Your code can call <code>resetIdleTimer</code> for any other events that may need to invalidate the idle timer (such as significant accelerometer input).</p>\n\n<pre><code>@interface MainViewController : UIViewController\n{\n NSTimer *idleTimer;\n}\n@end\n\n#define kMaxIdleTimeSeconds 60.0\n\n@implementation MainViewController\n\n#pragma mark -\n#pragma mark Handling idle timeout\n\n- (void)resetIdleTimer {\n if (!idleTimer) {\n idleTimer = [[NSTimer scheduledTimerWithTimeInterval:kMaxIdleTimeSeconds\n target:self\n selector:@selector(idleTimerExceeded)\n userInfo:nil\n repeats:NO] retain];\n }\n else {\n if (fabs([idleTimer.fireDate timeIntervalSinceNow]) &lt; kMaxIdleTimeSeconds-1.0) {\n [idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kMaxIdleTimeSeconds]];\n }\n }\n}\n\n- (void)idleTimerExceeded {\n [idleTimer release]; idleTimer = nil;\n [self startScreenSaverOrSomethingInteresting];\n [self resetIdleTimer];\n}\n\n- (UIResponder *)nextResponder {\n [self resetIdleTimer];\n return [super nextResponder];\n}\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n [self resetIdleTimer];\n}\n\n@end\n</code></pre>\n\n<p>(memory cleanup code excluded for brevity.)</p>\n" }, { "answer_id": 14725059, "author": "Kay", "author_id": 437283, "author_profile": "https://Stackoverflow.com/users/437283", "pm_score": 2, "selected": false, "text": "<p>I just ran into this problem with a game that is controlled by motions i.e. has screen lock disabled but should enable it again when in menu mode. Instead of a timer I encapsulated all calls to <code>setIdleTimerDisabled</code> within a small class providing the following methods:</p>\n\n<pre><code>- (void) enableIdleTimerDelayed {\n [self performSelector:@selector (enableIdleTimer) withObject:nil afterDelay:60];\n}\n\n- (void) enableIdleTimer {\n [NSObject cancelPreviousPerformRequestsWithTarget:self];\n [[UIApplication sharedApplication] setIdleTimerDisabled:NO];\n}\n\n- (void) disableIdleTimer {\n [NSObject cancelPreviousPerformRequestsWithTarget:self];\n [[UIApplication sharedApplication] setIdleTimerDisabled:YES];\n}\n</code></pre>\n\n<p><code>disableIdleTimer</code> deactivates idle timer, <code>enableIdleTimerDelayed</code> when entering the menu or whatever should run with idle timer active and <code>enableIdleTimer</code> is called from your AppDelegate's <code>applicationWillResignActive</code> method to ensure all your changes are reset properly to the system default behaviour.<br>\nI wrote an article and provided the code for the singleton class IdleTimerManager <a href=\"http://www.scio.de/en/blog-a-news/scio-development-blog-en/entry/idle-timer-handling-in-iphone-games\" rel=\"nofollow\">Idle Timer Handling in iPhone Games</a></p>\n" }, { "answer_id": 25293578, "author": "Mihai Timar", "author_id": 757408, "author_profile": "https://Stackoverflow.com/users/757408", "pm_score": 2, "selected": false, "text": "<p>Here is another way to detect activity:</p>\n\n<p>The timer is added in <code>UITrackingRunLoopMode</code>, so it can only fire if there is <code>UITracking</code> activity. It also has the nice advantage of not spamming you for all touch events, thus informing if there was activity in the last <code>ACTIVITY_DETECT_TIMER_RESOLUTION</code> seconds. I named the selector <code>keepAlive</code> as it seems an appropriate use case for this. You can of course do whatever you desire with the information that there was activity recently.</p>\n\n<pre><code>_touchesTimer = [NSTimer timerWithTimeInterval:ACTIVITY_DETECT_TIMER_RESOLUTION\n target:self\n selector:@selector(keepAlive)\n userInfo:nil\n repeats:YES];\n[[NSRunLoop mainRunLoop] addTimer:_touchesTimer forMode:UITrackingRunLoopMode];\n</code></pre>\n" }, { "answer_id": 43940042, "author": "Sergey Stadnik", "author_id": 4745768, "author_profile": "https://Stackoverflow.com/users/4745768", "pm_score": 5, "selected": false, "text": "<p>For swift v 3.1</p>\n\n<p>dont't forget comment this line in AppDelegate <strong>//@UIApplicationMain</strong></p>\n\n<pre><code>extension NSNotification.Name {\n public static let TimeOutUserInteraction: NSNotification.Name = NSNotification.Name(rawValue: \"TimeOutUserInteraction\")\n}\n\n\nclass InterractionUIApplication: UIApplication {\n\nstatic let ApplicationDidTimoutNotification = \"AppTimout\"\n\n// The timeout in seconds for when to fire the idle timer.\nlet timeoutInSeconds: TimeInterval = 15 * 60\n\nvar idleTimer: Timer?\n\n// Listen for any touch. If the screen receives a touch, the timer is reset.\noverride func sendEvent(_ event: UIEvent) {\n super.sendEvent(event)\n\n if idleTimer != nil {\n self.resetIdleTimer()\n }\n\n if let touches = event.allTouches {\n for touch in touches {\n if touch.phase == UITouchPhase.began {\n self.resetIdleTimer()\n }\n }\n }\n}\n\n// Resent the timer because there was user interaction.\nfunc resetIdleTimer() {\n if let idleTimer = idleTimer {\n idleTimer.invalidate()\n }\n\n idleTimer = Timer.scheduledTimer(timeInterval: timeoutInSeconds, target: self, selector: #selector(self.idleTimerExceeded), userInfo: nil, repeats: false)\n}\n\n// If the timer reaches the limit as defined in timeoutInSeconds, post this notification.\nfunc idleTimerExceeded() {\n NotificationCenter.default.post(name:Notification.Name.TimeOutUserInteraction, object: nil)\n }\n} \n</code></pre>\n\n<blockquote>\n <p>create main.swif file and add this (name is important)</p>\n</blockquote>\n\n<pre><code>CommandLine.unsafeArgv.withMemoryRebound(to: UnsafeMutablePointer&lt;Int8&gt;.self, capacity: Int(CommandLine.argc)) {argv in\n_ = UIApplicationMain(CommandLine.argc, argv, NSStringFromClass(InterractionUIApplication.self), NSStringFromClass(AppDelegate.self))\n}\n</code></pre>\n\n<p>Observing notification in an any other class</p>\n\n<pre><code>NotificationCenter.default.addObserver(self, selector: #selector(someFuncitonName), name: Notification.Name.TimeOutUserInteraction, object: nil)\n</code></pre>\n" }, { "answer_id": 45496010, "author": "Jlam", "author_id": 199966, "author_profile": "https://Stackoverflow.com/users/199966", "pm_score": 3, "selected": false, "text": "<p>There's a way to do this app wide without individual controllers having to do anything. Just add a gesture recognizer that doesn't cancel touches. This way, all touches will be tracked for the timer, and other touches and gestures aren't affected at all so no one else has to know about it.</p>\n\n<pre><code>fileprivate var timer ... //timer logic here\n\n@objc public class CatchAllGesture : UIGestureRecognizer {\n override public func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent) {\n super.touchesBegan(touches, with: event)\n }\n override public func touchesEnded(_ touches: Set&lt;UITouch&gt;, with event: UIEvent) {\n //reset your timer here\n state = .failed\n super.touchesEnded(touches, with: event)\n }\n override public func touchesMoved(_ touches: Set&lt;UITouch&gt;, with event: UIEvent) {\n super.touchesMoved(touches, with: event)\n }\n}\n\n@objc extension YOURAPPAppDelegate {\n\n func addGesture () {\n let aGesture = CatchAllGesture(target: nil, action: nil)\n aGesture.cancelsTouchesInView = false\n self.window.addGestureRecognizer(aGesture)\n }\n}\n</code></pre>\n\n<p>In your app delegate's did finish launch method, just call addGesture and you're all set. All touches will go through the CatchAllGesture's methods without it preventing the functionality of others.</p>\n" }, { "answer_id": 65919565, "author": "Dmitriy Miyai", "author_id": 4730040, "author_profile": "https://Stackoverflow.com/users/4730040", "pm_score": 1, "selected": false, "text": "<p>Outside is 2021 and I would like share my approach to handle this without extending the UIApplication. I will not describe how to create a timer and reset it. But rather how to catch all events. So your AppDelegate starts with this:</p>\n<pre><code>@UIApplicationMain\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n var window: UIWindow?\n</code></pre>\n<p>So all you need to do is to subclass UIWindow and override <code>sendEvent</code>, like below</p>\n<pre><code>import UIKit\n\nclass MyWindow: UIWindow {\n\n override func sendEvent(_ event: UIEvent){\n super.sendEvent(event)\n NSLog(&quot;Application received an event. Do whatever you want&quot;)\n }\n}\n</code></pre>\n<p>And later create window with our class:</p>\n<pre><code>self.window = MyWindow(frame: UIScreen.main.bounds)\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544/" ]
Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I'm trying to figure out the best way to do that. There's this somewhat-related method in UIApplication: ``` [UIApplication sharedApplication].idleTimerDisabled; ``` It'd be nice if you instead had something like this: ``` NSTimeInterval timeElapsed = [UIApplication sharedApplication].idleTimeElapsed; ``` Then I could set up a timer and periodically check this value, and take some action when it exceeds a threshold. Hopefully that explains what I'm looking for. Has anyone tackled this issue already, or have any thoughts on how you would do it? Thanks.
Here's the answer I had been looking for: Have your application delegate subclass UIApplication. In the implementation file, override the sendEvent: method like so: ``` - (void)sendEvent:(UIEvent *)event { [super sendEvent:event]; // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets. NSSet *allTouches = [event allTouches]; if ([allTouches count] > 0) { // allTouches count only ever seems to be 1, so anyObject works here. UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase; if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) [self resetIdleTimer]; } } - (void)resetIdleTimer { if (idleTimer) { [idleTimer invalidate]; [idleTimer release]; } idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain]; } - (void)idleTimerExceeded { NSLog(@"idle time exceeded"); } ``` where maxIdleTime and idleTimer are instance variables. In order for this to work, you also need to modify your main.m to tell UIApplicationMain to use your delegate class (in this example, AppDelegate) as the principal class: ``` int retVal = UIApplicationMain(argc, argv, @"AppDelegate", @"AppDelegate"); ```
273,452
<p>I can't seem to find a nice clean example of using AES 128 bit encryption.</p> <p>Does anyone have some sample code?</p>
[ { "answer_id": 273499, "author": "Dan Esparza", "author_id": 19020, "author_profile": "https://Stackoverflow.com/users/19020", "pm_score": 7, "selected": false, "text": "<p>If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):</p>\n\n<blockquote>\n <p><a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx</a></p>\n</blockquote>\n\n<p>And just in case you need the sample in a hurry, here it is in all its plagiarized glory:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace RijndaelManaged_Example\n{\n class RijndaelExample\n {\n public static void Main()\n {\n try\n {\n\n string original = \"Here is some data to encrypt!\";\n\n // Create a new instance of the RijndaelManaged \n // class. This generates a new key and initialization \n // vector (IV). \n using (RijndaelManaged myRijndael = new RijndaelManaged())\n {\n\n myRijndael.GenerateKey();\n myRijndael.GenerateIV();\n // Encrypt the string to an array of bytes. \n byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);\n\n // Decrypt the bytes to a string. \n string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);\n\n //Display the original data and the decrypted data.\n Console.WriteLine(\"Original: {0}\", original);\n Console.WriteLine(\"Round Trip: {0}\", roundtrip);\n }\n\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Error: {0}\", e.Message);\n }\n }\n static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)\n {\n // Check arguments. \n if (plainText == null || plainText.Length &lt;= 0)\n throw new ArgumentNullException(\"plainText\");\n if (Key == null || Key.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length &lt;= 0)\n throw new ArgumentNullException(\"IV\");\n byte[] encrypted;\n // Create an RijndaelManaged object \n // with the specified key and IV. \n using (RijndaelManaged rijAlg = new RijndaelManaged())\n {\n rijAlg.Key = Key;\n rijAlg.IV = IV;\n\n // Create a decryptor to perform the stream transform.\n ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);\n\n // Create the streams used for encryption. \n using (MemoryStream msEncrypt = new MemoryStream())\n {\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n encrypted = msEncrypt.ToArray();\n }\n }\n }\n\n\n // Return the encrypted bytes from the memory stream. \n return encrypted;\n\n }\n\n static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)\n {\n // Check arguments. \n if (cipherText == null || cipherText.Length &lt;= 0)\n throw new ArgumentNullException(\"cipherText\");\n if (Key == null || Key.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length &lt;= 0)\n throw new ArgumentNullException(\"IV\");\n\n // Declare the string used to hold \n // the decrypted text. \n string plaintext = null;\n\n // Create an RijndaelManaged object \n // with the specified key and IV. \n using (RijndaelManaged rijAlg = new RijndaelManaged())\n {\n rijAlg.Key = Key;\n rijAlg.IV = IV;\n\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);\n\n // Create the streams used for decryption. \n using (MemoryStream msDecrypt = new MemoryStream(cipherText))\n {\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n {\n\n // Read the decrypted bytes from the decrypting stream \n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n\n }\n\n return plaintext;\n\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 273501, "author": "DCNYAM", "author_id": 30419, "author_profile": "https://Stackoverflow.com/users/30419", "pm_score": 3, "selected": false, "text": "<p>Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.</p>\n" }, { "answer_id": 1360208, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 3, "selected": false, "text": "<p>For a more complete example that performs key derivation in addition to the AES encryption, see the answer and links posted in <a href=\"https://stackoverflow.com/questions/1149611/getting-slowaes-and-rijndaelmanaged-class-in-net-to-play-together\">Getting AES encryption to work across Javascript and C#</a>. </p>\n\n<p><strong>EDIT</strong><br>\na side note: <a href=\"http://www.matasano.com/articles/javascript-cryptography/\" rel=\"nofollow noreferrer\">Javascript Cryptography considered harmful.</a> Worth the read.</p>\n" }, { "answer_id": 8779595, "author": "Javanese Girl", "author_id": 1136197, "author_profile": "https://Stackoverflow.com/users/1136197", "pm_score": 4, "selected": false, "text": "<p>Look at sample in here..</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=VS.100).aspx#Y2262\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=VS.100).aspx#Y2262</a></p>\n\n<p>The example on MSDN does not run normally (an error occurs) because there is <strong>no initial value</strong> of <strong>Initial Vector(iv)</strong> and <strong>Key</strong>. I add 2 line code and now work normally.</p>\n\n<p>More details see below:</p>\n\n<pre><code>using System.Windows.Forms;\nusing System;\nusing System.Text;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace AES_TESTER\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n try\n {\n\n string original = \"Here is some data to encrypt!\";\n MessageBox.Show(\"Original: \" + original);\n\n // Create a new instance of the RijndaelManaged\n // class. This generates a new key and initialization \n // vector (IV).\n using (RijndaelManaged myRijndael = new RijndaelManaged())\n {\n myRijndael.GenerateKey();\n myRijndael.GenerateIV();\n\n // Encrypt the string to an array of bytes.\n byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);\n\n StringBuilder s = new StringBuilder();\n foreach (byte item in encrypted)\n {\n s.Append(item.ToString(\"X2\") + \" \");\n }\n MessageBox.Show(\"Encrypted: \" + s);\n\n // Decrypt the bytes to a string.\n string decrypted = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);\n\n //Display the original data and the decrypted data.\n MessageBox.Show(\"Decrypted: \" + decrypted);\n }\n\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Error: {0}\", ex.Message);\n }\n }\n\n static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)\n {\n // Check arguments.\n if (plainText == null || plainText.Length &lt;= 0)\n throw new ArgumentNullException(\"plainText\");\n if (Key == null || Key.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n byte[] encrypted;\n // Create an RijndaelManaged object\n // with the specified key and IV.\n using (RijndaelManaged rijAlg = new RijndaelManaged())\n {\n rijAlg.Key = Key;\n rijAlg.IV = IV;\n rijAlg.Mode = CipherMode.CBC;\n rijAlg.Padding = PaddingMode.Zeros;\n\n // Create a decrytor to perform the stream transform.\n ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);\n\n // Create the streams used for encryption.\n using (MemoryStream msEncrypt = new MemoryStream())\n {\n using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))\n {\n using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))\n {\n\n //Write all data to the stream.\n swEncrypt.Write(plainText);\n }\n encrypted = msEncrypt.ToArray();\n }\n }\n }\n\n\n // Return the encrypted bytes from the memory stream.\n return encrypted;\n\n }\n\n static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)\n {\n // Check arguments.\n if (cipherText == null || cipherText.Length &lt;= 0)\n throw new ArgumentNullException(\"cipherText\");\n if (Key == null || Key.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n if (IV == null || IV.Length &lt;= 0)\n throw new ArgumentNullException(\"Key\");\n\n // Declare the string used to hold\n // the decrypted text.\n string plaintext = null;\n\n // Create an RijndaelManaged object\n // with the specified key and IV.\n using (RijndaelManaged rijAlg = new RijndaelManaged())\n {\n rijAlg.Key = Key;\n rijAlg.IV = IV;\n rijAlg.Mode = CipherMode.CBC;\n rijAlg.Padding = PaddingMode.Zeros;\n\n // Create a decrytor to perform the stream transform.\n ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);\n\n // Create the streams used for decryption.\n using (MemoryStream msDecrypt = new MemoryStream(cipherText))\n {\n using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))\n {\n using (StreamReader srDecrypt = new StreamReader(csDecrypt))\n {\n\n // Read the decrypted bytes from the decrypting stream\n // and place them in a string.\n plaintext = srDecrypt.ReadToEnd();\n }\n }\n }\n\n }\n\n return plaintext;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 13369641, "author": "YD4", "author_id": 1815264, "author_profile": "https://Stackoverflow.com/users/1815264", "pm_score": 2, "selected": false, "text": "<p>Try this code, maybe useful.<br>\n1.Create New C# Project and add follows code to Form1:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\nusing System.Security.Cryptography;\n\nnamespace ExampleCrypto\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n string strOriginalData = string.Empty;\n string strEncryptedData = string.Empty;\n string strDecryptedData = string.Empty;\n\n strOriginalData = \"this is original data 1234567890\"; // your original data in here\n MessageBox.Show(\"ORIGINAL DATA:\\r\\n\" + strOriginalData);\n\n clsCrypto aes = new clsCrypto();\n aes.IV = \"this is your IV\"; // your IV\n aes.KEY = \"this is your KEY\"; // your KEY \n strEncryptedData = aes.Encrypt(strOriginalData, CipherMode.CBC); // your cipher mode\n MessageBox.Show(\"ENCRYPTED DATA:\\r\\n\" + strEncryptedData);\n\n strDecryptedData = aes.Decrypt(strEncryptedData, CipherMode.CBC);\n MessageBox.Show(\"DECRYPTED DATA:\\r\\n\" + strDecryptedData);\n }\n\n }\n}\n</code></pre>\n\n<p>2.Create clsCrypto.cs and copy paste follows code in your class and run your code. I used MD5 to generated Initial Vector(IV) and KEY of AES.</p>\n\n<pre><code>using System;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.IO;\nusing System.Runtime.Remoting.Metadata.W3cXsd2001;\n\nnamespace ExampleCrypto\n{\n public class clsCrypto\n {\n private string _KEY = string.Empty;\n protected internal string KEY\n {\n get\n {\n return _KEY;\n }\n set\n {\n if (!string.IsNullOrEmpty(value))\n {\n _KEY = value;\n }\n }\n }\n\n private string _IV = string.Empty;\n protected internal string IV\n {\n get\n {\n return _IV;\n }\n set\n {\n if (!string.IsNullOrEmpty(value))\n {\n _IV = value;\n }\n }\n }\n\n private string CalcMD5(string strInput)\n {\n string strOutput = string.Empty;\n if (!string.IsNullOrEmpty(strInput))\n {\n try\n {\n StringBuilder strHex = new StringBuilder();\n using (MD5 md5 = MD5.Create())\n {\n byte[] bytArText = Encoding.Default.GetBytes(strInput);\n byte[] bytArHash = md5.ComputeHash(bytArText);\n for (int i = 0; i &lt; bytArHash.Length; i++)\n {\n strHex.Append(bytArHash[i].ToString(\"X2\"));\n }\n strOutput = strHex.ToString();\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n }\n return strOutput;\n }\n\n private byte[] GetBytesFromHexString(string strInput)\n {\n byte[] bytArOutput = new byte[] { };\n if ((!string.IsNullOrEmpty(strInput)) &amp;&amp; strInput.Length % 2 == 0)\n {\n SoapHexBinary hexBinary = null;\n try\n {\n hexBinary = SoapHexBinary.Parse(strInput);\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n bytArOutput = hexBinary.Value;\n }\n return bytArOutput;\n }\n\n private byte[] GenerateIV()\n {\n byte[] bytArOutput = new byte[] { };\n try\n {\n string strIV = CalcMD5(IV);\n bytArOutput = GetBytesFromHexString(strIV);\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n return bytArOutput;\n }\n\n private byte[] GenerateKey()\n {\n byte[] bytArOutput = new byte[] { };\n try\n {\n string strKey = CalcMD5(KEY);\n bytArOutput = GetBytesFromHexString(strKey);\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n return bytArOutput;\n }\n\n protected internal string Encrypt(string strInput, CipherMode cipherMode)\n {\n string strOutput = string.Empty;\n if (!string.IsNullOrEmpty(strInput))\n {\n try\n {\n byte[] bytePlainText = Encoding.Default.GetBytes(strInput);\n using (RijndaelManaged rijManaged = new RijndaelManaged())\n {\n rijManaged.Mode = cipherMode;\n rijManaged.BlockSize = 128;\n rijManaged.KeySize = 128;\n rijManaged.IV = GenerateIV();\n rijManaged.Key = GenerateKey();\n rijManaged.Padding = PaddingMode.Zeros;\n ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);\n using (MemoryStream memStream = new MemoryStream())\n {\n using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))\n {\n cpoStream.Write(bytePlainText, 0, bytePlainText.Length);\n cpoStream.FlushFinalBlock();\n }\n strOutput = Encoding.Default.GetString(memStream.ToArray());\n }\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n }\n return strOutput;\n }\n\n protected internal string Decrypt(string strInput, CipherMode cipherMode)\n {\n string strOutput = string.Empty;\n if (!string.IsNullOrEmpty(strInput))\n {\n try\n {\n byte[] byteCipherText = Encoding.Default.GetBytes(strInput);\n byte[] byteBuffer = new byte[strInput.Length];\n using (RijndaelManaged rijManaged = new RijndaelManaged())\n {\n rijManaged.Mode = cipherMode;\n rijManaged.BlockSize = 128;\n rijManaged.KeySize = 128;\n rijManaged.IV = GenerateIV();\n rijManaged.Key = GenerateKey();\n rijManaged.Padding = PaddingMode.Zeros;\n ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);\n using (MemoryStream memStream = new MemoryStream(byteCipherText))\n {\n using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))\n {\n cpoStream.Read(byteBuffer, 0, byteBuffer.Length);\n }\n strOutput = Encoding.Default.GetString(byteBuffer);\n }\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n }\n return strOutput;\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 14286740, "author": "Troy Alford", "author_id": 1454806, "author_profile": "https://Stackoverflow.com/users/1454806", "pm_score": 6, "selected": false, "text": "<p>I've recently had to bump up against this again in my own project - and wanted to share the somewhat simpler code that I've been using, as this question and series of answers kept coming up in my searches.</p>\n\n<p>I'm not going to get into the security concerns around how often to update things like your <em>Salt</em> and <em>Initialization Vector</em> - that's a topic for a security forum, and there are some great resources out there to look at. This is simply a block of code to implement <code>AesManaged</code> in C#.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace Your.Namespace.Security {\n public static class Cryptography {\n #region Settings\n\n private static int _iterations = 2;\n private static int _keySize = 256;\n\n private static string _hash = \"SHA1\";\n private static string _salt = \"aselrias38490a32\"; // Random\n private static string _vector = \"8947az34awl34kjq\"; // Random\n\n #endregion\n\n public static string Encrypt(string value, string password) {\n return Encrypt&lt;AesManaged&gt;(value, password);\n }\n public static string Encrypt&lt;T&gt;(string value, string password) \n where T : SymmetricAlgorithm, new() {\n byte[] vectorBytes = GetBytes&lt;ASCIIEncoding&gt;(_vector);\n byte[] saltBytes = GetBytes&lt;ASCIIEncoding&gt;(_salt);\n byte[] valueBytes = GetBytes&lt;UTF8Encoding&gt;(value);\n\n byte[] encrypted;\n using (T cipher = new T()) {\n PasswordDeriveBytes _passwordBytes = \n new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);\n byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);\n\n cipher.Mode = CipherMode.CBC;\n\n using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {\n using (MemoryStream to = new MemoryStream()) {\n using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {\n writer.Write(valueBytes, 0, valueBytes.Length);\n writer.FlushFinalBlock();\n encrypted = to.ToArray();\n }\n }\n }\n cipher.Clear();\n }\n return Convert.ToBase64String(encrypted);\n }\n\n public static string Decrypt(string value, string password) {\n return Decrypt&lt;AesManaged&gt;(value, password);\n }\n public static string Decrypt&lt;T&gt;(string value, string password) where T : SymmetricAlgorithm, new() {\n byte[] vectorBytes = GetBytes&lt;ASCIIEncoding&gt;(_vector);\n byte[] saltBytes = GetBytes&lt;ASCIIEncoding&gt;(_salt);\n byte[] valueBytes = Convert.FromBase64String(value);\n\n byte[] decrypted;\n int decryptedByteCount = 0;\n\n using (T cipher = new T()) {\n PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);\n byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);\n\n cipher.Mode = CipherMode.CBC;\n\n try {\n using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) {\n using (MemoryStream from = new MemoryStream(valueBytes)) {\n using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) {\n decrypted = new byte[valueBytes.Length];\n decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);\n }\n }\n }\n } catch (Exception ex) {\n return String.Empty;\n }\n\n cipher.Clear();\n }\n return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);\n }\n\n }\n}\n</code></pre>\n\n<p>The code is very simple to use. It literally just requires the following:</p>\n\n<pre><code>string encrypted = Cryptography.Encrypt(data, \"testpass\");\nstring decrypted = Cryptography.Decrypt(encrypted, \"testpass\");\n</code></pre>\n\n<p>By default, the implementation uses AesManaged - but you could actually also insert any other <code>SymmetricAlgorithm</code>. A list of the available <code>SymmetricAlgorithm</code> inheritors for .NET 4.5 can be found at: </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.aspx</a> </p>\n\n<p>As of the time of this post, the current list includes: </p>\n\n<ul>\n<li><code>AesManaged</code></li>\n<li><code>RijndaelManaged</code></li>\n<li><code>DESCryptoServiceProvider</code></li>\n<li><code>RC2CryptoServiceProvider</code> </li>\n<li><code>TripleDESCryptoServiceProvider</code></li>\n</ul>\n\n<p>To use <code>RijndaelManaged</code> with the code above, as an example, you would use:</p>\n\n<pre><code>string encrypted = Cryptography.Encrypt&lt;RijndaelManaged&gt;(dataToEncrypt, password);\nstring decrypted = Cryptography.Decrypt&lt;RijndaelManaged&gt;(encrypted, password);\n</code></pre>\n\n<p>I hope this is helpful to someone out there.</p>\n" }, { "answer_id": 17561816, "author": "0xEE00", "author_id": 1175886, "author_profile": "https://Stackoverflow.com/users/1175886", "pm_score": 2, "selected": false, "text": "<p>You can use password from text box like key...\nWith this code you can encrypt/decrypt text, picture, word document, pdf.... </p>\n\n<pre><code> public class Rijndael\n{\n private byte[] key;\n private readonly byte[] vector = { 255, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };\n\n ICryptoTransform EnkValue, DekValue;\n\n public Rijndael(byte[] key)\n {\n this.key = key;\n RijndaelManaged rm = new RijndaelManaged();\n rm.Padding = PaddingMode.PKCS7;\n EnkValue = rm.CreateEncryptor(key, vector);\n DekValue = rm.CreateDecryptor(key, vector);\n }\n\n public byte[] Encrypt(byte[] byte)\n {\n\n byte[] enkByte= byte;\n byte[] enkNewByte;\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, EnkValue, CryptoStreamMode.Write))\n {\n cs.Write(enkByte, 0, enkByte.Length);\n cs.FlushFinalBlock();\n\n ms.Position = 0;\n enkNewByte= new byte[ms.Length];\n ms.Read(enkNewByte, 0, enkNewByte.Length);\n }\n }\n return enkNeyByte;\n }\n\n public byte[] Dekrypt(byte[] enkByte)\n {\n byte[] dekByte;\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, DekValue, CryptoStreamMode.Write))\n {\n cs.Write(enkByte, 0, enkByte.Length);\n cs.FlushFinalBlock();\n\n ms.Position = 0;\n dekByte= new byte[ms.Length];\n ms.Read(dekByte, 0, dekByte.Length);\n }\n }\n return dekByte;\n }\n}\n</code></pre>\n\n<p>Convert password from text box to byte array...</p>\n\n<pre><code>private byte[] ConvertPasswordToByte(string password)\n {\n byte[] key = new byte[32];\n for (int i = 0; i &lt; passwprd.Length; i++)\n {\n key[i] = Convert.ToByte(passwprd[i]);\n }\n return key;\n }\n</code></pre>\n" }, { "answer_id": 24963085, "author": "siddharth", "author_id": 3876812, "author_profile": "https://Stackoverflow.com/users/3876812", "pm_score": 3, "selected": false, "text": "<pre><code>//Code to encrypt Data : \n public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv) \n { \n AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider(); \n //Block size : Gets or sets the block size, in bits, of the cryptographic operation. \n dataencrypt.BlockSize = 128; \n //KeySize: Gets or sets the size, in bits, of the secret key \n dataencrypt.KeySize = 128; \n //Key: Gets or sets the symmetric key that is used for encryption and decryption. \n dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key); \n //IV : Gets or sets the initialization vector (IV) for the symmetric algorithm \n dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv); \n //Padding: Gets or sets the padding mode used in the symmetric algorithm \n dataencrypt.Padding = PaddingMode.PKCS7; \n //Mode: Gets or sets the mode for operation of the symmetric algorithm \n dataencrypt.Mode = CipherMode.CBC; \n //Creates a symmetric AES encryptor object using the current key and initialization vector (IV). \n ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV); \n //TransformFinalBlock is a special function for transforming the last block or a partial block in the stream. \n //It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of \n //information returned at the end might be larger than a single block when padding is added. \n byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length); \n crypto1.Dispose(); \n //return the encrypted data \n return encrypteddata; \n } \n\n//code to decrypt data\n private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv) \n { \n\n AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider(); \n keydecrypt.BlockSize = 128; \n keydecrypt.KeySize = 128; \n keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key); \n keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv); \n keydecrypt.Padding = PaddingMode.PKCS7; \n keydecrypt.Mode = CipherMode.CBC; \n ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV); \n\n byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length); \n crypto1.Dispose(); \n return returnbytearray; \n }\n</code></pre>\n" }, { "answer_id": 26758901, "author": "Zeeshan Amber", "author_id": 3962935, "author_profile": "https://Stackoverflow.com/users/3962935", "pm_score": 2, "selected": false, "text": "<p>here is a neat and clean code to understand AES 256 algorithm implemented in C#\ncall Encrypt function as <code>encryptedstring = cryptObj.Encrypt(username, \"AGARAMUDHALA\", \"EZHUTHELLAM\", \"SHA1\", 3, \"@1B2c3D4e5F6g7H8\", 256);</code></p>\n\n<pre><code>public class Crypt\n{\n public string Encrypt(string passtext, string passPhrase, string saltV, string hashstring, int Iterations, string initVect, int keysize)\n {\n string functionReturnValue = null;\n // Convert strings into byte arrays.\n // Let us assume that strings only contain ASCII codes.\n // If strings include Unicode characters, use Unicode, UTF7, or UTF8\n // encoding.\n byte[] initVectorBytes = null;\n initVectorBytes = Encoding.ASCII.GetBytes(initVect);\n byte[] saltValueBytes = null;\n saltValueBytes = Encoding.ASCII.GetBytes(saltV);\n\n // Convert our plaintext into a byte array.\n // Let us assume that plaintext contains UTF8-encoded characters.\n byte[] plainTextBytes = null;\n plainTextBytes = Encoding.UTF8.GetBytes(passtext);\n // First, we must create a password, from which the key will be derived.\n // This password will be generated from the specified passphrase and\n // salt value. The password will be created using the specified hash\n // algorithm. Password creation can be done in several iterations.\n PasswordDeriveBytes password = default(PasswordDeriveBytes);\n password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashstring, Iterations);\n // Use the password to generate pseudo-random bytes for the encryption\n // key. Specify the size of the key in bytes (instead of bits).\n byte[] keyBytes = null;\n keyBytes = password.GetBytes(keysize/8);\n // Create uninitialized Rijndael encryption object.\n RijndaelManaged symmetricKey = default(RijndaelManaged);\n symmetricKey = new RijndaelManaged();\n\n // It is reasonable to set encryption mode to Cipher Block Chaining\n // (CBC). Use default options for other symmetric key parameters.\n symmetricKey.Mode = CipherMode.CBC;\n // Generate encryptor from the existing key bytes and initialization\n // vector. Key size will be defined based on the number of the key\n // bytes.\n ICryptoTransform encryptor = default(ICryptoTransform);\n encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);\n\n // Define memory stream which will be used to hold encrypted data.\n MemoryStream memoryStream = default(MemoryStream);\n memoryStream = new MemoryStream();\n\n // Define cryptographic stream (always use Write mode for encryption).\n CryptoStream cryptoStream = default(CryptoStream);\n cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);\n // Start encrypting.\n cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n\n // Finish encrypting.\n cryptoStream.FlushFinalBlock();\n // Convert our encrypted data from a memory stream into a byte array.\n byte[] cipherTextBytes = null;\n cipherTextBytes = memoryStream.ToArray();\n\n // Close both streams.\n memoryStream.Close();\n cryptoStream.Close();\n\n // Convert encrypted data into a base64-encoded string.\n string cipherText = null;\n cipherText = Convert.ToBase64String(cipherTextBytes);\n\n functionReturnValue = cipherText;\n return functionReturnValue;\n }\n public string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)\n {\n string functionReturnValue = null;\n\n // Convert strings defining encryption key characteristics into byte\n // arrays. Let us assume that strings only contain ASCII codes.\n // If strings include Unicode characters, use Unicode, UTF7, or UTF8\n // encoding.\n\n\n byte[] initVectorBytes = null;\n initVectorBytes = Encoding.ASCII.GetBytes(initVector);\n\n byte[] saltValueBytes = null;\n saltValueBytes = Encoding.ASCII.GetBytes(saltValue);\n\n // Convert our ciphertext into a byte array.\n byte[] cipherTextBytes = null;\n cipherTextBytes = Convert.FromBase64String(cipherText);\n\n // First, we must create a password, from which the key will be\n // derived. This password will be generated from the specified\n // passphrase and salt value. The password will be created using\n // the specified hash algorithm. Password creation can be done in\n // several iterations.\n PasswordDeriveBytes password = default(PasswordDeriveBytes);\n password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);\n\n // Use the password to generate pseudo-random bytes for the encryption\n // key. Specify the size of the key in bytes (instead of bits).\n byte[] keyBytes = null;\n keyBytes = password.GetBytes(keySize / 8);\n\n // Create uninitialized Rijndael encryption object.\n RijndaelManaged symmetricKey = default(RijndaelManaged);\n symmetricKey = new RijndaelManaged();\n\n // It is reasonable to set encryption mode to Cipher Block Chaining\n // (CBC). Use default options for other symmetric key parameters.\n symmetricKey.Mode = CipherMode.CBC;\n\n // Generate decryptor from the existing key bytes and initialization\n // vector. Key size will be defined based on the number of the key\n // bytes.\n ICryptoTransform decryptor = default(ICryptoTransform);\n decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);\n\n // Define memory stream which will be used to hold encrypted data.\n MemoryStream memoryStream = default(MemoryStream);\n memoryStream = new MemoryStream(cipherTextBytes);\n\n // Define memory stream which will be used to hold encrypted data.\n CryptoStream cryptoStream = default(CryptoStream);\n cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);\n\n // Since at this point we don't know what the size of decrypted data\n // will be, allocate the buffer long enough to hold ciphertext;\n // plaintext is never longer than ciphertext.\n byte[] plainTextBytes = null;\n plainTextBytes = new byte[cipherTextBytes.Length + 1];\n\n // Start decrypting.\n int decryptedByteCount = 0;\n decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n\n // Close both streams.\n memoryStream.Close();\n cryptoStream.Close();\n\n // Convert decrypted data into a string.\n // Let us assume that the original plaintext string was UTF8-encoded.\n string plainText = null;\n plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);\n\n // Return decrypted string.\n functionReturnValue = plainText;\n\n\n return functionReturnValue;\n }\n}\n</code></pre>\n" }, { "answer_id": 38075808, "author": "ARTAGE", "author_id": 6184711, "author_profile": "https://Stackoverflow.com/users/6184711", "pm_score": 3, "selected": false, "text": "<p><strong><em><a href=\"http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt\" rel=\"noreferrer\">http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt</a></em></strong></p>\n\n<pre><code>using System.Security.Cryptography;\nusing System.IO;\n</code></pre>\n\n<p> </p>\n\n<pre><code>public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)\n{\n byte[] encryptedBytes = null;\n byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };\n using (MemoryStream ms = new MemoryStream())\n {\n using (RijndaelManaged AES = new RijndaelManaged())\n {\n AES.KeySize = 256;\n AES.BlockSize = 128;\n var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);\n AES.Key = key.GetBytes(AES.KeySize / 8);\n AES.IV = key.GetBytes(AES.BlockSize / 8);\n AES.Mode = CipherMode.CBC;\n using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);\n cs.Close();\n }\n encryptedBytes = ms.ToArray();\n }\n }\n return encryptedBytes;\n}\n\npublic byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)\n{\n byte[] decryptedBytes = null;\n byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };\n using (MemoryStream ms = new MemoryStream())\n {\n using (RijndaelManaged AES = new RijndaelManaged())\n {\n AES.KeySize = 256;\n AES.BlockSize = 128;\n var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);\n AES.Key = key.GetBytes(AES.KeySize / 8);\n AES.IV = key.GetBytes(AES.BlockSize / 8);\n AES.Mode = CipherMode.CBC;\n using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);\n cs.Close();\n }\n decryptedBytes = ms.ToArray();\n }\n }\n return decryptedBytes;\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I can't seem to find a nice clean example of using AES 128 bit encryption. Does anyone have some sample code?
If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample): > > <http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx> > > > And just in case you need the sample in a hurry, here it is in all its plagiarized glory: ``` using System; using System.IO; using System.Security.Cryptography; namespace RijndaelManaged_Example { class RijndaelExample { public static void Main() { try { string original = "Here is some data to encrypt!"; // Create a new instance of the RijndaelManaged // class. This generates a new key and initialization // vector (IV). using (RijndaelManaged myRijndael = new RijndaelManaged()) { myRijndael.GenerateKey(); myRijndael.GenerateIV(); // Encrypt the string to an array of bytes. byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV); // Decrypt the bytes to a string. string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV); //Display the original data and the decrypted data. Console.WriteLine("Original: {0}", original); Console.WriteLine("Round Trip: {0}", roundtrip); } } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } } static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) { // Check arguments. if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException("plainText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV"); byte[] encrypted; // Create an RijndaelManaged object // with the specified key and IV. using (RijndaelManaged rijAlg = new RijndaelManaged()) { rijAlg.Key = Key; rijAlg.IV = IV; // Create a decryptor to perform the stream transform. ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } // Return the encrypted bytes from the memory stream. return encrypted; } static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) { // Check arguments. if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV"); // Declare the string used to hold // the decrypted text. string plaintext = null; // Create an RijndaelManaged object // with the specified key and IV. using (RijndaelManaged rijAlg = new RijndaelManaged()) { rijAlg.Key = Key; rijAlg.IV = IV; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; } } } ```
273,485
<p>Seems likes it might be useful to have the assert display a message when an assertion fails.</p> <p>Currently an <code>AssertionError</code> gets thrown, can you specify a custom message for it?</p> <p>Can you show an example mechanism for doing this (other than creating your own exception type and throwing it)?</p>
[ { "answer_id": 273488, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "<p>You certainly can:</p>\n<pre><code>assert x &gt; 0 : &quot;x must be greater than zero, but x = &quot; + x;\n</code></pre>\n<p>See <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html\" rel=\"noreferrer\">Programming with Assertions</a> for more information.</p>\n" }, { "answer_id": 273492, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 4, "selected": false, "text": "<p>It absolutely does:</p>\n\n<pre><code>assert importantVar != null : \"The important var was null!\";\n</code></pre>\n\n<p>This will add \"The important var was null\" to the exception that is thrown.</p>\n" }, { "answer_id": 273493, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>If you use</p>\n\n<pre><code>assert Expression1 : Expression2 ;\n</code></pre>\n\n<p>Expression2 is used as a detail message for the AssertionError.</p>\n" }, { "answer_id": 492499, "author": "matt burns", "author_id": 276093, "author_profile": "https://Stackoverflow.com/users/276093", "pm_score": 4, "selected": false, "text": "<pre><code>assert (condition) : \"some message\";\n</code></pre>\n\n<p>I'd recommend putting the conditional in brackets</p>\n\n<pre><code>assert (y &gt; x): \"y is too small. y = \" + y;\n</code></pre>\n\n<p>Imagine if you came across code like this...</p>\n\n<pre><code>assert isTrue() ? true : false : \"some message\";\n</code></pre>\n\n<p>Don't forget this has nothing to do with asserts you'd write in JUnit.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
Seems likes it might be useful to have the assert display a message when an assertion fails. Currently an `AssertionError` gets thrown, can you specify a custom message for it? Can you show an example mechanism for doing this (other than creating your own exception type and throwing it)?
You certainly can: ``` assert x > 0 : "x must be greater than zero, but x = " + x; ``` See [Programming with Assertions](https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html) for more information.
273,487
<p>I have read the very good blog post of Rob Conery <a href="http://blog.wekeroad.com/blog/crazy-talk-reducing-orm-friction/" rel="nofollow noreferrer">Crazy Talk: Reducing ORM Friction</a><br> How can I generalize this interface so I can implement it with NHibernate?</p> <pre><code>using System; using System.Collections; using System.Linq; using System.Linq.Expressions; public interface IRepository&lt;T&gt; { IQueryable&lt;T&gt; GetAll(); PagedList&lt;T&gt; GetPaged(int pageIndex, int pageSize); IQueryable&lt;T&gt; Find(Expression&lt;Func&lt;T, bool&gt;&gt; expression); void Save(T item); void Delete(T item); } </code></pre> <p>I want to use the <code>Expression&lt;Func&lt;T, bool&gt;&gt;</code> expression in NHibernate. Any clue?</p>
[ { "answer_id": 273503, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "<p>You'll need to walk the expression tree and build your Criteria.</p>\n" }, { "answer_id": 273506, "author": "Ryan Rinaldi", "author_id": 2278, "author_profile": "https://Stackoverflow.com/users/2278", "pm_score": 3, "selected": true, "text": "<p>Look at LINQ to NHibernate. Kyle Baley has a great <a href=\"http://codebetter.com/blogs/kyle.baley/archive/2008/04/07/trying-out-linq-for-nhibernate.aspx\" rel=\"nofollow noreferrer\">overview of it</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12514/" ]
I have read the very good blog post of Rob Conery [Crazy Talk: Reducing ORM Friction](http://blog.wekeroad.com/blog/crazy-talk-reducing-orm-friction/) How can I generalize this interface so I can implement it with NHibernate? ``` using System; using System.Collections; using System.Linq; using System.Linq.Expressions; public interface IRepository<T> { IQueryable<T> GetAll(); PagedList<T> GetPaged(int pageIndex, int pageSize); IQueryable<T> Find(Expression<Func<T, bool>> expression); void Save(T item); void Delete(T item); } ``` I want to use the `Expression<Func<T, bool>>` expression in NHibernate. Any clue?
Look at LINQ to NHibernate. Kyle Baley has a great [overview of it](http://codebetter.com/blogs/kyle.baley/archive/2008/04/07/trying-out-linq-for-nhibernate.aspx)
273,516
<p>Many of us need to deal with user input, search queries, and situations where the input text can potentially contain profanity or undesirable language. Oftentimes this needs to be filtered out.</p> <p>Where can one find a good list of swear words in various languages and dialects? </p> <p>Are there APIs available to sources that contain good lists? Or maybe an API that simply says "yes this is clean" or "no this is dirty" with some parameters?</p> <p>What are some good methods for catching folks trying to trick the system, like a$$, azz, or a55?</p> <p>Bonus points if you offer solutions for PHP. :)</p> <h2><em>Edit: Response to answers that say simply avoid the programmatic issue:</em></h2> <p>I think there is a place for this kind of filter when, for instance, a user can use public image search to find pictures that get added to a sensitive community pool. If they can search for "penis", then they will likely get many pictures of, yep. If we don't want pictures of that, then preventing the word as a search term is a good gatekeeper, though admittedly not a foolproof method. Getting the list of words in the first place is the real question.</p> <p>So I'm really referring to a way to figure out of a single token is dirty or not and then simply disallow it. I'd not bother preventing a sentiment like the totally hilarious "long necked giraffe" reference. Nothing you can do there. :)</p>
[ { "answer_id": 273520, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": 9, "selected": true, "text": "<p><a href=\"http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/\" rel=\"noreferrer\">Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?</a></p>\n<p>Also, one can't forget <a href=\"http://habitatchronicles.com/2007/03/the-untold-history-of-toontowns-speedchat-or-blockchattm-from-disney-finally-arrives/\" rel=\"noreferrer\">The Untold History of Toontown's SpeedChat</a>, where even using a &quot;safe-word whitelist&quot; resulted in a 14-year-old quickly circumventing it with:\n<em>&quot;I want to stick my long-necked Giraffe up your fluffy white bunny.&quot;</em></p>\n<p>Bottom line: Ultimately, for any system that you implement, there is absolutely no substitute for human review (whether peer or otherwise). Feel free to implement a rudimentary tool to get rid of the drive-by's, but for the determined troll, you absolutely must have a non-algorithm-based approach.</p>\n<p>A system that removes anonymity and introduces accountability (something that Stack Overflow does well) is helpful also, particularly in order to help combat <a href=\"http://www.penny-arcade.com/comic/2004/03/19/\" rel=\"noreferrer\">John Gabriel's G.I.F.T.</a></p>\n<p>You also asked where you can get profanity lists to get you started -- one open-source project to check out is <a href=\"http://dansguardian.org\" rel=\"noreferrer\">Dansguardian</a> -- check out the source code for their default profanity lists. There is also an additional third party <a href=\"http://contentfilter.futuragts.com/phraselists/\" rel=\"noreferrer\">Phrase List</a> that you can download for the proxy that may be a helpful gleaning point for you.</p>\n<p><strong>Edit in response to the question edit:</strong> Thanks for the clarification on what you're trying to do. In that case, if you're just trying to do a simple word filter, there are two ways you can do it. One is to create a single long regexp with all of the banned phrases that you want to censor, and merely do a regex find/replace with it. A regex like:</p>\n<pre><code>$filterRegex = &quot;(boogers|snot|poop|shucks|argh)&quot;\n</code></pre>\n<p>and run it on your input string using <a href=\"http://us.php.net/preg_match\" rel=\"noreferrer\">preg_match()</a> to wholesale test for a hit,</p>\n<p>or <a href=\"http://us.php.net/preg_replace\" rel=\"noreferrer\">preg_replace()</a> to blank them out.</p>\n<p>You can also load those functions up with arrays rather than a single long regex, and for long word lists, it may be more manageable. See the <a href=\"http://us.php.net/preg_replace\" rel=\"noreferrer\">preg_replace()</a> for some good examples as to how arrays can be used flexibly.</p>\n<p>For additional PHP programming examples, see this page for a <a href=\"http://www.bitrepository.com/advanced-word-filter.html\" rel=\"noreferrer\">somewhat advanced generic class</a> for word filtering that *'s out the center letters from censored words, and this <a href=\"https://stackoverflow.com/questions/24515/bad-words-filter\">previous Stack Overflow question</a> that also has a PHP example (the main valuable part in there is the SQL-based filtered word approach -- the leet-speak compensator can be dispensed with if you find it unnecessary).</p>\n<p>You also added: &quot;<em>Getting the list of words in the first place is the real question.</em>&quot; -- in addition to some of the previous Dansgaurdian links, you may find <a href=\"http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/\" rel=\"noreferrer\">this handy .zip</a> of 458 words to be helpful.</p>\n" }, { "answer_id": 273522, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": -1, "selected": false, "text": "<p>Don't.</p>\n\n<p>Because:</p>\n\n<ul>\n<li><strong><a href=\"http://www.urbandictionary.com/define.php?term=clbuttic\" rel=\"nofollow noreferrer\">Clbuttic</a></strong></li>\n<li>Profanity is not OMG EVIL</li>\n<li>Profanity cannot be effectively defined</li>\n<li>Most people quite probably don't appreciate being \"protected\" from profanity</li>\n</ul>\n\n<p>Edit: While I agree with the commenter who said \"censorship is wrong\", that is not the nature of this answer.</p>\n" }, { "answer_id": 273532, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 1, "selected": false, "text": "<p>Frankly, I'd let them get the \"trick the system\" words out and ban them instead, which is just me. But it also makes the programming simpler.</p>\n\n<p>What I'd do is implement a regex filter like so: <code>/[\\s]dooby (doo?)[\\s]/i</code> or it the word is prefixed on others, <code>/[\\s]doob(er|ed|est)[\\s]/</code>. These would prevent filtering words like assuaged, which is perfectly valid, but would also require knowledge of the other variants and updating the actual filter if you learn a new one. Obviously these are all examples, but you'd have to decide how to do it yourself.</p>\n\n<p>I'm not about to type out all the words I know, not when I don't actually want to know them.</p>\n" }, { "answer_id": 273538, "author": "Matt Passell", "author_id": 33836, "author_profile": "https://Stackoverflow.com/users/33836", "pm_score": 5, "selected": false, "text": "<p>I don't know of any good libraries for this, but whatever you do, make sure that you err in the direction of letting stuff through. I've dealt with systems that wouldn't allow me to use \"mpassell\" as a username, because it contains \"ass\" as a substring. That's a great way to alienate users!</p>\n" }, { "answer_id": 273544, "author": "Tim Cavanaugh", "author_id": 22798, "author_profile": "https://Stackoverflow.com/users/22798", "pm_score": 4, "selected": false, "text": "<p>Have a look at <a href=\"http://wiki.cdyne.com/wiki/index.php?title=Profanity_Filter\" rel=\"noreferrer\">CDYNE's Profanity Filter Web Service</a></p>\n\n<p><a href=\"http://ws.cdyne.com/ProfanityWS/Profanity.asmx\" rel=\"noreferrer\">Testing URL</a></p>\n" }, { "answer_id": 273575, "author": "Adam Jaskiewicz", "author_id": 35322, "author_profile": "https://Stackoverflow.com/users/35322", "pm_score": 1, "selected": false, "text": "<p>Don't. It just leads to problems. One clbuttic personal experience I have with profanity filters is the time where I was kick/banned from an IRC channel for mentioning that I was \"heading over the bridge to Hancock for a couple hours\" or something to that effect.</p>\n" }, { "answer_id": 273587, "author": "Axel", "author_id": 34778, "author_profile": "https://Stackoverflow.com/users/34778", "pm_score": 4, "selected": false, "text": "<p>The only way to prevent offensive user input is to prevent all user input.</p>\n\n<p>If you insist on allowing user input and need moderation, then incorporate human moderators.</p>\n" }, { "answer_id": 273596, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 3, "selected": false, "text": "<p>If you can do something like Digg/Stackoverflow where the users can downvote/mark obscene content... do so.</p>\n\n<p>Then all you need to do is review the \"naughty\" users, and block them if they break the rules.</p>\n" }, { "answer_id": 273835, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 5, "selected": false, "text": "<p>a profanity filtering system will never be perfect, even if the programmer is cocksure and keeps abreast of all nude developments</p>\n\n<p>that said, any list of 'naughty words' is likely to perform as well as any other list, since the underlying problem is <em>language understanding</em> which is pretty much intractable with current technology</p>\n\n<p>so, the only practical solution is twofold:</p>\n\n<ol>\n<li>be prepared to update your dictionary frequently</li>\n<li>hire a human editor to correct false positives (e.g. \"clbuttic\" instead of \"classic\") and false negatives (oops! missed one!)</li>\n</ol>\n" }, { "answer_id": 273855, "author": "Matthew", "author_id": 1645, "author_profile": "https://Stackoverflow.com/users/1645", "pm_score": 5, "selected": false, "text": "<p>During a job interview of mine, the company CTO who was interviewing me tried out a word/web game I wrote in Java. Out of a word list of the entire Oxford English dictionary, what was the first word that came up to be guessed?</p>\n\n<p>Of course, the most foul word in the English language.</p>\n\n<p>Somehow, I still got the job offer, but I then tracked down a profanity word list (not <a href=\"http://www.jivesoftware.com/jivespace/docs/DOC-1906\" rel=\"noreferrer\">unlike this one</a>) and wrote a quick script to generate a new dictionary without all of the bad words (without even having to look at the list).</p>\n\n<p>For your particular case, I think comparing the search to real words sounds like the way to go with a word list like that. The alternative styles/punctuation require a bit more work, but I doubt users will use that often enough to be an issue.</p>\n" }, { "answer_id": 274182, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 3, "selected": false, "text": "<p>Regarding your \"trick the system\" subquestion, you can handle that by normalizing both the \"bad word\" list and the user-entered text before doing your search. e.g., Use a series of regexes (or <strong>tr</strong> if PHP has it) to convert <strong>[z$5]</strong> to \"s\", <strong>[4@]</strong> to \"a\", etc., then compare the normalized \"bad word\" list against the normalized text. Note that the normalization could potentially lead to additional false positives, although I can't think of any actual cases at the moment.</p>\n\n<p>The larger challenge is to come up with something that will let people quote \"The <strong>pen is</strong> mightier than the sword\" while blocking \"p e n i s\".</p>\n" }, { "answer_id": 583449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I agree with HanClinto's post higher up in this discussion. I generally use regular expressions to string-match input text. And this is a vain effort, as, like you originally mentioned you have to explicitly account for every trick form of writing popular on the net in your \"blocked\" list.</p>\n\n<p>On a side note, while others are debating the ethics of censorship, I must agree that some form is necessary on the web. Some people simply enjoy posting vulgarity because it can be instantly offensive to a large body of people, and requires absolutely no thought on the author's part.</p>\n\n<p>Thank you for the ideas.</p>\n\n<p>HanClinto rules!</p>\n" }, { "answer_id": 2721306, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 3, "selected": false, "text": "<p>Beware of localization issues: what is a swearword in one language might be a perfectly normal word in another.</p>\n\n<p>One current example of this: ebay uses a dictionary approach to filter \"bad words\" from feedback. If you try to enter the german translation of \"this was a perfect transaction\" (\"das war eine perfekte Transaktion\"), ebay will reject the feedback due to bad words.</p>\n\n<p>Why? Because the german word for \"was\" is \"war\", and \"war\" is in ebay dictionary of \"bad words\".</p>\n\n<p>So beware of localisation issues.</p>\n" }, { "answer_id": 3829164, "author": "Gordon", "author_id": 208809, "author_profile": "https://Stackoverflow.com/users/208809", "pm_score": 1, "selected": false, "text": "<p>I agree with the futility of the subject, but if you have to have a filter, check out Ning's <a href=\"http://github.com/ning/boxwood\" rel=\"nofollow\">Boxwood</a>:</p>\n\n<blockquote>\n <p>Boxwood is a PHP extension for fast replacement of multiple words in a piece of text. It supports case-sensitive and case-insensitive matching. It requires that the text it operates on be encoded as UTF-8.</p>\n</blockquote>\n\n<p>Also see this blog post for more details:</p>\n\n<ul>\n<li><a href=\"http://www.sklar.com/blog/archives/122-Fast-Multiple-String-Replacement-in-PHP.html\" rel=\"nofollow\">Fast Multiple String Replacement in PHP</a></li>\n</ul>\n\n<blockquote>\n <p>With Boxwood, you can have your list of search terms be as long as you like -- the search and replace algorithm doesn't get slower with more words on the list of words to look for. It works by building a trie of all the search terms and then scans your subject text just once, walking down elements of the trie and comparing them to characters in your text. It supports US-ASCII and UTF-8, case-sensitive or insensitive matching, and has some English-centric word boundary checking logic.</p>\n</blockquote>\n" }, { "answer_id": 7073043, "author": "andrew", "author_id": 895890, "author_profile": "https://Stackoverflow.com/users/895890", "pm_score": 2, "selected": false, "text": "<p>Once you have a good MYSQL table of some bad words you want to filter (I started with one of the links in this thread), you can do something like this:</p>\n\n<pre><code>$errors = array(); //Initialize error array (I use this with all my PHP form validations)\n\n$SCREENNAME = mysql_real_escape_string($_POST['SCREENNAME']); //Escape the input data to prevent SQL injection when you query the profanity table.\n\n$ProfanityCheckString = strtoupper($SCREENNAME); //Make the input string uppercase (so that 'BaDwOrD' is the same as 'BADWORD'). All your values in the profanity table will need to be UPPERCASE for this to work.\n\n$ProfanityCheckString = preg_replace('/[_-]/','',$ProfanityCheckString); //I allow alphanumeric, underscores, and dashes...nothing else (I control this with PHP form validation). Pull out non-alphanumeric characters so 'B-A-D-W-O-R-D' shows up as 'BADWORD'.\n\n$ProfanityCheckString = preg_replace('/1/','I',$ProfanityCheckString); //Replace common numeric representations of letters so '84DW0RD' shows up as 'BADWORD'.\n\n$ProfanityCheckString = preg_replace('/3/','E',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/4/','A',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/5/','S',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/6/','G',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/7/','T',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/8/','B',$ProfanityCheckString);\n\n$ProfanityCheckString = preg_replace('/0/','O',$ProfanityCheckString); //Replace ZERO's with O's (Capital letter o's).\n\n$ProfanityCheckString = preg_replace('/Z/','S',$ProfanityCheckString); //Replace Z's with S's, another common substitution. Make sure you replace Z's with S's in your profanity database for this to work properly. Same with all the numbers too--having S3X7 in your database won't work, since this code would render that string as 'SEXY'. The profanity table should have the \"rendered\" version of the bad words.\n\n$CheckProfanity = mysql_query(\"SELECT * FROM DATABASE.TABLE p WHERE p.WORD = '\".$ProfanityCheckString.\"'\");\nif(mysql_num_rows($CheckProfanity) &gt; 0) {$errors[] = 'Please select another Screen Name.';} //Check your profanity table for the scrubbed input. You could get real crazy using LIKE and wildcards, but I only want a simple profanity filter.\n\nif (count($errors) &gt; 0) {foreach($errors as $error) {$errorString .= \"&lt;span class='PHPError'&gt;$error&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;\";} echo $errorString;} //Echo any PHP errors that come out of the validation, including any profanity flagging.\n\n\n//You can also use these lines to troubleshoot.\n//echo $ProfanityCheckString;\n//echo \"&lt;br /&gt;\";\n//echo mysql_error();\n//echo \"&lt;br /&gt;\";\n</code></pre>\n\n<p>I'm sure there is a more efficient way to do all those replacements, but I'm not smart enough to figure it out (and this seems to work okay, albeit inefficiently).</p>\n\n<p>I believe that you should err on the side of allowing users to register, and use humans to filter and add to your profanity table as required. Though it all depends on the cost of a false positive (okay word flagged as bad) versus a false negative (bad word gets through). That should ultimately govern how aggressive or conservative you are in your filtering strategy.</p>\n\n<p>I would also be very careful if you want to use wildcards, since they can sometimes behave more onerously than you intend.</p>\n" }, { "answer_id": 12851539, "author": "Jaider", "author_id": 480700, "author_profile": "https://Stackoverflow.com/users/480700", "pm_score": 1, "selected": false, "text": "<p>I concluded, in order to create a good profanity filter we need 3 main components, or at least it is what I am going to do. These they are:</p>\n\n<ol>\n<li>The filter: a background service that verify against a blacklist, dictionary or something like that.</li>\n<li>Not allow anonymous account</li>\n<li>Report abuse</li>\n</ol>\n\n<p>A bonus, it will be to reward somehow those who contribute with accurate abuse reporters and punish the offender, e.g. suspend their accounts.</p>\n" }, { "answer_id": 13115492, "author": "Chase Florell", "author_id": 124069, "author_profile": "https://Stackoverflow.com/users/124069", "pm_score": 2, "selected": false, "text": "<p>I'm a little late to the party, but I have a solution that might work for some who read this. It's in javascript instead of php, but there's a valid reason for it.</p>\n\n<blockquote>\n <p>Full disclosure, I wrote this plugin... </p>\n</blockquote>\n\n<p>Anyways. </p>\n\n<p>The approach I've gone with is to allow a user to \"Opt-In\" to their profanity filtering. Basically profanity will be allowed by default, but if my users don't want to read it, they don't have to. This also helps with the \"l33t sp3@k\" issue.</p>\n\n<p>The concept is a simple <a href=\"/questions/tagged/jquery\" class=\"post-tag\" title=\"show questions tagged &#39;jquery&#39;\" rel=\"tag\">jquery</a> plugin that gets injected by the server if the client's account is enabling profanity filtering. From there, it's just a couple simple lines that blot out the swears.</p>\n\n<p>Here's the demo page<br>\n<a href=\"https://chaseflorell.github.io/jQuery.ProfanityFilter/demo/\" rel=\"nofollow\">https://chaseflorell.github.io/jQuery.ProfanityFilter/demo/</a></p>\n\n<pre><code>&lt;div id=\"foo\"&gt;\n ass will fail but password will not\n&lt;/div&gt;\n\n&lt;script&gt;\n // code:\n $('#foo').profanityFilter({\n customSwears: ['ass']\n });\n&lt;/script&gt;\n</code></pre>\n\n<p><strong>result</strong> </p>\n\n<blockquote>\n <p>&#42;&#42;&#42; will fail but password will not</p>\n</blockquote>\n" }, { "answer_id": 13447680, "author": "nickhar", "author_id": 1714488, "author_profile": "https://Stackoverflow.com/users/1714488", "pm_score": 6, "selected": false, "text": "<p>Whilst I know that this question is fairly old, but it's a commonly occurring question...</p>\n\n<p>There is both a reason and a distinct need for profanity filters (see <a href=\"http://en.wikipedia.org/wiki/Profanity_filter\">Wikipedia entry here</a>), but they often fall short of being 100% accurate for very distinct reasons; <strong>Context</strong> and <strong>accuracy</strong>.</p>\n\n<p>It depends (wholly) on what you're trying to achieve - at it's most basic, you're probably trying to cover the \"<a href=\"http://en.wikipedia.org/wiki/Seven_dirty_words\">seven dirty words</a>\" and then some... Some businesses need to filter the most basic of profanity: basic swear words, URLs or even personal information and so on, but others need to prevent illicit account naming (Xbox live is an example) or far more...</p>\n\n<p>User generated content doesn't just contain potential swear words, it can also contain offensive references to:</p>\n\n<ul>\n<li>Sexual acts </li>\n<li>Sexual orientation</li>\n<li>Religion</li>\n<li>Ethnicity </li>\n<li>Etc...</li>\n</ul>\n\n<p>And potentially, in multiple languages. Shutterstock has developed <a href=\"https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words\">basic dirty-words lists</a> in 10 languages to date, but it's still basic and very much oriented towards their 'tagging' needs. There are a number of other lists available on the web.</p>\n\n<p>I agree with the accepted answer that it's not a defined science and <em>as</em> language is a continually evolving <em>challenge</em> but one where a 90% catch rate is better than 0%. It depends purely on your goals - what you're trying to achieve, the level of support you have and how important it is to remove profanities of different types.</p>\n\n<p>In building a filter, you need to consider the following elements and how they relate to your project:</p>\n\n<ul>\n<li>Words/phrases</li>\n<li>Acronyms (FOAD/LMFAO etc)</li>\n<li><a href=\"http://en.wikipedia.org/wiki/False_positive#Type_I_error\">False positives</a> (words, places and names like 'mishit', 'scunthorpe' and 'titsworth')</li>\n<li>URLs (porn sites are an obvious target)</li>\n<li>Personal information (email, address, phone etc - if applicable)</li>\n<li>Language choice (usually English by default)</li>\n<li>Moderation (how, if at all, you can interact with user generated content and what you can do with it)</li>\n</ul>\n\n<p>You can easily build a profanity filter that captures 90%+ of profanities, but you'll never hit 100%. It's just not possible. The closer you want to get to 100%, the harder it becomes... Having built a complex profanity engine in the past that dealt with more than 500K realtime messages per day, I'd offer the following advice:</p>\n\n<p><strong>A basic filter would involve:</strong></p>\n\n<ul>\n<li>Building a list of applicable profanities</li>\n<li>Developing a method of dealing with derivations of profanities</li>\n</ul>\n\n<p><strong>A moderately complex filer would involve, (In addition to a basic filter):</strong></p>\n\n<ul>\n<li>Using complex pattern matching to deal with extended derivations (using advanced regex)</li>\n<li>Dealing with <a href=\"http://en.wikipedia.org/wiki/Leet\">Leetspeak</a> (l33t)</li>\n<li>Dealing with <a href=\"http://en.wikipedia.org/wiki/False_positive#Type_I_error\">false positives</a></li>\n</ul>\n\n<p><strong>A complex filter would involve a number of the following (In addition to a moderate filter):</strong></p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/White_list\">Whitelists</a> and blacklists</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Bayesian_inference\">Naive bayesian inference</a> filtering of phrases/terms</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Soundex\">Soundex</a> functions (where a word sounds like another)</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\">Levenshtein distance</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Porter_Stemmer\">Stemming</a></li>\n<li>Human moderators to help guide a filtering engine to learn by example or where matches aren't accurate enough without guidance (a self/continually-improving system)</li>\n<li>Perhaps some form of AI engine</li>\n</ul>\n" }, { "answer_id": 42573870, "author": "Tural Ali", "author_id": 800639, "author_profile": "https://Stackoverflow.com/users/800639", "pm_score": 3, "selected": false, "text": "<p>I collected 2200 bad words in 12 languages: en, ar, cs, da, de, eo, es, fa, fi, fr, hi, hu, it, ja, ko, nl, no, pl, pt, ru, sv, th, tlh, tr, zh. </p>\n\n<p>MySQL dump, JSON, XML or CSV options are available. </p>\n\n<p><a href=\"https://github.com/turalus/openDB\" rel=\"noreferrer\">https://github.com/turalus/openDB</a></p>\n\n<p>I'd suggest you to execute this SQL into your DB and check everytime when user inputs something.</p>\n" }, { "answer_id": 55854134, "author": "HidekiAI", "author_id": 7234, "author_profile": "https://Stackoverflow.com/users/7234", "pm_score": 2, "selected": false, "text": "<p>Also late in the game, but doing some researches and stumbled across here. As others have mentioned, it's just almost close to impossible if it was automated, but if your design/requirement can involve in some cases (but not all the time) human interactions to review whether it is profane or not, you may consider ML. <a href=\"https://learn.microsoft.com/en-us/azure/cognitive-services/content-moderator/text-moderation-api#profanity\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/azure/cognitive-services/content-moderator/text-moderation-api#profanity</a> is my current choice right now for multiple reasons:</p>\n\n<ul>\n<li>Supports many localization</li>\n<li>They keep updating the database, so I don't have to keep up with latest slangs or languages (maintenance issue)</li>\n<li>When there is a high probability (I.e. 90% or more) you can just deny it pragmatically</li>\n<li>You can observe for category which causes a flag that may or may not be profanity, and can have somebody review it to teach that it is or isn't profane.</li>\n</ul>\n\n<p>For my need, it was/is based on public-friendly commercial service (OK, videogames) which other users may/will see the username, but the design requires that it has to go through profanity filter to reject offensive username. The sad part about this is the classic \"clbuttic\" issue will most likely occur since usernames are usually single word (up to N characters) of sometimes multiple words concatenated... Again, Microsoft's cognitive service will not flag \"Assist\" as Text.HasProfanity=true but may flag one of the categories probability to be high.</p>\n\n<p>As the OP inquires, what about \"a$$\", here's a result when I passed it through the filter:<a href=\"https://i.stack.imgur.com/dRYeT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dRYeT.png\" alt=\"enter image description here\"></a>, as you can see, it has determined it's not profane, but it has high probability that it is, so flags as recommendations of reviewing (human interactions).</p>\n\n<p>When probability is high, I can either return back \"I'm sorry, that name is already taken\" (even if it isn't) so that it is less offensive to anti-censorship persons or something, if we don't want to integrate human review, or return \"Your username have been notified to the live operation department, you may wait for your username to be reviewed and approved or chose another username\". Or whatever...</p>\n\n<p>By the way, the cost/price for this service is quite low for my purpose (how often does the username gets changed?), but again, for OP maybe the design demands more intensive queries and may not be ideal to pay/subscribe for ML-services, or cannot have human-review/interactions. It all depends on the design... But if design does fit the bill, perhaps this can be OP's solution.</p>\n\n<p>If interested, I can list the cons in the comment in the future.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27899/" ]
Many of us need to deal with user input, search queries, and situations where the input text can potentially contain profanity or undesirable language. Oftentimes this needs to be filtered out. Where can one find a good list of swear words in various languages and dialects? Are there APIs available to sources that contain good lists? Or maybe an API that simply says "yes this is clean" or "no this is dirty" with some parameters? What are some good methods for catching folks trying to trick the system, like a$$, azz, or a55? Bonus points if you offer solutions for PHP. :) *Edit: Response to answers that say simply avoid the programmatic issue:* ------------------------------------------------------------------------- I think there is a place for this kind of filter when, for instance, a user can use public image search to find pictures that get added to a sensitive community pool. If they can search for "penis", then they will likely get many pictures of, yep. If we don't want pictures of that, then preventing the word as a search term is a good gatekeeper, though admittedly not a foolproof method. Getting the list of words in the first place is the real question. So I'm really referring to a way to figure out of a single token is dirty or not and then simply disallow it. I'd not bother preventing a sentiment like the totally hilarious "long necked giraffe" reference. Nothing you can do there. :)
[Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?](http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/) Also, one can't forget [The Untold History of Toontown's SpeedChat](http://habitatchronicles.com/2007/03/the-untold-history-of-toontowns-speedchat-or-blockchattm-from-disney-finally-arrives/), where even using a "safe-word whitelist" resulted in a 14-year-old quickly circumventing it with: *"I want to stick my long-necked Giraffe up your fluffy white bunny."* Bottom line: Ultimately, for any system that you implement, there is absolutely no substitute for human review (whether peer or otherwise). Feel free to implement a rudimentary tool to get rid of the drive-by's, but for the determined troll, you absolutely must have a non-algorithm-based approach. A system that removes anonymity and introduces accountability (something that Stack Overflow does well) is helpful also, particularly in order to help combat [John Gabriel's G.I.F.T.](http://www.penny-arcade.com/comic/2004/03/19/) You also asked where you can get profanity lists to get you started -- one open-source project to check out is [Dansguardian](http://dansguardian.org) -- check out the source code for their default profanity lists. There is also an additional third party [Phrase List](http://contentfilter.futuragts.com/phraselists/) that you can download for the proxy that may be a helpful gleaning point for you. **Edit in response to the question edit:** Thanks for the clarification on what you're trying to do. In that case, if you're just trying to do a simple word filter, there are two ways you can do it. One is to create a single long regexp with all of the banned phrases that you want to censor, and merely do a regex find/replace with it. A regex like: ``` $filterRegex = "(boogers|snot|poop|shucks|argh)" ``` and run it on your input string using [preg\_match()](http://us.php.net/preg_match) to wholesale test for a hit, or [preg\_replace()](http://us.php.net/preg_replace) to blank them out. You can also load those functions up with arrays rather than a single long regex, and for long word lists, it may be more manageable. See the [preg\_replace()](http://us.php.net/preg_replace) for some good examples as to how arrays can be used flexibly. For additional PHP programming examples, see this page for a [somewhat advanced generic class](http://www.bitrepository.com/advanced-word-filter.html) for word filtering that \*'s out the center letters from censored words, and this [previous Stack Overflow question](https://stackoverflow.com/questions/24515/bad-words-filter) that also has a PHP example (the main valuable part in there is the SQL-based filtered word approach -- the leet-speak compensator can be dispensed with if you find it unnecessary). You also added: "*Getting the list of words in the first place is the real question.*" -- in addition to some of the previous Dansgaurdian links, you may find [this handy .zip](http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/) of 458 words to be helpful.
273,530
<p>Does anybody have a suggestion for a java library that performs automatic cropping and deskewing of images (like those retrieved from a flatbed scanner)?</p>
[ { "answer_id": 273552, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.imagemagick.org\" rel=\"nofollow noreferrer\">ImageMagick</a> can do that; you can use the <a href=\"http://sourceforge.net/projects/jmagick/\" rel=\"nofollow noreferrer\">ImageMagick Java bindings</a>. The <a href=\"http://www.imagemagick.org/Usage/crop/#trim\" rel=\"nofollow noreferrer\">auto-crop</a> operator is probably what you're looking for. Automatic deskewing is a much harder problem and involves some significant image processing; I'm not sure if ImageMagick can handle that. If you can figure out the skewing parameters using something else, ImageMagick can definitely unskew it for you.</p>\n" }, { "answer_id": 273564, "author": "Matt Passell", "author_id": 33836, "author_profile": "https://Stackoverflow.com/users/33836", "pm_score": 0, "selected": false, "text": "<p>I'd imagine that someone has built a library on top of the <a href=\"http://java.sun.com/javase/technologies/desktop/media/jai/\" rel=\"nofollow noreferrer\">Java Advanced Imaging API</a> for doing this. You could try Googling for \"Java Advanced Imaging deskew\".</p>\n" }, { "answer_id": 1618008, "author": "Roland Quast", "author_id": 195862, "author_profile": "https://Stackoverflow.com/users/195862", "pm_score": 0, "selected": false, "text": "<p>I've written a simple image deskew app, includes source. Available at:</p>\n\n<p><a href=\"http://www.recognition-software.com/image/deskew/\" rel=\"nofollow noreferrer\">http://www.recognition-software.com/image/deskew/</a></p>\n" }, { "answer_id": 4043042, "author": "anydoby", "author_id": 490108, "author_profile": "https://Stackoverflow.com/users/490108", "pm_score": 2, "selected": false, "text": "<p>I wrote a <a href=\"http://anydoby.com/jblog/en/java/1990\" rel=\"nofollow noreferrer\">note</a> that simple port of a very good deskewer. It works best if you have some text in the image.</p>\n" }, { "answer_id": 36248013, "author": "delkant", "author_id": 1250805, "author_profile": "https://Stackoverflow.com/users/1250805", "pm_score": 3, "selected": false, "text": "<p><strong>Deskewing</strong></p>\n\n<p>Take a look at <a href=\"https://github.com/nguyenq/tess4j\" rel=\"noreferrer\">Tess4j (Java JNA wrapper for Tesseract)</a>. </p>\n\n<p>You can combine <a href=\"http://tess4j.sourceforge.net/docs/docs-2.0/index.html?com/recognition/software/jdeskew/ImageDeskew.html\" rel=\"noreferrer\">ImageDeskew.getSkewAngle()</a> with <a href=\"http://tess4j.sourceforge.net/docs/docs-2.0/index.html?net/sourceforge/tess4j/util/ImageHelper.html\" rel=\"noreferrer\">ImageHelper.rotate(BufferedImage image, double angle)</a>.</p>\n\n<p>There is an example on how to use it on the test folder of the tess4j project <a href=\"https://github.com/nguyenq/tess4j/blob/master/src/test/java/net/sourceforge/tess4j/Tesseract1Test.java#L177\" rel=\"noreferrer\">Tesseract1Test.java</a></p>\n\n<pre><code>public void testDoOCR_SkewedImage() throws Exception {\n logger.info(\"doOCR on a skewed PNG image\");\n File imageFile = new File(this.testResourcesDataPath, \"eurotext_deskew.png\");\n BufferedImage bi = ImageIO.read(imageFile);\n ImageDeskew id = new ImageDeskew(bi);\n double imageSkewAngle = id.getSkewAngle(); // determine skew angle\n if ((imageSkewAngle &gt; MINIMUM_DESKEW_THRESHOLD || imageSkewAngle &lt; -(MINIMUM_DESKEW_THRESHOLD))) {\n bi = ImageHelper.rotateImage(bi, -imageSkewAngle); // deskew image\n }\n\n String expResult = \"The (quick) [brown] {fox} jumps!\\nOver the $43,456.78 &lt;lazy&gt; #90 dog\";\n String result = instance.doOCR(bi);\n logger.info(result);\n assertEquals(expResult, result.substring(0, expResult.length()));\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/goIQD.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/goIQD.png\" alt=\"eurotext_deskew.png\"></a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25939/" ]
Does anybody have a suggestion for a java library that performs automatic cropping and deskewing of images (like those retrieved from a flatbed scanner)?
**Deskewing** Take a look at [Tess4j (Java JNA wrapper for Tesseract)](https://github.com/nguyenq/tess4j). You can combine [ImageDeskew.getSkewAngle()](http://tess4j.sourceforge.net/docs/docs-2.0/index.html?com/recognition/software/jdeskew/ImageDeskew.html) with [ImageHelper.rotate(BufferedImage image, double angle)](http://tess4j.sourceforge.net/docs/docs-2.0/index.html?net/sourceforge/tess4j/util/ImageHelper.html). There is an example on how to use it on the test folder of the tess4j project [Tesseract1Test.java](https://github.com/nguyenq/tess4j/blob/master/src/test/java/net/sourceforge/tess4j/Tesseract1Test.java#L177) ``` public void testDoOCR_SkewedImage() throws Exception { logger.info("doOCR on a skewed PNG image"); File imageFile = new File(this.testResourcesDataPath, "eurotext_deskew.png"); BufferedImage bi = ImageIO.read(imageFile); ImageDeskew id = new ImageDeskew(bi); double imageSkewAngle = id.getSkewAngle(); // determine skew angle if ((imageSkewAngle > MINIMUM_DESKEW_THRESHOLD || imageSkewAngle < -(MINIMUM_DESKEW_THRESHOLD))) { bi = ImageHelper.rotateImage(bi, -imageSkewAngle); // deskew image } String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog"; String result = instance.doOCR(bi); logger.info(result); assertEquals(expResult, result.substring(0, expResult.length())); } ``` [![eurotext_deskew.png](https://i.stack.imgur.com/goIQD.png)](https://i.stack.imgur.com/goIQD.png)
273,546
<p>I'm trying to get a user control working asynchronously, yet no matter what I do it continues to work synchronously. I've stripped it down to its bare minimum as a test web application. This would be the user control:</p> <pre><code>&lt;%@ Control Language="C#" %&gt; &lt;script runat="server"&gt; SqlConnection m_oConnection; SqlCommand m_oCommand; void Page_Load(object sender, EventArgs e) { Trace.Warn("Page_Load"); string strDSN = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString + ";async=true"; string strSQL = "waitfor delay '00:00:10'; select * from MyTable"; m_oConnection = new SqlConnection(strDSN); m_oCommand = new SqlCommand(strSQL, m_oConnection); m_oConnection.Open(); Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true)); Page.ExecuteRegisteredAsyncTasks(); } IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state) { Trace.Warn("BeginHandler"); return m_oCommand.BeginExecuteReader(cb, state); } void EndHandler(IAsyncResult ar) { Trace.Warn("EndHandler"); GridView1.DataSource = m_oCommand.EndExecuteReader(ar); GridView1.DataBind(); m_oConnection.Close(); } void TimeoutHandler(IAsyncResult ar) { Trace.Warn("TimeoutHandler"); } &lt;/script&gt; &lt;asp:gridview id="GridView1" runat="server" /&gt; </code></pre> <p>And this would be the page in which I host the control three times:</p> <pre><code>&lt;%@ page language="C#" trace="true" async="true" asynctimeout="60" %&gt; &lt;%@ register tagprefix="uc" tagname="mycontrol" src="~/MyControl.ascx" %&gt; &lt;html&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;uc:mycontrol id="MyControl1" runat="server" /&gt; &lt;uc:mycontrol id="MyControl2" runat="server" /&gt; &lt;uc:mycontrol id="MyControl3" runat="server" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The page gets displayed without errors, but the trace at the bottom of the page shows each control instance is processed synchronously. What am I doing wrong? Is there a configuration setting somewhere I'm missing?</p>
[ { "answer_id": 273717, "author": "Charles", "author_id": 24898, "author_profile": "https://Stackoverflow.com/users/24898", "pm_score": 4, "selected": true, "text": "<p>Looks like I can answer my own question. The user control should not be calling <code>Page.ExecuteRegisteredAsyncTasks</code>. By doing that, the control was adding the async task, running it, and waiting for it to complete.</p>\n\n<p>Instead, each instance of the user control should call only <code>Page.RegisterAsyncTask</code>. After each control instance has done this the page automatically calls <code>RegistereAsyncTask</code> running all three registered async tasks simultaniously.</p>\n\n<p>So here is the new user control:</p>\n\n<pre><code>&lt;%@ Control Language=\"C#\" %&gt;\n&lt;script runat=\"server\"&gt;\n SqlConnection m_oConnection;\n SqlCommand m_oCommand;\n\n void Page_Load(object sender, EventArgs e)\n {\n Trace.Warn(ID, \"Page_Load - \" + Thread.CurrentThread.GetHashCode().ToString());\n string strDSN = ConfigurationManager.ConnectionStrings[\"DSN\"].ConnectionString + \";async=true\";\n string strSQL = \"waitfor delay '00:00:10'; select * from TEProcessedPerDay where Date &gt; dateadd(day, -90, getutcdate()) order by Date asc\";\n\n m_oConnection = new SqlConnection(strDSN);\n m_oCommand = new SqlCommand(strSQL, m_oConnection);\n m_oConnection.Open();\n\n Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true));\n }\n\n IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state)\n {\n Trace.Warn(ID, \"BeginHandler - \" + Thread.CurrentThread.GetHashCode().ToString());\n return m_oCommand.BeginExecuteReader(cb, state);\n }\n\n void EndHandler(IAsyncResult ar)\n {\n Trace.Warn(ID, \"EndHandler - \" + Thread.CurrentThread.GetHashCode().ToString());\n GridView1.DataSource = m_oCommand.EndExecuteReader(ar);\n GridView1.DataBind();\n m_oConnection.Close();\n }\n\n void TimeoutHandler(IAsyncResult ar)\n {\n Trace.Warn(ID, \"TimeoutHandler - \" + Thread.CurrentThread.GetHashCode().ToString());\n }\n&lt;/script&gt;\n&lt;asp:gridview id=\"GridView1\" runat=\"server\" /&gt;\n</code></pre>\n\n<p>And the unchanged page that creates three instances of the control:</p>\n\n<pre><code>&lt;%@ page language=\"C#\" async=\"true\" trace=\"true\" %&gt;\n&lt;%@ register tagprefix=\"uc\" tagname=\"mycontrol\" src=\"~/MyControl.ascx\" %&gt;\n&lt;html&gt;\n &lt;body&gt;\n &lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;uc:mycontrol id=\"MyControl1\" runat=\"server\" /&gt;\n &lt;uc:mycontrol id=\"MyControl2\" runat=\"server\" /&gt;\n &lt;uc:mycontrol id=\"MyControl3\" runat=\"server\" /&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 5229916, "author": "Nandun", "author_id": 649470, "author_profile": "https://Stackoverflow.com/users/649470", "pm_score": 1, "selected": false, "text": "<p>If I may add a little to the above post, we should not call the <code>ExecuteRegisteredAsyncTassk</code> explicitly unless there is a compelling reason. once you register the async task, the ASP.NET framework will execute all these tasks right after the <code>OnPrerender</code> event of the page lifecycle.</p>\n\n<p>An example for the usage of <code>ExecuteRegisteredAsyncTasks</code> could be;\nSometimes you may need to ensure that several async operations are completed before calling another async task. in a situation like this it is justifiable to use <code>ExecuteRegisteredAsyncTasks</code>.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24898/" ]
I'm trying to get a user control working asynchronously, yet no matter what I do it continues to work synchronously. I've stripped it down to its bare minimum as a test web application. This would be the user control: ``` <%@ Control Language="C#" %> <script runat="server"> SqlConnection m_oConnection; SqlCommand m_oCommand; void Page_Load(object sender, EventArgs e) { Trace.Warn("Page_Load"); string strDSN = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString + ";async=true"; string strSQL = "waitfor delay '00:00:10'; select * from MyTable"; m_oConnection = new SqlConnection(strDSN); m_oCommand = new SqlCommand(strSQL, m_oConnection); m_oConnection.Open(); Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true)); Page.ExecuteRegisteredAsyncTasks(); } IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state) { Trace.Warn("BeginHandler"); return m_oCommand.BeginExecuteReader(cb, state); } void EndHandler(IAsyncResult ar) { Trace.Warn("EndHandler"); GridView1.DataSource = m_oCommand.EndExecuteReader(ar); GridView1.DataBind(); m_oConnection.Close(); } void TimeoutHandler(IAsyncResult ar) { Trace.Warn("TimeoutHandler"); } </script> <asp:gridview id="GridView1" runat="server" /> ``` And this would be the page in which I host the control three times: ``` <%@ page language="C#" trace="true" async="true" asynctimeout="60" %> <%@ register tagprefix="uc" tagname="mycontrol" src="~/MyControl.ascx" %> <html> <body> <form id="form1" runat="server"> <uc:mycontrol id="MyControl1" runat="server" /> <uc:mycontrol id="MyControl2" runat="server" /> <uc:mycontrol id="MyControl3" runat="server" /> </form> </body> </html> ``` The page gets displayed without errors, but the trace at the bottom of the page shows each control instance is processed synchronously. What am I doing wrong? Is there a configuration setting somewhere I'm missing?
Looks like I can answer my own question. The user control should not be calling `Page.ExecuteRegisteredAsyncTasks`. By doing that, the control was adding the async task, running it, and waiting for it to complete. Instead, each instance of the user control should call only `Page.RegisterAsyncTask`. After each control instance has done this the page automatically calls `RegistereAsyncTask` running all three registered async tasks simultaniously. So here is the new user control: ``` <%@ Control Language="C#" %> <script runat="server"> SqlConnection m_oConnection; SqlCommand m_oCommand; void Page_Load(object sender, EventArgs e) { Trace.Warn(ID, "Page_Load - " + Thread.CurrentThread.GetHashCode().ToString()); string strDSN = ConfigurationManager.ConnectionStrings["DSN"].ConnectionString + ";async=true"; string strSQL = "waitfor delay '00:00:10'; select * from TEProcessedPerDay where Date > dateadd(day, -90, getutcdate()) order by Date asc"; m_oConnection = new SqlConnection(strDSN); m_oCommand = new SqlCommand(strSQL, m_oConnection); m_oConnection.Open(); Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler), new EndEventHandler(TimeoutHandler), null, true)); } IAsyncResult BeginHandler(object src, EventArgs e, AsyncCallback cb, object state) { Trace.Warn(ID, "BeginHandler - " + Thread.CurrentThread.GetHashCode().ToString()); return m_oCommand.BeginExecuteReader(cb, state); } void EndHandler(IAsyncResult ar) { Trace.Warn(ID, "EndHandler - " + Thread.CurrentThread.GetHashCode().ToString()); GridView1.DataSource = m_oCommand.EndExecuteReader(ar); GridView1.DataBind(); m_oConnection.Close(); } void TimeoutHandler(IAsyncResult ar) { Trace.Warn(ID, "TimeoutHandler - " + Thread.CurrentThread.GetHashCode().ToString()); } </script> <asp:gridview id="GridView1" runat="server" /> ``` And the unchanged page that creates three instances of the control: ``` <%@ page language="C#" async="true" trace="true" %> <%@ register tagprefix="uc" tagname="mycontrol" src="~/MyControl.ascx" %> <html> <body> <form id="form1" runat="server"> <uc:mycontrol id="MyControl1" runat="server" /> <uc:mycontrol id="MyControl2" runat="server" /> <uc:mycontrol id="MyControl3" runat="server" /> </form> </body> </html> ```
273,567
<p>Every Christmas we draw names for gift exchanges in my family. This usually involves mulitple redraws until no one has pulled their spouse. So this year I coded up my own name drawing app that takes in a bunch of names, a bunch of disallowed pairings, and sends off an email to everyone with their chosen giftee.</p> <p>Right now, the algorithm works like this (in pseudocode):</p> <pre><code>function DrawNames(list allPeople, map disallowedPairs) returns map // Make a list of potential candidates foreach person in allPeople person.potentialGiftees = People person.potentialGiftees.Remove(person) foreach pair in disallowedPairs if pair.first = person person.Remove(pair.second) // Loop through everyone and draw names while allPeople.count &gt; 0 currentPerson = allPeople.findPersonWithLeastPotentialGiftees giftee = pickRandomPersonFrom(currentPerson.potentialGiftees) matches[currentPerson] = giftee allPeople.Remove(currentPerson) foreach person in allPeople person.RemoveIfExists(giftee) return matches </code></pre> <p>Does anyone who knows more about graph theory know some kind of algorithm that would work better here? For my purposes, this works, but I'm curious.</p> <p>EDIT: Since the emails went out a while ago, and I'm just hoping to learn something I'll rephrase this as a graph theory question. I'm not so interested in the special cases where the exclusions are all pairs (as in spouses not getting each other). I'm more interested in the cases where there are enough exclusions that finding any solution becomes the hard part. My algorithm above is just a simple greedy algorithm that I'm not sure would succeed in all cases.</p> <p>Starting with a complete directed graph and a list of vertex pairs. For each vertex pair, remove the edge from the first vertex to the second.</p> <p>The goal is to get a graph where each vertex has one edge coming in, and one edge leaving.</p>
[ { "answer_id": 273572, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>I wouldn't use disallowed pairings, since that greatly increases the complexity of the problem. Just enter everyone's name and address into a list. Create a copy of the list and keep shuffling it until the addresses in each position of the two lists don't match. This will ensure that no one gets themselves, or their spouse.</p>\n\n<p>As a bonus, if you want to do this secret-ballot-style, print envelopes from the first list and names from the second list. Don't peek while stuffing the envelopes. (Or you could just automate emailing everyone thier pick.)</p>\n\n<p>There are even more solutions to this problem on <a href=\"https://stackoverflow.com/questions/268682/what-is-the-best-low-tech-protocol-to-simulate-drawing-names-out-of-a-hat-and-e\">this thread</a>.</p>\n" }, { "answer_id": 273583, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 3, "selected": false, "text": "<p>Hmmm. I took a course in graph theory, but simpler is to just randomly permute your list, pair each consecutive group, then swap any element that is disallowed with another. Since there's no disallowed person in any given pair, the swap will always succeed if you don't allow swaps with the group selected. Your algorithm is too complex.</p>\n" }, { "answer_id": 273815, "author": "Watson Ladd", "author_id": 29025, "author_profile": "https://Stackoverflow.com/users/29025", "pm_score": 5, "selected": true, "text": "<p>Just make a graph with edges connecting two people if they are allowed to share gifts and then use a perfect matching algorithm. (Look for \"Paths, Trees, and Flowers\" for the (clever) algorithm)</p>\n" }, { "answer_id": 303476, "author": "wxs", "author_id": 12981, "author_profile": "https://Stackoverflow.com/users/12981", "pm_score": 3, "selected": false, "text": "<p>I was just doing this myself, in the end the algorithm I used doesn't exactly model drawing names out of a hat, but it's pretty damn close. Basically shuffle the list, and then pair each person with the next person in the list. The only difference with drawing names out of a hat is that you get one cycle instead of potentially getting mini subgroups of people who only exchange gifts with each other. If anything that might be a feature.</p>\n\n<p>Implementation in Python:</p>\n\n<pre><code>import random\nfrom collections import deque\ndef pairup(people):\n \"\"\" Given a list of people, assign each one a secret santa partner\n from the list and return the pairings as a dict. Implemented to always\n create a perfect cycle\"\"\"\n random.shuffle(people)\n partners = deque(people)\n partners.rotate()\n return dict(zip(people,partners))\n</code></pre>\n" }, { "answer_id": 326055, "author": "dancarlson", "author_id": 41626, "author_profile": "https://Stackoverflow.com/users/41626", "pm_score": 1, "selected": false, "text": "<p>I just created a web app that will do exactly this - <a href=\"http://www.secretsantaswap.com/\" rel=\"nofollow noreferrer\">http://www.secretsantaswap.com/</a></p>\n\n<p>My algorithm allows for subgroups. It's not pretty, but it works.</p>\n\n<p>Operates as follows:\n<br />1. assign a unique identifier to all participants, remember which subgroup they're in\n<br />2. duplicate and shuffle that list (the targets)\n<br />3. create an array of the number of participants in each subgroup\n<br />4. duplicate array from [3] for targets\n<br />5. create a new array to hold the final matches\n<br />6. iterate through participants assigning the first target that doesn't match any of the following criteria:\n<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A. participant == target\n<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;B. participant.Subgroup == target.Subgroup\n<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;C. choosing the target will cause a subgroup to fail in the future (e.g. subgroup 1 must always have at least as many non-subgroup 1 targets remaining as participants subgroup 1 participants remaining)\n<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;D. participant(n+1) == target (n +1)\n<br />If we assign the target we also decrement the arrays from 3 and 4</p>\n\n<p>So, not pretty (at all) but it works. Hope it helps,</p>\n\n<p>Dan Carlson</p>\n" }, { "answer_id": 4149014, "author": "Eddie Rowe", "author_id": 503752, "author_profile": "https://Stackoverflow.com/users/503752", "pm_score": 2, "selected": false, "text": "<p>Create a graph where each edge is \"giftability\" Vertices that represent Spouses will NOT be adjacent. Select an edge at random (that is a gift assignment). Delete all edges coming from the gifter and all edges going to the receiver and repeat.</p>\n" }, { "answer_id": 8686772, "author": "dana", "author_id": 315689, "author_profile": "https://Stackoverflow.com/users/315689", "pm_score": 2, "selected": false, "text": "<p>There is a concept in graph theory called a <a href=\"http://en.wikipedia.org/wiki/Hamiltonian_path\" rel=\"nofollow\">Hamiltonian Circuit</a> that describes the \"goal\" you describe. One tip for anybody who finds this is to tell users which \"seed\" was used to generate the graph. This way if you have to re-generate the graph you can. The \"seed\" is also useful if you have to add or remove a person. In that case simply choose a new \"seed\" and generate a new graph, making sure to tell participants which \"seed\" is the current/latest one.</p>\n" }, { "answer_id": 12839952, "author": "suizo", "author_id": 836948, "author_profile": "https://Stackoverflow.com/users/836948", "pm_score": 1, "selected": false, "text": "<p>Here a simple implementation in java for the secret santa problem.</p>\n\n<pre><code>public static void main(String[] args) {\n ArrayList&lt;String&gt; donor = new ArrayList&lt;String&gt;();\n donor.add(\"Micha\");\n donor.add(\"Christoph\");\n donor.add(\"Benj\");\n donor.add(\"Andi\");\n donor.add(\"Test\");\n ArrayList&lt;String&gt; receiver = (ArrayList&lt;String&gt;) donor.clone();\n\n Collections.shuffle(donor);\n for (int i = 0; i &lt; donor.size(); i++) {\n Collections.shuffle(receiver);\n int target = 0;\n if(receiver.get(target).equals(donor.get(i))){ \n target++;\n } \n System.out.println(donor.get(i) + \" =&gt; \" + receiver.get(target));\n receiver.remove(receiver.get(target));\n }\n}\n</code></pre>\n" }, { "answer_id": 47478187, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Python solution here.</p>\n\n<p>Given a sequence of <code>(person, tags)</code>, where tags is itself a (possibly empty) sequence of strings, my algorithm suggests a chain of persons where each person gives a present to the next in the chain (the last person obviously is paired with the first one).</p>\n\n<p>The tags exist so that the persons can be grouped and every time the next person is chosen from the group most dis-joined to the last person chosen. The initial person is chosen by an empty set of tags, so it will be picked from the longest group.</p>\n\n<p>So, given an input sequence of:</p>\n\n<pre><code>example_sequence= [\n (\"person1\", (\"male\", \"company1\")),\n (\"person2\", (\"female\", \"company2\")),\n (\"person3\", (\"male\", \"company1\")),\n (\"husband1\", (\"male\", \"company2\", \"marriage1\")),\n (\"wife1\", (\"female\", \"company1\", \"marriage1\")),\n (\"husband2\", (\"male\", \"company3\", \"marriage2\")),\n (\"wife2\", (\"female\", \"company2\", \"marriage2\")),\n]\n</code></pre>\n\n<p>a suggestion is:</p>\n\n<p>['person1 [male,company1]',\n 'person2 [female,company2]',\n 'person3 [male,company1]',\n 'wife2 [female,marriage2,company2]',\n 'husband1 [male,marriage1,company2]',\n 'husband2 [male,marriage2,company3]',\n 'wife1 [female,marriage1,company1]']</p>\n\n<p>Of course, if all persons have no tags (e.g. an empty tuple) then there is only one group to choose from.</p>\n\n<p>There isn't always an optimal solution (think an input sequence of 10 women and 2 men, their genre being the only tag given), but it does a good work as much as it can.</p>\n\n<p>Py2/3 compatible.</p>\n\n<pre><code>import random, collections\n\nclass Statistics(object):\n def __init__(self):\n self.tags = collections.defaultdict(int)\n\n def account(self, tags):\n for tag in tags:\n self.tags[tag] += 1\n\n def tags_value(self, tags):\n return sum(1./self.tags[tag] for tag in tags)\n\n def most_disjoined(self, tags, groups):\n return max(\n groups.items(),\n key=lambda kv: (\n -self.tags_value(kv[0] &amp; tags),\n len(kv[1]),\n self.tags_value(tags - kv[0]) - self.tags_value(kv[0] - tags),\n )\n )\n\ndef secret_santa(people_and_their_tags):\n \"\"\"Secret santa algorithm.\n\n The lottery function expects a sequence of:\n (name, tags)\n\n For example:\n\n [\n (\"person1\", (\"male\", \"company1\")),\n (\"person2\", (\"female\", \"company2\")),\n (\"person3\", (\"male\", \"company1\")),\n (\"husband1\", (\"male\", \"company2\", \"marriage1\")),\n (\"wife1\", (\"female\", \"company1\", \"marriage1\")),\n (\"husband2\", (\"male\", \"company3\", \"marriage2\")),\n (\"wife2\", (\"female\", \"company2\", \"marriage2\")),\n ]\n\n husband1 is married to wife1 as seen by the common marriage1 tag\n person1, person3 and wife1 work at the same company.\n …\n\n The algorithm will try to match people with the least common characteristics\n between them, to maximize entrop— ehm, mingling!\n\n Have fun.\"\"\"\n\n # let's split the persons into groups\n\n groups = collections.defaultdict(list)\n stats = Statistics()\n\n for person, tags in people_and_their_tags:\n tags = frozenset(tag.lower() for tag in tags)\n stats.account(tags)\n person= \"%s [%s]\" % (person, \",\".join(tags))\n groups[tags].append(person)\n\n # shuffle all lists\n for group in groups.values():\n random.shuffle(group)\n\n output_chain = []\n prev_tags = frozenset()\n while 1:\n next_tags, next_group = stats.most_disjoined(prev_tags, groups)\n output_chain.append(next_group.pop())\n if not next_group: # it just got empty\n del groups[next_tags]\n if not groups: break\n prev_tags = next_tags\n\n return output_chain\n\nif __name__ == \"__main__\":\n example_sequence = [\n (\"person1\", (\"male\", \"company1\")),\n (\"person2\", (\"female\", \"company2\")),\n (\"person3\", (\"male\", \"company1\")),\n (\"husband1\", (\"male\", \"company2\", \"marriage1\")),\n (\"wife1\", (\"female\", \"company1\", \"marriage1\")),\n (\"husband2\", (\"male\", \"company3\", \"marriage2\")),\n (\"wife2\", (\"female\", \"company2\", \"marriage2\")),\n ]\n print(\"suggested chain (each person gives present to next person)\")\n import pprint\n pprint.pprint(secret_santa(example_sequence))\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8701/" ]
Every Christmas we draw names for gift exchanges in my family. This usually involves mulitple redraws until no one has pulled their spouse. So this year I coded up my own name drawing app that takes in a bunch of names, a bunch of disallowed pairings, and sends off an email to everyone with their chosen giftee. Right now, the algorithm works like this (in pseudocode): ``` function DrawNames(list allPeople, map disallowedPairs) returns map // Make a list of potential candidates foreach person in allPeople person.potentialGiftees = People person.potentialGiftees.Remove(person) foreach pair in disallowedPairs if pair.first = person person.Remove(pair.second) // Loop through everyone and draw names while allPeople.count > 0 currentPerson = allPeople.findPersonWithLeastPotentialGiftees giftee = pickRandomPersonFrom(currentPerson.potentialGiftees) matches[currentPerson] = giftee allPeople.Remove(currentPerson) foreach person in allPeople person.RemoveIfExists(giftee) return matches ``` Does anyone who knows more about graph theory know some kind of algorithm that would work better here? For my purposes, this works, but I'm curious. EDIT: Since the emails went out a while ago, and I'm just hoping to learn something I'll rephrase this as a graph theory question. I'm not so interested in the special cases where the exclusions are all pairs (as in spouses not getting each other). I'm more interested in the cases where there are enough exclusions that finding any solution becomes the hard part. My algorithm above is just a simple greedy algorithm that I'm not sure would succeed in all cases. Starting with a complete directed graph and a list of vertex pairs. For each vertex pair, remove the edge from the first vertex to the second. The goal is to get a graph where each vertex has one edge coming in, and one edge leaving.
Just make a graph with edges connecting two people if they are allowed to share gifts and then use a perfect matching algorithm. (Look for "Paths, Trees, and Flowers" for the (clever) algorithm)
273,578
<p><a href="https://web.archive.org/web/20210126032647/http://geekswithblogs.net/michelotti/archive/2007/12/17/117791.aspx" rel="nofollow noreferrer">Link</a></p> <p>I'm using ASP.NET with C# and trying to use linq to sql to update a data context as exhibited on the blog linked above. I created the timestamp field in the table just as stated and am using the following method:</p> <pre><code>private void updateRecord(TableName updatedRecord) { context db = new context(); db.TableName.Attach(updatedRecord,true); db.SubmitChanges(); } </code></pre> <p>My question is, are you supposed to assign the timeStamp field to anything in your updatedRecord before trying to call the Attach method on your data context?</p> <p>When I run this code I get the following exception: <code>System.Data.Linq.ChangeConflictException: Row not found or changed. </code> I update all of the fields, including the primary key of the record that I'm updating before passing the object to this update method. During debugging the TimeStamp attribute of the object shows as null. I'm not sure if it's supposed to be that way or not.</p> <p>Every book and resource I have says that this is the way to do it, but none of them go into great detail about this TimeStamp attribute.</p> <p>I know this is quick and easy, so if anybody knows, please let me know.</p>
[ { "answer_id": 273590, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "<p>If you have a timestamp column, then to update a record (from a vanilla object): yes, I would expect to have to assign it. Otherwise, you lose the ability to use the timestamp for optimistic concurrency checking.</p>\n\n<p>The idea is you take a copy of the timestamp when you get hold of your (disconnected) object, then when you update you can use this column to verify that nobody else has edited the row.</p>\n\n<p>There are two common scenarios:</p>\n\n<p>1: if you are only performing a short lived operation, get the record out of the database first - make your changes to the object, and simply SumbitChanges() [all with the same data-context]. The data-context will handle concurrency for you.</p>\n\n<p>2: if you are disconnecting the object (for example passing it to a client application for a while), then use something like serialization (LINQ-to-SQL objects support DataContractSerializer (optionally; you need to enable it)). So serialize the object at the server, pass it to the client - the client makes changes to their copy and passes it back. The server deserializes it and uses Attach() and SubmitChanges(). The record in memory should still have the timestamp that it had when extracted from the database, so we can perform optimistic concurrency spanning all the time the record has been disconnected.</p>\n" }, { "answer_id": 273740, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>Since you say that you created the time stamp field in the table, I wonder if, in the case where this column was added later, the column properties may not be set correctly.\nYou may want to check the properties on your TimeStamp column in the DBML designer. Make sure that:</p>\n\n<pre><code>AutoGenerated = true\nAuto-Sync = Always\nTime Stamp = True\nUpdate Check = Never\n</code></pre>\n\n<p>The server data type should be <code>rowversion NOT NULL</code></p>\n\n<p>If it is not set to be auto generated and synced always, the row version won't be returned from the insert since you haven't changed it when the insert was done. Even though this value is generated by the database the DataContext needs to know this so that it can handle it properly.</p>\n\n<p>In addition, now that you have a timestamp column, <code>UpdateCheck</code> should be set to <code>Never</code> for all of the other columns.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35617/" ]
[Link](https://web.archive.org/web/20210126032647/http://geekswithblogs.net/michelotti/archive/2007/12/17/117791.aspx) I'm using ASP.NET with C# and trying to use linq to sql to update a data context as exhibited on the blog linked above. I created the timestamp field in the table just as stated and am using the following method: ``` private void updateRecord(TableName updatedRecord) { context db = new context(); db.TableName.Attach(updatedRecord,true); db.SubmitChanges(); } ``` My question is, are you supposed to assign the timeStamp field to anything in your updatedRecord before trying to call the Attach method on your data context? When I run this code I get the following exception: `System.Data.Linq.ChangeConflictException: Row not found or changed.` I update all of the fields, including the primary key of the record that I'm updating before passing the object to this update method. During debugging the TimeStamp attribute of the object shows as null. I'm not sure if it's supposed to be that way or not. Every book and resource I have says that this is the way to do it, but none of them go into great detail about this TimeStamp attribute. I know this is quick and easy, so if anybody knows, please let me know.
If you have a timestamp column, then to update a record (from a vanilla object): yes, I would expect to have to assign it. Otherwise, you lose the ability to use the timestamp for optimistic concurrency checking. The idea is you take a copy of the timestamp when you get hold of your (disconnected) object, then when you update you can use this column to verify that nobody else has edited the row. There are two common scenarios: 1: if you are only performing a short lived operation, get the record out of the database first - make your changes to the object, and simply SumbitChanges() [all with the same data-context]. The data-context will handle concurrency for you. 2: if you are disconnecting the object (for example passing it to a client application for a while), then use something like serialization (LINQ-to-SQL objects support DataContractSerializer (optionally; you need to enable it)). So serialize the object at the server, pass it to the client - the client makes changes to their copy and passes it back. The server deserializes it and uses Attach() and SubmitChanges(). The record in memory should still have the timestamp that it had when extracted from the database, so we can perform optimistic concurrency spanning all the time the record has been disconnected.
273,606
<p>I am designing a WCF service which a client will call to get a list of GUID's from a server.</p> <p>How should I define my endpoint contract?</p> <p>Should I just return an Array? </p> <p>If so, will the array just be serialized by WCF?</p>
[ { "answer_id": 273616, "author": "Adron", "author_id": 29345, "author_profile": "https://Stackoverflow.com/users/29345", "pm_score": 2, "selected": false, "text": "<p>The Guids, if you're going for SOA oriented services, will need to be set as strings. The client will be responsible for turning them back into whatever. As for the listing of the Guids, they'd be returned as an array. If you have a contract with a regular Generics List Object of Guids like this</p>\n\n<pre><code>[DataMember] List&lt;Guid&gt; SomeGuidsGoInHere {get;set;}\n</code></pre>\n\n<p>then you'll get an array of Guids back. Which could cause compatability issues. What you'll want to do is setup a List of strings like this.</p>\n\n<pre><code>[DataMember] List&lt;String&gt; SomeGuidsAsStringsGoInHere {get;set;}\n</code></pre>\n" }, { "answer_id": 274320, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>If the client app has enough stuff to call web services, why not create the UUIDs locally using a built-in API?</p>\n" }, { "answer_id": 1354324, "author": "Blue Toque", "author_id": 116268, "author_profile": "https://Stackoverflow.com/users/116268", "pm_score": 0, "selected": false, "text": "<p>When developing in Visual Studio, Microsoft provides some specialized magic when generating the WSDL for a method that takes a Guid as a parameter or returns a Guid; it imposes a restriction on the Guid.</p>\n\n<p>You can just return a Guid to your heart's content, both in WCF and in regular web services.</p>\n\n<p>Guid Simple Type is below:</p>\n\n<pre><code>&lt;s:simpleType name=\"guid\"&gt;\n &lt;s:restriction base=\"s:string\"&gt;\n &lt;s:pattern value=\"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\" /&gt;\n &lt;/s:restriction&gt;\n&lt;/s:simpleType&gt;\n</code></pre>\n\n<p>And generated WSDL for a method that takes a Guid as a parameter:</p>\n\n<pre><code>&lt;s:element name=\"GetToken\"&gt;\n &lt;s:complexType&gt;\n &lt;s:sequence&gt;\n &lt;s:element minOccurs=\"1\" maxOccurs=\"1\" name=\"objUserGUID\" type=\"s1:guid\" /&gt;\n &lt;s:element minOccurs=\"0\" maxOccurs=\"1\" name=\"strPassword\" type=\"s:string\" /&gt;\n &lt;/s:sequence&gt;\n &lt;/s:complexType&gt;\n&lt;/s:element&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am designing a WCF service which a client will call to get a list of GUID's from a server. How should I define my endpoint contract? Should I just return an Array? If so, will the array just be serialized by WCF?
The Guids, if you're going for SOA oriented services, will need to be set as strings. The client will be responsible for turning them back into whatever. As for the listing of the Guids, they'd be returned as an array. If you have a contract with a regular Generics List Object of Guids like this ``` [DataMember] List<Guid> SomeGuidsGoInHere {get;set;} ``` then you'll get an array of Guids back. Which could cause compatability issues. What you'll want to do is setup a List of strings like this. ``` [DataMember] List<String> SomeGuidsAsStringsGoInHere {get;set;} ```
273,612
<p>It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;</p> <p>"loop again? y/n"</p>
[ { "answer_id": 273618, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 5, "selected": true, "text": "<pre><code>while True:\n func()\n answer = raw_input( \"Loop again? \" )\n if answer != 'y':\n break\n</code></pre>\n" }, { "answer_id": 273620, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": 3, "selected": false, "text": "<pre><code>keepLooping = True\nwhile keepLooping:\n # do stuff here\n\n # Prompt the user to continue\n q = raw_input(\"Keep looping? [yn]: \")\n if not q.startswith(\"y\"):\n keepLooping = False\n</code></pre>\n" }, { "answer_id": 273677, "author": "Jason L", "author_id": 35616, "author_profile": "https://Stackoverflow.com/users/35616", "pm_score": 3, "selected": false, "text": "<p>There are two usual approaches, both already mentioned, which amount to:</p>\n\n<pre><code>while True:\n do_stuff() # and eventually...\n break; # break out of the loop\n</code></pre>\n\n<p>or</p>\n\n<pre><code>x = True\nwhile x:\n do_stuff() # and eventually...\n x = False # set x to False to break the loop\n</code></pre>\n\n<p>Both will work properly. From a \"sound design\" perspective it's best to use the second method because 1) <code>break</code> can have counterintuitive behavior in nested scopes in some languages; 2) the first approach is counter to the intended use of \"while\"; 3) your routines should always have a single point of exit</p>\n" }, { "answer_id": 321040, "author": "J.T. Hurley", "author_id": 39851, "author_profile": "https://Stackoverflow.com/users/39851", "pm_score": 1, "selected": false, "text": "<pre><code>While raw_input(\"loop again? y/n \") != 'n':\n do_stuff()\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33061/" ]
It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like; "loop again? y/n"
``` while True: func() answer = raw_input( "Loop again? " ) if answer != 'y': break ```
273,623
<p>I have a list of numbers, say {2,4,5,6,7} I have a table, foos, with foos.ID, including say, {1,2,3,4,8,9}</p> <p>Id like to take my list of numbers, and find those without a counterpart in the ID field of my table.</p> <p>One way to achieve this would be to create a table bars, loaded with {2,4,5,6,7} in the ID field. Then, I would do </p> <pre> SELECT bars.* FROM bars LEFT JOIN foos ON bars.ID = foos.ID WHERE foos.ID IS NULL </pre> <p>However, I'd like to accomplish this sans temp table. </p> <p>Anyone have any input on how it might happen?</p>
[ { "answer_id": 273649, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 4, "selected": false, "text": "<p>I can't find a solution to your precise problem that doesn't use a temporary table, but an alternate way of doing your query using a sub-select instead of a join is:</p>\n\n<pre><code>SELECT bars.* FROM bars WHERE bars.ID NOT IN (SELECT ID FROM foos)\n</code></pre>\n\n<p>Like the other posters I originally wrote:</p>\n\n<pre><code>SELECT * FROM foos WHERE foos.ID NOT IN (2, 4, 5, 6, 7)\n</code></pre>\n\n<p>but then I realised that this is producing the opposite to what you want.</p>\n" }, { "answer_id": 273699, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>Alnitak's (and yours) solution should work, and I can not thing about anything else which can work only in SQL language.</p>\n\n<p>But here comes the question - how do you pass the list of values? Isn't it better to handle this in the calling code - i.e. request the ID's and compare it in the colling code, which may be in a language better suited for this kind of manipulations.</p>\n" }, { "answer_id": 273703, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": false, "text": "<p>This is a problem that is pretty common: generating a relation on the fly without creating a table. SQL solutions for this problem are pretty awkward. One example using a derived table:</p>\n\n<pre><code>SELECT n.id\nFROM\n (SELECT 2 AS id \n UNION SELECT 3 \n UNION SELECT 4 \n UNION SELECT 5 \n UNION SELECT 6 \n UNION SELECT 7) AS n\n LEFT OUTER JOIN foos USING (id)\nWHERE foos.id IS NULL;\n</code></pre>\n\n<p>But this doesn't scale very well, because you might have many values instead of just six. It can become tiresome to construct a long list with one <code>UNION</code> needed per value.</p>\n\n<p>Another solution is to keep a general-purpose table of ten digits on hand, and use it repeatedly for multiple purposes.</p>\n\n<pre><code>CREATE TABLE num (i int);\nINSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);\n\nSELECT n.id\nFROM \n (SELECT n1.i + n10.i*10 AS id\n FROM num AS n1 CROSS JOIN num AS n10\n WHERE n1.i + n10.i*10 IN (2, 3, 4, 5, 6, 7)) AS n\n LEFT OUTER JOIN foos USING (id)\nWHERE foos.id IS NULL;\n</code></pre>\n\n<p>I show the inner query generating values from 0..99 even though this isn't necessary for this case. But you might have values greater than 10 in your list. The point is that with one table <code>num</code>, you can generate large numbers without having to resort to very long chains with one <code>UNION</code> per value. Also, you can specify the list of desired values in one place, which is more convenient and readable.</p>\n" }, { "answer_id": 2683561, "author": "Daniel", "author_id": 322357, "author_profile": "https://Stackoverflow.com/users/322357", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem. I had a range where the auto-incrementing primary key had some missing values, so first I found how many there were:\n<code>select count(*) from node where nid &gt; 1962</code>.\nComparing this number against the highest value, I got the number missing. Then I ran this query:\n<code>select n2.nid from node n1 right join node n2 on n1.nid = (n2.nid - 1) where n1.nid is null and n2.nid &gt; 1962</code>\nThis will find the number of non-consecutive missing records. It won't show consecutive ones, and I'm not entirely certain how to do that, beyond changing the ON clause to allow greater latitude (which would make the JOIN table substantially larger).\nIn any case, this gave me five results out of the total seven missing, and the other two were guaranteed to be next to at least one of the five. If you have a larger number missing, you'll probably need some other way of finding the remaining missing.</p>\n" }, { "answer_id": 5891079, "author": "Alex Matulich", "author_id": 582329, "author_profile": "https://Stackoverflow.com/users/582329", "pm_score": 3, "selected": false, "text": "<p>If you use PHP, you can make this work without creating any temporary tables.</p>\n\n<pre><code>SELECT ID FROM foos WHERE foos.ID IN (2, 4, 5, 6, 7)\n</code></pre>\n\n<p>You can use PHP's array_diff() function to convert this to the desired result. If your list (2,4,5,6,7) is in an array called $list and the result of the query above is in an array $result, then</p>\n\n<pre><code>$no_counterparts = array_diff($list, $result);\n</code></pre>\n\n<p>...will return all the numbers in your list with no counterpart in your database table. While this solution doesn't perform the entire operation within the query, the post-processing you need to do in PHP is minimal to get what you want, and it may be worthwhile to avoid having to create a temporary table.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26001/" ]
I have a list of numbers, say {2,4,5,6,7} I have a table, foos, with foos.ID, including say, {1,2,3,4,8,9} Id like to take my list of numbers, and find those without a counterpart in the ID field of my table. One way to achieve this would be to create a table bars, loaded with {2,4,5,6,7} in the ID field. Then, I would do ``` SELECT bars.* FROM bars LEFT JOIN foos ON bars.ID = foos.ID WHERE foos.ID IS NULL ``` However, I'd like to accomplish this sans temp table. Anyone have any input on how it might happen?
This is a problem that is pretty common: generating a relation on the fly without creating a table. SQL solutions for this problem are pretty awkward. One example using a derived table: ``` SELECT n.id FROM (SELECT 2 AS id UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7) AS n LEFT OUTER JOIN foos USING (id) WHERE foos.id IS NULL; ``` But this doesn't scale very well, because you might have many values instead of just six. It can become tiresome to construct a long list with one `UNION` needed per value. Another solution is to keep a general-purpose table of ten digits on hand, and use it repeatedly for multiple purposes. ``` CREATE TABLE num (i int); INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9); SELECT n.id FROM (SELECT n1.i + n10.i*10 AS id FROM num AS n1 CROSS JOIN num AS n10 WHERE n1.i + n10.i*10 IN (2, 3, 4, 5, 6, 7)) AS n LEFT OUTER JOIN foos USING (id) WHERE foos.id IS NULL; ``` I show the inner query generating values from 0..99 even though this isn't necessary for this case. But you might have values greater than 10 in your list. The point is that with one table `num`, you can generate large numbers without having to resort to very long chains with one `UNION` per value. Also, you can specify the list of desired values in one place, which is more convenient and readable.
273,624
<p>How do you create a 1 bit per pixel mask from an image using GDI in C#? The image I am trying to create the mask from is held in a System.Drawing.Graphics object.</p> <p>I have seen examples that use Get/SetPixel in a loop, which are too slow. The method that interests me is one that uses only BitBlits, like <a href="http://www.vbaccelerator.com/home/VB/Tips/Mask_Images/article.asp" rel="nofollow noreferrer">this</a>. I just can't get it to work in C#, any help is much appreciated.</p>
[ { "answer_id": 273686, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>using System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Runtime.InteropServices;\n</code></pre>\n\n<p>...</p>\n\n<pre><code> public static Bitmap BitmapTo1Bpp(Bitmap img) {\n int w = img.Width;\n int h = img.Height;\n Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);\n BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);\n for (int y = 0; y &lt; h; y++) {\n byte[] scan = new byte[(w + 7) / 8];\n for (int x = 0; x &lt; w; x++) {\n Color c = img.GetPixel(x, y);\n if (c.GetBrightness() &gt;= 0.5) scan[x / 8] |= (byte)(0x80 &gt;&gt; (x % 8));\n }\n Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);\n }\n bmp.UnlockBits(data);\n return bmp;\n }\n</code></pre>\n\n<p>GetPixel() is slow, you can speed it up with an unsafe byte*.</p>\n" }, { "answer_id": 275934, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Do you mean LockBits? Bob Powell has an overview of LockBits <a href=\"https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx\" rel=\"nofollow noreferrer\">here</a>; this should provide access to the RGB values, to do what you need. You might also want to look at ColorMatrix, <a href=\"http://www.java2s.com/Code/CSharp/2D-Graphics/UseColorMatrixtograytheimage.htm\" rel=\"nofollow noreferrer\">like so</a>.</p>\n" }, { "answer_id": 647724, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 2, "selected": false, "text": "<p>In the Win32 C API the process to create a mono mask is simple.</p>\n\n<ul>\n<li>Create an uninitialzied 1bpp bitmap as big as the source bitmap.</li>\n<li>Select it into a DC.</li>\n<li>Select the source bitmap into a DC.</li>\n<li>SetBkColor on the destination DC to match the mask color of the source bitmap.</li>\n<li>BitBlt the source onto the destination using SRC_COPY.</li>\n</ul>\n\n<p>For bonus points its then usually desirable to blit the mask back onto the source bitmap (using SRC_AND) to zero out the mask color there.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24201/" ]
How do you create a 1 bit per pixel mask from an image using GDI in C#? The image I am trying to create the mask from is held in a System.Drawing.Graphics object. I have seen examples that use Get/SetPixel in a loop, which are too slow. The method that interests me is one that uses only BitBlits, like [this](http://www.vbaccelerator.com/home/VB/Tips/Mask_Images/article.asp). I just can't get it to work in C#, any help is much appreciated.
Try this: ``` using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; ``` ... ``` public static Bitmap BitmapTo1Bpp(Bitmap img) { int w = img.Width; int h = img.Height; Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed); BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed); for (int y = 0; y < h; y++) { byte[] scan = new byte[(w + 7) / 8]; for (int x = 0; x < w; x++) { Color c = img.GetPixel(x, y); if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8)); } Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length); } bmp.UnlockBits(data); return bmp; } ``` GetPixel() is slow, you can speed it up with an unsafe byte\*.
273,630
<p>Actually my question is all in the title.<br> Anyway:<br> I have a class and I use explicit constructor: <br>.h<br></p> <pre><code>class MyClass { public: explicit MyClass(const string&amp; s): query(s) {} private: string query; } </code></pre> <p>Is it obligatory or not to put <b>explicit</b> keyword in implementation(.cpp) file?</p>
[ { "answer_id": 273633, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<p>No, it is not. The <code>explicit</code> keyword is only permitted in the header. My gcc says:</p>\n\n<pre><code>test.cpp:6: error: only declarations of constructors can be 'explicit'\n</code></pre>\n\n<p>for the following code:</p>\n\n<pre><code>class foo {\npublic:\n explicit foo(int);\n};\n\nexplicit foo::foo(int) {}\n</code></pre>\n" }, { "answer_id": 274117, "author": "Joe Ganley", "author_id": 35678, "author_profile": "https://Stackoverflow.com/users/35678", "pm_score": 0, "selected": false, "text": "<p>Re the followup question (which you really should have submitted as a separate question), the initialization list goes with the constructor's implementation (its function body), which might be in either the header or the cpp file.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28298/" ]
Actually my question is all in the title. Anyway: I have a class and I use explicit constructor: .h ``` class MyClass { public: explicit MyClass(const string& s): query(s) {} private: string query; } ``` Is it obligatory or not to put **explicit** keyword in implementation(.cpp) file?
No, it is not. The `explicit` keyword is only permitted in the header. My gcc says: ``` test.cpp:6: error: only declarations of constructors can be 'explicit' ``` for the following code: ``` class foo { public: explicit foo(int); }; explicit foo::foo(int) {} ```
273,639
<p>I have a windows form application that uses a Shared class to house all of the common objects for the application. The settings class has a collection of objects that do things periodically, and then there's something of interest, they need to alert the main form and have it update.</p> <p>I'm currently doing this through Events on the objects, and when each object is created, I add an EventHandler to maps the event back to the form. However, I'm running into some trouble that suggests that these requests aren't always ending up on the main copy of my form. For example, my form has a notification tray icon, but when the form captures and event and attempts to display a bubble, no bubble appears. However, if I modify that code to make the icon visible (though it already is), and then display the bubble, a second icon appears and displays the bubble properly.</p> <p>Has anybody run into this before? Is there a way that I can force all of my events to be captured by the single instance of the form, or is there a completely different way to handle this? I can post code samples if necessary, but I'm thinking it's a common threading problem.</p> <p><strong>MORE INFORMATION:</strong> I'm currently using Me.InvokeRequired in the event handler on my form, and it always returns FALSE in this case. Also, the second tray icon created when I make it visible from this form doesn't have a context menu on it, whereas the "real" icon does - does that clue anybody in?</p> <p>I'm going to pull my hair out! This can't be that hard!</p> <p><strong>SOLUTION</strong>: Thanks to nobugz for the clue, and it lead me to the code I'm now using (which works beautifully, though I can't help thinking there's a better way to do this). I added a private boolean variable to the form called "IsPrimary", and added the following code to the form constructor:</p> <pre><code> Public Sub New() If My.Application.OpenForms(0).Equals(Me) Then Me.IsFirstForm = True End If End Sub </code></pre> <p>Once this variable is set and the constructor finishes, it heads right to the event handler, and I deal with it this way (CAVEAT: Since the form I'm looking for is the primary form for the application, My.Application.OpenForms(0) gets what I need. If I was looking for the first instance of a non-startup form, I'd have to iterate through until I found it):</p> <pre><code> Public Sub EventHandler() If Not IsFirstForm Then Dim f As Form1 = My.Application.OpenForms(0) f.EventHandler() Me.Close() ElseIf InvokeRequired Then Me.Invoke(New HandlerDelegate(AddressOf EventHandler)) Else ' Do your event handling code ' End If End Sub </code></pre> <p>First, it checks to see if it's running on the correct form - if it's not, then call the right form. Then it checks to see if the thread is correct, and calls the UI thread if it's not. Then it runs the event code. I don't like that it's potentially three calls, but I can't think of another way to do it. It seems to work well, though it's a little cumbersome. If anybody has a better way to do it, I'd love to hear it!</p> <p>Again, thanks for all the help - this was going to drive me nuts!</p>
[ { "answer_id": 273653, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 3, "selected": true, "text": "<p>I think it is a threading problem too. Are you using Control.Invoke() in your event handler? .NET usually catches violations when you debug the app but there are cases it can't. NotifyIcon is one of them, there is no window handle to check thread affinity.</p>\n\n<p>Edit after OP changed question:</p>\n\n<p>A classic VB.NET trap is to reference a Form instance by its type name. Like Form1.NotifyIcon1.Something. That doesn't work as expected when you use threading. It will create a <em>new</em> instance of the Form1 class, not use the existing instance. That instance isn't visible (Show() was never called) and is otherwise dead as a doornail since it is running on thread that doesn't pump a message loop. Seeing a second icon appear is a dead give-away. So is getting InvokeRequired = False when you know you are using it from a thread.</p>\n\n<p>You must use a reference to the existing form instance. If that is hard to come by (you usually pass \"Me\" as an argument to the class constructor), you can use Application.OpenForms:</p>\n\n<pre><code> Dim main As Form1 = CType(Application.OpenForms(0), Form1)\n if (main.InvokeRequired)\n ' etc...\n</code></pre>\n" }, { "answer_id": 273654, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 0, "selected": false, "text": "<p>Use Control.InvokeRequired to determine if you're on the proper thread, then use Control.Invoke if you're not.</p>\n" }, { "answer_id": 273655, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 0, "selected": false, "text": "<p>You should look at the documentation for the Invoke method on the Form. It will allow you to make the code that updates the form run on the thread that owns the form, (which it must do, Windows forms are not thread safe).\nSomething like\nPrivate Delegate Sub UpdateStatusDelegate(ByVal newStatus as String)</p>\n\n<p>Public sub UpdateStatus(ByVal newStatus as String)\nIf Me.InvokeRequired Then\nDim d As New UpdateStatusDelegate(AddressOf UpdateStatus)\nMe.Invoke(d,new Object() {newStatus})\nElse\n'Update the form status\nEnd If</p>\n\n<p>If you provide some sample code I would be happy to provide a more tailored example.</p>\n\n<p>Edit after OP said they are using InvokeRequired.</p>\n\n<p>Before calling InvokeRequired, check that the form handle has been created, there is a HandleCreated property I belive. InvokeRequired always returns false if the control doesn't currently have a handle, this would then mean the code is not thread safe even though you have done the right thing to make it so. Update your question when you find out. Some sample code would be helpful too.</p>\n" }, { "answer_id": 335769, "author": "Brian Rudolph", "author_id": 33114, "author_profile": "https://Stackoverflow.com/users/33114", "pm_score": 0, "selected": false, "text": "<p>in c# it looks like this:</p>\n\n<pre><code>private EventHandler StatusHandler = new EventHandler(eventHandlerCode)\nvoid eventHandlerCode(object sender, EventArgs e)\n {\n if (this.InvokeRequired)\n {\n this.Invoke(StatusHandler, sender, e);\n }\n else\n {\n //do work\n }\n }\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8114/" ]
I have a windows form application that uses a Shared class to house all of the common objects for the application. The settings class has a collection of objects that do things periodically, and then there's something of interest, they need to alert the main form and have it update. I'm currently doing this through Events on the objects, and when each object is created, I add an EventHandler to maps the event back to the form. However, I'm running into some trouble that suggests that these requests aren't always ending up on the main copy of my form. For example, my form has a notification tray icon, but when the form captures and event and attempts to display a bubble, no bubble appears. However, if I modify that code to make the icon visible (though it already is), and then display the bubble, a second icon appears and displays the bubble properly. Has anybody run into this before? Is there a way that I can force all of my events to be captured by the single instance of the form, or is there a completely different way to handle this? I can post code samples if necessary, but I'm thinking it's a common threading problem. **MORE INFORMATION:** I'm currently using Me.InvokeRequired in the event handler on my form, and it always returns FALSE in this case. Also, the second tray icon created when I make it visible from this form doesn't have a context menu on it, whereas the "real" icon does - does that clue anybody in? I'm going to pull my hair out! This can't be that hard! **SOLUTION**: Thanks to nobugz for the clue, and it lead me to the code I'm now using (which works beautifully, though I can't help thinking there's a better way to do this). I added a private boolean variable to the form called "IsPrimary", and added the following code to the form constructor: ``` Public Sub New() If My.Application.OpenForms(0).Equals(Me) Then Me.IsFirstForm = True End If End Sub ``` Once this variable is set and the constructor finishes, it heads right to the event handler, and I deal with it this way (CAVEAT: Since the form I'm looking for is the primary form for the application, My.Application.OpenForms(0) gets what I need. If I was looking for the first instance of a non-startup form, I'd have to iterate through until I found it): ``` Public Sub EventHandler() If Not IsFirstForm Then Dim f As Form1 = My.Application.OpenForms(0) f.EventHandler() Me.Close() ElseIf InvokeRequired Then Me.Invoke(New HandlerDelegate(AddressOf EventHandler)) Else ' Do your event handling code ' End If End Sub ``` First, it checks to see if it's running on the correct form - if it's not, then call the right form. Then it checks to see if the thread is correct, and calls the UI thread if it's not. Then it runs the event code. I don't like that it's potentially three calls, but I can't think of another way to do it. It seems to work well, though it's a little cumbersome. If anybody has a better way to do it, I'd love to hear it! Again, thanks for all the help - this was going to drive me nuts!
I think it is a threading problem too. Are you using Control.Invoke() in your event handler? .NET usually catches violations when you debug the app but there are cases it can't. NotifyIcon is one of them, there is no window handle to check thread affinity. Edit after OP changed question: A classic VB.NET trap is to reference a Form instance by its type name. Like Form1.NotifyIcon1.Something. That doesn't work as expected when you use threading. It will create a *new* instance of the Form1 class, not use the existing instance. That instance isn't visible (Show() was never called) and is otherwise dead as a doornail since it is running on thread that doesn't pump a message loop. Seeing a second icon appear is a dead give-away. So is getting InvokeRequired = False when you know you are using it from a thread. You must use a reference to the existing form instance. If that is hard to come by (you usually pass "Me" as an argument to the class constructor), you can use Application.OpenForms: ``` Dim main As Form1 = CType(Application.OpenForms(0), Form1) if (main.InvokeRequired) ' etc... ```
273,641
<p>This question has been discussed in two blog posts (<a href="http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/" rel="nofollow noreferrer">http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/</a>, <a href="http://dow.ngra.de/2008/10/28/what-do-we-really-know-about-non-blocking-concurrency-in-java/" rel="nofollow noreferrer">http://dow.ngra.de/2008/10/28/what-do-we-really-know-about-non-blocking-concurrency-in-java/</a>), but I haven't heard a definitive answer yet. If we have one thread that does this:</p> <pre><code>public class HeartBeatThread extends Thread { public static int counter = 0; public static volatile int cacheFlush = 0; public HeartBeatThread() { setDaemon(true); } static { new HeartBeatThread().start(); } public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } counter++; cacheFlush++; } } } </code></pre> <p>And many clients that run the following:</p> <pre><code>if (counter == HeartBeatThread.counter) return; counter = HeartBeatThread.cacheFlush; </code></pre> <p>is it threadsafe or not?</p>
[ { "answer_id": 273690, "author": "jiriki", "author_id": 19907, "author_profile": "https://Stackoverflow.com/users/19907", "pm_score": 1, "selected": false, "text": "<p>Well, I don't think it is.</p>\n\n<p>The first if-statement: </p>\n\n<pre><code>if (counter == HeartBeatThread.counter) \n return;\n</code></pre>\n\n<p>Does not access any volatile field and is not synchronized. So you might read stale data forever and never get to the point of accessing the volatile field.</p>\n\n<p>Quoting from one of the comments in the second blog entry: \"anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.\"\nBut in your case B (the client) never reads f (=cacheFlush). So changes to HeartBeatThread.counter do not have to become visible to the client.</p>\n" }, { "answer_id": 273708, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 4, "selected": true, "text": "<p>Within the java memory model? No, you are not ok. </p>\n\n<p>I've seen a number of attempts to head towards a very 'soft flush' approach like this, but without an explicit fence, you're definitely playing with fire.</p>\n\n<p>The 'happens before' semantics in </p>\n\n<p><a href=\"http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7</a></p>\n\n<p>start to referring to purely inter-thread actions as 'actions' at the end of 17.4.2. This drives a lot of confusion since prior to that point they distinguish between inter- and intra- thread actions. Consequently, the intra-thread action of manipulating counter isn't explicitly synchronized across the volatile action by the happens-before relationship. You have two threads of reasoning to follow about synchronization, one governs local consistency and is subject to all the nice tricks of alias analysis, etc to shuffle operations The other is about global consistency and is only defined for inter-thread operations.</p>\n\n<p>One for the intra-thread logic that says within the thread the reads and writes are consistently reordered and one for the inter-thread logic that says things like volatile reads/writes and that synchronization starts/ends are appropriately fenced. </p>\n\n<p>The problem is the visibility of the non-volatile write is undefined as it is an intra-thread operation and therefore not covered by the specification. The processor its running on should be able to see it as it you executed those statements serially, but its sequentialization for inter-thread purposes is potentially undefined.</p>\n\n<p>Now, the reality of whether or not this can affect you is another matter entirely.</p>\n\n<p>While running java on x86 and x86-64 platforms? Technically you're in murky territory, but practically the very strong guarantees x86 places on reads and writes including the total order on the read/write across the access to cacheflush and the local ordering on the two writes and the two reads should enable this code to execute correctly provided it makes it through the compiler unmolested. That assumes the compiler doesn't step in and try to use the freedom it is permitted under the standard to reorder operations on you due to the provable lack of aliasing between the two intra-thread operations.</p>\n\n<p>If you move to a memory with weaker release semantics like an ia64? Then you're back on your own. </p>\n\n<p>A compiler could in perfectly good faith break this program in java on any platform, however. That it functions right now is an artifact of current implementations of the standard, not of the standard.</p>\n\n<p>As an aside, in the CLR, the runtime model is stronger, and this sort of trick is legal because the individual writes from each thread have ordered visibility, so be careful trying to translate any examples from there.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20022/" ]
This question has been discussed in two blog posts (<http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/>, <http://dow.ngra.de/2008/10/28/what-do-we-really-know-about-non-blocking-concurrency-in-java/>), but I haven't heard a definitive answer yet. If we have one thread that does this: ``` public class HeartBeatThread extends Thread { public static int counter = 0; public static volatile int cacheFlush = 0; public HeartBeatThread() { setDaemon(true); } static { new HeartBeatThread().start(); } public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } counter++; cacheFlush++; } } } ``` And many clients that run the following: ``` if (counter == HeartBeatThread.counter) return; counter = HeartBeatThread.cacheFlush; ``` is it threadsafe or not?
Within the java memory model? No, you are not ok. I've seen a number of attempts to head towards a very 'soft flush' approach like this, but without an explicit fence, you're definitely playing with fire. The 'happens before' semantics in <http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7> start to referring to purely inter-thread actions as 'actions' at the end of 17.4.2. This drives a lot of confusion since prior to that point they distinguish between inter- and intra- thread actions. Consequently, the intra-thread action of manipulating counter isn't explicitly synchronized across the volatile action by the happens-before relationship. You have two threads of reasoning to follow about synchronization, one governs local consistency and is subject to all the nice tricks of alias analysis, etc to shuffle operations The other is about global consistency and is only defined for inter-thread operations. One for the intra-thread logic that says within the thread the reads and writes are consistently reordered and one for the inter-thread logic that says things like volatile reads/writes and that synchronization starts/ends are appropriately fenced. The problem is the visibility of the non-volatile write is undefined as it is an intra-thread operation and therefore not covered by the specification. The processor its running on should be able to see it as it you executed those statements serially, but its sequentialization for inter-thread purposes is potentially undefined. Now, the reality of whether or not this can affect you is another matter entirely. While running java on x86 and x86-64 platforms? Technically you're in murky territory, but practically the very strong guarantees x86 places on reads and writes including the total order on the read/write across the access to cacheflush and the local ordering on the two writes and the two reads should enable this code to execute correctly provided it makes it through the compiler unmolested. That assumes the compiler doesn't step in and try to use the freedom it is permitted under the standard to reorder operations on you due to the provable lack of aliasing between the two intra-thread operations. If you move to a memory with weaker release semantics like an ia64? Then you're back on your own. A compiler could in perfectly good faith break this program in java on any platform, however. That it functions right now is an artifact of current implementations of the standard, not of the standard. As an aside, in the CLR, the runtime model is stronger, and this sort of trick is legal because the individual writes from each thread have ordered visibility, so be careful trying to translate any examples from there.
273,662
<p>With multiple developers working on the same Tomcat application, I'd like to tell the application to install to a different path, based on the current user and revision control client/view.</p> <p>So, if Bob is building, the app should be installed in Bob's test environment, maybe /bob1 or something like that. Bob might have several revision control clients/views/workspaces he works with so he could have /bob1, /bob2, /bob3, etc.</p> <p>The install location is specified in the build.properties file. Is there a way to avoid checking that file out and changing it for each specific user and revision control view?</p> <p>Can "ant install" take arguments or be configured to consider environment variables for the install target?</p>
[ { "answer_id": 275622, "author": "flicken", "author_id": 12880, "author_profile": "https://Stackoverflow.com/users/12880", "pm_score": 2, "selected": false, "text": "<p>You can override ant properties from the command line. </p>\n\n<pre><code>ant -Dinstall.location=/bob1 install\n</code></pre>\n\n<p>See <a href=\"http://ant.apache.org/manual/running.html\" rel=\"nofollow noreferrer\">Running Ant</a> for more information.</p>\n" }, { "answer_id": 275794, "author": "SAL9000", "author_id": 11609, "author_profile": "https://Stackoverflow.com/users/11609", "pm_score": 0, "selected": false, "text": "<p>Defining properties with the -D option at the command line is fine, though it can get tedious if there are many of them frequently. In order to resist the urge to wrap the ant invocation in a bash script, there is the common practise to import property files.</p>\n\n<p>In the main build file you put: </p>\n\n<pre><code>&lt;property file=\"default.properties\" /&gt;\n</code></pre>\n\n<p>Then you have a file named default.properties.sample with a sample configuration. This is being checked into version control. The developers check out default.properties.sample, copy it to default.properties and edit it according to their needs.</p>\n\n<p>You should set an ignore default flag for default.samples in order to prevent it from being checked in accidentally (svn:ignore with subversion).</p>\n" }, { "answer_id": 294776, "author": "Jeffrey Fredrick", "author_id": 35894, "author_profile": "https://Stackoverflow.com/users/35894", "pm_score": 4, "selected": true, "text": "<p>I typically use a variation on the default properties answer already given:</p>\n\n<pre><code>&lt;property file=\"local.properties\" /&gt;\n&lt;property file=\"default.properties\" /&gt;\n</code></pre>\n\n<p>I read the local properties file first and the default one second. Users don't edit the default one (then accidentally check it in), they just define the properties they want to override in the local.properties.</p>\n" }, { "answer_id": 7097507, "author": "Dooze", "author_id": 899223, "author_profile": "https://Stackoverflow.com/users/899223", "pm_score": 1, "selected": false, "text": "<p>This answer is quite late but I just wanted to put it in for someone who may be in need of of it. The answer pertains to the second part of your question.\n\"Can \"ant install\" take arguments or be configured to consider environment variables for the install target?\"</p>\n\n<ol>\n<li><p>Define the environment virable in your build file:</p>\n\n<pre><code>&lt;property environment=\"env\" /&gt;\n</code></pre></li>\n<li><p>reference the env variable and use it to indicate a path. This is done in my classpath definition inside my build file. It says include a jar named api.jar from the weblogic lib directory. You can access any other path so long as there's an associated environment virable defined for it. For example, you can access Program Files, Documents, Java Home etc if you sent environment variables for them. Here the environment variable defined for weblogic installation directory is BEA_HOME</p>\n\n<pre><code>&lt;fileset dir=\"${env.BEA_HOME}/wlserver_10.0/server/lib\"&gt;\n &lt;include name=\"api.jar\" /&gt;\n&lt;/fileset&gt;\n</code></pre></li>\n</ol>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22917/" ]
With multiple developers working on the same Tomcat application, I'd like to tell the application to install to a different path, based on the current user and revision control client/view. So, if Bob is building, the app should be installed in Bob's test environment, maybe /bob1 or something like that. Bob might have several revision control clients/views/workspaces he works with so he could have /bob1, /bob2, /bob3, etc. The install location is specified in the build.properties file. Is there a way to avoid checking that file out and changing it for each specific user and revision control view? Can "ant install" take arguments or be configured to consider environment variables for the install target?
I typically use a variation on the default properties answer already given: ``` <property file="local.properties" /> <property file="default.properties" /> ``` I read the local properties file first and the default one second. Users don't edit the default one (then accidentally check it in), they just define the properties they want to override in the local.properties.
273,664
<p>I find AWK really useful. Here is a one liner I put together to manipulate data.</p> <pre><code>ls | awk '{ print "awk " "'"'"'" " {print $1,$2,$3} " "'"'"'" " " $1 ".old_ext &gt; " $1 ".new_ext" }' &gt; file.csh </code></pre> <p>I used this AWK to make a script file that would rename some files and only print out selective columns. Anyone know a better way to do this? What are you best AWK one liners or clever manipulations?</p>
[ { "answer_id": 273673, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "<p>Henry Spencer wrote a fairly good implementation of nroff on awk. He called it \"awf\". He also claimed that if Larry Wall had known how powerful awk was, he wouldn't have needed to invent perl.</p>\n" }, { "answer_id": 273737, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 1, "selected": false, "text": "<p>Here's a couple of awks that I used to use regularly ... note that you can use $1, $2, etc to get out the column you want. So, for manipulating a bunch of files, for example here's a stupid command you could use instead of mv ...</p>\n\n<pre><code>ls -1 *.mp3 | awk '{printf(\"mv %s newDir/%s\\n\",$1,$1)}' | /bin/sh\n</code></pre>\n\n<p>Or if you're looking at a set of processes maybe ...</p>\n\n<pre><code>ps -ef | grep -v username | awk '{printf(\"kill -9 %s\\n\",$2)}' | /bin/sh\n</code></pre>\n\n<p>Pretty trivial but you can see how that would get you quite a ways. =) Most of the stuff I used to do you can use xargs for, but hey, who needs them new fangled commands?</p>\n" }, { "answer_id": 273771, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 4, "selected": true, "text": "<p>The <a href=\"https://archive.org/details/pdfy-MgN0H1joIoDVoIC7\" rel=\"nofollow noreferrer\">AWK book</a> is full of great examples. They used to be collected for download from <a href=\"http://cm.bell-labs.com/cm/cs/who/bwk/awkcode.txt\" rel=\"nofollow noreferrer\">Kernighan's webpage</a> (404s now).</p>\n" }, { "answer_id": 274539, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>I use this script a lot for editing PATH and path-like environment variables.\nUsage:</p>\n\n<pre><code>export PATH=$(clnpath /new/bin:/other/bin:$PATH /old/bin:/other/old/bin)\n</code></pre>\n\n<p>This command adds /new/bin and /other/bin in front of PATH, removes both /old/bin and /other/old/bin from PATH (if present - no error if absent), and removes duplicate directory entries on path.</p>\n\n<pre><code>: \"@(#)$Id: clnpath.sh,v 1.6 1999/06/08 23:34:07 jleffler Exp $\"\n#\n# Print minimal version of $PATH, possibly removing some items\n\ncase $# in\n0) chop=\"\"; path=${PATH:?};;\n1) chop=\"\"; path=$1;;\n2) chop=$2; path=$1;;\n*) echo \"Usage: `basename $0 .sh` [$PATH [remove:list]]\" &gt;&amp;2\n exit 1;;\nesac\n\n# Beware of the quotes in the assignment to chop!\necho \"$path\" |\n${AWK:-awk} -F: '#\nBEGIN { # Sort out which path components to omit\n chop=\"'\"$chop\"'\";\n if (chop != \"\") nr = split(chop, remove); else nr = 0;\n for (i = 1; i &lt;= nr; i++)\n omit[remove[i]] = 1;\n }\n{\n for (i = 1; i &lt;= NF; i++)\n {\n x=$i;\n if (x == \"\") x = \".\";\n if (omit[x] == 0 &amp;&amp; path[x]++ == 0)\n {\n output = output pad x;\n pad = \":\";\n }\n }\n print output;\n}'\n</code></pre>\n" }, { "answer_id": 424776, "author": "jtimberman", "author_id": 7672, "author_profile": "https://Stackoverflow.com/users/7672", "pm_score": 2, "selected": false, "text": "<p>I use this: </p>\n\n<pre><code>df -m | awk '{p+=$3}; END {print p}'\n</code></pre>\n\n<p>To total all disk space used on a system across filesystems.</p>\n" }, { "answer_id": 428260, "author": "Vijay Dev", "author_id": 27474, "author_profile": "https://Stackoverflow.com/users/27474", "pm_score": 2, "selected": false, "text": "<p>You can find several nice one liners <a href=\"http://www.catonmat.net/blog/awk-one-liners-explained-part-three/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 433035, "author": "PEZ", "author_id": 44639, "author_profile": "https://Stackoverflow.com/users/44639", "pm_score": 2, "selected": false, "text": "<p>Many years ago I wrote a tail script in awk:</p>\n\n<pre><code>#!/usr/bin/awk -f\nBEGIN {\n lines=10\n}\n\n{\n high = NR % lines + 1\n a[high] = $0\n}\n\nEND {\n for (i = 0; i &lt; lines; i++) {\n n = (i + high) % lines + 1\n if (n in a) {\n print a[n]\n }\n }\n}\n</code></pre>\n\n<p>It's silly, I know, but that's what awk does to you. It's just very fun playing with it.</p>\n" }, { "answer_id": 1597829, "author": "Jim", "author_id": 118850, "author_profile": "https://Stackoverflow.com/users/118850", "pm_score": 0, "selected": false, "text": "<p>Count memory used by httpd</p>\n\n<pre><code>ps -ylC httpd | awk '/[0-9]/ {SUM += $8} END {print SUM/1024}'\n</code></pre>\n\n<p>Or any other process by replacing httpd. Dividing by 1024 to get output in MB.</p>\n" }, { "answer_id": 11468566, "author": "Juan Diego Godoy Robles", "author_id": 1200821, "author_profile": "https://Stackoverflow.com/users/1200821", "pm_score": 0, "selected": false, "text": "<p>I managed to build a DOS tree command emulator for UNIX ( find + awk ):</p>\n\n<pre><code>find . -type d -print 2&gt;/dev/null|awk '{for (i=1;i&lt; NF;i++)printf(\"%\"length($i)\"s\",\"|\");gsub(/[^\\/]*\\//,\"--\",$0);print $NF}' FS='/'\n</code></pre>\n" }, { "answer_id": 14119098, "author": "Juan Diego Godoy Robles", "author_id": 1200821, "author_profile": "https://Stackoverflow.com/users/1200821", "pm_score": 0, "selected": false, "text": "<p>Print lines between two patterns:</p>\n\n<pre><code>awk '/END/{flag=0}flag;/START/{flag=1}' inputFile\n</code></pre>\n\n<p>Detailed explanation: <a href=\"http://nixtip.wordpress.com/2010/10/12/print-lines-between-two-patterns-the-awk-way/\" rel=\"nofollow\">http://nixtip.wordpress.com/2010/10/12/print-lines-between-two-patterns-the-awk-way/</a> </p>\n" }, { "answer_id": 31574445, "author": "Andrew", "author_id": 2708215, "author_profile": "https://Stackoverflow.com/users/2708215", "pm_score": 0, "selected": false, "text": "<p>A couple of favorites, essentially unrelated to each other. Read as 2 different, unconnected suggestions.</p>\n\n<h2>Identifying Column Numbers Easily</h2>\n\n<p>:</p>\n\n<p>For those that use awk frequently, as I do for log analysis at work, I often find myself needing to find out what the column numbers are for a file. So, if I am analyzing, say, Apache access files (some samples can be found <a href=\"http://www.monitorware.com/en/logsamples/apache.php\" rel=\"nofollow\">here</a>) I run the script below against the file:</p>\n\n<pre><code>NR == 1 {\n for (i = 1 ; i &lt;= NF ; i++)\n {\n print i \"\\t\" $i\n }\n }\nNR &gt; 1 {\n exit\n }\n</code></pre>\n\n<p>I typically call it \"cn.awk\", for 'c'olumn 'n'umbers. Creative, eh? Anyway, the output looks like:</p>\n\n<pre><code>1 64.242.88.10\n2 -\n3 -\n4 [07/Mar/2004:16:05:49\n5 -0800]\n6 \"GET\n7 /twiki/bin/edit/Main/Double_bounce_sender?topicparent=Main.ConfigurationVariables\n8 HTTP/1.1\"\n9 401\n10 12846\n</code></pre>\n\n<p>Very easy to tell what's what. I usually alias this on my servers and have it everywhere.</p>\n\n<hr>\n\n<h2>Referencing Fields by Name</h2>\n\n<p>Now, suppose your file has a header row and you'd rather use those names instead of field numbers. This allows you to do so:</p>\n\n<pre><code>NR == 1 {\n for (i = 1 ; i &lt;= NF ; i++)\n {\n field[$i] = i\n }\n }\n</code></pre>\n\n<p>Now, suppose I have this header row...</p>\n\n<p><code>metric,time,val,location,http_status,http_request</code></p>\n\n<p>...and I'd like to sum the <code>val</code> column. Instead of referring to $3, I can refer to it by name:</p>\n\n<pre><code>NR &gt; 1 {\n SUM += $field[\"val\"]\n }\n</code></pre>\n\n<p>The main benefit is making the script much more readable.</p>\n" }, { "answer_id": 38797072, "author": "Zlemini ", "author_id": 6684013, "author_profile": "https://Stackoverflow.com/users/6684013", "pm_score": 0, "selected": false, "text": "<p>Printing fields is one of the first things mentioned in most AWK tutorials.</p>\n\n<pre><code>awk '{print $1,$3}' file\n</code></pre>\n\n<p>Lesser known but equally useful is excluding fields which is also possible:</p>\n\n<pre><code>awk '{$1=$3=\"\"}1' file\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30181/" ]
I find AWK really useful. Here is a one liner I put together to manipulate data. ``` ls | awk '{ print "awk " "'"'"'" " {print $1,$2,$3} " "'"'"'" " " $1 ".old_ext > " $1 ".new_ext" }' > file.csh ``` I used this AWK to make a script file that would rename some files and only print out selective columns. Anyone know a better way to do this? What are you best AWK one liners or clever manipulations?
The [AWK book](https://archive.org/details/pdfy-MgN0H1joIoDVoIC7) is full of great examples. They used to be collected for download from [Kernighan's webpage](http://cm.bell-labs.com/cm/cs/who/bwk/awkcode.txt) (404s now).
273,671
<p>In an attempt to hide the Safari UI components for an web-app bookmarked as a Homescreen Icon. I am using this meta tag </p> <pre><code>&lt;meta name="apple-mobile-web-app-capable" content="yes" /&gt; </code></pre> <p>as specified on <a href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW2" rel="nofollow noreferrer">iPhone Dev Center</a> but the address bar and toolbar are still there when launched from the home screen icon. What do I need to do different? Does anyone have an example?</p>
[ { "answer_id": 273693, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 3, "selected": false, "text": "<p>Is it being launched from the home screen? The documentation on the linked page does not mention but I found this @ <a href=\"https://developer.apple.com/webapps/docs/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/chapter_8_section_1.html#//apple_ref/doc/uid/TP40002051-CH3-SW3\" rel=\"nofollow noreferrer\">Configuring Web Applications</a>:</p>\n\n<blockquote>\n <p>For example, you can specify an icon for your web application used to represent it when added to the Home screen, as described in “Specifying a Webpage Icon for Web Clip.” <b>You can also minimize the Safari on iPhone user interface</b>, as described in “Changing the Status Bar Appearance” and “Hiding Safari User Interface Components,” <b>when your web application is launched from the Home screen</b>. These are all optional settings that when added to your web content are ignored by other platforms</p>\n</blockquote>\n" }, { "answer_id": 274904, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 0, "selected": false, "text": "<p>That should indeed behave as expected, I have used it in the past without any difficulties. </p>\n" }, { "answer_id": 2002558, "author": "Benoit", "author_id": 222769, "author_profile": "https://Stackoverflow.com/users/222769", "pm_score": 3, "selected": false, "text": "<p>Have you tried adding...</p>\n\n<pre><code>&lt;meta name=\"apple-touch-fullscreen\" content=\"yes\" /&gt;\n</code></pre>\n" }, { "answer_id": 3049787, "author": "mbxtr", "author_id": 205815, "author_profile": "https://Stackoverflow.com/users/205815", "pm_score": 2, "selected": false, "text": "<p>I know this is pretty old, but I came across this while searching for a solution. I was able to fix this by also adding:</p>\n\n<pre><code>window.top.scrollTo(0, 1);\n</code></pre>\n\n<p>to the body's onload method. Hope it helps anyone else coming across this.</p>\n" }, { "answer_id": 3286565, "author": "Steve Jorgensen", "author_id": 396373, "author_profile": "https://Stackoverflow.com/users/396373", "pm_score": 5, "selected": false, "text": "<pre><code>window.top.scrollTo(0, 1);\n</code></pre>\n\n<p>Works on iPhone, but not in iPad. I have been successful hiding the browser components on iPad (so presumably everywhere) by using</p>\n\n<pre><code>&lt;meta name=\"apple-mobile-web-app-capable\" content=\"yes\" /&gt;\n</code></pre>\n\n<p>and launching from a home-screen link. I am also using</p>\n\n<pre><code>&lt;meta name=\"viewport\" \n content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" /&gt;\n</code></pre>\n\n<p>I have not tried seeing if the browser components are still hidden if I leave out the viewport properties.</p>\n" }, { "answer_id": 4420887, "author": "Toby", "author_id": 539420, "author_profile": "https://Stackoverflow.com/users/539420", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW2\" rel=\"nofollow\">http://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW2</a></p>\n\n<p>It works on iOS 4.0.</p>\n" }, { "answer_id": 7828983, "author": "Andrew", "author_id": 924783, "author_profile": "https://Stackoverflow.com/users/924783", "pm_score": 2, "selected": false, "text": "<p>From what I can tell, iOS only pays attention to the flags when you actually add the app. If the apple-mobile-web-app-capable thingy doesn't work at first, try deleting your app from the home screen then re-adding it.</p>\n\n<p>I've run some experiments and found:</p>\n\n<ul>\n<li>the location of the meta tag within the headers doesn't seem to matter (I thought it might!)<br></li>\n<li>after adding the app and having it remove the address bar correctly, if you then remove the meta tags from the web page, iOS continues to remove the toolbar.<br></li>\n<li>even after rebooting the device it still 'remembers' whether to remove the toolbar. The only way I've found of resetting this behaviour is to remove and re-add the app.</li>\n</ul>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 12193324, "author": "Pierre", "author_id": 1635519, "author_profile": "https://Stackoverflow.com/users/1635519", "pm_score": 1, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>&lt;meta name=\"apple-mobile-web-app-capable\" content=\"yes\"&gt;\n&lt;meta name=\"viewport\" content=\"width=device-width; user-scalable=0;\"&gt;\n&lt;meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\"&gt;\n&lt;link rel=\"apple-touch-icon\" href=\"icon.png\"&gt;\n</code></pre>\n" }, { "answer_id": 12392872, "author": "Samuel Lindblom", "author_id": 407397, "author_profile": "https://Stackoverflow.com/users/407397", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;meta name=\"apple-mobile-web-app-capable\" content=\"yes\" /&gt;\n</code></pre>\n\n<p>This will work if:</p>\n\n<ol>\n<li>The tag exists when the app is added to the home screen.</li>\n<li>The app is launched from the home screen.</li>\n</ol>\n" }, { "answer_id": 15271110, "author": "Charles Ingalls", "author_id": 1874138, "author_profile": "https://Stackoverflow.com/users/1874138", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;meta name=\"apple-mobile-web-app-capable\" content=\"yes\" /&gt;\n</code></pre>\n\n<p>works on iOS6 + Mobile Safari Browser but ONLY if you added the page to your homescreen AFTER you included the meta tag on your site.</p>\n" }, { "answer_id": 16294322, "author": "jsDebugger", "author_id": 642395, "author_profile": "https://Stackoverflow.com/users/642395", "pm_score": 0, "selected": false, "text": "<p>all above meta tags and window.scrollTo, did not work on ipad for me,\ni found a button on safari next to bookmarks where you get an option called 'Add to Home Screen' it creates a new tile icon, and you can launch your web app like a native app, and no address bar there.</p>\n" }, { "answer_id": 22546030, "author": "B.Asselin", "author_id": 418229, "author_profile": "https://Stackoverflow.com/users/418229", "pm_score": 0, "selected": false, "text": "<p>Since iOS 7.1, you can use <code>minimal-ui</code></p>\n\n<pre><code>&lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1, minimal-ui\"&gt;\n</code></pre>\n" }, { "answer_id": 23705271, "author": "Cristian Dinu", "author_id": 2552781, "author_profile": "https://Stackoverflow.com/users/2552781", "pm_score": 1, "selected": false, "text": "<p>There is a new directive, called \"minimal-ui\" that iOS browser takes into account (at least on the iPhone where I tested). Toolbars are hidden until the user clicks on the status bar on top. Very nice for one page apps!</p>\n\n<p>Here is the snippet I use:</p>\n\n<p><code>&lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui\"&gt;</code></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In an attempt to hide the Safari UI components for an web-app bookmarked as a Homescreen Icon. I am using this meta tag ``` <meta name="apple-mobile-web-app-capable" content="yes" /> ``` as specified on [iPhone Dev Center](https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW2) but the address bar and toolbar are still there when launched from the home screen icon. What do I need to do different? Does anyone have an example?
``` window.top.scrollTo(0, 1); ``` Works on iPhone, but not in iPad. I have been successful hiding the browser components on iPad (so presumably everywhere) by using ``` <meta name="apple-mobile-web-app-capable" content="yes" /> ``` and launching from a home-screen link. I am also using ``` <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> ``` I have not tried seeing if the browser components are still hidden if I leave out the viewport properties.
273,675
<p>From an application I'm building I need to print existing PDFs (created by another app). How can I do this in C# and provide a mechanism so the user can select a different printer or other properties. </p> <p>I've looked at the PrintDialog but not sure what file it is attempting to print, if any, b/c the output is always a blank page. Maybe I'm just missing something there.</p> <p>Do I need to use "iTextSharp" (as suggested else where)? That seems odd to me since I can "send the the file to the printer" I just don't have any nice dialog before hand to set the printer etc. and I don't really want to write a printing dialog from the ground up but it seems like a lot of examples I found by searching did just that.</p> <p>Any advice, examples or sample code would be great!</p> <p>Also if PDF is the issue the files could be created by the other app in a diff format such as bitmap or png if that makes things easier.</p>
[ { "answer_id": 273702, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 1, "selected": false, "text": "<p>You will need Acrobat or some other application that can print the PDF. From there you P/Invoke to <a href=\"http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx\" rel=\"nofollow noreferrer\">ShellExecute</a> to print the document.</p>\n" }, { "answer_id": 273729, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 5, "selected": false, "text": "<p>Display a little dialog with a combobox that has its Items set to the string collection returned by <code>PrinterSettings.InstalledPrinters</code>.</p>\n\n<p>If you can make it a requirement that <a href=\"http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm\" rel=\"noreferrer\">GSView</a> be installed on the machine, you can then silently print the PDF. It's a little slow and roundabout but at least you don't have to pop up Acrobat.</p>\n\n<p>Here's some code I use to print out some PDFs that I get back from a UPS Web service:</p>\n\n<pre><code> private void PrintFormPdfData(byte[] formPdfData)\n {\n string tempFile;\n\n tempFile = Path.GetTempFileName();\n\n using (FileStream fs = new FileStream(tempFile, FileMode.Create))\n {\n fs.Write(formPdfData, 0, formPdfData.Length);\n fs.Flush();\n }\n\n try\n {\n string gsArguments;\n string gsLocation;\n ProcessStartInfo gsProcessInfo;\n Process gsProcess;\n\n gsArguments = string.Format(\"-grey -noquery -printer \\\"HP LaserJet 5M\\\" \\\"{0}\\\"\", tempFile);\n gsLocation = @\"C:\\Program Files\\Ghostgum\\gsview\\gsprint.exe\";\n\n gsProcessInfo = new ProcessStartInfo();\n gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;\n gsProcessInfo.FileName = gsLocation;\n gsProcessInfo.Arguments = gsArguments;\n\n gsProcess = Process.Start(gsProcessInfo);\n gsProcess.WaitForExit();\n }\n finally\n {\n File.Delete(tempFile);\n }\n }\n</code></pre>\n\n<p>As you can see, it takes the PDF data as a byte array, writes it to a temp file, and launches gsprint.exe to print the file silently to the named printer (\"HP Laserjet 5M\"). You could replace the printer name with whatever the user chose in your dialog box.</p>\n\n<p>Printing a PNG or GIF would be much easier -- just extend the PrintDocument class and use the normal print dialog provided by Windows Forms.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 273822, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Although this is VB you can easily translate it. By the way Adobe does not pop up, it only prints the pdf and then goes away.</p>\n\n<pre><code>''' &lt;summary&gt;\n''' Start Adobe Process to print document\n''' &lt;/summary&gt;\n''' &lt;param name=\"p\"&gt;&lt;/param&gt;\n''' &lt;remarks&gt;&lt;/remarks&gt;\nPrivate Function printDoc(ByVal p As PrintObj) As PrintObj\n Dim myProcess As New Process()\n Dim myProcessStartInfo As New ProcessStartInfo(adobePath)\n Dim errMsg As String = String.Empty\n Dim outFile As String = String.Empty\n myProcessStartInfo.UseShellExecute = False\n myProcessStartInfo.RedirectStandardOutput = True\n myProcessStartInfo.RedirectStandardError = True\n\n Try\n\n If canIprintFile(p.sourceFolder &amp; p.sourceFileName) Then\n isAdobeRunning(p)'Make sure Adobe is not running; wait till it's done\n Try\n myProcessStartInfo.Arguments = \" /t \" &amp; \"\"\"\" &amp; p.sourceFolder &amp; p.sourceFileName &amp; \"\"\"\" &amp; \" \" &amp; \"\"\"\" &amp; p.destination &amp; \"\"\"\"\n myProcess.StartInfo = myProcessStartInfo\n myProcess.Start()\n myProcess.CloseMainWindow()\n isAdobeRunning(p)\n myProcess.Dispose()\n Catch ex As Exception\n End Try\n p.result = \"OK\"\n Else\n p.result = \"The file that the Document Printer is tryng to print is missing.\"\n sendMailNotification(\"The file that the Document Printer is tryng to print\" &amp; vbCrLf &amp; _\n \"is missing. The file in question is: \" &amp; vbCrLf &amp; _\n p.sourceFolder &amp; p.sourceFileName, p)\n End If\n Catch ex As Exception\n p.result = ex.Message\n sendMailNotification(ex.Message, p)\n Finally\n myProcess.Dispose()\n End Try\n Return p\nEnd Function\n</code></pre>\n" }, { "answer_id": 1675144, "author": "David Duffett", "author_id": 91619, "author_profile": "https://Stackoverflow.com/users/91619", "pm_score": 1, "selected": false, "text": "<p>You could also use PDFsharp - it's an open source library for creating and manipulating PDFs.\n<a href=\"http://www.pdfsharp.net/\" rel=\"nofollow noreferrer\">http://www.pdfsharp.net/</a></p>\n" }, { "answer_id": 11131365, "author": "Parvej Solkar", "author_id": 1434525, "author_profile": "https://Stackoverflow.com/users/1434525", "pm_score": 1, "selected": false, "text": "<p>I'm doing the same thing for my project and it worked for me</p>\n\n<p>See if it can help you...</p>\n\n<pre><code>Process p = new Process();\np.EnableRaisingEvents = true; //Important line of code\np.StartInfo = new ProcessStartInfo()\n{\n CreateNoWindow = true,\n Verb = \"print\",\n FileName = file,\n Arguments = \"/d:\"+printDialog1.PrinterSettings.PrinterName\n}; \ntry\n{\n p.Start();\n} \ncatch \n{ \n /* your fallback code */ \n}\n</code></pre>\n\n<p>You can also play with different options of windows </p>\n\n<p>PRINT command to get desired output...<a href=\"http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/print.mspx?mfr=true\" rel=\"nofollow\">Reference link</a></p>\n" }, { "answer_id": 28775043, "author": "Marko", "author_id": 1078115, "author_profile": "https://Stackoverflow.com/users/1078115", "pm_score": 1, "selected": false, "text": "<p>After much research and googling about this task Microsoft has released a great KB to print a pdf without any other applications necessary. No need to call adobe or ghostprint. It can print without saving a file to the disk makes life very easy.</p>\n\n<p><a href=\"http://support2.microsoft.com/?kbid=322091\" rel=\"nofollow\">http://support2.microsoft.com/?kbid=322091</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From an application I'm building I need to print existing PDFs (created by another app). How can I do this in C# and provide a mechanism so the user can select a different printer or other properties. I've looked at the PrintDialog but not sure what file it is attempting to print, if any, b/c the output is always a blank page. Maybe I'm just missing something there. Do I need to use "iTextSharp" (as suggested else where)? That seems odd to me since I can "send the the file to the printer" I just don't have any nice dialog before hand to set the printer etc. and I don't really want to write a printing dialog from the ground up but it seems like a lot of examples I found by searching did just that. Any advice, examples or sample code would be great! Also if PDF is the issue the files could be created by the other app in a diff format such as bitmap or png if that makes things easier.
Display a little dialog with a combobox that has its Items set to the string collection returned by `PrinterSettings.InstalledPrinters`. If you can make it a requirement that [GSView](http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm) be installed on the machine, you can then silently print the PDF. It's a little slow and roundabout but at least you don't have to pop up Acrobat. Here's some code I use to print out some PDFs that I get back from a UPS Web service: ``` private void PrintFormPdfData(byte[] formPdfData) { string tempFile; tempFile = Path.GetTempFileName(); using (FileStream fs = new FileStream(tempFile, FileMode.Create)) { fs.Write(formPdfData, 0, formPdfData.Length); fs.Flush(); } try { string gsArguments; string gsLocation; ProcessStartInfo gsProcessInfo; Process gsProcess; gsArguments = string.Format("-grey -noquery -printer \"HP LaserJet 5M\" \"{0}\"", tempFile); gsLocation = @"C:\Program Files\Ghostgum\gsview\gsprint.exe"; gsProcessInfo = new ProcessStartInfo(); gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden; gsProcessInfo.FileName = gsLocation; gsProcessInfo.Arguments = gsArguments; gsProcess = Process.Start(gsProcessInfo); gsProcess.WaitForExit(); } finally { File.Delete(tempFile); } } ``` As you can see, it takes the PDF data as a byte array, writes it to a temp file, and launches gsprint.exe to print the file silently to the named printer ("HP Laserjet 5M"). You could replace the printer name with whatever the user chose in your dialog box. Printing a PNG or GIF would be much easier -- just extend the PrintDocument class and use the normal print dialog provided by Windows Forms. Good luck!
273,695
<p>I've been using a local git repository interacting with my group's CVS repository for several months, now. I've made an almost neurotic number of branches, most of which have thankfully merged back into my trunk. But naming is starting to become an issue. If I have a task easily named with a simple label, but I accomplish it in three stages which each include their own branch and merge situation, then I can repeat the branch name each time, but that makes the history a little confusing. If I get more specific in the names, with a separate description for each stage, then the branch names start to get long and unwieldy.</p> <p>I did learn looking through old threads here that I could start naming branches with a / in the name, i.e., topic/task, or something like that. I may start doing that and seeing if it helps keep things better organized.</p> <p>What are some best practices for naming git branches?</p> <p>Edit: Nobody has actually suggested any naming conventions. I do delete branches when I'm done with them. I just happen to have several around due to management constantly adjusting my priorities. :) As an example of why I might need more than one branch on a task, suppose I need to commit the first discrete milestone in the task to the group's CVS repository. At that point, due to my imperfect interaction with CVS, I would perform that commit and then kill that branch. (I've seen too much weirdness interacting with CVS if I try to continue to use the same branch at that point.)</p>
[ { "answer_id": 273760, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 6, "selected": false, "text": "<p>My personal preference is to delete the branch name after I’m done with a topic branch.</p>\n\n<p>Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.</p>\n\n<p>The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.</p>\n\n<p>That makes the output of <code>git branch</code> more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.</p>\n" }, { "answer_id": 280157, "author": "farktronix", "author_id": 677, "author_profile": "https://Stackoverflow.com/users/677", "pm_score": 5, "selected": false, "text": "<p>Why does it take three branches/merges for every task? Can you explain more about that?</p>\n\n<p>If you use a bug tracking system you can use the bug number as part of the branch name. This will keep the branch names unique, and you can prefix them with a short and descriptive word or two to keep them human readable, like <code>\"ResizeWindow-43523\"</code>. It also helps make things easier when you go to clean up branches, since you can look up the associated bug. This is how I usually name my branches.</p>\n\n<p>Since these branches are eventually getting merged back into master, you should be safe deleting them after you merge. Unless you're merging with <code>--squash</code>, the entire history of the branch will still exist should you ever need it.</p>\n" }, { "answer_id": 2150402, "author": "Gary S. Weaver", "author_id": 178651, "author_profile": "https://Stackoverflow.com/users/178651", "pm_score": 3, "selected": false, "text": "<p>Following up on <a href=\"https://stackoverflow.com/a/280157/5411817\">farktronix's suggestion</a>, we have been using Jira ticket numbers for similar in mercurial, and I'm planning to continue using them for git branches. But I think the ticket number itself is probably unique enough. While it might be helpful to have a descriptive word in the branch name as farktronix noted, if you are switching between branches often enough, you probably want less to type. Then if you need to know the branch name, look in Jira for the associated keywords in the ticket if you don't know it. In addition, you should include the ticket number in each comment.</p>\n<p>If your branch represents a version, it appears that the common convention is to use x.x.x (example: &quot;1.0.0&quot;) format for branch names and vx.x.x (example &quot;v1.0.0&quot;) for tag names (to avoid conflict). See also: <a href=\"https://stackoverflow.com/questions/2006265/is-there-an-standard-naming-convention-for-git-tags\">is-there-an-standard-naming-convention-for-git-tags</a></p>\n" }, { "answer_id": 4258654, "author": "Brian Carlton", "author_id": 20147, "author_profile": "https://Stackoverflow.com/users/20147", "pm_score": 9, "selected": false, "text": "<p><a href=\"http://nvie.com/posts/a-successful-git-branching-model/\" rel=\"noreferrer\">A successful Git branching model</a> by Vincent Driessen has good suggestions. A picture is below. If this branching model appeals to you consider the <a href=\"https://github.com/nvie/gitflow/tree/master\" rel=\"noreferrer\">flow extension to git</a>. Others have <a href=\"http://jeffkreeftmeijer.com/2010/why-arent-you-using-git-flow/\" rel=\"noreferrer\">commented about flow</a></p>\n\n<p>Driessen's model includes</p>\n\n<ul>\n<li><p>A master branch, used only for release. Typical name <code>master</code>.</p></li>\n<li><p>A \"develop\" branch off of that branch. That's the one used for most main-line work. Commonly named <code>develop</code>.</p></li>\n<li><p>Multiple feature branches off of the develop branch. Name based on the name of the feature. These will be merged back into develop, not into the master or release branches.</p></li>\n<li><p>Release branch to hold candidate releases, with only bug fixes and no new features. Typical name <code>rc1.1</code>.</p></li>\n</ul>\n\n<p>Hotfixes are short-lived branches for changes that come from master and will go into master without development branch being involved.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tjJCt.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/tjJCt.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 6065944, "author": "Phil Hord", "author_id": 33342, "author_profile": "https://Stackoverflow.com/users/33342", "pm_score": 10, "selected": false, "text": "<p>Here are some branch naming conventions that I use and the reasons for them</p>\n\n<p><strong>Branch naming conventions</strong></p>\n\n<ol>\n<li>Use grouping tokens (words) at the beginning of your branch names.</li>\n<li>Define and use short lead tokens to differentiate branches in a way that is meaningful to your workflow.</li>\n<li>Use slashes to separate parts of your branch names.</li>\n<li>Do not use bare numbers as leading parts.</li>\n<li>Avoid long descriptive names for long-lived branches.</li>\n</ol>\n\n<p><strong>Group tokens</strong></p>\n\n<p>Use \"grouping\" tokens in front of your branch names. </p>\n\n<pre><code>group1/foo\ngroup2/foo\ngroup1/bar\ngroup2/bar\ngroup3/bar\ngroup1/baz\n</code></pre>\n\n<p>The groups can be named whatever you like to match your workflow. I like to use short nouns for mine. Read on for more clarity.</p>\n\n<p><strong>Short well-defined tokens</strong></p>\n\n<p>Choose short tokens so they do not add too much noise to every one of your branch names. I use these:</p>\n\n<pre><code>wip Works in progress; stuff I know won't be finished soon\nfeat Feature I'm adding or expanding\nbug Bug fix or experiment\njunk Throwaway branch created to experiment\n</code></pre>\n\n<p>Each of these tokens can be used to tell you to which part of your workflow each branch belongs.</p>\n\n<p>It sounds like you have multiple branches for different cycles of a change. I do not know what your cycles are, but let's assume they are 'new', 'testing' and 'verified'. You can name your branches with abbreviated versions of these tags, always spelled the same way, to both group them and to remind you which stage you're in.</p>\n\n<pre><code>new/frabnotz\nnew/foo\nnew/bar\ntest/foo\ntest/frabnotz\nver/foo\n</code></pre>\n\n<p>You can quickly tell which branches have reached each different stage, and you can group them together easily using Git's pattern matching options.</p>\n\n<pre><code>$ git branch --list \"test/*\"\ntest/foo\ntest/frabnotz\n\n$ git branch --list \"*/foo\"\nnew/foo\ntest/foo\nver/foo\n\n$ gitk --branches=\"*/foo\"\n</code></pre>\n\n<p><strong>Use slashes to separate parts</strong></p>\n\n<p>You may use most any delimiter you like in branch names, but I find slashes to be the most flexible. You might prefer to use dashes or dots. But slashes let you do some branch renaming when pushing or fetching to/from a remote.</p>\n\n<pre><code>$ git push origin 'refs/heads/feature/*:refs/heads/phord/feat/*'\n$ git push origin 'refs/heads/bug/*:refs/heads/review/bugfix/*'\n</code></pre>\n\n<p>For me, slashes also work better for tab expansion (command completion) in my shell. The way I have it configured I can search for branches with different sub-parts by typing the first characters of the part and pressing the TAB key. Zsh then gives me a list of branches which match the part of the token I have typed. This works for preceding tokens as well as embedded ones.</p>\n\n<pre><code>$ git checkout new&lt;TAB&gt;\nMenu: new/frabnotz new/foo new/bar\n\n\n$ git checkout foo&lt;TAB&gt;\nMenu: new/foo test/foo ver/foo\n</code></pre>\n\n<p>(Zshell is very configurable about command completion and I could also configure it to handle dashes, underscores or dots the same way. But I choose not to.)</p>\n\n<p>It also lets you search for branches in many git commands, like this:</p>\n\n<pre><code>git branch --list \"feature/*\"\ngit log --graph --oneline --decorate --branches=\"feature/*\" \ngitk --branches=\"feature/*\" \n</code></pre>\n\n<p>Caveat: As Slipp points out in the comments, slashes can cause problems. Because branches are implemented as paths, you cannot have a branch named \"foo\" and another branch named \"foo/bar\". This can be confusing for new users.</p>\n\n<p><strong>Do not use bare numbers</strong></p>\n\n<p>Do not use use bare numbers (or hex numbers) as part of your branch naming scheme. Inside tab-expansion of a reference name, git may decide that a number is part of a sha-1 instead of a branch name. For example, my issue tracker names bugs with decimal numbers. I name my related branches CRnnnnn rather than just nnnnn to avoid confusion. </p>\n\n<pre><code>$ git checkout CR15032&lt;TAB&gt;\nMenu: fix/CR15032 test/CR15032\n</code></pre>\n\n<p>If I tried to expand just 15032, git would be unsure whether I wanted to search SHA-1's or branch names, and my choices would be somewhat limited.</p>\n\n<p><strong>Avoid long descriptive names</strong></p>\n\n<p>Long branch names can be very helpful when you are looking at a list of branches. But it can get in the way when looking at decorated one-line logs as the branch names can eat up most of the single line and abbreviate the visible part of the log.</p>\n\n<p>On the other hand long branch names can be more helpful in \"merge commits\" if you do not habitually rewrite them by hand. The default merge commit message is <code>Merge branch 'branch-name'</code>. You may find it more helpful to have merge messages show up as <code>Merge branch 'fix/CR15032/crash-when-unformatted-disk-inserted'</code> instead of just <code>Merge branch 'fix/CR15032'</code>.</p>\n" }, { "answer_id": 19300703, "author": "MikeG", "author_id": 1241201, "author_profile": "https://Stackoverflow.com/users/1241201", "pm_score": 6, "selected": false, "text": "<p>I've mixed and matched from different schemes I've seen and based on the tooling I'm using.<br>\nSo my completed branch name would be:</p>\n\n<blockquote>\n <p>name/feature/issue-tracker-number/short-description</p>\n</blockquote>\n\n<p>which would translate to:</p>\n\n<blockquote>\n <p>mike/blogs/RSSI-12/logo-fix</p>\n</blockquote>\n\n<p>The parts are separated by forward slashes because those get interpreted as folders in SourceTree for easy organization. We use Jira for our issue tracking so including the number makes it easier to look up in the system. Including that number also makes it searchable when trying to find that issue inside Github when trying to submit a pull request. </p>\n" }, { "answer_id": 24223634, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "<p>Note, as illustrated in the <a href=\"https://github.com/git/git/commit/e703d7118c68bb5b1f850dae4060609a88500b18\" rel=\"noreferrer\">commit e703d7</a> or <a href=\"https://github.com/git/git/commit/b6c2a0d45d4165dfd326bd7a28e66d9cedb8ae84\" rel=\"noreferrer\">commit b6c2a0d</a> (March 2014), now part of Git 2.0, you will find another naming convention (that you can apply to branches).</p>\n\n<blockquote>\n <p>\"When you need to use space, use dash\" is a strange way to say that you must not use a space.<br>\n Because it is more common for the command line descriptions to use dashed-multi-words, you do not even want to use spaces in these places. </p>\n</blockquote>\n\n<p>A branch name cannot have space (see \"<a href=\"https://stackoverflow.com/a/3651867/6309\">Which characters are illegal within a branch name?</a>\" and <a href=\"http://git-scm.com/docs/git-check-ref-format\" rel=\"noreferrer\"><code>git check-ref-format</code> man page</a>).</p>\n\n<p>So for every branch name that would be represented by a multi-word expression, using a '<code>-</code>' (dash) as a separator is a good idea.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18103/" ]
I've been using a local git repository interacting with my group's CVS repository for several months, now. I've made an almost neurotic number of branches, most of which have thankfully merged back into my trunk. But naming is starting to become an issue. If I have a task easily named with a simple label, but I accomplish it in three stages which each include their own branch and merge situation, then I can repeat the branch name each time, but that makes the history a little confusing. If I get more specific in the names, with a separate description for each stage, then the branch names start to get long and unwieldy. I did learn looking through old threads here that I could start naming branches with a / in the name, i.e., topic/task, or something like that. I may start doing that and seeing if it helps keep things better organized. What are some best practices for naming git branches? Edit: Nobody has actually suggested any naming conventions. I do delete branches when I'm done with them. I just happen to have several around due to management constantly adjusting my priorities. :) As an example of why I might need more than one branch on a task, suppose I need to commit the first discrete milestone in the task to the group's CVS repository. At that point, due to my imperfect interaction with CVS, I would perform that commit and then kill that branch. (I've seen too much weirdness interacting with CVS if I try to continue to use the same branch at that point.)
Here are some branch naming conventions that I use and the reasons for them **Branch naming conventions** 1. Use grouping tokens (words) at the beginning of your branch names. 2. Define and use short lead tokens to differentiate branches in a way that is meaningful to your workflow. 3. Use slashes to separate parts of your branch names. 4. Do not use bare numbers as leading parts. 5. Avoid long descriptive names for long-lived branches. **Group tokens** Use "grouping" tokens in front of your branch names. ``` group1/foo group2/foo group1/bar group2/bar group3/bar group1/baz ``` The groups can be named whatever you like to match your workflow. I like to use short nouns for mine. Read on for more clarity. **Short well-defined tokens** Choose short tokens so they do not add too much noise to every one of your branch names. I use these: ``` wip Works in progress; stuff I know won't be finished soon feat Feature I'm adding or expanding bug Bug fix or experiment junk Throwaway branch created to experiment ``` Each of these tokens can be used to tell you to which part of your workflow each branch belongs. It sounds like you have multiple branches for different cycles of a change. I do not know what your cycles are, but let's assume they are 'new', 'testing' and 'verified'. You can name your branches with abbreviated versions of these tags, always spelled the same way, to both group them and to remind you which stage you're in. ``` new/frabnotz new/foo new/bar test/foo test/frabnotz ver/foo ``` You can quickly tell which branches have reached each different stage, and you can group them together easily using Git's pattern matching options. ``` $ git branch --list "test/*" test/foo test/frabnotz $ git branch --list "*/foo" new/foo test/foo ver/foo $ gitk --branches="*/foo" ``` **Use slashes to separate parts** You may use most any delimiter you like in branch names, but I find slashes to be the most flexible. You might prefer to use dashes or dots. But slashes let you do some branch renaming when pushing or fetching to/from a remote. ``` $ git push origin 'refs/heads/feature/*:refs/heads/phord/feat/*' $ git push origin 'refs/heads/bug/*:refs/heads/review/bugfix/*' ``` For me, slashes also work better for tab expansion (command completion) in my shell. The way I have it configured I can search for branches with different sub-parts by typing the first characters of the part and pressing the TAB key. Zsh then gives me a list of branches which match the part of the token I have typed. This works for preceding tokens as well as embedded ones. ``` $ git checkout new<TAB> Menu: new/frabnotz new/foo new/bar $ git checkout foo<TAB> Menu: new/foo test/foo ver/foo ``` (Zshell is very configurable about command completion and I could also configure it to handle dashes, underscores or dots the same way. But I choose not to.) It also lets you search for branches in many git commands, like this: ``` git branch --list "feature/*" git log --graph --oneline --decorate --branches="feature/*" gitk --branches="feature/*" ``` Caveat: As Slipp points out in the comments, slashes can cause problems. Because branches are implemented as paths, you cannot have a branch named "foo" and another branch named "foo/bar". This can be confusing for new users. **Do not use bare numbers** Do not use use bare numbers (or hex numbers) as part of your branch naming scheme. Inside tab-expansion of a reference name, git may decide that a number is part of a sha-1 instead of a branch name. For example, my issue tracker names bugs with decimal numbers. I name my related branches CRnnnnn rather than just nnnnn to avoid confusion. ``` $ git checkout CR15032<TAB> Menu: fix/CR15032 test/CR15032 ``` If I tried to expand just 15032, git would be unsure whether I wanted to search SHA-1's or branch names, and my choices would be somewhat limited. **Avoid long descriptive names** Long branch names can be very helpful when you are looking at a list of branches. But it can get in the way when looking at decorated one-line logs as the branch names can eat up most of the single line and abbreviate the visible part of the log. On the other hand long branch names can be more helpful in "merge commits" if you do not habitually rewrite them by hand. The default merge commit message is `Merge branch 'branch-name'`. You may find it more helpful to have merge messages show up as `Merge branch 'fix/CR15032/crash-when-unformatted-disk-inserted'` instead of just `Merge branch 'fix/CR15032'`.
273,711
<p>I have an Eclipse RCP application that displays a lot (10k+) of small images next to each other, like a film strip. For each image, I am using a SWT <code>Image</code> object. This uses an excessive amount of memory and resources. I am looking for a more efficient way. I thought of taking all of these images and concatenating them by creating an <code>ImageData</code> object of the proper total, concatenated width (with a constant height) and using <code>setPixel()</code> for the rest of the pixels. However, the <code>Palette</code> used in the <code>ImageData</code> constructor I can't figure out.</p> <p>I also searched for SWT tiling or mosaic functionality to create one image from a group of images, but found nothing.</p> <p>Any ideas how I can display thousands of small images next to each other efficiently? Please note that once the images are displayed, they are not manipulated, so this is a one-time cost.</p>
[ { "answer_id": 287468, "author": "alexmcchessers", "author_id": 998, "author_profile": "https://Stackoverflow.com/users/998", "pm_score": 0, "selected": false, "text": "<p>Presumably not every image is visible on screen at any one time? Perhaps a better solution would be to only load the images when they become (or are about to become) visible, disposing of them when they have been scrolled off the screen. Obviously you'd want to keep a few in memory on either side of the current viewport in order to make a smooth transition for the user.</p>\n" }, { "answer_id": 287491, "author": "Scott Wegner", "author_id": 33791, "author_profile": "https://Stackoverflow.com/users/33791", "pm_score": 0, "selected": false, "text": "<p>I previously worked with a Java application to create photomosaics, and found it very difficult to achieve adequate performance and memory usage using the java imaging (JAI) libraries and SWT. Although we weren't using nearly as many images as you mention, one route was to rely on a utilities outside of java. In particular, you could use ImageMagick command-line utilities to stitch together your mosaic, and the load the completed memory from disk. If you want to get fancy, there is also a C++ API for ImageMagick, which is very efficient in memory.</p>\n" }, { "answer_id": 290904, "author": "Herman Lintvelt", "author_id": 27602, "author_profile": "https://Stackoverflow.com/users/27602", "pm_score": 3, "selected": true, "text": "<p>You can draw directly on the GC (graphics context) of a new (big) image. Having one big Image should result in much less resource usage than thousands of smaller images (each image in SWT keeps some OS graphics object handle)</p>\n\n<p>What you can try is something like this:</p>\n\n<pre><code> final List&lt;Image&gt; images;\n final Image bigImage = new Image(Display.getCurrent(), combinedWidth, height);\n final GC gc = new GC(bigImage);\n //loop thru all the images while increasing x as necessary:\n int x = 0;\n int y = 0;\n for (Image curImage : images) {\n gc.drawImage(curImage, x, y);\n x += curImage.getBounds().width;\n }\n //very important to dispose GC!!!\n gc.dispose();\n //now you can use bigImage\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/725/" ]
I have an Eclipse RCP application that displays a lot (10k+) of small images next to each other, like a film strip. For each image, I am using a SWT `Image` object. This uses an excessive amount of memory and resources. I am looking for a more efficient way. I thought of taking all of these images and concatenating them by creating an `ImageData` object of the proper total, concatenated width (with a constant height) and using `setPixel()` for the rest of the pixels. However, the `Palette` used in the `ImageData` constructor I can't figure out. I also searched for SWT tiling or mosaic functionality to create one image from a group of images, but found nothing. Any ideas how I can display thousands of small images next to each other efficiently? Please note that once the images are displayed, they are not manipulated, so this is a one-time cost.
You can draw directly on the GC (graphics context) of a new (big) image. Having one big Image should result in much less resource usage than thousands of smaller images (each image in SWT keeps some OS graphics object handle) What you can try is something like this: ``` final List<Image> images; final Image bigImage = new Image(Display.getCurrent(), combinedWidth, height); final GC gc = new GC(bigImage); //loop thru all the images while increasing x as necessary: int x = 0; int y = 0; for (Image curImage : images) { gc.drawImage(curImage, x, y); x += curImage.getBounds().width; } //very important to dispose GC!!! gc.dispose(); //now you can use bigImage ```
273,721
<p>I wonder if there is an example which html files and java files are resides in different folders. </p>
[ { "answer_id": 273818, "author": "Loren_", "author_id": 13703, "author_profile": "https://Stackoverflow.com/users/13703", "pm_score": 3, "selected": false, "text": "<p>I don't recommend using a separate page directory unless you are quite comfortable with how resource streams work, which I am not.</p>\n\n<p>The vast majority of wicket projects I have seen keep class and html files in the source directory. I tried separating them myself but then found that getting my hands on other resources, like images and such, was a hassle; so, I wound up putting those resources in the package directory - in the end I had resources in several different places and it was more of a mess than putting everything in package directory would have been. </p>\n\n<p>That said, here's the code I used to put my html templates in a separate folder. It should be added to Init() in your application class.</p>\n\n<pre><code>IResourceSettings resourceSettings = getResourceSettings();\nresourceSettings.addResourceFolder(\"pages\"); //the full path to your folder, relative to the context root\nresourceSettings.setResourceStreamLocator((IResourceStreamLocator) new PathStripperLocator());\n</code></pre>\n\n<p><a href=\"https://cwiki.apache.org/confluence/display/WICKET/Control+where+HTML+files+are+loaded+from\" rel=\"nofollow noreferrer\">https://cwiki.apache.org/confluence/display/WICKET/Control+where+HTML+files+are+loaded+from</a> has a tutorial on this.</p>\n" }, { "answer_id": 278173, "author": "laz", "author_id": 8753, "author_profile": "https://Stackoverflow.com/users/8753", "pm_score": 0, "selected": false, "text": "<p>This is one area where using Maven to manage your project is very nice. Since Maven has two locations that are included on the classpath, you can logically separate the Java source and the HTML files and still have them maintain the same package structure. The Java code goes into src/main/java and the HTML goes into src/main/resources. When building or running the code both of these locations are added to the classpath.</p>\n\n<p>If Maven isn't for you perhaps this idea could be applied to whatever environment you are using.</p>\n" }, { "answer_id": 326827, "author": "ThaDon", "author_id": 33689, "author_profile": "https://Stackoverflow.com/users/33689", "pm_score": 2, "selected": false, "text": "<p>I use Maven (as the user above points out) and typically put all my .html pages in <code>src/main/resources/same/package/name/as/corresponding/java/file</code></p>\n\n<p>I find this works nicely as my designers can checkout the base package from the resources folder and they don't get confused by all the .java files (and more importantly they don't accidentally change them!)</p>\n\n<p>I made a <a href=\"http://www.nabble.com/-OT--Making-it-easy-for-Designers-in-my-Wicket-project-td12595352.html#a12908330\" rel=\"nofollow noreferrer\">post to the mailing list</a> if you are interested.</p>\n" }, { "answer_id": 450057, "author": "emeraldjava", "author_id": 55794, "author_profile": "https://Stackoverflow.com/users/55794", "pm_score": 1, "selected": false, "text": "<p>I use seperate folders for my java and html wicket source files, but my ant build process then copies the html to the classes folder of my web app so i avoid issues of having to setup wicket resource settings. </p>\n\n<p>My basic build.properties has</p>\n\n<pre><code>\nweb.root = ${project.home}/web\nweb.java.dir = ${web.root}/java\nweb.html.dir = ${web.root}/html\n\nwar.root = ${project.home}/war\nweb.inf.dir = ${war.root}/WEB-INF\nwar.lib.dir = ${web.inf.dir}/lib\nwar.classes.dir = ${web.inf.dir}/classes\n\nwicket.version = 1.3.5\nwicket.jar = ${war.lib.dir}/wicket-${wicket.version}.jar\nwicket-extend.jar = ${war.lib.dir}/wicket-extensions-${wicket.version}.jar\nwicket-spring.jar = ${war.lib.dir}/wicket-spring-${wicket.version}.jar\n</code></pre>\n\n<p>and the compile / assemble ant targets look like</p>\n\n<pre><code>&lt;target name=\"compile-web\"&gt;\n &lt;path id=\"wicket.build.classpath\"&gt;\n &lt;filelist&gt;\n &lt;file name=\"${wicket.jar}\"/&gt;\n &lt;file name=\"${wicket-extend.jar}\"/&gt;\n &lt;file name=\"${wicket-spring.jar}\"/&gt;\n &lt;file name=\"${externaljars.path}/spring/2.5.6/spring.jar\"/&gt;\n &lt;/filelist&gt;\n &lt;/path&gt;\n\n &lt;javac destdir=\"${war.classes.dir}\" classpathref=\"wicket.build.classpath\" \n debug=\"on\" srcdir=\"${web.java.dir}\"&gt;\n &lt;include name=\"**/*.java\"/&gt;\n &lt;/javac&gt;\n&lt;/target&gt;\n\n&lt;target name=\"assemble-war\" depends=\"compile-web\"&gt;\n &lt;copy todir=\"${war.classes.dir}\" overwrite=\"true\"&gt;\n &lt;fileset dir=\"${web.html.dir}\"/&gt;\n &lt;/copy&gt;\n &lt;delete file=\"${dist.dir}/validationservice.war\"/&gt;\n &lt;war destfile=\"${dist.dir}/validationservice.war\" webxml=\"${web.inf.dir}/web.xml\" basedir=\"${war.dir}\"&gt;\n &lt;/war&gt;\n&lt;/target&gt; \n</code></pre>\n" }, { "answer_id": 3016494, "author": "rcl", "author_id": 113800, "author_profile": "https://Stackoverflow.com/users/113800", "pm_score": 2, "selected": false, "text": "<p>I'm not a fan of having the HTML files residing inside the <code>src/main/resources</code> folder. I think the simplest way to handle this and obtain a clean separation in version control and within your project is to use the last set up in <a href=\"https://cwiki.apache.org/WICKET/control-where-html-files-are-loaded-from.html\" rel=\"nofollow noreferrer\">the Wicket article</a> linked by perilandmishap:</p>\n\n<pre><code>&lt;project&gt;\n[...]\n &lt;build&gt;\n &lt;resources&gt;\n &lt;resource&gt;\n &lt;filtering&gt;false&lt;/filtering&gt;\n &lt;directory&gt;src/main/html&lt;/directory&gt;\n &lt;/resource&gt;\n &lt;/resources&gt;\n[...]\n &lt;/build&gt;\n[...]\n&lt;/project&gt;\n</code></pre>\n\n<p>So, now all your HTML files will be in the new, separate HTML folder but still merged with your Java classes. Just remember you would still use the package naming scheme within the HTML folder, i.e. <code>src/main/html/com/your/package</code></p>\n" }, { "answer_id": 3027865, "author": "deamon", "author_id": 238134, "author_profile": "https://Stackoverflow.com/users/238134", "pm_score": 0, "selected": false, "text": "<p>I would put Java and HTML files into the same folder. That would make it much more comfortable to pick the HTML file corresponding to a Java class. Think of a components HTML file as a sort of UI description that would otherwise be written in Java (like with Swing).</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34367/" ]
I wonder if there is an example which html files and java files are resides in different folders.
I don't recommend using a separate page directory unless you are quite comfortable with how resource streams work, which I am not. The vast majority of wicket projects I have seen keep class and html files in the source directory. I tried separating them myself but then found that getting my hands on other resources, like images and such, was a hassle; so, I wound up putting those resources in the package directory - in the end I had resources in several different places and it was more of a mess than putting everything in package directory would have been. That said, here's the code I used to put my html templates in a separate folder. It should be added to Init() in your application class. ``` IResourceSettings resourceSettings = getResourceSettings(); resourceSettings.addResourceFolder("pages"); //the full path to your folder, relative to the context root resourceSettings.setResourceStreamLocator((IResourceStreamLocator) new PathStripperLocator()); ``` <https://cwiki.apache.org/confluence/display/WICKET/Control+where+HTML+files+are+loaded+from> has a tutorial on this.
273,732
<p>I have an application where, in the course of using the application, a user might click from</p> <pre><code>virginia.usa.com </code></pre> <p>to</p> <pre><code>newyork.usa.com </code></pre> <p>Since I'd rather not create a new session each time a user crosses from one subdomain to another, what's a good way to share session info across multiple subdomains?</p>
[ { "answer_id": 273761, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 0, "selected": false, "text": "<p>If you're using PHP, one hack would be to make a little include script (or two) to do the following:</p>\n\n<p>1 Serialize your $_SESSION array\n 2 Pass that string as a hidden input, making all your links to those buttons in separate forms using POST.\n 3 Also include a boolean hidden input to let your script know whether it needs to use the current session or unserialize $_POST['session']\n 4 Deploy this across your site, calling things where appropriate</p>\n\n<p>I wouldn't do this if there's actually a sanctioned way to transfer a session. I hope you've at least considered using cookies.</p>\n" }, { "answer_id": 273775, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "<p>Track your own sessions and use a cookie with an appropriate domain setting, ie. <code>.usa.com</code>.</p>\n\n<p>Alternatively, if you're using PHP, I believe there's a setting to change the default domain setting of the session cookie it uses, that may be useful too.</p>\n\n<p>The settings you're looking for are:</p>\n\n<pre><code>session.use_cookies = 1\nsession.use_only_cookies = 1\nsession.cookie_domain = .usa.com\n</code></pre>\n" }, { "answer_id": 2088853, "author": "Matt Connolly", "author_id": 2845, "author_profile": "https://Stackoverflow.com/users/2845", "pm_score": 6, "selected": true, "text": "<p>You tagged this with ASP.NET and IIS, so I will assume that is your environment. Make sure you have this in your web.config:</p>\n\n<pre><code>&lt;httpCookies domain=\".usa.com\"/&gt;\n</code></pre>\n\n<p>If your 2 subdomains map to the same application, then you are done. However, if they are different applications you will need to do some additional work, like using a SQL Server based Session storage (and hacking the stored procedures to make sure all applications share the same session data) or with an HttpModule to intercept the application name, since even with shared cookies and the same machine key, 2 applications will still use 2 different stores for their session data.</p>\n" }, { "answer_id": 21687318, "author": "Chris", "author_id": 750018, "author_profile": "https://Stackoverflow.com/users/750018", "pm_score": 0, "selected": false, "text": "<p>Matt's answer is definitely the way to go if you have multiple subdomains pointing at the same IIS app (which is exactly the situation I have right now, using wildcard DNS and then doing subdomain 'sniffing' on the receiving end).</p>\n\n<p>However, I wanted to add something that I experienced in case anyone is finding that this is not working for them. Setting the httpCookies line alone didn't do it for me, I had to add a machineKey entry into my web.config file:</p>\n\n<p>machineKey decryptionKey=\"12...D1\" validationKey=\"D7..8B\"</p>\n\n<p>Particularly odd since I am <em>not</em> in a web farm setup (unless AWS/EC2 is effectively acting as such).. As soon as I did this, it worked like a champ.</p>\n" }, { "answer_id": 23796013, "author": "vm0112", "author_id": 3630244, "author_profile": "https://Stackoverflow.com/users/3630244", "pm_score": 2, "selected": false, "text": "<p>I recently went thru this and learned the hard way. Localhost is actually considered a TLD. Cookie domains require at least a second level domain - test.com. If you want cookies to work for a domain and all it's sub-domains, prefix with a '.' - .test.com.</p>\n\n<p>When running/debugging locally, setting a domain of localhost will fail, and it will fail even if the domain is set properly because visual studio uses localhost by default.</p>\n\n<p>This default localhost can be changed in the project properties so that the project will actually run at cookie domain test.com. Essentially, if the address in the browser matches , you can get it to work.</p>\n\n<p>My issue is documented here: <a href=\"https://stackoverflow.com/questions/23620622/setting-servicestack-cookie-domain-in-web-config-causes-session-id-to-change-on\">Setting ServiceStack Cookie Domain in Web.Config Causes Session Id to Change on Every Request</a></p>\n\n<p>Hope this helps.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28118/" ]
I have an application where, in the course of using the application, a user might click from ``` virginia.usa.com ``` to ``` newyork.usa.com ``` Since I'd rather not create a new session each time a user crosses from one subdomain to another, what's a good way to share session info across multiple subdomains?
You tagged this with ASP.NET and IIS, so I will assume that is your environment. Make sure you have this in your web.config: ``` <httpCookies domain=".usa.com"/> ``` If your 2 subdomains map to the same application, then you are done. However, if they are different applications you will need to do some additional work, like using a SQL Server based Session storage (and hacking the stored procedures to make sure all applications share the same session data) or with an HttpModule to intercept the application name, since even with shared cookies and the same machine key, 2 applications will still use 2 different stores for their session data.
273,743
<p>I have a web directory where I store some config files. I'd like to use wget to pull those files down and maintain their current structure. For instance, the remote directory looks like:</p> <pre><code>http://mysite.com/configs/.vim/ </code></pre> <p>.vim holds multiple files and directories. I want to replicate that on the client using wget. Can't seem to find the right combo of wget flags to get this done. Any ideas?</p>
[ { "answer_id": 273755, "author": "Conor McDermottroe", "author_id": 63985, "author_profile": "https://Stackoverflow.com/users/63985", "pm_score": 3, "selected": false, "text": "<pre><code>wget -r http://mysite.com/configs/.vim/\n</code></pre>\n\n<p>works for me.</p>\n\n<p>Perhaps you have a .wgetrc which is interfering with it?</p>\n" }, { "answer_id": 273757, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": -1, "selected": false, "text": "<p>You should be able to do it simply by adding a -r</p>\n\n<pre><code>wget -r http://stackoverflow.com/\n</code></pre>\n" }, { "answer_id": 273776, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 11, "selected": true, "text": "<p>You have to pass the <code>-np</code>/<code>--no-parent</code> option to <code>wget</code> (in addition to <code>-r</code>/<code>--recursive</code>, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:</p>\n\n<pre><code>wget --recursive --no-parent http://example.com/configs/.vim/\n</code></pre>\n\n<p>To avoid downloading the auto-generated <code>index.html</code> files, use the <code>-R</code>/<code>--reject</code> option:</p>\n\n<pre><code>wget -r -np -R \"index.html*\" http://example.com/configs/.vim/\n</code></pre>\n" }, { "answer_id": 5335576, "author": "Sri", "author_id": 435912, "author_profile": "https://Stackoverflow.com/users/435912", "pm_score": 7, "selected": false, "text": "<p>To download a directory recursively, which rejects index.html* files and downloads without the hostname, parent directory and the whole directory structure :</p>\n\n<pre><code>wget -r -nH --cut-dirs=2 --no-parent --reject=\"index.html*\" http://mysite.com/dir1/dir2/data\n</code></pre>\n" }, { "answer_id": 13519665, "author": "Sean Villani", "author_id": 463188, "author_profile": "https://Stackoverflow.com/users/463188", "pm_score": 7, "selected": false, "text": "<p>For anyone else that having similar issues. Wget follows <code>robots.txt</code> which might not allow you to grab the site. No worries, you can turn it off:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>wget -e robots=off http://www.example.com/\n</code></pre>\n\n<p><a href=\"http://www.gnu.org/software/wget/manual/html_node/Robot-Exclusion.html\">http://www.gnu.org/software/wget/manual/html_node/Robot-Exclusion.html</a></p>\n" }, { "answer_id": 14894734, "author": "Erich Eichinger", "author_id": 51264, "author_profile": "https://Stackoverflow.com/users/51264", "pm_score": 5, "selected": false, "text": "<p>Here's the complete wget command that worked for me to download files from a server's directory (ignoring <code>robots.txt</code>):</p>\n\n<pre><code>wget -e robots=off --cut-dirs=3 --user-agent=Mozilla/5.0 --reject=\"index.html*\" --no-parent --recursive --relative --level=1 --no-directories http://www.example.com/archive/example/5.3.0/\n</code></pre>\n" }, { "answer_id": 16587702, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>If <code>--no-parent</code> not help, you might use <code>--include</code> option.</p>\n\n<p>Directory struct:</p>\n\n<pre><code>http://&lt;host&gt;/downloads/good\nhttp://&lt;host&gt;/downloads/bad\n</code></pre>\n\n<p>And you want to download <code>downloads/good</code> but not <code>downloads/bad</code> directory:</p>\n\n<pre><code>wget --include downloads/good --mirror --execute robots=off --no-host-directories --cut-dirs=1 --reject=\"index.html*\" --continue http://&lt;host&gt;/downloads/good\n</code></pre>\n" }, { "answer_id": 21983475, "author": "SamGoody", "author_id": 87520, "author_profile": "https://Stackoverflow.com/users/87520", "pm_score": 5, "selected": false, "text": "<p>You should use the -m (mirror) flag, as that takes care to not mess with timestamps and to recurse indefinitely.</p>\n\n<pre><code>wget -m http://example.com/configs/.vim/\n</code></pre>\n\n<p>If you add the points mentioned by others in this thread, it would be:</p>\n\n<pre><code>wget -m -e robots=off --no-parent http://example.com/configs/.vim/\n</code></pre>\n" }, { "answer_id": 26478435, "author": "prayagupa", "author_id": 432903, "author_profile": "https://Stackoverflow.com/users/432903", "pm_score": 3, "selected": false, "text": "<p>To fetch a directory recursively with username and password, use the following command: </p>\n\n<pre><code>wget -r --user=(put username here) --password='(put password here)' --no-parent http://example.com/\n</code></pre>\n" }, { "answer_id": 42501032, "author": "Devon", "author_id": 3008405, "author_profile": "https://Stackoverflow.com/users/3008405", "pm_score": 2, "selected": false, "text": "<p>Wget 1.18 may work better, e.g., I got bitten by a version 1.12 bug where...</p>\n\n<pre><code>wget --recursive (...)\n</code></pre>\n\n<p>...only retrieves index.html instead of all files.</p>\n\n<p>Workaround was to notice some 301 redirects and try the new location — given the new URL, wget got all the files in the directory.</p>\n" }, { "answer_id": 46820751, "author": "rkok", "author_id": 3018750, "author_profile": "https://Stackoverflow.com/users/3018750", "pm_score": 3, "selected": false, "text": "<p>This version downloads recursively and doesn't create parent directories.</p>\n\n<pre><code>wgetod() {\n NSLASH=\"$(echo \"$1\" | perl -pe 's|.*://[^/]+(.*?)/?$|\\1|' | grep -o / | wc -l)\"\n NCUT=$((NSLASH &gt; 0 ? NSLASH-1 : 0))\n wget -r -nH --user-agent=Mozilla/5.0 --cut-dirs=$NCUT --no-parent --reject=\"index.html*\" \"$1\"\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<ol>\n<li>Add to <code>~/.bashrc</code> or paste into terminal</li>\n<li><code>wgetod \"http://example.com/x/\"</code></li>\n</ol>\n" }, { "answer_id": 49063898, "author": "Jordan Gee", "author_id": 416688, "author_profile": "https://Stackoverflow.com/users/416688", "pm_score": 2, "selected": false, "text": "<p>All you need is two flags, one is <code>\"-r\"</code> for recursion and <code>\"--no-parent\"</code> (or <code>-np</code>) in order not to go in the <code>'.'</code> and <code>\"..\"</code> . Like this:</p>\n\n<p><code>wget -r --no-parent http://example.com/configs/.vim/</code></p>\n\n<p>That's it. It will download into the following local tree: <code>./example.com/configs/.vim</code> .\nHowever if you do not want the first two directories, then use the additional flag <code>--cut-dirs=2</code> as suggested in earlier replies:</p>\n\n<p><code>wget -r --no-parent --cut-dirs=2 http://example.com/configs/.vim/</code></p>\n\n<p>And it will download your file tree only into <code>./.vim/</code></p>\n\n<p>In fact, I got the first line from this answer precisely from the <a href=\"https://www.gnu.org/software/wget/manual/wget.html#Directory_002dBased-Limits\" rel=\"nofollow noreferrer\">wget manual</a>, they have a very clean example towards the end of section 4.3.</p>\n" }, { "answer_id": 57834913, "author": "pr-pal", "author_id": 5785743, "author_profile": "https://Stackoverflow.com/users/5785743", "pm_score": 2, "selected": false, "text": "<p>The following option seems to be the perfect combination when dealing with recursive download:</p>\n\n<p>wget -nd -np -P /dest/dir --recursive <a href=\"http://url/dir1/dir2\" rel=\"nofollow noreferrer\">http://url/dir1/dir2</a></p>\n\n<p>Relevant snippets from man pages for convenience:</p>\n\n<pre><code> -nd\n --no-directories\n Do not create a hierarchy of directories when retrieving recursively. With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the\n filenames will get extensions .n).\n\n\n -np\n --no-parent\n Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.\n</code></pre>\n" }, { "answer_id": 62584994, "author": "Tumelo Mapheto", "author_id": 12005685, "author_profile": "https://Stackoverflow.com/users/12005685", "pm_score": 1, "selected": false, "text": "<p>Recursive wget ignoring robots (for websites)</p>\n<pre><code>wget -e robots=off -r -np --page-requisites --convert-links 'http://example.com/folder/'\n</code></pre>\n<p>-e robots=off causes it to ignore robots.txt for that domain</p>\n<p>-r makes it recursive</p>\n<p>-np = no parents, so it doesn't follow links up to the parent folder</p>\n" }, { "answer_id": 65442746, "author": "berezovskyi", "author_id": 464590, "author_profile": "https://Stackoverflow.com/users/464590", "pm_score": 3, "selected": false, "text": "<p>First of all, thanks to everyone who posted their answers. Here is my &quot;ultimate&quot; wget script to download a website recursively:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>wget --recursive ${comment# self-explanatory} \\\n --no-parent ${comment# will not crawl links in folders above the base of the URL} \\\n --convert-links ${comment# convert links with the domain name to relative and uncrawled to absolute} \\\n --random-wait --wait 3 --no-http-keep-alive ${comment# do not get banned} \\\n --no-host-directories ${comment# do not create folders with the domain name} \\\n --execute robots=off --user-agent=Mozilla/5.0 ${comment# I AM A HUMAN!!!} \\\n --level=inf --accept '*' ${comment# do not limit to 5 levels or common file formats} \\\n --reject=&quot;index.html*&quot; ${comment# use this option if you need an exact mirror} \\\n --cut-dirs=0 ${comment# replace 0 with the number of folders in the path, 0 for the whole domain} \\\n$URL\n</code></pre>\n<p>Afterwards, <a href=\"https://superuser.com/questions/61025/how-can-i-make-wget-rename-downloaded-files-to-not-include-the-query-string\">stripping the query params</a> from URLs like <code>main.css?crc=12324567</code> and running a local server (e.g. via <code>python3 -m http.server</code> in the dir you just wget'ed) to run JS may be necessary. Please note that the <code>--convert-links</code> option kicks in only after the full crawl was completed.</p>\n<p>Also, if you are trying to wget a website that may go down soon, you should <a href=\"https://www.archiveteam.org/index.php?title=ArchiveBot\" rel=\"noreferrer\">get in touch with the ArchiveTeam</a> and ask them to add your website to their ArchiveBot queue.</p>\n" }, { "answer_id": 69024542, "author": "SentientFlesh", "author_id": 11019416, "author_profile": "https://Stackoverflow.com/users/11019416", "pm_score": 2, "selected": false, "text": "<p>It sounds like you're trying to get a mirror of your file. While <code>wget</code> has some interesting FTP and SFTP uses, a simple mirror should work. Just a few considerations to make sure you're able to download the file properly.</p>\n<h2>Respect <code>robots.txt</code></h2>\n<p>Ensure that if you have a <code>/robots.txt</code> file in your <code>public_html</code>, <code>www</code>, or <code>configs</code> directory it does not prevent crawling. If it does, you need to instruct <code>wget</code> to ignore it using the following option in your <code>wget</code> command by adding:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>wget -e robots=off 'http://your-site.com/configs/.vim/'\n</code></pre>\n<h2>Convert remote links to local files.</h2>\n<p>Additionally, <code>wget</code> must be <strong>instructed</strong> to convert links into downloaded files. If you've done everything above correctly, you should be fine here. The easiest way I've found to get all files, provided nothing is hidden behind a non-public directory, is using the <code>mirror</code> command.</p>\n<h3>Try this:</h3>\n<pre class=\"lang-sh prettyprint-override\"><code>wget -mpEk 'http://your-site.com/configs/.vim/'\n\n# If robots.txt is present:\n\nwget -mpEk robots=off 'http://your-site.com/configs/.vim/'\n\n# Good practice to only deal with the highest level directory you specify (instead of downloading all of `mysite.com` you're just mirroring from `.vim`\n\nwget -mpEk robots=off --no-parent 'http://your-site.com/configs/.vim/'\n</code></pre>\n<p>Using <code>-m</code> instead of <code>-r</code> is preferred as it doesn't have a maximum recursion depth and it downloads all assets. Mirror is pretty good at determining the full depth of a site, however if you have many external links you could end up downloading more than just your site, which is why we use <code>-p -E -k</code>. All pre-requisite files to make the page, and a preserved directory structure should be the output. <code>-k</code> converts links to local files.\nSince you should have a link set up, you should get your config folder with a file <code>/.vim</code>.</p>\n<p>Mirror mode also works with a directory structure that's set up as an <code>ftp://</code> also.</p>\n<h3>General rule of thumb:</h3>\n<p>Depending on the side of the site you are doing a mirror of, you're sending many calls to the server. In order to prevent you from being blacklisted or cut off, use the <code>wait</code> option to rate-limit your downloads.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>wget -mpEk --no-parent robots=off --random-wait 'http://your-site.com/configs/.vim/'\n</code></pre>\n<p>But if you're simply downloading the <code>../config/.vim/</code> file you shouldn't have to worry about it as your ignoring parent directories and downloading a single file.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476/" ]
I have a web directory where I store some config files. I'd like to use wget to pull those files down and maintain their current structure. For instance, the remote directory looks like: ``` http://mysite.com/configs/.vim/ ``` .vim holds multiple files and directories. I want to replicate that on the client using wget. Can't seem to find the right combo of wget flags to get this done. Any ideas?
You have to pass the `-np`/`--no-parent` option to `wget` (in addition to `-r`/`--recursive`, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this: ``` wget --recursive --no-parent http://example.com/configs/.vim/ ``` To avoid downloading the auto-generated `index.html` files, use the `-R`/`--reject` option: ``` wget -r -np -R "index.html*" http://example.com/configs/.vim/ ```
273,751
<p>I have a SSIS package that eventually I would like to pass parameters too, these parameters will come from a .NET application (VB or C#) so I was curious if anyone knows of how to do this, or better yet a website with helpful hints on how to do it. </p> <p>So basically I want to execute a SSIS package from .NET passing the SSIS package parameters that it can use within it. </p> <p>For instance, the SSIS package will use flat file importing into a SQL db however the Path and name of the file could be the parameter that is passed from the .Net application.</p>
[ { "answer_id": 1920083, "author": "Craig Schwarze", "author_id": 226235, "author_profile": "https://Stackoverflow.com/users/226235", "pm_score": 6, "selected": false, "text": "<p>Here is how to set variables in the package from code - </p>\n\n<pre><code>using Microsoft.SqlServer.Dts.Runtime;\n\nprivate void Execute_Package()\n { \n string pkgLocation = @\"c:\\test.dtsx\";\n\n Package pkg;\n Application app;\n DTSExecResult pkgResults;\n Variables vars;\n\n app = new Application();\n pkg = app.LoadPackage(pkgLocation, null);\n\n vars = pkg.Variables;\n vars[\"A_Variable\"].Value = \"Some value\"; \n\n pkgResults = pkg.Execute(null, vars, null, null, null);\n\n if (pkgResults == DTSExecResult.Success)\n Console.WriteLine(\"Package ran successfully\");\n else\n Console.WriteLine(\"Package failed\");\n }\n</code></pre>\n" }, { "answer_id": 26012658, "author": "Faiz", "author_id": 82961, "author_profile": "https://Stackoverflow.com/users/82961", "pm_score": 3, "selected": false, "text": "<p>To add to @Craig Schwarze answer,</p>\n\n<p>Here are some related MSDN links:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms136090.aspx\">Loading and Running a Local Package Programmatically:</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms403355.aspx\">Loading and Running a Remote Package Programmatically</a></p>\n\n<p>Capturing Events from a Running Package:</p>\n\n<pre><code>using System;\nusing Microsoft.SqlServer.Dts.Runtime;\n\nnamespace RunFromClientAppWithEventsCS\n{\n class MyEventListener : DefaultEvents\n {\n public override bool OnError(DtsObject source, int errorCode, string subComponent, \n string description, string helpFile, int helpContext, string idofInterfaceWithError)\n {\n // Add application-specific diagnostics here.\n Console.WriteLine(\"Error in {0}/{1} : {2}\", source, subComponent, description);\n return false;\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n string pkgLocation;\n Package pkg;\n Application app;\n DTSExecResult pkgResults;\n\n MyEventListener eventListener = new MyEventListener();\n\n pkgLocation =\n @\"C:\\Program Files\\Microsoft SQL Server\\100\\Samples\\Integration Services\" +\n @\"\\Package Samples\\CalculatedColumns Sample\\CalculatedColumns\\CalculatedColumns.dtsx\";\n app = new Application();\n pkg = app.LoadPackage(pkgLocation, eventListener);\n pkgResults = pkg.Execute(null, null, eventListener, null, null);\n\n Console.WriteLine(pkgResults.ToString());\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 28603315, "author": "Paul Hatcher", "author_id": 102792, "author_profile": "https://Stackoverflow.com/users/102792", "pm_score": 5, "selected": false, "text": "<p>Here's how do to it with the SSDB catalog that was introduced with SQL Server 2012...</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Data.SqlClient;\n\nusing Microsoft.SqlServer.Management.IntegrationServices;\n\npublic List&lt;string&gt; ExecutePackage(string folder, string project, string package)\n{\n // Connection to the database server where the packages are located\n SqlConnection ssisConnection = new SqlConnection(@\"Data Source=.\\SQL2012;Initial Catalog=master;Integrated Security=SSPI;\");\n\n // SSIS server object with connection\n IntegrationServices ssisServer = new IntegrationServices(ssisConnection);\n\n // The reference to the package which you want to execute\n PackageInfo ssisPackage = ssisServer.Catalogs[\"SSISDB\"].Folders[folder].Projects[project].Packages[package];\n\n // Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)\n Collection&lt;PackageInfo.ExecutionValueParameterSet&gt; executionParameter = new Collection&lt;PackageInfo.ExecutionValueParameterSet&gt;();\n\n // Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized\n executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = \"SYNCHRONIZED\", ParameterValue = 1 });\n\n // Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)\n executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = \"LOGGING_LEVEL\", ParameterValue = 3 });\n\n // Add a project parameter (value) to fill a project parameter\n executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = \"MyProjectParameter\", ParameterValue = \"some value\" });\n\n // Add a project package (value) to fill a package parameter\n executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = \"MyPackageParameter\", ParameterValue = \"some value\" });\n\n // Get the identifier of the execution to get the log\n long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);\n\n // Loop through the log and do something with it like adding to a list\n var messages = new List&lt;string&gt;();\n foreach (OperationMessage message in ssisServer.Catalogs[\"SSISDB\"].Executions[executionIdentifier].Messages)\n {\n messages.Add(message.MessageType + \": \" + message.Message);\n }\n\n return messages;\n}\n</code></pre>\n\n<p>The code is a slight adaptation of <a href=\"http://social.technet.microsoft.com/wiki/contents/articles/21978.execute-ssis-2012-package-with-parameters-via-net.aspx?CommentPosted=true#commentmessage\">http://social.technet.microsoft.com/wiki/contents/articles/21978.execute-ssis-2012-package-with-parameters-via-net.aspx?CommentPosted=true#commentmessage</a></p>\n\n<p>There is also a similar article at <a href=\"http://domwritescode.com/2014/05/15/project-deployment-model-changes/\">http://domwritescode.com/2014/05/15/project-deployment-model-changes/</a></p>\n" }, { "answer_id": 49421794, "author": "Ayan Chakraborty", "author_id": 9411269, "author_profile": "https://Stackoverflow.com/users/9411269", "pm_score": 1, "selected": false, "text": "<p>So there is another way you can actually fire it from any language.\nThe best way I think, you can just create a batch file which will call your .dtsx package.</p>\n\n<p>Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.</p>\n\n<p>Below is a blog for more details.. </p>\n\n<p><a href=\"https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/\" rel=\"nofollow noreferrer\">https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/</a></p>\n\n<p>Happy coding.. :)</p>\n\n<p>Thanks,\nAyan</p>\n" }, { "answer_id": 58619403, "author": "rafayel ahmed", "author_id": 5263516, "author_profile": "https://Stackoverflow.com/users/5263516", "pm_score": 0, "selected": false, "text": "<p>You can use this Function if you have some variable in the SSIS.</p>\n\n<pre><code> Package pkg;\n\n Microsoft.SqlServer.Dts.Runtime.Application app;\n DTSExecResult pkgResults;\n Variables vars;\n\n app = new Microsoft.SqlServer.Dts.Runtime.Application();\n pkg = app.LoadPackage(\" Location of your SSIS package\", null);\n\n vars = pkg.Variables;\n\n // your variables\n vars[\"somevariable1\"].Value = \"yourvariable1\";\n vars[\"somevariable2\"].Value = \"yourvariable2\";\n\n pkgResults = pkg.Execute(null, vars, null, null, null);\n\n if (pkgResults == DTSExecResult.Success)\n {\n Console.WriteLine(\"Package ran successfully\");\n }\n else\n {\n\n Console.WriteLine(\"Package failed\");\n }\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a SSIS package that eventually I would like to pass parameters too, these parameters will come from a .NET application (VB or C#) so I was curious if anyone knows of how to do this, or better yet a website with helpful hints on how to do it. So basically I want to execute a SSIS package from .NET passing the SSIS package parameters that it can use within it. For instance, the SSIS package will use flat file importing into a SQL db however the Path and name of the file could be the parameter that is passed from the .Net application.
Here is how to set variables in the package from code - ``` using Microsoft.SqlServer.Dts.Runtime; private void Execute_Package() { string pkgLocation = @"c:\test.dtsx"; Package pkg; Application app; DTSExecResult pkgResults; Variables vars; app = new Application(); pkg = app.LoadPackage(pkgLocation, null); vars = pkg.Variables; vars["A_Variable"].Value = "Some value"; pkgResults = pkg.Execute(null, vars, null, null, null); if (pkgResults == DTSExecResult.Success) Console.WriteLine("Package ran successfully"); else Console.WriteLine("Package failed"); } ```
273,789
<p>In javascript, is there an equivalent of String.indexOf() that takes a regular expression instead of a string for the first first parameter while still allowing a second parameter ?</p> <p>I need to do something like </p> <pre><code>str.indexOf(/[abc]/ , i); </code></pre> <p>and</p> <pre><code>str.lastIndexOf(/[abc]/ , i); </code></pre> <p>While String.search() takes a regexp as a parameter it does not allow me to specify a second argument!</p> <p>Edit:<br> This turned out to be harder than I originally thought so I wrote a small test function to test all the provided solutions... it assumes regexIndexOf and regexLastIndexOf have been added to the String object.</p> <pre><code>function test (str) { var i = str.length +2; while (i--) { if (str.indexOf('a',i) != str.regexIndexOf(/a/,i)) alert (['failed regexIndexOf ' , str,i , str.indexOf('a',i) , str.regexIndexOf(/a/,i)]) ; if (str.lastIndexOf('a',i) != str.regexLastIndexOf(/a/,i) ) alert (['failed regexLastIndexOf ' , str,i,str.lastIndexOf('a',i) , str.regexLastIndexOf(/a/,i)]) ; } } </code></pre> <p>and I am testing as follow to make sure that at least for one character regexp, the result is the same as if we used indexOf</p> <p>//Look for the a among the xes<br> test('xxx');<br> test('axx');<br> test('xax');<br> test('xxa');<br> test('axa');<br> test('xaa');<br> test('aax');<br> test('aaa'); </p>
[ { "answer_id": 273797, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": false, "text": "<p>You could use substr.</p>\n\n<pre><code>str.substr(i).match(/[abc]/);\n</code></pre>\n" }, { "answer_id": 273810, "author": "Glenn", "author_id": 25191, "author_profile": "https://Stackoverflow.com/users/25191", "pm_score": 8, "selected": false, "text": "<p>Instances of the <code>String</code> constructor have a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search\" rel=\"noreferrer\"><code>.search()</code> method</a> which accepts a RegExp and returns the index of the first match.</p>\n\n<p>To start the search from a particular position (faking the second parameter of <code>.indexOf()</code>) you can <code>slice</code> off the first <code>i</code> characters:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>str.slice(i).search(/re/)\n</code></pre>\n\n<p>But this will get the index in the shorter string (after the first part was sliced off) so you'll want to then add the length of the chopped off part (<code>i</code>) to the returned index if it wasn't <code>-1</code>. This will give you the index in the original string:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function regexIndexOf(text, re, i) {\n var indexInSuffix = text.slice(i).search(re);\n return indexInSuffix &lt; 0 ? indexInSuffix : indexInSuffix + i;\n}\n</code></pre>\n" }, { "answer_id": 273829, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "<p>It does not natively, but you certainly can add this functionality</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n\nString.prototype.regexIndexOf = function( pattern, startIndex )\n{\n startIndex = startIndex || 0;\n var searchResult = this.substr( startIndex ).search( pattern );\n return ( -1 === searchResult ) ? -1 : searchResult + startIndex;\n}\n\nString.prototype.regexLastIndexOf = function( pattern, startIndex )\n{\n startIndex = startIndex === undefined ? this.length : startIndex;\n var searchResult = this.substr( 0, startIndex ).reverse().regexIndexOf( pattern, 0 );\n return ( -1 === searchResult ) ? -1 : this.length - ++searchResult;\n}\n\nString.prototype.reverse = function()\n{\n return this.split('').reverse().join('');\n}\n\n// Indexes 0123456789\nvar str = 'caabbccdda';\n\nalert( [\n str.regexIndexOf( /[cd]/, 4 )\n , str.regexLastIndexOf( /[cd]/, 4 )\n , str.regexIndexOf( /[yz]/, 4 )\n , str.regexLastIndexOf( /[yz]/, 4 )\n , str.lastIndexOf( 'd', 4 )\n , str.regexLastIndexOf( /d/, 4 )\n , str.lastIndexOf( 'd' )\n , str.regexLastIndexOf( /d/ )\n ]\n);\n\n&lt;/script&gt;\n</code></pre>\n\n<p>I didn't fully test these methods, but they seem to work so far.</p>\n" }, { "answer_id": 273902, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": false, "text": "<p>Based on BaileyP's answer. The main difference is that these methods return <code>-1</code> if the pattern can't be matched.</p>\n\n<p><strong>Edit:</strong> Thanks to Jason Bunting's answer I got an idea. Why not modify the <code>.lastIndex</code> property of the regex? Though this will only work for patterns with the global flag (<code>/g</code>).</p>\n\n<p><strong>Edit:</strong> Updated to pass the test-cases.</p>\n\n<pre><code>String.prototype.regexIndexOf = function(re, startPos) {\n startPos = startPos || 0;\n\n if (!re.global) {\n var flags = \"g\" + (re.multiline?\"m\":\"\") + (re.ignoreCase?\"i\":\"\");\n re = new RegExp(re.source, flags);\n }\n\n re.lastIndex = startPos;\n var match = re.exec(this);\n\n if (match) return match.index;\n else return -1;\n}\n\nString.prototype.regexLastIndexOf = function(re, startPos) {\n startPos = startPos === undefined ? this.length : startPos;\n\n if (!re.global) {\n var flags = \"g\" + (re.multiline?\"m\":\"\") + (re.ignoreCase?\"i\":\"\");\n re = new RegExp(re.source, flags);\n }\n\n var lastSuccess = -1;\n for (var pos = 0; pos &lt;= startPos; pos++) {\n re.lastIndex = pos;\n\n var match = re.exec(this);\n if (!match) break;\n\n pos = match.index;\n if (pos &lt;= startPos) lastSuccess = pos;\n }\n\n return lastSuccess;\n}\n</code></pre>\n" }, { "answer_id": 273954, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": -1, "selected": false, "text": "<p>Well, as you are just looking to match the position of a <em>character</em> , regex is possibly overkill. </p>\n\n<p>I presume all you want is, instead of \"find first of these this character\" , just find first of these characters. </p>\n\n<p>This of course is the simple answer, but does what your question sets out to do, albeit without the regex part ( because you didn't clarify why specifically it had to be a regex )</p>\n\n<pre><code>function mIndexOf( str , chars, offset )\n{\n var first = -1; \n for( var i = 0; i &lt; chars.length; i++ )\n {\n var p = str.indexOf( chars[i] , offset ); \n if( p &lt; first || first === -1 )\n {\n first = p;\n }\n }\n return first; \n}\nString.prototype.mIndexOf = function( chars, offset )\n{\n return mIndexOf( this, chars, offset ); # I'm really averse to monkey patching. \n};\nmIndexOf( \"hello world\", ['a','o','w'], 0 );\n&gt;&gt; 4 \nmIndexOf( \"hello world\", ['a'], 0 );\n&gt;&gt; -1 \nmIndexOf( \"hello world\", ['a','o','w'], 4 );\n&gt;&gt; 4\nmIndexOf( \"hello world\", ['a','o','w'], 5 );\n&gt;&gt; 6\nmIndexOf( \"hello world\", ['a','o','w'], 7 );\n&gt;&gt; -1 \nmIndexOf( \"hello world\", ['a','o','w','d'], 7 );\n&gt;&gt; 10\nmIndexOf( \"hello world\", ['a','o','w','d'], 10 );\n&gt;&gt; 10\nmIndexOf( \"hello world\", ['a','o','w','d'], 11 );\n&gt;&gt; -1\n</code></pre>\n" }, { "answer_id": 274094, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 8, "selected": true, "text": "<p>Combining a few of the approaches already mentioned (the indexOf is obviously rather simple), I think these are the functions that will do the trick:</p>\n<pre><code>function regexIndexOf(string, regex, startpos) {\n var indexOf = string.substring(startpos || 0).search(regex);\n return (indexOf &gt;= 0) ? (indexOf + (startpos || 0)) : indexOf;\n}\n\nfunction regexLastIndexOf(string, regex, startpos) {\n regex = (regex.global) ? regex : new RegExp(regex.source, &quot;g&quot; + (regex.ignoreCase ? &quot;i&quot; : &quot;&quot;) + (regex.multiLine ? &quot;m&quot; : &quot;&quot;));\n if(typeof (startpos) == &quot;undefined&quot;) {\n startpos = string.length;\n } else if(startpos &lt; 0) {\n startpos = 0;\n }\n var stringToWorkWith = string.substring(0, startpos + 1);\n var lastIndexOf = -1;\n var nextStop = 0;\n while((result = regex.exec(stringToWorkWith)) != null) {\n lastIndexOf = result.index;\n regex.lastIndex = ++nextStop;\n }\n return lastIndexOf;\n}\n</code></pre>\n<hr />\n<p>UPDATE: Edited <code>regexLastIndexOf()</code> so that is seems to mimic <code>lastIndexOf()</code> now. Please let me know if it still fails and under what circumstances.</p>\n<hr />\n<p>UPDATE: Passes all tests found on in comments on this page, and my own. Of course, that doesn't mean it's bulletproof. Any feedback appreciated.</p>\n" }, { "answer_id": 274680, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "<p>After having all the proposed solutions fail my tests one way or the other, (edit: some were updated to pass the tests after I wrote this) I found the mozilla implementation for <a href=\"https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:String:indexOf\" rel=\"nofollow noreferrer\">Array.indexOf</a> and <a href=\"https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:String:lastIndexOf\" rel=\"nofollow noreferrer\">Array.lastIndexOf</a></p>\n\n<p>I used those to implement my version of String.prototype.regexIndexOf and String.prototype.regexLastIndexOf as follows:</p>\n\n<pre><code>String.prototype.regexIndexOf = function(elt /*, from*/)\n {\n var arr = this.split('');\n var len = arr.length;\n\n var from = Number(arguments[1]) || 0;\n from = (from &lt; 0) ? Math.ceil(from) : Math.floor(from);\n if (from &lt; 0)\n from += len;\n\n for (; from &lt; len; from++) {\n if (from in arr &amp;&amp; elt.exec(arr[from]) ) \n return from;\n }\n return -1;\n};\n\nString.prototype.regexLastIndexOf = function(elt /*, from*/)\n {\n var arr = this.split('');\n var len = arr.length;\n\n var from = Number(arguments[1]);\n if (isNaN(from)) {\n from = len - 1;\n } else {\n from = (from &lt; 0) ? Math.ceil(from) : Math.floor(from);\n if (from &lt; 0)\n from += len;\n else if (from &gt;= len)\n from = len - 1;\n }\n\n for (; from &gt; -1; from--) {\n if (from in arr &amp;&amp; elt.exec(arr[from]) )\n return from;\n }\n return -1;\n };\n</code></pre>\n\n<p>They seem to pass the test functions I provided in the question.</p>\n\n<p>Obviously they only work if the regular expression matches one character but that is enough for my purpose since I will be using it for things like ( [abc] , \\s , \\W , \\D )</p>\n\n<p>I will keep monitoring the question in case someone provides a better/faster/cleaner/more generic implementation that works on any regular expression.</p>\n" }, { "answer_id": 274850, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 3, "selected": false, "text": "<p><code>RexExp</code> instances have a <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex\" rel=\"noreferrer\">lastIndex</a> property already (if they are global) and so what I'm doing is copying the regular expression, modifying it slightly to suit our purposes, <code>exec</code>-ing it on the string and looking at the <code>lastIndex</code>. This will inevitably be faster than looping on the string. (You have enough examples of how to put this onto the string prototype, right?)</p>\n\n<pre><code>function reIndexOf(reIn, str, startIndex) {\n var re = new RegExp(reIn.source, 'g' + (reIn.ignoreCase ? 'i' : '') + (reIn.multiLine ? 'm' : ''));\n re.lastIndex = startIndex || 0;\n var res = re.exec(str);\n if(!res) return -1;\n return re.lastIndex - res[0].length;\n};\n\nfunction reLastIndexOf(reIn, str, startIndex) {\n var src = /\\$$/.test(reIn.source) &amp;&amp; !/\\\\\\$$/.test(reIn.source) ? reIn.source : reIn.source + '(?![\\\\S\\\\s]*' + reIn.source + ')';\n var re = new RegExp(src, 'g' + (reIn.ignoreCase ? 'i' : '') + (reIn.multiLine ? 'm' : ''));\n re.lastIndex = startIndex || 0;\n var res = re.exec(str);\n if(!res) return -1;\n return re.lastIndex - res[0].length;\n};\n\nreIndexOf(/[abc]/, \"tommy can eat\"); // Returns 6\nreIndexOf(/[abc]/, \"tommy can eat\", 8); // Returns 11\nreLastIndexOf(/[abc]/, \"tommy can eat\"); // Returns 11\n</code></pre>\n\n<p>You could also prototype the functions onto the RegExp object:</p>\n\n<pre><code>RegExp.prototype.indexOf = function(str, startIndex) {\n var re = new RegExp(this.source, 'g' + (this.ignoreCase ? 'i' : '') + (this.multiLine ? 'm' : ''));\n re.lastIndex = startIndex || 0;\n var res = re.exec(str);\n if(!res) return -1;\n return re.lastIndex - res[0].length;\n};\n\nRegExp.prototype.lastIndexOf = function(str, startIndex) {\n var src = /\\$$/.test(this.source) &amp;&amp; !/\\\\\\$$/.test(this.source) ? this.source : this.source + '(?![\\\\S\\\\s]*' + this.source + ')';\n var re = new RegExp(src, 'g' + (this.ignoreCase ? 'i' : '') + (this.multiLine ? 'm' : ''));\n re.lastIndex = startIndex || 0;\n var res = re.exec(str);\n if(!res) return -1;\n return re.lastIndex - res[0].length;\n};\n\n\n/[abc]/.indexOf(\"tommy can eat\"); // Returns 6\n/[abc]/.indexOf(\"tommy can eat\", 8); // Returns 11\n/[abc]/.lastIndexOf(\"tommy can eat\"); // Returns 11\n</code></pre>\n\n<p>A quick explanation of how I am modifying the <code>RegExp</code>: For <code>indexOf</code> I just have to ensure that the global flag is set. For <code>lastIndexOf</code> of I am using a negative look-ahead to find the last occurrence unless the <code>RegExp</code> was already matching at the end of the string.</p>\n" }, { "answer_id": 12228895, "author": "jakov", "author_id": 1100709, "author_profile": "https://Stackoverflow.com/users/1100709", "pm_score": 2, "selected": false, "text": "<p>I needed a <code>regexIndexOf</code> function also for an array, so I programed one myself. However I doubt, that it's optimized, but i guess it should work properly.</p>\n\n<pre><code>Array.prototype.regexIndexOf = function (regex, startpos = 0) {\n len = this.length;\n for(x = startpos; x &lt; len; x++){\n if(typeof this[x] != 'undefined' &amp;&amp; (''+this[x]).match(regex)){\n return x;\n }\n }\n return -1;\n}\n\narr = [];\narr.push(null);\narr.push(NaN);\narr[3] = 7;\narr.push('asdf');\narr.push('qwer');\narr.push(9);\narr.push('...');\nconsole.log(arr);\narr.regexIndexOf(/\\d/, 4);\n</code></pre>\n" }, { "answer_id": 16558822, "author": "amwinter", "author_id": 329867, "author_profile": "https://Stackoverflow.com/users/329867", "pm_score": 1, "selected": false, "text": "<p>In certain simple cases, you can simplify your backwards search by using split.</p>\n\n<pre><code>function regexlast(string,re){\n var tokens=string.split(re);\n return (tokens.length&gt;1)?(string.length-tokens[tokens.length-1].length):null;\n}\n</code></pre>\n\n<p>This has a few serious problems:</p>\n\n<ol>\n<li>overlapping matches won't show up</li>\n<li>returned index is for the end of the match rather than the beginning (fine if your regex is a constant)</li>\n</ol>\n\n<p>But on the bright side it's way less code. For a constant-length regex that can't overlap (like <code>/\\s\\w/</code> for finding word boundaries) this is good enough.</p>\n" }, { "answer_id": 21420210, "author": "pmrotule", "author_id": 1895428, "author_profile": "https://Stackoverflow.com/users/1895428", "pm_score": 6, "selected": false, "text": "<p>I have a short version for you. It works well for me!</p>\n\n<pre><code>var match = str.match(/[abc]/gi);\nvar firstIndex = str.indexOf(match[0]);\nvar lastIndex = str.lastIndexOf(match[match.length-1]);\n</code></pre>\n\n<p>And if you want a prototype version:</p>\n\n<pre><code>String.prototype.indexOfRegex = function(regex){\n var match = this.match(regex);\n return match ? this.indexOf(match[0]) : -1;\n}\n\nString.prototype.lastIndexOfRegex = function(regex){\n var match = this.match(regex);\n return match ? this.lastIndexOf(match[match.length-1]) : -1;\n}\n</code></pre>\n\n<p><strong>EDIT</strong> : if you want to add support for fromIndex</p>\n\n<pre><code>String.prototype.indexOfRegex = function(regex, fromIndex){\n var str = fromIndex ? this.substring(fromIndex) : this;\n var match = str.match(regex);\n return match ? str.indexOf(match[0]) + fromIndex : -1;\n}\n\nString.prototype.lastIndexOfRegex = function(regex, fromIndex){\n var str = fromIndex ? this.substring(0, fromIndex) : this;\n var match = str.match(regex);\n return match ? str.lastIndexOf(match[match.length-1]) : -1;\n}\n</code></pre>\n\n<p>To use it, as simple as this:</p>\n\n<pre><code>var firstIndex = str.indexOfRegex(/[abc]/gi);\nvar lastIndex = str.lastIndexOfRegex(/[abc]/gi);\n</code></pre>\n" }, { "answer_id": 23177741, "author": "npjohns", "author_id": 1331851, "author_profile": "https://Stackoverflow.com/users/1331851", "pm_score": 0, "selected": false, "text": "<p>For data with sparse matches, using string.search is the fastest across browsers. It re-slices a string each iteration to :</p>\n\n<pre><code>function lastIndexOfSearch(string, regex, index) {\n if(index === 0 || index)\n string = string.slice(0, Math.max(0,index));\n var idx;\n var offset = -1;\n while ((idx = string.search(regex)) !== -1) {\n offset += idx + 1;\n string = string.slice(idx + 1);\n }\n return offset;\n}\n</code></pre>\n\n<p>For dense data I made this. It's complex compared to the execute method, but for dense data, it's 2-10x faster than every other method I tried, and about 100x faster than the accepted solution. The main points are:</p>\n\n<ol>\n<li>It calls exec on the regex passed in once to verify there is a match or quit early. I do this using (?= in a similar method, but on IE checking with exec is dramatically faster.</li>\n<li>It constructs and caches a modified regex in the format '(r).<em>(?!.</em>?r)'</li>\n<li><p>The new regex is executed and the results from either that exec, or the first exec, are returned;</p>\n\n<pre><code>function lastIndexOfGroupSimple(string, regex, index) {\n if (index === 0 || index) string = string.slice(0, Math.max(0, index + 1));\n regex.lastIndex = 0;\n var lastRegex, index\n flags = 'g' + (regex.multiline ? 'm' : '') + (regex.ignoreCase ? 'i' : ''),\n key = regex.source + '$' + flags,\n match = regex.exec(string);\n if (!match) return -1;\n if (lastIndexOfGroupSimple.cache === undefined) lastIndexOfGroupSimple.cache = {};\n lastRegex = lastIndexOfGroupSimple.cache[key];\n if (!lastRegex)\n lastIndexOfGroupSimple.cache[key] = lastRegex = new RegExp('.*(' + regex.source + ')(?!.*?' + regex.source + ')', flags);\n index = match.index;\n lastRegex.lastIndex = match.index;\n return (match = lastRegex.exec(string)) ? lastRegex.lastIndex - match[1].length : index;\n};\n</code></pre></li>\n</ol>\n\n<p><a href=\"http://jsperf.com/lastindexof-regex/6\" rel=\"nofollow\">jsPerf of methods</a></p>\n\n<p>I don't understand the purpose of the tests up top. Situations that require a regex are impossible to compare against a call to indexOf, which I think is the point of making the method in the first place. To get the test to pass, it makes more sense to use 'xxx+(?!x)', than adjust the way the regex iterates.</p>\n" }, { "answer_id": 30792707, "author": "Eli", "author_id": 117588, "author_profile": "https://Stackoverflow.com/users/117588", "pm_score": 0, "selected": false, "text": "<p>Jason Bunting's last index of does not work. Mine is not optimal, but it works.</p>\n\n<pre><code>//Jason Bunting's\nString.prototype.regexIndexOf = function(regex, startpos) {\nvar indexOf = this.substring(startpos || 0).search(regex);\nreturn (indexOf &gt;= 0) ? (indexOf + (startpos || 0)) : indexOf;\n}\n\nString.prototype.regexLastIndexOf = function(regex, startpos) {\nvar lastIndex = -1;\nvar index = this.regexIndexOf( regex );\nstartpos = startpos === undefined ? this.length : startpos;\n\nwhile ( index &gt;= 0 &amp;&amp; index &lt; startpos )\n{\n lastIndex = index;\n index = this.regexIndexOf( regex, index + 1 );\n}\nreturn lastIndex;\n}\n</code></pre>\n" }, { "answer_id": 31373042, "author": "rmg.n3t", "author_id": 3672064, "author_profile": "https://Stackoverflow.com/users/3672064", "pm_score": 4, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>str.search(regex)\n</code></pre>\n\n<p>See the documentation <a href=\"http://www.w3schools.com/jsref/jsref_search.asp\">here.</a></p>\n" }, { "answer_id": 32232028, "author": "Xotic750", "author_id": 592253, "author_profile": "https://Stackoverflow.com/users/592253", "pm_score": 0, "selected": false, "text": "<p>There are still no native methods that perform the requested task.</p>\n\n<p>Here is the code that I am using. It mimics the behaviour of <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf\" rel=\"nofollow\">String.prototype.indexOf</a> and <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf\" rel=\"nofollow\">String.prototype.lastIndexOf</a> methods but they also accept a RegExp as the search argument in addition to a string representing the value to search for.</p>\n\n<p>Yes it is quite long as an answer goes as it tries to follow current standards as close as possible and of course contains a reasonable amount of <a href=\"http://usejsdoc.org/\" rel=\"nofollow\">JSDOC</a> comments. However, once minified, the code is only 2.27k and once gzipped for transmission it is only 1023 bytes.</p>\n\n<p>The 2 methods that this adds to <code>String.prototype</code> (using <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow\">Object.defineProperty</a> where available) are:</p>\n\n<ol>\n<li><code>searchOf</code></li>\n<li><code>searchLastOf</code></li>\n</ol>\n\n<p>It passes all the tests that the OP posted and additionally I have tested the routines quite thoroughly in my daily usage, and have attempted to be sure that they work across multiple environments, but feedback/issues are always welcome.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/*jslint maxlen:80, browser:true */\r\n\r\n/*\r\n * Properties used by searchOf and searchLastOf implementation.\r\n */\r\n\r\n/*property\r\n MAX_SAFE_INTEGER, abs, add, apply, call, configurable, defineProperty,\r\n enumerable, exec, floor, global, hasOwnProperty, ignoreCase, index,\r\n lastIndex, lastIndexOf, length, max, min, multiline, pow, prototype,\r\n remove, replace, searchLastOf, searchOf, source, toString, value, writable\r\n*/\r\n\r\n/*\r\n * Properties used in the testing of searchOf and searchLastOf implimentation.\r\n */\r\n\r\n/*property\r\n appendChild, createTextNode, getElementById, indexOf, lastIndexOf, length,\r\n searchLastOf, searchOf, unshift\r\n*/\r\n\r\n(function () {\r\n 'use strict';\r\n\r\n var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1,\r\n getNativeFlags = new RegExp('\\\\/([a-z]*)$', 'i'),\r\n clipDups = new RegExp('([\\\\s\\\\S])(?=[\\\\s\\\\S]*\\\\1)', 'g'),\r\n pToString = Object.prototype.toString,\r\n pHasOwn = Object.prototype.hasOwnProperty,\r\n stringTagRegExp;\r\n\r\n /**\r\n * Defines a new property directly on an object, or modifies an existing\r\n * property on an object, and returns the object.\r\n *\r\n * @private\r\n * @function\r\n * @param {Object} object\r\n * @param {string} property\r\n * @param {Object} descriptor\r\n * @returns {Object}\r\n * @see https://goo.gl/CZnEqg\r\n */\r\n function $defineProperty(object, property, descriptor) {\r\n if (Object.defineProperty) {\r\n Object.defineProperty(object, property, descriptor);\r\n } else {\r\n object[property] = descriptor.value;\r\n }\r\n\r\n return object;\r\n }\r\n\r\n /**\r\n * Returns true if the operands are strictly equal with no type conversion.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} a\r\n * @param {*} b\r\n * @returns {boolean}\r\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4\r\n */\r\n function $strictEqual(a, b) {\r\n return a === b;\r\n }\r\n\r\n /**\r\n * Returns true if the operand inputArg is undefined.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg\r\n * @returns {boolean}\r\n */\r\n function $isUndefined(inputArg) {\r\n return $strictEqual(typeof inputArg, 'undefined');\r\n }\r\n\r\n /**\r\n * Provides a string representation of the supplied object in the form\r\n * \"[object type]\", where type is the object type.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg The object for which a class string represntation\r\n * is required.\r\n * @returns {string} A string value of the form \"[object type]\".\r\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2\r\n */\r\n function $toStringTag(inputArg) {\r\n var val;\r\n if (inputArg === null) {\r\n val = '[object Null]';\r\n } else if ($isUndefined(inputArg)) {\r\n val = '[object Undefined]';\r\n } else {\r\n val = pToString.call(inputArg);\r\n }\r\n\r\n return val;\r\n }\r\n\r\n /**\r\n * The string tag representation of a RegExp object.\r\n *\r\n * @private\r\n * @type {string}\r\n */\r\n stringTagRegExp = $toStringTag(getNativeFlags);\r\n\r\n /**\r\n * Returns true if the operand inputArg is a RegExp.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg\r\n * @returns {boolean}\r\n */\r\n function $isRegExp(inputArg) {\r\n return $toStringTag(inputArg) === stringTagRegExp &amp;&amp;\r\n pHasOwn.call(inputArg, 'ignoreCase') &amp;&amp;\r\n typeof inputArg.ignoreCase === 'boolean' &amp;&amp;\r\n pHasOwn.call(inputArg, 'global') &amp;&amp;\r\n typeof inputArg.global === 'boolean' &amp;&amp;\r\n pHasOwn.call(inputArg, 'multiline') &amp;&amp;\r\n typeof inputArg.multiline === 'boolean' &amp;&amp;\r\n pHasOwn.call(inputArg, 'source') &amp;&amp;\r\n typeof inputArg.source === 'string';\r\n }\r\n\r\n /**\r\n * The abstract operation throws an error if its argument is a value that\r\n * cannot be converted to an Object, otherwise returns the argument.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg The object to be tested.\r\n * @throws {TypeError} If inputArg is null or undefined.\r\n * @returns {*} The inputArg if coercible.\r\n * @see https://goo.gl/5GcmVq\r\n */\r\n function $requireObjectCoercible(inputArg) {\r\n var errStr;\r\n\r\n if (inputArg === null || $isUndefined(inputArg)) {\r\n errStr = 'Cannot convert argument to object: ' + inputArg;\r\n throw new TypeError(errStr);\r\n }\r\n\r\n return inputArg;\r\n }\r\n\r\n /**\r\n * The abstract operation converts its argument to a value of type string\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg\r\n * @returns {string}\r\n * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring\r\n */\r\n function $toString(inputArg) {\r\n var type,\r\n val;\r\n\r\n if (inputArg === null) {\r\n val = 'null';\r\n } else {\r\n type = typeof inputArg;\r\n if (type === 'string') {\r\n val = inputArg;\r\n } else if (type === 'undefined') {\r\n val = type;\r\n } else {\r\n if (type === 'symbol') {\r\n throw new TypeError('Cannot convert symbol to string');\r\n }\r\n\r\n val = String(inputArg);\r\n }\r\n }\r\n\r\n return val;\r\n }\r\n\r\n /**\r\n * Returns a string only if the arguments is coercible otherwise throws an\r\n * error.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg\r\n * @throws {TypeError} If inputArg is null or undefined.\r\n * @returns {string}\r\n */\r\n function $onlyCoercibleToString(inputArg) {\r\n return $toString($requireObjectCoercible(inputArg));\r\n }\r\n\r\n /**\r\n * The function evaluates the passed value and converts it to an integer.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg The object to be converted to an integer.\r\n * @returns {number} If the target value is NaN, null or undefined, 0 is\r\n * returned. If the target value is false, 0 is returned\r\n * and if true, 1 is returned.\r\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.4\r\n */\r\n function $toInteger(inputArg) {\r\n var number = +inputArg,\r\n val = 0;\r\n\r\n if ($strictEqual(number, number)) {\r\n if (!number || number === Infinity || number === -Infinity) {\r\n val = number;\r\n } else {\r\n val = (number &gt; 0 || -1) * Math.floor(Math.abs(number));\r\n }\r\n }\r\n\r\n return val;\r\n }\r\n\r\n /**\r\n * Copies a regex object. Allows adding and removing native flags while\r\n * copying the regex.\r\n *\r\n * @private\r\n * @function\r\n * @param {RegExp} regex Regex to copy.\r\n * @param {Object} [options] Allows specifying native flags to add or\r\n * remove while copying the regex.\r\n * @returns {RegExp} Copy of the provided regex, possibly with modified\r\n * flags.\r\n */\r\n function $copyRegExp(regex, options) {\r\n var flags,\r\n opts,\r\n rx;\r\n\r\n if (options !== null &amp;&amp; typeof options === 'object') {\r\n opts = options;\r\n } else {\r\n opts = {};\r\n }\r\n\r\n // Get native flags in use\r\n flags = getNativeFlags.exec($toString(regex))[1];\r\n flags = $onlyCoercibleToString(flags);\r\n if (opts.add) {\r\n flags += opts.add;\r\n flags = flags.replace(clipDups, '');\r\n }\r\n\r\n if (opts.remove) {\r\n // Would need to escape `options.remove` if this was public\r\n rx = new RegExp('[' + opts.remove + ']+', 'g');\r\n flags = flags.replace(rx, '');\r\n }\r\n\r\n return new RegExp(regex.source, flags);\r\n }\r\n\r\n /**\r\n * The abstract operation ToLength converts its argument to an integer\r\n * suitable for use as the length of an array-like object.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg The object to be converted to a length.\r\n * @returns {number} If len &lt;= +0 then +0 else if len is +INFINITY then\r\n * 2^53-1 else min(len, 2^53-1).\r\n * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength\r\n */\r\n function $toLength(inputArg) {\r\n return Math.min(Math.max($toInteger(inputArg), 0), MAX_SAFE_INTEGER);\r\n }\r\n\r\n /**\r\n * Copies a regex object so that it is suitable for use with searchOf and\r\n * searchLastOf methods.\r\n *\r\n * @private\r\n * @function\r\n * @param {RegExp} regex Regex to copy.\r\n * @returns {RegExp}\r\n */\r\n function $toSearchRegExp(regex) {\r\n return $copyRegExp(regex, {\r\n add: 'g',\r\n remove: 'y'\r\n });\r\n }\r\n\r\n /**\r\n * Returns true if the operand inputArg is a member of one of the types\r\n * Undefined, Null, Boolean, Number, Symbol, or String.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg\r\n * @returns {boolean}\r\n * @see https://goo.gl/W68ywJ\r\n * @see https://goo.gl/ev7881\r\n */\r\n function $isPrimitive(inputArg) {\r\n var type = typeof inputArg;\r\n\r\n return type === 'undefined' ||\r\n inputArg === null ||\r\n type === 'boolean' ||\r\n type === 'string' ||\r\n type === 'number' ||\r\n type === 'symbol';\r\n }\r\n\r\n /**\r\n * The abstract operation converts its argument to a value of type Object\r\n * but fixes some environment bugs.\r\n *\r\n * @private\r\n * @function\r\n * @param {*} inputArg The argument to be converted to an object.\r\n * @throws {TypeError} If inputArg is not coercible to an object.\r\n * @returns {Object} Value of inputArg as type Object.\r\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.9\r\n */\r\n function $toObject(inputArg) {\r\n var object;\r\n\r\n if ($isPrimitive($requireObjectCoercible(inputArg))) {\r\n object = Object(inputArg);\r\n } else {\r\n object = inputArg;\r\n }\r\n\r\n return object;\r\n }\r\n\r\n /**\r\n * Converts a single argument that is an array-like object or list (eg.\r\n * arguments, NodeList, DOMTokenList (used by classList), NamedNodeMap\r\n * (used by attributes property)) into a new Array() and returns it.\r\n * This is a partial implementation of the ES6 Array.from\r\n *\r\n * @private\r\n * @function\r\n * @param {Object} arrayLike\r\n * @returns {Array}\r\n */\r\n function $toArray(arrayLike) {\r\n var object = $toObject(arrayLike),\r\n length = $toLength(object.length),\r\n array = [],\r\n index = 0;\r\n\r\n array.length = length;\r\n while (index &lt; length) {\r\n array[index] = object[index];\r\n index += 1;\r\n }\r\n\r\n return array;\r\n }\r\n\r\n if (!String.prototype.searchOf) {\r\n /**\r\n * This method returns the index within the calling String object of\r\n * the first occurrence of the specified value, starting the search at\r\n * fromIndex. Returns -1 if the value is not found.\r\n *\r\n * @function\r\n * @this {string}\r\n * @param {RegExp|string} regex A regular expression object or a String.\r\n * Anything else is implicitly converted to\r\n * a String.\r\n * @param {Number} [fromIndex] The location within the calling string\r\n * to start the search from. It can be any\r\n * integer. The default value is 0. If\r\n * fromIndex &lt; 0 the entire string is\r\n * searched (same as passing 0). If\r\n * fromIndex &gt;= str.length, the method will\r\n * return -1 unless searchValue is an empty\r\n * string in which case str.length is\r\n * returned.\r\n * @returns {Number} If successful, returns the index of the first\r\n * match of the regular expression inside the\r\n * string. Otherwise, it returns -1.\r\n */\r\n $defineProperty(String.prototype, 'searchOf', {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (regex) {\r\n var str = $onlyCoercibleToString(this),\r\n args = $toArray(arguments),\r\n result = -1,\r\n fromIndex,\r\n match,\r\n rx;\r\n\r\n if (!$isRegExp(regex)) {\r\n return String.prototype.indexOf.apply(str, args);\r\n }\r\n\r\n if ($toLength(args.length) &gt; 1) {\r\n fromIndex = +args[1];\r\n if (fromIndex &lt; 0) {\r\n fromIndex = 0;\r\n }\r\n } else {\r\n fromIndex = 0;\r\n }\r\n\r\n if (fromIndex &gt;= $toLength(str.length)) {\r\n return result;\r\n }\r\n\r\n rx = $toSearchRegExp(regex);\r\n rx.lastIndex = fromIndex;\r\n match = rx.exec(str);\r\n if (match) {\r\n result = +match.index;\r\n }\r\n\r\n return result;\r\n }\r\n });\r\n }\r\n\r\n if (!String.prototype.searchLastOf) {\r\n /**\r\n * This method returns the index within the calling String object of\r\n * the last occurrence of the specified value, or -1 if not found.\r\n * The calling string is searched backward, starting at fromIndex.\r\n *\r\n * @function\r\n * @this {string}\r\n * @param {RegExp|string} regex A regular expression object or a String.\r\n * Anything else is implicitly converted to\r\n * a String.\r\n * @param {Number} [fromIndex] Optional. The location within the\r\n * calling string to start the search at,\r\n * indexed from left to right. It can be\r\n * any integer. The default value is\r\n * str.length. If it is negative, it is\r\n * treated as 0. If fromIndex &gt; str.length,\r\n * fromIndex is treated as str.length.\r\n * @returns {Number} If successful, returns the index of the first\r\n * match of the regular expression inside the\r\n * string. Otherwise, it returns -1.\r\n */\r\n $defineProperty(String.prototype, 'searchLastOf', {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value: function (regex) {\r\n var str = $onlyCoercibleToString(this),\r\n args = $toArray(arguments),\r\n result = -1,\r\n fromIndex,\r\n length,\r\n match,\r\n pos,\r\n rx;\r\n\r\n if (!$isRegExp(regex)) {\r\n return String.prototype.lastIndexOf.apply(str, args);\r\n }\r\n\r\n length = $toLength(str.length);\r\n if (!$strictEqual(args[1], args[1])) {\r\n fromIndex = length;\r\n } else {\r\n if ($toLength(args.length) &gt; 1) {\r\n fromIndex = $toInteger(args[1]);\r\n } else {\r\n fromIndex = length - 1;\r\n }\r\n }\r\n\r\n if (fromIndex &gt;= 0) {\r\n fromIndex = Math.min(fromIndex, length - 1);\r\n } else {\r\n fromIndex = length - Math.abs(fromIndex);\r\n }\r\n\r\n pos = 0;\r\n rx = $toSearchRegExp(regex);\r\n while (pos &lt;= fromIndex) {\r\n rx.lastIndex = pos;\r\n match = rx.exec(str);\r\n if (!match) {\r\n break;\r\n }\r\n\r\n pos = +match.index;\r\n if (pos &lt;= fromIndex) {\r\n result = pos;\r\n }\r\n\r\n pos += 1;\r\n }\r\n\r\n return result;\r\n }\r\n });\r\n }\r\n}());\r\n\r\n(function () {\r\n 'use strict';\r\n\r\n /*\r\n * testing as follow to make sure that at least for one character regexp,\r\n * the result is the same as if we used indexOf\r\n */\r\n\r\n var pre = document.getElementById('out');\r\n\r\n function log(result) {\r\n pre.appendChild(document.createTextNode(result + '\\n'));\r\n }\r\n\r\n function test(str) {\r\n var i = str.length + 2,\r\n r,\r\n a,\r\n b;\r\n\r\n while (i) {\r\n a = str.indexOf('a', i);\r\n b = str.searchOf(/a/, i);\r\n r = ['Failed', 'searchOf', str, i, a, b];\r\n if (a === b) {\r\n r[0] = 'Passed';\r\n }\r\n\r\n log(r);\r\n a = str.lastIndexOf('a', i);\r\n b = str.searchLastOf(/a/, i);\r\n r = ['Failed', 'searchLastOf', str, i, a, b];\r\n if (a === b) {\r\n r[0] = 'Passed';\r\n }\r\n\r\n log(r);\r\n i -= 1;\r\n }\r\n }\r\n\r\n /*\r\n * Look for the a among the xes\r\n */\r\n\r\n test('xxx');\r\n test('axx');\r\n test('xax');\r\n test('xxa');\r\n test('axa');\r\n test('xaa');\r\n test('aax');\r\n test('aaa');\r\n}());</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;pre id=\"out\"&gt;&lt;/pre&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 56451404, "author": "Armin Bu", "author_id": 2587809, "author_profile": "https://Stackoverflow.com/users/2587809", "pm_score": 0, "selected": false, "text": "<p>If you are looking for a very simple lastIndex lookup with RegExp and don't care if it mimics lastIndexOf to the last detail, this may catch your attention.</p>\n\n<p>I simply reverse the string, and subtract the first occurence index from length - 1. It happens to pass my test, but I think there could arise a performance issue with long strings.</p>\n\n<pre class=\"lang-ts prettyprint-override\"><code>interface String {\n reverse(): string;\n lastIndex(regex: RegExp): number;\n}\n\nString.prototype.reverse = function(this: string) {\n return this.split(\"\")\n .reverse()\n .join(\"\");\n};\n\nString.prototype.lastIndex = function(this: string, regex: RegExp) {\n const exec = regex.exec(this.reverse());\n return exec === null ? -1 : this.length - 1 - exec.index;\n};\n</code></pre>\n" }, { "answer_id": 57053741, "author": "wfreude", "author_id": 7796844, "author_profile": "https://Stackoverflow.com/users/7796844", "pm_score": 0, "selected": false, "text": "<p>I used <code>String.prototype.match(regex)</code> which returns a string array of all found matches of the given <code>regex</code> in the string (more info <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match\" rel=\"nofollow noreferrer\">see here</a>): </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getLastIndex(text, regex, limit = text.length) {\r\n const matches = text.match(regex);\r\n\r\n // no matches found\r\n if (!matches) {\r\n return -1;\r\n }\r\n\r\n // matches found but first index greater than limit\r\n if (text.indexOf(matches[0] + matches[0].length) &gt; limit) {\r\n return -1;\r\n }\r\n\r\n // reduce index until smaller than limit\r\n let i = matches.length - 1;\r\n let index = text.lastIndexOf(matches[i]);\r\n while (index &gt; limit &amp;&amp; i &gt;= 0) {\r\n i--;\r\n index = text.lastIndexOf(matches[i]);\r\n }\r\n return index &gt; limit ? -1 : index;\r\n}\r\n\r\n// expect -1 as first index === 14\r\nconsole.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\\. /g, 10));\r\n\r\n// expect 29\r\nconsole.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\\. /g));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 57740885, "author": "user984003", "author_id": 984003, "author_profile": "https://Stackoverflow.com/users/984003", "pm_score": 0, "selected": false, "text": "<pre><code>var mystring = \"abc ab a\";\nvar re = new RegExp(\"ab\"); // any regex here\n\nif ( re.exec(mystring) != null ){ \n alert(\"matches\"); // true in this case\n}\n</code></pre>\n\n<p>Use standard regular expressions:</p>\n\n<pre><code>var re = new RegExp(\"^ab\"); // At front\nvar re = new RegExp(\"ab$\"); // At end\nvar re = new RegExp(\"ab(c|d)\"); // abc or abd\n</code></pre>\n" }, { "answer_id": 68181020, "author": "Oliver", "author_id": 2046109, "author_profile": "https://Stackoverflow.com/users/2046109", "pm_score": 2, "selected": false, "text": "<p>For a solution that's more concise than most of the other answers posted, you may want to use the <code>String.prototype.replace</code> function which will run a function on every detected pattern. For example:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let firstIndex = -1;\n&quot;the 1st numb3r&quot;.replace(/\\d/,(p,i) =&gt; { firstIndex = i; });\n// firstIndex === 4\n</code></pre>\n<p>This is especially useful for the &quot;last index&quot; case:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let lastIndex = -1;\n&quot;the l4st numb3r&quot;.replace(/\\d/g,(p,i) =&gt; { lastIndex = i; });\n// lastIndex === 13\n</code></pre>\n<p>Here, it's important to include the &quot;g&quot; modifier so that all occurrences are evaluated. These versions will also result in <code>-1</code> if the regular expression was not found.</p>\n<p>Finally, here are the more general functions which include a start index:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function indexOfRegex(str,regex,start = 0) {\n regex = regex.global ? regex : new RegExp(regex.source,regex.flags + &quot;g&quot;);\n let index = -1;\n str.replace(regex,function() {\n const pos = arguments[arguments.length - 2];\n if(index &lt; 0 &amp;&amp; pos &gt;= start)\n index = pos;\n });\n return index;\n}\n\nfunction lastIndexOfRegex(str,regex,start = str.length - 1) {\n regex = regex.global ? regex : new RegExp(regex.source,regex.flags + &quot;g&quot;);\n let index = -1;\n str.replace(regex,function() {\n const pos = arguments[arguments.length - 2];\n if(pos &lt;= start)\n index = pos;\n });\n return index;\n}\n</code></pre>\n<p>These functions specifically avoid splitting the string at the start index which I feel is risky in the age of Unicode. They don't modify the prototype of common Javascript classes (although you're free to do so yourself). They accept more RegExp flags, for example &quot;u&quot; or &quot;s&quot; and any flags that may be added in the future. And I find it easier to reason about callback functions than for/while loops.</p>\n" }, { "answer_id": 69110638, "author": "user16864806", "author_id": 16864806, "author_profile": "https://Stackoverflow.com/users/16864806", "pm_score": 0, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let regExp; // your RegExp here\narr.map(x =&gt; !!x.toString().match(regExp)).indexOf(true)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 71609276, "author": "Tyler V.", "author_id": 1038564, "author_profile": "https://Stackoverflow.com/users/1038564", "pm_score": 1, "selected": false, "text": "<p>The regexIndexOf from Jason Bunting can be inverted more simply and still support UTF8 characters by doing this:</p>\n<pre><code>function regexLastIndexOf(string, regex, startpos=0) {\n return text.length - regexIndexOf([...text].reverse().join(&quot;&quot;), regex, startpos) - 1;\n}\n</code></pre>\n" }, { "answer_id": 73584108, "author": "ruohola", "author_id": 9835872, "author_profile": "https://Stackoverflow.com/users/9835872", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll\" rel=\"nofollow noreferrer\"><code>String.prototype.matchAll()</code></a>, together with the convenient <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at\" rel=\"nofollow noreferrer\"><code>Array.prototype.at()</code></a>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const str = \"foo a foo B\";\nconst matches = [...str.matchAll(/[abc]/gi)];\n\nif (matches.length) {\n const indexOfFirstMatch = matches.at(0).index;\n const indexOfLastMatch = matches.at(-1).index;\n console.log(indexOfFirstMatch, indexOfLastMatch)\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238/" ]
In javascript, is there an equivalent of String.indexOf() that takes a regular expression instead of a string for the first first parameter while still allowing a second parameter ? I need to do something like ``` str.indexOf(/[abc]/ , i); ``` and ``` str.lastIndexOf(/[abc]/ , i); ``` While String.search() takes a regexp as a parameter it does not allow me to specify a second argument! Edit: This turned out to be harder than I originally thought so I wrote a small test function to test all the provided solutions... it assumes regexIndexOf and regexLastIndexOf have been added to the String object. ``` function test (str) { var i = str.length +2; while (i--) { if (str.indexOf('a',i) != str.regexIndexOf(/a/,i)) alert (['failed regexIndexOf ' , str,i , str.indexOf('a',i) , str.regexIndexOf(/a/,i)]) ; if (str.lastIndexOf('a',i) != str.regexLastIndexOf(/a/,i) ) alert (['failed regexLastIndexOf ' , str,i,str.lastIndexOf('a',i) , str.regexLastIndexOf(/a/,i)]) ; } } ``` and I am testing as follow to make sure that at least for one character regexp, the result is the same as if we used indexOf //Look for the a among the xes test('xxx'); test('axx'); test('xax'); test('xxa'); test('axa'); test('xaa'); test('aax'); test('aaa');
Combining a few of the approaches already mentioned (the indexOf is obviously rather simple), I think these are the functions that will do the trick: ``` function regexIndexOf(string, regex, startpos) { var indexOf = string.substring(startpos || 0).search(regex); return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf; } function regexLastIndexOf(string, regex, startpos) { regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : "")); if(typeof (startpos) == "undefined") { startpos = string.length; } else if(startpos < 0) { startpos = 0; } var stringToWorkWith = string.substring(0, startpos + 1); var lastIndexOf = -1; var nextStop = 0; while((result = regex.exec(stringToWorkWith)) != null) { lastIndexOf = result.index; regex.lastIndex = ++nextStop; } return lastIndexOf; } ``` --- UPDATE: Edited `regexLastIndexOf()` so that is seems to mimic `lastIndexOf()` now. Please let me know if it still fails and under what circumstances. --- UPDATE: Passes all tests found on in comments on this page, and my own. Of course, that doesn't mean it's bulletproof. Any feedback appreciated.
273,794
<p>Similar to <a href="https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships">this question</a> but for MySQL....</p> <p>How can I programmatically determine foreign key references in MySQL (assuming InnoDB)? I can almost get them with:</p> <pre><code>SHOW TABLE STATUS WHERE Name = 'MyTableName'; </code></pre> <p>...but alas, the comment column which seems to contain some of this info gets truncated so I can't rely on it. There must be some other way...</p> <p>I'd be happy with a C API call, a SQL statement, anything--I just need something that consistently works.</p> <p>Note: I've also considered parsing the results of a "SHOW CREATE TABLE MyTableName" statement, but I'm really hoping there's something simpler.</p>
[ { "answer_id": 273812, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>Try <code>INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS</code></p>\n" }, { "answer_id": 273907, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 6, "selected": true, "text": "<p>There are two tables you can query to get this information: <a href=\"http://dev.mysql.com/doc/refman/5.1/en/table-constraints-table.html\" rel=\"noreferrer\"><code>INFORMATION_SCHEMA.TABLE_CONSTRAINTS</code></a> and <a href=\"http://dev.mysql.com/doc/refman/5.1/en/key-column-usage-table.html\" rel=\"noreferrer\"><code>INFORMATION_SCHEMA.KEY_COLUMN_USAGE</code></a>.</p>\n\n<p>Here's a query from the comments on the latter page linked above, which demonstrates how to get the info you seek.</p>\n\n<pre><code>SELECT CONCAT( table_name, '.', column_name, ' -&gt; ', \n referenced_table_name, '.', referenced_column_name ) AS list_of_fks \nFROM INFORMATION_SCHEMA.key_column_usage \nWHERE referenced_table_schema = 'test' \n AND referenced_table_name IS NOT NULL \nORDER BY table_name, column_name;\n</code></pre>\n\n<p>Use your schema name instead of '<code>test</code>' above.</p>\n" }, { "answer_id": 11860718, "author": "JavierCane", "author_id": 967124, "author_profile": "https://Stackoverflow.com/users/967124", "pm_score": 3, "selected": false, "text": "<p>Here you have a little improvement over the @bill solution:</p>\n\n<pre><code>SELECT CONSTRAINT_SCHEMA AS db,\n CONCAT (\n TABLE_NAME,\n '.',\n COLUMN_NAME,\n ' -&gt; ',\n REFERENCED_TABLE_NAME,\n '.',\n REFERENCED_COLUMN_NAME\n ) AS relationship \nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE REFERENCED_TABLE_NAME = 'your_table_name'\nORDER BY CONSTRAINT_SCHEMA,\n TABLE_NAME,\n COLUMN_NAME;\n</code></pre>\n\n<p>In this case I was filtering by relationships with the \"your_table_name\" fields and seeing from which database the relationship comes.</p>\n" }, { "answer_id": 37545164, "author": "Bkeshh Mhrjn", "author_id": 6404516, "author_profile": "https://Stackoverflow.com/users/6404516", "pm_score": -1, "selected": false, "text": "<pre><code>SELECT TABLE_NAME,\n COLUMN_NAME,\n CONSTRAINT_NAME,\n REFERENCED_TABLE_NAME,\n REFERENCED_COLUMN_NAME \nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE REFERENCED_TABLE_NAME = 'table_name'\n AND TABLE_SCHEMA = 'table_schema';\n</code></pre>\n" }, { "answer_id": 60381666, "author": "kinsay", "author_id": 9156012, "author_profile": "https://Stackoverflow.com/users/9156012", "pm_score": 0, "selected": false, "text": "<p>based on Bill Karwin answered, I used this solution to get all the info I needed, included on_delete and on_update rules:</p>\n\n<pre><code>SELECT kcu.referenced_table_schema, kcu.constraint_name, kcu.table_name, kcu.column_name, kcu.referenced_table_name, kcu.referenced_column_name, \n rc.update_rule, rc.delete_rule \nFROM INFORMATION_SCHEMA.key_column_usage kcu\nJOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc on kcu.constraint_name = rc.constraint_name\nWHERE kcu.referenced_table_schema = 'db_name' \nAND kcu.referenced_table_name IS NOT NULL \nORDER BY kcu.table_name, kcu.column_name\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23934/" ]
Similar to [this question](https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships) but for MySQL.... How can I programmatically determine foreign key references in MySQL (assuming InnoDB)? I can almost get them with: ``` SHOW TABLE STATUS WHERE Name = 'MyTableName'; ``` ...but alas, the comment column which seems to contain some of this info gets truncated so I can't rely on it. There must be some other way... I'd be happy with a C API call, a SQL statement, anything--I just need something that consistently works. Note: I've also considered parsing the results of a "SHOW CREATE TABLE MyTableName" statement, but I'm really hoping there's something simpler.
There are two tables you can query to get this information: [`INFORMATION_SCHEMA.TABLE_CONSTRAINTS`](http://dev.mysql.com/doc/refman/5.1/en/table-constraints-table.html) and [`INFORMATION_SCHEMA.KEY_COLUMN_USAGE`](http://dev.mysql.com/doc/refman/5.1/en/key-column-usage-table.html). Here's a query from the comments on the latter page linked above, which demonstrates how to get the info you seek. ``` SELECT CONCAT( table_name, '.', column_name, ' -> ', referenced_table_name, '.', referenced_column_name ) AS list_of_fks FROM INFORMATION_SCHEMA.key_column_usage WHERE referenced_table_schema = 'test' AND referenced_table_name IS NOT NULL ORDER BY table_name, column_name; ``` Use your schema name instead of '`test`' above.
273,803
<p>How can I figure out what is actually causing the following error? The page is the same as other pages but for some reason, only this page is having this error. It also only happens on the ISP (GoDaddy) who has a trust level of Medium and I can't set a breakpoint and try to catch it.</p> <pre><code>Server Error in '/' Application. Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. </code></pre> <p>Source Error:</p> <pre><code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. </code></pre> <pre> Stack Trace: [SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.] System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0 System.Security.CodeAccessPermission.Demand() +59 System.IO.Path.GetTempPath() +54 hh.a(Int32 A_0, Boolean A_1, Boolean A_2) +20 jg.b(c A_0, UInt64 A_1) +234 ei.b(c A_0, UInt64 A_1) +18 jg.a(c A_0, UInt64 A_1, Boolean A_2) +61 </pre> <pre><code>Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433 </code></pre> <p>If you have had this issue or just know how I can fix or trace it please add your answer. Trust level of Medium is required by the ISP.</p>
[ { "answer_id": 273851, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>I don't believe GoDaddy supports Full trust - though that may have changed recently. The error is caused by the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.gettemppath.aspx\" rel=\"nofollow noreferrer\">System.IO.Path.GetTempPath</a> call, which requires <a href=\"http://msdn.microsoft.com/en-us/library/system.security.permissions.environmentpermission.aspx\" rel=\"nofollow noreferrer\">EnvironmentPermission</a>.</p>\n\n<p>The call stack prior to that is obfuscated, so my guess is it's from a component vendor. Check for an update or fix for partial trust from them, or replace it.</p>\n" }, { "answer_id": 817045, "author": "Jon Adams", "author_id": 2291, "author_profile": "https://Stackoverflow.com/users/2291", "pm_score": 3, "selected": true, "text": "<p>Have you tried using a local instance of IIS and setting the trust level to medium? That would help you debug and try stuff a little quicker. </p>\n\n<p>(And is a good habit to get into anyway. You want to test in an environment as close to production as possible. And the VS web server definitely has a few important differences that can get you if you don't test in IIS too.)</p>\n" }, { "answer_id": 1103071, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>Setting breakpoints in obfuscated, non-debug assemblies are hard. It will likely lead you nowhere.</p>\n\n<p>Find out why the obfuscated component is trying to access the temp path.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
How can I figure out what is actually causing the following error? The page is the same as other pages but for some reason, only this page is having this error. It also only happens on the ISP (GoDaddy) who has a trust level of Medium and I can't set a breakpoint and try to catch it. ``` Server Error in '/' Application. Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. ``` Source Error: ``` An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. ``` ``` Stack Trace: [SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.] System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0 System.Security.CodeAccessPermission.Demand() +59 System.IO.Path.GetTempPath() +54 hh.a(Int32 A_0, Boolean A_1, Boolean A_2) +20 jg.b(c A_0, UInt64 A_1) +234 ei.b(c A_0, UInt64 A_1) +18 jg.a(c A_0, UInt64 A_1, Boolean A_2) +61 ``` ``` Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433 ``` If you have had this issue or just know how I can fix or trace it please add your answer. Trust level of Medium is required by the ISP.
Have you tried using a local instance of IIS and setting the trust level to medium? That would help you debug and try stuff a little quicker. (And is a good habit to get into anyway. You want to test in an environment as close to production as possible. And the VS web server definitely has a few important differences that can get you if you don't test in IIS too.)
273,809
<p>I have a bunch of controls on my window. One of them is a refresh button that performs a cumbersome task on a background thread.</p> <p>When the user clicks the refresh button, I put the cursor in a wait (hourglass) status and disable the whole window -- <code>Me.IsEnabled = False</code>.</p> <p>I'd like to support cancellation of the refresh action by letting the user click a cancel button, but I can't facilitate this while the whole window is disabled.</p> <p>Is there a way to do this besides disabling each control (except for the cancel button) one by one and then re-enabling them one by one when the user clicks cancel?</p>
[ { "answer_id": 273846, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 2, "selected": false, "text": "<p>You can data bind each controls IsEnabled property to your custom boolean dependency property that signals when your application is in lock down. Just don't bind the cancel button.</p>\n\n<p>As Donnelle mentioned You can setup multi binding with a converter. Here are a couple examples you can refer to.\n<a href=\"http://www.stackenbloggen.de/PermaLink,guid,ce63f9a5-ccaa-4777-bf3d-d54e69eadec9.aspx\" rel=\"nofollow noreferrer\">WPF MultiBinding with Converter</a>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms771336.aspx\" rel=\"nofollow noreferrer\">Implementing Parameterized MultiBinding Sample</a></p>\n" }, { "answer_id": 273852, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 6, "selected": true, "text": "<p>You can put all the controls in one panel (Grid, StackPanel, etc.), and leave the cancel button in another panel. Then set the IsEnabled property of the other panel.</p>\n\n<p>In practice, this will probably introduce more than one additional panel.</p>\n\n<p>For example, if you had a StackPanel of buttons, you can add an additional StackPanel:</p>\n\n<pre><code>&lt;StackPanel Orientation=\"Horizontal\"&gt;\n &lt;StackPanel x:Name=\"controlContainer\" Orientation=\"Horizontal\"&gt;\n &lt;!-- Other Buttons Here --&gt;\n &lt;/StackPanel&gt;\n &lt;Button Content=\"Cancel\" /&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n\n<p>Then, you would do the following to disable everything but the cancel button:</p>\n\n<pre><code>controlContainer.IsEnabled = false;\n</code></pre>\n" }, { "answer_id": 4927138, "author": "DJR", "author_id": 607211, "author_profile": "https://Stackoverflow.com/users/607211", "pm_score": 3, "selected": false, "text": "<p>I also wanted the user to be able to cancel out of loading.\nI found a lovely solution.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (Control ctrl in this.Controls)\n ctrl.Enabled = false;\n\nCancelButton.Enabled = true;\n</code></pre>\n<p>This also allows the main window to be selected and moved unlike <code>this.Enabled = false;</code>\nwhich completely locks up the window.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
I have a bunch of controls on my window. One of them is a refresh button that performs a cumbersome task on a background thread. When the user clicks the refresh button, I put the cursor in a wait (hourglass) status and disable the whole window -- `Me.IsEnabled = False`. I'd like to support cancellation of the refresh action by letting the user click a cancel button, but I can't facilitate this while the whole window is disabled. Is there a way to do this besides disabling each control (except for the cancel button) one by one and then re-enabling them one by one when the user clicks cancel?
You can put all the controls in one panel (Grid, StackPanel, etc.), and leave the cancel button in another panel. Then set the IsEnabled property of the other panel. In practice, this will probably introduce more than one additional panel. For example, if you had a StackPanel of buttons, you can add an additional StackPanel: ``` <StackPanel Orientation="Horizontal"> <StackPanel x:Name="controlContainer" Orientation="Horizontal"> <!-- Other Buttons Here --> </StackPanel> <Button Content="Cancel" /> </StackPanel> ``` Then, you would do the following to disable everything but the cancel button: ``` controlContainer.IsEnabled = false; ```
273,847
<p>I'm developing multi-language support for our web app. We're using <a href="http://docs.djangoproject.com/en/dev/topics/i18n/" rel="noreferrer">Django's helpers</a> around the <a href="http://en.wikipedia.org/wiki/Gettext" rel="noreferrer">gettext</a> library. Everything has been surprisingly easy, except for the question of how to handle sentences that include significant HTML markup. Here's a simple example:</p> <pre><code>Please &lt;a href="/login/"&gt;log in&lt;/a&gt; to continue. </code></pre> <p>Here are the approaches I can think of:</p> <ol> <li><p>Change the link to include the whole sentence. Regardless of whether the change is a good idea in this case, the problem with this solution is that UI becomes dependent on the needs of i18n when the two are ideally independent.</p></li> <li><p>Mark the whole string above for translation (formatting included). The translation strings would then also include the HTML directly. The problem with this is that changing the HTML formatting requires changing all the translation.</p></li> <li><p>Tightly couple multiple translations, then use string interpolation to combine them. For the example, the phrase "Please %s to continue" and "log in" could be marked separately for translation, then combined. The "log in" is localized, then wrapped in the HREF, then inserted into the translated phrase, which keeps the %s in translation to mark where the link should go. This approach complicates the code and breaks the independence of translation strings.</p></li> </ol> <p>Are there any other options? How have others solved this problem?</p>
[ { "answer_id": 273914, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 3, "selected": false, "text": "<p>Disclaimer: I am not experienced in internationalization of software myself.</p>\n\n<ol>\n<li>I don't think this would be good in any case - just introduces too much coupling …</li>\n<li>As long as you keep formatting sparse in the parts which need to be translated, this could be okay. Giving translators the possibility to give special words importance (by either making them a link or probably using <code>&lt;strong /&gt;</code> emphasis sounds like a good idea. However, those translations with (X)HTML possibly cannot be used anywhere else easily.</li>\n<li>This sounds like unnecessary work to me …</li>\n</ol>\n\n<p>If it were me, I think I would go with the second approach, but I would put the URI into a formatting parameter, so that this can be changed without having to change all those translations.</p>\n\n<pre><code>Please &lt;a href=\"%s\"&gt;log in&lt;/a&gt; to continue.\n</code></pre>\n\n<p>You should keep in mind that you may need to teach your translators a basic knowledge of (X)HTML if you go with this approach, so that they do not screw up your markup and so that they know what to expect from that text they write. Anyhow, this additional knowledge might lead to a better semantic markup, because, as mentioned above, texts could be translated and annotated with (X)HTML to reflect local writing style.</p>\n" }, { "answer_id": 274037, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 4, "selected": false, "text": "<p>2, with a potential twist.</p>\n\n<p>You certainly could localize the whole string, like:</p>\n\n<pre><code>loginLink=Please &lt;a href=\"/login\"&gt;log in&lt;/a&gt; to continue\n</code></pre>\n\n<p>However, depending on your tooling and your localization group, they might prefer for you to do something like:</p>\n\n<pre><code>// tokens in this string add html links\nloginLink=Please {0}log in{1} to continue\n</code></pre>\n\n<p>That would be my preferred method. You could use a different substitution pattern if you have localization tooling that ignores certain characters. E.g.</p>\n\n<pre><code>loginLink=Please %startlink%log in%endlink% to continue\n</code></pre>\n\n<p>Then perform the substitution in your jsp, servlet, or equivalent for whatever language you're using ...</p>\n" }, { "answer_id": 275217, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Makes no sense, how would you translate \"log in\"?</li>\n<li>I don't think many translators have experience with HTML (the regular non-HTML-aware translators would be cheaper)</li>\n<li>I would go with option 3, or use \"Please %slog in%s to continue\" and replace the %s with parts of the link.</li>\n</ol>\n" }, { "answer_id": 276526, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 1, "selected": false, "text": "<p>Interesting question, I'll be having this problem very soon. I think I'll go for 2, without any kind of tricky stuff. HTML markup is simple, urls won't move anytime soon, and if anything is changed a new entry will be created in django.po, so we get a chance to review the translation ( ex: a script should check for empty translations after <code>makemessages</code> ).</p>\n\n<p>So, in template :</p>\n\n<pre><code>{% load i18n %}\n{% trans 'hello &lt;a href=\"/\"&gt;world&lt;/a&gt;' %}\n</code></pre>\n\n<p>... then, after <code>python manage.py makemessages</code> I get in my django.po</p>\n\n<pre><code>#: templates/out.html:3\nmsgid \"hello &lt;a href=\\\"/\\\"&gt;world&lt;/a&gt;\"\nmsgstr \"\"\n</code></pre>\n\n<p>I change it to my needs</p>\n\n<pre><code>#: templates/out.html:3\nmsgid \"hello &lt;a href=\\\"/\\\"&gt;world&lt;/a&gt;\"\nmsgstr \"bonjour &lt;a href=\\\"/\\\"&gt;monde&lt;/a&gt;\"\n</code></pre>\n\n<p>... and in the simple yet frequent cases I'll encounter, it won't be worth any further trouble. The other solutions here seems quite smart but I don't think the solution to markup problems is more markup. Plus, I want to avoid too much confusing stuff inside templates.</p>\n\n<p>Your templates should be quite stable after a while, I guess, but I don't know what other trouble you expect. If the content changes over and over, perhaps that content's place is not inside the template but inside a model.</p>\n\n<p>Edit: I just checked it out in the <a href=\"http://docs.djangoproject.com/en/dev/topics/i18n/?\" rel=\"nofollow noreferrer\">documentation</a>, if you ever need variables inside a translation, there is <code>blocktrans</code>.</p>\n" }, { "answer_id": 283902, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 2, "selected": false, "text": "<p>What ever you do keep the whole sentence as one string. You need to understand the whole sentece to translate it correctly. </p>\n\n<p>Not all words should be translated in all languages: e.g. in Norwegian one doesn't use \"please\" (we <em>can</em> say \"vær så snill\" literally \"be so kind\" but when used as a command it sounds too forceful) so the correct norwegian vould be:</p>\n\n<ul>\n<li>\"Logg inn for å fortsette\" lit.: \"Log in to continue\" or</li>\n<li>\"Fortsett ved å logge inn\" lit.: \"Continue by to log in\" etc. </li>\n</ul>\n\n<p>You must allow completely changing the order, e.g. in a fictional demo language:</p>\n\n<ul>\n<li>\"Für kontinuer Loggen bitte ins\" (if it was real) lit.: \"To continue log please in\" </li>\n</ul>\n\n<p>Some language may even have one single word for (most of) this sentence too...</p>\n\n<p>I'll recommend solution 1 or possibly \"Please %{startlink}log in%{endlink} to continue\" this way the translator can make the whole sentence a link if that's more natural, and it can be completely restructured.</p>\n" }, { "answer_id": 309630, "author": "Mike Sickler", "author_id": 16534, "author_profile": "https://Stackoverflow.com/users/16534", "pm_score": 4, "selected": false, "text": "<p>Solution 2 is what you want. Send them the whole sentence, with the HTML markup embedded. </p>\n\n<p>Reasons:</p>\n\n<ol>\n<li>The predominant translation tool, Trados, can preserve the markup from inadvertent corruption by a translator.</li>\n<li>Trados can also auto-translate text that it has seen before, even if the content of the tags have changed (but the number of tags and their position in the sentence are the same). At the very least, the translator will give you a good discount. </li>\n<li>Styling is locale-specific. In some cases, bold will be inappropriate in Chinese or Japanese, and italics are less commonly used in East Asian languages, for example. The translator should have the freedom to either keep or remove the styles. </li>\n<li>Word order is language-specific. If you were to segment the above sentence into fragments, it might work for English and French, but in Chinese or Japanese the word order would not be correct when you concatenate. For this reason, it is best i18n practice to externalize entire sentences, not sentence fragments.</li>\n</ol>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm developing multi-language support for our web app. We're using [Django's helpers](http://docs.djangoproject.com/en/dev/topics/i18n/) around the [gettext](http://en.wikipedia.org/wiki/Gettext) library. Everything has been surprisingly easy, except for the question of how to handle sentences that include significant HTML markup. Here's a simple example: ``` Please <a href="/login/">log in</a> to continue. ``` Here are the approaches I can think of: 1. Change the link to include the whole sentence. Regardless of whether the change is a good idea in this case, the problem with this solution is that UI becomes dependent on the needs of i18n when the two are ideally independent. 2. Mark the whole string above for translation (formatting included). The translation strings would then also include the HTML directly. The problem with this is that changing the HTML formatting requires changing all the translation. 3. Tightly couple multiple translations, then use string interpolation to combine them. For the example, the phrase "Please %s to continue" and "log in" could be marked separately for translation, then combined. The "log in" is localized, then wrapped in the HREF, then inserted into the translated phrase, which keeps the %s in translation to mark where the link should go. This approach complicates the code and breaks the independence of translation strings. Are there any other options? How have others solved this problem?
2, with a potential twist. You certainly could localize the whole string, like: ``` loginLink=Please <a href="/login">log in</a> to continue ``` However, depending on your tooling and your localization group, they might prefer for you to do something like: ``` // tokens in this string add html links loginLink=Please {0}log in{1} to continue ``` That would be my preferred method. You could use a different substitution pattern if you have localization tooling that ignores certain characters. E.g. ``` loginLink=Please %startlink%log in%endlink% to continue ``` Then perform the substitution in your jsp, servlet, or equivalent for whatever language you're using ...
273,848
<p>I am developing a HTML form designer that needs to generate static HTML and show this to the user. I keep writing ugly code like this:</p> <pre><code>public string GetCheckboxHtml() { return ("&amp;lt;input type="checkbox" name="somename" /&amp;gt;"); } </code></pre> <p>Isn't there a set of strongly typed classes that describe html elements and allow me to write code like this instead:</p> <pre><code>var checkbox = new HtmlCheckbox(attributes); return checkbox.Html(); </code></pre> <p>I just can't think of the correct namespace to look for this or the correct search term to use in Google.</p>
[ { "answer_id": 273866, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 2, "selected": false, "text": "<p>One option is to use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx\" rel=\"nofollow noreferrer\">XElement</a> <a href=\"http://msdn.microsoft.com/en-us/library/bb387019.aspx\" rel=\"nofollow noreferrer\">functional construction</a>. See <a href=\"http://jacobcarpenter.wordpress.com/2008/04/16/pc1-a-solution/\" rel=\"nofollow noreferrer\">this blog post</a> for an example calendar generator.</p>\n\n<p>In your case, your Html could be generated with:</p>\n\n<pre><code>var input = new XElement(\"input\",\n new XAttribute(\"type\", \"checkbox\"),\n new XAttribute(\"name\", \"somename\"));\n\nreturn input.ToString();\n</code></pre>\n" }, { "answer_id": 273873, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "<p>You could use the classes in the System.Web.UI.HtmlControls namespace. Then you can use RenderControl to generate the html content.</p>\n\n<pre><code>HtmlInputCheckBox box = new HtmlInputCheckBox();\n\nStringBuilder sb = new StringBuilder();\nusing(StringWriter sw = new StringWriter(sb))\nusing(HtmlTextWriter htw = new HtmlTextWriter(sw))\n{\n box.RenderControl(htw);\n}\nstring html = sb.ToString();\n</code></pre>\n" }, { "answer_id": 273881, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 4, "selected": true, "text": "<p>Well, if you download the <a href=\"http://www.codeplex.com/aspnet/Wiki/View.aspx?title=MVC&amp;referringTitle=Home\" rel=\"nofollow noreferrer\">ASP.NET MVC</a> DLL's (which you can use in <em>any</em> type of project... including Console apps)... then you can use the many HTML helpers they have.</p>\n" }, { "answer_id": 273904, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>HtmlTextWriter contains goodies like \"WriteStartTag\" and \"WriteEndTag\", which can be used to create properly formed HTML fairly easily.</p>\n\n<p>You essentially pass the tagname and attributes to the HtmlTextWriter, and it generates the proper HTML, and will close it properly with WriteEndTag.</p>\n\n<p>You can also use the prewritten HTMLControls that wrap this code up into strongly typed classes.</p>\n" }, { "answer_id": 273987, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 0, "selected": false, "text": "<p>Also consider using System.Xml. By using it, you almost guarantee your HTML is XHTML compliant.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am developing a HTML form designer that needs to generate static HTML and show this to the user. I keep writing ugly code like this: ``` public string GetCheckboxHtml() { return ("&lt;input type="checkbox" name="somename" /&gt;"); } ``` Isn't there a set of strongly typed classes that describe html elements and allow me to write code like this instead: ``` var checkbox = new HtmlCheckbox(attributes); return checkbox.Html(); ``` I just can't think of the correct namespace to look for this or the correct search term to use in Google.
Well, if you download the [ASP.NET MVC](http://www.codeplex.com/aspnet/Wiki/View.aspx?title=MVC&referringTitle=Home) DLL's (which you can use in *any* type of project... including Console apps)... then you can use the many HTML helpers they have.
273,869
<p>The topic generically says it all. Basically in a situation like this:</p> <pre><code>boost::scoped_array&lt;int&gt; p(new int[10]); </code></pre> <p>Is there any appreciable difference in performance between doing: <code>&amp;p[0]</code> and <code>p.get()</code>?</p> <p>I ask because I prefer the first one, it has a more natural pointer like syntax. In fact, it makes it so you could replace p with a native pointer or array and not have to change anything else.</p> <p>I am guessing since get is a one liner "<code>return ptr;</code>" that the compiler will inline that, and I hope that it is smart enough to to inline <code>operator[]</code> in such a way that it is able to not dereference and then immediately reference.</p> <p>Anyone know?</p>
[ { "answer_id": 273900, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>The only way to know is to actually measure it!</p>\n\n<p>But if you have the source of the boost:scoped_array you could llok at the code and see what it does. I am sure it is pretty similar.</p>\n\n<pre><code>T * scoped_array::get() const // never throws\n{\n return ptr;\n}\n\nT &amp; scoped_array::operator[](std::ptrdiff_t i) const // never throws\n{\n BOOST_ASSERT(ptr != 0);\n BOOST_ASSERT(i &gt;= 0);\n return ptr[i];\n}\n</code></pre>\n\n<p>Write two versions of the code (one using get() the other using operator[]). Compile to assembley with optimizations turned on. See if your compiler actually manages to optimize away the ptr+0.</p>\n" }, { "answer_id": 273945, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 2, "selected": true, "text": "<p>OK, I've done some basic tests as per Martin York's suggestions.</p>\n\n<p>It seems that g++ (4.3.2) is actually pretty good about this. At both -O2 and -O3 optimization levels, it outputs slightly different but functionally equivalent assembly for both <code>&amp;p[0]</code> and <code>p.get()</code>.</p>\n\n<p>At -Os as expected, it took the path of least complexity and emits a call to the <code>operator[]</code>. One thing to note is that the <code>&amp;p[0]</code> version does cause g++ to emit a copy of the <code>operator[]</code> body, but it is never used, so there is a slight code bloat if you never use <code>operator[]</code> otherwise:</p>\n\n<p>The tested code was this (with the <code>#if</code> both 0 and 1):</p>\n\n<pre><code>#include &lt;boost/scoped_array.hpp&gt;\n#include &lt;cstdio&gt;\n\nint main() {\n boost::scoped_array&lt;int&gt; p(new int[10]);\n#if 1\n printf(\"%p\\n\", &amp;p[0]);\n#else\n printf(\"%p\\n\", p.get());\n#endif\n}\n</code></pre>\n" }, { "answer_id": 274242, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 0, "selected": false, "text": "<p>Is this a question you're asking just for academic interest or is this for some current code you're writing?</p>\n\n<p>In general, people recommend that code clarity is more important that speed, so unless your sure this is going to make a difference you should pick whichever option is clearer and matches your code base. FWIW, I personally think that the get() is clearer.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13430/" ]
The topic generically says it all. Basically in a situation like this: ``` boost::scoped_array<int> p(new int[10]); ``` Is there any appreciable difference in performance between doing: `&p[0]` and `p.get()`? I ask because I prefer the first one, it has a more natural pointer like syntax. In fact, it makes it so you could replace p with a native pointer or array and not have to change anything else. I am guessing since get is a one liner "`return ptr;`" that the compiler will inline that, and I hope that it is smart enough to to inline `operator[]` in such a way that it is able to not dereference and then immediately reference. Anyone know?
OK, I've done some basic tests as per Martin York's suggestions. It seems that g++ (4.3.2) is actually pretty good about this. At both -O2 and -O3 optimization levels, it outputs slightly different but functionally equivalent assembly for both `&p[0]` and `p.get()`. At -Os as expected, it took the path of least complexity and emits a call to the `operator[]`. One thing to note is that the `&p[0]` version does cause g++ to emit a copy of the `operator[]` body, but it is never used, so there is a slight code bloat if you never use `operator[]` otherwise: The tested code was this (with the `#if` both 0 and 1): ``` #include <boost/scoped_array.hpp> #include <cstdio> int main() { boost::scoped_array<int> p(new int[10]); #if 1 printf("%p\n", &p[0]); #else printf("%p\n", p.get()); #endif } ```
273,898
<p>I have two forms in microsoft access, one called Bill and the other one called Payment. They both have Total amount as a field in both of the forms. I am trying to reference the Bill total amount to the Payment total amount. </p> <p>I have tried in the Payment total amount control source : =Forms!Bill![Total Amount]</p> <p>but this doesnt seem to work. In Design view it says '#Name?' in the text box. </p> <p>How would you do this? </p>
[ { "answer_id": 273950, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "<p>Is either of the forms a subform? If so, you need to reference the subform control or the parent property:</p>\n\n<pre><code>Me.Parent.[Total order]\nMe.[Subform Control name Here].form.[Total order]\n</code></pre>\n\n<p>Note that the Subform Control name is not always the same as the form contained.</p>\n\n<p>EDIT: Either omit Me or use Form!FormName in a control.</p>\n\n<p>EDIT2: Please note that the usual way of referencing forms, subform and controls is with either bang (!) or dot (.). parentheses and quotes are rarely used. This can be seen in both the Microsoft Access MVPs site ( <a href=\"http://www.mvps.org/access/forms/frm0031.htm\" rel=\"nofollow noreferrer\">http://www.mvps.org/access/forms/frm0031.htm</a> ) and Microsoft's own site ( <a href=\"http://support.microsoft.com/kb/209099\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/209099</a> ), as mentioned by Knox.</p>\n\n<p>If not, have you tried the Expression builder? It will help ensure that you have the correct names.</p>\n\n<p>As an aside, it is best to avoid spaces in the names of fields and controls, it will save you a good deal of work. It is also best to rename controls so they do not have the same name as the fields they contain, txtOrderTotal, for example.</p>\n" }, { "answer_id": 274059, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 0, "selected": false, "text": "<p>Remou's answer only works in code - however it looks like you are defining the control source of a text box so try this: </p>\n\n<pre><code>=Forms(\"Bill\")![Total order]\n</code></pre>\n" }, { "answer_id": 277718, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "<p>My favorite solution is here always to go back to recordsets and calculate corresponding totals, as you are not <strong><em>allways sure</em></strong> that totals at form level are correctly updated (there might always be a pending control/recordset update for any reason). You have then the possibility to use the DSUM and related functions!</p>\n\n<p>Exemple:</p>\n\n<pre><code>dsum(Forms(\"Bill\").recordsource, \"unitPrice*lineQuantity\")\n</code></pre>\n\n<p>Of course you could have more complex solutions such as defining a temporary recordset to get your total amount per invoice.</p>\n\n<pre><code>Dim rs as DAO.recordset, _\n myBillNumber as variant, _\n myBillAmount as variant\n\nset rs = currentDb.openRecordset(_ \n \"SELECT billNumber, sum(unitPrice*lineQuantity) as totalPrice FROM \" &amp; _\n Forms(\"Bill\").recordset.name \" GROUP BY billNumber\")\n\nmyBillNumber = rs.fields(0)\nmyBillAmount = rs.fields(1)\n</code></pre>\n\n<p>It might seem complicated but once you get used to it you'll never hesitate to use it and you'll never ever have the kind of problem you are facing now.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have two forms in microsoft access, one called Bill and the other one called Payment. They both have Total amount as a field in both of the forms. I am trying to reference the Bill total amount to the Payment total amount. I have tried in the Payment total amount control source : =Forms!Bill![Total Amount] but this doesnt seem to work. In Design view it says '#Name?' in the text box. How would you do this?
Is either of the forms a subform? If so, you need to reference the subform control or the parent property: ``` Me.Parent.[Total order] Me.[Subform Control name Here].form.[Total order] ``` Note that the Subform Control name is not always the same as the form contained. EDIT: Either omit Me or use Form!FormName in a control. EDIT2: Please note that the usual way of referencing forms, subform and controls is with either bang (!) or dot (.). parentheses and quotes are rarely used. This can be seen in both the Microsoft Access MVPs site ( <http://www.mvps.org/access/forms/frm0031.htm> ) and Microsoft's own site ( <http://support.microsoft.com/kb/209099> ), as mentioned by Knox. If not, have you tried the Expression builder? It will help ensure that you have the correct names. As an aside, it is best to avoid spaces in the names of fields and controls, it will save you a good deal of work. It is also best to rename controls so they do not have the same name as the fields they contain, txtOrderTotal, for example.
273,908
<p>Problem: I have an integer; this integer needs to be converted to a stl::string type. </p> <p>In the past, I've used <code>stringstream</code> to do a conversion, and that's just kind of cumbersome. I know the C way is to do a <code>sprintf</code>, but I'd much rather do a C++ method that is typesafe(er).</p> <p>Is there a better way to do this? </p> <p>Here is the stringstream approach I have used in the past:</p> <pre><code>std::string intToString(int i) { std::stringstream ss; std::string s; ss &lt;&lt; i; s = ss.str(); return s; } </code></pre> <p>Of course, this could be rewritten as so:</p> <pre><code>template&lt;class T&gt; std::string t_to_string(T i) { std::stringstream ss; std::string s; ss &lt;&lt; i; s = ss.str(); return s; } </code></pre> <p>However, I have the notion that this is a fairly 'heavy-weight' implementation.</p> <p>Zan noted that the invocation is pretty nice, however:</p> <pre><code>std::string s = t_to_string(my_integer); </code></pre> <p>At any rate, a nicer way would be... nice. </p> <blockquote> <h3>Related:</h3> <p><a href="https://stackoverflow.com/questions/228005/alternative-to-itoa-for-converting-integer-to-string-c">Alternative to itoa() for converting integer to string C++?</a> </p> </blockquote>
[ { "answer_id": 273919, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 5, "selected": false, "text": "<p>Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).</p>\n" }, { "answer_id": 273961, "author": "Mic", "author_id": 35656, "author_profile": "https://Stackoverflow.com/users/35656", "pm_score": 5, "selected": false, "text": "<p>Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:</p>\n\n<pre><code>#include &lt;boost/lexical_cast.hpp&gt;\nstd::string s = boost::lexical_cast&lt;std::string&gt;(i);\n</code></pre>\n\n<p>it also provides some safety:</p>\n\n<pre><code>try{\n std::string s = boost::lexical_cast&lt;std::string&gt;(i);\n}catch(boost::bad_lexical_cast &amp;){\n ...\n}\n</code></pre>\n" }, { "answer_id": 8362045, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 8, "selected": true, "text": "<p>Now in c++11 we have</p>\n\n<pre><code>#include &lt;string&gt;\nstring s = std::to_string(123);\n</code></pre>\n\n<p>Link to reference: <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/to_string\">http://en.cppreference.com/w/cpp/string/basic_string/to_string</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26227/" ]
Problem: I have an integer; this integer needs to be converted to a stl::string type. In the past, I've used `stringstream` to do a conversion, and that's just kind of cumbersome. I know the C way is to do a `sprintf`, but I'd much rather do a C++ method that is typesafe(er). Is there a better way to do this? Here is the stringstream approach I have used in the past: ``` std::string intToString(int i) { std::stringstream ss; std::string s; ss << i; s = ss.str(); return s; } ``` Of course, this could be rewritten as so: ``` template<class T> std::string t_to_string(T i) { std::stringstream ss; std::string s; ss << i; s = ss.str(); return s; } ``` However, I have the notion that this is a fairly 'heavy-weight' implementation. Zan noted that the invocation is pretty nice, however: ``` std::string s = t_to_string(my_integer); ``` At any rate, a nicer way would be... nice. > > ### Related: > > > [Alternative to itoa() for converting integer to string C++?](https://stackoverflow.com/questions/228005/alternative-to-itoa-for-converting-integer-to-string-c) > > >
Now in c++11 we have ``` #include <string> string s = std::to_string(123); ``` Link to reference: <http://en.cppreference.com/w/cpp/string/basic_string/to_string>
273,909
<p>Is there a idiomatic way of removing elements from PATH-like shell variables?</p> <p>That is I want to take</p> <pre><code>PATH=/home/joe/bin:/usr/local/bin:/usr/bin:/bin:/path/to/app/bin:. </code></pre> <p>and <strong>remove</strong> or <strong>replace</strong> the <code>/path/to/app/bin</code> without clobbering the rest of the variable. Extra points for allowing me <em>put</em> new elements in arbitrary positions. The target will be recognizable by a well defined string, and may occur at any point in the list.</p> <p>I know I've seen this done, and can probably cobble something together on my own, but I'm looking for a nice approach. Portability and standardization a plus.</p> <p>I use bash, but example are welcome in your favorite shell as well.</p> <hr> <p>The context here is one of needing to switch conveniently between multiple versions (one for doing analysis, another for working on the framework) of a large scientific analysis package which produces a couple dozen executables, has data stashed around the filesystem, and uses environment variable to help find all this stuff. I would like to write a script that selects a version, and need to be able to remove the <code>$PATH</code> elements relating to the currently active version and replace them with the same elements relating to the new version.</p> <hr> <p>This is related to the problem of preventing repeated <code>$PATH</code> elements when re-running login scripts and the like.</p> <hr> <ul> <li>Previous similar question: <a href="https://stackoverflow.com/questions/135754/how-to-keep-from-duplicating-path-variable-in-csh">How to keep from duplicating path variable in csh</a></li> <li>Subsequent similar question: <a href="https://stackoverflow.com/questions/370047/what-is-the-most-elegant-way-to-remove-a-path-from-the-path-variable-in-bash">What is the most elegant way to remove a path from the $PATH variable in Bash?</a></li> </ul>
[ { "answer_id": 273998, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 2, "selected": false, "text": "<p>For deleting an element you can use sed:</p>\n\n<pre><code>#!/bin/bash\nNEW_PATH=$(echo -n $PATH | tr \":\" \"\\n\" | sed \"/foo/d\" | tr \"\\n\" \":\")\nexport PATH=$NEW_PATH\n</code></pre>\n\n<p>will delete the paths that contain \"foo\" from the path.</p>\n\n<p>You could also use sed to insert a new line before or after a given line.</p>\n\n<p>Edit: you can remove duplicates by piping through sort and uniq:</p>\n\n<pre><code>echo -n $PATH | tr \":\" \"\\n\" | sort | uniq -c | sed -n \"/ 1 / s/.*1 \\(.*\\)/\\1/p\" | sed \"/foo/d\" | tr \"\\n\" \":\"\n</code></pre>\n" }, { "answer_id": 274081, "author": "waynecolvin", "author_id": 35658, "author_profile": "https://Stackoverflow.com/users/35658", "pm_score": 0, "selected": false, "text": "<p>The first thing to pop into my head to change just part of a string is a sed substitution.</p>\n\n<p>example:\nif echo $PATH => \"/usr/pkg/bin:/usr/bin:/bin:/usr/pkg/games:/usr/pkg/X11R6/bin\"\nthen to change \"/usr/bin\" to \"/usr/local/bin\" could be done like this:</p>\n\n<p>## produces standard output file</p>\n\n<p>## the \"=\" character is used instead of slash (\"/\") since that would be messy,\n # alternative quoting character should be unlikely in PATH</p>\n\n<p>## the path separater character \":\" is both removed and re-added here,\n # might want an extra colon after the last path</p>\n\n<p>echo $PATH | sed '=/usr/bin:=/usr/local/bin:='</p>\n\n<p>This solution replaces an entire path-element so might be redundant if new-element is similar.</p>\n\n<p>If the new PATH'-s aren't dynamic but always within some constant set you could save <em>those</em> in a variable and assign as needed:</p>\n\n<p>PATH=$TEMP_PATH_1; \n # commands ... ; \\n\nPATH=$TEMP_PATH_2;\n # commands etc... ;</p>\n\n<p>Might not be what you were thinking. some of the relevant commands on bash/unix would be:</p>\n\n<p>pushd\npopd\ncd\nls # maybe l -1A for single column;\nfind\ngrep\nwhich # could confirm that file is where you think it came from;\nenv\ntype</p>\n\n<p>..and all that and more have <em>some</em> bearing on PATH or directories in general. The text altering part could be done any number of ways!</p>\n\n<p>Whatever solution chosen would have 4 parts:</p>\n\n<p>1) fetch the path as it is\n2) decode the path to find the part needing changes\n3) determing what changes are needed/integrating those changes\n4) validation/final integration/setting the variable</p>\n" }, { "answer_id": 274448, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>There are a couple of relevant programs in the answers to \"<a href=\"https://stackoverflow.com/questions/135754/how-to-keep-from-duplicating-path-variable-in-csh\">How to keep from duplicating path variable in csh</a>\". They concentrate more on ensuring that there are no repeated elements, but the script I provide can be used as:</p>\n\n<pre><code>export PATH=$(clnpath $head_dirs:$PATH:$tail_dirs $remove_dirs)\n</code></pre>\n\n<p>Assuming you have one or more directories in $head_dirs and one or more directories in $tail_dirs and one or more directories in $remove_dirs, then it uses the shell to concatenate the head, current and tail parts into a massive value, and then removes each of the directories listed in $remove_dirs from the result (not an error if they don't exist), as well as eliminating second and subsequent occurrences of any directory in the path.</p>\n\n<p>This does not address putting path components into a specific position (other than at the beginning or end, and those only indirectly). Notationally, specifying where you want to add the new element, or which element you want to replace, is messy.</p>\n" }, { "answer_id": 275035, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 1, "selected": false, "text": "<p>OK, thanks to all responders. I've prepared an encapsulated version of florin's answer. The first pass looks like this:</p>\n\n<pre><code># path_tools.bash\n#\n# A set of tools for manipulating \":\" separated lists like the\n# canonical $PATH variable.\n#\n# /bin/sh compatibility can probably be regained by replacing $( )\n# style command expansion with ` ` style\n###############################################################################\n# Usage:\n#\n# To remove a path:\n# replace-path PATH $PATH /exact/path/to/remove \n# replace-path-pattern PATH $PATH &lt;grep pattern for target path&gt; \n#\n# To replace a path:\n# replace-path PATH $PATH /exact/path/to/remove /replacement/path \n# replace-path-pattern PATH $PATH &lt;target pattern&gt; /replacement/path\n# \n###############################################################################\n# Finds the _first_ list element matching $2\n#\n# $1 name of a shell variable to be set\n# $2 name of a variable with a path-like structure\n# $3 a grep pattern to match the desired element of $1\nfunction path-element-by-pattern (){ \n target=$1;\n list=$2;\n pat=$3;\n\n export $target=$(echo -n $list | tr \":\" \"\\n\" | grep -m 1 $pat);\n return\n}\n\n# Removes or replaces an element of $1\n#\n# $1 name of the shell variable to set (i.e. PATH) \n# $2 a \":\" delimited list to work from (i.e. $PATH)\n# $2 the precise string to be removed/replaced\n# $3 the replacement string (use \"\" for removal)\nfunction replace-path () {\n path=$1;\n list=$2;\n removestr=$3;\n replacestr=$4; # Allowed to be \"\"\n\n export $path=$(echo -n $list | tr \":\" \"\\n\" | sed \"s|$removestr|$replacestr|\" | tr \"\\n\" \":\" | sed \"s|::|:|g\");\n unset removestr\n return \n}\n\n# Removes or replaces an element of $1\n#\n# $1 name of the shell variable to set (i.e. PATH) \n# $2 a \":\" delimited list to work from (i.e. $PATH)\n# $2 a grep pattern identifying the element to be removed/replaced\n# $3 the replacement string (use \"\" for removal)\nfunction replace-path-pattern () {\n path=$1;\n list=$2;\n removepat=$3; \n replacestr=$4; # Allowed to be \"\"\n\n path-element-by-pattern removestr $list $removepat;\n replace-path $path $list $removestr $replacestr;\n}\n</code></pre>\n\n<p>Still needs error trapping in all the functions, and I should probably stick in a repeated path solution while I'm at it. </p>\n\n<p>You use it by doing a <code>. /include/path/path_tools.bash</code> in the working script and calling on of the the <code>replace-path*</code> functions.</p>\n\n<hr>\n\n<p>I am still open to new and/or better answers.</p>\n" }, { "answer_id": 294025, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": true, "text": "<p>Addressing the proposed solution from dmckee:</p>\n\n<ol>\n<li>While some versions of Bash may allow hyphens in function names, others (MacOS X) do not.</li>\n<li>I don't see a need to use return immediately before the end of the function.</li>\n<li>I don't see the need for all the semi-colons.</li>\n<li>I don't see why you have path-element-by-pattern export a value. Think of <code>export</code> as equivalent to setting (or even creating) a global variable - something to be avoided whenever possible.</li>\n<li>I'm not sure what you expect '<code>replace-path PATH $PATH /usr</code>' to do, but it does not do what I would expect.</li>\n</ol>\n\n<p>Consider a PATH value that starts off containing:</p>\n\n<pre><code>.\n/Users/jleffler/bin\n/usr/local/postgresql/bin\n/usr/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/usr/local/bin\n/usr/bin\n/bin\n/sw/bin\n/usr/sbin\n/sbin\n</code></pre>\n\n<p>The result I got (from '<code>replace-path PATH $PATH /usr</code>') is:</p>\n\n<pre><code>.\n/Users/jleffler/bin\n/local/postgresql/bin\n/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/local/bin\n/bin\n/bin\n/sw/bin\n/sbin\n/sbin\n</code></pre>\n\n<p>I would have expected to get my original path back since /usr does not appear as a (complete) path element, only as part of a path element.</p>\n\n<p>This can be fixed in <code>replace-path</code> by modifying one of the <code>sed</code> commands:</p>\n\n<pre><code>export $path=$(echo -n $list | tr \":\" \"\\n\" | sed \"s:^$removestr\\$:$replacestr:\" |\n tr \"\\n\" \":\" | sed \"s|::|:|g\")\n</code></pre>\n\n<p>I used ':' instead of '|' to separate parts of the substitute since '|' could (in theory) appear in a path component, whereas by definition of PATH, a colon cannot. I observe that the second <code>sed</code> could eliminate the current directory from the middle of a PATH. That is, a legitimate (though perverse) value of PATH could be:</p>\n\n<pre><code>PATH=/bin::/usr/local/bin\n</code></pre>\n\n<p>After processing, the current directory would no longer be on the PATH.</p>\n\n<p>A similar change to anchor the match is appropriate in <code>path-element-by-pattern</code>:</p>\n\n<pre><code>export $target=$(echo -n $list | tr \":\" \"\\n\" | grep -m 1 \"^$pat\\$\")\n</code></pre>\n\n<p>I note in passing that <code>grep -m 1</code> is not standard (it is a GNU extension, also available on MacOS X). And, indeed, the<code>-n</code> option for <code>echo</code> is also non-standard; you would be better off simply deleting the trailing colon that is added by virtue of converting the newline from echo into a colon. Since path-element-by-pattern is used just once, has undesirable side-effects (it clobbers any pre-existing exported variable called <code>$removestr</code>), it can be replaced sensibly by its body. This, along with more liberal use of quotes to avoid problems with spaces or unwanted file name expansion, leads to:</p>\n\n<pre><code># path_tools.bash\n#\n# A set of tools for manipulating \":\" separated lists like the\n# canonical $PATH variable.\n#\n# /bin/sh compatibility can probably be regained by replacing $( )\n# style command expansion with ` ` style\n###############################################################################\n# Usage:\n#\n# To remove a path:\n# replace_path PATH $PATH /exact/path/to/remove\n# replace_path_pattern PATH $PATH &lt;grep pattern for target path&gt;\n#\n# To replace a path:\n# replace_path PATH $PATH /exact/path/to/remove /replacement/path\n# replace_path_pattern PATH $PATH &lt;target pattern&gt; /replacement/path\n#\n###############################################################################\n\n# Remove or replace an element of $1\n#\n# $1 name of the shell variable to set (e.g. PATH)\n# $2 a \":\" delimited list to work from (e.g. $PATH)\n# $3 the precise string to be removed/replaced\n# $4 the replacement string (use \"\" for removal)\nfunction replace_path () {\n path=$1\n list=$2\n remove=$3\n replace=$4 # Allowed to be empty or unset\n\n export $path=$(echo \"$list\" | tr \":\" \"\\n\" | sed \"s:^$remove\\$:$replace:\" |\n tr \"\\n\" \":\" | sed 's|:$||')\n}\n\n# Remove or replace an element of $1\n#\n# $1 name of the shell variable to set (e.g. PATH)\n# $2 a \":\" delimited list to work from (e.g. $PATH)\n# $3 a grep pattern identifying the element to be removed/replaced\n# $4 the replacement string (use \"\" for removal)\nfunction replace_path_pattern () {\n path=$1\n list=$2\n removepat=$3\n replacestr=$4 # Allowed to be empty or unset\n\n removestr=$(echo \"$list\" | tr \":\" \"\\n\" | grep -m 1 \"^$removepat\\$\")\n replace_path \"$path\" \"$list\" \"$removestr\" \"$replacestr\"\n}\n</code></pre>\n\n<p>I have a Perl script called <code>echopath</code> which I find useful when debugging problems with PATH-like variables:</p>\n\n<pre><code>#!/usr/bin/perl -w\n#\n# \"@(#)$Id: echopath.pl,v 1.7 1998/09/15 03:16:36 jleffler Exp $\"\n#\n# Print the components of a PATH variable one per line.\n# If there are no colons in the arguments, assume that they are\n# the names of environment variables.\n\n@ARGV = $ENV{PATH} unless @ARGV;\n\nforeach $arg (@ARGV)\n{\n $var = $arg;\n $var = $ENV{$arg} if $arg =~ /^[A-Za-z_][A-Za-z_0-9]*$/;\n $var = $arg unless $var;\n @lst = split /:/, $var;\n foreach $val (@lst)\n {\n print \"$val\\n\";\n }\n}\n</code></pre>\n\n<p>When I run the modified solution on the test code below:</p>\n\n<pre><code>echo\nxpath=$PATH\nreplace_path xpath $xpath /usr\nechopath $xpath\n\necho\nxpath=$PATH\nreplace_path_pattern xpath $xpath /usr/bin /work/bin\nechopath xpath\n\necho\nxpath=$PATH\nreplace_path_pattern xpath $xpath \"/usr/.*/bin\" /work/bin\nechopath xpath\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>.\n/Users/jleffler/bin\n/usr/local/postgresql/bin\n/usr/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/usr/local/bin\n/usr/bin\n/bin\n/sw/bin\n/usr/sbin\n/sbin\n\n.\n/Users/jleffler/bin\n/usr/local/postgresql/bin\n/usr/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/usr/local/bin\n/work/bin\n/bin\n/sw/bin\n/usr/sbin\n/sbin\n\n.\n/Users/jleffler/bin\n/work/bin\n/usr/local/mysql/bin\n/Users/jleffler/perl/v5.10.0/bin\n/usr/local/bin\n/usr/bin\n/bin\n/sw/bin\n/usr/sbin\n/sbin\n</code></pre>\n\n<p>This looks correct to me - at least, for my definition of what the problem is.</p>\n\n<p>I note that <code>echopath LD_LIBRARY_PATH</code> evaluates <code>$LD_LIBRARY_PATH</code>. It would be nice if your functions were able to do that, so the user could type:</p>\n\n<pre><code>replace_path PATH /usr/bin /work/bin\n</code></pre>\n\n<p>That can be done by using:</p>\n\n<pre><code>list=$(eval echo '$'$path)\n</code></pre>\n\n<p>This leads to this revision of the code:</p>\n\n<pre><code># path_tools.bash\n#\n# A set of tools for manipulating \":\" separated lists like the\n# canonical $PATH variable.\n#\n# /bin/sh compatibility can probably be regained by replacing $( )\n# style command expansion with ` ` style\n###############################################################################\n# Usage:\n#\n# To remove a path:\n# replace_path PATH /exact/path/to/remove\n# replace_path_pattern PATH &lt;grep pattern for target path&gt;\n#\n# To replace a path:\n# replace_path PATH /exact/path/to/remove /replacement/path\n# replace_path_pattern PATH &lt;target pattern&gt; /replacement/path\n#\n###############################################################################\n\n# Remove or replace an element of $1\n#\n# $1 name of the shell variable to set (e.g. PATH)\n# $2 the precise string to be removed/replaced\n# $3 the replacement string (use \"\" for removal)\nfunction replace_path () {\n path=$1\n list=$(eval echo '$'$path)\n remove=$2\n replace=$3 # Allowed to be empty or unset\n\n export $path=$(echo \"$list\" | tr \":\" \"\\n\" | sed \"s:^$remove\\$:$replace:\" |\n tr \"\\n\" \":\" | sed 's|:$||')\n}\n\n# Remove or replace an element of $1\n#\n# $1 name of the shell variable to set (e.g. PATH)\n# $2 a grep pattern identifying the element to be removed/replaced\n# $3 the replacement string (use \"\" for removal)\nfunction replace_path_pattern () {\n path=$1\n list=$(eval echo '$'$path)\n removepat=$2\n replacestr=$3 # Allowed to be empty or unset\n\n removestr=$(echo \"$list\" | tr \":\" \"\\n\" | grep -m 1 \"^$removepat\\$\")\n replace_path \"$path\" \"$removestr\" \"$replacestr\"\n}\n</code></pre>\n\n<p>The following revised test now works too:</p>\n\n<pre><code>echo\nxpath=$PATH\nreplace_path xpath /usr\nechopath xpath\n\necho\nxpath=$PATH\nreplace_path_pattern xpath /usr/bin /work/bin\nechopath xpath\n\necho\nxpath=$PATH\nreplace_path_pattern xpath \"/usr/.*/bin\" /work/bin\nechopath xpath\n</code></pre>\n\n<p>It produces the same output as before.</p>\n" }, { "answer_id": 294156, "author": "dj_segfault", "author_id": 14924, "author_profile": "https://Stackoverflow.com/users/14924", "pm_score": 2, "selected": false, "text": "<p>Just a note that bash itself can do search and replace. It can do all the normal \"once or all\", cases [in]sensitive options you would expect.</p>\n\n<p>From the man page:</p>\n\n<p><code>${parameter/pattern/string}</code></p>\n\n<p>The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If Ipattern begins with <code>/</code>, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with <code>#</code>, it must match at the beginning of the expanded value of parameter. If pattern begins with <code>%</code>, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the <code>/</code> following pattern may be omitted. If parameter is <code>@</code> or <code>*</code>, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with <code>@</code> or\n<code>*</code>, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.</p>\n\n<p>You can also do field splitting by setting <code>$IFS</code> (input field separator) to the desired delimiter.</p>\n" }, { "answer_id": 346860, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "<p>This is easy using awk.</p>\n\n<h3>Replace</h3>\n\n<pre><code>{\n for(i=1;i&lt;=NF;i++) \n if($i == REM) \n if(REP)\n print REP; \n else\n continue;\n else \n print $i; \n}\n</code></pre>\n\n<p>Start it using </p>\n\n<pre><code>function path_repl {\n echo $PATH | awk -F: -f rem.awk REM=\"$1\" REP=\"$2\" | paste -sd:\n}\n\n$ echo $PATH\n/bin:/usr/bin:/home/js/usr/bin\n$ path_repl /bin /baz\n/baz:/usr/bin:/home/js/usr/bin\n$ path_repl /bin\n/usr/bin:/home/js/usr/bin\n</code></pre>\n\n<h3>Append</h3>\n\n<p>Inserts at the given position. By default, it appends at the end.</p>\n\n<pre><code>{ \n if(IDX &lt; 1) IDX = NF + IDX + 1\n for(i = 1; i &lt;= NF; i++) {\n if(IDX == i) \n print REP \n print $i\n }\n if(IDX == NF + 1)\n print REP\n}\n</code></pre>\n\n<p>Start it using </p>\n\n<pre><code>function path_app {\n echo $PATH | awk -F: -f app.awk REP=\"$1\" IDX=\"$2\" | paste -sd:\n}\n\n$ echo $PATH\n/bin:/usr/bin:/home/js/usr/bin\n$ path_app /baz 0\n/bin:/usr/bin:/home/js/usr/bin:/baz\n$ path_app /baz -1\n/bin:/usr/bin:/baz:/home/js/usr/bin\n$ path_app /baz 1\n/baz:/bin:/usr/bin:/home/js/usr/bin\n</code></pre>\n\n<h3>Remove duplicates</h3>\n\n<p>This one keeps the first occurences.</p>\n\n<pre><code>{ \n for(i = 1; i &lt;= NF; i++) {\n if(!used[$i]) {\n print $i\n used[$i] = 1\n }\n }\n}\n</code></pre>\n\n<p>Start it like this:</p>\n\n<pre><code>echo $PATH | awk -F: -f rem_dup.awk | paste -sd:\n</code></pre>\n\n<h3>Validate whether all elements exist</h3>\n\n<p>The following will print an error message for all entries that are not existing in the filesystem, and return a nonzero value.</p>\n\n<pre><code>echo -n $PATH | xargs -d: stat -c %n\n</code></pre>\n\n<p>To simply check whether all elements are paths and get a return code, you can also use <code>test</code>:</p>\n\n<pre><code>echo -n $PATH | xargs -d: -n1 test -d\n</code></pre>\n" }, { "answer_id": 373476, "author": "nicerobot", "author_id": 23056, "author_profile": "https://Stackoverflow.com/users/23056", "pm_score": 3, "selected": false, "text": "<p>Reposting my answer to <a href=\"https://stackoverflow.com/questions/370047/what-is-the-most-elegant-way-to-remove-a-path-from-the-path-variable-in-bash#370255\">What is the most elegant way to remove a path from the $PATH variable in Bash?</a> :</p>\n\n<pre><code>#!/bin/bash\nIFS=:\n# convert it to an array\nt=($PATH)\nunset IFS\n# perform any array operations to remove elements from the array\nt=(${t[@]%%*usr*})\nIFS=:\n# output the new array\necho \"${t[*]}\"\n</code></pre>\n\n<p>or the one-liner:</p>\n\n<pre><code>PATH=$(IFS=':';t=($PATH);unset IFS;t=(${t[@]%%*usr*});IFS=':';echo \"${t[*]}\");\n</code></pre>\n" }, { "answer_id": 7593620, "author": "nash", "author_id": 970554, "author_profile": "https://Stackoverflow.com/users/970554", "pm_score": 1, "selected": false, "text": "<p>suppose </p>\n\n<pre><code>echo $PATH\n/usr/lib/jvm/java-1.6.0/bin:lib/jvm/java-1.6.0/bin/:/lib/jvm/java-1.6.0/bin/:/usr/lib/qt-3.3/bin:/usr/lib/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/tvnadeesh/bin\n</code></pre>\n\n<p>If you want to remove /lib/jvm/java-1.6.0/bin/ do like as below </p>\n\n<pre><code>export PATH=$(echo $PATH | sed 's/\\/lib\\/jvm\\/java-1.6.0\\/bin\\/://g')\n</code></pre>\n\n<p><code>sed</code> will take input from <code>echo $PATH</code> and replace /lib/jvm/java-1.6.0/bin/: with empty</p>\n\n<p>in this way you can remove</p>\n" }, { "answer_id": 11939195, "author": "GreenFox", "author_id": 1594168, "author_profile": "https://Stackoverflow.com/users/1594168", "pm_score": 1, "selected": false, "text": "<ul>\n<li>Order of PATH is not distrubed </li>\n<li>Handles corner cases like empty path, space in path gracefully</li>\n<li>Partial match of dir does not give false positives</li>\n<li>Treats path at head and tail of PATH in proper ways. No <strong>:</strong> garbage and such.</li>\n</ul>\n\n<p>Say you have\n /foo:/some/path:/some/path/dir1:/some/path/dir2:/bar\nand you want to replace \n /some/path\nThen it correctly replaces \"/some/path\" but \nleaves \"/some/path/dir1\" or \"/some/path/dir2\", as what you would expect.</p>\n\n<pre><code>function __path_add(){ \n if [ -d \"$1\" ] ; then \n local D=\":${PATH}:\"; \n [ \"${D/:$1:/:}\" == \"$D\" ] &amp;&amp; PATH=\"$PATH:$1\"; \n PATH=\"${PATH/#:/}\"; \n export PATH=\"${PATH/%:/}\"; \n fi \n}\nfunction __path_remove(){ \n local D=\":${PATH}:\"; \n [ \"${D/:$1:/:}\" != \"$D\" ] &amp;&amp; PATH=\"${D/:$1:/:}\"; \n PATH=\"${PATH/#:/}\"; \n export PATH=\"${PATH/%:/}\"; \n} \n# Just for the shake of completeness\nfunction __path_replace(){ \n if [ -d \"$2\" ] ; then \n local D=\":${PATH}:\"; \n if [ \"${D/:$1:/:}\" != \"$D\" ] ; then\n PATH=\"${D/:$1:/:$2:}\"; \n PATH=\"${PATH/#:/}\"; \n export PATH=\"${PATH/%:/}\"; \n fi\n fi \n} \n</code></pre>\n\n<p>Related post\n<a href=\"https://stackoverflow.com/questions/370047/what-is-the-most-elegant-way-to-remove-a-path-from-the-path-variable-in-bash/11926946#11926946\">What is the most elegant way to remove a path from the $PATH variable in Bash?</a></p>\n" }, { "answer_id": 25749546, "author": "derekm", "author_id": 2355587, "author_profile": "https://Stackoverflow.com/users/2355587", "pm_score": 0, "selected": false, "text": "<p>In line with <a href=\"https://stackoverflow.com/a/294156/2355587\">dj_segfault's answer</a>, I do this in scripts that append/prepend environment variables that might be executed multiple times:</p>\n\n<pre><code>ld_library_path=${ORACLE_HOME}/lib\nLD_LIBRARY_PATH=${LD_LIBRARY_PATH//${ld_library_path}?(:)/}\nexport LD_LIBRARY_PATH=${ld_library_path}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\n</code></pre>\n\n<p>Using this same technique to remove, replace or manipulate entries in PATH is trivial given the filename-expansion-like pattern matching and pattern-list support of shell parameter expansion.</p>\n" }, { "answer_id": 56151409, "author": "Steeve McCauley", "author_id": 916462, "author_profile": "https://Stackoverflow.com/users/916462", "pm_score": 1, "selected": false, "text": "<p>I prefer using ruby to the likes of awk/sed/foo these days, so here's my approach to deal with dupes,</p>\n\n<pre><code># add it to the path\nPATH=~/bin/:$PATH:~/bin\nexport PATH=$(ruby -e 'puts ENV[\"PATH\"].split(/:/).uniq.join(\":\")')\n</code></pre>\n\n<p>create a function for reuse,</p>\n\n<pre><code>mungepath() {\n export PATH=$(ruby -e 'puts ENV[\"PATH\"].split(/:/).uniq.join(\":\")')\n}\n</code></pre>\n\n<p>Hash, arrays and strings in a ruby one liner :)</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2509/" ]
Is there a idiomatic way of removing elements from PATH-like shell variables? That is I want to take ``` PATH=/home/joe/bin:/usr/local/bin:/usr/bin:/bin:/path/to/app/bin:. ``` and **remove** or **replace** the `/path/to/app/bin` without clobbering the rest of the variable. Extra points for allowing me *put* new elements in arbitrary positions. The target will be recognizable by a well defined string, and may occur at any point in the list. I know I've seen this done, and can probably cobble something together on my own, but I'm looking for a nice approach. Portability and standardization a plus. I use bash, but example are welcome in your favorite shell as well. --- The context here is one of needing to switch conveniently between multiple versions (one for doing analysis, another for working on the framework) of a large scientific analysis package which produces a couple dozen executables, has data stashed around the filesystem, and uses environment variable to help find all this stuff. I would like to write a script that selects a version, and need to be able to remove the `$PATH` elements relating to the currently active version and replace them with the same elements relating to the new version. --- This is related to the problem of preventing repeated `$PATH` elements when re-running login scripts and the like. --- * Previous similar question: [How to keep from duplicating path variable in csh](https://stackoverflow.com/questions/135754/how-to-keep-from-duplicating-path-variable-in-csh) * Subsequent similar question: [What is the most elegant way to remove a path from the $PATH variable in Bash?](https://stackoverflow.com/questions/370047/what-is-the-most-elegant-way-to-remove-a-path-from-the-path-variable-in-bash)
Addressing the proposed solution from dmckee: 1. While some versions of Bash may allow hyphens in function names, others (MacOS X) do not. 2. I don't see a need to use return immediately before the end of the function. 3. I don't see the need for all the semi-colons. 4. I don't see why you have path-element-by-pattern export a value. Think of `export` as equivalent to setting (or even creating) a global variable - something to be avoided whenever possible. 5. I'm not sure what you expect '`replace-path PATH $PATH /usr`' to do, but it does not do what I would expect. Consider a PATH value that starts off containing: ``` . /Users/jleffler/bin /usr/local/postgresql/bin /usr/local/mysql/bin /Users/jleffler/perl/v5.10.0/bin /usr/local/bin /usr/bin /bin /sw/bin /usr/sbin /sbin ``` The result I got (from '`replace-path PATH $PATH /usr`') is: ``` . /Users/jleffler/bin /local/postgresql/bin /local/mysql/bin /Users/jleffler/perl/v5.10.0/bin /local/bin /bin /bin /sw/bin /sbin /sbin ``` I would have expected to get my original path back since /usr does not appear as a (complete) path element, only as part of a path element. This can be fixed in `replace-path` by modifying one of the `sed` commands: ``` export $path=$(echo -n $list | tr ":" "\n" | sed "s:^$removestr\$:$replacestr:" | tr "\n" ":" | sed "s|::|:|g") ``` I used ':' instead of '|' to separate parts of the substitute since '|' could (in theory) appear in a path component, whereas by definition of PATH, a colon cannot. I observe that the second `sed` could eliminate the current directory from the middle of a PATH. That is, a legitimate (though perverse) value of PATH could be: ``` PATH=/bin::/usr/local/bin ``` After processing, the current directory would no longer be on the PATH. A similar change to anchor the match is appropriate in `path-element-by-pattern`: ``` export $target=$(echo -n $list | tr ":" "\n" | grep -m 1 "^$pat\$") ``` I note in passing that `grep -m 1` is not standard (it is a GNU extension, also available on MacOS X). And, indeed, the`-n` option for `echo` is also non-standard; you would be better off simply deleting the trailing colon that is added by virtue of converting the newline from echo into a colon. Since path-element-by-pattern is used just once, has undesirable side-effects (it clobbers any pre-existing exported variable called `$removestr`), it can be replaced sensibly by its body. This, along with more liberal use of quotes to avoid problems with spaces or unwanted file name expansion, leads to: ``` # path_tools.bash # # A set of tools for manipulating ":" separated lists like the # canonical $PATH variable. # # /bin/sh compatibility can probably be regained by replacing $( ) # style command expansion with ` ` style ############################################################################### # Usage: # # To remove a path: # replace_path PATH $PATH /exact/path/to/remove # replace_path_pattern PATH $PATH <grep pattern for target path> # # To replace a path: # replace_path PATH $PATH /exact/path/to/remove /replacement/path # replace_path_pattern PATH $PATH <target pattern> /replacement/path # ############################################################################### # Remove or replace an element of $1 # # $1 name of the shell variable to set (e.g. PATH) # $2 a ":" delimited list to work from (e.g. $PATH) # $3 the precise string to be removed/replaced # $4 the replacement string (use "" for removal) function replace_path () { path=$1 list=$2 remove=$3 replace=$4 # Allowed to be empty or unset export $path=$(echo "$list" | tr ":" "\n" | sed "s:^$remove\$:$replace:" | tr "\n" ":" | sed 's|:$||') } # Remove or replace an element of $1 # # $1 name of the shell variable to set (e.g. PATH) # $2 a ":" delimited list to work from (e.g. $PATH) # $3 a grep pattern identifying the element to be removed/replaced # $4 the replacement string (use "" for removal) function replace_path_pattern () { path=$1 list=$2 removepat=$3 replacestr=$4 # Allowed to be empty or unset removestr=$(echo "$list" | tr ":" "\n" | grep -m 1 "^$removepat\$") replace_path "$path" "$list" "$removestr" "$replacestr" } ``` I have a Perl script called `echopath` which I find useful when debugging problems with PATH-like variables: ``` #!/usr/bin/perl -w # # "@(#)$Id: echopath.pl,v 1.7 1998/09/15 03:16:36 jleffler Exp $" # # Print the components of a PATH variable one per line. # If there are no colons in the arguments, assume that they are # the names of environment variables. @ARGV = $ENV{PATH} unless @ARGV; foreach $arg (@ARGV) { $var = $arg; $var = $ENV{$arg} if $arg =~ /^[A-Za-z_][A-Za-z_0-9]*$/; $var = $arg unless $var; @lst = split /:/, $var; foreach $val (@lst) { print "$val\n"; } } ``` When I run the modified solution on the test code below: ``` echo xpath=$PATH replace_path xpath $xpath /usr echopath $xpath echo xpath=$PATH replace_path_pattern xpath $xpath /usr/bin /work/bin echopath xpath echo xpath=$PATH replace_path_pattern xpath $xpath "/usr/.*/bin" /work/bin echopath xpath ``` The output is: ``` . /Users/jleffler/bin /usr/local/postgresql/bin /usr/local/mysql/bin /Users/jleffler/perl/v5.10.0/bin /usr/local/bin /usr/bin /bin /sw/bin /usr/sbin /sbin . /Users/jleffler/bin /usr/local/postgresql/bin /usr/local/mysql/bin /Users/jleffler/perl/v5.10.0/bin /usr/local/bin /work/bin /bin /sw/bin /usr/sbin /sbin . /Users/jleffler/bin /work/bin /usr/local/mysql/bin /Users/jleffler/perl/v5.10.0/bin /usr/local/bin /usr/bin /bin /sw/bin /usr/sbin /sbin ``` This looks correct to me - at least, for my definition of what the problem is. I note that `echopath LD_LIBRARY_PATH` evaluates `$LD_LIBRARY_PATH`. It would be nice if your functions were able to do that, so the user could type: ``` replace_path PATH /usr/bin /work/bin ``` That can be done by using: ``` list=$(eval echo '$'$path) ``` This leads to this revision of the code: ``` # path_tools.bash # # A set of tools for manipulating ":" separated lists like the # canonical $PATH variable. # # /bin/sh compatibility can probably be regained by replacing $( ) # style command expansion with ` ` style ############################################################################### # Usage: # # To remove a path: # replace_path PATH /exact/path/to/remove # replace_path_pattern PATH <grep pattern for target path> # # To replace a path: # replace_path PATH /exact/path/to/remove /replacement/path # replace_path_pattern PATH <target pattern> /replacement/path # ############################################################################### # Remove or replace an element of $1 # # $1 name of the shell variable to set (e.g. PATH) # $2 the precise string to be removed/replaced # $3 the replacement string (use "" for removal) function replace_path () { path=$1 list=$(eval echo '$'$path) remove=$2 replace=$3 # Allowed to be empty or unset export $path=$(echo "$list" | tr ":" "\n" | sed "s:^$remove\$:$replace:" | tr "\n" ":" | sed 's|:$||') } # Remove or replace an element of $1 # # $1 name of the shell variable to set (e.g. PATH) # $2 a grep pattern identifying the element to be removed/replaced # $3 the replacement string (use "" for removal) function replace_path_pattern () { path=$1 list=$(eval echo '$'$path) removepat=$2 replacestr=$3 # Allowed to be empty or unset removestr=$(echo "$list" | tr ":" "\n" | grep -m 1 "^$removepat\$") replace_path "$path" "$removestr" "$replacestr" } ``` The following revised test now works too: ``` echo xpath=$PATH replace_path xpath /usr echopath xpath echo xpath=$PATH replace_path_pattern xpath /usr/bin /work/bin echopath xpath echo xpath=$PATH replace_path_pattern xpath "/usr/.*/bin" /work/bin echopath xpath ``` It produces the same output as before.
273,929
<p><strong>In Oracle I can declare a reference cursor...</strong></p> <pre><code>TYPE t_spool IS REF CURSOR RETURN spool%ROWTYPE; </code></pre> <p><strong>...and use it to pass a cursor as the return value...</strong></p> <pre><code>FUNCTION end_spool RETURN t_spool AS v_spool t_spool; BEGIN COMMIT; OPEN v_spool FOR SELECT * FROM spool WHERE key = g_spool_key ORDER BY seq; RETURN v_spool; END end_spool; </code></pre> <p><strong>...and then capture it as a result set using JDBC...</strong></p> <pre><code>private Connection conn; private CallableStatement stmt; private OracleResultSet rset; [...clip...] stmt = conn.prepareCall("{ ? = call " + call + "}"); stmt.registerOutParameter(1, OracleTypes.CURSOR); stmt.execute(); rset = (OracleResultSet)stmt.getObject(1); </code></pre> <p><strong>What is the equivalent in MySQL?</strong></p>
[ { "answer_id": 274399, "author": "Spencer Kormos", "author_id": 8528, "author_profile": "https://Stackoverflow.com/users/8528", "pm_score": 2, "selected": false, "text": "<p>Googling on cursors in MySQL, it doesn't seem like you can actually return a Cursor from a Proc or Function. Additionally, I found the following in the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-implementation-notes.html\" rel=\"nofollow noreferrer\">MySQL JDBC manual</a>:</p>\n\n<p>\"MySQL does not support SQL cursors, and the JDBC driver doesn't emulate them, so \"setCursorName()\" has no effect.\"</p>\n\n<p>In general, I believe Oracle's implementation here breaks JDBC, and is not used elsewhere (MySQL, MSSQL, etc). You should be returning your results as a select statement and iterating over the JDBC ResultSet, as is standard (and intended) practice when using JDBC.</p>\n" }, { "answer_id": 445434, "author": "Yoni", "author_id": 36071, "author_profile": "https://Stackoverflow.com/users/36071", "pm_score": 3, "selected": false, "text": "<p>Mysql has an implicit cursor that you can magically return from a stored procedure if you issue a select.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>CREATE PROCEDURE `TEST`()\nMODIFIES SQL DATA\nBEGIN\n SELECT * FROM test_table;\nEND;\n</code></pre>\n\n<p>and in your java code:</p>\n\n<pre><code>String query = \"{CALL TEST()}\";\nCallableStatement cs = con.prepareCall(query,\n ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_READ_ONLY);\nResultSet rs = cs.executeQuery();\n</code></pre>\n" }, { "answer_id": 2952466, "author": "manuel rodriguez coria", "author_id": 355774, "author_profile": "https://Stackoverflow.com/users/355774", "pm_score": -1, "selected": false, "text": "<p>fill a temporary table in a procedure and just read the temporary table... :)</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
**In Oracle I can declare a reference cursor...** ``` TYPE t_spool IS REF CURSOR RETURN spool%ROWTYPE; ``` **...and use it to pass a cursor as the return value...** ``` FUNCTION end_spool RETURN t_spool AS v_spool t_spool; BEGIN COMMIT; OPEN v_spool FOR SELECT * FROM spool WHERE key = g_spool_key ORDER BY seq; RETURN v_spool; END end_spool; ``` **...and then capture it as a result set using JDBC...** ``` private Connection conn; private CallableStatement stmt; private OracleResultSet rset; [...clip...] stmt = conn.prepareCall("{ ? = call " + call + "}"); stmt.registerOutParameter(1, OracleTypes.CURSOR); stmt.execute(); rset = (OracleResultSet)stmt.getObject(1); ``` **What is the equivalent in MySQL?**
Mysql has an implicit cursor that you can magically return from a stored procedure if you issue a select. Here's an example: ``` CREATE PROCEDURE `TEST`() MODIFIES SQL DATA BEGIN SELECT * FROM test_table; END; ``` and in your java code: ``` String query = "{CALL TEST()}"; CallableStatement cs = con.prepareCall(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = cs.executeQuery(); ```
273,937
<p>I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class. </p> <p>Here is the code</p> <pre><code>import wx class mainPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) menubar = wx.MenuBar() parser = wx.Menu() one =wx.MenuItem(parser,1,'&amp;Extract Tables with One Heading or Label') two =wx.MenuItem(parser,1,'&amp;Extract Tables with Two Headings or Labels') three =wx.MenuItem(parser,1,'&amp;Extract Tables with Three Headings or Labels') four =wx.MenuItem(parser,1,'&amp;Extract Tables with Four Headings or Labels') quit = wx.MenuItem(parser, 2, '&amp;Quit\tCtrl+Q') parser.AppendItem(one) parser.AppendItem(two) parser.AppendItem(three) parser.AppendItem(four) parser.AppendItem(quit) menubar.Append(parser, '&amp;Table Parsers') textRip = wx.Menu() section =wx.MenuItem(parser,1,'&amp;Extract Text With Section Headings') textRip.AppendItem(section) menubar.Append(textRip, '&amp;Text Rippers') dataHandling = wx.Menu() deHydrate =wx.MenuItem(dataHandling,1,'&amp;Extract Data from Tables') dataHandling.AppendItem(deHydrate) menubar.Append(dataHandling, '&amp;Data Extraction') self.Bind(wx.EVT_MENU, self.OnQuit, id=2) </code></pre> <h1>this is where I think I am being clever by using a button click to create an instance</h1> <h1>of subPanel.</h1> <pre><code> self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) self.SetMenuBar(menubar) self.Centre() self.Show(True) def OnQuit(self, event): self.Close() class subPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350)) getDirectory.SetDefault() getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400)) getTerm1.SetDefault() #getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button) self.Centre() self.Show(True) app = wx.App() mainPanel(None, -1, '') app.MainLoop() </code></pre>
[ { "answer_id": 274004, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 1, "selected": false, "text": "<p>I don't know wxWidgets, but based on what I know of Python, I'm guessing that you need to change:</p>\n\n<pre><code>self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1)\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>self.Bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1)\n</code></pre>\n\n<p>\"subPanel\" is a globally defined class, not a member of \"self\" (which is a mainPanel).</p>\n\n<p>Edit: Ah, \"Bind\" seems to bind an action to a function, so you need to give it a function that creates the other class. Try the following. It still doesn't work, but at least it now crashes during the subPanel creation.</p>\n\n<pre><code>self.Bind(wx.EVT_MENU, lambda(x): subPanel(None, -1, 'TEST'),id=1)\n</code></pre>\n" }, { "answer_id": 274145, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 1, "selected": false, "text": "<p>You should handle the button click event, and create the panel in your button handler (like you already do with your OnQuit method).</p>\n\n<p>I think the following code basically does what you're after -- creates a new Frame when the button is clicked/menu item is selected.</p>\n\n<pre><code>import wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent, title=\"My Frame\", num=1):\n\n self.num = num\n wx.Frame.__init__(self, parent, -1, title)\n panel = wx.Panel(self)\n\n button = wx.Button(panel, -1, \"New Panel\")\n button.SetPosition((15, 15))\n self.Bind(wx.EVT_BUTTON, self.OnNewPanel, button)\n self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)\n\n # Now create a menu\n menubar = wx.MenuBar()\n self.SetMenuBar(menubar)\n\n # Panel menu\n panel_menu = wx.Menu()\n\n # The menu item\n menu_newpanel = wx.MenuItem(panel_menu,\n wx.NewId(),\n \"&amp;New Panel\",\n \"Creates a new panel\",\n wx.ITEM_NORMAL)\n panel_menu.AppendItem(menu_newpanel)\n\n menubar.Append(panel_menu, \"&amp;Panels\")\n # Bind the menu event\n self.Bind(wx.EVT_MENU, self.OnNewPanel, menu_newpanel)\n\n def OnNewPanel(self, event):\n panel = MyFrame(self, \"Panel %s\" % self.num, self.num+1)\n panel.Show()\n\n def OnCloseWindow(self, event):\n self.Destroy()\n\ndef main():\n application = wx.PySimpleApp()\n frame = MyFrame(None)\n frame.Show()\n application.MainLoop()\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<hr>\n\n<p><strong>Edit</strong>: Added code to do this from a menu.</p>\n" }, { "answer_id": 274160, "author": "DrBloodmoney", "author_id": 35681, "author_profile": "https://Stackoverflow.com/users/35681", "pm_score": 1, "selected": true, "text": "<p>You need an event handler in your bind expression</p>\n\n<pre><code>self.bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1)\n</code></pre>\n\n<p>needs to be changed to:</p>\n\n<pre><code>self.bind(wx.EVT_MENU, &lt;event handler&gt;, &lt;id of menu item&gt;)\n</code></pre>\n\n<p>where your event handler responds to the event and instantiates the subpanel:</p>\n\n<pre><code>def OnMenuItem(self, evt): #don't forget the evt\n sp = SubPanel(self, wx.ID_ANY, 'TEST')\n #I assume you will add it to a sizer\n #if you aren't... you should\n test_sizer.Add(sp, 1, wx.EXPAND)\n #force the frame to refresh the sizers:\n self.Layout()\n</code></pre>\n\n<p>Alternatively, you can instantiate the subpanel in your frame's <code>__init__</code> and call a <code>subpanel.Hide()</code> after instantiation, and then your menuitem event handler and call a show on the panel <code>subpanel.Show()</code></p>\n\n<p>Edit: Here is some code that will do what I think that you are asking:</p>\n\n<pre><code>#!usr/bin/env python\n\nimport wx\n\nclass TestFrame(wx.Frame):\n def __init__(self, parent, *args, **kwargs):\n wx.Frame.__init__(self, parent, *args, **kwargs)\n framesizer = wx.BoxSizer(wx.VERTICAL)\n mainpanel = MainPanel(self, wx.ID_ANY)\n self.subpanel = SubPanel(self, wx.ID_ANY)\n self.subpanel.Hide()\n framesizer.Add(mainpanel, 1, wx.EXPAND)\n framesizer.Add(self.subpanel, 1, wx.EXPAND)\n self.SetSizerAndFit(framesizer)\n\nclass MainPanel(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n panelsizer = wx.BoxSizer(wx.VERTICAL)\n but = wx.Button(self, wx.ID_ANY, \"Add\")\n self.Bind(wx.EVT_BUTTON, self.OnAdd, but)\n self.panel_shown = False\n panelsizer.Add(but, 0)\n self.SetSizer(panelsizer)\n\n def OnAdd(self, evt):\n if not self.panel_shown:\n self.GetParent().subpanel.Show()\n self.GetParent().Fit()\n self.GetParent().Layout()\n self.panel_shown = True\n else:\n self.GetParent().subpanel.Hide()\n self.GetParent().Fit()\n self.GetParent().Layout()\n self.panel_shown = False\n\nclass SubPanel(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n spsizer = wx.BoxSizer(wx.VERTICAL)\n text = wx.StaticText(self, wx.ID_ANY, label='I am a subpanel')\n spsizer.Add(text, 1, wx.EXPAND)\n self.SetSizer(spsizer)\n\nif __name__ == '__main__':\n app = wx.App()\n frame = TestFrame(None, wx.ID_ANY, \"Test Frame\")\n frame.Show()\n app.MainLoop()\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30105/" ]
I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class. Here is the code ``` import wx class mainPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) menubar = wx.MenuBar() parser = wx.Menu() one =wx.MenuItem(parser,1,'&Extract Tables with One Heading or Label') two =wx.MenuItem(parser,1,'&Extract Tables with Two Headings or Labels') three =wx.MenuItem(parser,1,'&Extract Tables with Three Headings or Labels') four =wx.MenuItem(parser,1,'&Extract Tables with Four Headings or Labels') quit = wx.MenuItem(parser, 2, '&Quit\tCtrl+Q') parser.AppendItem(one) parser.AppendItem(two) parser.AppendItem(three) parser.AppendItem(four) parser.AppendItem(quit) menubar.Append(parser, '&Table Parsers') textRip = wx.Menu() section =wx.MenuItem(parser,1,'&Extract Text With Section Headings') textRip.AppendItem(section) menubar.Append(textRip, '&Text Rippers') dataHandling = wx.Menu() deHydrate =wx.MenuItem(dataHandling,1,'&Extract Data from Tables') dataHandling.AppendItem(deHydrate) menubar.Append(dataHandling, '&Data Extraction') self.Bind(wx.EVT_MENU, self.OnQuit, id=2) ``` this is where I think I am being clever by using a button click to create an instance ===================================================================================== of subPanel. ============ ``` self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) self.SetMenuBar(menubar) self.Centre() self.Show(True) def OnQuit(self, event): self.Close() class subPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350)) getDirectory.SetDefault() getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400)) getTerm1.SetDefault() #getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button) self.Centre() self.Show(True) app = wx.App() mainPanel(None, -1, '') app.MainLoop() ```
You need an event handler in your bind expression ``` self.bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1) ``` needs to be changed to: ``` self.bind(wx.EVT_MENU, <event handler>, <id of menu item>) ``` where your event handler responds to the event and instantiates the subpanel: ``` def OnMenuItem(self, evt): #don't forget the evt sp = SubPanel(self, wx.ID_ANY, 'TEST') #I assume you will add it to a sizer #if you aren't... you should test_sizer.Add(sp, 1, wx.EXPAND) #force the frame to refresh the sizers: self.Layout() ``` Alternatively, you can instantiate the subpanel in your frame's `__init__` and call a `subpanel.Hide()` after instantiation, and then your menuitem event handler and call a show on the panel `subpanel.Show()` Edit: Here is some code that will do what I think that you are asking: ``` #!usr/bin/env python import wx class TestFrame(wx.Frame): def __init__(self, parent, *args, **kwargs): wx.Frame.__init__(self, parent, *args, **kwargs) framesizer = wx.BoxSizer(wx.VERTICAL) mainpanel = MainPanel(self, wx.ID_ANY) self.subpanel = SubPanel(self, wx.ID_ANY) self.subpanel.Hide() framesizer.Add(mainpanel, 1, wx.EXPAND) framesizer.Add(self.subpanel, 1, wx.EXPAND) self.SetSizerAndFit(framesizer) class MainPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) panelsizer = wx.BoxSizer(wx.VERTICAL) but = wx.Button(self, wx.ID_ANY, "Add") self.Bind(wx.EVT_BUTTON, self.OnAdd, but) self.panel_shown = False panelsizer.Add(but, 0) self.SetSizer(panelsizer) def OnAdd(self, evt): if not self.panel_shown: self.GetParent().subpanel.Show() self.GetParent().Fit() self.GetParent().Layout() self.panel_shown = True else: self.GetParent().subpanel.Hide() self.GetParent().Fit() self.GetParent().Layout() self.panel_shown = False class SubPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) spsizer = wx.BoxSizer(wx.VERTICAL) text = wx.StaticText(self, wx.ID_ANY, label='I am a subpanel') spsizer.Add(text, 1, wx.EXPAND) self.SetSizer(spsizer) if __name__ == '__main__': app = wx.App() frame = TestFrame(None, wx.ID_ANY, "Test Frame") frame.Show() app.MainLoop() ```
273,941
<p>I am trying to write a function that will pull the name of a property and the type using syntax like below:</p> <pre><code>private class SomeClass { Public string Col1; } PropertyMapper&lt;Somewhere&gt; propertyMapper = new PropertyMapper&lt;Somewhere&gt;(); propertyMapper.MapProperty(x =&gt; x.Col1) </code></pre> <p>Is there any way to pass the property through to the function without any major changes to this syntax?</p> <p>I would like to get the property name and the property type.</p> <p>So in the example below i would want to retrieve </p> <p><code>Name = "Col1"</code> and <code>Type = "System.String"</code></p> <p>Can anyone help?</p>
[ { "answer_id": 273971, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 7, "selected": true, "text": "<p>Here's enough of an example of using <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx\" rel=\"noreferrer\">Expressions</a> to get the name of a property or field to get you started:</p>\n\n<pre><code>public static MemberInfo GetMemberInfo&lt;T, U&gt;(Expression&lt;Func&lt;T, U&gt;&gt; expression)\n{\n var member = expression.Body as MemberExpression;\n if (member != null)\n return member.Member;\n\n throw new ArgumentException(\"Expression is not a member access\", \"expression\");\n}\n</code></pre>\n\n<p>Calling code would look like this:</p>\n\n<pre><code>public class Program\n{\n public string Name\n {\n get { return \"My Program\"; }\n }\n\n static void Main()\n {\n MemberInfo member = ReflectionUtility.GetMemberInfo((Program p) =&gt; p.Name);\n Console.WriteLine(member.Name);\n }\n}\n</code></pre>\n\n<p>A word of caution, though: the simple statment of <code>(Program p) =&gt; p.Name</code> actually involves quite a bit of work (and can take measurable amounts of time). Consider caching the result rather than calling the method frequently.</p>\n" }, { "answer_id": 26766261, "author": "chapacool", "author_id": 4220232, "author_profile": "https://Stackoverflow.com/users/4220232", "pm_score": 2, "selected": false, "text": "<p>I found this very useful.</p>\n\n<pre><code>public class PropertyMapper&lt;T&gt;\n{\n public virtual PropertyInfo PropertyInfo&lt;U&gt;(Expression&lt;Func&lt;T, U&gt;&gt; expression)\n {\n var member = expression.Body as MemberExpression;\n if (member != null &amp;&amp; member.Member is PropertyInfo)\n return member.Member as PropertyInfo;\n\n throw new ArgumentException(\"Expression is not a Property\", \"expression\");\n }\n\n public virtual string PropertyName&lt;U&gt;(Expression&lt;Func&lt;T, U&gt;&gt; expression)\n {\n return PropertyInfo&lt;U&gt;(expression).Name;\n }\n\n public virtual Type PropertyType&lt;U&gt;(Expression&lt;Func&lt;T, U&gt;&gt; expression)\n {\n return PropertyInfo&lt;U&gt;(expression).PropertyType;\n }\n}\n</code></pre>\n\n<p>I made this little class to follow the original request.\nIf you need the name of the property you can use it like this:</p>\n\n<pre><code>PropertyMapper&lt;SomeClass&gt; propertyMapper = new PropertyMapper&lt;SomeClass&gt;();\nstring name = propertyMapper.PropertyName(x =&gt; x.Col1);\n</code></pre>\n" }, { "answer_id": 36487242, "author": "TheRock", "author_id": 5121114, "author_profile": "https://Stackoverflow.com/users/5121114", "pm_score": 2, "selected": false, "text": "<p>I just thought I would put this here to build on the previous approach. </p>\n\n<pre><code>public static class Helpers\n{\n public static string PropertyName&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expression)\n {\n var member = expression.Body as MemberExpression;\n if (member != null &amp;&amp; member.Member is PropertyInfo)\n return member.Member.Name;\n\n throw new ArgumentException(\"Expression is not a Property\", \"expression\");\n }\n}\n</code></pre>\n\n<p>You can then call it in the following fashion:</p>\n\n<pre><code>Helpers.PropertyName(() =&gt; TestModel.TestProperty);\n</code></pre>\n\n<p>I should also point out that with VS 2015 and C# 6.0 you can simply use nameof. </p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/dn986596.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/dn986596.aspx</a></p>\n" }, { "answer_id": 37966790, "author": "Anand Patel", "author_id": 6495286, "author_profile": "https://Stackoverflow.com/users/6495286", "pm_score": 2, "selected": false, "text": "<p>This can be easily done in C# 6. To get the name of property use nameof operator.</p>\n\n<pre><code>nameof(User.UserId)\n</code></pre>\n\n<p>and to get type of property use typeof operator.</p>\n\n<pre><code>typeof(User.UserId)\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1213936/" ]
I am trying to write a function that will pull the name of a property and the type using syntax like below: ``` private class SomeClass { Public string Col1; } PropertyMapper<Somewhere> propertyMapper = new PropertyMapper<Somewhere>(); propertyMapper.MapProperty(x => x.Col1) ``` Is there any way to pass the property through to the function without any major changes to this syntax? I would like to get the property name and the property type. So in the example below i would want to retrieve `Name = "Col1"` and `Type = "System.String"` Can anyone help?
Here's enough of an example of using [Expressions](http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx) to get the name of a property or field to get you started: ``` public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression) { var member = expression.Body as MemberExpression; if (member != null) return member.Member; throw new ArgumentException("Expression is not a member access", "expression"); } ``` Calling code would look like this: ``` public class Program { public string Name { get { return "My Program"; } } static void Main() { MemberInfo member = ReflectionUtility.GetMemberInfo((Program p) => p.Name); Console.WriteLine(member.Name); } } ``` A word of caution, though: the simple statment of `(Program p) => p.Name` actually involves quite a bit of work (and can take measurable amounts of time). Consider caching the result rather than calling the method frequently.
273,943
<p>Presuming I have a class named <code>A</code>, and I want to use the decorator design pattern. Correct me if I'm wrong, but for that to work , we'll need to create a decorator class, say <code>ADecorator</code>, which will hold a reference to an <code>A</code> instance, and all the other decorators will extend this to add functionality.</p> <p>I don't understand why do we have to create a decorator class, instead of using an <code>A</code> instance?</p>
[ { "answer_id": 274061, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>In some languages (like Ruby or JavaScript) you could just add new functionality to an A instance. I notice that your question is tagged Java, so I assume that you are asking why you can't do this in Java. The reason is that Java is statically typed. An A instance can only ever have the methods that class A defines or inherits. Therefore, if you want at run time to give an A instance a method that A does not define, then this new method must be defined in a different class.</p>\n" }, { "answer_id": 274234, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 6, "selected": true, "text": "<p>The decorator pattern is used to add capabilities to objects dynamically (that is, at run time). Normally the object will have its capabilities fixed when you write the class. But an important point is that the functionality of the object is extended in a way that is transparent to the client of the object because it implements the same interface as the original object delegates responsibility to the decorated object.</p>\n\n<p>The decorator pattern works in scenarios where there are many optional functionality that an object may have. Without the decorator pattern you will have to create a different class for each object-option configuration. One example that is pretty useful comes from the <strong><em>Head First Design Patterns</em></strong> book by O'Reilly. It uses a coffee shop example that sounds just like StarBucks.</p>\n\n<p>So you have the basic coffee with a method like cost.</p>\n\n<pre><code>public double cost(){\n return 3.45;\n}\n</code></pre>\n\n<p>Then the customer can add cream which costs 0.35 so you now create a CoffeeCream class with the cost method:</p>\n\n<pre><code>public double cost(){\n return 3.80;\n}\n</code></pre>\n\n<p>Then the customer may want Mocha which costs 0.5, and they may want Mocha with Cream or Mocha without Cream. So you create classes CoffeeMochaCream and CoffeeMocha. Then a customer wants double cream so you create a class CoffeeCreamCream… etc. What you end up with is class explosion. Please excuse the poor example used. It's a bit late and I know it's trivial but it does express the point.</p>\n\n<p>Instead you can create an Item abstract class with an abstract cost method:</p>\n\n<pre><code>public abstract class Item{\n public abstract double cost();\n}\n</code></pre>\n\n<p>And you can create a concrete Coffee class that extends Item:</p>\n\n<pre><code>public class Coffee extends Item{\n public double cost(){\n return 3.45;\n }\n}\n</code></pre>\n\n<p>Then you create a CoffeeDecorator that extend the same interface and contain an Item.</p>\n\n<pre><code>public abstract class CoffeeDecorator extends Item{\n private Item item;\n ...\n}\n</code></pre>\n\n<p>Then you can create concrete decorators for each option:</p>\n\n<pre><code>public class Mocha extends CoffeeDecorator{\n\n public double cost(){\n return item.cost() + 0.5;\n }\n\n}\n</code></pre>\n\n<p>Notice how the decorator does not care what type of object it is wrapping just as long as it's an Item? It uses the cost() of the item object and simply adds its own cost.</p>\n\n<pre><code>public class Cream extends CoffeeDecorator{\n\n public double cost(){\n return item.cost() + 0.35;\n }\n\n}\n</code></pre>\n\n<p>Now it is possible for a large number of configurations with these few classes:\ne.g.</p>\n\n<pre><code> Item drink = new Cream(new Mocha(new Coffee))); //Mocha with cream\n</code></pre>\n\n<p>or </p>\n\n<pre><code> Item drink = new Cream(new Mocha(new Cream(new Coffee))));//Mocha with double cream\n</code></pre>\n\n<p>And so on.</p>\n" }, { "answer_id": 274394, "author": "Spencer Kormos", "author_id": 8528, "author_profile": "https://Stackoverflow.com/users/8528", "pm_score": 2, "selected": false, "text": "<p>BTW, if you're just starting out on patterns, the Head First Design Patterns book is <em>phenomenal</em>. It really makes the concepts simple to digest, and makes sure to contrast and compare similar patterns in a way that is ridiculously easy to understand.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
Presuming I have a class named `A`, and I want to use the decorator design pattern. Correct me if I'm wrong, but for that to work , we'll need to create a decorator class, say `ADecorator`, which will hold a reference to an `A` instance, and all the other decorators will extend this to add functionality. I don't understand why do we have to create a decorator class, instead of using an `A` instance?
The decorator pattern is used to add capabilities to objects dynamically (that is, at run time). Normally the object will have its capabilities fixed when you write the class. But an important point is that the functionality of the object is extended in a way that is transparent to the client of the object because it implements the same interface as the original object delegates responsibility to the decorated object. The decorator pattern works in scenarios where there are many optional functionality that an object may have. Without the decorator pattern you will have to create a different class for each object-option configuration. One example that is pretty useful comes from the ***Head First Design Patterns*** book by O'Reilly. It uses a coffee shop example that sounds just like StarBucks. So you have the basic coffee with a method like cost. ``` public double cost(){ return 3.45; } ``` Then the customer can add cream which costs 0.35 so you now create a CoffeeCream class with the cost method: ``` public double cost(){ return 3.80; } ``` Then the customer may want Mocha which costs 0.5, and they may want Mocha with Cream or Mocha without Cream. So you create classes CoffeeMochaCream and CoffeeMocha. Then a customer wants double cream so you create a class CoffeeCreamCream… etc. What you end up with is class explosion. Please excuse the poor example used. It's a bit late and I know it's trivial but it does express the point. Instead you can create an Item abstract class with an abstract cost method: ``` public abstract class Item{ public abstract double cost(); } ``` And you can create a concrete Coffee class that extends Item: ``` public class Coffee extends Item{ public double cost(){ return 3.45; } } ``` Then you create a CoffeeDecorator that extend the same interface and contain an Item. ``` public abstract class CoffeeDecorator extends Item{ private Item item; ... } ``` Then you can create concrete decorators for each option: ``` public class Mocha extends CoffeeDecorator{ public double cost(){ return item.cost() + 0.5; } } ``` Notice how the decorator does not care what type of object it is wrapping just as long as it's an Item? It uses the cost() of the item object and simply adds its own cost. ``` public class Cream extends CoffeeDecorator{ public double cost(){ return item.cost() + 0.35; } } ``` Now it is possible for a large number of configurations with these few classes: e.g. ``` Item drink = new Cream(new Mocha(new Coffee))); //Mocha with cream ``` or ``` Item drink = new Cream(new Mocha(new Cream(new Coffee))));//Mocha with double cream ``` And so on.
273,946
<p>Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.</p>
[ { "answer_id": 273962, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 10, "selected": true, "text": "<p>Define a maximum size.\nThen, compute a resize ratio by taking <code>min(maxwidth/width, maxheight/height)</code>.</p>\n<p>The proper size is <code>oldsize*ratio</code>.</p>\n<p>There is of course also a library method to do this: the method <code>Image.thumbnail</code>.<br />\nBelow is an (edited) example from the <a href=\"https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=thumbnail#PIL.Image.Image.thumbnail\" rel=\"nofollow noreferrer\">PIL documentation</a>.</p>\n<pre><code>import os, sys\nimport Image\n\nsize = 128, 128\n\nfor infile in sys.argv[1:]:\n outfile = os.path.splitext(infile)[0] + &quot;.thumbnail&quot;\n if infile != outfile:\n try:\n im = Image.open(infile)\n im.thumbnail(size, Image.Resampling.LANCZOS)\n im.save(outfile, &quot;JPEG&quot;)\n except IOError:\n print &quot;cannot create thumbnail for '%s'&quot; % infile\n</code></pre>\n" }, { "answer_id": 364789, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>If you are trying to maintain the same aspect ratio, then wouldn't you resize by some percentage of the original size?</p>\n\n<p>For example, half the original size</p>\n\n<pre><code>half = 0.5\nout = im.resize( [int(half * s) for s in im.size] )\n</code></pre>\n" }, { "answer_id": 451580, "author": "tomvon", "author_id": 55959, "author_profile": "https://Stackoverflow.com/users/55959", "pm_score": 9, "selected": false, "text": "<p>This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. Change &quot;basewidth&quot; to any other number to change the default width of your images.</p>\n<pre><code>from PIL import Image\n\nbasewidth = 300\nimg = Image.open('somepic.jpg')\nwpercent = (basewidth/float(img.size[0]))\nhsize = int((float(img.size[1])*float(wpercent)))\nimg = img.resize((basewidth,hsize), Image.Resampling.LANCZOS)\nimg.save('somepic.jpg')\n</code></pre>\n" }, { "answer_id": 940368, "author": "Franz", "author_id": 79427, "author_profile": "https://Stackoverflow.com/users/79427", "pm_score": 6, "selected": false, "text": "<p>I also recommend using PIL's thumbnail method, because it removes all the ratio hassles from you.</p>\n\n<p>One important hint, though: Replace</p>\n\n<pre><code>im.thumbnail(size)\n</code></pre>\n\n<p>with</p>\n\n<pre><code>im.thumbnail(size,Image.ANTIALIAS)\n</code></pre>\n\n<p>by default, PIL uses the Image.NEAREST filter for resizing which results in good performance, but poor quality.</p>\n" }, { "answer_id": 16689816, "author": "Nips", "author_id": 671391, "author_profile": "https://Stackoverflow.com/users/671391", "pm_score": 2, "selected": false, "text": "<p>My ugly example.</p>\n\n<p>Function get file like: \"pic[0-9a-z].[extension]\", resize them to 120x120, moves section to center and save to \"ico[0-9a-z].[extension]\", works with portrait and landscape:</p>\n\n<pre><code>def imageResize(filepath):\n from PIL import Image\n file_dir=os.path.split(filepath)\n img = Image.open(filepath)\n\n if img.size[0] &gt; img.size[1]:\n aspect = img.size[1]/120\n new_size = (img.size[0]/aspect, 120)\n else:\n aspect = img.size[0]/120\n new_size = (120, img.size[1]/aspect)\n img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])\n img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])\n\n if img.size[0] &gt; img.size[1]:\n new_img = img.crop( (\n (((img.size[0])-120)/2),\n 0,\n 120+(((img.size[0])-120)/2),\n 120\n ) )\n else:\n new_img = img.crop( (\n 0,\n (((img.size[1])-120)/2),\n 120,\n 120+(((img.size[1])-120)/2)\n ) )\n\n new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])\n</code></pre>\n" }, { "answer_id": 30227474, "author": "muZk", "author_id": 2056593, "author_profile": "https://Stackoverflow.com/users/2056593", "pm_score": 6, "selected": false, "text": "<p>Based in @tomvon, I finished using the following (pick your case):</p>\n\n<p>a) <strong>Resizing height</strong> (<em>I know the new width, so I need the new height</em>)</p>\n\n<pre><code>new_width = 680\nnew_height = new_width * height / width \n</code></pre>\n\n<p>b) <strong>Resizing width</strong> (<em>I know the new height, so I need the new width</em>)</p>\n\n<pre><code>new_height = 680\nnew_width = new_height * width / height\n</code></pre>\n\n<p>Then just:</p>\n\n<pre><code>img = img.resize((new_width, new_height), Image.ANTIALIAS)\n</code></pre>\n" }, { "answer_id": 32806728, "author": "guettli", "author_id": 633961, "author_profile": "https://Stackoverflow.com/users/633961", "pm_score": 3, "selected": false, "text": "<pre><code>from PIL import Image\nfrom resizeimage import resizeimage\n\ndef resize_file(in_file, out_file, size):\n with open(in_file) as fd:\n image = resizeimage.resize_thumbnail(Image.open(fd), size)\n image.save(out_file)\n image.close()\n\nresize_file('foo.tif', 'foo_small.jpg', (256, 256))\n</code></pre>\n\n<p>I use this library:</p>\n\n<pre><code>pip install python-resize-image\n</code></pre>\n" }, { "answer_id": 36036843, "author": "Mohideen bin Mohammed", "author_id": 4453737, "author_profile": "https://Stackoverflow.com/users/4453737", "pm_score": 4, "selected": false, "text": "<pre><code>from PIL import Image\n\nimg = Image.open('/your image path/image.jpg') # image extension *.png,*.jpg\nnew_width = 200\nnew_height = 300\nimg = img.resize((new_width, new_height), Image.ANTIALIAS)\nimg.save('output image name.png') # format may what you want *.png, *jpg, *.gif\n</code></pre>\n" }, { "answer_id": 50347460, "author": "Shanness", "author_id": 1606452, "author_profile": "https://Stackoverflow.com/users/1606452", "pm_score": 3, "selected": false, "text": "<p>Just updating this question with a more modern wrapper\nThis library wraps Pillow (a fork of PIL)\n<a href=\"https://pypi.org/project/python-resize-image/\" rel=\"noreferrer\">https://pypi.org/project/python-resize-image/</a></p>\n\n<p>Allowing you to do something like this :-</p>\n\n<pre><code>from PIL import Image\nfrom resizeimage import resizeimage\n\nfd_img = open('test-image.jpeg', 'r')\nimg = Image.open(fd_img)\nimg = resizeimage.resize_width(img, 200)\nimg.save('test-image-width.jpeg', img.format)\nfd_img.close()\n</code></pre>\n\n<p>Heaps more examples in the above link.</p>\n" }, { "answer_id": 50618150, "author": "Alex", "author_id": 3511819, "author_profile": "https://Stackoverflow.com/users/3511819", "pm_score": 2, "selected": false, "text": "<p>A simple method for keeping constrained ratios and passing a max width / height. Not the prettiest but gets the job done and is easy to understand:</p>\n\n<pre><code>def resize(img_path, max_px_size, output_folder):\n with Image.open(img_path) as img:\n width_0, height_0 = img.size\n out_f_name = os.path.split(img_path)[-1]\n out_f_path = os.path.join(output_folder, out_f_name)\n\n if max((width_0, height_0)) &lt;= max_px_size:\n print('writing {} to disk (no change from original)'.format(out_f_path))\n img.save(out_f_path)\n return\n\n if width_0 &gt; height_0:\n wpercent = max_px_size / float(width_0)\n hsize = int(float(height_0) * float(wpercent))\n img = img.resize((max_px_size, hsize), Image.ANTIALIAS)\n print('writing {} to disk'.format(out_f_path))\n img.save(out_f_path)\n return\n\n if width_0 &lt; height_0:\n hpercent = max_px_size / float(height_0)\n wsize = int(float(width_0) * float(hpercent))\n img = img.resize((max_px_size, wsize), Image.ANTIALIAS)\n print('writing {} to disk'.format(out_f_path))\n img.save(out_f_path)\n return\n</code></pre>\n\n<p>Here's a <a href=\"https://gist.github.com/agalea91/12149be6d4f64ba61c7b1d222fce3174\" rel=\"nofollow noreferrer\">python script</a> that uses this function to run batch image resizing.</p>\n" }, { "answer_id": 54176442, "author": "hoohoo-b", "author_id": 5544999, "author_profile": "https://Stackoverflow.com/users/5544999", "pm_score": 3, "selected": false, "text": "<p>If you don't want / don't have a need to open image with Pillow, use this:</p>\n\n<pre><code>from PIL import Image\n\nnew_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))\n</code></pre>\n" }, { "answer_id": 54314043, "author": "noEmbryo", "author_id": 5985925, "author_profile": "https://Stackoverflow.com/users/5985925", "pm_score": 2, "selected": false, "text": "<p>I was trying to resize some images for a slideshow video and because of that, I wanted not just one max dimension, but a max width <em>and</em> a max height (the size of the video frame).<br>\nAnd there was always the possibility of a portrait video...<br>\nThe <code>Image.thumbnail</code> method was promising, but I could not make it upscale a smaller image.</p>\n\n<p>So after I couldn't find an obvious way to do that here (or at some other places), I wrote this function and put it here for the ones to come:</p>\n\n<pre><code>from PIL import Image\n\ndef get_resized_img(img_path, video_size):\n img = Image.open(img_path)\n width, height = video_size # these are the MAX dimensions\n video_ratio = width / height\n img_ratio = img.size[0] / img.size[1]\n if video_ratio &gt;= 1: # the video is wide\n if img_ratio &lt;= video_ratio: # image is not wide enough\n width_new = int(height * img_ratio)\n size_new = width_new, height\n else: # image is wider than video\n height_new = int(width / img_ratio)\n size_new = width, height_new\n else: # the video is tall\n if img_ratio &gt;= video_ratio: # image is not tall enough\n height_new = int(width / img_ratio)\n size_new = width, height_new\n else: # image is taller than video\n width_new = int(height * img_ratio)\n size_new = width_new, height\n return img.resize(size_new, resample=Image.LANCZOS)\n</code></pre>\n" }, { "answer_id": 55580396, "author": "Siddhartha Mukherjee", "author_id": 8548160, "author_profile": "https://Stackoverflow.com/users/8548160", "pm_score": 2, "selected": false, "text": "<p>I resizeed the image in such a way and it's working very well</p>\n\n<pre><code>from io import BytesIO\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nimport os, sys\nfrom PIL import Image\n\n\ndef imageResize(image):\n outputIoStream = BytesIO()\n imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS) \n imageTemproaryResized.save(outputIoStream , format='PNG', quality='10') \n outputIoStream.seek(0)\n uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', \"%s.jpg\" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)\n\n ## For upload local folder\n fs = FileSystemStorage()\n filename = fs.save(uploadedImage.name, uploadedImage)\n</code></pre>\n" }, { "answer_id": 57990437, "author": "Kanish Mathew", "author_id": 8937480, "author_profile": "https://Stackoverflow.com/users/8937480", "pm_score": 2, "selected": false, "text": "<p>Have updated the answer above by \"tomvon\"</p>\n\n<pre><code>from PIL import Image\n\nimg = Image.open(image_path)\n\nwidth, height = img.size[:2]\n\nif height &gt; width:\n baseheight = 64\n hpercent = (baseheight/float(img.size[1]))\n wsize = int((float(img.size[0])*float(hpercent)))\n img = img.resize((wsize, baseheight), Image.ANTIALIAS)\n img.save('resized.jpg')\nelse:\n basewidth = 64\n wpercent = (basewidth/float(img.size[0]))\n hsize = int((float(img.size[1])*float(wpercent)))\n img = img.resize((basewidth,hsize), Image.ANTIALIAS)\n img.save('resized.jpg')\n</code></pre>\n" }, { "answer_id": 60273833, "author": "user391339", "author_id": 391339, "author_profile": "https://Stackoverflow.com/users/391339", "pm_score": 3, "selected": false, "text": "<p>Open your image file </p>\n\n<pre><code>from PIL import Image\nim = Image.open(\"image.png\")\n</code></pre>\n\n<p><a href=\"https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize\" rel=\"noreferrer\">Use PIL Image.resize(size, resample=0) method</a>, where you substitute (width, height) of your image for the size 2-tuple.</p>\n\n<p>This will display your image at original size:</p>\n\n<pre><code>display(im.resize((int(im.size[0]),int(im.size[1])), 0) )\n</code></pre>\n\n<p>This will display your image at 1/2 the size:</p>\n\n<pre><code>display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )\n</code></pre>\n\n<p>This will display your image at 1/3 the size:</p>\n\n<pre><code>display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )\n</code></pre>\n\n<p>This will display your image at 1/4 the size:</p>\n\n<pre><code>display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )\n</code></pre>\n\n<p>etc etc </p>\n" }, { "answer_id": 61567040, "author": "RockOGOlic", "author_id": 12720264, "author_profile": "https://Stackoverflow.com/users/12720264", "pm_score": 3, "selected": false, "text": "<p>I will also add a version of the resize that keeps the aspect ratio fixed.\nIn this case, it will adjust the height to match the width of the new image, based on the initial aspect ratio, <em>asp_rat</em>, which is <strong>float</strong> (!). \nBut, to adjust the width to the height, instead, you just need to comment one line and uncomment the other in the <strong>else</strong> loop. You will see, where.</p>\n\n<p>You do not need the semicolons (;), I keep them just to remind myself of syntax of languages I use more often.</p>\n\n<pre><code>from PIL import Image\n\nimg_path = \"filename.png\";\nimg = Image.open(img_path); # puts our image to the buffer of the PIL.Image object\n\nwidth, height = img.size;\nasp_rat = width/height;\n\n# Enter new width (in pixels)\nnew_width = 50;\n\n# Enter new height (in pixels)\nnew_height = 54;\n\nnew_rat = new_width/new_height;\n\nif (new_rat == asp_rat):\n img = img.resize((new_width, new_height), Image.ANTIALIAS); \n\n# adjusts the height to match the width\n# NOTE: if you want to adjust the width to the height, instead -&gt; \n# uncomment the second line (new_width) and comment the first one (new_height)\nelse:\n new_height = round(new_width / asp_rat);\n #new_width = round(new_height * asp_rat);\n img = img.resize((new_width, new_height), Image.ANTIALIAS);\n\n# usage: resize((x,y), resample)\n# resample filter -&gt; PIL.Image.BILINEAR, PIL.Image.NEAREST (default), PIL.Image.BICUBIC, etc..\n# https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize\n\n# Enter the name under which you would like to save the new image\nimg.save(\"outputname.png\");\n</code></pre>\n\n<p>And, it is done. I tried to document it as much as I can, so it is clear. </p>\n\n<p>I hope it might be helpful to someone out there!</p>\n" }, { "answer_id": 63224327, "author": "666", "author_id": 14017226, "author_profile": "https://Stackoverflow.com/users/14017226", "pm_score": -1, "selected": false, "text": "<pre><code>import cv2\nfrom skimage import data \nimport matplotlib.pyplot as plt\nfrom skimage.util import img_as_ubyte\nfrom skimage import io\nfilename='abc.png'\nimage=plt.imread(filename)\nim=cv2.imread('abc.png')\nprint(im.shape)\nim.resize(300,300)\nprint(im.shape)\nplt.imshow(image)\n</code></pre>\n" }, { "answer_id": 64680872, "author": "Riz.Khan", "author_id": 10485321, "author_profile": "https://Stackoverflow.com/users/10485321", "pm_score": 0, "selected": false, "text": "<p>The following script creates nice thumbnails of all JPEG images preserving aspect ratios with 128x128 max resolution.</p>\n<pre><code>from PIL import Image\nimg = Image.open(&quot;D:\\\\Pictures\\\\John.jpg&quot;)\nimg.thumbnail((680,680))\nimg.save(&quot;D:\\\\Pictures\\\\John_resize.jpg&quot;)\n</code></pre>\n" }, { "answer_id": 65904414, "author": "Vito Gentile", "author_id": 738017, "author_profile": "https://Stackoverflow.com/users/738017", "pm_score": 3, "selected": false, "text": "<p>You can combine PIL's <a href=\"https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.thumbnail\" rel=\"nofollow noreferrer\"><code>Image.thumbnail</code></a> with <a href=\"https://stackoverflow.com/a/9860611/738017\"><code>sys.maxsize</code></a> if your resize limit is only on one dimension (width or height).</p>\n<p>For instance, if you want to resize an image so that its height is no more than 100px, while keeping aspect ratio, you can do something like this:</p>\n<pre><code>import sys\nfrom PIL import Image\n\nimage.thumbnail([sys.maxsize, 100], Image.ANTIALIAS)\n</code></pre>\n<p>Keep in mind that <code>Image.thumbnail</code> will resize the image in place, which is different from <code>Image.resize</code> that instead returns the resized image without changing the original one.</p>\n<p><strong>EDIT</strong>: <code>Image.ANTIALIAS</code> raises a deprecation warning, and will be removed in PIL 10 (July 2023). Instead, you should use <code>Resampling.LANCZOS</code>:</p>\n<pre><code>import sys\nfrom PIL import Image\nfrom PIL.Image import Resampling\n\nimage.thumbnail([sys.maxsize, 100], Resampling.LANCZOS)\n</code></pre>\n" }, { "answer_id": 69232569, "author": "mustafa candan", "author_id": 6482263, "author_profile": "https://Stackoverflow.com/users/6482263", "pm_score": 2, "selected": false, "text": "<p>The simplest way that worked for me</p>\n<pre><code>image = image.resize((image.width*2, image.height*2), Image.ANTIALIAS)\n</code></pre>\n<p>Example</p>\n<pre><code>from PIL import Image, ImageGrab\nimage = ImageGrab.grab(bbox=(0,0,400,600)) #take screenshot\nimage = image.resize((image.width*2, image.height*2), Image.ANTIALIAS)\nimage.save('Screen.png')\n</code></pre>\n" }, { "answer_id": 69866695, "author": "Ruhul Amin", "author_id": 5421542, "author_profile": "https://Stackoverflow.com/users/5421542", "pm_score": 2, "selected": false, "text": "<p>To make the new image half the width and half the height of the original image, Use below code :</p>\n<pre><code> from PIL import Image\n im = Image.open(&quot;image.jpg&quot;)\n resized_im = im.resize((round(im.size[0]*0.5), round(im.size[1]*0.5)))\n \n #Save the cropped image\n resized_im.save('resizedimage.jpg')\n</code></pre>\n<p>To resize with fixed width with ration:</p>\n<pre><code>from PIL import Image\nnew_width = 300\nim = Image.open(&quot;img/7.jpeg&quot;)\nconcat = int(new_width/float(im.size[0]))\nsize = int((float(im.size[1])*float(concat)))\nresized_im = im.resize((new_width,size), Image.ANTIALIAS)\n#Save the cropped image\nresized_im.save('resizedimage.jpg')\n</code></pre>\n" }, { "answer_id": 69989692, "author": "Mohamed TOUATI", "author_id": 11394480, "author_profile": "https://Stackoverflow.com/users/11394480", "pm_score": 2, "selected": false, "text": "<pre><code># Importing Image class from PIL module\nfrom PIL import Image\n\n# Opens a image in RGB mode\nim = Image.open(r&quot;C:\\Users\\System-Pc\\Desktop\\ybear.jpg&quot;)\n\n# Size of the image in pixels (size of original image)\n# (This is not mandatory)\nwidth, height = im.size\n\n# Setting the points for cropped image\nleft = 4\ntop = height / 5\nright = 154\nbottom = 3 * height / 5\n\n# Cropped image of above dimension\n# (It will not change original image)\nim1 = im.crop((left, top, right, bottom))\nnewsize = (300, 300)\nim1 = im1.resize(newsize)\n# Shows the image in image viewer\nim1.show()\n</code></pre>\n" }, { "answer_id": 70719475, "author": "24_saurabh sharma", "author_id": 17900612, "author_profile": "https://Stackoverflow.com/users/17900612", "pm_score": 0, "selected": false, "text": "<pre><code>######get resize coordinate after resize the image using this function#####\ndef scale_img_pixel(points,original_dim,resize_dim):\n multi_list = [points]\n new_point_list = []\n multi_list_point = []\n for point in multi_list:\n multi_list_point.append([point[0],point[1]])\n multi_list_point.append([point[2],point[3]])\n for lsingle_point in multi_list_point:\n x1 = int((lsingle_point[0] * (resize_dim[0] / original_dim[0])))\n y1 = int((lsingle_point[1] * (resize_dim[1] / original_dim[1])))\n new_point_list.append(x1)\n new_point_list.append(y1)\n \n return new_point_list\n \n \n points = [774,265,909,409]\n original_dim = (1237,1036)\n resize_dim = (640,480)\n result = scale_img_pixel(points,original_dim,resize_dim)\n print(&quot;result: &quot;, result) \n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3912/" ]
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
Define a maximum size. Then, compute a resize ratio by taking `min(maxwidth/width, maxheight/height)`. The proper size is `oldsize*ratio`. There is of course also a library method to do this: the method `Image.thumbnail`. Below is an (edited) example from the [PIL documentation](https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=thumbnail#PIL.Image.Image.thumbnail). ``` import os, sys import Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size, Image.Resampling.LANCZOS) im.save(outfile, "JPEG") except IOError: print "cannot create thumbnail for '%s'" % infile ```
273,949
<p>For some reason I'm not getting this. (Example model below) If I write: </p> <pre><code>var property = typeof(sedan).GetProperty("TurningRadius"); Attribute.GetCustomAttributes(property,typeof(MyAttribute), false) </code></pre> <p>the call will return MyAttribute(2) despite indicating I don't want to search the inheritance chain. Does anyone know what code I can write so that calling</p> <pre><code>MagicAttributeSearcher(typeof(Sedan).GetProperty("TurningRadius")) </code></pre> <p>returns nothing while calling</p> <pre><code>MagicAttributeSearcher(typeof(Vehicle).GetProperty("TurningRadius")) </code></pre> <p>returns MyAttribute(1)?</p> <hr> <p>Example Model:</p> <pre><code>public class Sedan : Car { // ... } public class Car : Vehicle { [MyAttribute(2)] public override int TurningRadius { get; set; } } public abstract class Vehicle { [MyAttribute(1)] public virtual int TurningRadius { get; set; } } </code></pre>
[ { "answer_id": 274005, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>I think this is what you're after - note that I had to make TurningRadius abstract in Vehicle and overridden in Car. Is that okay?</p>\n\n<pre><code>using System;\nusing System.Reflection;\n\npublic class MyAttribute : Attribute\n{\n public MyAttribute(int x) {}\n}\n\npublic class Sedan : Car\n{\n // ...\n}\n\npublic class Car : Vehicle\n{\n public override int TurningRadius { get; set; }\n}\n\npublic abstract class Vehicle\n{\n [MyAttribute(1)]\n public virtual int TurningRadius { get; set; }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n MagicAttributeSearcher(typeof(Sedan));\n MagicAttributeSearcher(typeof(Vehicle));\n }\n\n static void MagicAttributeSearcher(Type type)\n {\n PropertyInfo prop = type.GetProperty(\"TurningRadius\");\n var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);\n Console.WriteLine(\"{0}: {1}\", type, attr);\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Sedan:\nVehicle: MyAttribute\n</code></pre>\n" }, { "answer_id": 276252, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 2, "selected": false, "text": "<p>I believe the problem is that when you obtain the property TurningRadius from the Sedan object in the first line</p>\n\n<pre><code>var property = typeof(sedan).GetProperty(\"TurningRadius\");\n</code></pre>\n\n<p>what you are actually getting is the TurningRadius property declared at Car level, since Sedan doesn't have its own overload. </p>\n\n<p>Therefore, when you request its attributes, you are getting the ones defined at car even if you requested not to go up in the inheritance chain, as the property you are querying is the one defined in Car.</p>\n\n<p>You should change the GetProperty to add the necessary flags to obtain only declaring members. I believe <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.declaredonly.aspx\" rel=\"nofollow noreferrer\">DeclaredOnly</a> should do.</p>\n\n<p>Edit: Note that this change will have the first line return null, so watch out for NullPointerExceptions.</p>\n" }, { "answer_id": 276255, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>Okay, given the extra information - I believe the problem is that <code>GetProperty</code> is going up the inheritance change.</p>\n\n<p>If you change your call to <code>GetProperty</code> to:</p>\n\n<pre><code>PropertyInfo prop = type.GetProperty(\"TurningRadius\",\n BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);\n</code></pre>\n\n<p>then <code>prop</code> will be null if the property isn't overridden. For instance:</p>\n\n<pre><code>static bool MagicAttributeSearcher(Type type)\n{\n PropertyInfo prop = type.GetProperty(\"TurningRadius\", BindingFlags.Instance | \n BindingFlags.Public | BindingFlags.DeclaredOnly);\n\n if (prop == null)\n {\n return false;\n }\n var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);\n return attr != null;\n}\n</code></pre>\n\n<p>This returns <code>true</code> and only if:</p>\n\n<ul>\n<li>The specified type overrides the <code>TurningRadius</code> property (or declares a new one)</li>\n<li>The property has the <code>MyAttribute</code> attribute.</li>\n</ul>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
For some reason I'm not getting this. (Example model below) If I write: ``` var property = typeof(sedan).GetProperty("TurningRadius"); Attribute.GetCustomAttributes(property,typeof(MyAttribute), false) ``` the call will return MyAttribute(2) despite indicating I don't want to search the inheritance chain. Does anyone know what code I can write so that calling ``` MagicAttributeSearcher(typeof(Sedan).GetProperty("TurningRadius")) ``` returns nothing while calling ``` MagicAttributeSearcher(typeof(Vehicle).GetProperty("TurningRadius")) ``` returns MyAttribute(1)? --- Example Model: ``` public class Sedan : Car { // ... } public class Car : Vehicle { [MyAttribute(2)] public override int TurningRadius { get; set; } } public abstract class Vehicle { [MyAttribute(1)] public virtual int TurningRadius { get; set; } } ```
Okay, given the extra information - I believe the problem is that `GetProperty` is going up the inheritance change. If you change your call to `GetProperty` to: ``` PropertyInfo prop = type.GetProperty("TurningRadius", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); ``` then `prop` will be null if the property isn't overridden. For instance: ``` static bool MagicAttributeSearcher(Type type) { PropertyInfo prop = type.GetProperty("TurningRadius", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); if (prop == null) { return false; } var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false); return attr != null; } ``` This returns `true` and only if: * The specified type overrides the `TurningRadius` property (or declares a new one) * The property has the `MyAttribute` attribute.
273,964
<p>I have a CSS rule like this:</p> <pre><code>a:hover { background-color: #fff; } </code></pre> <p>But this results in a bad-looking gap at the bottom on image links, and what's even worse, if I have transparent images, the link's background color can be seen through the image.</p> <p>I have stumbled upon this problem many times before, but I always solved it using the quick-and-dirty approach of assigning a class to image links:</p> <pre><code>a.imagelink:hover { background-color: transparent; } </code></pre> <p>Today I was looking for a more elegant solution to this problem when I stumbled upon <a href="https://developer.mozilla.org/en/Images%2c_Tables%2c_and_Mysterious_Gaps" rel="noreferrer">this</a>.</p> <p>Basically what it suggests is using <code>display: block</code>, and this really solves the problem for non-transparent images. However, it results in another problem: now the link is as wide as the paragraph, although the image is not.</p> <p>Is there a nice way to solve this problem, or do I have to use the dirty approach again?</p> <p>Thanks,</p>
[ { "answer_id": 273973, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Untested idea:</p>\n\n<pre><code>a:hover {background-color: #fff;}\nimg:hover { background-color: transparent;}\n</code></pre>\n" }, { "answer_id": 273993, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 0, "selected": false, "text": "<p>The following should work (untested):</p>\n\n<p>First you</p>\n\n<pre><code> a:hover { background-color: #fff; }\n</code></pre>\n\n<p>Then you</p>\n\n<pre><code>a:imagelink:hover { background-color: inherit; }\n</code></pre>\n\n<p>The second rule will override the first for &lt;a class=\"imagelink\" etc.> and preserve the background color of the parent.</p>\n\n<p>I tried to do this without the class=\"\", but I can't find a CSS selector that is the opposite of foo > bar, which styles a bar when it is the child of a foo. You would want to style the foo when it <em>has</em> a child of class bar. You can do that and even fancier things with jQuery, but that may not be desirable as a general technique.</p>\n" }, { "answer_id": 274240, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 0, "selected": false, "text": "<p>you could use display: inline-block but that's not completely crossbrowser. IE6 and lower will have a problem with it.</p>\n\n<p>I assume you have whitespaces between <code>&lt;a&gt;</code> and <code>&lt;img&gt;</code>? try removing that like this:</p>\n\n<p><code>&lt;a&gt;&lt;img /&gt;&lt;/a&gt;</code></p>\n" }, { "answer_id": 274301, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>I'm confused at what you are terming \"image links\"... is that an 'img' tag inside of an anchor? Or are you setting the image in CSS?</p>\n\n<p>If you're setting the image in CSS, then there is no problem here (since you're already able to target it)... so I must assume you mean:</p>\n\n<pre><code>&lt;a ...&gt;&lt;img src=\"...\" /&gt;&lt;/a&gt;\n</code></pre>\n\n<p>To which, I would suggest that you specify a background color on the image... So, assuming the container it's in <em>should</em> be white...</p>\n\n<pre><code>a:hover { background: SomeColor }\na:hover img { background-color: #fff; }\n</code></pre>\n" }, { "answer_id": 274400, "author": "Gabe", "author_id": 9835, "author_profile": "https://Stackoverflow.com/users/9835", "pm_score": 4, "selected": true, "text": "<p>I tried to find some selector that would get only <code>&lt;a&gt;</code> elements that don't have <code>&lt;img&gt;</code> descendants, but couldn't find any...\nAbout images with that bottom gap, you could do the following: </p>\n\n<pre><code>a img{vertical-align:text-bottom;}\n</code></pre>\n\n<p>This should get rid of the background showing up behind the image, but may throw off the layout (by not much, though), so be careful.</p>\n\n<p>For the transparent images, you should use a class.</p>\n\n<p>I really hope that's solved in CSS3, by implementing a parent selector.</p>\n" }, { "answer_id": 274629, "author": "Massimiliano Torromeo", "author_id": 35069, "author_profile": "https://Stackoverflow.com/users/35069", "pm_score": 2, "selected": false, "text": "<p>I usually do something like this to remove the gap under images:</p>\n\n<pre><code>img {\n display: block;\n float: left;\n}\n</code></pre>\n\n<p>Of course this is not always the ideal solution but it's fine in most situations.</p>\n" }, { "answer_id": 4514276, "author": "Kim", "author_id": 52025, "author_profile": "https://Stackoverflow.com/users/52025", "pm_score": 0, "selected": false, "text": "<p>I had this problem today, and used another solution than <code>display: block</code> thanks to the link by asker. This means I am able to retain the link <strong>ONLY</strong> on the image and not expand it to its container.</p>\n\n<p>Images are inline, so they have space below them for lower part of letters like \"y, j, g\". This positions the images at <code>baseline</code>, but you can alter it if you have no <code>&lt;a&gt;TEXT HERE&lt;/a&gt;</code> like with a <strong>logo</strong>. However you still need to mask the text line space and its easy if you use a plain color as background (eg in <code>body</code> or <code>div#wrapper</code>).</p>\n\n<pre><code>body {\n background-color: #112233; \n}\na:hover {\n background-color: red;\n}\na img {\n border-style: none; /* not need for this solution, but removes borders around images which have a link */\n vertical-align: bottom; /* here */\n}\na:hover img {\n background-color: #112233; /* MUST match the container background, or you arent masking the hover effect */\n}\n</code></pre>\n" }, { "answer_id": 8697949, "author": "Paulish", "author_id": 1115844, "author_profile": "https://Stackoverflow.com/users/1115844", "pm_score": 2, "selected": false, "text": "<p>This way works way better. </p>\n\n<pre><code>a[href$=jpg], a[href$=jpeg], a[href$=jpe], a[href$=png], a[href$=gif] {\n text-decoration: none;\n border: 0 none;\n background-color: transparent;\n }\n</code></pre>\n\n<p>No cumbersome classes that have to be applied to each image. Detailed description here:</p>\n\n<p><a href=\"http://perishablepress.com/press/2008/10/14/css-remove-link-underlines-borders-linked-images/\" rel=\"nofollow\">http://perishablepress.com/press/2008/10/14/css-remove-link-underlines-borders-linked-images/</a></p>\n" }, { "answer_id": 13104102, "author": "Balu", "author_id": 1775414, "author_profile": "https://Stackoverflow.com/users/1775414", "pm_score": 0, "selected": false, "text": "<p>I had the same problem. In my case I am using the image as background. I did the following and it resolved my problem:</p>\n\n<pre><code>background-image: url(file:\"use the same background image or color\");\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2119/" ]
I have a CSS rule like this: ``` a:hover { background-color: #fff; } ``` But this results in a bad-looking gap at the bottom on image links, and what's even worse, if I have transparent images, the link's background color can be seen through the image. I have stumbled upon this problem many times before, but I always solved it using the quick-and-dirty approach of assigning a class to image links: ``` a.imagelink:hover { background-color: transparent; } ``` Today I was looking for a more elegant solution to this problem when I stumbled upon [this](https://developer.mozilla.org/en/Images%2c_Tables%2c_and_Mysterious_Gaps). Basically what it suggests is using `display: block`, and this really solves the problem for non-transparent images. However, it results in another problem: now the link is as wide as the paragraph, although the image is not. Is there a nice way to solve this problem, or do I have to use the dirty approach again? Thanks,
I tried to find some selector that would get only `<a>` elements that don't have `<img>` descendants, but couldn't find any... About images with that bottom gap, you could do the following: ``` a img{vertical-align:text-bottom;} ``` This should get rid of the background showing up behind the image, but may throw off the layout (by not much, though), so be careful. For the transparent images, you should use a class. I really hope that's solved in CSS3, by implementing a parent selector.
273,969
<p>I'm having a little bit of trouble making a sticky form that will remember what is entered in it on form submission if the value has double quotes. The problem is that the HTML is supposed to read something like:</p> <pre><code>&lt;input type="text" name="something" value="Whatever value you entered" /&gt; </code></pre> <p>However, if the phrase: "How do I do this?" is typed in with quotes, the resulting HTML is similar to:</p> <pre><code>&lt;input type="text" this?="" do="" i="" how="" value="" name="something"/&gt; </code></pre> <p>How would I have to filter the double quotes? I've tried it with magic quotes on and off, I've used stripslashes and addslashes, but so far I haven't come across the right solution. What's the best way to get around this problem for PHP?</p>
[ { "answer_id": 273976, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": true, "text": "<p>You want <a href=\"http://www.php.net/htmlentities\" rel=\"noreferrer\">htmlentities()</a>.</p>\n\n<p><code>&lt;input type=\"text\" value=\"&lt;?php echo htmlentities($myValue); ?&gt;\"&gt;</code></p>\n" }, { "answer_id": 274002, "author": "thesmart", "author_id": 20176, "author_profile": "https://Stackoverflow.com/users/20176", "pm_score": 4, "selected": false, "text": "<p>The above will encode all sorts of characters that have html entity code. I prefer to use:</p>\n\n<pre><code>htmlspecialchars($myValue, ENT_QUOTES, 'utf-8');\n</code></pre>\n\n<p>This will only encode:</p>\n\n<pre><code>'&amp;' (ampersand) becomes '&amp;amp;'\n'\"' (double quote) becomes '&amp;quot;' when ENT_NOQUOTES is not set.\n''' (single quote) becomes '&amp;#039;' only when ENT_QUOTES is set.\n'&lt;' (less than) becomes '&amp;lt;'\n'&gt;' (greater than) becomes '&amp;gt;'\n</code></pre>\n\n<p>You could also do a strip_tags on the $myValue to remove html and php tags.</p>\n" }, { "answer_id": 12838206, "author": "mcmlxxxvi", "author_id": 1614641, "author_profile": "https://Stackoverflow.com/users/1614641", "pm_score": 2, "selected": false, "text": "<p>This is what I use:\n</p>\n\n<pre><code>htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_DISALLOWED | ENT_HTML5, 'UTF-8')\n</code></pre>\n\n<ul>\n<li><code>ENT_QUOTES</code> tells PHP to convert both single and double quotes, which I find desirable.</li>\n<li><code>ENT_SUBSTITUTE</code> and <code>ENT_DISALLOWED</code> deal with invalid Unicode. They're quite similar - as far as I understand, the first substitutes invalid code unit sequences, i.e. <strong>invalidly encoded characters or sequences that do not represent characters</strong>, while the second substitutes invalid code points for the given document type, i.e. <strong>characters which are not allowed for the document type specified</strong> (or the default if not explicitly specified). The <a href=\"http://www.php.net/manual/en/function.htmlentities.php\" rel=\"nofollow noreferrer\">documentation</a> is undesirably laconic on them.</li>\n<li><code>ENT_HTML5</code> is the document type I use. You can use a different one, but it should match your page doctype.</li>\n<li><code>UTF-8</code> is the encoding of my document. I suggest that, unless you are absolutely sure you're using PHP 5.4.0, you explicitly specify the encoding - especially if you'll be dealing with non-English text. A host I do some work on uses 5.2.something, which defaults to <code>ISO-8859-1</code> and produces gibberish.</li>\n</ul>\n\n<p>As <strong>thesmart</strong> suggests, <code>htmlspecialchars</code> encodes only reserved HTML characters while <code>htmlentities</code> converts everything that has an HTML representation. In most contexts either will do the job. <a href=\"https://stackoverflow.com/questions/46483/htmlentities-vs-htmlspecialchars\">Here</a> is a discussion on the subject.</p>\n\n<p>One more thing: it is a best practice to keep magic quotes disabled since they give a false sense of security and are deprecated in 5.3.0 and removed from 5.4.0. If they are enabled, each quote in your fields will be prepended by a backslash on postback (and multiple postbacks will add more and more slashes). I see that the OP is able to change the setting, but for future references: if you are on a shared host or otherwise don't have access to <code>php.ini</code>, the easiest way is to add</p>\n\n<pre><code>php_flag magic_quotes_gpc Off\n</code></pre>\n\n<p>to the <code>.htaccess</code> file.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
I'm having a little bit of trouble making a sticky form that will remember what is entered in it on form submission if the value has double quotes. The problem is that the HTML is supposed to read something like: ``` <input type="text" name="something" value="Whatever value you entered" /> ``` However, if the phrase: "How do I do this?" is typed in with quotes, the resulting HTML is similar to: ``` <input type="text" this?="" do="" i="" how="" value="" name="something"/> ``` How would I have to filter the double quotes? I've tried it with magic quotes on and off, I've used stripslashes and addslashes, but so far I haven't come across the right solution. What's the best way to get around this problem for PHP?
You want [htmlentities()](http://www.php.net/htmlentities). `<input type="text" value="<?php echo htmlentities($myValue); ?>">`
273,970
<p>Right now we've got web pages that show UI elements, and web pages that just process form submissions, and then redirect back to the UI pages. They do this using PHP's header() function:</p> <pre><code>header("Location: /other_page.php"); </code></pre> <p>This causes a 302 Found response to be sent; according to the HTTP 1.1 spec, 302 is for cases where "The requested resource resides temporarily under a different URI." <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3" rel="nofollow noreferrer">[HTTP 1.1 spec]</a></p> <p>Functionally, this is fine, but it doens't seem like this is the proper status code for what we're doing. It looks like 303 ("See Other") is the appropriate status here, so I'm wondering if there's any reason not to use it. We'd have to be more explicit in our use of header(), since we'd have to specify that status line rather than just a Location: field. Thoughts?</p>
[ { "answer_id": 273989, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>I've never used it myself... as it says in your link:</p>\n\n<blockquote>\n <p>Note: Many pre-HTTP/1.1 user agents do\n not understand the 303\n status. When interoperability with such clients is a concern, the\n 302 status code may be used instead, since most user agents react\n to a 302 response as described here for 303.</p>\n</blockquote>\n\n<p>This seems a good enough reason to me to stick with 302.</p>\n\n<p>FYI <a href=\"http://www.php.net/header\" rel=\"nofollow noreferrer\">header()</a> takes extra parameters in which you can set the status code:</p>\n\n<p><code>header('Location: /foo.php', true, 303);</code></p>\n" }, { "answer_id": 274021, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 1, "selected": false, "text": "<p>To expand on RoBorg's answer, many browsers do not understand more than a handful of the many, many HTTP response codes.</p>\n\n<p>A side note: it you are at all concerned about search engine placement, 302s can (supposedly) cause problems.</p>\n" }, { "answer_id": 274036, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 4, "selected": true, "text": "<p>You can use either, but the proper statuscode to use for redirect-after-post is 303.</p>\n\n<p>The confusion has a historical explanation. Originally, 302 specified that the browser mustn't change the method of the redirected request. This makes it unfit for redirect-after-post, where you want the browser to issue a GET request. However, all browsers seems to misinterpret the specs and always issue a GET request. In order to clear up the ambiguity HTTP/1.1 specified two new codes: 303 and 307. 303 essentially specifies the de-facto interpretation of 302, while 307 specifies the original specification of 302. So in practice 302 and 303 are interchangeable, and in theory 302 and 307 are.</p>\n\n<p>If you <em>really</em> care about compatibility, 302 is a safer bet than 303, since HTTP/1.0 agents may not understand 303, but all modern browsers speak HTTP/1.1, so it isn't a real issue. I would recommend using 303, since that's the most correct thing to do.</p>\n\n<p>On a side-note; The <code>Location</code> field should be a full URL. In practice it doesn't matter - browsers are forgiving - but if you care about the specs, that's the proper thing to do.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20903/" ]
Right now we've got web pages that show UI elements, and web pages that just process form submissions, and then redirect back to the UI pages. They do this using PHP's header() function: ``` header("Location: /other_page.php"); ``` This causes a 302 Found response to be sent; according to the HTTP 1.1 spec, 302 is for cases where "The requested resource resides temporarily under a different URI." [[HTTP 1.1 spec]](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3) Functionally, this is fine, but it doens't seem like this is the proper status code for what we're doing. It looks like 303 ("See Other") is the appropriate status here, so I'm wondering if there's any reason not to use it. We'd have to be more explicit in our use of header(), since we'd have to specify that status line rather than just a Location: field. Thoughts?
You can use either, but the proper statuscode to use for redirect-after-post is 303. The confusion has a historical explanation. Originally, 302 specified that the browser mustn't change the method of the redirected request. This makes it unfit for redirect-after-post, where you want the browser to issue a GET request. However, all browsers seems to misinterpret the specs and always issue a GET request. In order to clear up the ambiguity HTTP/1.1 specified two new codes: 303 and 307. 303 essentially specifies the de-facto interpretation of 302, while 307 specifies the original specification of 302. So in practice 302 and 303 are interchangeable, and in theory 302 and 307 are. If you *really* care about compatibility, 302 is a safer bet than 303, since HTTP/1.0 agents may not understand 303, but all modern browsers speak HTTP/1.1, so it isn't a real issue. I would recommend using 303, since that's the most correct thing to do. On a side-note; The `Location` field should be a full URL. In practice it doesn't matter - browsers are forgiving - but if you care about the specs, that's the proper thing to do.
273,978
<p>What makes all the words of a programming language actually do anything? I mean, what's actually happening to make the computer know what all of those words mean? If I verbally tell my my computer to do something, it doesn't do it, because it doesn't understand. So how exactly can these human words written into a language actually cause the computer to do some desirable activity? </p>
[ { "answer_id": 273983, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>In the simplest case, a program called a <strong>compiler</strong> takes the programming language words you write and converts them to <em>machine language</em> which the computer can understand. Compilers understand a specific programming language (C#, Java, etc) which has very specific rules about how you explain to the compiler what you want it to do.</p>\n\n<p>Interpretation and understanding of those rules is most of what Stack Overflow is about. :)</p>\n" }, { "answer_id": 273984, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": -1, "selected": false, "text": "<p>Basically, you start out with something simple such as:</p>\n\n<pre><code>print(\"Hello World\");\n</code></pre>\n\n<p>Then you simply sprinkle syntactic sugar and magic tokens over it until it does what you want!</p>\n" }, { "answer_id": 273986, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 2, "selected": false, "text": "<p>Programming is where you take a series of steps which solve a certain problem, and write them out in a certain language which requires certain syntax. When you have described those steps in the language, you can use a compiler (as per Greg's comment) which translates from that language into one the computer can interpret.</p>\n\n<p>The art lies in making sure you describe the steps well enough :)</p>\n" }, { "answer_id": 273988, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "<p>A computer programming language is actually a highly abstracted language that is converted down into a very very basic language that computers actually understand.</p>\n\n<p>Basically, computers really only understand machine language, which is a basic language implemented in binary (1's and 0's). One level above this is assembly language, which is a very primitive language that is at least human readable.</p>\n\n<p>In a high level language, we might have something like:</p>\n\n<pre><code>Person.WalkForward(10 steps)\n</code></pre>\n\n<p>In Machine code it would be:</p>\n\n<pre><code>Lift Persons Left Foot Up\nLean Forward\nPlace Left Foot Down\nLift Right Foot up\nLean Forward \nPlace Right Foot Down\netc\n</code></pre>\n\n<p>Now obviously, nobody wants to write programs that tell the computer every little repetitive thing to do so we have tools called compilers.</p>\n\n<p>A compiler takes a higher level language that is easier for a human to understand, and converts it down to machine code, so that the computer can run it.</p>\n" }, { "answer_id": 273997, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>The CPU has a register (a thingy that can store a number) called an instruction pointer. The instruction pointer says what address in memory to pull an instruction from. The CPU pulls an instruction, executes it, and goes on to the next instruction, unless the instruction that it executed said to go somewhere else. These instructions are fairly weak. Add this number to that number. Store this number over there. Take the next instruction from over there. A program called a compiler analyzes your program and turns it into machine code (I'm skipping a few steps here).</p>\n\n<p>Two books that will give you a decent overview of this process are <a href=\"http://mitpress.mit.edu/sicp/full-text/book/book.html\" rel=\"nofollow noreferrer\">SICP</a> and <a href=\"http://www1.idc.ac.il/tecs/\" rel=\"nofollow noreferrer\">TECS</a>.</p>\n" }, { "answer_id": 274001, "author": "wonderchook", "author_id": 32113, "author_profile": "https://Stackoverflow.com/users/32113", "pm_score": 1, "selected": false, "text": "<p>You could compare how programming works to translating between languages. Say you were on a desert island with 2 other people. You only speak French. Person number 1 (we'll call him Fred) only speaks French and Japanese. Person 2 (Bob) only speaks Japanese. Say you need to ask Bob to go help you gather some firewood. Imagine in this case you are the program and Bob is the computer. You say to Fred in French \"Can you tell Bob to come help me.\" Fred translates into Japanese and asks Bob to help you. In this case Fred would be the compiler. He translates the request into something Bob can understand. That is sort of how a computer program works.</p>\n\n<p>There is a good <a href=\"http://computer.howstuffworks.com/program1.htm\" rel=\"nofollow noreferrer\">How Stuff Works</a> article that explains things.</p>\n\n<p>I personally didn't really understand how computers could work the way they do until I took a digital electronics class. Prior to that the whole idea of how computers could work at all for me. After I built a binary counter it all made sense.</p>\n" }, { "answer_id": 274020, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 6, "selected": false, "text": "<p>It all starts with the CPU or processor. Each processor type has a defined set of instructions it's able to perform. These instructions operate over ones and zeroes, which in turn represent whatever you wish them to: numbers, letters, even the instructions themselves. </p>\n\n<p>At the lowest level, a zero is determined by the presence of a certain voltage (usually near 0V) at a transistor and a 1 is the presence of a different voltage (CPU dependent, say 5V)</p>\n\n<p>The machine instructions themselves are sets of zeroes and ones placed in a special locations called registers in the processor, the processor takes the instruction and its operands from specific locations and performs the operation, placing the result on yet another location, afterwards going to fetch the next instruction and so on and so forth until it runs out of instructions to perform or is turned off.</p>\n\n<p>A simple example. Let's say the machine instruction 001 means add two numbers. </p>\n\n<p>Then you write a program that adds two numbers, usually like this:</p>\n\n<pre><code>4 + 5\n</code></pre>\n\n<p>Then you pass this text to a compiler which will generate the adequate machine code for the processor you will run the program on (sidenote, you can compile code to be run in a different processor from the one you are currently running, it's a process called cross compilation and it's useful, for instance, in embedded platforms). Well, the compiler will end up generating, roughly,</p>\n\n<pre><code>001 00000100 00000101\n</code></pre>\n\n<p>with additional boilerplate machine code to place the 001 instruction in the next instruction register (instruction pointer) and the binary encoded numbers in data registers (or RAM).</p>\n\n<p>The process of generating machine code from structured languages is fairly complex and places limits on how normal these languages can end up looking like. That's why you can't write a program in english, there's too much ambiguity in it for a compiler to be able to generate the proper sequence of zeroes and ones.</p>\n\n<p>The instructions CPUs can execute are fairly basic and simple, addition, division, negation, read from RAM, place in RAM, read from register, and so on. </p>\n\n<p>The next question is, how can these simple instructions over numbers generate all the wonders we see in computing (internet, games, movie players, etc.)? </p>\n\n<p>It basically boils down to the creation of adequate models, for instance a 3D gaming engine has a mathematical model that represents the game world and can calculate the position/collisions of game objects based on it. </p>\n\n<p>These models are built on very many of these small instructions, and here's where high level languages (which are not machine code) really shine because they raise the abstraction level and you can then <em>think closer to the model you want to implement</em>, allowing you to easily reason about things like how to efficiently calculate the next position the soldier is going to be based on the received input from the controller instead of preventing you to reason easily because you are too busy trying not to forget a 0. </p>\n\n<p>A crucial moment occurred with the jump from assembly language (a language very similar to machine code, it was the first programming language and it's CPU specific. Every assembly instruction directly translates into machine code) to C (which is portable among different CPUs and is at a higher level of abstraction than assembly: each line of C code represents many machine code instructions). This was a huge productivity increase for programmers, they no longer had to port programs between different CPUs, and they could think a lot more easily about the underlying models, leading to the continued complexity increase in software we've seen (and even demand) from the 1970s until today. </p>\n\n<p>The pending missing link is how to control what to do with that information and how to receive input from external sources, say displaying images in the screen or writing information to a hard drive, or printing an image on a printer, or receiving keypunches from a keyboard. This is all made possible by the rest of the hardware present in the computer which is controlled in a way similar to that of the CPU, you place data and instructions in certain transistors in the graphic card or the network card or the hard drive or the RAM. The CPU has instructions that will allow it to place some data or instruction into (or read information out of) the proper location of different pieces of hardware.</p>\n\n<p>Another relevant thing to the existence of what we have today is that all modern computers come with big programs called operating systems that manage all the basic stuff like talking to hardware and error handling, like what happens if a program crashes and so on. In addition, many modern programming environments come with <strong>a lot</strong> of already written code (standard libraries) to handle many basic tasks like drawing on a screen or read a file. This libraries will in turn will ask the operating system to talk to the hardware in its behalf. </p>\n\n<p>If these weren't available, programming would be a very very hard and tedious task as every program you write would have to create again code to draw a single letter on the screen or to read a single bit from each specific type of hard drive, for example.</p>\n\n<p>It seems I got carried away, I hope you understand something out of this :-)</p>\n" }, { "answer_id": 274092, "author": "interstar", "author_id": 8482, "author_profile": "https://Stackoverflow.com/users/8482", "pm_score": 0, "selected": false, "text": "<p>As people are already noting, there's some pre-program (usually a \"compiler\") which translates the words of your program into a more long-winded \"lower level\" language called \"machine code\".</p>\n\n<p>The machine code consists of very simple instructions which are already \"understood\" by (or at least make sense in terms of) the underlying processor. For example, an instruction which copies data out of a memory location, and into a special part of the processor (called the \"accumulator\" where simple arithetic can be done to it.) or an instruction to add the contents of two of the slots in the accumulator.</p>\n\n<p>The complex, sophisticated programs you see (including the compilers and interpreters of higher level languages) are all, ultimately built out of these simple instructions being run millions of times.</p>\n" }, { "answer_id": 274120, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 1, "selected": false, "text": "<p>Several people have already provided summaries of the translation process from a typical programming language down to actual machine code that a processor can execute.</p>\n\n<p>To understand this process, it's helpful to have a concrete feel for what it's actually like to program at the level of machine code. Once you have an understanding of what the processor itself can do, it's easier to understand higher-level programming constructs as the abbreviations they are.</p>\n\n<p>But unfortunately, writing machine code for a desktop computer is not much fun.</p>\n\n<p>As an alternative, there is a great old game called <a href=\"http://en.wikipedia.org/wiki/Corewar\" rel=\"nofollow noreferrer\">Corewar</a> in which you write little programs using a simplified machine language. These programs then battle each other for survival. You can write basic programs in the raw machine language, and then there's a system of macros so you don't have to repeat yourself so much, and that's the first step towards a full-featured language.</p>\n\n<p>Another easy, rewarding, but low-level thing to do is to program a simple embedded controller like an <a href=\"http://en.wikipedia.org/wiki/Arduino\" rel=\"nofollow noreferrer\">Arduino</a>. There are lots of easy introductions like <a href=\"http://www.ladyada.net/learn/arduino/\" rel=\"nofollow noreferrer\">this one</a> available. You'll still be using a compiler, but the resulting machine code is easier to understand (if you want to) because the capabilities of the processor are so much simpler.</p>\n\n<p>Both of these are great ways to get a feel for how digital computers actually work.</p>\n" }, { "answer_id": 274150, "author": "Steve Fallows", "author_id": 18882, "author_profile": "https://Stackoverflow.com/users/18882", "pm_score": 3, "selected": false, "text": "<p>A good book that talks about computers for non-engineers is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735611319\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">'Code' by Charles Petzold</a>. I don't recall exactly if it covers exactly your question, but I think so. If you are interested enough to go farther it's a good choice.</p>\n\n<p><a href=\"http://ecx.images-amazon.com/images/I/11MYtZPhJEL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA198_SH20_OU01_.jpg\" rel=\"nofollow noreferrer\">Code http://ecx.images-amazon.com/images/I/11MYtZPhJEL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA198_SH20_OU01_.jpg</a></p>\n" }, { "answer_id": 274152, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>Computer programming is the act of giving the computer a set of instructions in a language that it can understand. Programmers normally write instructions in a high-level programming language, and those instruction then get translated into the binary language that the computer understands. Programs that do this translation are called compilers.</p>\n" }, { "answer_id": 274177, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 0, "selected": false, "text": "<p>The computer has a preset number of instructions; thing it already knows how to do. A computer program is simply a list of instructions that the computer will execute sequentially.</p>\n\n<p>Early programs were written directly in machine language. Programmers, to make their lives easier, started to create abstractions to simplify the programs they need to write. Over time, more and more abstractions are added, like layers of an onion, but it all boils down to essentially the same thing - executing a series of instructions. </p>\n\n<p>If you want to learn about programming without focusing on compilers, technology, etc, you get a good indication of what a program is when you start to create 3D scenes in <a href=\"http://www.alice.org\" rel=\"nofollow noreferrer\">Alice</a>. Alice is free from Carnegie Mellon University. You end up learn how to programming without trying to learn proramming.</p>\n\n<p>If however you want to learn more about the technical details, your best bet would be to look at some intro compi-sci university text books. The following <a href=\"http://computer.howstuffworks.com/c.htm/printable\" rel=\"nofollow noreferrer\">How C Programming Works</a> might also give you some answers.</p>\n" }, { "answer_id": 415091, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I have two crazy suggestions. Go back in time!</p>\n\n<p><b>1. Get a programmable calculator. </b></p>\n\n<p>A <a href=\"http://en.wikipedia.org/wiki/Programmable_calculator\" rel=\"nofollow noreferrer\">programmable calculator</a> is a regular calculator, you can do the usual stuff with it: enter numbers, enter operation signs, and after pressing the equel key, you can read the result on the tiny display. In addition, programmable calculator can store short sequences of keystrokes as a program, which later can be \"replayed\" with a single keypress. Say, you set this sequence as a program (one instruction per line):</p>\n\n<pre><code>(Start)\n*\n2\n+\n1\n=\n(Stop)\n</code></pre>\n\n<p>Now you have a custom operation: pressing the \"program\" key (or which one you've assigned to) it will run the sequence without your further assistance and will multiply the content of the display with 2 and will add 1 - this is a program!</p>\n\n<p>Later you can try more enhanced techniques: storing temporary results to memory, branch on result.</p>\n\n<p>Pros:</p>\n\n<ul>\n<li>A calculator is a familiar environment. You already have the basics.</li>\n<li>It's simple. You have not to learn lot of instructions and programming techniques.</li>\n<li>Modern programming languages are far from the ground, while programmable calculators \"are on it\". You will learn the fundamentals: memory, branch, elementary operations. Computers works very same (on the machine language level).</li>\n<li>You will meet low-level problems: memory, division by zero.</li>\n<li>It's extremly cool.</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>It's obsolete. You have to learn a modern programming language, which will be different. </li>\n<li>It's uncomfortable (hm, it's a pro instead: you can't use comfortable click-and-play toys). Maybe you can't even save your code.</li>\n<li>It's not a trivial task to get one. You can try on E-Bay. Also, there will be no problem with documentations, most modells have large user groups on the internet.</li>\n</ul>\n\n<p>The best choice IMHO the <a href=\"http://www.ti59.com/\" rel=\"nofollow noreferrer\">TI-59</a>.</p>\n\n<p><b>2. Learn the BASIC language with the help of an emulator. </b></p>\n\n<p>When you turn on a machine which have a built-in <a href=\"http://en.wikipedia.org/wiki/BASIC_programming_language\" rel=\"nofollow noreferrer\">BASIC language</a> interpreter, it's ready to accept your commands, and performs just as you type. First, you can try some instructions in command mode, e.g.:</p>\n\n<pre><code>PRINT 5*4\n</code></pre>\n\n<p>It will print \"20\" in the next line, wow. If you've played enough in command mode, you can organize the instructions into programs, then you can run, edit, enhance it.</p>\n\n<p>Pros:</p>\n\n<ul>\n<li>BASIC is a real programming language, designed for education.</li>\n<li>When you later meet a modern programming language, and will discover the differences, you will see the progress of the programming techniques (e.g. procedural, structures etc.) of the last 30 years.</li>\n<li>It's cool, especially if you get a real one, not just an emulator.</li>\n</ul>\n\n<p>Cons</p>\n\n<ul>\n<li>It's obsolete. Almost 30 years passed since that age.</li>\n<li>Old machines are compact, closed systems. There are no files (in the form today we use them), folders, file types, it may confuse beginners.</li>\n</ul>\n\n<p>My favourite BASIC system is the <a href=\"http://en.wikipedia.org/wiki/Commodore_16\" rel=\"nofollow noreferrer\">Commodore 16 (Plus/4)</a>, which is very similar to the famous C64. but more comfortable. I prefer <a href=\"http://yape.homeserver.hu/download.htm\" rel=\"nofollow noreferrer\">YAPE</a> emulator, it can save/load memory snapshots or BASIC programs to file.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35661/" ]
What makes all the words of a programming language actually do anything? I mean, what's actually happening to make the computer know what all of those words mean? If I verbally tell my my computer to do something, it doesn't do it, because it doesn't understand. So how exactly can these human words written into a language actually cause the computer to do some desirable activity?
It all starts with the CPU or processor. Each processor type has a defined set of instructions it's able to perform. These instructions operate over ones and zeroes, which in turn represent whatever you wish them to: numbers, letters, even the instructions themselves. At the lowest level, a zero is determined by the presence of a certain voltage (usually near 0V) at a transistor and a 1 is the presence of a different voltage (CPU dependent, say 5V) The machine instructions themselves are sets of zeroes and ones placed in a special locations called registers in the processor, the processor takes the instruction and its operands from specific locations and performs the operation, placing the result on yet another location, afterwards going to fetch the next instruction and so on and so forth until it runs out of instructions to perform or is turned off. A simple example. Let's say the machine instruction 001 means add two numbers. Then you write a program that adds two numbers, usually like this: ``` 4 + 5 ``` Then you pass this text to a compiler which will generate the adequate machine code for the processor you will run the program on (sidenote, you can compile code to be run in a different processor from the one you are currently running, it's a process called cross compilation and it's useful, for instance, in embedded platforms). Well, the compiler will end up generating, roughly, ``` 001 00000100 00000101 ``` with additional boilerplate machine code to place the 001 instruction in the next instruction register (instruction pointer) and the binary encoded numbers in data registers (or RAM). The process of generating machine code from structured languages is fairly complex and places limits on how normal these languages can end up looking like. That's why you can't write a program in english, there's too much ambiguity in it for a compiler to be able to generate the proper sequence of zeroes and ones. The instructions CPUs can execute are fairly basic and simple, addition, division, negation, read from RAM, place in RAM, read from register, and so on. The next question is, how can these simple instructions over numbers generate all the wonders we see in computing (internet, games, movie players, etc.)? It basically boils down to the creation of adequate models, for instance a 3D gaming engine has a mathematical model that represents the game world and can calculate the position/collisions of game objects based on it. These models are built on very many of these small instructions, and here's where high level languages (which are not machine code) really shine because they raise the abstraction level and you can then *think closer to the model you want to implement*, allowing you to easily reason about things like how to efficiently calculate the next position the soldier is going to be based on the received input from the controller instead of preventing you to reason easily because you are too busy trying not to forget a 0. A crucial moment occurred with the jump from assembly language (a language very similar to machine code, it was the first programming language and it's CPU specific. Every assembly instruction directly translates into machine code) to C (which is portable among different CPUs and is at a higher level of abstraction than assembly: each line of C code represents many machine code instructions). This was a huge productivity increase for programmers, they no longer had to port programs between different CPUs, and they could think a lot more easily about the underlying models, leading to the continued complexity increase in software we've seen (and even demand) from the 1970s until today. The pending missing link is how to control what to do with that information and how to receive input from external sources, say displaying images in the screen or writing information to a hard drive, or printing an image on a printer, or receiving keypunches from a keyboard. This is all made possible by the rest of the hardware present in the computer which is controlled in a way similar to that of the CPU, you place data and instructions in certain transistors in the graphic card or the network card or the hard drive or the RAM. The CPU has instructions that will allow it to place some data or instruction into (or read information out of) the proper location of different pieces of hardware. Another relevant thing to the existence of what we have today is that all modern computers come with big programs called operating systems that manage all the basic stuff like talking to hardware and error handling, like what happens if a program crashes and so on. In addition, many modern programming environments come with **a lot** of already written code (standard libraries) to handle many basic tasks like drawing on a screen or read a file. This libraries will in turn will ask the operating system to talk to the hardware in its behalf. If these weren't available, programming would be a very very hard and tedious task as every program you write would have to create again code to draw a single letter on the screen or to read a single bit from each specific type of hard drive, for example. It seems I got carried away, I hope you understand something out of this :-)
273,995
<p>How does one prevent an inclusion cycle in C? ie. You shouldn't have a.h #include "b.h", which #include's "c.h" which #include's "a.h". I'm looking for a way of preventing this from happening using some sort of C directive.</p> <p>I had originally thought this would've prevented this from happening:</p> <p>Contents of a.h:</p> <pre><code>#ifndef __A_H #define __A_H #include "b.h" #endif // __A_H </code></pre> <p>Contents of b.h:</p> <pre><code>#ifndef __B_H #define __B_H #include "c.h" #endif // __B_H </code></pre> <p>Contents of c.h:</p> <pre><code>#ifndef __C_H #define __C_H #include "a.h" #endif // __C_H </code></pre> <p>But it doesn't seem to work.</p>
[ { "answer_id": 274008, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 4, "selected": true, "text": "<p>It does work allright: the files <strong>are</strong> repeatedly included, but the sections protected by #ifdndef/#define/#endif <strong>are not</strong> repeated, and that breaks the cycle.</p>\n\n<p>Use your compiler to produce the preprocessed output and look at it for yourself. With GNU CC, you need to use \"-E\" option on the .c[pp] file, like this:</p>\n\n<pre><code>gcc -E $(CFLAGS) -o foo.i foo.cpp\n</code></pre>\n" }, { "answer_id": 274012, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 1, "selected": false, "text": "<p>Macros with leading underscores are reserved for the preprocessor/compiler.</p>\n\n<p>Try changing __*_H to something more standard.<br>\nI use HAVE__*_H.</p>\n" }, { "answer_id": 274013, "author": "Todd Gamblin", "author_id": 9122, "author_profile": "https://Stackoverflow.com/users/9122", "pm_score": 1, "selected": false, "text": "<p>That should work. It's written correctly in your example and compiles fine for me. Did you mistype something in your actual code, or is it really some other problem you're seeing?</p>\n\n<p>You shouldn't start things out with __, though, as that's reserved for the compiler and/or system libraries. Try some other names for your guards.</p>\n" }, { "answer_id": 274015, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 0, "selected": false, "text": "<p>This works.</p>\n\n<p>Just to be sure, I actually compiled a test.c that included a.h with your 3 header files.</p>\n\n<p>I verified this works for several versions of MSVC, Digital Mars and GCC.</p>\n" }, { "answer_id": 283666, "author": "Manoj Doubts", "author_id": 31116, "author_profile": "https://Stackoverflow.com/users/31116", "pm_score": 1, "selected": false, "text": "<p>ya in addition to the above things if you are working on turbo c and you are doing a project with these source files then do not attach the header files which are #included in the source files.And even then if it is not working then try it from command prompt because some compiler options give these errors again and again.so here if the header files contents are between the #ifndef and #endif then there will be no problem even you include both the files. So try removing the header files from the project keeping them in the same directory.bcos u didnt specified environment i specified turbo C because i faced this situation once on turbo C with the header files #included in source file and attached to the project files list then there will be \"multiple declaration problem\".also after compiling (even with errors) go to external command line and go to directory where that file is stored and try with the filename.exe directly.ok </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19026/" ]
How does one prevent an inclusion cycle in C? ie. You shouldn't have a.h #include "b.h", which #include's "c.h" which #include's "a.h". I'm looking for a way of preventing this from happening using some sort of C directive. I had originally thought this would've prevented this from happening: Contents of a.h: ``` #ifndef __A_H #define __A_H #include "b.h" #endif // __A_H ``` Contents of b.h: ``` #ifndef __B_H #define __B_H #include "c.h" #endif // __B_H ``` Contents of c.h: ``` #ifndef __C_H #define __C_H #include "a.h" #endif // __C_H ``` But it doesn't seem to work.
It does work allright: the files **are** repeatedly included, but the sections protected by #ifdndef/#define/#endif **are not** repeated, and that breaks the cycle. Use your compiler to produce the preprocessed output and look at it for yourself. With GNU CC, you need to use "-E" option on the .c[pp] file, like this: ``` gcc -E $(CFLAGS) -o foo.i foo.cpp ```
274,009
<p>I have a "username" TEdit on a Delphi 2006 login form. When the application starts up the user is asked to enter the username. The TEdit gets focus and the caret is placed in its horizontal center for some reason. As soon as anything is typed the caret is left aligned again and everything looks normal. </p> <p>It is also strange that it wasn't always like this. This behaviour suddenly started a few years ago (I believe we still used Delphi 6 at that time). Any idea what might be causing this?</p> <p>Additional info (has been asked for): <li>The problem is widespread: D2006 and D6 (I believe), 5 or 6 Delphi instances on as much computers, all applications using that login form. The effect is limited to the form however, it does not occur on other TEdits.</li> <li>The TEdit is not filled with spaces (that would be strange to do in the first place).</li> <br> More info (Nov 13): <li>The caret is not centered exactly, it is <i>almost</i> centered.</li> <li>Currently it seems to occur in a DLL only. The same login dialog is used in regular executables and does not show the problem there (although I believe it did at some time).</li> <li>The edit field is a password edit, the OnChange handler sets an integer field of that form only, there are no other event handlers on that edit field.</li> <li>I added another plain TEdit, which is also the ActiveControl so that it has focus when the form shows (as it was with the password edit). I also removed the default text "Edit1". Now the issue is present in that TEdit in the same way.</li> <li>The "centered" caret goes back to normal if either a character is entered or if I tab through the controls - when I come back to the TEdit it looks normal. This was the same with the password edit.</li></p>
[ { "answer_id": 274518, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 1, "selected": false, "text": "<p>Just a few additional questions: </p>\n\n<ol>\n<li>Is this problem on one pc or on more pc's?</li>\n<li>Does it occur on one application or on all applications?</li>\n<li>Does it happen only on your Delphi applications or on all applications?</li>\n</ol>\n\n<p>If it is only on one pc, I think it is a strange registry setting. If its on more pc's but you only have one delphi development pc, it could still be a registry setting. But there are other possibilities.</p>\n\n<p>You could try some tests:</p>\n\n<ol>\n<li>Create an simple app on the dev pc and run it on another. Does this show the effect.</li>\n<li>Use an app that is created by Delphi but build on another pc that does not show the effect, and run it on the dev pc, does this show the effect?</li>\n</ol>\n\n<p>I really think this is a registry setting. According to the information you gave me, it happened since Delphi 6 and is still happening. \nIt also can be a locale setting but then it has to happen in more programs.</p>\n\n<p><strong>Edit:</strong>\nThanks for the extra info. \nSo it looks like the problem can be isolated to a single form. But it occurs on all pc's.</p>\n\n<p>What you can do, is delete the edit, and re-add a new one. This saves searching for weird property values. </p>\n\n<ul>\n<li>Are there events hooked on the TEdit that can possible explain the effects?</li>\n<li>What property values are set? (But I prefer a look at the dfm and the code, because then I'm possible able to reproduce the effect.)</li>\n</ul>\n" }, { "answer_id": 274549, "author": "Stephan Eggermont", "author_id": 35306, "author_profile": "https://Stackoverflow.com/users/35306", "pm_score": 0, "selected": false, "text": "<p>Are you sure it is a simple TEdit? It might be initialized with a few spaces instead of an empty string. The onChange handler then might just strip spaces as soon as you start typing.\nA TEdit extension might have text alignment set on centered instead of left, and set text alignment only on onChange.</p>\n\n<p>[edit]\nPlease show the event handlers of the TEdit.</p>\n" }, { "answer_id": 287198, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I've also noticed this behaviour in richedits.</p>\n\n<p>One place in our app is a double click on a grid which displays another screen containing a RichEdit. The caret always seems to appear in the Richedit in the same place as the double click on the grid occured, ie if the dblclick was on the 3rd line of the grid, the caret will appear ~3 lines down on the edit. As soon as a key is pressed, the caret resets to the correct position of top left.</p>\n\n<p>Its not limited to a certain form or pc as it happens on all developers machines and also on clients machines. \nThe app was originally developed in Delphi 5, but the problem didn't occur (or wasn't noticed) until we moved to D2006.</p>\n\n<p>Its not a particularily big problem, just... irritating.</p>\n" }, { "answer_id": 2103150, "author": "DamienD", "author_id": 254839, "author_profile": "https://Stackoverflow.com/users/254839", "pm_score": 2, "selected": false, "text": "<p>I had also the same problem in Delphi 2007,<br> \nwith a TEdit placed in a modal form called by double-clicking in a Grid.</p>\n\n<p>I made some tests launching the same Form from a TSpeedButton.\nI noticed that the problem with the TEdit appears only when the grid is focused.</p>\n\n<p><strong>after more tests the problem appears to be a bug in the VCL</strong>.<br>\nin TCustomGrid.paint there is a Call of SetCaretPos, even if the grid is not on an active Form.</p>\n\n<pre><code> ../..\n Focused := IsActiveControl;\n if Focused and (CurRow = Row) and (CurCol = Col) then\n begin\n SetCaretPos(Where.Left, Where.Top); \n Include(DrawState, gdFocused);\n end;\n ../.. \n</code></pre>\n\n<p>the code above is from TCustomGrid.paint in Grids.pas\nin this code, Focused is set to true if the grid is the \"activeControl\" of the parent form, the code don't take into account if the form is active or not.</p>\n\n<p>then, if the grid need to be repaint, setCaretPos is called with grid coordinates, causing the bug mentioned in the question.</p>\n\n<p>The bug is very difficult to notice because, most of the times, the caret simply disappear from the active form instead of blinking near the middle of a TEdit.</p>\n\n<p><strong>steps to reproduce the bug :</strong> <br></p>\n\n<ol>\n<li>start new VCL form app. </li>\n<li>add TStringGrid into it. </li>\n<li>add a second form to the app with just a TEdit in it.</li>\n<li>return in main form (unit1) and call form2.showmodal from the grid DblClick event.</li>\n</ol>\n\n<p>that's all : you can launch the application and double click on a grid cell.\nif you drag the modal form away of the main form, the grid will need to be repaint, then causing the caret to disappear from the modal form (or to appear in the middle of the TEdit if you are very lucky) </p>\n\n<p>So, I think a fix is needed in Grids.pas.</p>\n\n<p>in the excerpt of grid.pas above, I suggest replacing the call of the function IsActiveControl by a call of a new function called IsFocusedControl :</p>\n\n<pre><code>// new function introduced to fix a bug\n// this function is a duplicate of the function IsActiveControl\n// with a minor modification (see comment)\nfunction TCustomGrid.IsFocusedControl: Boolean;\nvar\n H: Hwnd;\n ParentForm: TCustomForm;\nbegin\n Result := False;\n ParentForm := GetParentForm(Self);\n if Assigned(ParentForm) then\n begin\n if (ParentForm.ActiveControl = Self) then\n //Result := True; // removed by DamienD\n Result := ParentForm.Active; // added by DamienD\n end\n else\n begin\n H := GetFocus;\n while IsWindow(H) and (Result = False) do\n begin\n if H = WindowHandle then\n Result := True\n else\n H := GetParent(H);\n end;\n end;\nend;\n</code></pre>\n\n<p>this fix (made in Delphi2007) worked well for me, but is not garanteed. <br>\n(also, <a href=\"https://stackoverflow.com/questions/1055010/how-to-recompile-a-specific-unit-from-the-vcl/1055021#1055021\">do not modify directly units of the VCL</a>).</p>\n" }, { "answer_id": 2323230, "author": "Michael Chen", "author_id": 279995, "author_profile": "https://Stackoverflow.com/users/279995", "pm_score": 0, "selected": false, "text": "<p>Another workaround:</p>\n\n<p>Before showing the second form, prevent the grid on the first form doing Paint action. Code snippet as below.</p>\n\n<pre><code>Gird.BeginUpdate;\n\ntry\n\n //Show the second form here\n\nfinally\n\n Grid.EndUpdate;\n\nend;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/274009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35657/" ]
I have a "username" TEdit on a Delphi 2006 login form. When the application starts up the user is asked to enter the username. The TEdit gets focus and the caret is placed in its horizontal center for some reason. As soon as anything is typed the caret is left aligned again and everything looks normal. It is also strange that it wasn't always like this. This behaviour suddenly started a few years ago (I believe we still used Delphi 6 at that time). Any idea what might be causing this? Additional info (has been asked for): - The problem is widespread: D2006 and D6 (I believe), 5 or 6 Delphi instances on as much computers, all applications using that login form. The effect is limited to the form however, it does not occur on other TEdits. - The TEdit is not filled with spaces (that would be strange to do in the first place). More info (Nov 13): - The caret is not centered exactly, it is *almost* centered. - Currently it seems to occur in a DLL only. The same login dialog is used in regular executables and does not show the problem there (although I believe it did at some time). - The edit field is a password edit, the OnChange handler sets an integer field of that form only, there are no other event handlers on that edit field. - I added another plain TEdit, which is also the ActiveControl so that it has focus when the form shows (as it was with the password edit). I also removed the default text "Edit1". Now the issue is present in that TEdit in the same way. - The "centered" caret goes back to normal if either a character is entered or if I tab through the controls - when I come back to the TEdit it looks normal. This was the same with the password edit.
I had also the same problem in Delphi 2007, with a TEdit placed in a modal form called by double-clicking in a Grid. I made some tests launching the same Form from a TSpeedButton. I noticed that the problem with the TEdit appears only when the grid is focused. **after more tests the problem appears to be a bug in the VCL**. in TCustomGrid.paint there is a Call of SetCaretPos, even if the grid is not on an active Form. ``` ../.. Focused := IsActiveControl; if Focused and (CurRow = Row) and (CurCol = Col) then begin SetCaretPos(Where.Left, Where.Top); Include(DrawState, gdFocused); end; ../.. ``` the code above is from TCustomGrid.paint in Grids.pas in this code, Focused is set to true if the grid is the "activeControl" of the parent form, the code don't take into account if the form is active or not. then, if the grid need to be repaint, setCaretPos is called with grid coordinates, causing the bug mentioned in the question. The bug is very difficult to notice because, most of the times, the caret simply disappear from the active form instead of blinking near the middle of a TEdit. **steps to reproduce the bug :** 1. start new VCL form app. 2. add TStringGrid into it. 3. add a second form to the app with just a TEdit in it. 4. return in main form (unit1) and call form2.showmodal from the grid DblClick event. that's all : you can launch the application and double click on a grid cell. if you drag the modal form away of the main form, the grid will need to be repaint, then causing the caret to disappear from the modal form (or to appear in the middle of the TEdit if you are very lucky) So, I think a fix is needed in Grids.pas. in the excerpt of grid.pas above, I suggest replacing the call of the function IsActiveControl by a call of a new function called IsFocusedControl : ``` // new function introduced to fix a bug // this function is a duplicate of the function IsActiveControl // with a minor modification (see comment) function TCustomGrid.IsFocusedControl: Boolean; var H: Hwnd; ParentForm: TCustomForm; begin Result := False; ParentForm := GetParentForm(Self); if Assigned(ParentForm) then begin if (ParentForm.ActiveControl = Self) then //Result := True; // removed by DamienD Result := ParentForm.Active; // added by DamienD end else begin H := GetFocus; while IsWindow(H) and (Result = False) do begin if H = WindowHandle then Result := True else H := GetParent(H); end; end; end; ``` this fix (made in Delphi2007) worked well for me, but is not garanteed. (also, [do not modify directly units of the VCL](https://stackoverflow.com/questions/1055010/how-to-recompile-a-specific-unit-from-the-vcl/1055021#1055021)).
274,011
<p>I would like to know if there is software that, given a regex and of course some other constraints like length, produces random text that always matches the given regex. Thanks</p>
[ { "answer_id": 274016, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 0, "selected": false, "text": "<p>Instead of starting from a regexp, you should be looking into writing a small context free grammer, this will allow you to easily generate such random text. Unfortunately, I know of no tool which will do it directly for you, so you would need to do a bit of code yourself to actually generate the text. If you have not worked with grammers before, I suggest you read a bit about bnf format and \"compiler compilers\" before proceeding...</p>\n" }, { "answer_id": 274019, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>I'm not aware of any, although it should be possible. The usual approach is to write a grammar instead of a regular expression, and then create functions for each non-terminal that randomly decide which production to expand. If you could post a description of the kinds of strings that you want to generate, and what language you are using, we may be able to get you started.</p>\n" }, { "answer_id": 274035, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": 1, "selected": false, "text": "<p>We did something <em>similar</em> in Python not too long ago for a <a href=\"http://www.pyweek.org/e/RegExExpress/\" rel=\"nofollow noreferrer\">RegEx game</a> that we wrote. We had the constraint that the regex had to be randomly generated, and the selected words had to be real words. You can download the completed game EXE <a href=\"http://samwashburn.com/hanclinto/RegExExpress%201.3%20EXE.zip\" rel=\"nofollow noreferrer\">here</a>, and the Python source code <a href=\"http://media.pyweek.org/dl/7/RegExExpress/regex_express-1.3.zip\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Here is a snippet:</p>\n\n<pre><code>def generate_problem(level):\n keep_trying = True\n while(keep_trying):\n regex = gen_regex(level)\n # print 'regex = ' + regex\n counter = 0\n match = 0\n notmatch = 0\n goodwords = []\n badwords = []\n num_words = 2 + level * 3\n if num_words &gt; 18:\n num_words = 18\n max_word_length = level + 4\n while (counter &lt; 10000) and ((match &lt; num_words) or (notmatch &lt; num_words)):\n counter += 1\n rand_word = words[random.randint(0,max_word)]\n if len(rand_word) &gt; max_word_length:\n continue\n mo = re.search(regex, rand_word)\n if mo:\n match += 1\n if len(goodwords) &lt; num_words:\n goodwords.append(rand_word)\n else:\n notmatch += 1\n if len(badwords) &lt; num_words:\n badwords.append(rand_word)\n if counter &lt; 10000:\n new_prob = problem.problem()\n new_prob.title = 'Level ' + str(level)\n new_prob.explanation = 'This is a level %d puzzle. ' % level\n new_prob.goodwords = goodwords\n new_prob.badwords = badwords\n new_prob.regex = regex\n keep_trying = False\n return new_prob\n</code></pre>\n" }, { "answer_id": 274041, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 3, "selected": false, "text": "<p>Check out the <a href=\"http://github.com/benburkert/randexp\" rel=\"nofollow noreferrer\">RandExp</a> Ruby gem. It does what you want, though only in a limited fashion. (It won't work with every possible regexp, only regexps which meet some restrictions.)</p>\n" }, { "answer_id": 274047, "author": "Jay Kominek", "author_id": 32878, "author_profile": "https://Stackoverflow.com/users/32878", "pm_score": 4, "selected": false, "text": "<p>All regular expressions can be expressed as context free grammars. And there is <a href=\"http://www.cosc.canterbury.ac.nz/research/reports/TechReps/1997/tr_9710.pdf\" rel=\"noreferrer\">a nice algorithm already worked out</a> for producing random sentences, from any CFG, of a given length. So upconvert the regex to a cfg, apply the algorithm, and wham, you're done.</p>\n" }, { "answer_id": 1590617, "author": "Wilfred Springer", "author_id": 136476, "author_profile": "https://Stackoverflow.com/users/136476", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://code.google.com/p/xeger\" rel=\"noreferrer\">Xeger</a> is capable of doing it: </p>\n\n<pre><code>String regex = \"[ab]{4,6}c\";\nXeger generator = new Xeger(regex);\nString result = generator.generate();\nassert result.matches(regex);\n</code></pre>\n" }, { "answer_id": 9553179, "author": "fent", "author_id": 157629, "author_profile": "https://Stackoverflow.com/users/157629", "pm_score": 3, "selected": false, "text": "<p>If you want a Javascript solution, try <a href=\"http://fent.github.com/randexp.js/\">randexp.js</a>.</p>\n" }, { "answer_id": 24659692, "author": "Mifmif", "author_id": 1250229, "author_profile": "https://Stackoverflow.com/users/1250229", "pm_score": 2, "selected": false, "text": "<p>Too late but it could help newcomer , here is a useful <a href=\"https://github.com/mifmif/Generex\" rel=\"nofollow\">java library</a> that provide many features for using regex to generate String (random generation ,generate String based on it's index, generate all String..) check it out <a href=\"https://github.com/mifmif/Generex\" rel=\"nofollow\">here</a> .</p>\n\n<p>Example :</p>\n\n<pre><code> Generex generex = new Generex(\"[0-3]([a-c]|[e-g]{1,2})\");\n\n // generate the second String in lexicographical order that match the given Regex.\n String secondString = generex.getMatchedString(2);\n System.out.println(secondString);// it print '0b'\n\n // Generate all String that matches the given Regex.\n List&lt;String&gt; matchedStrs = generex.getAllMatchedStrings();\n\n // Using Generex iterator\n Iterator iterator = generex.iterator();\n while (iterator.hasNext()) {\n System.out.print(iterator.next() + \" \");\n }\n // it print 0a 0b 0c 0e 0ee 0e 0e 0f 0fe 0f 0f 0g 0ge 0g 0g 1a 1b 1c 1e\n // 1ee 1e 1e 1f 1fe 1f 1f 1g 1ge 1g 1g 2a 2b 2c 2e 2ee 2e 2e 2f 2fe 2f 2f 2g\n // 2ge 2g 2g 3a 3b 3c 3e 3ee 3e 3e 3f 3fe 3f 3f 3g 3ge 3g 3g 1ee\n\n // Generate random String\n String randomStr = generex.random();\n System.out.println(randomStr);// a random value from the previous String list\n</code></pre>\n" }, { "answer_id": 43377488, "author": "Sjoerd", "author_id": 182971, "author_profile": "https://Stackoverflow.com/users/182971", "pm_score": 5, "selected": false, "text": "<p>Yes, software that can generate a random match to a regex:</p>\n<ul>\n <li><a href=\"https://github.com/asciimoo/exrex\" rel=\"nofollow noreferrer\">Exrex</a>, Python</li>\n <li><a href=\"https://www.npmjs.com/package/pxeger\" rel=\"nofollow noreferrer\">Pxeger</a>, Javascript</li>\n <li><a href=\"https://github.com/audreyt/regex-genex\" rel=\"nofollow noreferrer\">regex-genex</a>, Haskell</li>\n <li><a href=\"https://github.com/bluezio/xeger\" rel=\"nofollow noreferrer\">Xeger</a>, Java</li>\n <li><a href=\"https://github.com/crdoconnor/xeger\" rel=\"nofollow noreferrer\">Xeger</a>, Python</li>\n <li><a href=\"https://github.com/mifmif/Generex\" rel=\"nofollow noreferrer\">Generex</a>, Java</li>\n <li><a href=\"https://github.com/GoranSiska/rxrdg\" rel=\"nofollow noreferrer\">rxrdg</a>, C#</li>\n <li><a href=\"http://search.cpan.org/~steve/String-Random-0.20/Random.pm\" rel=\"nofollow noreferrer\">String::Random</a>, Perl</li>\n <li><a href=\"https://regldg.com/\" rel=\"nofollow noreferrer\">regldg</a>, C</li>\n <li><a href=\"https://github.com/gajus/paggern\" rel=\"nofollow noreferrer\">paggern</a>, PHP</li>\n <li><a href=\"https://github.com/icomefromthenet/ReverseRegex\" rel=\"nofollow noreferrer\">ReverseRegex</a>, PHP</li>\n <li><a href=\"https://fent.github.io/randexp.js/\" rel=\"nofollow noreferrer\">randexp.js</a>, Javascript</li>\n <li><a href=\"https://github.com/elarsonSU/egret\" rel=\"nofollow noreferrer\">EGRET</a>, Python/C++</li>\n <li><a href=\"https://github.com/fmselab/mutrex\" rel=\"nofollow noreferrer\">MutRex</a>, Java</li>\n <li><a href=\"https://github.com/moodmosaic/Fare\" rel=\"nofollow noreferrer\">Fare</a>, C#</li>\n <li><a href=\"https://pypi.python.org/pypi/rstr/2.1.3\" rel=\"nofollow noreferrer\">rstr</a>, Python</li>\n <li><a href=\"https://github.com/benburkert/randexp\" rel=\"nofollow noreferrer\">randexp</a>, Ruby</li>\n <li><a href=\"https://github.com/zach-klippenstein/goregen\" rel=\"nofollow noreferrer\">goregen</a>, Go</li>\n <li><a href=\"https://github.com/six2six/bfgex\" rel=\"nofollow noreferrer\">bfgex</a>, Java</li>\n <li><a href=\"https://github.com/arh23/regexgen\" rel=\"nofollow noreferrer\">regexgen</a>, Javascript</li>\n <li><a href=\"https://github.com/paul-wolf/strgen\" rel=\"nofollow noreferrer\">strgen</a>, Python</li>\n <li><a href=\"https://github.com/moznion/java-random-string\" rel=\"nofollow noreferrer\">random-string</a>, Java</li>\n <li><a href=\"https://launchpad.net/regexp-unfolder\" rel=\"nofollow noreferrer\">regexp-unfolder</a>, Clojure</li>\n <li><a href=\"https://hackage.haskell.org/package/string-random\" rel=\"nofollow noreferrer\">string-random</a>, Haskell</li>\n <li><a href=\"https://code.google.com/archive/p/rxrdg/\" rel=\"nofollow noreferrer\">rxrdg</a>, C#</li>\n <li><a href=\"http://search.cpan.org/~bowmanbs/Regexp-Genex-0.07/lib/Regexp/Genex.pm\" rel=\"nofollow noreferrer\">Regexp::Genex</a>, Perl</li>\n <li><a href=\"https://pypi.python.org/pypi/StringGenerator/0.2.0\" rel=\"nofollow noreferrer\">StringGenerator</a>, Python</li>\n <li><a href=\"https://github.com/Songmu/strrand\" rel=\"nofollow noreferrer\">strrand</a>, Go</li>\n <li><a href=\"https://godoc.org/github.com/zach-klippenstein/goregen\" rel=\"nofollow noreferrer\">regen</a>, Go</li>\n <li><a href=\"https://www.microsoft.com/en-us/research/project/rex-regular-expression-exploration/\" rel=\"nofollow noreferrer\">Rex</a>, C#</li>\n <li><a href=\"https://github.com/tom-lord/regexp-examples\" rel=\"nofollow noreferrer\">regexp-examples</a>, Ruby</li>\n <li><a href=\"https://github.com/alixaxel/genex.js\" rel=\"nofollow noreferrer\">genex.js</a>, JavaScript</li>\n <li><a href=\"https://github.com/alixaxel/genex\" rel=\"nofollow noreferrer\">genex</a>, Go</li>\n</ul>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/274011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11906/" ]
I would like to know if there is software that, given a regex and of course some other constraints like length, produces random text that always matches the given regex. Thanks
[Xeger](http://code.google.com/p/xeger) is capable of doing it: ``` String regex = "[ab]{4,6}c"; Xeger generator = new Xeger(regex); String result = generator.generate(); assert result.matches(regex); ```
274,022
<p>I very rarely meet any other programmers!</p> <p>My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense.</p> <p>So how do I say or read "=>" as in:-</p> <pre><code>IEnumerable&lt;Person&gt; Adults = people.Where(p =&gt; p.Age &gt; 16) </code></pre> <p>Or is there even an agreed way of saying it?</p>
[ { "answer_id": 274025, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 8, "selected": true, "text": "<p>I usually say 'such that' when reading that operator.</p>\n\n<p>In your example, p => p.Age > 16 reads as \"P, such that p.Age is greater than 16.\"</p>\n\n<p>In fact, I asked this very question on the official linq pre-release forums, and Anders Hejlsberg responded by saying</p>\n\n<blockquote>\n <p>I usually read the => operator as \"becomes\" or \"for which\". For example,<br />\n Func f = x => x * 2;<br />\n Func test = c => c.City == \"London\";<br />\n reads as \"x becomes x * 2\" and \"c for which c.City equals London\"</p>\n</blockquote>\n\n<p>As far as 'goes to' - that's never made sense to me. 'p' isn't going anywhere.</p>\n\n<p>In the case of reading code to someone, say, over the phone, then as long as they're a fellow C# programmer, I'd just use the word 'lambda' - that is, \"p lambda p dot age greater-than sixteen.\"</p>\n\n<p>In comments Steve Jessop mentioned 'maps to' in the case of transformations - so taking Anders' example:</p>\n\n<pre><code>x =&gt; x * 2;\n</code></pre>\n\n<p>would read</p>\n\n<blockquote>\n <p>x maps to x times 2.</p>\n</blockquote>\n\n<p>That does seem much closer to the actual intention of the code than 'becomes' for this case.</p>\n" }, { "answer_id": 274027, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://blogs.msdn.com/ericlippert/archive/2008/05/16/reading-code-over-the-telephone.aspx\" rel=\"noreferrer\">Reading Code Over the Telephone</a> </p>\n\n<p>From Eric Lippert:</p>\n\n<p>I personally would say c=>c+1 as \"see goes to see plus one\". Some variations that I've heard:</p>\n\n<p>For a projection, (Customer c)=>c.Name: \"customer see becomes see dot name\"</p>\n\n<p>For a predicate, (Customer c)=>c.Age > 21: \"customer see such that see dot age is greater than twenty-one\"</p>\n" }, { "answer_id": 274029, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 3, "selected": false, "text": "<p>I've seen people say, \"Arrow.\"</p>\n" }, { "answer_id": 274031, "author": "CodeChef", "author_id": 21786, "author_profile": "https://Stackoverflow.com/users/21786", "pm_score": 3, "selected": false, "text": "<p>I use \"goes to\" because a LINQ book told me to :)</p>\n" }, { "answer_id": 274033, "author": "Tad Donaghe", "author_id": 1572436, "author_profile": "https://Stackoverflow.com/users/1572436", "pm_score": 1, "selected": false, "text": "<p>Part of the problem is that you can read it out loud differently depending on how it's structured. It's a shame it's not as pretty or as integrated as ruby's |'s.</p>\n" }, { "answer_id": 274155, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 2, "selected": false, "text": "<p>Apart from acquiring the preceding scope (all variables and constants that are in scope for a normal line of code at the point where a lambda expression occurs are available to the code of the expression) a lambda expression is essentially syntactic sugar for an inline function. </p>\n\n<p>The list of values to the left of the production operator (\"=>\") contributes the structure and content of the stack frame used to make the call to this function. You could say that the list of values contributes both the parameter declarations and the arguments that are passed; in more conventional code these determine the structure and content of the stack frame used to make the call to a function.</p>\n\n<p>As a result, the values \"go to\" the expression code. Would you rather say \"defines the stack frame for\" or \"goes to\" ? :)</p>\n\n<p>In the narrowly defined application of boolean expressions used as filter conditions (a dominant use of lambda expressions extensively considered by other answers to this question) it is very reasonable to skip the method in favour of the intent of the code, and this leads to \"for which\" being just as succinct and saying more about the meaning of the code. </p>\n\n<p>However, lambda expressions are not the sole province of Linq and outside of this context the more general form \"goes to\" should be used.</p>\n\n<hr>\n\n<h2>But why \"goes to\" ?</h2>\n\n<p>Because \"populates the stack frame of the following code\" is far too long to keep saying it. I suppose you could say \"is/are passed to\".</p>\n\n<p>A crucial difference between explicitly passed parameters and captured variables (if I remember correctly - correct me if I'm wrong) is that the former are passed by reference and the latter by value.</p>\n" }, { "answer_id": 274247, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>I haven't thought it about much, but I just succintly say \"to\". It's short and concise, and implies that the variable is passed <em>to</em> the expression. I suppose it could be confused with the numeral 2 (\"two\"), but I tend to pronounce \"to\" more like \"ta\" when speaking. Nobody (who knows lambdas, at least) has ever told me they thought it ambiguous...</p>\n\n<pre><code>// \"Func f equals x to x times two\"\nFunc f = x=&gt; x * 2;\n\n// \"Func test equals c to c dot City equals London\"\nFunc test = c =&gt; c.City == \"London\"\n</code></pre>\n" }, { "answer_id": 274635, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 6, "selected": false, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/bb397687.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>All lambda expressions use the lambda\n operator =>, which is read as \"goes\n to\".</p>\n</blockquote>\n" }, { "answer_id": 275095, "author": "orcmid", "author_id": 33810, "author_profile": "https://Stackoverflow.com/users/33810", "pm_score": 2, "selected": false, "text": "<p>My short answer: \"c 'lambda-of' e\". Although I am clinging to \"'lambda' c 'function' e\", I think lambda-of is the ecumenical compromise. Analysis follows.</p>\n\n<p>This is a great question if only for the bizarre answers. Most of the translations have other meanings than for lambda expressions, leading to exotic interpretations. As an old lambda-expression hacker, I just ignore the .NET notation and rewrite it as lambda in my head while wishing they had done almost anything else for this.</p>\n\n<hr>\n\n<p>For narrating code over the phone, you want someone to be able to write the code down in sequence. That is a problem, of course, but lambda-arrow or something is probably the best you can get, or maybe lambda-in, but lambda-of is the most accurate. </p>\n\n<p>The problem is the infix usage and how to name the whole thing and the role of the left and right parts with something that works when spoken in the infix place.</p>\n\n<p>This may be an over-constrained problem!</p>\n\n<hr>\n\n<p>I wouldn't use \"such that\" because that implies that the right hand side is a predicate that the left-hand side should satisfy. That is very different from talking about a right-hand side from which the left-hand side has been abstracted as a functional parameter. (The MSDN statement about \"All lambda expressions\" is simply offensive as well as inaccurate.)</p>\n\n<p>Something rankles about \"goes to\" although it may be as close as we can get. \"Goes to\" implies a transformation, but there is not exactly some variable c that goes to an expression in c. The abstraction to a function is a little elusive. I could get accustomed to this, but I still yearn for something that emphasizes the abstraction of the variable.</p>\n\n<p>Since the left-hand side is always a simple identifier in the cases used so far [but wait for extensions that may confuse this later on], I think for \"c => expression\" I would read \"c 'lambda-function' expression\"' or even \"c 'arg' 'function' expression\". In the last case, I could then say things like \"b 'arg' c 'arg' 'function' expression\". </p>\n\n<p>It might be better to make it even more clear that a lambda-expression is being introduced and say something like \"'arg' b 'arg' c 'function' expression\". </p>\n\n<p>Figuring out how to translate all of this to other languages is an exercise for the student [;&lt;).</p>\n\n<p>I still worry about \"(b, c) => expression\" and other variants that may come into being if they haven't already. Perhaps \"'args' b, c 'function' expression\".</p>\n\n<hr>\n\n<p>After all of this musing, I notice that I am coming around to translating \"c => e\" as \"'lambda' c 'function' e\" and noticing that the mapping to exact form is to be understood by context: λc(e), c => e, f <strong>where</strong> f(c) = e, etc.</p>\n\n<p>I expect that the \"goes-to\" explanation will prevail simply because this is where a dominant majority is going to see lambda expressions for the first time. That's a pity. A good compromise might be \"c '<strong>lambda-of</strong>' e\"</p>\n" }, { "answer_id": 393581, "author": "Aidos", "author_id": 12040, "author_profile": "https://Stackoverflow.com/users/12040", "pm_score": 4, "selected": false, "text": "<p>I've always called it the \"wang operator\" :-)</p>\n\n<p>\"p wang age of p greater than 16\"</p>\n" }, { "answer_id": 2128880, "author": "Max Strini", "author_id": 19393, "author_profile": "https://Stackoverflow.com/users/19393", "pm_score": 3, "selected": false, "text": "<p>How about \"maps to\"? It's both succinct and arguably more technically accurate (i.e. no suggestion of a state change as with \"goes to\" or \"becomes\", no conflation of a set with its characteristic function as with \"such that\" or \"for which\") than the other alternatives. Though if there's already a standard as the MSDN page appears to imply, maybe you should just go with that (at least for C# code).</p>\n" }, { "answer_id": 2128938, "author": "Will Vousden", "author_id": 58635, "author_profile": "https://Stackoverflow.com/users/58635", "pm_score": 2, "selected": false, "text": "<p>\"Maps to\" is my preferred pronunciation. Mathematically speaking, a function \"maps\" its arguments to its return value (one might even call the function a \"mapping\"), so it makes sense to me to use this terminology in programming, particularly as functional programming (especially the lambda calculus) is very close to mathematics. It's also more neutral than \"becomes\", \"goes to\", etc., since it doesn't suggest change of state, as contextfree mentioned.</p>\n" }, { "answer_id": 16270890, "author": "Jonesopolis", "author_id": 1786428, "author_profile": "https://Stackoverflow.com/users/1786428", "pm_score": 2, "selected": false, "text": "<p>If you imagine a lambda expression as the anonymous method that it is, \"goes to\" makes decent sense enough. </p>\n\n<pre><code>(n =&gt; n == String.Empty)\n</code></pre>\n\n<p>n \"goes to\" the expression n == String.Empty.</p>\n\n<p>It goes to the anonymous method, so you don't have to go to the method in the code!</p>\n\n<p>Sorry for that.</p>\n\n<p>Honestly, I don't like to use \"goes to\" in my head, but I saw other people saying it seemed weird, and I thought I'd clear that up.</p>\n" }, { "answer_id": 19103429, "author": "Pharylon", "author_id": 2045257, "author_profile": "https://Stackoverflow.com/users/2045257", "pm_score": 1, "selected": false, "text": "<p>In Ruby, this same sybmol is called \"hashrocket,\" and I've heard C# programmers use that term too (even though doing so is wrong).</p>\n" }, { "answer_id": 30714993, "author": "Allan", "author_id": 4987218, "author_profile": "https://Stackoverflow.com/users/4987218", "pm_score": 0, "selected": false, "text": "<p>My two cents:</p>\n\n<pre><code>s =&gt; s.Age &gt; 12 &amp;&amp; s.Age &lt; 20\n</code></pre>\n\n<p>\"Lambda Expression with parameter s is { <code>return s.Age &gt; 12 &amp;&amp; s.Age &lt; 20;</code> }\"</p>\n\n<p>I like this because it reminds me of where lamdba expression comes from</p>\n\n<pre><code>delegate(Student s) { return s.Age &gt; 12 &amp;&amp; s.Age &lt; 20; };\n</code></pre>\n\n<p>=> is just a shortcut so you don't have to use the delegate keyword and include the type info since it can be inferred by the compiler.</p>\n" }, { "answer_id": 60467168, "author": "Arthur", "author_id": 12983089, "author_profile": "https://Stackoverflow.com/users/12983089", "pm_score": 0, "selected": false, "text": "<p>My term for => as applied to the examples shown result</p>\n\n<pre><code>'result = s =&gt; s.Age &gt; 12 &amp;&amp; s.Age &lt; 20'\n</code></pre>\n\n<p>s where s.Age is greater than 12 and s.Age less than 20</p>\n\n<pre><code>'result = x =&gt; x * 2'\n</code></pre>\n\n<p>x where x is multiplied by 2</p>\n\n<pre><code>'result = c =&gt; c.City == \"London\"'\n</code></pre>\n\n<p>c where c.city is equivalent to \"London\"</p>\n\n<pre><code>'result = n =&gt; n == String.Empty'\n</code></pre>\n\n<p>n where n is an empty string</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/274022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29411/" ]
I very rarely meet any other programmers! My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense. So how do I say or read "=>" as in:- ``` IEnumerable<Person> Adults = people.Where(p => p.Age > 16) ``` Or is there even an agreed way of saying it?
I usually say 'such that' when reading that operator. In your example, p => p.Age > 16 reads as "P, such that p.Age is greater than 16." In fact, I asked this very question on the official linq pre-release forums, and Anders Hejlsberg responded by saying > > I usually read the => operator as "becomes" or "for which". For example, > > Func f = x => x \* 2; > > Func test = c => c.City == "London"; > > reads as "x becomes x \* 2" and "c for which c.City equals London" > > > As far as 'goes to' - that's never made sense to me. 'p' isn't going anywhere. In the case of reading code to someone, say, over the phone, then as long as they're a fellow C# programmer, I'd just use the word 'lambda' - that is, "p lambda p dot age greater-than sixteen." In comments Steve Jessop mentioned 'maps to' in the case of transformations - so taking Anders' example: ``` x => x * 2; ``` would read > > x maps to x times 2. > > > That does seem much closer to the actual intention of the code than 'becomes' for this case.
274,024
<p>I'm increasingly becoming aware that there must be major differences in the ways that regular expressions will be interpreted by browsers.<br /> As an example, a co-worker had written this regular expression, to validate that a file being uploaded would have a PDF extension:</p> <pre><code>^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf)$ </code></pre> <p>This works in Internet Explorer, and in Google Chrome, but does NOT work in Firefox. The test always fails, even for an actual PDF. So I decided that the extra stuff was irrelevant and simplified it to:</p> <pre><code>^.+\.pdf$ </code></pre> <p>and now it works fine in Firefox, as well as continuing to work in IE and Chrome.<br /> Is this a quirk specific to asp:FileUpload and RegularExpressionValidator controls in ASP.NET, or is it simply due to different browsers supporting regex in different ways? Either way, what are some of the latter that you've encountered?</p>
[ { "answer_id": 274052, "author": "Mauricio", "author_id": 33913, "author_profile": "https://Stackoverflow.com/users/33913", "pm_score": 1, "selected": false, "text": "<p>If you're using javascript, not enclosing the regex with slashes causes error in Firefox.</p>\n\n<p>Try doing <code>var regex = /^(([a-zA-Z]:)|(\\\\{2}\\w+)\\$?)(\\\\(\\w[\\w].*))(.pdf)$/;</code></p>\n" }, { "answer_id": 274093, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 3, "selected": true, "text": "<p>As far as I know firefox doesn't let you have the full path of an upload. Interpretation of regular expressions seems irrelevant in this case. I have yet to see any difference between modern browsers in regular expression execution.</p>\n" }, { "answer_id": 274103, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 0, "selected": false, "text": "<p>I have not noticed a difference between browsers in regards to the pattern syntax. However, I have noticed a difference between C# and Javascript as C#'s implementation allows back references and Javascript's implementation does not.</p>\n" }, { "answer_id": 274193, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "<p>Regarding the actual question: The original regex requires the value to start with a drive letter or UNC device name. It's quite possible that Firefox simply doesn't include that with the filename. Note also that, if you have any intention of being cross-platform, that regex would fail on any non-Windows system, regardless of browser, as they don't use drive letters or UNC paths. Your simplified regex (\"accept anything, so long as it ends with .pdf\") is about as good of a filename check as you're going to get.</p>\n\n<p><em>However</em>, Jonathan's comment to the original question cannot be overemphasized. Never, ever, <em>ever</em> trust the filename as an adequate means of determining its contents. Or the MIME type, for that matter. The client software talking to your web server (which might not even be a browser) can lie to you about anything and you'll never know unless you verify it. In this case, that means feeding the received file into some code that understands the PDF format and having that code tell you whether it's a valid PDF or not. Checking the filename may help to prevent people from trying to submit obviously incorrect files, but it is not a sufficient test of the files that are received.</p>\n\n<p>(I realize that you may know about the need for additional validation, but the next person who has a similar situation and finds your question may not.)</p>\n" }, { "answer_id": 274209, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 1, "selected": false, "text": "<p>As Dave mentioned, Firefox does not give the path, only the file name. Also as he mentioned, it doesn't account for differences between operating systems. I think the best check you could do would be to check if the file name ends with PDF. Also, this doesn't ensure it's a valid PDF, just that the file name ends with PDF. Depending on your needs, you may want to verify that it's actually a PDF by checking the content.</p>\n" }, { "answer_id": 274880, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>I believe JavaScript REs are defined by the ECMA standard, and I doubt there are many differences between JS interpreters. I haven't found any, in my programs, or seen mentioned in an article.</p>\n\n<p>Your message is actually a bit confusing, since you throw ASP stuff in there. I don't see how you conclude it is the browser's fault when you talk about server-side technology or generated code. Actually, we don't even know if you are talking about JS on the browser, validation of upload field (you can no longer do it, at least in a simple way, with FF3) or on the server side (neither FF nor Opera nor Safari upload the full path of the uploaded file. I am surprised to learn that Chrome does like IE...).</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/274024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
I'm increasingly becoming aware that there must be major differences in the ways that regular expressions will be interpreted by browsers. As an example, a co-worker had written this regular expression, to validate that a file being uploaded would have a PDF extension: ``` ^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf)$ ``` This works in Internet Explorer, and in Google Chrome, but does NOT work in Firefox. The test always fails, even for an actual PDF. So I decided that the extra stuff was irrelevant and simplified it to: ``` ^.+\.pdf$ ``` and now it works fine in Firefox, as well as continuing to work in IE and Chrome. Is this a quirk specific to asp:FileUpload and RegularExpressionValidator controls in ASP.NET, or is it simply due to different browsers supporting regex in different ways? Either way, what are some of the latter that you've encountered?
As far as I know firefox doesn't let you have the full path of an upload. Interpretation of regular expressions seems irrelevant in this case. I have yet to see any difference between modern browsers in regular expression execution.
274,039
<p>I would like to do this:</p> <pre><code>[RequiresAuthentication(CompanyType.Client)] public class FooController { public ActionResult OnlyClientUsersCanDoThis() public ActionResult OnlyClientUsersCanDoThisToo() [RequiresAuthentication] public ActionResult AnyTypeOfUserCanDoThis() </code></pre> <p>You can see why this won't work. On the third action the controller-level filter will block non-clients. I would like instead to "resolve" conflicting filters. I would like for the more specific filter (action filter) to always win. This seems natural and intuitive.</p> <p>Once upon a time filterContext exposed MethodInfo for the executing action. That would have made this pretty easy. I considered doing some reflection myself using route info. That won't work because the action it might be overloaded and I cannot tell which one is the current executing one.</p> <p>The alternative is to scope filters either at the controller level or the action level, but no mix, which will create a lot of extra attribute noise.</p>
[ { "answer_id": 274423, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": false, "text": "<p>We're looking into a way to expose other filters, but no promises.</p>\n\n<p>Applying a filter to the controller isn't really a \"scope\", it's merely a short-hand for applying it to all filters. Unfortunately, that means you can't include all but one action. One simple way you could do this is to put that one method in another controller. You could even add a custom route just for that one case so the URL doesn't have to change.</p>\n" }, { "answer_id": 2060147, "author": "Thomas", "author_id": 250207, "author_profile": "https://Stackoverflow.com/users/250207", "pm_score": 0, "selected": false, "text": "<p>you can put authorisation logic into the OnActionExecuting(..) method of the Controller, i.e.</p>\n\n<pre><code>public override void OnActionExecuting(ActionExecutingContext filterContext) {\n base.OnActionExecuting(filterContext);\n new RequiresAuthentication()\n { /* initialization */ }.OnActionExecuting(filterContext);\n}\n</code></pre>\n\n<p>Hope this helps,</p>\n\n<p>Thomas</p>\n" }, { "answer_id": 7937692, "author": "saintedlama", "author_id": 263251, "author_profile": "https://Stackoverflow.com/users/263251", "pm_score": 0, "selected": false, "text": "<p>You could change filter order with the general auth filter on the controller and the specific auth filters on the actions. Somehow like this:</p>\n\n<pre><code>[RequiresAuthentication]\npublic class FooController\n{\n [RequiresAuthentication(CompanyType.Client)]\n public ActionResult OnlyClientUsersCanDoThis()\n\n [RequiresAuthentication(CompanyType.Client)]\n public ActionResult OnlyClientUsersCanDoThisToo()\n\n public ActionResult AnyTypeOfUserCanDoThis()\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/274039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29493/" ]
I would like to do this: ``` [RequiresAuthentication(CompanyType.Client)] public class FooController { public ActionResult OnlyClientUsersCanDoThis() public ActionResult OnlyClientUsersCanDoThisToo() [RequiresAuthentication] public ActionResult AnyTypeOfUserCanDoThis() ``` You can see why this won't work. On the third action the controller-level filter will block non-clients. I would like instead to "resolve" conflicting filters. I would like for the more specific filter (action filter) to always win. This seems natural and intuitive. Once upon a time filterContext exposed MethodInfo for the executing action. That would have made this pretty easy. I considered doing some reflection myself using route info. That won't work because the action it might be overloaded and I cannot tell which one is the current executing one. The alternative is to scope filters either at the controller level or the action level, but no mix, which will create a lot of extra attribute noise.
We're looking into a way to expose other filters, but no promises. Applying a filter to the controller isn't really a "scope", it's merely a short-hand for applying it to all filters. Unfortunately, that means you can't include all but one action. One simple way you could do this is to put that one method in another controller. You could even add a custom route just for that one case so the URL doesn't have to change.
274,051
<p>Is keeping JMS connections / sessions / consumer always open a bad practice?</p> <p>Code draft example:</p> <pre><code>// app startup code ConnectionFactory cf = (ConnectionFactory)jndiContext.lookup(CF_JNDI_NAME); Connection connection = cf.createConnection(user,pass); Session session = connection.createSession(true,Session.TRANSACTIONAL); MessageConsumer consumer = session.createConsumer(new Queue(queueName)); consumer.setMessageListener(new MyListener()); connection.start(); connection.setExceptionListener(new MyExceptionHandler()); // handle connection error // ... Message are processed on MyListener asynchronously ... // app shutdown code consumer.close(); session.close(); connection.close(); </code></pre> <p>Any suggestions to improve this pattern of JMS usage? </p>
[ { "answer_id": 274204, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 4, "selected": true, "text": "<p>That is a very common and acceptable practice when dealing with long lived connections. For many JMS servers it is in fact preferable to creating a new connection each time it is needed. </p>\n" }, { "answer_id": 277594, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 3, "selected": false, "text": "<p>Agreed. Here are some <a href=\"http://activemq.apache.org/how-do-i-use-jms-efficiently.html\" rel=\"noreferrer\">good tips on how to use JMS efficiently</a> which includes keeping around connections/sessions/producers/consumers.</p>\n\n<p>You might also want to check the <a href=\"http://activemq.apache.org/should-i-use-transactions.html\" rel=\"noreferrer\">recommendation on using transactions</a> too if you are interested in maximising performance.</p>\n" }, { "answer_id": 279289, "author": "John M", "author_id": 20734, "author_profile": "https://Stackoverflow.com/users/20734", "pm_score": 2, "selected": false, "text": "<p>In our app, we will have connections/sessions/consumers/producers open for months at a time. We've had to work with our vendor (BEA) to make that work reliably. But any troubles with that is a bug the vendor needs to fix.</p>\n" }, { "answer_id": 10809716, "author": "Shashi", "author_id": 933250, "author_profile": "https://Stackoverflow.com/users/933250", "pm_score": 3, "selected": false, "text": "<p>The choice of keeping connection/session/producer/consumer open for long or not should be based on the frequency at which producer/consumer sends/receives messages. </p>\n\n<p>If a producer sends or a consumer receives messages frequently then the connections/sessions/producer/consumer should be kept open. On the other hand if messages send/receive is infrequent then it is not good keeping these JMS objects open will consume system resources like sockets. </p>\n" }, { "answer_id": 40217347, "author": "eparvan", "author_id": 5202500, "author_profile": "https://Stackoverflow.com/users/5202500", "pm_score": 2, "selected": false, "text": "<p>FYI, there is no need to close the sessions, producers, and consumers of a closed connection( <a href=\"http://grepcode.com/file/repo1.maven.org/maven2/org.codehaus.fabric3.api/javax-jms/1.1.1/javax/jms/Connection.java?av=f#276\" rel=\"nofollow\">javax.jms.Connection</a> ).\nThe code below should be enough to release the resources:</p>\n\n<pre><code>try { \n this.connection.close();\n } catch (JMSException e) {\n //\n }\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/274051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35323/" ]
Is keeping JMS connections / sessions / consumer always open a bad practice? Code draft example: ``` // app startup code ConnectionFactory cf = (ConnectionFactory)jndiContext.lookup(CF_JNDI_NAME); Connection connection = cf.createConnection(user,pass); Session session = connection.createSession(true,Session.TRANSACTIONAL); MessageConsumer consumer = session.createConsumer(new Queue(queueName)); consumer.setMessageListener(new MyListener()); connection.start(); connection.setExceptionListener(new MyExceptionHandler()); // handle connection error // ... Message are processed on MyListener asynchronously ... // app shutdown code consumer.close(); session.close(); connection.close(); ``` Any suggestions to improve this pattern of JMS usage?
That is a very common and acceptable practice when dealing with long lived connections. For many JMS servers it is in fact preferable to creating a new connection each time it is needed.
274,056
<p>I'm setting up a User Control driven by a XML configuration. It is easier to explain by example. Take a look at the following configuration snippet:</p> <pre><code>&lt;node&gt; &lt;text lbl="Text:"/&gt; &lt;checkbox lbl="Check me:" checked="true"/&gt; &lt;/node&gt; </code></pre> <p>What I'm trying to achieve to translate that snippet into a single text box and a checkbox control. Of course, had the snippet contained more nodes more controls would be generated automatically.</p> <p>Give the iterative nature of the task, I have chosen to use Repeater. Within it I have placed two (well more, see bellow) Controls, one CheckBox and one Editbox. In order to choose which control get activate, I used an inline switch command, checking the name of the current configuration node.</p> <p>Sadly, that doesn't work. The problem lies in the fact that the switch is being run during rendering time, long after data binding had happened. That alone would not be a problem, was not for the fact that a configuration node might offer the needed info to data bind. Consider what would happen if the check box control will try to bind to the text node in the snippet above, desperately looking for it's "checked" attribute.</p> <p>Any ideas how to make this possible?</p> <p>Thanks, Boaz</p> <p>Here is my current code:</p> <p>Here is my code (which runs on a more complex syntax than the one above):</p> <pre><code>&lt;asp:Repeater ID="settingRepeater" runat="server"&gt; &lt;ItemTemplate&gt; &lt;% switch (((XmlNode)Page.GetDataItem()).LocalName) { case "text": %&gt; &lt;asp:Label ID="settingsLabel" CssClass="editlabel" Text='&lt;%# XPath("@lbl") %&gt;' runat="server" /&gt; &lt;asp:TextBox ID="settingsLabelText" Text='&lt;%# SettingsNode.SelectSingleNode(XPath("@xpath").ToString()).InnerText %&gt;' runat="server" AutoPostBack="true" Columns='&lt;%# XmlUtils.OptReadInt((XmlNode)Page.GetDataItem(),"@width",20) %&gt;' /&gt; &lt;% break; case "checkbox": %&gt; &lt;asp:CheckBox ID="settingsCheckBox" Text='&lt;%# XPath("@lbl") %&gt;' runat="server" Checked='&lt;%# ((XmlElement)SettingsNode.SelectSingleNode(XPath("@xpath").ToString())).HasAttribute(XPath("@att").ToString()) %&gt;' /&gt; &lt;% break; } %&gt; &amp;nbsp;&amp;nbsp; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre>
[ { "answer_id": 274249, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<p>You need something that looks more like this:</p>\n\n<pre><code>&lt;ItemTemplate&gt;\n &lt;%# GetContent(Page.GetDataItem()) %&gt;\n&lt;/ItemTemplate&gt;\n</code></pre>\n\n<p>And then have all your controls generated in the code-behind. </p>\n" }, { "answer_id": 276591, "author": "Boaz", "author_id": 2892, "author_profile": "https://Stackoverflow.com/users/2892", "pm_score": 3, "selected": true, "text": "<p>One weekend later, here is what I came with as a solution. My main goal was to find something that will both work and allow you to keep specifying the exact content of the Item Template in markup. Doing things from code would work but can still be cumbersome.</p>\n\n<p>The code should be straight forward to follow, but the gist of the matter lies in two parts. </p>\n\n<p>The first is the usage of the Repeater item created event to filter out unwanted parts of the template. </p>\n\n<p>The second is to store decisions made in ViewState in order to recreate the page during post back. The later is crucial as you'll notice that I used the Item.DataItem . During post backs, control recreation happens much earlier in the page life cycle. When the ItemCreate fires, the DataItem is null.</p>\n\n<p>Here is my solution:</p>\n\n<p><strong>Control markup</strong></p>\n\n<pre><code> &lt;asp:Repeater ID=\"settingRepeater\" runat=\"server\" \n onitemcreated=\"settingRepeater_ItemCreated\" \n &gt;\n &lt;ItemTemplate&gt;\n &lt;asp:PlaceHolder ID=\"text\" runat=\"server\"&gt;\n &lt;asp:Label ID=\"settingsLabel\" CssClass=\"editlabel\" Text='&lt;%# XPath(\"@lbl\") %&gt;' runat=\"server\" /&gt;\n &lt;asp:TextBox ID=\"settingsLabelText\" runat=\"server\"\n Text='&lt;%# SettingsNode.SelectSingleNode(XPath(\"@xpath\").ToString()).InnerText %&gt;'\n Columns='&lt;%# XmlUtils.OptReadInt((XmlNode)Page.GetDataItem(),\"@width\",20) %&gt;'\n\n /&gt;\n\n &lt;/asp:PlaceHolder&gt;\n &lt;asp:PlaceHolder ID=\"att_adder\" runat=\"server\"&gt;\n &lt;asp:CheckBox ID=\"settingsAttAdder\" Text='&lt;%# XPath(\"@lbl\") %&gt;' runat=\"server\"\n Checked='&lt;%# ((XmlElement)SettingsNode.SelectSingleNode(XPath(\"@xpath\").ToString())).HasAttribute(XPath(\"@att\").ToString()) %&gt;'\n /&gt;\n &lt;/asp:PlaceHolder&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:Repeater&gt;\n</code></pre>\n\n<p><em>Note:</em> for extra ease I added the PlaceHolder control to group things and make the decision of which controls to remove easier.</p>\n\n<p><strong>Code behind</strong></p>\n\n<p>The code bellow is built on the notion that every repeater item is of a type. The type is extracted from the configuration xml. In my specific scenario, I could make that type to a single control by means of ID. This could be easily modified if needed.</p>\n\n<pre><code> protected List&lt;string&gt; repeaterItemTypes\n {\n get\n {\n List&lt;string&gt; ret = (List&lt;string&gt;)ViewState[\"repeaterItemTypes\"];\n if (ret == null)\n {\n ret = new List&lt;string&gt;();\n ViewState[\"repeaterItemTypes\"] = ret;\n }\n return ret;\n }\n }\n\n protected void settingRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)\n {\n string type;\n if (e.Item.DataItem != null)\n {\n // data binding mode..\n type = ((XmlNode)e.Item.DataItem).LocalName;\n int i = e.Item.ItemIndex;\n if (i == repeaterItemTypes.Count)\n repeaterItemTypes.Add(type);\n else\n repeaterItemTypes.Insert(e.Item.ItemIndex, type);\n }\n else\n {\n // restoring from ViewState\n type = repeaterItemTypes[e.Item.ItemIndex];\n }\n\n for (int i = e.Item.Controls.Count - 1; i &gt;= 0; i--)\n {\n if (e.Item.Controls[i].ID != type) e.Item.Controls.RemoveAt(i);\n }\n }\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2892/" ]
I'm setting up a User Control driven by a XML configuration. It is easier to explain by example. Take a look at the following configuration snippet: ``` <node> <text lbl="Text:"/> <checkbox lbl="Check me:" checked="true"/> </node> ``` What I'm trying to achieve to translate that snippet into a single text box and a checkbox control. Of course, had the snippet contained more nodes more controls would be generated automatically. Give the iterative nature of the task, I have chosen to use Repeater. Within it I have placed two (well more, see bellow) Controls, one CheckBox and one Editbox. In order to choose which control get activate, I used an inline switch command, checking the name of the current configuration node. Sadly, that doesn't work. The problem lies in the fact that the switch is being run during rendering time, long after data binding had happened. That alone would not be a problem, was not for the fact that a configuration node might offer the needed info to data bind. Consider what would happen if the check box control will try to bind to the text node in the snippet above, desperately looking for it's "checked" attribute. Any ideas how to make this possible? Thanks, Boaz Here is my current code: Here is my code (which runs on a more complex syntax than the one above): ``` <asp:Repeater ID="settingRepeater" runat="server"> <ItemTemplate> <% switch (((XmlNode)Page.GetDataItem()).LocalName) { case "text": %> <asp:Label ID="settingsLabel" CssClass="editlabel" Text='<%# XPath("@lbl") %>' runat="server" /> <asp:TextBox ID="settingsLabelText" Text='<%# SettingsNode.SelectSingleNode(XPath("@xpath").ToString()).InnerText %>' runat="server" AutoPostBack="true" Columns='<%# XmlUtils.OptReadInt((XmlNode)Page.GetDataItem(),"@width",20) %>' /> <% break; case "checkbox": %> <asp:CheckBox ID="settingsCheckBox" Text='<%# XPath("@lbl") %>' runat="server" Checked='<%# ((XmlElement)SettingsNode.SelectSingleNode(XPath("@xpath").ToString())).HasAttribute(XPath("@att").ToString()) %>' /> <% break; } %> &nbsp;&nbsp; </ItemTemplate> </asp:Repeater> ```
One weekend later, here is what I came with as a solution. My main goal was to find something that will both work and allow you to keep specifying the exact content of the Item Template in markup. Doing things from code would work but can still be cumbersome. The code should be straight forward to follow, but the gist of the matter lies in two parts. The first is the usage of the Repeater item created event to filter out unwanted parts of the template. The second is to store decisions made in ViewState in order to recreate the page during post back. The later is crucial as you'll notice that I used the Item.DataItem . During post backs, control recreation happens much earlier in the page life cycle. When the ItemCreate fires, the DataItem is null. Here is my solution: **Control markup** ``` <asp:Repeater ID="settingRepeater" runat="server" onitemcreated="settingRepeater_ItemCreated" > <ItemTemplate> <asp:PlaceHolder ID="text" runat="server"> <asp:Label ID="settingsLabel" CssClass="editlabel" Text='<%# XPath("@lbl") %>' runat="server" /> <asp:TextBox ID="settingsLabelText" runat="server" Text='<%# SettingsNode.SelectSingleNode(XPath("@xpath").ToString()).InnerText %>' Columns='<%# XmlUtils.OptReadInt((XmlNode)Page.GetDataItem(),"@width",20) %>' /> </asp:PlaceHolder> <asp:PlaceHolder ID="att_adder" runat="server"> <asp:CheckBox ID="settingsAttAdder" Text='<%# XPath("@lbl") %>' runat="server" Checked='<%# ((XmlElement)SettingsNode.SelectSingleNode(XPath("@xpath").ToString())).HasAttribute(XPath("@att").ToString()) %>' /> </asp:PlaceHolder> </ItemTemplate> </asp:Repeater> ``` *Note:* for extra ease I added the PlaceHolder control to group things and make the decision of which controls to remove easier. **Code behind** The code bellow is built on the notion that every repeater item is of a type. The type is extracted from the configuration xml. In my specific scenario, I could make that type to a single control by means of ID. This could be easily modified if needed. ``` protected List<string> repeaterItemTypes { get { List<string> ret = (List<string>)ViewState["repeaterItemTypes"]; if (ret == null) { ret = new List<string>(); ViewState["repeaterItemTypes"] = ret; } return ret; } } protected void settingRepeater_ItemCreated(object sender, RepeaterItemEventArgs e) { string type; if (e.Item.DataItem != null) { // data binding mode.. type = ((XmlNode)e.Item.DataItem).LocalName; int i = e.Item.ItemIndex; if (i == repeaterItemTypes.Count) repeaterItemTypes.Add(type); else repeaterItemTypes.Insert(e.Item.ItemIndex, type); } else { // restoring from ViewState type = repeaterItemTypes[e.Item.ItemIndex]; } for (int i = e.Item.Controls.Count - 1; i >= 0; i--) { if (e.Item.Controls[i].ID != type) e.Item.Controls.RemoveAt(i); } } ```
274,157
<p>Wordpress provides a function called "the_permalink()" that returns, you guessed it!, the permalink to a given post while in a loop of posts.</p> <p>I am trying to URL encode that permalink and when I execute this code:</p> <pre><code>&lt;?php print(the_permalink()); $permalink = the_permalink(); print($permalink); print(urlencode(the_permalink())); print(urlencode($permalink)); $url = 'http://wpmu.local/graphjam/2008/11/06/test4/'; print($url); print(urlencode($url)); ?&gt; </code></pre> <p>it produces these results in HTML:</p> <pre><code>http://wpmu.local/graphjam/2008/11/06/test4/ http://wpmu.local/graphjam/2008/11/06/test4/ http://wpmu.local/graphjam/2008/11/06/test4/ http://wpmu.local/graphjam/2008/11/06/test4/ http%3A%2F%2Fwpmu.local%2Fgraphjam%2F2008%2F11%2F06%2Ftest4%2F </code></pre> <p>I would expect lines 2, 3 and 5 of the output to be URL encoded, but only line 5 is so. Thoughts?</p>
[ { "answer_id": 274163, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 4, "selected": false, "text": "<p>According to the docs, <a href=\"http://codex.wordpress.org/Template_Tags/the_permalink\" rel=\"noreferrer\"><code>the_permalink</code></a> prints the permalink vs returns it. So, <code>urlencode</code> isn't getting anything to encode.</p>\n\n<p>Try <a href=\"http://codex.wordpress.org/Template_Tags/get_permalink\" rel=\"noreferrer\"><code>get_permalink</code></a>.</p>\n\n<hr>\n\n<p>[<strong>EDIT</strong>]</p>\n\n<p>A little late for an edit, but I didn't realize the print counts were such an issue.</p>\n\n<p>Here's where they're all coming from:</p>\n\n<pre><code>&lt;?php\nprint(the_permalink()); // prints (1)\n$permalink = the_permalink(); // prints (2)\nprint($permalink); // nothing\nprint(urlencode(the_permalink())); // prints (3)\nprint(urlencode($permalink)); // nothing\n$url = 'http://wpmu.local/graphjam/2008/11/06/test4/'; \nprint($url); // prints (4)\nprint(urlencode($url)); // prints (5)\n?&gt;\n</code></pre>\n" }, { "answer_id": 274304, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 3, "selected": false, "text": "<p>@Jonathan has the reason why, and the way you should deal with it in WordPress (ie. use the right function for the job).</p>\n\n<p>Here is how to fix it when there isn't a function that returns a string:</p>\n\n<pre><code>ob_start();\nthe_permalink();\n$permalink = ob_get_clean();\nprint(urlencode($permalink));\n</code></pre>\n" }, { "answer_id": 283439, "author": "Ozh", "author_id": 36850, "author_profile": "https://Stackoverflow.com/users/36850", "pm_score": 3, "selected": false, "text": "<p><code>the_permalink()</code> <strong>echoes</strong> the permalink</p>\n\n<p><code>get_the_permalink()</code> <strong>returns</strong> the permalink so it can be assigned to a variable.</p>\n\n<p>(same goes with most functions in WordPress: the_something() has a get_the_something() to return value instead of echoing it)</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33754/" ]
Wordpress provides a function called "the\_permalink()" that returns, you guessed it!, the permalink to a given post while in a loop of posts. I am trying to URL encode that permalink and when I execute this code: ``` <?php print(the_permalink()); $permalink = the_permalink(); print($permalink); print(urlencode(the_permalink())); print(urlencode($permalink)); $url = 'http://wpmu.local/graphjam/2008/11/06/test4/'; print($url); print(urlencode($url)); ?> ``` it produces these results in HTML: ``` http://wpmu.local/graphjam/2008/11/06/test4/ http://wpmu.local/graphjam/2008/11/06/test4/ http://wpmu.local/graphjam/2008/11/06/test4/ http://wpmu.local/graphjam/2008/11/06/test4/ http%3A%2F%2Fwpmu.local%2Fgraphjam%2F2008%2F11%2F06%2Ftest4%2F ``` I would expect lines 2, 3 and 5 of the output to be URL encoded, but only line 5 is so. Thoughts?
According to the docs, [`the_permalink`](http://codex.wordpress.org/Template_Tags/the_permalink) prints the permalink vs returns it. So, `urlencode` isn't getting anything to encode. Try [`get_permalink`](http://codex.wordpress.org/Template_Tags/get_permalink). --- [**EDIT**] A little late for an edit, but I didn't realize the print counts were such an issue. Here's where they're all coming from: ``` <?php print(the_permalink()); // prints (1) $permalink = the_permalink(); // prints (2) print($permalink); // nothing print(urlencode(the_permalink())); // prints (3) print(urlencode($permalink)); // nothing $url = 'http://wpmu.local/graphjam/2008/11/06/test4/'; print($url); // prints (4) print(urlencode($url)); // prints (5) ?> ```
274,158
<p>I have a very painful library which, at the moment, is accepting a C# string as a way to get arrays of data; apparently, this makes marshalling for pinvokes easier. </p> <p>So how do I make a ushort array into a string by bytes? I've tried:</p> <pre><code>int i; String theOutData = ""; ushort[] theImageData = inImageData.DataArray; //this is as slow like molasses in January for (i = 0; i &lt; theImageData.Length; i++) { byte[] theBytes = System.BitConverter.GetBytes(theImageData[i]); theOutData += String.Format("{0:d}{1:d}", theBytes[0], theBytes[1]); } </code></pre> <p>I can do it this way, but it doesn't finish in anything remotely close to a sane amount of time.</p> <p>What should I do here? Go unsafe? Go through some kind of IntPtr intermediate?</p> <p>If it were a char* in C++, this would be significantly easier...</p> <p>edit: the function call is</p> <pre><code>DataElement.SetByteValue(string inArray, VL Length); </code></pre> <p>where VL is a 'Value Length', a DICOM type, and the function itself is generated as a wrapper to a C++ library by SWIG. It seems that the representation chosen is string, because that can cross managed/unmanaged boundaries relatively easily, but throughout the C++ code in the project (this is GDCM), the char* is simply used as a byte buffer. So, when you want to set your image buffer pointer, in C++ it's fairly simple, but in C#, I'm stuck with this weird problem.</p> <p>This is hackeration, and I know that probably the best thing is to make the SWIG library work right. I really don't know how to do that, and would rather a quick workaround on the C# side, if such exists.</p>
[ { "answer_id": 274205, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 1, "selected": false, "text": "<p>One thing you can do is switch from using a string to a stringBuilder it will help performance tremendously.</p>\n\n<p>If you are willing to use unsafe code you can use pointers and implement the your c# code just like your c++. Or you could write a small c++\\cli dll that implements this functionality.</p>\n" }, { "answer_id": 274207, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": true, "text": "<p>P/Invoke can actually handle what you're after most of the time using StringBuilder to create writable buffers, for example see <a href=\"http://www.pinvoke.net/search.aspx?search=GetWindowText\" rel=\"noreferrer\">pinvoke.net on GetWindowText and related functions</a>.</p>\n\n<p>However, that aside, with data as ushort, I assume that it is encoded in UTF-16LE. If that is the case you can use Encoding.Unicode.GetString(), but that will exepect a byte array rather than a ushort array. To turn your ushorts into bytes, you can allocate a separate byte array and use Buffer.BlockCopy, something like this:</p>\n\n<pre><code>ushort[] data = new ushort[10];\nfor (int i = 0; i &lt; data.Length; ++i)\n data[i] = (char) ('A' + i);\n\nstring asString;\nbyte[] asBytes = new byte[data.Length * sizeof(ushort)];\nBuffer.BlockCopy(data, 0, asBytes, 0, asBytes.Length);\nasString = Encoding.Unicode.GetString(asBytes);\n</code></pre>\n\n<p>However, if unsafe code is OK, you have another option. Get the start of the array as a ushort*, and hard-cast it to char*, and then pass it to the string constructor, like so:</p>\n\n<pre><code>string asString;\nunsafe\n{\n fixed (ushort *dataPtr = &amp;data[0])\n asString = new string((char *) dataPtr, 0, data.Length);\n}\n</code></pre>\n" }, { "answer_id": 274222, "author": "Dan Shield", "author_id": 4633, "author_profile": "https://Stackoverflow.com/users/4633", "pm_score": 0, "selected": false, "text": "<p>I don't like this much, but it seems to work given the following assumptions:</p>\n\n<p><strong>1.</strong> Each ushort is an ASCII char between 0 and 127</p>\n\n<p><strong>2.</strong> (Ok, I guess there is just one assumption)</p>\n\n<pre><code> ushort[] data = inData; // The ushort array source\n\n Byte[] bytes = new Byte[data.Length]; // Assumption - only need one byte per ushort\n\n int i = 0;\n foreach(ushort x in data) {\n byte[] tmp = System.BitConverter.GetBytes(x);\n bytes[i++] = tmp[0];\n // Note: not using tmp[1] as all characters in 0 &lt; x &lt; 127 use one byte.\n }\n\n String str = Encoding.ASCII.GetString(bytes);\n</code></pre>\n\n<p>I'm sure there are better ways to do this, but it's all I could come up with quickly.</p>\n" }, { "answer_id": 274224, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>Look into the <a href=\"http://msdn.microsoft.com/en-us/library/system.buffer.aspx\" rel=\"nofollow noreferrer\">Buffer</a> class:</p>\n\n<pre><code>ushort[] theImageData = inImageData.DataArray;\n\nbyte[] buf = new byte[Buffer.ByteLength(theImageData)]; // 2 bytes per short\nBuffer.BlockCopy(theImageData, 0, buf, 0, Buffer.ByteLength(theImageData));\n\nstring theOutData = System.Text.Encoding.ASCII.GetString(buf);\n</code></pre>\n" }, { "answer_id": 377915, "author": "user47414", "author_id": 47414, "author_profile": "https://Stackoverflow.com/users/47414", "pm_score": 1, "selected": false, "text": "<p>Just FYI, this has been fixed in later revision (gdcm 2.0.10). Look here:</p>\n\n<p><a href=\"http://gdcm.sourceforge.net/\" rel=\"nofollow noreferrer\">http://gdcm.sourceforge.net/</a></p>\n\n<p>-> <a href=\"http://apps.sourceforge.net/mediawiki/gdcm/index.php?title=GDCM_Release_2.0\" rel=\"nofollow noreferrer\">http://apps.sourceforge.net/mediawiki/gdcm/index.php?title=GDCM_Release_2.0</a></p>\n" }, { "answer_id": 65860043, "author": "KVM", "author_id": 1830854, "author_profile": "https://Stackoverflow.com/users/1830854", "pm_score": 0, "selected": false, "text": "<p>You can avoid unnecessary copying this way :</p>\n<pre><code>public static class Helpers\n{\n public static string ConvertToString(this ushort[] uSpan)\n {\n byte[] bytes = new byte[sizeof(ushort) * uSpan.Length];\n\n for (int i = 0; i &lt; uSpan.Length; i++)\n {\n Unsafe.As&lt;byte, ushort&gt;(ref bytes[i * 2]) = uSpan[i];\n }\n\n return Encoding.Unicode.GetString(bytes);\n }\n}\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21981/" ]
I have a very painful library which, at the moment, is accepting a C# string as a way to get arrays of data; apparently, this makes marshalling for pinvokes easier. So how do I make a ushort array into a string by bytes? I've tried: ``` int i; String theOutData = ""; ushort[] theImageData = inImageData.DataArray; //this is as slow like molasses in January for (i = 0; i < theImageData.Length; i++) { byte[] theBytes = System.BitConverter.GetBytes(theImageData[i]); theOutData += String.Format("{0:d}{1:d}", theBytes[0], theBytes[1]); } ``` I can do it this way, but it doesn't finish in anything remotely close to a sane amount of time. What should I do here? Go unsafe? Go through some kind of IntPtr intermediate? If it were a char\* in C++, this would be significantly easier... edit: the function call is ``` DataElement.SetByteValue(string inArray, VL Length); ``` where VL is a 'Value Length', a DICOM type, and the function itself is generated as a wrapper to a C++ library by SWIG. It seems that the representation chosen is string, because that can cross managed/unmanaged boundaries relatively easily, but throughout the C++ code in the project (this is GDCM), the char\* is simply used as a byte buffer. So, when you want to set your image buffer pointer, in C++ it's fairly simple, but in C#, I'm stuck with this weird problem. This is hackeration, and I know that probably the best thing is to make the SWIG library work right. I really don't know how to do that, and would rather a quick workaround on the C# side, if such exists.
P/Invoke can actually handle what you're after most of the time using StringBuilder to create writable buffers, for example see [pinvoke.net on GetWindowText and related functions](http://www.pinvoke.net/search.aspx?search=GetWindowText). However, that aside, with data as ushort, I assume that it is encoded in UTF-16LE. If that is the case you can use Encoding.Unicode.GetString(), but that will exepect a byte array rather than a ushort array. To turn your ushorts into bytes, you can allocate a separate byte array and use Buffer.BlockCopy, something like this: ``` ushort[] data = new ushort[10]; for (int i = 0; i < data.Length; ++i) data[i] = (char) ('A' + i); string asString; byte[] asBytes = new byte[data.Length * sizeof(ushort)]; Buffer.BlockCopy(data, 0, asBytes, 0, asBytes.Length); asString = Encoding.Unicode.GetString(asBytes); ``` However, if unsafe code is OK, you have another option. Get the start of the array as a ushort\*, and hard-cast it to char\*, and then pass it to the string constructor, like so: ``` string asString; unsafe { fixed (ushort *dataPtr = &data[0]) asString = new string((char *) dataPtr, 0, data.Length); } ```
274,162
<p>Is there a specific reason why I should be using the <code>Html.CheckBox</code>, <code>Html.TextBox</code>, etc methods instead of just manually writing the HTML?</p> <pre><code>&lt;%= Html.TextBox("uri") %&gt; </code></pre> <p>renders the following HTML</p> <pre><code>&lt;input type="text" value="" name="uri" id="uri"/&gt; </code></pre> <p>It guess it saves you a few key strokes but other than that. Is there a specific reason why I should go out of my way to use the HtmlHelpers whenever possible or is it just a preference thing?</p>
[ { "answer_id": 274169, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>I haven't been doing MVC too long, but I've already written some extension methods to generate menu tabs based on Html.ActionLink. It allows me to be consistent with my usage and, if I decide to change how my CSS menus work, only modify a single method to output the new tab format.</p>\n\n<p>The other use that I have made of them is in conditional output using ViewData to supply values to the controls.</p>\n" }, { "answer_id": 274170, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 2, "selected": false, "text": "<p>One thing is for consistency...I for one always forget the name attribute. Plus, you can extend the functions for your own projects. They're not called <strong>helpers</strong> for nothing!</p>\n" }, { "answer_id": 274264, "author": "Glenn", "author_id": 25191, "author_profile": "https://Stackoverflow.com/users/25191", "pm_score": 2, "selected": false, "text": "<p>The upside to using an abstraction layer is future proofing your code in a pluggable way. Maybe today, you create HTML 4 pages but tomorrow you want to create XHTML pages or XAML or XUL. That's a lot of changes if you just hard code the tags everywhere, especially if you've got hundreds of pages. If everything is calling this library, then all you've got to do is rewrite the library. The downside is that it is usually considered to be slightly less readable by humans. So, it most probably increases the cognitive demand on your maintenance programmers. These advantages and disadvantages really have nothing to do with MVC.</p>\n" }, { "answer_id": 274272, "author": "user17060", "author_id": 17060, "author_profile": "https://Stackoverflow.com/users/17060", "pm_score": 3, "selected": false, "text": "<p>Another benefit is that if your ViewData contains a value matching the name of the field it will be populated. </p>\n\n<p>e.g.</p>\n\n<pre><code>ViewData[\"FirstName\"] = \"Joe Bloggs\"; \n\n&lt;%=Html.TextBox(\"FirstName\") %&gt;\n</code></pre>\n\n<p>will render </p>\n\n<pre><code>&lt;input type=\"text\" value=\"Joe Bloggs\" id=\"FirstName\" /&gt;\n</code></pre>\n" }, { "answer_id": 274273, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It actually auto populates your textbox based upon first your ViewData.Model.uri and second by ViewData[\"uri\"]. Doing it manually you'd need to do <code>&lt;input value=\"&lt;%Html.Encode(ViewData.Model.Uri\"%&gt;\" /&gt;</code></p>\n" }, { "answer_id": 274289, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 4, "selected": true, "text": "<p>There are huge benefits:</p>\n\n<p>It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState.</p>\n\n<p>It allows built in support for the Validation features of MVC.</p>\n\n<p>It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of \"Controller Adapter\" type methodology).</p>\n\n<p>It leads to the idea of building your own \"controls\" : <a href=\"http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx\" rel=\"nofollow noreferrer\">http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx</a></p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
Is there a specific reason why I should be using the `Html.CheckBox`, `Html.TextBox`, etc methods instead of just manually writing the HTML? ``` <%= Html.TextBox("uri") %> ``` renders the following HTML ``` <input type="text" value="" name="uri" id="uri"/> ``` It guess it saves you a few key strokes but other than that. Is there a specific reason why I should go out of my way to use the HtmlHelpers whenever possible or is it just a preference thing?
There are huge benefits: It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState. It allows built in support for the Validation features of MVC. It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of "Controller Adapter" type methodology). It leads to the idea of building your own "controls" : <http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx>
274,172
<p>VB.Net2005</p> <p>Simplified Code:</p> <pre><code> MustInherit Class InnerBase(Of Inheritor) End Class MustInherit Class OuterBase(Of Inheritor) Class Inner Inherits InnerBase(Of Inner) End Class End Class Class ChildClass Inherits OuterBase(Of ChildClass) End Class Class ChildClassTwo Inherits OuterBase(Of ChildClassTwo) End Class MustInherit Class CollectionClass(Of _ Inheritor As CollectionClass(Of Inheritor, Member), _ Member As OuterBase(Of Member)) Dim fails As Member.Inner ' Type parameter cannot be used as qualifier Dim works As New ChildClass.Inner Dim failsAsExpected As ChildClassTwo.Inner = works ' type conversion failure End Class </code></pre> <p>The error message on the "fails" line is in the subject, and "Member.Inner" is highlighted. Incidentally, the same error occurs with trying to call a shared method of OuterBase.</p> <p>The "works" line works, but there are a dozen (and counting) ChildClass classes in real life.</p> <p>The "failsAsExpected" line is there to show that, with generics, each ChildClass has its own distinct Inner class.</p> <p>My question: is there a way to get a variable, in class CollectionClass, defined as type Member.Inner? what's the critical difference that the compiler can't follow?</p> <p>(I was eventually able to generate an object by creating a dummy object of type param and calling a method defined in OuterBase. Not the cleanest approach.)</p> <p>Edit 2008/12/2 altered code to make the two "base" classes generic.</p>
[ { "answer_id": 274169, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>I haven't been doing MVC too long, but I've already written some extension methods to generate menu tabs based on Html.ActionLink. It allows me to be consistent with my usage and, if I decide to change how my CSS menus work, only modify a single method to output the new tab format.</p>\n\n<p>The other use that I have made of them is in conditional output using ViewData to supply values to the controls.</p>\n" }, { "answer_id": 274170, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 2, "selected": false, "text": "<p>One thing is for consistency...I for one always forget the name attribute. Plus, you can extend the functions for your own projects. They're not called <strong>helpers</strong> for nothing!</p>\n" }, { "answer_id": 274264, "author": "Glenn", "author_id": 25191, "author_profile": "https://Stackoverflow.com/users/25191", "pm_score": 2, "selected": false, "text": "<p>The upside to using an abstraction layer is future proofing your code in a pluggable way. Maybe today, you create HTML 4 pages but tomorrow you want to create XHTML pages or XAML or XUL. That's a lot of changes if you just hard code the tags everywhere, especially if you've got hundreds of pages. If everything is calling this library, then all you've got to do is rewrite the library. The downside is that it is usually considered to be slightly less readable by humans. So, it most probably increases the cognitive demand on your maintenance programmers. These advantages and disadvantages really have nothing to do with MVC.</p>\n" }, { "answer_id": 274272, "author": "user17060", "author_id": 17060, "author_profile": "https://Stackoverflow.com/users/17060", "pm_score": 3, "selected": false, "text": "<p>Another benefit is that if your ViewData contains a value matching the name of the field it will be populated. </p>\n\n<p>e.g.</p>\n\n<pre><code>ViewData[\"FirstName\"] = \"Joe Bloggs\"; \n\n&lt;%=Html.TextBox(\"FirstName\") %&gt;\n</code></pre>\n\n<p>will render </p>\n\n<pre><code>&lt;input type=\"text\" value=\"Joe Bloggs\" id=\"FirstName\" /&gt;\n</code></pre>\n" }, { "answer_id": 274273, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It actually auto populates your textbox based upon first your ViewData.Model.uri and second by ViewData[\"uri\"]. Doing it manually you'd need to do <code>&lt;input value=\"&lt;%Html.Encode(ViewData.Model.Uri\"%&gt;\" /&gt;</code></p>\n" }, { "answer_id": 274289, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 4, "selected": true, "text": "<p>There are huge benefits:</p>\n\n<p>It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState.</p>\n\n<p>It allows built in support for the Validation features of MVC.</p>\n\n<p>It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of \"Controller Adapter\" type methodology).</p>\n\n<p>It leads to the idea of building your own \"controls\" : <a href=\"http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx\" rel=\"nofollow noreferrer\">http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx</a></p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
VB.Net2005 Simplified Code: ``` MustInherit Class InnerBase(Of Inheritor) End Class MustInherit Class OuterBase(Of Inheritor) Class Inner Inherits InnerBase(Of Inner) End Class End Class Class ChildClass Inherits OuterBase(Of ChildClass) End Class Class ChildClassTwo Inherits OuterBase(Of ChildClassTwo) End Class MustInherit Class CollectionClass(Of _ Inheritor As CollectionClass(Of Inheritor, Member), _ Member As OuterBase(Of Member)) Dim fails As Member.Inner ' Type parameter cannot be used as qualifier Dim works As New ChildClass.Inner Dim failsAsExpected As ChildClassTwo.Inner = works ' type conversion failure End Class ``` The error message on the "fails" line is in the subject, and "Member.Inner" is highlighted. Incidentally, the same error occurs with trying to call a shared method of OuterBase. The "works" line works, but there are a dozen (and counting) ChildClass classes in real life. The "failsAsExpected" line is there to show that, with generics, each ChildClass has its own distinct Inner class. My question: is there a way to get a variable, in class CollectionClass, defined as type Member.Inner? what's the critical difference that the compiler can't follow? (I was eventually able to generate an object by creating a dummy object of type param and calling a method defined in OuterBase. Not the cleanest approach.) Edit 2008/12/2 altered code to make the two "base" classes generic.
There are huge benefits: It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState. It allows built in support for the Validation features of MVC. It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of "Controller Adapter" type methodology). It leads to the idea of building your own "controls" : <http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx>
274,179
<p>I have followed the instructions to setup rxtx on windows from <a href="http://www.jcontrol.org/download/readme_rxtx_en.html" rel="nofollow noreferrer">http://www.jcontrol.org/download/readme_rxtx_en.html</a>.</p> <p>What I did exactly was copy rxtxSerial.dll to "C:\Program Files\Java\jdk1.6.0_07\jre\bin" and copied RXTXcomm.jar to "C:\Program Files\Java\jdk1.6.0_07\jre\lib\ext" (my JAVA_HOME variable is set to C:\Program Files\Java\jdk1.6.0_07\jre)</p> <p>I also added RXTXcomm.jar to my eclipse project.</p> <p>But when I run it, it still says "NoSuchPortException"</p> <pre> Devel Library ========================================= Native lib Version = RXTX-2.0-7pre1 Java lib Version = RXTX-2.0-7pre1 java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver gnu.io.NoSuchPortException at gnu.io.CommPortIdentifier.getPortIdentifier(CommPortIdentifier.java:218) at TwoWaySerialComm.connect(TwoWaySerialComm.java:20) at TwoWaySerialComm.main(TwoWaySerialComm.java:107) </pre> <p>In my java file, I tell it:</p> <pre> try { (new TwoWaySerialComm()).connect("COM4"); } </pre> <p>and I've also tried the Java Comm API. Both cannot recognize my serial port but I am sure I followed the instruction correctly. There files are there.</p> <p>Does anybody have any idea what it could be?</p>
[ { "answer_id": 274257, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "<p>Try putting <code>rxtxSerial.dll</code> in</p>\n\n<pre><code>C:\\Program Files\\Java\\jdk1.6.0_07\\jre\\lib\\bin\n ^^^\n</code></pre>\n" }, { "answer_id": 274464, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 0, "selected": false, "text": "<p>It may be that your system does not have a COM4 defined or it's not accessible. It's hard to guess what may be wrong, because you haven't posted you port init code - what you posted looks like wrapper code.</p>\n\n<p>Here is my working init code using the javax.comm API (but using SerialPort from serialio.com):</p>\n\n<pre><code>// name comes from config and is \"COM1\", \"COM2\", ...\nSerialPort port=(SerialPort)CommPortIdentifier.getPortIdentifier(name).open(\"YourPortOwnerIdHere\",5000); // owner and ms timeout\nport.setSerialPortParams(bau,dtb,stb,par);\nport.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN|SerialPort.FLOWCONTROL_RTSCTS_OUT);\nport.enableReceiveTimeout(1000);\n</code></pre>\n\n<p>Hopefully this points you in the right direction.</p>\n" }, { "answer_id": 277265, "author": "Peter", "author_id": 26483, "author_profile": "https://Stackoverflow.com/users/26483", "pm_score": 1, "selected": false, "text": "<p>you can use \nCommPortIdentifier.getPortIdentifiers()</p>\n\n<p>to identify all possible ports your system finds.</p>\n" }, { "answer_id": 746771, "author": "Daniel Schneller", "author_id": 1252368, "author_profile": "https://Stackoverflow.com/users/1252368", "pm_score": 1, "selected": false, "text": "<p>I am not too familiar with RXTX, but is this normal?</p>\n\n<pre><code>java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver\n</code></pre>\n\n<p>Otherwise maybe the problem is not with the port itself after all, but something with the classes themselves?\nJust a guess.</p>\n" }, { "answer_id": 770712, "author": "johnstosh", "author_id": 93518, "author_profile": "https://Stackoverflow.com/users/93518", "pm_score": 0, "selected": false, "text": "<p>I agree that you're problem looks like a ClassCastException and not the other.</p>\n\n<p>For windows, I'm using \"Windows Java Serial Com Port Driver\" at <a href=\"http://www.engidea.com/blog/informatica/winjcom/winjcom.html\" rel=\"nofollow noreferrer\">http://www.engidea.com/blog/informatica/winjcom/winjcom.html</a> and it is much easier for me to set up.</p>\n\n<p>In either case, you want the DLL in the BIN directory, not LIB\\BIN as was suggested. At least that's what's working for me. I'm using NetBeans and I've also found it helpful to put the jar and dll into various bin and lib\\ext folders in the JDK.</p>\n\n<p>Note that if you have multiple versions of the JRE on your machine, you might not be using the one that you think you are using. Also, as a practical matter I've found it more helpful to just copy both the jar and dll into the various bin and lib\\ext folders. Makes it just a paste, paste, paste operation.</p>\n\n<p>For windows, I recommend \"Windows Java Serial Com Port Driver\" because it solved my problems with USB serial ports. I had fits with RXTX because it would crash when the USB was unplugged. winjcom solved that problem and others as well. It has very helpful error exceptions.</p>\n\n<p>Also, make sure your serial drivers are up-to-date. Downloading an update fixed my other bug.\n-Stosh</p>\n" }, { "answer_id": 1407361, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I also had a problem when closing the serialPort within the serialEvent function.\nMaybe it's a deadlock problem, where the close method waits forever for serialEvent's lock to be released.\nStarting a new thread to close the port worked for me.</p>\n" }, { "answer_id": 2132079, "author": "wiking", "author_id": 258391, "author_profile": "https://Stackoverflow.com/users/258391", "pm_score": 1, "selected": false, "text": "<p>You can also try an alternative solution that was specifically implemented for Windows. There should be plenty available, one of them you can get from <a href=\"http://www.caerustech.com/JCommWin32.php\" rel=\"nofollow noreferrer\">http://www.caerustech.com/JCommWin32.php</a> </p>\n\n<p>Shultz</p>\n" }, { "answer_id": 2736618, "author": "Memafe", "author_id": 328783, "author_profile": "https://Stackoverflow.com/users/328783", "pm_score": 0, "selected": false, "text": "<p>For your question, my code is the following:</p>\n\n<pre><code>if (idPuerto == null)\n{\n formulario = form;\n boolean encontrado = false;\n\n\n listaPuertos = CommPortIdentifier.getPortIdentifiers();\n\n while( listaPuertos.hasMoreElements() &amp;&amp; encontrado == false )\n {\n idPuerto = (CommPortIdentifier)listaPuertos.nextElement();\n //System.out.println(idPuerto.getName());\n\n if( idPuerto.getPortType() == CommPortIdentifier.PORT_SERIAL )\n {\n if( idPuerto.getName().equals(RFIDBascApp.ComBasc) )\n { \n encontrado = true;\n logger.AddInfoUser(\"Puerto serie encontrado\");\n\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 4560703, "author": "darkphoenix", "author_id": 477753, "author_profile": "https://Stackoverflow.com/users/477753", "pm_score": -1, "selected": false, "text": "<p>@Pinheiro you might want to take a look at <a href=\"http://rxtx.qbang.org/wiki/index.php/Trouble_shooting#How_does_rxtx_detect_ports.3F__Can_I_override_it.3F\" rel=\"nofollow\">this</a></p>\n" }, { "answer_id": 4935149, "author": "Hamedz", "author_id": 464219, "author_profile": "https://Stackoverflow.com/users/464219", "pm_score": 0, "selected": false, "text": "<p>You had <code>NoSuchPortException</code>, so first of all iterate on all available ports!</p>\n\n<pre><code>import gnu.io.CommPortIdentifier; \nimport java.util.Enumeration; \n\npublic class ListAvailablePorts { \n\n public void list() { \n Enumeration ports = CommPortIdentifier.getPortIdentifiers(); \n\n while(ports.hasMoreElements()){ \n CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();\n System.out.println(port.getName());\n }\n } \n\n public static void main(String[] args) { \n new ListAvailablePorts().list(); \n } \n} \n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
I have followed the instructions to setup rxtx on windows from <http://www.jcontrol.org/download/readme_rxtx_en.html>. What I did exactly was copy rxtxSerial.dll to "C:\Program Files\Java\jdk1.6.0\_07\jre\bin" and copied RXTXcomm.jar to "C:\Program Files\Java\jdk1.6.0\_07\jre\lib\ext" (my JAVA\_HOME variable is set to C:\Program Files\Java\jdk1.6.0\_07\jre) I also added RXTXcomm.jar to my eclipse project. But when I run it, it still says "NoSuchPortException" ``` Devel Library ========================================= Native lib Version = RXTX-2.0-7pre1 Java lib Version = RXTX-2.0-7pre1 java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver gnu.io.NoSuchPortException at gnu.io.CommPortIdentifier.getPortIdentifier(CommPortIdentifier.java:218) at TwoWaySerialComm.connect(TwoWaySerialComm.java:20) at TwoWaySerialComm.main(TwoWaySerialComm.java:107) ``` In my java file, I tell it: ``` try { (new TwoWaySerialComm()).connect("COM4"); } ``` and I've also tried the Java Comm API. Both cannot recognize my serial port but I am sure I followed the instruction correctly. There files are there. Does anybody have any idea what it could be?
Try putting `rxtxSerial.dll` in ``` C:\Program Files\Java\jdk1.6.0_07\jre\lib\bin ^^^ ```
274,185
<p>Let's say there's a.gz, and b.gz.</p> <p>$ gzip_merge a.gz b.gz -output c.gz</p> <p>I'd like to have this program. Of course,</p> <p>$ cat a.gz b.gz > c.gz</p> <p>doesn't work. Because the final DEFLATE block of a.gz has BFINAL, and the GZIP header of b.gz. (Refer to RFC1951, RFC1952) But if you unset BFINAL, throw away the second GZIP header and walk through the byte boundaries of the second gzip file, you can merge it.</p> <p>In fact, I thought of writing an open source program for this matter, but didn't know how to publish it. So I asked the Joel to be my program manager, and I walked him through my explanation and defense, he finally understood what I wanted to do, but said he was too busy. :(</p> <p>Of course, I could write one myself and try my way to publish it. But I can't do this alone because my day work belongs to the property of my employer.</p> <p>Is there any volunteers? We could work as programmer(me), publisher(you) or programmer(you), publisher(me). All I need is some credit. I once implemented a Universal Decompressor Virtual Machine described in RFC3320. So I know this is feasible. </p> <p>OR, you could point me to THAT program. It would be very useful for managing log files like merging 365 (day) gzipped log files to one. ;)</p> <p>Thanks.</p>
[ { "answer_id": 274190, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 6, "selected": true, "text": "<blockquote>\n <p>Of course, cat a.gz b.gz > c.gz doesn't work.</p>\n</blockquote>\n\n<p>Actually, it works just fine. I just tested it. It's even documented (sort of) in the gzip man page.</p>\n\n<pre><code> Multiple compressed files can be concatenated. In this case, gunzip\n will extract all members at once. For example:\n\n gzip -c file1 &gt; foo.gz\n gzip -c file2 &gt;&gt; foo.gz\n\n Then\n\n gunzip -c foo\n\n is equivalent to\n\n cat file1 file2\n</code></pre>\n" }, { "answer_id": 11461282, "author": "Suman", "author_id": 1203129, "author_profile": "https://Stackoverflow.com/users/1203129", "pm_score": 3, "selected": false, "text": "<p>You could also:</p>\n\n<pre><code>zcat a.gz b.gz &gt; c.txt &amp;&amp; gzip c.txt\n</code></pre>\n\n<p>as long as your Linux/Unix distribution has zcat built in, which most of them do (and you could install it for the ones that do not.)</p>\n\n<p>Alternatively:</p>\n\n<pre><code>zcat a.gz b.gz | gzip -c &gt; c.txt.gz\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24349/" ]
Let's say there's a.gz, and b.gz. $ gzip\_merge a.gz b.gz -output c.gz I'd like to have this program. Of course, $ cat a.gz b.gz > c.gz doesn't work. Because the final DEFLATE block of a.gz has BFINAL, and the GZIP header of b.gz. (Refer to RFC1951, RFC1952) But if you unset BFINAL, throw away the second GZIP header and walk through the byte boundaries of the second gzip file, you can merge it. In fact, I thought of writing an open source program for this matter, but didn't know how to publish it. So I asked the Joel to be my program manager, and I walked him through my explanation and defense, he finally understood what I wanted to do, but said he was too busy. :( Of course, I could write one myself and try my way to publish it. But I can't do this alone because my day work belongs to the property of my employer. Is there any volunteers? We could work as programmer(me), publisher(you) or programmer(you), publisher(me). All I need is some credit. I once implemented a Universal Decompressor Virtual Machine described in RFC3320. So I know this is feasible. OR, you could point me to THAT program. It would be very useful for managing log files like merging 365 (day) gzipped log files to one. ;) Thanks.
> > Of course, cat a.gz b.gz > c.gz doesn't work. > > > Actually, it works just fine. I just tested it. It's even documented (sort of) in the gzip man page. ``` Multiple compressed files can be concatenated. In this case, gunzip will extract all members at once. For example: gzip -c file1 > foo.gz gzip -c file2 >> foo.gz Then gunzip -c foo is equivalent to cat file1 file2 ```
274,196
<p>I've got a large number of integer arrays. Each one has a few thousand integers in it, and each integer is generally the same as the one before it or is different by only a single bit or two. I'd like to shrink each array down as small as possible to reduce my disk IO. </p> <p>Zlib shrinks it to about 25% of its original size. That's nice, but I don't think its algorithm is particularly well suited for the problem. Does anyone know a compression library or simple algorithm that might perform better for this type of information?</p> <p>Update: zlib after converting it to an array of xor deltas shrinks it to about 20% of the original size. </p>
[ { "answer_id": 274201, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 0, "selected": false, "text": "<p>Did you try bzip2 for this?\n<a href=\"http://bzip.org/\" rel=\"nofollow noreferrer\">http://bzip.org/</a></p>\n\n<p>It's always worked better than zlib for me.</p>\n" }, { "answer_id": 274206, "author": "Dirk Groeneveld", "author_id": 13562, "author_profile": "https://Stackoverflow.com/users/13562", "pm_score": 3, "selected": false, "text": "<p>Have you considered <a href=\"http://en.wikipedia.org/wiki/Run-length_encoding\" rel=\"noreferrer\">Run-length encoding</a>?</p>\n\n<p>Or try this: Instead of storing the numbers themselves, you store the differences between the numbers. 1 1 2 2 2 3 5 becomes 1 0 1 0 0 1 2. Now most of the numbers you have to encode are very small. To store a small integer, use an 8-bit integer instead of the 32-bit one you'll encode on most platforms. That's a factor of 4 right there. If you do need to be prepared for bigger gaps than that, designate the high-bit of the 8-bit integer to say \"this number requires the next 8 bits as well\".</p>\n\n<p>You can combine that with run-length encoding for even better compression ratios, depending on your data.</p>\n\n<p>Neither of these options is particularly hard to implement, and they all run very fast and with very little memory (as opposed to, say, bzip).</p>\n" }, { "answer_id": 274215, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p>Perhaps the answer is to pre-filter the arrays in a way analogous to the <a href=\"http://www.libpng.org/pub/png/spec/iso/index-object.html#9Filters\" rel=\"nofollow noreferrer\">Filtering used to create small PNG images</a>. Here are some ideas right off the top of my head. I've not tried these approaches, but if you feel like playing, they could be interesting.</p>\n\n<ol>\n<li><p>Break your ints up each into 4 bytes, so i<sub>0</sub>, i<sub>1</sub>, i<sub>2</sub>, ..., i<sub>n</sub> becomes b<sub>0,0</sub>, b<sub>0,1</sub>, b<sub>0,2</sub>, b<sub>0,3</sub>, b<sub>1,0</sub>, b<sub>1,1</sub>, b<sub>1,2</sub>, b<sub>1,3</sub>, ..., b<sub>n,0</sub>, b<sub>n,1</sub>, b<sub>n,2</sub>, b<sub>n,3</sub>. Then write out all the b<sub>i,0</sub>s, followed by the b<sub>i,1</sub>s, b<sub>i,2</sub>s, and b<sub>i,3</sub>s. If most of the time your numbers differ only by a bit or two, you should get nice long runs of repeated bytes, which should compress really nicely using something like Run-length Encoding or zlib. This is my favourite of the methods I present.</p></li>\n<li><p>If the integers in each array are closely-related to the one before, you could maybe store the original integer, followed by diffs against the previous entry - this should give a smaller set of values to draw from, which typically results in a more compressed form. </p></li>\n<li><p>If you have various bits differing, you still may have largish differences, but if you're more likely to have large numeric differences that correspond to (usually) one or two bits differing, you may be better off with a scheme where you create ahebyte array - use the first 4 bytes to encode the first integer, and then for each subsequent entry, use 0 or more bytes to indicate which bits should be flipped - storing 0, 1, 2, ..., or 31 in the byte, with a sentinel (say 32) to indicate when you're done. This could result the raw number of bytes needed to represent and integer to something close to 2 on average, which most bytes coming from a limited set (0 - 32). Run that stream through zlib, and maybe you'll be pleasantly surprised.</p></li>\n</ol>\n" }, { "answer_id": 274218, "author": "comingstorm", "author_id": 210211, "author_profile": "https://Stackoverflow.com/users/210211", "pm_score": 2, "selected": false, "text": "<p>You want to preprocess your data -- reversibly transform it to some form that is better-suited to your back-end data compression method, first. The details will depend on both the back-end compression method, and (more critically) on the properties you expect from the data you're compressing.</p>\n\n<p>In your case, zlib is a byte-wise compression method, but your data comes in (32-bit?) integers. You don't need to reimplement zlib yourself, but you do need to read up on how it works, so you can figure out how to present it with easily compressible data, or if it's appropriate for your purposes at all.</p>\n\n<p>Zlib implements a form of Lempel-Ziv coding. JPG and many others use Huffman coding for their backend. Run-length encoding is popular for many ad hoc uses. Etc., etc. ...</p>\n" }, { "answer_id": 274243, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 0, "selected": false, "text": "<p>Since your concern is to reduce disk IO, you'll want to compress each integer array independently, without making reference to other integer arrays.</p>\n\n<p>A common technique for your scenario is to store the differences, since a small number of differences can be encoded with short codewords. It sounds like you need to come up with your own coding scheme for differences, since they are multi-bit differences, perhaps using an 8 bit byte something like this as a starting point:</p>\n\n<ul>\n<li>1 bit to indicate that a complete new integer follows, or that this byte encodes a difference from the last integer, </li>\n<li>1 bit to indicate that there are more bytes following, recording more single bit differences for the same integer.</li>\n<li>6 bits to record the bit number to switch from your previous integer.</li>\n</ul>\n\n<p>If there are more than 4 bits different, then store the integer.</p>\n\n<p>This scheme might not be appropriate if you also have a lot of completely different codes, since they'll take 5 bytes each now instead of 4.</p>\n" }, { "answer_id": 274278, "author": "Jay Kominek", "author_id": 32878, "author_profile": "https://Stackoverflow.com/users/32878", "pm_score": 4, "selected": true, "text": "<p>If most of the integers really are the same as the previous, and the inter-symbol difference can usually be expressed as a single bit flip, this sounds like a job for XOR.</p>\n\n<p>Take an input stream like:</p>\n\n<pre><code>1101\n1101\n1110\n1110\n0110\n</code></pre>\n\n<p>and output:</p>\n\n<pre><code>1101\n0000\n0010\n0000\n1000\n</code></pre>\n\n<p>a bit of pseudo code</p>\n\n<pre><code>compressed[0] = uncompressed[0]\nloop\n compressed[i] = uncompressed[i-1] ^ uncompressed[i]\n</code></pre>\n\n<p>We've now reduced most of the output to 0, even when a high bit is changed. The RLE compression in any other tool you use will have a field day with this. It'll work even better on 32-bit integers, and it can still encode a radically different integer popping up in the stream. You're saved the bother of dealing with bit-packing yourself, as everything remains an int-sized quantity.</p>\n\n<p>When you want to decompress:</p>\n\n<pre><code>uncompressed[0] = compressed[0]\nloop\n uncompressed[i] = uncompressed[i-1] ^ compressed[i]\n</code></pre>\n\n<p>This also has the advantage of being a simple algorithm that is going to run really, really fast, since it is just XOR.</p>\n" }, { "answer_id": 274395, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>\"Zlib shrinks it by a factor of about 4x.\" means that a file of 100K now takes up <strong>negative</strong> 300K; that's pretty impressive by any definition :-). I assume you mean it shrinks it by 75%, i.e., to 1/4 its original size.</p>\n\n<p>One possibility for an optimized compression is as follows (it assumes a 32-bit integer and at most 3 bits changing from element to element).</p>\n\n<ul>\n<li>Output the first integer (32 bits).</li>\n<li>Output the number of bit changes (n=0-3, 2 bits).</li>\n<li>Output n bit specifiers (0-31, 5 bits each).</li>\n</ul>\n\n<p>Worst case for this compression is 3 bit changes in every integer (2+5+5+5 bits) which will tend towards 17/32 of original size (46.875% compression).</p>\n\n<p>I say \"tends towards\" since the first integer is always 32 bits but, for any decent sized array, that first integer would be negligable.</p>\n\n<p>Best case is a file of identical integers (no bit changes for every integer, just the 2 zero bits) - this will tend towards 2/32 of original size (93.75% compression).</p>\n\n<p>Where you average 2 bits different per consecutive integer (as you say is your common case), you'll get 2+5+5 bits per integer which will tend towards 12/32 or 62.5% compression.</p>\n\n<p>Your break-even point (if zlib gives 75% compression) is 8 bits per integer which would be</p>\n\n<ul>\n<li>single-bit changes (2+5 = 7 bits) : 80% of the transitions.</li>\n<li>double-bit changes (2+5+5 = 12 bits) : 20% of the transitions.</li>\n</ul>\n\n<p>This means your average would have to be 1.2 bit changes per integer to make this worthwhile.</p>\n\n<p>One thing I would suggest looking at is 7zip - this has a very liberal licence and you can link it with your code (I think the source is available as well).</p>\n\n<p>I notice (for my stuff anyway) it performs <em>much</em> better than WinZip on a Windows platform so it may also outperform zlib.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23524/" ]
I've got a large number of integer arrays. Each one has a few thousand integers in it, and each integer is generally the same as the one before it or is different by only a single bit or two. I'd like to shrink each array down as small as possible to reduce my disk IO. Zlib shrinks it to about 25% of its original size. That's nice, but I don't think its algorithm is particularly well suited for the problem. Does anyone know a compression library or simple algorithm that might perform better for this type of information? Update: zlib after converting it to an array of xor deltas shrinks it to about 20% of the original size.
If most of the integers really are the same as the previous, and the inter-symbol difference can usually be expressed as a single bit flip, this sounds like a job for XOR. Take an input stream like: ``` 1101 1101 1110 1110 0110 ``` and output: ``` 1101 0000 0010 0000 1000 ``` a bit of pseudo code ``` compressed[0] = uncompressed[0] loop compressed[i] = uncompressed[i-1] ^ uncompressed[i] ``` We've now reduced most of the output to 0, even when a high bit is changed. The RLE compression in any other tool you use will have a field day with this. It'll work even better on 32-bit integers, and it can still encode a radically different integer popping up in the stream. You're saved the bother of dealing with bit-packing yourself, as everything remains an int-sized quantity. When you want to decompress: ``` uncompressed[0] = compressed[0] loop uncompressed[i] = uncompressed[i-1] ^ compressed[i] ``` This also has the advantage of being a simple algorithm that is going to run really, really fast, since it is just XOR.
274,265
<p>I can't for the life of me find a way to make this work.</p> <p>If I have 3 divs (a left sidebar, a main body, and a footer), how can I have the sidebar and main body sit next to each other without setting their positions as "absolute" or floating them? Doing either of these options result in the footer div not being pushed down by one or the other.</p> <p>How might I accomplish this regardless of what comes before these elements (say another header div or something)?</p> <p>In case it helps, here's an illustration of the two cases I'm trying to allow for:</p> <p><img src="https://i.stack.imgur.com/zjEzC.jpg" alt="alt text"></p> <p>Here's a simplified version of the HTML I currently have set up:</p> <pre><code>&lt;div id="sidebar"&gt;&lt;/div&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;div id="footer"&gt;&lt;/div&gt; </code></pre>
[ { "answer_id": 274269, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 5, "selected": true, "text": "<p>You need to specify the footer to clear the float:</p>\n\n<pre><code>#footer{\n clear: both;\n}\n</code></pre>\n\n<p>This forces it under floated elements.</p>\n\n<p>Other options for clear are left and right.</p>\n" }, { "answer_id": 436054, "author": "Marco Luglio", "author_id": 14263, "author_profile": "https://Stackoverflow.com/users/14263", "pm_score": 0, "selected": false, "text": "<p>Right now you're pretty hopeless if you don't want to float anything, nor use position: absolute.</p>\n\n<p>The only alternatives left are:</p>\n\n<ul>\n<li>use display:inline-block for the sidebar and content divs (this is not supported by all browsers yet)</li>\n<li>wait for the <a href=\"http://www.w3.org/TR/css3-layout\" rel=\"nofollow noreferrer\">css advanced layout module</a> or some other column module (will take forever probably)</li>\n<li>go back to using tables</li>\n</ul>\n" }, { "answer_id": 500381, "author": "unigogo", "author_id": 61145, "author_profile": "https://Stackoverflow.com/users/61145", "pm_score": 1, "selected": false, "text": "<p>Doing either of these options result in the footer div not being pushed down by one or the other?</p>\n\n<p>Try <a href=\"http://www.pagecolumn.com/2_column_div_generator.htm\" rel=\"nofollow noreferrer\">this tool</a></p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
I can't for the life of me find a way to make this work. If I have 3 divs (a left sidebar, a main body, and a footer), how can I have the sidebar and main body sit next to each other without setting their positions as "absolute" or floating them? Doing either of these options result in the footer div not being pushed down by one or the other. How might I accomplish this regardless of what comes before these elements (say another header div or something)? In case it helps, here's an illustration of the two cases I'm trying to allow for: ![alt text](https://i.stack.imgur.com/zjEzC.jpg) Here's a simplified version of the HTML I currently have set up: ``` <div id="sidebar"></div> <div id="content"></div> <div id="footer"></div> ```
You need to specify the footer to clear the float: ``` #footer{ clear: both; } ``` This forces it under floated elements. Other options for clear are left and right.
274,286
<p>I have a new VPS server, and I'm trying to get it to connect to another server at the same ISP. When I connect via mysql's command line tool, the connection is very fast.</p> <p>When I use PHP to connect to the remote DB, the connection time may take up to 5 seconds. Queries after this are executed quickly.</p> <p>This is not limited to mysql, using file_get_contents() to download a file from nearly any other server gives the same lag. Using wget to get the file does not have this lag.</p> <p>I timed DNS queries from within PHP using dns_get_record(), and these are fast (1-2 milliseconds).</p> <p>Any thoughts on what in the php config may be causing this? </p> <p>Thanks.</p>
[ { "answer_id": 274343, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 2, "selected": false, "text": "<p>I would check to see what mode PHP is running in, is it for some reason running the scripts as a CGI. Basically is PHP itself really slow, and its only noticeable when running remote operations.</p>\n\n<p>Check the web server's configuration. Also if it's an option, try PHP from the command line and see if it performs better without the web server layer involved. </p>\n" }, { "answer_id": 275204, "author": "Jay", "author_id": 31479, "author_profile": "https://Stackoverflow.com/users/31479", "pm_score": 2, "selected": true, "text": "<p>I ended up upgrading from PHP 5.1.6 to PHP 5.2.6, and the problem went away. It definitely was a DNS lookup issue within PHP, the following would take about 5 seconds to run:</p>\n\n<pre><code>gethostbyname('example.com')\n</code></pre>\n\n<p>I have a feeling IPV6 was an issue (mostly a hunch from reading about this online), but I don't have any proof.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31479/" ]
I have a new VPS server, and I'm trying to get it to connect to another server at the same ISP. When I connect via mysql's command line tool, the connection is very fast. When I use PHP to connect to the remote DB, the connection time may take up to 5 seconds. Queries after this are executed quickly. This is not limited to mysql, using file\_get\_contents() to download a file from nearly any other server gives the same lag. Using wget to get the file does not have this lag. I timed DNS queries from within PHP using dns\_get\_record(), and these are fast (1-2 milliseconds). Any thoughts on what in the php config may be causing this? Thanks.
I ended up upgrading from PHP 5.1.6 to PHP 5.2.6, and the problem went away. It definitely was a DNS lookup issue within PHP, the following would take about 5 seconds to run: ``` gethostbyname('example.com') ``` I have a feeling IPV6 was an issue (mostly a hunch from reading about this online), but I don't have any proof.
274,315
<p>I'm writing a C# app using the WebBrowser control, and I want all content I display to come from embedded resources - not static local files, and not remote files.</p> <p>Setting the initial text of the control to an embedded HTML file works great with this code inspired by <a href="http://blog.topholt.com/2008/03/18/c-trick-load-embedded-resources-in-a-class-library/" rel="nofollow noreferrer">this post</a>:</p> <pre><code>browser.DocumentText=loadResourceText("myapp.index.html"); private string loadResourceText(string name) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream stream = assembly.GetManifestResourceStream(name); StreamReader streamReader = new StreamReader(stream); String myText = streamReader.ReadToEnd(); return myText; } </code></pre> <p>As good as that is, files referred to in the HTML - javascript, images like <code>&lt;img src="whatever.png"/&gt;</code> etc, don't work. I found similar questions <a href="https://stackoverflow.com/questions/72103/how-do-i-reference-a-local-resource-in-generated-html-in-winforms-webbrowser-co#273840">here</a> and <a href="https://stackoverflow.com/questions/153748/webbrowser-control-from-net-how-to-inject-javascript">here</a>, but neither is asking <em>exactly</em> what I mean, namely referring to <em>embedded</em> resources in the exe, not files. </p> <p>I tried <code>res://...</code> and using a <code>&lt;base href='..."</code> but neither seemed to work (though I may have not got it right).</p> <p>Perhaps (following my own suggestion on <a href="https://stackoverflow.com/questions/72103/how-do-i-reference-a-local-resource-in-generated-html-in-winforms-webbrowser-co#273840">this question</a>), using a little embedded C# webserver is the only way... but I would have thought there is some trick to get this going?</p> <p>Thanks!</p>
[ { "answer_id": 274530, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>I can see three ways to get this going:</p>\n\n<p>1: write the files you need to flat files in the temp area, navigate the <code>WebBrowser</code> to the html file, and delete them once the page has loaded</p>\n\n<p>2: as you say, an embedded web-server - herhaps <code>HttpListener</code> - but note that this uses HTTP.SYS, and so requires admin priveleges (or you need to <a href=\"https://stackoverflow.com/questions/169904/\">pre-open the port</a>)</p>\n\n<p>3: like 1, but using named-pipe server to avoid writing a file</p>\n\n<p>I have to say, the first is a lot simpler and requires zero configuration.</p>\n" }, { "answer_id": 1471460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>/// Hi try this may help u.\nprivate string CheckImages(ExtendedWebBrowser browser)\n{\n StringBuilder builderHTML = new StringBuilder(browser.Document.Body.Parent.OuterHtml);\n ProcessURLS(browser, builderHTML, \"img\", \"src\"); \n ProcessURLS(browser, builderHTML, \"link\", \"href\");\n // ext...\n\n return builderHTML.ToString();\n\n}\n\nprivate static void ProcessURLS(ExtendedWebBrowser browser, StringBuilder builderHTML, string strLink, string strHref)\n{\n for (int k = 0; k &lt; browser.Document.Body.Parent.GetElementsByTagName(strLink).Count; k++)\n {\n string strURL = browser.Document.Body.Parent.GetElementsByTagName(strLink)[k].GetAttribute(strHref);\n string strOuterHTML = browser.Document.Body.Parent.GetElementsByTagName(strLink)[k].OuterHtml;\n string[] strlist = strOuterHTML.Split(new string[] { \" \" }, StringSplitOptions.None);\n StringBuilder builder = new StringBuilder();\n for (int p = 0; p &lt; strlist.Length; p++)\n {\n if (strlist[p].StartsWith(strHref)) \n builder.Append (strlist[p].Contains(\"http\")? strlist[p] + \" \":\n (strURL.StartsWith(\"http\") ? strHref + \"=\" + strURL + \" \":\n strHref + \"= \" + \"http://xyz.com\" + strURL + \" \" )); \n else\n builder.Append(strlist[p] + \" \");\n }\n\n builderHTML.Replace(strOuterHTML, builder.ToString());\n }\n}\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25362/" ]
I'm writing a C# app using the WebBrowser control, and I want all content I display to come from embedded resources - not static local files, and not remote files. Setting the initial text of the control to an embedded HTML file works great with this code inspired by [this post](http://blog.topholt.com/2008/03/18/c-trick-load-embedded-resources-in-a-class-library/): ``` browser.DocumentText=loadResourceText("myapp.index.html"); private string loadResourceText(string name) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream stream = assembly.GetManifestResourceStream(name); StreamReader streamReader = new StreamReader(stream); String myText = streamReader.ReadToEnd(); return myText; } ``` As good as that is, files referred to in the HTML - javascript, images like `<img src="whatever.png"/>` etc, don't work. I found similar questions [here](https://stackoverflow.com/questions/72103/how-do-i-reference-a-local-resource-in-generated-html-in-winforms-webbrowser-co#273840) and [here](https://stackoverflow.com/questions/153748/webbrowser-control-from-net-how-to-inject-javascript), but neither is asking *exactly* what I mean, namely referring to *embedded* resources in the exe, not files. I tried `res://...` and using a `<base href='..."` but neither seemed to work (though I may have not got it right). Perhaps (following my own suggestion on [this question](https://stackoverflow.com/questions/72103/how-do-i-reference-a-local-resource-in-generated-html-in-winforms-webbrowser-co#273840)), using a little embedded C# webserver is the only way... but I would have thought there is some trick to get this going? Thanks!
I can see three ways to get this going: 1: write the files you need to flat files in the temp area, navigate the `WebBrowser` to the html file, and delete them once the page has loaded 2: as you say, an embedded web-server - herhaps `HttpListener` - but note that this uses HTTP.SYS, and so requires admin priveleges (or you need to [pre-open the port](https://stackoverflow.com/questions/169904/)) 3: like 1, but using named-pipe server to avoid writing a file I have to say, the first is a lot simpler and requires zero configuration.
274,319
<p>I know that I need to tell my UITextField to resign first responder when I want to dismis the keyboard, but I'm not sure how to know when the user has pressed the "Done" key on the keyboard. Is there a notification I can watch for?</p>
[ { "answer_id": 274325, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 6, "selected": false, "text": "<p>If you connect the DidEndOnExit event of the text field to an action (IBAction) in InterfaceBuilder, it will be messaged when the user dismisses the keyboard (with the return key) and the sender will be a reference to the UITextField that fired the event.</p>\n\n<p>For example:</p>\n\n<pre><code>-(IBAction)userDoneEnteringText:(id)sender\n{\n UITextField theField = (UITextField*)sender;\n // do whatever you want with this text field\n}\n</code></pre>\n\n<p>Then, in InterfaceBuilder, link the DidEndOnExit event of the text field to this action on your controller (or whatever you're using to link events from the UI). Whenever the user enters text and dismisses the text field, the controller will be sent this message.</p>\n" }, { "answer_id": 274354, "author": "kubi", "author_id": 28422, "author_profile": "https://Stackoverflow.com/users/28422", "pm_score": 9, "selected": true, "text": "<p>I set the delegate of the <code>UITextField</code> to my <code>ViewController</code> class. </p>\n\n<p>In that class I implemented this method as following:</p>\n\n<pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField {\n [textField resignFirstResponder];\n return NO;\n}\n</code></pre>\n" }, { "answer_id": 286109, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>kubi, thanks. Your code worked. Just to be explicit (for newbies like) as you say you have to set the <code>UITextField</code>'s <code>delegate</code> to be equal to the ViewController in which the text field resides. You can do this wherever you please. I chose the <code>viewDidLoad</code> method.</p>\n\n<pre><code>- (void)viewDidLoad \n{\n // sets the textField delegates to equal this viewController ... this allows for the keyboard to disappear after pressing done\n daTextField.delegate = self;\n}\n</code></pre>\n" }, { "answer_id": 813097, "author": "Hugo", "author_id": 99595, "author_profile": "https://Stackoverflow.com/users/99595", "pm_score": 5, "selected": false, "text": "<p>You can also create a method in your controller</p>\n\n<pre><code> -(IBAction)editingEnded:(id)sender{\n [sender resignFirstResponder]; \n}\n</code></pre>\n\n<p>and then in Connection Inspector in IB connect Event \"Did End On Exit\" to it.</p>\n" }, { "answer_id": 1501581, "author": "mobibob", "author_id": 157804, "author_profile": "https://Stackoverflow.com/users/157804", "pm_score": 2, "selected": false, "text": "<p>You will notice that the method \"textFieldShouldReturn\" provides the text-field object that has hit the DONE key. If you set the TAG you can switch on that text field. Or you can track and compare the object's pointer with some member value stored by its creator.</p>\n\n<p>My approach is like this for a self-study:</p>\n\n<pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField {\n NSLog(@\"%s\", __FUNCTION__);\n\n bool fDidResign = [textField resignFirstResponder];\n\n NSLog(@\"%s: did %resign the keyboard\", __FUNCTION__, fDidResign ? @\"\" : @\"not \");\n\n return fDidResign;\n}\n</code></pre>\n\n<p>Meanwhile, I put the \"validation\" test that denies the resignation follows. It is only for illustration, so if the user types NO! into the field, it will not dismiss. The behavior was as I wanted, but the sequence of output was not as I expected.</p>\n\n<pre><code>- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {\n NSLog(@\"%s\", __FUNCTION__);\n\n if( [[textField text] isEqualToString:@\"NO!\"] ) {\n NSLog(@\"%@\", textField.text);\n return NO;\n } else {\n return YES;\n }\n}\n</code></pre>\n\n<p>Following is my NSLog output for this denial followed by the acceptance. You will notice that I am returning the result of the resign, but I expected it to return FALSE to me to report back to the caller?! Other than that, it has the necessary behavior.</p>\n\n<pre>\n13.313 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]\n13.320 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldEndEditing:]\n13.327 StudyKbd[109:207] NO!\n13.333 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]: did resign the keyboard\n59.891 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]\n59.897 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldEndEditing:]\n59.917 StudyKbd[109:207] -[StudyKbdViewController doneEditText]: NO\n59.928 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]: did resign the keyboard\n</pre>\n" }, { "answer_id": 3517932, "author": "user415897", "author_id": 415897, "author_profile": "https://Stackoverflow.com/users/415897", "pm_score": 4, "selected": false, "text": "<p>Just add</p>\n\n<pre><code>[textField endEditing:YES];\n</code></pre>\n\n<p>where you want to disable keyboard and display the picker view.</p>\n" }, { "answer_id": 4445098, "author": "matt", "author_id": 341994, "author_profile": "https://Stackoverflow.com/users/341994", "pm_score": 4, "selected": false, "text": "<p>Here is a trick for getting automatic keyboard dismissal behavior with no code at all. In the nib, edit the First Responder proxy object in the Identity inspector, adding a new first responder action; let's call it <code>dummy:</code>. Now hook the Did End on Exit event of the text field to the <code>dummy:</code> action of the First Responder proxy object. That's it! Since the text field's Did End on Exit event now has an action–target pair, the text field automatically dismisses its keyboard when the user taps Return; and since there is no penalty for not finding a handler for a message sent up the responder chain, the app doesn't crash even though there is no implementation of <code>dummy:</code> anywhere.</p>\n" }, { "answer_id": 11142987, "author": "Ryan Bourne", "author_id": 1472792, "author_profile": "https://Stackoverflow.com/users/1472792", "pm_score": 2, "selected": false, "text": "<p>Here's what I had to do to get it to work, and I think is necessary for anyone with a Number Pad for a keyboard (or any other ones without a done button:</p>\n\n<ol>\n<li>I changed the UIView in the ViewController to a UIControl.</li>\n<li><p>I created a function called </p>\n\n<pre><code>-(IBAction)backgroundIsTapped:(id)sender\n</code></pre></li>\n</ol>\n\n<p>This was also defined in the .h file.</p>\n\n<p>After this, I linked to to the 'touch down' bit for the ViewController in Interface Builder.</p>\n\n<p>In the 'background is tapped' function, I put this:</p>\n\n<pre><code> [answerField resignFirstResponder];\n</code></pre>\n\n<p>Just remember to change 'answerField' to the name of the UITextField you want to remove the keyboard from (obviously make sure your UITextField is defined like below:)</p>\n\n<pre><code> IBOutlet UITextField * &lt;nameoftextfieldhere&gt;;\n</code></pre>\n\n<p>I know this topic probably died a long time ago... but I'm hoping this will help someone, somewhere!</p>\n" }, { "answer_id": 17281631, "author": "Gal Blank", "author_id": 662469, "author_profile": "https://Stackoverflow.com/users/662469", "pm_score": -1, "selected": false, "text": "<pre><code>textField.returnKeyType = UIReturnKeyDone;\n</code></pre>\n" }, { "answer_id": 18761422, "author": "pooja_chaudhary", "author_id": 2572580, "author_profile": "https://Stackoverflow.com/users/2572580", "pm_score": 0, "selected": false, "text": "<p>Create a function hidekeyboard and link it to the textfield in the .xib file and select DidEndOnExit </p>\n\n<pre><code>-(IBAction)Hidekeyboard \n{ \n textfield_name.resignFirstResponder; \n} \n</code></pre>\n" }, { "answer_id": 19950504, "author": "chandru", "author_id": 2955364, "author_profile": "https://Stackoverflow.com/users/2955364", "pm_score": 0, "selected": false, "text": "<p>If you have created the view using Interface Builder, Use the following\nJust create a method,</p>\n\n<pre><code>-(IBAction)dismissKeyboard:(id)sender\n{\n[sender resignFirstResponder];\n}\n</code></pre>\n\n<p>Just right click the text field in the view , and set the event as Did End on Exit, and wire it to the method \"dismissKeyboard\".</p>\n\n<p>The best guide for beginners is\n \"Head First iPhone and iPad Development, 2nd Edition\"</p>\n" }, { "answer_id": 21481747, "author": "Vineesh TP", "author_id": 1213364, "author_profile": "https://Stackoverflow.com/users/1213364", "pm_score": 0, "selected": false, "text": "<p>try this</p>\n\n<pre><code>- (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text\n{\n if ([text isEqualToString:@\"\\n\"]) {\n [textView resignFirstResponder];\n return NO;\n }\n return YES;\n}\n</code></pre>\n" }, { "answer_id": 25829644, "author": "jake", "author_id": 3092976, "author_profile": "https://Stackoverflow.com/users/3092976", "pm_score": 0, "selected": false, "text": "<pre><code>//====================================================\n// textFieldShouldReturn:\n//====================================================\n-(BOOL) textFieldShouldReturn:(UITextField*) textField { \n [textField resignFirstResponder];\n if(textField.returnKeyType != UIReturnKeyDone){\n [[textField.superview viewWithTag: self.nextTextField] becomeFirstResponder];\n }\n return YES;\n}\n</code></pre>\n" }, { "answer_id": 25863083, "author": "Metalhead1247", "author_id": 1837565, "author_profile": "https://Stackoverflow.com/users/1837565", "pm_score": 2, "selected": false, "text": "<p>You can also use </p>\n\n<pre><code> - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event \n {\n\n [self.yourTextField resignFirstResponder];\n\n }\n</code></pre>\n\n<p>Best one if You have many Uitextfields :</p>\n\n<pre><code>- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event\n { \n [self.view endEditing:YES];\n }\n</code></pre>\n" }, { "answer_id": 32447740, "author": "Moose", "author_id": 441197, "author_profile": "https://Stackoverflow.com/users/441197", "pm_score": 1, "selected": false, "text": "<p><strong>Here is a quite clean way to end edition with the Return Key or a touch in the background.</strong></p>\n\n<p>In Interface builder, embed your fields in a view of class UIFormView</p>\n\n<p>What does this class :</p>\n\n<ul>\n<li>Automatically attach itself as fields delegate ( Either awaked from nib, or added manually )</li>\n<li>Keep a reference on the current edited field</li>\n<li>Dismiss the keyboard on return or touch in the background</li>\n</ul>\n\n<p>Here is the code :</p>\n\n<p><em>Interface</em></p>\n\n<pre><code>#import &lt;UIKit/UIKit.h&gt;\n\n@interface UIFormView : UIView&lt;UITextFieldDelegate&gt;\n\n-(BOOL)textFieldValueIsValid:(UITextField*)textField;\n-(void)endEdit;\n\n@end\n</code></pre>\n\n<p><em>Implementation</em></p>\n\n<pre><code>#import \"UIFormView.h\"\n\n@implementation UIFormView\n{\n UITextField* currentEditingTextField;\n}\n\n// Automatically register fields\n\n-(void)addSubview:(UIView *)view\n{\n [super addSubview:view];\n if ([view isKindOfClass:[UITextField class]]) {\n if ( ![(UITextField*)view delegate] ) [(UITextField*)view setDelegate:self];\n }\n}\n\n// UITextField Protocol\n\n-(void)textFieldDidBeginEditing:(UITextField *)textField\n{\n currentEditingTextField = textField;\n}\n\n-(void)textFieldDidEndEditing:(UITextField *)textField\n{\n currentEditingTextField = NULL;\n}\n\n-(void)touchesBegan:(NSSet&lt;UITouch *&gt; *)touches withEvent:(UIEvent *)event\n{\n [self endEdit];\n}\n\n- (BOOL)textFieldShouldReturn:(UITextField *)textField\n{\n if ([self textFieldValueIsValid:textField]) {\n [self endEdit];\n return YES;\n } else {\n return NO;\n }\n}\n\n// Own functions\n\n-(void)endEdit\n{\n if (currentEditingTextField) {\n [currentEditingTextField endEditing:YES];\n currentEditingTextField = NULL;\n }\n}\n\n\n// Override this in your subclass to handle eventual values that may prevent validation.\n\n-(BOOL)textFieldValueIsValid:(UITextField*)textField\n{\n return YES;\n}\n\n@end\n</code></pre>\n\n<ul>\n<li><p>By subclassing the form and overriding the\n<code>textFieldValueIsValid:</code> method, you\ncan avoid end of edition if the value is not correct for the given\nfield.</p></li>\n<li><p>If a field has a delegate set in Interface Builder, then the form does not change it. I don't see many reasons to set a different delegate to a particular field, but why not…</p></li>\n</ul>\n\n<p>There is many ways to improve this form view class - Attach a delegate, do some layout, handle when the keyboards covers a field ( using the currentEditingTextField frame ), automatically start edition for the next field, ...</p>\n\n<p>I personally keep it in my framework, and always subclass it to add features, it is quite often useful \"as-is\".</p>\n\n<p>I hope it will helps. Cheers all</p>\n" }, { "answer_id": 33496692, "author": "Abhimanyu Rathore", "author_id": 3811649, "author_profile": "https://Stackoverflow.com/users/3811649", "pm_score": 1, "selected": false, "text": "<p>if you want all editing of in a UIViewController you can use. </p>\n\n<pre><code>[[self view]endEditing:YES];\n</code></pre>\n\n<p>and if you want dismiss a perticular UITextField keyboard hide then use.</p>\n\n<p>1.add delegate in your viewcontroller.h</p>\n\n<pre><code>&lt;UITextFieldDelegate&gt;\n</code></pre>\n\n<ol start=\"2\">\n<li><p>make delegation unable to your textfield .</p>\n\n<p>self.yourTextField.delegate = self;</p></li>\n<li><p>add this method in to your viewcontroller. </p>\n\n<p>-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{\n[textField resignFirstResponder];\nreturn YES;}</p></li>\n</ol>\n" }, { "answer_id": 37105867, "author": "Safin Ahmed", "author_id": 4023670, "author_profile": "https://Stackoverflow.com/users/4023670", "pm_score": 4, "selected": false, "text": "<p>In Swift you can write an IBAction in the Controller and set the <strong>Did End On Exit</strong> event of the text field to that action</p>\n\n<pre><code>@IBAction func returnPressed(sender: UITextField) {\n self.view.endEditing(true)\n}\n</code></pre>\n" }, { "answer_id": 41509280, "author": "Burf2000", "author_id": 369313, "author_profile": "https://Stackoverflow.com/users/369313", "pm_score": 1, "selected": false, "text": "<p>Anyone looking for <strong>Swift 3</strong></p>\n\n<p>1) Make sure your <strong>UITextField's Delegate</strong> is wired to your ViewController in the Storyboard</p>\n\n<p>2) Implement <strong>UITextFieldDelegate</strong> in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )</p>\n\n<p>3) Use the delegate method below</p>\n\n<pre><code>func textFieldShouldReturn(textField: UITextField) -&gt; Bool { \n textField.resignFirstResponder() \nreturn false }\n</code></pre>\n" }, { "answer_id": 46044623, "author": "Artem Deviatov", "author_id": 3110071, "author_profile": "https://Stackoverflow.com/users/3110071", "pm_score": -1, "selected": false, "text": "<p>Swift 3, iOS 9+</p>\n\n<p><code>@IBAction private func noteFieldDidEndOnExit(_ sender: UITextField) {}</code></p>\n\n<p>UPD: It still works fine for me. I think guy that devoted this answer just didn't understand that he needs to bind this action to the UITextField at the storyboard.</p>\n" }, { "answer_id": 48002031, "author": "Tanjima Kothiya", "author_id": 9135954, "author_profile": "https://Stackoverflow.com/users/9135954", "pm_score": 1, "selected": false, "text": "<p>Programmatically set the delegate of the UITextField in swift 3</p>\n\n<p><strong>Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )</strong></p>\n\n<pre><code> lazy var firstNameTF: UITextField = {\n\n let firstname = UITextField()\n firstname.placeholder = \"FirstName\"\n firstname.frame = CGRect(x:38, y: 100, width: 244, height: 30)\n firstname.textAlignment = .center\n firstname.borderStyle = UITextBorderStyle.roundedRect\n firstname.keyboardType = UIKeyboardType.default\n firstname.delegate = self\n return firstname\n}()\n\nlazy var lastNameTF: UITextField = {\n\n let lastname = UITextField()\n lastname.placeholder = \"LastName\"\n lastname.frame = CGRect(x:38, y: 150, width: 244, height: 30)\n lastname.textAlignment = .center\n lastname.borderStyle = UITextBorderStyle.roundedRect\n lastname.keyboardType = UIKeyboardType.default\n lastname.delegate = self\n return lastname\n}()\n\nlazy var emailIdTF: UITextField = {\n\n let emailid = UITextField()\n emailid.placeholder = \"EmailId\"\n emailid.frame = CGRect(x:38, y: 200, width: 244, height: 30)\n emailid.textAlignment = .center\n emailid.borderStyle = UITextBorderStyle.roundedRect\n emailid.keyboardType = UIKeyboardType.default\n emailid.delegate = self\n return emailid\n}()\n</code></pre>\n\n<p>// Mark:- handling delegate textField..</p>\n\n<pre><code>override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {\n view.endEditing(true)\n}\n\nfunc textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {\n\n if textField == firstNameTF {\n\n lastNameTF.becomeFirstResponder()\n }\n\n else if textField == lastNameTF {\n\n emailIdTF.becomeFirstResponder()\n }\n else {\n view.emailIdTF(true)\n }\n return true\n}\n</code></pre>\n" }, { "answer_id": 54823250, "author": "Prakhar Prakash Bhardwaj", "author_id": 10739965, "author_profile": "https://Stackoverflow.com/users/10739965", "pm_score": 0, "selected": false, "text": "<p>This is how I dismiss the keyboard in Swift 4.2 and it works for me:</p>\n\n<pre><code> override func viewDidLoad() {\n super.viewDidLoad()\n\n let tap = UITapGestureRecognizer(target: self, action: \n #selector(dismissKeyboard))\n\n view.addGestureRecognizer(tap)\n }\n\n @objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {\n numberField.resignFirstResponder()\n }\n</code></pre>\n" }, { "answer_id": 56944913, "author": "Gulsan Borbhuiya", "author_id": 8593710, "author_profile": "https://Stackoverflow.com/users/8593710", "pm_score": 4, "selected": false, "text": "<p><code>Swift 4.2</code> and It will work 100%</p>\n\n<pre><code>import UIKit\n\nclass ViewController: UIViewController, UITextFieldDelegate {\n\n @IBOutlet weak var textField: UITextField!\n\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n self.textField.delegate = self\n\n }\n\n // hide key board when the user touches outside keyboard\n\n override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {\n self.view.endEditing(true)\n }\n\n // user presses return key\n\n func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {\n textField.resignFirstResponder()\n return true\n }\n\n}\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28422/" ]
I know that I need to tell my UITextField to resign first responder when I want to dismis the keyboard, but I'm not sure how to know when the user has pressed the "Done" key on the keyboard. Is there a notification I can watch for?
I set the delegate of the `UITextField` to my `ViewController` class. In that class I implemented this method as following: ``` - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return NO; } ```
274,344
<p>When you lock an object is that object locked throughout the whole application?</p> <p>For Example, this snippet from C# 3.0 in a Nutshell Section 19.6.1 "Thread Safety and .NET Framework Types":</p> <pre><code>static void AddItems( ) { for (int i = 0; i &lt; 100; i++) lock (list) list.Add ("Item " + list.Count); string[] items; lock (list) items = list.ToArray( ); foreach (string s in items) Console.WriteLine (s); } </code></pre> <p>Does the first lock:</p> <pre><code>lock (list) list.Add ("Item " + list.Count); </code></pre> <p>prevent another thread from accessing:</p> <pre><code>lock (list) items = list.ToArray( ); </code></pre> <p>or can both be executed at the same time?</p> <p>And does the CLR automatically make your static methods thread safe? Or is that up to the developer?</p> <p>Thanks, John</p>
[ { "answer_id": 274347, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "<p>The CLR doesn't automatically make static methods thread-safe; you must do it yourself.</p>\n\n<p>lock(list) uses that object as a lock, so if a different thread reaches another point with lock(list) (with the same 'list' object), the other thread will block until the first thread releases the lock.</p>\n\n<p>To be clear, lock(foo) doesn't \"lock the foo object\", rather it acquires the lock associated with the foo object so that the critical section (the statement in the construct \"lock(o) stmt\") runs only when the current thread has acquired the lock.</p>\n" }, { "answer_id": 274357, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": true, "text": "<pre><code>class UsefulStuff {\n object _TheLock = new object { };\n public void UsefulThingNumberOne() {\n lock(_TheLock) {\n //CodeBlockA\n }\n }\n public void UsefulThingNumberTwo() {\n lock(_TheLock) {\n //CodeBlockB\n }\n }\n}\n</code></pre>\n\n<p><code>CodeBlockA</code> and <code>CodeBlockB</code> are prevented from executing at the same time in different threads, because they are both locked on the same object instance <code>_TheLock</code>.</p>\n\n<p>The methods on <code>_TheLock</code> itself are completely unaffected.</p>\n" }, { "answer_id": 274564, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 3, "selected": false, "text": "<p>One other thing to note is that static constructors ARE executed in a threadsafe way by the runtime. If you are creating a singleton and declare it as:</p>\n\n<pre><code>public class Foo\n{\n private static Foo instance = new Foo();\n\n public static Foo Instance\n {\n get { return instance; }\n }\n}\n</code></pre>\n\n<p>Then it will be threadsafe. If however, you instantiate a new Foo <strong>inside</strong> the Instance getter, then you would need to write your own thread safety (ie. lock an object)</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19490/" ]
When you lock an object is that object locked throughout the whole application? For Example, this snippet from C# 3.0 in a Nutshell Section 19.6.1 "Thread Safety and .NET Framework Types": ``` static void AddItems( ) { for (int i = 0; i < 100; i++) lock (list) list.Add ("Item " + list.Count); string[] items; lock (list) items = list.ToArray( ); foreach (string s in items) Console.WriteLine (s); } ``` Does the first lock: ``` lock (list) list.Add ("Item " + list.Count); ``` prevent another thread from accessing: ``` lock (list) items = list.ToArray( ); ``` or can both be executed at the same time? And does the CLR automatically make your static methods thread safe? Or is that up to the developer? Thanks, John
``` class UsefulStuff { object _TheLock = new object { }; public void UsefulThingNumberOne() { lock(_TheLock) { //CodeBlockA } } public void UsefulThingNumberTwo() { lock(_TheLock) { //CodeBlockB } } } ``` `CodeBlockA` and `CodeBlockB` are prevented from executing at the same time in different threads, because they are both locked on the same object instance `_TheLock`. The methods on `_TheLock` itself are completely unaffected.
274,348
<p>In my small WPF project, I have a <code>TabControl</code> with three tabs. On each tab is a <code>ListBox</code>. This project keeps track of groceries we need to buy. (No, it's not homework, it's for my wife.) So I have a list of <code>ShoppingListItem</code>s, each of which has a <code>Name</code> and a <code>Needed</code> property: <code>true</code> when we need the item, and <code>false</code> after we buy it.</p> <p>So the three tabs are All, Bought, and Needed. They should all point to the same <code>ShoppingListItemCollection</code> (which inherits from <code>ObservableCollection&lt;ShoppingListItem&gt;</code>). But Bought should only show the items where Needed is false, and Needed should only show items where Needed is true. (The All tab has checkboxes on the items.)</p> <p>This doesn't seem <em>that</em> hard, but after a couple hours, I'm no closer to figuring this out. It seems like a CollectionView or CollectionViewSource is what I need, but I can't get anything to happen; I check and uncheck the boxes on the All tab, and the items on the other two tabs just sit there staring at me.</p> <p>Any ideas?</p>
[ { "answer_id": 274421, "author": "steve", "author_id": 32103, "author_profile": "https://Stackoverflow.com/users/32103", "pm_score": 0, "selected": false, "text": "<p>Here are a couple of ideas:</p>\n\n<ol>\n<li>When tabs Bought and Needed load, filter them yourself by creating new collections with the items you want, or</li>\n<li>when tabs Bought and Needed load, override the list item databind and toggle visability based on Needed</li>\n</ol>\n" }, { "answer_id": 274458, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 2, "selected": false, "text": "<p>You can use a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.aspx\" rel=\"nofollow noreferrer\">CollectionViewSource</a> to reuse the original collection with a filter. </p>\n\n<pre><code>&lt;Window.Resources&gt;\n &lt;CollectionViewSource x:Key=\"NeededItems\" Source=\"{Binding Items}\" Filter=\"NeededCollectionViewSource_Filter\" /&gt;\n &lt;CollectionViewSource x:Key=\"BoughtItems\" Source=\"{Binding Items}\" Filter=\"BoughtCollectionViewSource_Filter\" /&gt;\n&lt;/Window.Resources&gt;\n\n&lt;TabControl&gt;\n &lt;TabItem Header=\"All\"&gt;\n &lt;ListBox DisplayMemberPath=\"Name\" ItemsSource=\"{Binding Items}\" /&gt;\n &lt;/TabItem&gt;\n &lt;TabItem Header=\"Bought\"&gt;\n &lt;ListBox DisplayMemberPath=\"Name\" ItemsSource=\"{Binding Source={StaticResource BoughtItems}}\" /&gt;\n &lt;/TabItem&gt;\n &lt;TabItem Header=\"Needed\"&gt;\n &lt;ListBox DisplayMemberPath=\"Name\" ItemsSource=\"{Binding Source={StaticResource NeededItems}}\" /&gt;\n &lt;/TabItem&gt;\n&lt;/TabControl&gt;\n</code></pre>\n\n<p>Some code behind is required for the filter.</p>\n\n<pre><code>private void NeededCollectionViewSource_Filter(object sender, FilterEventArgs e)\n{\n e.Accepted = ((ShoppingListItem) e.Item).Needed;\n}\n\nprivate void BoughtCollectionViewSource_Filter(object sender, FilterEventArgs e)\n{\n e.Accepted = !((ShoppingListItem) e.Item).Needed;\n}\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
In my small WPF project, I have a `TabControl` with three tabs. On each tab is a `ListBox`. This project keeps track of groceries we need to buy. (No, it's not homework, it's for my wife.) So I have a list of `ShoppingListItem`s, each of which has a `Name` and a `Needed` property: `true` when we need the item, and `false` after we buy it. So the three tabs are All, Bought, and Needed. They should all point to the same `ShoppingListItemCollection` (which inherits from `ObservableCollection<ShoppingListItem>`). But Bought should only show the items where Needed is false, and Needed should only show items where Needed is true. (The All tab has checkboxes on the items.) This doesn't seem *that* hard, but after a couple hours, I'm no closer to figuring this out. It seems like a CollectionView or CollectionViewSource is what I need, but I can't get anything to happen; I check and uncheck the boxes on the All tab, and the items on the other two tabs just sit there staring at me. Any ideas?
You can use a [CollectionViewSource](http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.aspx) to reuse the original collection with a filter. ``` <Window.Resources> <CollectionViewSource x:Key="NeededItems" Source="{Binding Items}" Filter="NeededCollectionViewSource_Filter" /> <CollectionViewSource x:Key="BoughtItems" Source="{Binding Items}" Filter="BoughtCollectionViewSource_Filter" /> </Window.Resources> <TabControl> <TabItem Header="All"> <ListBox DisplayMemberPath="Name" ItemsSource="{Binding Items}" /> </TabItem> <TabItem Header="Bought"> <ListBox DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource BoughtItems}}" /> </TabItem> <TabItem Header="Needed"> <ListBox DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource NeededItems}}" /> </TabItem> </TabControl> ``` Some code behind is required for the filter. ``` private void NeededCollectionViewSource_Filter(object sender, FilterEventArgs e) { e.Accepted = ((ShoppingListItem) e.Item).Needed; } private void BoughtCollectionViewSource_Filter(object sender, FilterEventArgs e) { e.Accepted = !((ShoppingListItem) e.Item).Needed; } ```
274,360
<p>Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn't a built-in function to do this directly. What options do I have (if any)?</p>
[ { "answer_id": 274363, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": true, "text": "<pre><code>interface IInterface\n{\n}\n\nclass TheClass implements IInterface\n{\n}\n\n$cls = new TheClass();\nif ($cls instanceof IInterface) {\n echo \"yes\";\n}\n</code></pre>\n\n<p>You can use the \"instanceof\" operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface.</p>\n" }, { "answer_id": 274476, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 6, "selected": false, "text": "<p>nlaq points out that <code>instanceof</code> can be used to test if the object is an instance of a class that implements an interface.</p>\n\n<p>But <code>instanceof</code> doesn't distinguish between a class type and an interface. You don't know if the object is a <em>class</em> that happens to be called <code>IInterface</code>.</p>\n\n<p>You can also use the reflection API in PHP to test this more specifically:</p>\n\n<pre><code>$class = new ReflectionClass('TheClass');\nif ($class-&gt;implementsInterface('IInterface'))\n{\n print \"Yep!\\n\";\n}\n</code></pre>\n\n<p>See <a href=\"http://php.net/manual/en/book.reflection.php\" rel=\"noreferrer\">http://php.net/manual/en/book.reflection.php</a></p>\n" }, { "answer_id": 12031401, "author": "Jess Telford", "author_id": 473961, "author_profile": "https://Stackoverflow.com/users/473961", "pm_score": 7, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/users/8331/therefromhere\">therefromhere</a> points out, you can use <code>class_implements()</code>. Just as with Reflection, this allows you to specify the class name as a string and doesn't require an instance of the class:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>interface IInterface\n{\n}\n\nclass TheClass implements IInterface\n{\n}\n\n$interfaces = class_implements('TheClass');\n\nif (isset($interfaces['IInterface'])) {\n echo \"Yes!\";\n}\n</code></pre>\n\n<p><code>class_implements()</code> is part of the SPL extension.</p>\n\n<p>See: <a href=\"http://php.net/manual/en/function.class-implements.php\" rel=\"noreferrer\">http://php.net/manual/en/function.class-implements.php</a></p>\n\n<h1>Performance Tests</h1>\n\n<p>Some simple performance tests show the costs of each approach:</p>\n\n<h2>Given an instance of an object</h2>\n\n<pre>\nObject construction outside the loop (100,000 iterations)\n ____________________________________________\n| class_implements | Reflection | instanceOf |\n|------------------|------------|------------|\n| 140 ms | 290 ms | 35 ms |\n'--------------------------------------------'\n\nObject construction inside the loop (100,000 iterations)\n ____________________________________________\n| class_implements | Reflection | instanceOf |\n|------------------|------------|------------|\n| 182 ms | 340 ms | 83 ms | Cheap Constructor\n| 431 ms | 607 ms | 338 ms | Expensive Constructor\n'--------------------------------------------'\n</pre>\n\n<h2>Given only a class name</h2>\n\n<pre>\n100,000 iterations\n ____________________________________________\n| class_implements | Reflection | instanceOf |\n|------------------|------------|------------|\n| 149 ms | 295 ms | N/A |\n'--------------------------------------------'\n</pre>\n\n<p>Where the expensive __construct() is:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function __construct() {\n $tmp = array(\n 'foo' =&gt; 'bar',\n 'this' =&gt; 'that'\n ); \n\n $in = in_array('those', $tmp);\n}\n</code></pre>\n\n<p>These tests are based on <a href=\"http://pastebin.com/2xftNXip\" rel=\"noreferrer\">this simple code</a>.</p>\n" }, { "answer_id": 21826939, "author": "d.raev", "author_id": 1621821, "author_profile": "https://Stackoverflow.com/users/1621821", "pm_score": 5, "selected": false, "text": "<p>Just to help future searches <a href=\"http://bg2.php.net/is_subclass_of\" rel=\"noreferrer\">is_subclass_of</a> is also a good variant (for PHP 5.3.7+):</p>\n\n<pre><code>if (is_subclass_of($my_class_instance, 'ISomeInterfaceName')){\n echo 'I can do it!';\n}\n</code></pre>\n" }, { "answer_id": 32307868, "author": "Starx", "author_id": 295264, "author_profile": "https://Stackoverflow.com/users/295264", "pm_score": 3, "selected": false, "text": "<p>You can also do the following</p>\n\n<pre><code>public function yourMethod(YourInterface $objectSupposedToBeImplementing) {\n //.....\n}\n</code></pre>\n\n<p>It will throw an recoverable error if the <code>$objectSupposedToBeImplementing</code> does not implement <code>YourInterface</code> Interface.</p>\n" }, { "answer_id": 60517838, "author": "SirPilan", "author_id": 9968486, "author_profile": "https://Stackoverflow.com/users/9968486", "pm_score": 4, "selected": false, "text": "<h1>Update</h1>\n<p>The <code>is_a</code> <a href=\"https://www.php.net/manual/en/function.is-a.php\" rel=\"noreferrer\">function</a> is missing here as alternative.</p>\n<p>I did some performance tests to check which of the stated ways is the most performant.</p>\n<h1>Results over 100k iterations</h1>\n<pre><code> instanceof [object] took 7.67 ms | + 0% | ..........\n is_a [object] took 12.30 ms | + 60% | ................\n is_a [class] took 17.43 ms | +127% | ......................\nclass_implements [object] took 28.37 ms | +270% | ....................................\n reflection [class] took 34.17 ms | +346% | ............................................\n</code></pre>\n<p>Added some dots to actually &quot;feel&quot; see the difference.</p>\n<p>Generated by this: <a href=\"https://3v4l.org/8Cog7\" rel=\"noreferrer\">https://3v4l.org/8Cog7</a></p>\n<h1>Conclusion</h1>\n<p>In case you have an <em>object</em> to check, use <code>instanceof</code> like mentioned in the accepted answer.</p>\n<p>In case you have a <em>class</em> to check, use <code>is_a</code>.</p>\n<h1>Bonus</h1>\n<p>Given the case you want to instantiate a class based on an interface you require it to have, it is more preformant to use <code>is_a</code>. There is only one exception - when the constructor is empty.</p>\n<p>Example:\n<code>is_a(&lt;className&gt;, &lt;interfaceName&gt;, true);</code></p>\n<p>It will return <code>bool</code>. The third parameter &quot;<a href=\"https://www.php.net/manual/en/function.is-a.php#refsect1-function.is-a-parameters\" rel=\"noreferrer\">allow_string</a>&quot; allows it to check class names <strong>without</strong> instantiating the class.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn't a built-in function to do this directly. What options do I have (if any)?
``` interface IInterface { } class TheClass implements IInterface { } $cls = new TheClass(); if ($cls instanceof IInterface) { echo "yes"; } ``` You can use the "instanceof" operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface.
274,361
<p>ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that does this operation: </p> <pre><code>strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) </code></pre> <p>I get this error: </p> <blockquote> <p>chr() arg not in range(256)</p> </blockquote> <p>If I try to encode the string as latin-1 first I get this error:</p> <blockquote> <p>'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)</p> </blockquote> <p>I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!</p>
[ { "answer_id": 274403, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<p>Your first error 'chr() arg not in range(256)' probably means you have underflowed the value, because chr cannot take negative numbers. I don't know what the encryption algorithm is supposed to do when the inputcounter + 33 is more than the actual character representation, you'll have to check what to do in that case.</p>\n\n<p>About the second error. you must decode() and not encode() a regular string object to get a proper representation of your data. encode() takes a unicode object (those starting with u') and generates a regular string to be output or written to a file. decode() takes a string object and generate a unicode object with the corresponding code points. This is done with the unicode() call when generated from a string object, you could also call a.decode('latin-1') instead.</p>\n\n<pre><code>&gt;&gt;&gt; a = '\\222\\222\\223\\225'\n&gt;&gt;&gt; u = unicode(a,'latin-1')\n&gt;&gt;&gt; u\nu'\\x92\\x92\\x93\\x95'\n&gt;&gt;&gt; print u.encode('utf-8')\nÂÂÂÂ\n&gt;&gt;&gt; print u.encode('utf-16')\nÿþ\n&gt;&gt;&gt; print u.encode('latin-1')\n\n&gt;&gt;&gt; for c in u:\n... print chr(ord(c) - 3 - 0 -30)\n...\nq\nq\nr\nt\n&gt;&gt;&gt; for c in u:\n... print chr(ord(c) - 3 -200 -30)\n...\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 2, in &lt;module&gt;\nValueError: chr() arg not in range(256)\n</code></pre>\n" }, { "answer_id": 274412, "author": "jacob", "author_id": 35697, "author_profile": "https://Stackoverflow.com/users/35697", "pm_score": 0, "selected": false, "text": "<p>Well its because its been encrypted with some terrible scheme that just changes the ord() of the character by some request, so the string coming out of the database has been encrypted and this decrypts it. What you supplied above does not seem to work. In the database it is latin-1, django converts it to unicode, but I cannot pass it to the function as unicode, but when i try and encode it to latin-1 i see that error.</p>\n" }, { "answer_id": 274440, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>As Vinko notes, Latin-1 or ISO 8859-1 doesn't have printable characters for the octal string you quote. According to my notes for 8859-1, \"C1 Controls (0x80 - 0x9F) are from ISO/IEC 6429:1992. It does not define names for 80, 81, or 99\". The code point names are as Vinko lists them:</p>\n\n<pre><code>\\222 = 0x92 =&gt; PRIVATE USE TWO\n\\223 = 0x93 =&gt; SET TRANSMIT STATE\n\\225 = 0x95 =&gt; MESSAGE WAITING\n</code></pre>\n\n<p>The correct UTF-8 encoding of those is (Unicode, binary, hex):</p>\n\n<pre><code>U+0092 = %11000010 %10010010 = 0xC2 0x92\nU+0093 = %11000010 %10010011 = 0xC2 0x93\nU+0095 = %11000010 %10010101 = 0xC2 0x95\n</code></pre>\n\n<p>The LATIN SMALL LETTER A WITH CIRCUMFLEX is ISO 8859-1 code 0xE2 and hence Unicode U+00E2; in UTF-8, that is %11000011 %10100010 or 0xC3 0xA2.</p>\n\n<p>The CENT SIGN is ISO 8859-1 code 0xA2 and hence Unicode U+00A2; in UTF-8, that is %11000011 %10000010 or 0xC3 0x82.</p>\n\n<p>So, whatever else you are seeing, you do not seem to be seeing a UTF-8 encoding of ISO 8859-1. All else apart, you are seeing but 5 bytes where you would have to see 8.</p>\n\n<p><em>Added</em>:\nThe previous part of the answer addresses the 'UTF-8 encoding' claim, but ignores the rest of the question, which says:</p>\n\n<pre><code>Now I need to pass the string into a function that does this operation:\n\n strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30)\n\nI get this error: chr() arg not in range(256). If I try to encode the\nstring as Latin-1 first I get this error: 'latin-1' codec can't encode\ncharacters in position 0-3: ordinal not in range(256).\n</code></pre>\n\n<p>You don't actually show us how intCounter is defined, but if it increments gently per character, sooner or later '<code>ord(c) - 3 - intCounter - 30</code>' is going to be negative (and, by the way, why not combine the constants and use '<code>ord(c) - intCounter - 33</code>'?), at which point, <code>chr()</code> is likely to complain. You would need to add 256 if the value is negative, or use a modulus operation to ensure you have a positive value between 0 and 255 to pass to <code>chr()</code>. Since we can't see how intCounter is incremented, we can't tell if it cycles from 0 to 255 or whether it increases monotonically. If the latter, then you need an expression such as:</p>\n\n<pre><code>chr(mod(ord(c) - mod(intCounter, 255) + 479, 255))\n</code></pre>\n\n<p>where 256 - 33 = 223, of course, and 479 = 256 + 223. This guarantees that the value passed to <code>chr()</code> is positive and in the range 0..255 for any input character c and any value of intCounter (and, because the <code>mod()</code> function never gets a negative argument, it also works regardless of how <code>mod()</code> behaves when its arguments are negative).</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35697/" ]
ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that does this operation: ``` strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) ``` I get this error: > > chr() arg not in range(256) > > > If I try to encode the string as latin-1 first I get this error: > > 'latin-1' codec can't encode characters in position 0-3: ordinal not > in range(256) > > > I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!
Your first error 'chr() arg not in range(256)' probably means you have underflowed the value, because chr cannot take negative numbers. I don't know what the encryption algorithm is supposed to do when the inputcounter + 33 is more than the actual character representation, you'll have to check what to do in that case. About the second error. you must decode() and not encode() a regular string object to get a proper representation of your data. encode() takes a unicode object (those starting with u') and generates a regular string to be output or written to a file. decode() takes a string object and generate a unicode object with the corresponding code points. This is done with the unicode() call when generated from a string object, you could also call a.decode('latin-1') instead. ``` >>> a = '\222\222\223\225' >>> u = unicode(a,'latin-1') >>> u u'\x92\x92\x93\x95' >>> print u.encode('utf-8') ÂÂÂÂ >>> print u.encode('utf-16') ÿþ >>> print u.encode('latin-1') >>> for c in u: ... print chr(ord(c) - 3 - 0 -30) ... q q r t >>> for c in u: ... print chr(ord(c) - 3 -200 -30) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError: chr() arg not in range(256) ```
274,375
<p>I want to setup a statistics monitoring platform to watch a specific service, but I'm not quiet sure how to go about it. Processing the intercepted data isn't my concern, just how to go about it. One idea was to setup a proxy between the client application and the service so that all TCP traffic went first to my proxy, the proxy would then delegate the intercepted messages to an awaiting thread/fork to pass the message on and recieve the results. The other was to try and sniff the traffic between client &amp; service.</p> <p>My primary goal is to avoid any serious loss in transmission speed between client &amp; application but get 100% complete communications between client &amp; service.</p> <p>Environment: UBuntu 8.04</p> <p>Language: c/c++</p> <p>In the background I was thinking of using a sqlite DB running completely in memory or a 20-25MB memcache dameon slaved to my process.</p> <p>Update: Specifically I am trying to track the usage of keys for a memcache daemon, storing the # of sets/gets success/fails on the key. The idea is that most keys have some sort of separating character [`|_-#] to create a sort of namespace. The idea is to step in between the daemon and the client, split the keys apart by a configured separator and record statistics on them. </p>
[ { "answer_id": 274393, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "<p>Exactly what are you trying to track? If you want a simple count of packets or bytes, or basic header information, then <code>iptables</code> will record that for you:</p>\n\n<pre><code>iptables -I INPUT -p tcp -d $HOST_IP --dport $HOST_PORT -j LOG $LOG_OPTIONS\n</code></pre>\n\n<p>If you need more detailed information, look into the <code>iptables ULOG</code> target, which sends each packet to userspace for analysis.</p>\n\n<p>See <a href=\"http://www.netfilter.org\" rel=\"nofollow noreferrer\">http://www.netfilter.org</a> for <em>very</em> thorough docs.</p>\n" }, { "answer_id": 274481, "author": "derobert", "author_id": 27727, "author_profile": "https://Stackoverflow.com/users/27727", "pm_score": 1, "selected": true, "text": "<p>You didn't mention one approach: you could modify memcached or your client to record the statistics you need. This is probably the easiest and cleanest approach.</p>\n\n<p>Between the proxy and the libpcap approach, there are a couple of tradeoffs:</p>\n\n<pre><code>- If you do the packet capture approach, you have to reassemble the TCP\n streams into something usable yourself. OTOH, if your monitor program\n gets bogged down, it'll just lose some packets, it won't break the cache.\n Same if it crashes. You also don't have to reconfigure anything; packet\n capture is transparent. \n\n- If you do the proxy approach, the kernel handles all the TCP work for\n you. You'll never lose requests. But if your monitor bogs down, it'll bog\n down the app. And if your monitor crashes, it'll break caching. You\n probably will have to reconfigure your app and/or memcached servers so\n that the connections go through the proxy.\n</code></pre>\n\n<p>In short, the proxy will probably be easier to code, but implementing it may be a royal pain, and it had better be perfect or its taking down your caching. Changing the app or memcached seems like the sanest approach to me.</p>\n\n<p>BTW: You have looked at memcached's built-in statistics reporting? I don't think its granular enough for what you want, but if you haven't seen it, take a look before doing actual work :-D</p>\n" }, { "answer_id": 274722, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 0, "selected": false, "text": "<p>iptables provides <strong>libipq</strong>, a userspace packet queuing library. From the manpage:</p>\n\n<blockquote>\n <p>Netfilter provides a mechanism for\n passing packets out of the stack for\n queueing to userspace, then receiving\n these packets back into the kernel\n with a verdict specifying what to do\n with the packets (such as ACCEPT or\n DROP). These packets may also be\n modified in userspace prior to\n reinjection back into the kernel.</p>\n</blockquote>\n\n<p>By setting up tailored <strong>iptables</strong> rules that forward packets to libipq, in addition to specifying the verdict for them, it's possible to do packet inspection for statistics analysis.</p>\n\n<p>Another viable option is manually sniff packets by means of libpcap or PF_PACKET socket with the socket-filter support.</p>\n" }, { "answer_id": 275288, "author": "Krunch", "author_id": 35831, "author_profile": "https://Stackoverflow.com/users/35831", "pm_score": 1, "selected": false, "text": "<p>If you want to go the sniffer way, it might be easier to use tcpflow instead of tcpdump or libpcap. tcpflow will only output TCP payload so you don't need to care about reassembling the data stream yourself. If you prefer using a library instead of gluing a bunch of programs together you might be interested in libnids.</p>\n\n<p>libnids and tcpflow are also available on other Unix flavours and do not restrict you to just Linux (contrarily to iptables).</p>\n\n<p><a href=\"http://www.circlemud.org/~jelson/software/tcpflow/\" rel=\"nofollow noreferrer\">http://www.circlemud.org/~jelson/software/tcpflow/</a>\n<a href=\"http://libnids.sourceforge.net/\" rel=\"nofollow noreferrer\">http://libnids.sourceforge.net/</a></p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908/" ]
I want to setup a statistics monitoring platform to watch a specific service, but I'm not quiet sure how to go about it. Processing the intercepted data isn't my concern, just how to go about it. One idea was to setup a proxy between the client application and the service so that all TCP traffic went first to my proxy, the proxy would then delegate the intercepted messages to an awaiting thread/fork to pass the message on and recieve the results. The other was to try and sniff the traffic between client & service. My primary goal is to avoid any serious loss in transmission speed between client & application but get 100% complete communications between client & service. Environment: UBuntu 8.04 Language: c/c++ In the background I was thinking of using a sqlite DB running completely in memory or a 20-25MB memcache dameon slaved to my process. Update: Specifically I am trying to track the usage of keys for a memcache daemon, storing the # of sets/gets success/fails on the key. The idea is that most keys have some sort of separating character [`|\_-#] to create a sort of namespace. The idea is to step in between the daemon and the client, split the keys apart by a configured separator and record statistics on them.
You didn't mention one approach: you could modify memcached or your client to record the statistics you need. This is probably the easiest and cleanest approach. Between the proxy and the libpcap approach, there are a couple of tradeoffs: ``` - If you do the packet capture approach, you have to reassemble the TCP streams into something usable yourself. OTOH, if your monitor program gets bogged down, it'll just lose some packets, it won't break the cache. Same if it crashes. You also don't have to reconfigure anything; packet capture is transparent. - If you do the proxy approach, the kernel handles all the TCP work for you. You'll never lose requests. But if your monitor bogs down, it'll bog down the app. And if your monitor crashes, it'll break caching. You probably will have to reconfigure your app and/or memcached servers so that the connections go through the proxy. ``` In short, the proxy will probably be easier to code, but implementing it may be a royal pain, and it had better be perfect or its taking down your caching. Changing the app or memcached seems like the sanest approach to me. BTW: You have looked at memcached's built-in statistics reporting? I don't think its granular enough for what you want, but if you haven't seen it, take a look before doing actual work :-D
274,384
<p>Is anyone aware of any gems, tutorials, or solutions enabling a user to sign in to a website at one domain and automatically given access to other partner domains in the same session? </p> <p>I have two rails apps running, let's call them App-A and App-B. App-A has a database associated with it, powering the registration and login at App-A.com. I'd now like to give all of those users with App-A.com accounts access to App-B.com, without making them reregister or manually login to App-B.com separately.</p> <p>Thanks in advance for any help! --Mark</p>
[ { "answer_id": 274640, "author": "Ricardo Acras", "author_id": 19224, "author_profile": "https://Stackoverflow.com/users/19224", "pm_score": 4, "selected": true, "text": "<p>You can set the same session_key in both apps. In appA environment.rb change the session_key, like this</p>\n\n<pre><code>Rails::Initializer.run do |config|\n ... \n config.action_controller.session = {\n :session_key =&gt; '_portal_session',\n :secret =&gt; '72bf006c18d459acf51836d2aea01e0afd0388f860fe4b07a9a57dedd25c631749ba9b65083a85af38bd539cc810e81f559e76d6426c5e77b6064f42e14f7415'\n }\n ...\nend\n</code></pre>\n\n<p>Do the same in AppB. (remember to use the very same secret)</p>\n\n<p>Now you have shared sessions. Let's say you use restfull_authentication, wich sets a session variable called <strong>user_id</strong>. When you authenticate in appA it sets the user_id in the session. Now, in appB you just have to verify if user_id exists in the session.</p>\n\n<p>This is the overall schema, you can elaborate more using this idea.</p>\n" }, { "answer_id": 275056, "author": "Raimonds Simanovskis", "author_id": 16829, "author_profile": "https://Stackoverflow.com/users/16829", "pm_score": 1, "selected": false, "text": "<p>If you want to create single sign-on solution for your applications then I recommend to take a look at <a href=\"http://code.google.com/p/rubycas-server/\" rel=\"nofollow noreferrer\">RubyCAS</a> solution. It could be used also to provide single sign-on for other non-Rails applications as well as you can integrate authentication with LDAP or other authentication providers.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is anyone aware of any gems, tutorials, or solutions enabling a user to sign in to a website at one domain and automatically given access to other partner domains in the same session? I have two rails apps running, let's call them App-A and App-B. App-A has a database associated with it, powering the registration and login at App-A.com. I'd now like to give all of those users with App-A.com accounts access to App-B.com, without making them reregister or manually login to App-B.com separately. Thanks in advance for any help! --Mark
You can set the same session\_key in both apps. In appA environment.rb change the session\_key, like this ``` Rails::Initializer.run do |config| ... config.action_controller.session = { :session_key => '_portal_session', :secret => '72bf006c18d459acf51836d2aea01e0afd0388f860fe4b07a9a57dedd25c631749ba9b65083a85af38bd539cc810e81f559e76d6426c5e77b6064f42e14f7415' } ... end ``` Do the same in AppB. (remember to use the very same secret) Now you have shared sessions. Let's say you use restfull\_authentication, wich sets a session variable called **user\_id**. When you authenticate in appA it sets the user\_id in the session. Now, in appB you just have to verify if user\_id exists in the session. This is the overall schema, you can elaborate more using this idea.
274,408
<p>I'm trying to create a database scripter tool for a local database I'm using.</p> <p>I've been able to generate create scripts for the tables, primary keys, indexes, and foreign keys, but I can't find any way to generate create scripts for the table defaults.</p> <p>For indexes, it's as easy as </p> <pre><code>foreach (Index index in table.Indexes) { ScriptingOptions drop = new ScriptingOptions(); drop.ScriptDrops = true; drop.IncludeIfNotExists = true; foreach (string dropstring in index.Script(drop)) { createScript.Append(dropstring); } ScriptingOptions create = new ScriptingOptions(); create.IncludeIfNotExists = true; foreach (string createstring in index.Script(create)) { createScript.Append(createstring); } } </code></pre> <p>But the Table object doesn't have a Defaults property. Is there some other way to generate scripts for the table defaults?</p>
[ { "answer_id": 274514, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 2, "selected": false, "text": "<p>While I haven't used SMO, I looked up MSDN and here is what I found.</p>\n\n<p>Table has a Columns property (column collection), which should have reference to each column. <br> Each Column will have a DefaultConstraint property.</p>\n\n<p>Is this what you are looking for?</p>\n" }, { "answer_id": 274578, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 3, "selected": false, "text": "<p>Try using <a href=\"https://learn.microsoft.com/en-US/dotnet/api/microsoft.sqlserver.management.smo.scripter?view=sql-smo-160\" rel=\"nofollow noreferrer\">Scripter</a> object with DriAll option set:</p>\n<pre><code>Server server = new Server(@&quot;.\\SQLEXPRESS&quot;);\nDatabase db = server.Databases[&quot;AdventureWorks&quot;];\nList&lt;Urn&gt; list = new List&lt;Urn&gt;();\nDataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table);\nforeach (DataRow row in dataTable.Rows)\n{\n list.Add(new Urn((string)row[&quot;Urn&quot;]));\n}\nScripter scripter = new Scripter();\nscripter.Server = server;\nscripter.Options.IncludeHeaders = true;\nscripter.Options.SchemaQualify = true;\nscripter.Options.SchemaQualifyForeignKeysReferences = true;\nscripter.Options.NoCollation = true;\nscripter.Options.DriAllConstraints = true;\nscripter.Options.DriAll = true;\nscripter.Options.DriAllKeys = true;\nscripter.Options.DriIndexes = true;\nscripter.Options.ClusteredIndexes = true;\nscripter.Options.NonClusteredIndexes = true;\nscripter.Options.ToFileOnly = true;\nscripter.Options.FileName = @&quot;C:\\tables.sql&quot;;\nscripter.Script(list.ToArray());\n</code></pre>\n" }, { "answer_id": 45218123, "author": "Goldfish", "author_id": 3355999, "author_profile": "https://Stackoverflow.com/users/3355999", "pm_score": 0, "selected": false, "text": "<p><strong>Addition to the Pavel's answer.</strong></p>\n\n<p>I needed to get the script for a invidual table only. 1. I wanted to pass the table schema name and table name as parameter and generate script. 2. assign the script to a variable rather than writing to file.</p>\n\n<p>code for a individual table:</p>\n\n<pre><code>/*get a particular table script only*/\nTable myTable = db.Tables[\"TableName\", \"SchemaName\"];\nscripter.Script(new Urn[] { myTable.Urn});\n</code></pre>\n\n<p>Write script to a variable:</p>\n\n<pre><code>StringCollection sc = scripter.Script(new Urn[] { myTable.Urn });\nforeach (string script in sc)\n{\n sb.AppendLine();\n sb.AppendLine(\"--create table\");\n sb.Append(script + \";\");\n}\n</code></pre>\n\n<p>I hope it will help future readers.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
I'm trying to create a database scripter tool for a local database I'm using. I've been able to generate create scripts for the tables, primary keys, indexes, and foreign keys, but I can't find any way to generate create scripts for the table defaults. For indexes, it's as easy as ``` foreach (Index index in table.Indexes) { ScriptingOptions drop = new ScriptingOptions(); drop.ScriptDrops = true; drop.IncludeIfNotExists = true; foreach (string dropstring in index.Script(drop)) { createScript.Append(dropstring); } ScriptingOptions create = new ScriptingOptions(); create.IncludeIfNotExists = true; foreach (string createstring in index.Script(create)) { createScript.Append(createstring); } } ``` But the Table object doesn't have a Defaults property. Is there some other way to generate scripts for the table defaults?
Try using [Scripter](https://learn.microsoft.com/en-US/dotnet/api/microsoft.sqlserver.management.smo.scripter?view=sql-smo-160) object with DriAll option set: ``` Server server = new Server(@".\SQLEXPRESS"); Database db = server.Databases["AdventureWorks"]; List<Urn> list = new List<Urn>(); DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table); foreach (DataRow row in dataTable.Rows) { list.Add(new Urn((string)row["Urn"])); } Scripter scripter = new Scripter(); scripter.Server = server; scripter.Options.IncludeHeaders = true; scripter.Options.SchemaQualify = true; scripter.Options.SchemaQualifyForeignKeysReferences = true; scripter.Options.NoCollation = true; scripter.Options.DriAllConstraints = true; scripter.Options.DriAll = true; scripter.Options.DriAllKeys = true; scripter.Options.DriIndexes = true; scripter.Options.ClusteredIndexes = true; scripter.Options.NonClusteredIndexes = true; scripter.Options.ToFileOnly = true; scripter.Options.FileName = @"C:\tables.sql"; scripter.Script(list.ToArray()); ```
274,418
<p>We're using Stored Procedures for <em>every query</em> to the DB. This seems incredibly un-<a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">DRY</a>:</p> <ol> <li>Design the table</li> <li>Design CRUD operation SPs for that table</li> <li>Design code (preferably a class) to fill parameters and execute CRUD SPs</li> </ol> <p>If we add a single column, or change a datatype, we have to edit the table, a handful of SPs, and a handful of functions in a class within .NET.</p> <p>What are some tips for reducing this duplication?</p> <p>UPDATE:</p> <p>In combination with Vinko's idea, I found <a href="https://web.archive.org/web/20211020131038/https://aspnet.4guysfromrolla.com/articles/092408-1.aspx#postadlink" rel="nofollow noreferrer">this</a>. Here's a bit of code (in C#) that I came up with for those that need it:</p> <pre><code>SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnString"].ConnectionString); SqlCommand comm = new SqlCommand("NameOfStoredProcedure", conn); comm.CommandType = CommandType.StoredProcedure; conn.Open(); SqlCommandBuilder.DeriveParameters(comm); conn.Close(); foreach (SqlParameter param in comm.Parameters) { /* do stuff */ } </code></pre>
[ { "answer_id": 274424, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>I suggest using a code-generation tool, such as NetTiers to generate your CRUD layer.</p>\n" }, { "answer_id": 274427, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 1, "selected": false, "text": "<p>OOP design principles are for procedural code, not declarative code. In particular, reusing SP's is highly problematic.</p>\n\n<p>UI designs based on CRUD generators are well-named. Another way to explicitly turn users into data entry clerks. If you employ these, make sure you have a great abstraction layer between what they produce, and what the users have to deal with.</p>\n\n<blockquote>\n <p>If we add a single column, or change a datatype, we have to edit the table, a handful of SPs, and a handful of functions in a class within .NET.</p>\n</blockquote>\n\n<p>Sure sounds like your database design is dictating your OOP requirements. Start from the other direction instead.</p>\n" }, { "answer_id": 274434, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<p>One tip to avoid modification of at least the SPs is writing them to use 'introspection', that is, deducing the column names and datatypes from the internal tables or the information_schema views. </p>\n\n<p>It's more complex code to write, but it'll avoid having to modify it each time the table changes, and it can be reused in the rest of the SPs.</p>\n\n<p>Create a single SP that will describe the tables for you, for instance using a temp table (colname varchar, type varchar) that you'll call from the rest of SPs.</p>\n\n<p>By the way, this can get very complex and even unfeasible if your queries are complex, but on the other hand, if they are not, it can save you a lot of trouble.</p>\n" }, { "answer_id": 274438, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 1, "selected": false, "text": "<p>All these metaquery approaches die in their tracks as soon as the SQL gets beyond a single table. Or want a calculated column. Or ...</p>\n" }, { "answer_id": 274597, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 0, "selected": false, "text": "<p>I don't think this really falls under the DRY guideline. This is simply about persistence, and if you're doing #3 manually then you should look at adopting one of the toolsets that make this easier. LINQ to SQL is my personal favorite, but there are many.</p>\n\n<p>Your #2 can easily be automated as well. Reducing your overall work required to 1) design the data model (in concept) 2) implement it at the persistence layer (create your table, or add your column) 3) make use of it at the application level.</p>\n" }, { "answer_id": 276613, "author": "John MacIntyre", "author_id": 29043, "author_profile": "https://Stackoverflow.com/users/29043", "pm_score": 1, "selected": false, "text": "<p>Personally, I'm not a big fan of putting my querying code into stored procedures. With the exception of highly complex things, it just seems like redundant overkill.</p>\n\n<p>Here's how I handle my database and crud object design :</p>\n\n<ol>\n<li>I create the data model</li>\n<li>I create a view for each table</li>\n<li>I create insert, update, &amp; delete procs for each table.</li>\n<li>All my C# code points to the views and procs. </li>\n</ol>\n\n<p>This allows me to :</p>\n\n<ol>\n<li>Have a highly flexible query target (the view)</li>\n<li>Query against the views in any manner I need without redundancy.</li>\n<li>Prevent direct access to the tables via database security</li>\n<li>Abstract the data model in the event I ever need to refactor the underlying data model without breaking my code (I know, this could have performance costs)</li>\n</ol>\n\n<p>Having one view representing the target table will probably handle many queries, and even if it doesn't, the worst that will happen is you need to create a view specifically for the query, which is the equivalent to creating a proc for it, so there's no down side.</p>\n\n<p>I hear people recommending using stored procedures to prevent SQL Injection attacks, but if you use parameterized queries when querying your view, this won't be an issue anyway. ... and we always use parameterized queries any way ... right? ;-)</p>\n" }, { "answer_id": 276617, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>There are some tables which will not have CRUD, and should not be accessible from your application and are artifacts of the database implementation model. Particularly, many-to-many link tables should not be accessed by your application, they should be managed by the database through stored procedures.</p>\n" }, { "answer_id": 615373, "author": "Daniel", "author_id": 47225, "author_profile": "https://Stackoverflow.com/users/47225", "pm_score": 1, "selected": false, "text": "<p>The 'DeriveParameters' approach you use does work, but involves 2 database trips for each request. There will be a performance hit with this approach. Microsoft's Data Access Application Block SqlHelper class will mitigate this by doing the exact same 'introspection', but optionally caching parameters for re-use. This will let you create single-line SP calls with no repetitive \"goo\" setting up parameters, etc.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/cc309504.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc309504.aspx</a> </p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25538/" ]
We're using Stored Procedures for *every query* to the DB. This seems incredibly un-[DRY](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself): 1. Design the table 2. Design CRUD operation SPs for that table 3. Design code (preferably a class) to fill parameters and execute CRUD SPs If we add a single column, or change a datatype, we have to edit the table, a handful of SPs, and a handful of functions in a class within .NET. What are some tips for reducing this duplication? UPDATE: In combination with Vinko's idea, I found [this](https://web.archive.org/web/20211020131038/https://aspnet.4guysfromrolla.com/articles/092408-1.aspx#postadlink). Here's a bit of code (in C#) that I came up with for those that need it: ``` SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnString"].ConnectionString); SqlCommand comm = new SqlCommand("NameOfStoredProcedure", conn); comm.CommandType = CommandType.StoredProcedure; conn.Open(); SqlCommandBuilder.DeriveParameters(comm); conn.Close(); foreach (SqlParameter param in comm.Parameters) { /* do stuff */ } ```
One tip to avoid modification of at least the SPs is writing them to use 'introspection', that is, deducing the column names and datatypes from the internal tables or the information\_schema views. It's more complex code to write, but it'll avoid having to modify it each time the table changes, and it can be reused in the rest of the SPs. Create a single SP that will describe the tables for you, for instance using a temp table (colname varchar, type varchar) that you'll call from the rest of SPs. By the way, this can get very complex and even unfeasible if your queries are complex, but on the other hand, if they are not, it can save you a lot of trouble.
274,439
<p>How to, in C# round any value to 10 interval? For example, if I have 11, I want it to return 10, if I have 136, then I want it to return 140. </p> <p>I can easily do it by hand</p> <pre><code>return ((int)(number / 10)) * 10; </code></pre> <p>But I am looking for an builtin algorithm to do this job, something like Math.Round(). The reason why I won't want to do by hand is that I don't want to write same or similar piece of code all over my projects, even for something as simple as the above. </p>
[ { "answer_id": 274447, "author": "Raymond Martineau", "author_id": 33952, "author_profile": "https://Stackoverflow.com/users/33952", "pm_score": 3, "selected": false, "text": "<p>Rounding a float to an integer is similar to (int)(x+0.5), as opposed to simply casting x - if you want a multiple of 10, you can easily adapt that.</p>\n\n<p>If you just want to do integer math and are rounding it to ten, try (x+10/2)/10*10.</p>\n\n<p><strong>Edit:</strong> I noticed that this response doesn't meet the original's author's request, and is also a biased form of rounding that I prefer not to do. However, another accepted response already stated Math.round(), a much better solution. </p>\n" }, { "answer_id": 274453, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 5, "selected": false, "text": "<p>Use Math.Ceiling to always round up.</p>\n<pre><code>int number = 236;\nnumber = (int)(Math.Ceiling(number / 10.0d) * 10);\n</code></pre>\n<p>Modulus(%) gets the remainder, so you get:</p>\n<pre><code>// number = 236 + 10 - 6\n</code></pre>\n<p>Put that into an extension method</p>\n<pre><code>public static int roundupbyten(this int i){\n // return i + (10 - i % 10); &lt;-- logic error. Oops!\n return (int)(Math.Ceiling(i / 10.0d)*10); // fixed\n}\n\n// call like so:\nint number = 236.roundupbyten();\n</code></pre>\n<p>above edited: I should've gone with my first instinct to use Math.Ceiling</p>\n<p>I <a href=\"http://atomiton.blogspot.com/2007/12/calculating-checkdigit-using.html\" rel=\"noreferrer\">blogged about this when calculating UPC check digits</a>.</p>\n" }, { "answer_id": 274487, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 8, "selected": true, "text": "<p>There is no built-in function in the class library that will do this. The closest is <a href=\"http://msdn.microsoft.com/en-us/library/system.math.round.aspx\" rel=\"noreferrer\">System.Math.Round()</a> which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension method, if you are working with .NET 3.5, which will allow you to use the function much more cleanly.</p>\n\n<pre><code>public static class ExtensionMethods\n{\n public static int RoundOff (this int i)\n {\n return ((int)Math.Round(i / 10.0)) * 10;\n }\n}\n\nint roundedNumber = 236.RoundOff(); // returns 240\nint roundedNumber2 = 11.RoundOff(); // returns 10\n</code></pre>\n\n<p>If you are programming against an older version of the .NET framework, just remove the \"this\" from the RoundOff function, and call the function like so:</p>\n\n<pre><code>int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240\nint roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10\n</code></pre>\n" }, { "answer_id": 1788392, "author": "Jronny", "author_id": 217606, "author_profile": "https://Stackoverflow.com/users/217606", "pm_score": 5, "selected": false, "text": "<p>This might be a little too late but I guess this might be of good help someday...</p>\n\n<p>I have tried this:</p>\n\n<pre><code>public int RoundOff(int number, int interval){\n int remainder = number % interval;\n number += (remainder &lt; interval / 2) ? -remainder : (interval - remainder);\n return number;\n}\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code>int number = 11;\nint roundednumber = RoundOff(number, 10);\n</code></pre>\n\n<p>This way, you have the option whether if the half of the interval will be rounded up or rounded down. =)</p>\n" }, { "answer_id": 11822721, "author": "Dave", "author_id": 389665, "author_profile": "https://Stackoverflow.com/users/389665", "pm_score": 2, "selected": false, "text": "<p>I prefer to not bring in the <code>Math</code> library nor go to floating point so my suggestion is just do integer arithmetic like below where I round up to the next 1K. Wrap it in a method or lambda snippet or something if you don't want to repeat.</p>\n\n<pre><code>int MyRoundedUp1024Int = ((lSomeInteger + 1023) / 1024) * 1024;\n</code></pre>\n\n<p>I have not run performance tests on this vs. other the ways but I'd bet it is the fastest way to do this save maybe a shifting and rotating of bits version of this.</p>\n" }, { "answer_id": 14493950, "author": "Lucas925", "author_id": 2006170, "author_profile": "https://Stackoverflow.com/users/2006170", "pm_score": 2, "selected": false, "text": "<p>Old question but here is a way to do what has been asked plus I extended it to be able to round any number to the number of sig figs you want.</p>\n\n<pre><code> private double Rounding(double d, int digits)\n {\n int neg = 1;\n if (d &lt; 0)\n {\n d = d * (-1);\n neg = -1;\n }\n\n int n = 0;\n if (d &gt; 1)\n {\n while (d &gt; 1)\n {\n d = d / 10;\n n++;\n }\n d = Math.Round(d * Math.Pow(10, digits));\n d = d * Math.Pow(10, n - digits);\n }\n else\n {\n while (d &lt; 0.1)\n {\n d = d * 10;\n n++;\n }\n d = Math.Round(d * Math.Pow(10, digits));\n d = d / Math.Pow(10, n + digits);\n }\n\n return d*neg;\n }\n\n\n private void testing()\n {\n double a = Rounding(1230435.34553,3);\n double b = Rounding(0.004567023523,4);\n double c = Rounding(-89032.5325,2);\n double d = Rounding(-0.123409,4);\n double e = Rounding(0.503522,1);\n Console.Write(a.ToString() + \"\\n\" + b.ToString() + \"\\n\" + \n c.ToString() + \"\\n\" + d.ToString() + \"\\n\" + e.ToString() + \"\\n\");\n }\n</code></pre>\n" }, { "answer_id": 71622330, "author": "Jon", "author_id": 2350083, "author_profile": "https://Stackoverflow.com/users/2350083", "pm_score": 0, "selected": false, "text": "<p>Here's how I round to the nearest multiple of any arbitrary factor without converting from integral types to floating-point values. This works for any int from <code>int.MinValue + 1</code> to <code>int.MaxValue</code></p>\n<p>I used the <a href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero\" rel=\"nofollow noreferrer\">Round half away from zero equation</a>, <code>Round(x) = sgn(x)*Floor(Abs(x) + 0.5)</code>, the fact that <code>Floor(z) = z - (z%1)</code>, and my desired output equation <code>F(value, factor) = Round(value/factor)*factor</code> to derive the an equation that doesn't require precise decimal division.</p>\n<pre><code>public static int RoundToNearestMultipleOfFactor(this int value, int factor)\n{\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var halfAbsFactor = Math.Abs(factor) &gt;&gt; 1;\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n}\n</code></pre>\n<p>Here's the entire extension method class with methods for both <code>int</code> and <code>long</code> as well as methods to round only toward or away from zero.</p>\n<pre><code>/// &lt;summary&gt;\n/// Extension methods for rounding integral numeric types\n/// &lt;/summary&gt;\npublic static class IntegralRoundingExtensions\n{\n /// &lt;summary&gt;\n /// Rounds to the nearest multiple of a &lt;paramref name=&quot;factor&quot;/&gt; using &lt;see cref=&quot;MidpointRounding.AwayFromZero&quot;/&gt; for midpoints.\n /// &lt;para&gt;\n /// Performs the operation Round(value / factor) * factor without converting to a floating type.\n /// &lt;/para&gt;\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;remarks&gt;\n /// Uses math derived from the &lt;see href=&quot;https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero&quot;&gt;Round half away from zero equation&lt;/see&gt;: y = sgn(x)*Floor(Abs(x) + 0.5) and floor equation: Floor(z) = z - (z % 1)\n /// &lt;/remarks&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n /// &lt;seealso cref=&quot;MidpointRounding&quot;/&gt;\n public static long RoundToNearestMultipleOfFactor(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var halfAbsFactor = Math.Abs(factor) &gt;&gt; 1;\n // return value + Math.Sign(value) * (halfAbsFactor - ((Math.Abs(value) + halfAbsFactor) % factor));\n //fix overflow\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n }\n\n /// &lt;summary&gt;\n /// Round to the nearest multiple of &lt;paramref name=&quot;factor&quot;/&gt; with magnitude less than or equal to &lt;paramref name=&quot;value&quot;/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n public static long RoundToMultipleOfFactorTowardZero(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder;\n }\n\n /// &lt;summary&gt;\n /// Round to the nearest multiple of &lt;paramref name=&quot;factor&quot;/&gt; with magnitude greater than or equal to &lt;paramref name=&quot;value&quot;/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n public static long RoundToMultipleOfFactorAwayFromZero(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder + Math.Sign(value) * Math.Abs(factor);\n }\n\n /// &lt;summary&gt;\n /// Rounds to the nearest multiple of a &lt;paramref name=&quot;factor&quot;/&gt; using &lt;see cref=&quot;MidpointRounding.AwayFromZero&quot;/&gt; for midpoints.\n /// &lt;para&gt;\n /// Performs the operation Round(value / factor) * factor without converting to a floating type.\n /// &lt;/para&gt;\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;remarks&gt;\n /// Uses math derived from the &lt;see href=&quot;https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero&quot;&gt;Round half away from zero equation&lt;/see&gt;: y = sgn(x)*Floor(Abs(x) + 0.5) and floor equation: Floor(z) = z - (z % 1)\n /// &lt;/remarks&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n /// &lt;seealso cref=&quot;MidpointRounding&quot;/&gt;\n public static int RoundToNearestMultipleOfFactor(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var halfAbsFactor = Math.Abs(factor) &gt;&gt; 1;\n // return value + Math.Sign(value) * (halfAbsFactor - ((Math.Abs(value) + halfAbsFactor) % factor));\n //fix overflow\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n }\n\n /// &lt;summary&gt;\n /// Round to the nearest multiple of &lt;paramref name=&quot;factor&quot;/&gt; with magnitude less than or equal to &lt;paramref name=&quot;value&quot;/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n public static int RoundToMultipleOfFactorTowardZero(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder;\n }\n\n /// &lt;summary&gt;\n /// Round to the nearest multiple of &lt;paramref name=&quot;factor&quot;/&gt; with magnitude greater than or equal to &lt;paramref name=&quot;value&quot;/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n public static int RoundToMultipleOfFactorAwayFromZero(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder + Math.Sign(value) * Math.Abs(factor);\n }\n}\n</code></pre>\n" }, { "answer_id": 72225775, "author": "Snap", "author_id": 7993601, "author_profile": "https://Stackoverflow.com/users/7993601", "pm_score": 0, "selected": false, "text": "<p>As far as I know there isn't a native built-in c# library that rounds integers to the nearest tens place.</p>\n<p>If you're using c# 8 or later you can create small switch expression utility methods that can do a lot of cool helpful things. If you're using an older version, <code>if/else</code> and <code>switch case</code> blocks can be used instead:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static int RoundIntToTens(int anInt)\n =&gt; (anInt, (anInt &lt; 0 ? 0 - anInt : anInt) % 10) switch\n {\n // If int needs to be &quot;round down&quot; and is negative or positive\n (&gt;= 0, &lt; 5) or (&lt; 0, &lt; 5) =&gt; anInt - anInt % 10,\n // If int needs to be &quot;round up&quot; and is NOT negative (but might be 0)\n (&gt;= 0, &gt;= 5) =&gt; anInt + (10 - anInt % 10),\n // If int needs to be &quot;round up&quot; and is negative\n (&lt; 0, &gt;= 5) =&gt; anInt - (10 + anInt % 10)\n };\n</code></pre>\n<p>You would have to import it where ever you use it but that'd be the case with any library unless there's a way to add classes to a global name space.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
How to, in C# round any value to 10 interval? For example, if I have 11, I want it to return 10, if I have 136, then I want it to return 140. I can easily do it by hand ``` return ((int)(number / 10)) * 10; ``` But I am looking for an builtin algorithm to do this job, something like Math.Round(). The reason why I won't want to do by hand is that I don't want to write same or similar piece of code all over my projects, even for something as simple as the above.
There is no built-in function in the class library that will do this. The closest is [System.Math.Round()](http://msdn.microsoft.com/en-us/library/system.math.round.aspx) which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension method, if you are working with .NET 3.5, which will allow you to use the function much more cleanly. ``` public static class ExtensionMethods { public static int RoundOff (this int i) { return ((int)Math.Round(i / 10.0)) * 10; } } int roundedNumber = 236.RoundOff(); // returns 240 int roundedNumber2 = 11.RoundOff(); // returns 10 ``` If you are programming against an older version of the .NET framework, just remove the "this" from the RoundOff function, and call the function like so: ``` int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240 int roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10 ```
274,457
<p>I created a project using the default tab-controller project. I am using interface builder to edit the .xib file and add images and buttons. I hook them up to the FirstViewController object in interface builder (that I created and set it's class to the same as the code file). I hooked everything up using <code>IBoutlets</code> and <code>IBActions</code>. </p> <p>Everything was working fine, but then I made some changes in interface builder (added a <code>UILabel</code>) and now a method that is run when clicked (I ran through it with the debugger) has a line that adds a subview to the view controller, and it acts as if it wasn't executed. The method (and code is run through) is executed with no errors (per the debugger) but the view is simply not being added. This happened after I made some change via interface builder. </p> <p>Now, if I hook-up my button to "Selected First View Controller" by clicking on the appropriate tab and dragging the <code>IBOutlet</code> to the <code>UILabel</code>, that label now has multiple referencing outlets. Now, if I do the same thing for the button, the method (the <code>IBAction</code>) is executed twice but the subview is actually added and displayed. But, I get a memory access error because my <code>IBAction</code> (button) method access a property that stores something. I am guessing this has to do with somehow creating the memory in the First View Controller but trying to access it in the Selected First View Controller? If that makes any sense?</p> <p>I have no idea why this is happening and why it just the button suddenly stopped working. I tried to explain this problem the best I could, it is sort of confusing. But if anyone has any tips or ideas I would love to hear what you guys think about this problem and how to solve it.</p>
[ { "answer_id": 274447, "author": "Raymond Martineau", "author_id": 33952, "author_profile": "https://Stackoverflow.com/users/33952", "pm_score": 3, "selected": false, "text": "<p>Rounding a float to an integer is similar to (int)(x+0.5), as opposed to simply casting x - if you want a multiple of 10, you can easily adapt that.</p>\n\n<p>If you just want to do integer math and are rounding it to ten, try (x+10/2)/10*10.</p>\n\n<p><strong>Edit:</strong> I noticed that this response doesn't meet the original's author's request, and is also a biased form of rounding that I prefer not to do. However, another accepted response already stated Math.round(), a much better solution. </p>\n" }, { "answer_id": 274453, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 5, "selected": false, "text": "<p>Use Math.Ceiling to always round up.</p>\n<pre><code>int number = 236;\nnumber = (int)(Math.Ceiling(number / 10.0d) * 10);\n</code></pre>\n<p>Modulus(%) gets the remainder, so you get:</p>\n<pre><code>// number = 236 + 10 - 6\n</code></pre>\n<p>Put that into an extension method</p>\n<pre><code>public static int roundupbyten(this int i){\n // return i + (10 - i % 10); &lt;-- logic error. Oops!\n return (int)(Math.Ceiling(i / 10.0d)*10); // fixed\n}\n\n// call like so:\nint number = 236.roundupbyten();\n</code></pre>\n<p>above edited: I should've gone with my first instinct to use Math.Ceiling</p>\n<p>I <a href=\"http://atomiton.blogspot.com/2007/12/calculating-checkdigit-using.html\" rel=\"noreferrer\">blogged about this when calculating UPC check digits</a>.</p>\n" }, { "answer_id": 274487, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 8, "selected": true, "text": "<p>There is no built-in function in the class library that will do this. The closest is <a href=\"http://msdn.microsoft.com/en-us/library/system.math.round.aspx\" rel=\"noreferrer\">System.Math.Round()</a> which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension method, if you are working with .NET 3.5, which will allow you to use the function much more cleanly.</p>\n\n<pre><code>public static class ExtensionMethods\n{\n public static int RoundOff (this int i)\n {\n return ((int)Math.Round(i / 10.0)) * 10;\n }\n}\n\nint roundedNumber = 236.RoundOff(); // returns 240\nint roundedNumber2 = 11.RoundOff(); // returns 10\n</code></pre>\n\n<p>If you are programming against an older version of the .NET framework, just remove the \"this\" from the RoundOff function, and call the function like so:</p>\n\n<pre><code>int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240\nint roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10\n</code></pre>\n" }, { "answer_id": 1788392, "author": "Jronny", "author_id": 217606, "author_profile": "https://Stackoverflow.com/users/217606", "pm_score": 5, "selected": false, "text": "<p>This might be a little too late but I guess this might be of good help someday...</p>\n\n<p>I have tried this:</p>\n\n<pre><code>public int RoundOff(int number, int interval){\n int remainder = number % interval;\n number += (remainder &lt; interval / 2) ? -remainder : (interval - remainder);\n return number;\n}\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code>int number = 11;\nint roundednumber = RoundOff(number, 10);\n</code></pre>\n\n<p>This way, you have the option whether if the half of the interval will be rounded up or rounded down. =)</p>\n" }, { "answer_id": 11822721, "author": "Dave", "author_id": 389665, "author_profile": "https://Stackoverflow.com/users/389665", "pm_score": 2, "selected": false, "text": "<p>I prefer to not bring in the <code>Math</code> library nor go to floating point so my suggestion is just do integer arithmetic like below where I round up to the next 1K. Wrap it in a method or lambda snippet or something if you don't want to repeat.</p>\n\n<pre><code>int MyRoundedUp1024Int = ((lSomeInteger + 1023) / 1024) * 1024;\n</code></pre>\n\n<p>I have not run performance tests on this vs. other the ways but I'd bet it is the fastest way to do this save maybe a shifting and rotating of bits version of this.</p>\n" }, { "answer_id": 14493950, "author": "Lucas925", "author_id": 2006170, "author_profile": "https://Stackoverflow.com/users/2006170", "pm_score": 2, "selected": false, "text": "<p>Old question but here is a way to do what has been asked plus I extended it to be able to round any number to the number of sig figs you want.</p>\n\n<pre><code> private double Rounding(double d, int digits)\n {\n int neg = 1;\n if (d &lt; 0)\n {\n d = d * (-1);\n neg = -1;\n }\n\n int n = 0;\n if (d &gt; 1)\n {\n while (d &gt; 1)\n {\n d = d / 10;\n n++;\n }\n d = Math.Round(d * Math.Pow(10, digits));\n d = d * Math.Pow(10, n - digits);\n }\n else\n {\n while (d &lt; 0.1)\n {\n d = d * 10;\n n++;\n }\n d = Math.Round(d * Math.Pow(10, digits));\n d = d / Math.Pow(10, n + digits);\n }\n\n return d*neg;\n }\n\n\n private void testing()\n {\n double a = Rounding(1230435.34553,3);\n double b = Rounding(0.004567023523,4);\n double c = Rounding(-89032.5325,2);\n double d = Rounding(-0.123409,4);\n double e = Rounding(0.503522,1);\n Console.Write(a.ToString() + \"\\n\" + b.ToString() + \"\\n\" + \n c.ToString() + \"\\n\" + d.ToString() + \"\\n\" + e.ToString() + \"\\n\");\n }\n</code></pre>\n" }, { "answer_id": 71622330, "author": "Jon", "author_id": 2350083, "author_profile": "https://Stackoverflow.com/users/2350083", "pm_score": 0, "selected": false, "text": "<p>Here's how I round to the nearest multiple of any arbitrary factor without converting from integral types to floating-point values. This works for any int from <code>int.MinValue + 1</code> to <code>int.MaxValue</code></p>\n<p>I used the <a href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero\" rel=\"nofollow noreferrer\">Round half away from zero equation</a>, <code>Round(x) = sgn(x)*Floor(Abs(x) + 0.5)</code>, the fact that <code>Floor(z) = z - (z%1)</code>, and my desired output equation <code>F(value, factor) = Round(value/factor)*factor</code> to derive the an equation that doesn't require precise decimal division.</p>\n<pre><code>public static int RoundToNearestMultipleOfFactor(this int value, int factor)\n{\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var halfAbsFactor = Math.Abs(factor) &gt;&gt; 1;\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n}\n</code></pre>\n<p>Here's the entire extension method class with methods for both <code>int</code> and <code>long</code> as well as methods to round only toward or away from zero.</p>\n<pre><code>/// &lt;summary&gt;\n/// Extension methods for rounding integral numeric types\n/// &lt;/summary&gt;\npublic static class IntegralRoundingExtensions\n{\n /// &lt;summary&gt;\n /// Rounds to the nearest multiple of a &lt;paramref name=&quot;factor&quot;/&gt; using &lt;see cref=&quot;MidpointRounding.AwayFromZero&quot;/&gt; for midpoints.\n /// &lt;para&gt;\n /// Performs the operation Round(value / factor) * factor without converting to a floating type.\n /// &lt;/para&gt;\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;remarks&gt;\n /// Uses math derived from the &lt;see href=&quot;https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero&quot;&gt;Round half away from zero equation&lt;/see&gt;: y = sgn(x)*Floor(Abs(x) + 0.5) and floor equation: Floor(z) = z - (z % 1)\n /// &lt;/remarks&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n /// &lt;seealso cref=&quot;MidpointRounding&quot;/&gt;\n public static long RoundToNearestMultipleOfFactor(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var halfAbsFactor = Math.Abs(factor) &gt;&gt; 1;\n // return value + Math.Sign(value) * (halfAbsFactor - ((Math.Abs(value) + halfAbsFactor) % factor));\n //fix overflow\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n }\n\n /// &lt;summary&gt;\n /// Round to the nearest multiple of &lt;paramref name=&quot;factor&quot;/&gt; with magnitude less than or equal to &lt;paramref name=&quot;value&quot;/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n public static long RoundToMultipleOfFactorTowardZero(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder;\n }\n\n /// &lt;summary&gt;\n /// Round to the nearest multiple of &lt;paramref name=&quot;factor&quot;/&gt; with magnitude greater than or equal to &lt;paramref name=&quot;value&quot;/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n public static long RoundToMultipleOfFactorAwayFromZero(this long value, long factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder + Math.Sign(value) * Math.Abs(factor);\n }\n\n /// &lt;summary&gt;\n /// Rounds to the nearest multiple of a &lt;paramref name=&quot;factor&quot;/&gt; using &lt;see cref=&quot;MidpointRounding.AwayFromZero&quot;/&gt; for midpoints.\n /// &lt;para&gt;\n /// Performs the operation Round(value / factor) * factor without converting to a floating type.\n /// &lt;/para&gt;\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;remarks&gt;\n /// Uses math derived from the &lt;see href=&quot;https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero&quot;&gt;Round half away from zero equation&lt;/see&gt;: y = sgn(x)*Floor(Abs(x) + 0.5) and floor equation: Floor(z) = z - (z % 1)\n /// &lt;/remarks&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n /// &lt;seealso cref=&quot;MidpointRounding&quot;/&gt;\n public static int RoundToNearestMultipleOfFactor(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var halfAbsFactor = Math.Abs(factor) &gt;&gt; 1;\n // return value + Math.Sign(value) * (halfAbsFactor - ((Math.Abs(value) + halfAbsFactor) % factor));\n //fix overflow\n return value + Math.Sign(value) * (halfAbsFactor - (Math.Abs(value) % factor + halfAbsFactor % factor) % factor);\n }\n\n /// &lt;summary&gt;\n /// Round to the nearest multiple of &lt;paramref name=&quot;factor&quot;/&gt; with magnitude less than or equal to &lt;paramref name=&quot;value&quot;/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n public static int RoundToMultipleOfFactorTowardZero(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder;\n }\n\n /// &lt;summary&gt;\n /// Round to the nearest multiple of &lt;paramref name=&quot;factor&quot;/&gt; with magnitude greater than or equal to &lt;paramref name=&quot;value&quot;/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;value&quot;&gt;The value to round.&lt;/param&gt;\n /// &lt;param name=&quot;factor&quot;&gt;The factor to round to a multiple of. Must not be zero. Sign does not matter.&lt;/param&gt;\n /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;If &lt;paramref name=&quot;factor&quot;/&gt; is zero&lt;/exception&gt;\n public static int RoundToMultipleOfFactorAwayFromZero(this int value, int factor)\n {\n if (factor == 0)\n {\n throw new ArgumentOutOfRangeException(nameof(factor), factor, &quot;Cannot be zero&quot;);\n }\n\n var remainder = value % factor; // negative iff value is negative\n\n if (remainder == 0)\n {\n return value;\n }\n\n return value - remainder + Math.Sign(value) * Math.Abs(factor);\n }\n}\n</code></pre>\n" }, { "answer_id": 72225775, "author": "Snap", "author_id": 7993601, "author_profile": "https://Stackoverflow.com/users/7993601", "pm_score": 0, "selected": false, "text": "<p>As far as I know there isn't a native built-in c# library that rounds integers to the nearest tens place.</p>\n<p>If you're using c# 8 or later you can create small switch expression utility methods that can do a lot of cool helpful things. If you're using an older version, <code>if/else</code> and <code>switch case</code> blocks can be used instead:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static int RoundIntToTens(int anInt)\n =&gt; (anInt, (anInt &lt; 0 ? 0 - anInt : anInt) % 10) switch\n {\n // If int needs to be &quot;round down&quot; and is negative or positive\n (&gt;= 0, &lt; 5) or (&lt; 0, &lt; 5) =&gt; anInt - anInt % 10,\n // If int needs to be &quot;round up&quot; and is NOT negative (but might be 0)\n (&gt;= 0, &gt;= 5) =&gt; anInt + (10 - anInt % 10),\n // If int needs to be &quot;round up&quot; and is negative\n (&lt; 0, &gt;= 5) =&gt; anInt - (10 + anInt % 10)\n };\n</code></pre>\n<p>You would have to import it where ever you use it but that'd be the case with any library unless there's a way to add classes to a global name space.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
I created a project using the default tab-controller project. I am using interface builder to edit the .xib file and add images and buttons. I hook them up to the FirstViewController object in interface builder (that I created and set it's class to the same as the code file). I hooked everything up using `IBoutlets` and `IBActions`. Everything was working fine, but then I made some changes in interface builder (added a `UILabel`) and now a method that is run when clicked (I ran through it with the debugger) has a line that adds a subview to the view controller, and it acts as if it wasn't executed. The method (and code is run through) is executed with no errors (per the debugger) but the view is simply not being added. This happened after I made some change via interface builder. Now, if I hook-up my button to "Selected First View Controller" by clicking on the appropriate tab and dragging the `IBOutlet` to the `UILabel`, that label now has multiple referencing outlets. Now, if I do the same thing for the button, the method (the `IBAction`) is executed twice but the subview is actually added and displayed. But, I get a memory access error because my `IBAction` (button) method access a property that stores something. I am guessing this has to do with somehow creating the memory in the First View Controller but trying to access it in the Selected First View Controller? If that makes any sense? I have no idea why this is happening and why it just the button suddenly stopped working. I tried to explain this problem the best I could, it is sort of confusing. But if anyone has any tips or ideas I would love to hear what you guys think about this problem and how to solve it.
There is no built-in function in the class library that will do this. The closest is [System.Math.Round()](http://msdn.microsoft.com/en-us/library/system.math.round.aspx) which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension method, if you are working with .NET 3.5, which will allow you to use the function much more cleanly. ``` public static class ExtensionMethods { public static int RoundOff (this int i) { return ((int)Math.Round(i / 10.0)) * 10; } } int roundedNumber = 236.RoundOff(); // returns 240 int roundedNumber2 = 11.RoundOff(); // returns 10 ``` If you are programming against an older version of the .NET framework, just remove the "this" from the RoundOff function, and call the function like so: ``` int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240 int roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10 ```
274,465
<p>I have some question:</p> <p>How to make a role based web application? Such as in forum sites, there is many user types, admin, moderator etc... is the roles of these user types stored in database or web.config? And when a user login to our site, how to control this users roles? In short I want to learn about authorization and authentication. </p> <p>Thanks..</p>
[ { "answer_id": 274468, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "<p>Check this articles and videos:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx\" rel=\"nofollow noreferrer\">Introduction to Membership</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/9ab2fxh0.aspx\" rel=\"nofollow noreferrer\">Managing Authorization Using Roles</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/x28wfk74.aspx\" rel=\"nofollow noreferrer\">Creating the Application Services Database for SQL Server</a></li>\n<li><a href=\"https://web.archive.org/web/20210513220018/http://aspnet.4guysfromrolla.com/articles/120705-1.aspx\" rel=\"nofollow noreferrer\">Examining ASP.NET 2.0's Membership, Roles, and Profile</a></li>\n<li><a href=\"http://www.odetocode.com/Articles/427.aspx\" rel=\"nofollow noreferrer\">Membership and Role Providers in ASP.NET 2.0</a> (Tutorial)</li>\n<li><a href=\"http://www.asp.net/LEARN/security-videos/\" rel=\"nofollow noreferrer\">ASP .NET Security Videos</a></li>\n</ul>\n" }, { "answer_id": 274473, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>I've found that the built in Authorization schemes work great for simple situations where you only need to basically authenticate who can enter and who can leave, but fall short for custom situations, such as having special administrator accounts etc.</p>\n\n<p>In those situations, I've created my own authentication scheme.</p>\n" }, { "answer_id": 274486, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": true, "text": "<p>@Mavera:</p>\n\n<p>Basicly, its the concept of having your own users table in your own database, where you can manage permissions and store login information (Properly hashed of course). In the case of a multi-level permission scheme, I usually use two or more tables, for example:</p>\n\n<pre><code>TblUsers:\n-----------------------------------------------------------------\n| UserID (PK) | UserName | HashedPassword | PermissionLevel (FK)|\n|---------------------------------------------------------------|\n| 1 | BobTables| adfafs2312 | 2 |\n-----------------------------------------------------------------\n\nTblPermissions\n-------------------------------------\n| PermissionID (PK) | Description |\n--------------------------------------\n| 1 | User |\n| 2 | SuperUser |\n| 3 | Admin |\n--------------------------------------\n</code></pre>\n\n<p>You can add 3rd table that contains a One-To-Many relationship between TblPermissions that exposes the actual abilities the user may be allowed to do.</p>\n\n<p>Querying a user would be as simple as:</p>\n\n<pre><code>SELECT TblUser.Username, TblPermissions.Description \n FROM TblUsers, TblPermissions \n WHERE TblUser.UserID = @UserID \n AND TblUser.PermissionLevel = TblPermission.PermissionID;\n</code></pre>\n\n<p>Create a custom class to encapsulate that information, and store it in ASP.NET session when they are logged in.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439507/" ]
I have some question: How to make a role based web application? Such as in forum sites, there is many user types, admin, moderator etc... is the roles of these user types stored in database or web.config? And when a user login to our site, how to control this users roles? In short I want to learn about authorization and authentication. Thanks..
@Mavera: Basicly, its the concept of having your own users table in your own database, where you can manage permissions and store login information (Properly hashed of course). In the case of a multi-level permission scheme, I usually use two or more tables, for example: ``` TblUsers: ----------------------------------------------------------------- | UserID (PK) | UserName | HashedPassword | PermissionLevel (FK)| |---------------------------------------------------------------| | 1 | BobTables| adfafs2312 | 2 | ----------------------------------------------------------------- TblPermissions ------------------------------------- | PermissionID (PK) | Description | -------------------------------------- | 1 | User | | 2 | SuperUser | | 3 | Admin | -------------------------------------- ``` You can add 3rd table that contains a One-To-Many relationship between TblPermissions that exposes the actual abilities the user may be allowed to do. Querying a user would be as simple as: ``` SELECT TblUser.Username, TblPermissions.Description FROM TblUsers, TblPermissions WHERE TblUser.UserID = @UserID AND TblUser.PermissionLevel = TblPermission.PermissionID; ``` Create a custom class to encapsulate that information, and store it in ASP.NET session when they are logged in.
274,469
<p>This works (prints, for example, “3 arguments”):</p> <pre><code>to run argv do shell script "echo " &amp; (count argv) &amp; " arguments" end run </code></pre> <p>This doesn't (prints only “Argument 3: three”, and not the previous two arguments):</p> <pre><code>to run argv do shell script "echo " &amp; (count argv) &amp; " arguments" repeat with i from 1 to (count argv) do shell script "echo 'Argument " &amp; i &amp; ": " &amp; (item i of argv) &amp; "'" end repeat end run </code></pre> <p>In both cases, I'm running the script using <code>osascript</code> on Mac OS X 10.5.5. Example invocation:</p> <pre><code>osascript 'Script that takes arguments.applescript' Test argument three </code></pre> <p>I'm not redirecting the output, so I know that the script is not throwing an error.</p> <p>If I add a <code>display dialog</code> statement above the <code>do shell script</code>, it throws a “no user interaction allowed” error, so I know that it is executing the loop body.</p> <p>What am I doing wrong? What is it about this loop that causes osascript to not print anything?</p>
[ { "answer_id": 274526, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "<p>Your problem appears to be unrelated to the loop, or the use of argv, for that matter. Here's a much simpler test case where only the last <code>do shell script</code> actually returns a result:</p>\n<pre><code>do shell script &quot;echo foo&quot;\ndelay 2\ndo shell script &quot;echo bar&quot;\n</code></pre>\n<p>In addition, the following slight change will produce expected results:</p>\n<pre><code>to run argv\n do shell script &quot;echo &quot; &amp; (count argv) &amp; &quot; arguments &gt; /test.txt&quot;\n \n repeat with i from 1 to (count argv)\n do shell script &quot;echo 'Argument &quot; &amp; i &amp; &quot;: &quot; &amp; (item i of argv) &amp; &quot;' &gt;&gt; /test.txt&quot;\n end repeat\nend run\n</code></pre>\n<p><code>test.txt</code> will contain four lines, like so:</p>\n<pre><code>3 arguments\nArgument 1: foo\nArgument 2: bar\nArgument 3: baz\n</code></pre>\n<p>This workaround fails:</p>\n<pre><code>to run argv\n do shell script &quot;echo &quot; &amp; (count argv) &amp; &quot; arguments &gt; /tmp/foo.txt&quot;\n \n repeat with i from 1 to (count argv)\n do shell script &quot;echo 'Argument &quot; &amp; i &amp; &quot;: &quot; &amp; (item i of argv) &amp; &quot;' &gt;&gt; /tmp/foo.txt&quot;\n end repeat\n \n do shell script &quot;cat /tmp/foo.txt&quot;\n do shell script &quot;rm /tmp/foo.txt&quot;\nend run\n</code></pre>\n<p>Even now, only the last line is returned. This may be related to the following question of <a href=\"http://developer.apple.com/technotes/tn2002/tn2065.html\" rel=\"nofollow noreferrer\">TN2065</a>:</p>\n<blockquote>\n<p>Q: My script will produce output over a long time. How do I read the results as they come in?</p>\n<p>A: Again, the short answer is that you don’t — do shell script will not return until the command is done. In Unix terms, it cannot be used to create a pipe. What you can do, however, is to put the command into the background (see the next question), send its output to a file, and then read the file as it fills up.</p>\n</blockquote>\n<p>Alas, I don't have enough AppleScript-fu to know how to have AppleScript itself read multiple lines, which I suspect would work.</p>\n" }, { "answer_id": 274541, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "<p>Try this to avoid having to use the temporary file.</p>\n\n<pre><code>to run argv\n set accumulator to do shell script \"echo \" &amp; (count argv) &amp; \" arguments\" altering line endings false\n repeat with i from 1 to (count argv)\n set ln to do shell script \"echo 'Argument \" &amp; i &amp; \": \" &amp; (item i of argv) &amp; \"'\" altering line endings false\n set accumulator to accumulator &amp; ln\n end repeat\n return accumulator\nend run\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30461/" ]
This works (prints, for example, “3 arguments”): ``` to run argv do shell script "echo " & (count argv) & " arguments" end run ``` This doesn't (prints only “Argument 3: three”, and not the previous two arguments): ``` to run argv do shell script "echo " & (count argv) & " arguments" repeat with i from 1 to (count argv) do shell script "echo 'Argument " & i & ": " & (item i of argv) & "'" end repeat end run ``` In both cases, I'm running the script using `osascript` on Mac OS X 10.5.5. Example invocation: ``` osascript 'Script that takes arguments.applescript' Test argument three ``` I'm not redirecting the output, so I know that the script is not throwing an error. If I add a `display dialog` statement above the `do shell script`, it throws a “no user interaction allowed” error, so I know that it is executing the loop body. What am I doing wrong? What is it about this loop that causes osascript to not print anything?
Try this to avoid having to use the temporary file. ``` to run argv set accumulator to do shell script "echo " & (count argv) & " arguments" altering line endings false repeat with i from 1 to (count argv) set ln to do shell script "echo 'Argument " & i & ": " & (item i of argv) & "'" altering line endings false set accumulator to accumulator & ln end repeat return accumulator end run ```
274,474
<p>My usage case is compiling generated source files from a java program using the ToolProvider and JavaCompiler classes provided in JDK 6. The source files contain references to classes in the context classloader (it runs in a J2EE container), but not in the system classloader. My understanding is that by default the ToolProvider will create the JavaCompiler instance with the system classloader.</p> <p>Is there a way to specify a classloader for JavaCompiler to use?</p> <p>I tried this approach, modified from something on IBM DeveloperWorks:</p> <pre><code>FileManagerImpl fm = new FileManagerImpl(compiler.getStandardFileManager(null, null, null);); </code></pre> <p>with FileManagerImpl defined as:</p> <pre><code>static final class FileManagerImpl extends ForwardingJavaFileManager&lt;JavaFileManager&gt; { public FileManagerImpl(JavaFileManager fileManager) { super(fileManager); } @Override public ClassLoader getClassLoader(JavaFileManager.Location location) { new Exception().printStackTrace(); return Thread.currentThread().getContextClassLoader(); } } </code></pre> <p>The stacktrace indicates it's only called once during annotation processing. I verified the class referenced in the source file to be compiled is not on the system classpath but is available from the context classloader.</p>
[ { "answer_id": 335708, "author": "tcurdt", "author_id": 33165, "author_profile": "https://Stackoverflow.com/users/33165", "pm_score": 1, "selected": false, "text": "<p>Another option is to use <a href=\"http://commons.apache.org/jci/usage.html\" rel=\"nofollow noreferrer\">Commons JCI</a>.</p>\n" }, { "answer_id": 665896, "author": "Leihca", "author_id": 74289, "author_profile": "https://Stackoverflow.com/users/74289", "pm_score": 3, "selected": false, "text": "<p>If you know the classpath to the files that are known to the contextclassloader you can pass them to the compiler:</p>\n\n<pre><code> StandardJavaFileManager fileManager = compiler.getStandardFileManager(this /* diagnosticlistener */, null, null);\n// get compilationunits from somewhere, for instance via fileManager.getJavaFileObjectsFromFiles(List&lt;file&gt; files)\nList&lt;String&gt; options = new ArrayList&lt;String&gt;();\noptions.add(\"-classpath\");\nStringBuilder sb = new StringBuilder();\nURLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();\nfor (URL url : urlClassLoader.getURLs())\n sb.append(url.getFile()).append(File.pathSeparator);\noptions.add(sb.toString());\nCompilationTask task = compiler.getTask(null, fileManager, this /* diagnosticlistener */, options, null, compilationUnits);\ntask.call();\n</code></pre>\n\n<p>This example assumes you're using a URLClassloader (which allows you to retrieve the classpath) but you could insert your own classpath if you wanted to. </p>\n" }, { "answer_id": 2318656, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 0, "selected": false, "text": "<p>You're asking two separate questions here.</p>\n\n<p>One is how to compile classes not found in the system classpath. This is easily solved by passing the \"-classpath\" command-line argument to the compiler (as first mentioned by Leihca).</p>\n\n<p>The second is how to instantiate ToolProvider and JavaCompiler on the thread context classloader. At the time of this writing, this is an unsolved question: <a href=\"https://stackoverflow.com/questions/2315719/how-to-interact-with-javax-tools-toolprovider-outside-the-system-classloader\">Using javax.tools.ToolProvider from a custom classloader?</a></p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33897/" ]
My usage case is compiling generated source files from a java program using the ToolProvider and JavaCompiler classes provided in JDK 6. The source files contain references to classes in the context classloader (it runs in a J2EE container), but not in the system classloader. My understanding is that by default the ToolProvider will create the JavaCompiler instance with the system classloader. Is there a way to specify a classloader for JavaCompiler to use? I tried this approach, modified from something on IBM DeveloperWorks: ``` FileManagerImpl fm = new FileManagerImpl(compiler.getStandardFileManager(null, null, null);); ``` with FileManagerImpl defined as: ``` static final class FileManagerImpl extends ForwardingJavaFileManager<JavaFileManager> { public FileManagerImpl(JavaFileManager fileManager) { super(fileManager); } @Override public ClassLoader getClassLoader(JavaFileManager.Location location) { new Exception().printStackTrace(); return Thread.currentThread().getContextClassLoader(); } } ``` The stacktrace indicates it's only called once during annotation processing. I verified the class referenced in the source file to be compiled is not on the system classpath but is available from the context classloader.
If you know the classpath to the files that are known to the contextclassloader you can pass them to the compiler: ``` StandardJavaFileManager fileManager = compiler.getStandardFileManager(this /* diagnosticlistener */, null, null); // get compilationunits from somewhere, for instance via fileManager.getJavaFileObjectsFromFiles(List<file> files) List<String> options = new ArrayList<String>(); options.add("-classpath"); StringBuilder sb = new StringBuilder(); URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); for (URL url : urlClassLoader.getURLs()) sb.append(url.getFile()).append(File.pathSeparator); options.add(sb.toString()); CompilationTask task = compiler.getTask(null, fileManager, this /* diagnosticlistener */, options, null, compilationUnits); task.call(); ``` This example assumes you're using a URLClassloader (which allows you to retrieve the classpath) but you could insert your own classpath if you wanted to.
274,482
<p>I am just getting started with CodeIgniter, and I am trying to hash out my regular modules/functions to get them working properly within the MVC framework. I have a few specific questions for anyone who has a strong CodeIgniter background:</p> <p><strong>SESSIONS</strong></p> <p>The CodeIgniter session stores session data on the client side in a cookie, which just isn't going to work for me. I know there are a few replacements for it, or I could build my own library/helper; but I just don't see any benefit over just using <code>$_SESSION</code>.</p> <p>If I just use <code>$_SESSION</code>, will I have any problems with the rest of the framework? Does any other part of the framework depend on using the CodeIgniter session?</p> <p>I feel a bit weird about stepping outside the framework for something so basic, but I am pretty comfortable with plain PHP. I am basically just looking to use CodeIgniter for MVC, and to enforce a more modular aspect for my projects.</p> <p><strong>CODE FLOW &amp; CONFIG</strong></p> <p>I have a few config items that need to be done before almost anything else. </p> <p>For example, say I have a constant <code>APP_LIVE</code>, which is set true/false based on the name of the current server. This has to happen really early as paths, error reporting, the CodeIgniter system, and application folders, etc. will be set based on it.</p> <p>The problem is that the <code>system_folder</code>, and <code>application_folder</code> (which will be set based on which server the code is running on) are set first thing in the <code>index.php</code> file, before any of the configs have loaded.</p> <p>Also, I have a functions that check for things in the URL, and may redirect before the page ever loads. For example, some pages need to enfore the presence of <code>www.</code> in the URL (for SEO), track affiliates, visitor sources, marketing flags, etc.</p> <p>Where is the best place to put things like this that have to happen really early? I know there is a config file, an autoload file, a constants file, etc., but those are too late for some items. Is it a bad practice to simply put these things into the top of the main <code>index.php</code> file, or to make an include there to a global config file? Again, I feel like I am stepping outside the framework, and wonder if I'm just doing that because I don't have a solid understanding of it yet?</p> <p><strong>LAYOUT / HEADER FOOTER</strong></p> <p>Like most people, I have a top header, navigation, footer, etc. I am used to just having them in files, which are included into my page template. I believe I can do that the same way by just making them views and including them into my main page view. Is that the best way to go? Some of them need a bit of data; like what page they are on for the navigation, etc. What's the best way to handle navigation, shared header/footer, etc.?</p>
[ { "answer_id": 274506, "author": "John McCollum", "author_id": 22946, "author_profile": "https://Stackoverflow.com/users/22946", "pm_score": 2, "selected": false, "text": "<p>The newly released CI 1.7 handles sessions in the database (if you're using one). </p>\n\n<p>However, CI is designed to be loosely coupled, so you shouldn't notice any major issues if you decide to use $_SESSION instead.</p>\n\n<p>For your header / footer / navigation, you could create (for example) headerview.php, footerview.php, and contentview.php, and pass data to your views by doing something like this in the controller:</p>\n\n<pre><code>$data['title'] = 'about us';\n$data['content'] = 'hello world!';\n\n$this-&gt;load-&gt;view('headerview', $data);\n$this-&gt;load-&gt;view('contentview', $data);\n$this-&gt;load-&gt;view('footerview');\n</code></pre>\n\n<p>Basically, you can treat these views exactly like includes, but with the added benefit that you can change the variables within. I would steer clear of calling other views from within views, but that might just be me.</p>\n\n<p>I've made additions to index.php myself once or twice, to set initial values and such, and have never had a problem with it.</p>\n\n<p>Congratulations on your choice of framework; I'm sure you won't be disappointed. ;)</p>\n" }, { "answer_id": 274513, "author": "Mehmet Duran", "author_id": 5591, "author_profile": "https://Stackoverflow.com/users/5591", "pm_score": 1, "selected": false, "text": "<p>You can either have multiple load->view lines in every controller but I personally find it coupled. I strongly suggest that you take a look at hooks in CodeIgniter where you can define functions that would be automatically run after each controller/method (a fine example of AOP).</p>\n" }, { "answer_id": 282432, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Actually the $_SESSION array seems to get unset so you can't use the native PHP sessions (at least on 1.7). However in CodeIgniter wiki there's a session class that uses the native php sessions - you can use it the same way as the other, but it stores only session_id in the cookie. Here it is:\n<a href=\"http://codeigniter.com/wiki/Native_session/\" rel=\"nofollow noreferrer\">http://codeigniter.com/wiki/Native_session/</a></p>\n" }, { "answer_id": 294862, "author": "Teej", "author_id": 37532, "author_profile": "https://Stackoverflow.com/users/37532", "pm_score": 0, "selected": false, "text": "<p>@lacho I created my own auth library on $_SESSION. and it works fine on 1.7. </p>\n\n<p>I believe $_SESSION is much more secure since CI 'sessions' are cookies that are stored on the client side which are classified as 'user-passed-information' that can't be trusted. </p>\n" }, { "answer_id": 13374048, "author": "A Bright Worker", "author_id": 209558, "author_profile": "https://Stackoverflow.com/users/209558", "pm_score": 0, "selected": false, "text": "<p>You can try with native using your own session class</p>\n\n<p><a href=\"http://www.moreofless.co.uk/using-native-php-sessions-with-codeigniter/\" rel=\"nofollow\">http://www.moreofless.co.uk/using-native-php-sessions-with-codeigniter/</a></p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
I am just getting started with CodeIgniter, and I am trying to hash out my regular modules/functions to get them working properly within the MVC framework. I have a few specific questions for anyone who has a strong CodeIgniter background: **SESSIONS** The CodeIgniter session stores session data on the client side in a cookie, which just isn't going to work for me. I know there are a few replacements for it, or I could build my own library/helper; but I just don't see any benefit over just using `$_SESSION`. If I just use `$_SESSION`, will I have any problems with the rest of the framework? Does any other part of the framework depend on using the CodeIgniter session? I feel a bit weird about stepping outside the framework for something so basic, but I am pretty comfortable with plain PHP. I am basically just looking to use CodeIgniter for MVC, and to enforce a more modular aspect for my projects. **CODE FLOW & CONFIG** I have a few config items that need to be done before almost anything else. For example, say I have a constant `APP_LIVE`, which is set true/false based on the name of the current server. This has to happen really early as paths, error reporting, the CodeIgniter system, and application folders, etc. will be set based on it. The problem is that the `system_folder`, and `application_folder` (which will be set based on which server the code is running on) are set first thing in the `index.php` file, before any of the configs have loaded. Also, I have a functions that check for things in the URL, and may redirect before the page ever loads. For example, some pages need to enfore the presence of `www.` in the URL (for SEO), track affiliates, visitor sources, marketing flags, etc. Where is the best place to put things like this that have to happen really early? I know there is a config file, an autoload file, a constants file, etc., but those are too late for some items. Is it a bad practice to simply put these things into the top of the main `index.php` file, or to make an include there to a global config file? Again, I feel like I am stepping outside the framework, and wonder if I'm just doing that because I don't have a solid understanding of it yet? **LAYOUT / HEADER FOOTER** Like most people, I have a top header, navigation, footer, etc. I am used to just having them in files, which are included into my page template. I believe I can do that the same way by just making them views and including them into my main page view. Is that the best way to go? Some of them need a bit of data; like what page they are on for the navigation, etc. What's the best way to handle navigation, shared header/footer, etc.?
The newly released CI 1.7 handles sessions in the database (if you're using one). However, CI is designed to be loosely coupled, so you shouldn't notice any major issues if you decide to use $\_SESSION instead. For your header / footer / navigation, you could create (for example) headerview.php, footerview.php, and contentview.php, and pass data to your views by doing something like this in the controller: ``` $data['title'] = 'about us'; $data['content'] = 'hello world!'; $this->load->view('headerview', $data); $this->load->view('contentview', $data); $this->load->view('footerview'); ``` Basically, you can treat these views exactly like includes, but with the added benefit that you can change the variables within. I would steer clear of calling other views from within views, but that might just be me. I've made additions to index.php myself once or twice, to set initial values and such, and have never had a problem with it. Congratulations on your choice of framework; I'm sure you won't be disappointed. ;)
274,493
<p>When copying large files using <code>shutil.copy()</code>, you get no indication of how the operation is progressing..</p> <p>I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of <code>open().read()</code> and <code>.write()</code> to do the actual copying. It displays the progress bar using <code>sys.stdout.write("\r%s\r" % (the_progress_bar))</code> which is a little hackish, but it works.</p> <p>You can see the code (in context) <a href="http://github.com/dbr/checktveps/tree/1be8f4445fbf766eba25f98f78ec52e955571608/autoPathTv.py#L64-153" rel="noreferrer">on github here</a></p> <p>Is there any built-in module that will do this better? Is there any improvements that can be made to this code?</p>
[ { "answer_id": 274497, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>Two things:</p>\n\n<ul>\n<li>I would make the default block size a <em>lot</em> larger than 512. I would start with 16384 and perhaps more.</li>\n<li>For modularity, it might be better to have the <code>copy_with_prog</code> function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress.</li>\n</ul>\n\n<p>Perhaps something like this:</p>\n\n<pre><code>def copy_with_prog(src, dest, callback = None):\n while True:\n # copy loop stuff\n if callback:\n callback(pos, total)\n\nprog = ProgressBar(...)\ncopy_with_prog(src, dest, lambda pos, total: prog.update(pos, total))\n</code></pre>\n" }, { "answer_id": 275945, "author": "Jim Carroll", "author_id": 35922, "author_profile": "https://Stackoverflow.com/users/35922", "pm_score": 3, "selected": false, "text": "<p>Overkill? Perhaps. But on almost any system, Linux, Mac, and With a quick wxWidgets install on Windows, you can have the real deal, with pause and cancel buttons in a gui setup. Macs ship with wxWidgets these days, and it's a common package on Linux.</p>\n\n<p>A single file is very quick (it will immediately finish and look broken) so you might consider creating a fileSet job that ticks along once per file instead of once per block. Enjoy!</p>\n\n<p>-Jim Carroll</p>\n\n<pre><code>\"\"\"\nThreaded Jobs.\n\nAny class that does a long running process can inherit\nfrom ThreadedJob. This enables running as a background\nthread, progress notification, pause and cancel. The\ntime remaining is also calculated by the ThreadedJob class.\n\"\"\"\nimport wx.lib.newevent\nimport thread\nimport exceptions\nimport time\n\n(RunEvent, EVT_RUN) = wx.lib.newevent.NewEvent()\n(CancelEvent, EVT_CANCEL) = wx.lib.newevent.NewEvent()\n(DoneEvent, EVT_DONE) = wx.lib.newevent.NewEvent()\n(ProgressStartEvent, EVT_PROGRESS_START) = wx.lib.newevent.NewEvent()\n(ProgressEvent, EVT_PROGRESS) = wx.lib.newevent.NewEvent()\n\nclass InterruptedException(exceptions.Exception):\n def __init__(self, args = None):\n self.args = args\n #\n#\n\nclass ThreadedJob:\n def __init__(self):\n # tell them ten seconds at first\n self.secondsRemaining = 10.0\n self.lastTick = 0\n\n # not running yet\n self.isPaused = False\n self.isRunning = False\n self.keepGoing = True\n\n def Start(self):\n self.keepGoing = self.isRunning = True\n thread.start_new_thread(self.Run, ())\n\n self.isPaused = False\n #\n\n def Stop(self):\n self.keepGoing = False\n #\n\n def WaitUntilStopped(self):\n while self.isRunning:\n time.sleep(0.1)\n wx.SafeYield()\n #\n #\n\n def IsRunning(self):\n return self.isRunning\n #\n\n def Run(self):\n # this is overridden by the\n # concrete ThreadedJob\n print \"Run was not overloaded\"\n self.JobFinished()\n\n pass\n #\n\n def Pause(self):\n self.isPaused = True\n pass\n #\n\n def Continue(self):\n self.isPaused = False\n pass\n #\n\n def PossibleStoppingPoint(self):\n if not self.keepGoing:\n raise InterruptedException(\"process interrupted.\")\n wx.SafeYield()\n\n # allow cancel while paused\n while self.isPaused:\n if not self.keepGoing:\n raise InterruptedException(\"process interrupted.\")\n\n # don't hog the CPU\n time.sleep(0.1)\n #\n #\n\n def SetProgressMessageWindow(self, win):\n self.win = win\n #\n\n def JobBeginning(self, totalTicks):\n\n self.lastIterationTime = time.time()\n self.totalTicks = totalTicks\n\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, ProgressStartEvent(total=totalTicks))\n #\n #\n\n def JobProgress(self, currentTick):\n dt = time.time() - self.lastIterationTime\n self.lastIterationTime = time.time()\n dtick = currentTick - self.lastTick\n self.lastTick = currentTick\n\n alpha = 0.92\n if currentTick &gt; 1:\n self.secondsPerTick = dt * (1.0 - alpha) + (self.secondsPerTick * alpha)\n else:\n self.secondsPerTick = dt\n #\n\n if dtick &gt; 0:\n self.secondsPerTick /= dtick\n\n self.secondsRemaining = self.secondsPerTick * (self.totalTicks - 1 - currentTick) + 1\n\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, ProgressEvent(count=currentTick))\n #\n #\n\n def SecondsRemaining(self):\n return self.secondsRemaining\n #\n\n def TimeRemaining(self):\n\n if 1: #self.secondsRemaining &gt; 3:\n minutes = self.secondsRemaining // 60\n seconds = int(self.secondsRemaining % 60.0)\n return \"%i:%02i\" % (minutes, seconds)\n else:\n return \"a few\"\n #\n\n def JobFinished(self):\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, DoneEvent())\n #\n\n # flag we're done before we post the all done message\n self.isRunning = False\n #\n#\n\nclass EggTimerJob(ThreadedJob):\n \"\"\" A sample Job that demonstrates the mechanisms and features of the Threaded Job\"\"\"\n def __init__(self, duration):\n self.duration = duration\n ThreadedJob.__init__(self)\n #\n\n def Run(self):\n \"\"\" This can either be run directly for synchronous use of the job,\n or started as a thread when ThreadedJob.Start() is called.\n\n It is responsible for calling JobBeginning, JobProgress, and JobFinished.\n And as often as possible, calling PossibleStoppingPoint() which will \n sleep if the user pauses, and raise an exception if the user cancels.\n \"\"\"\n self.time0 = time.clock()\n self.JobBeginning(self.duration)\n\n try:\n for count in range(0, self.duration):\n time.sleep(1.0)\n self.JobProgress(count)\n self.PossibleStoppingPoint()\n #\n except InterruptedException:\n # clean up if user stops the Job early\n print \"canceled prematurely!\"\n #\n\n # always signal the end of the job\n self.JobFinished()\n #\n #\n\n def __str__(self):\n \"\"\" The job progress dialog expects the job to describe its current state.\"\"\"\n response = []\n if self.isPaused:\n response.append(\"Paused Counting\")\n elif not self.isRunning:\n response.append(\"Will Count the seconds\")\n else:\n response.append(\"Counting\")\n #\n return \" \".join(response)\n #\n#\n\nclass FileCopyJob(ThreadedJob):\n \"\"\" A common file copy Job. \"\"\"\n\n def __init__(self, orig_filename, copy_filename, block_size=32*1024):\n\n self.src = orig_filename\n self.dest = copy_filename\n self.block_size = block_size\n ThreadedJob.__init__(self)\n #\n\n def Run(self):\n \"\"\" This can either be run directly for synchronous use of the job,\n or started as a thread when ThreadedJob.Start() is called.\n\n It is responsible for calling JobBeginning, JobProgress, and JobFinished.\n And as often as possible, calling PossibleStoppingPoint() which will \n sleep if the user pauses, and raise an exception if the user cancels.\n \"\"\"\n self.time0 = time.clock()\n\n try:\n source = open(self.src, 'rb')\n\n # how many blocks?\n import os\n (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime) = os.stat(self.src)\n num_blocks = st_size / self.block_size\n current_block = 0\n\n self.JobBeginning(num_blocks)\n\n dest = open(self.dest, 'wb')\n\n while 1:\n copy_buffer = source.read(self.block_size)\n if copy_buffer:\n dest.write(copy_buffer)\n current_block += 1\n self.JobProgress(current_block)\n self.PossibleStoppingPoint()\n else:\n break\n\n source.close()\n dest.close()\n\n except InterruptedException:\n # clean up if user stops the Job early\n dest.close()\n # unlink / delete the file that is partially copied\n os.unlink(self.dest)\n print \"canceled, dest deleted!\"\n #\n\n # always signal the end of the job\n self.JobFinished()\n #\n #\n\n def __str__(self):\n \"\"\" The job progress dialog expects the job to describe its current state.\"\"\"\n response = []\n if self.isPaused:\n response.append(\"Paused Copy\")\n elif not self.isRunning:\n response.append(\"Will Copy a file\")\n else:\n response.append(\"Copying\")\n #\n return \" \".join(response)\n #\n#\n\nclass JobProgress(wx.Dialog):\n \"\"\" This dialog shows the progress of any ThreadedJob.\n\n It can be shown Modally if the main application needs to suspend\n operation, or it can be shown Modelessly for background progress\n reporting.\n\n app = wx.PySimpleApp()\n job = EggTimerJob(duration = 10)\n dlg = JobProgress(None, job)\n job.SetProgressMessageWindow(dlg)\n job.Start()\n dlg.ShowModal()\n\n\n \"\"\"\n def __init__(self, parent, job):\n self.job = job\n\n wx.Dialog.__init__(self, parent, -1, \"Progress\", size=(350,200))\n\n # vertical box sizer\n sizeAll = wx.BoxSizer(wx.VERTICAL)\n\n # Job status text\n self.JobStatusText = wx.StaticText(self, -1, \"Starting...\")\n sizeAll.Add(self.JobStatusText, 0, wx.EXPAND|wx.ALL, 8)\n\n # wxGague\n self.ProgressBar = wx.Gauge(self, -1, 10, wx.DefaultPosition, (250, 15))\n sizeAll.Add(self.ProgressBar, 0, wx.EXPAND|wx.ALL, 8)\n\n # horiz box sizer, and spacer to right-justify\n sizeRemaining = wx.BoxSizer(wx.HORIZONTAL)\n sizeRemaining.Add((2,2), 1, wx.EXPAND)\n\n # time remaining read-only edit\n # putting wide default text gets a reasonable initial layout.\n self.remainingText = wx.StaticText(self, -1, \"???:??\")\n sizeRemaining.Add(self.remainingText, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 8)\n\n # static text: remaining\n self.remainingLabel = wx.StaticText(self, -1, \"remaining\")\n sizeRemaining.Add(self.remainingLabel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 8)\n\n # add that row to the mix\n sizeAll.Add(sizeRemaining, 1, wx.EXPAND)\n\n # horiz box sizer &amp; spacer\n sizeButtons = wx.BoxSizer(wx.HORIZONTAL)\n sizeButtons.Add((2,2), 1, wx.EXPAND|wx.ADJUST_MINSIZE)\n\n # Pause Button\n self.PauseButton = wx.Button(self, -1, \"Pause\")\n sizeButtons.Add(self.PauseButton, 0, wx.ALL, 4)\n self.Bind(wx.EVT_BUTTON, self.OnPauseButton, self.PauseButton)\n\n # Cancel button\n self.CancelButton = wx.Button(self, wx.ID_CANCEL, \"Cancel\")\n sizeButtons.Add(self.CancelButton, 0, wx.ALL, 4)\n self.Bind(wx.EVT_BUTTON, self.OnCancel, self.CancelButton)\n\n # Add all the buttons on the bottom row to the dialog\n sizeAll.Add(sizeButtons, 0, wx.EXPAND|wx.ALL, 4)\n\n self.SetSizer(sizeAll)\n #sizeAll.Fit(self)\n sizeAll.SetSizeHints(self)\n\n # jobs tell us how they are doing\n self.Bind(EVT_PROGRESS_START, self.OnProgressStart)\n self.Bind(EVT_PROGRESS, self.OnProgress)\n self.Bind(EVT_DONE, self.OnDone)\n\n self.Layout()\n #\n\n def OnPauseButton(self, event):\n if self.job.isPaused:\n self.job.Continue()\n self.PauseButton.SetLabel(\"Pause\")\n self.Layout()\n else:\n self.job.Pause()\n self.PauseButton.SetLabel(\"Resume\")\n self.Layout()\n #\n #\n\n def OnCancel(self, event):\n self.job.Stop()\n #\n\n def OnProgressStart(self, event):\n self.ProgressBar.SetRange(event.total)\n self.statusUpdateTime = time.clock()\n #\n\n def OnProgress(self, event):\n # update the progress bar\n self.ProgressBar.SetValue(event.count)\n\n self.remainingText.SetLabel(self.job.TimeRemaining())\n\n # update the text a max of 20 times a second\n if time.clock() - self.statusUpdateTime &gt; 0.05:\n self.JobStatusText.SetLabel(str(self.job))\n self.statusUpdateTime = time.clock()\n self.Layout()\n #\n #\n\n # when a job is done\n def OnDone(self, event):\n self.ProgressBar.SetValue(0)\n self.JobStatusText.SetLabel(\"Finished\")\n self.Destroy()\n #\n#\n\nif __name__ == \"__main__\":\n app = wx.PySimpleApp()\n #job = EggTimerJob(duration = 10)\n job = FileCopyJob(\"VeryBigFile.mp4\", \"/tmp/test_junk.mp4\", 1024*1024*10)\n dlg = JobProgress(None, job)\n job.SetProgressMessageWindow(dlg)\n job.Start()\n dlg.ShowModal()\n#\n</code></pre>\n" }, { "answer_id": 24737210, "author": "frmdstryr", "author_id": 2362877, "author_profile": "https://Stackoverflow.com/users/2362877", "pm_score": 1, "selected": false, "text": "<p>If you want to use the Windows copy dialog with progress you can use these:</p>\n\n<ul>\n<li><a href=\"https://github.com/tjguk/winshell/\" rel=\"nofollow\">https://github.com/tjguk/winshell/</a></li>\n<li><a href=\"https://github.com/frmdstryr/pywinutils\" rel=\"nofollow\">https://github.com/frmdstryr/pywinutils</a></li>\n</ul>\n" }, { "answer_id": 51088330, "author": "Gabriel Coutinho De Miranda", "author_id": 8479907, "author_profile": "https://Stackoverflow.com/users/8479907", "pm_score": 2, "selected": false, "text": "<p>I have this shutil.copy() with progress bar made in a simple way just with built in modules.\nIf you are using utf-8 encoding you can get a progress like the second example in the gif image:\n<a href=\"https://i.stack.imgur.com/Qocmx.gif\" rel=\"nofollow noreferrer\">Progress bars examples for this:</a></p>\n\n<p>Read the comments to change style and colors. The first and last examples don't need utf-8.\nYou can use the command CPprogress(SOURCE, DESTINATION) just where you had shutil.copy(src, dst):</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nCPprogress(SOURCE, DESTINATION)\n\nI made this to give shutil.copy() [or shutil.copy2() in this case] a progress bar.\n\nYou can use CPprogress(SOURCE, DESTINATION) just like shutil.copy(src, dst). SOURCE must be a file path and DESTINATION a file or folder path.\n\nIt will give you a progress bar for each file copied. Just copy this code above the place where you want to use CPprogress(SOURCE, DESTINATION) in your code.\n\nYou can easily change the look of the progress bar:\n - To keep the style and just change the colors, replace the colors values of progressCOLOR and finalCOLOR (orange code at the end of the lines).\n - The use a solid block progress bar, # -*- coding: utf-8 -*- is required. Otherwise, you will get an encoding error. Some basic terminals, like xterm, may not show the progress bar because of the utf-8 characters.\n To use this style, remove the comments #STYLE# in lines ###COLORS### - BlueCOLOR and endBLOCK.\n In def getPERCECENTprogress() remove the comments #STYLE# AND COMMENT THE PREVIOUS line. Do the same in def CPprogress()\n If you don't want the utf-8 encoding, delete the four lines beginning with #STYLE#.\n\nNOTE: If you want to copy lots of small files, the copy process for file is so fast \n that all you will see is a lot of lines scrolling in you terminal window - not enough time for a 'progress'.\n In that case, I use an overall progress that shows only one progress bar to the complete job. nzX\n'''\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\n\n######## COLORS ######\nprogressCOLOR = '\\033[38;5;33;48;5;236m' #\\033[38;5;33;48;5;236m# copy inside '' for colored progressbar| orange:#\\033[38;5;208;48;5;235m\nfinalCOLOR = '\\033[38;5;33;48;5;33m' #\\033[38;5;33;48;5;33m# copy inside '' for colored progressbar| orange:#\\033[38;5;208;48;5;208m\n#STYLE#BlueCOLOR = '\\033[38;5;33m'#\\033[38;5;33m# copy inside '' for colored progressbar Orange#'\\033[38;5;208m'# # BG progress# #STYLE# \n#STYLE#endBLOCK = '' # ▌ copy OR '' for none # BG progress# #STYLE# requires utf8 coding header\n########\n\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nCEND = '\\033[0m'\n\ndef getPERCECENTprogress(source_path, destination_path):\n time.sleep(.24)\n if os.path.exists(destination_path):\n while os.path.getsize(source_path) != os.path.getsize(destination_path):\n sys.stdout.write('\\r')\n percentagem = int((float(os.path.getsize(destination_path))/float(os.path.getsize(source_path))) * 100)\n steps = int(percentagem/5)\n copiado = int(os.path.getsize(destination_path)/1000000)# Should be 1024000 but this get's equal to Thunar file manager report (Linux - Xfce)\n sizzz = int(os.path.getsize(source_path)/1000000)\n sys.stdout.write((\" {:d} / {:d} Mb \".format(copiado, sizzz)) + (BOLD + progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + (\" {:d}% \".format(percentagem))) # BG progress\n #STYLE#sys.stdout.write((\" {:d} / {:d} Mb \".format(copiado, sizzz)) + (BOLD + BlueCOLOR + \"▐\" + \"{:s}\".format('█'*steps) + CEND) + (\"{:s}\".format(' '*(20-steps))+ BOLD + BlueCOLOR + endBLOCK+ CEND) +(\" {:d}% \".format(percentagem))) #STYLE# # BG progress# closer to GUI but less compatible (no block bar with xterm) # requires utf8 coding header\n sys.stdout.flush()\n time.sleep(.01)\n\ndef CPprogress(SOURCE, DESTINATION):\n if os.path.isdir(DESTINATION):\n dst_file = os.path.join(DESTINATION, os.path.basename(SOURCE))\n else: dst_file = DESTINATION\n print \" \"\n print (BOLD + UNDERLINE + \"FROM:\" + CEND + \" \"), SOURCE\n print (BOLD + UNDERLINE + \"TO:\" + CEND + \" \"), dst_file\n print \" \"\n threading.Thread(name='progresso', target=getPERCECENTprogress, args=(SOURCE, dst_file)).start()\n shutil.copy2(SOURCE, DESTINATION)\n time.sleep(.02)\n sys.stdout.write('\\r')\n sys.stdout.write((\" {:d} / {:d} Mb \".format((int(os.path.getsize(dst_file)/1000000)), (int(os.path.getsize(SOURCE)/1000000)))) + (BOLD + finalCOLOR + \"{:20s}\".format('|'*20) + CEND) + (\" {:d}% \".format(100))) # BG progress 100%\n #STYLE#sys.stdout.write((\" {:d} / {:d} Mb \".format((int(os.path.getsize(dst_file)/1000000)), (int(os.path.getsize(SOURCE)/1000000)))) + (BOLD + BlueCOLOR + \"▐\" + \"{:s}{:s}\".format(('█'*20), endBLOCK) + CEND) + (\" {:d}% \".format(100))) #STYLE# # BG progress 100%# closer to GUI but less compatible (no block bar with xterm) # requires utf8 coding header\n sys.stdout.flush()\n print \" \"\n print \" \"\n\n'''\n#Ex. Copy all files from root of the source dir to destination dir\n\nfolderA = '/path/to/SOURCE' # SOURCE\nfolderB = '/path/to/DESTINATION' # DESTINATION\nfor FILE in os.listdir(folderA):\n if not os.path.isdir(os.path.join(folderA, FILE)):\n if os.path.exists(os.path.join(folderB, FILE)): continue # as we are using shutil.copy2() that overwrites destination, this skips existing files\n CPprogress(os.path.join(folderA, FILE), folderB) # use the command as if it was shutil.copy2() but with progress\n\n\n 75 / 150 Mb |||||||||| | 50%\n'''\n</code></pre>\n" }, { "answer_id": 51088424, "author": "Gabriel Coutinho De Miranda", "author_id": 8479907, "author_profile": "https://Stackoverflow.com/users/8479907", "pm_score": 0, "selected": false, "text": "<p>If you want an overall progress, you can use something like this (made for another script). Note that in this case, the 'threading.Thread' that calls the progress bar was placed outside the 'for' loop. Also, the measures need be taken in a different way. This is the third example (non utf-8) from the gif image in the previous answer. It adds a files 'ToGo’ counting:</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nEx.\nCopyProgress('/path/to/SOURCE', '/path/to/DESTINATION')\n\n\nI think this 'copy with overall progress' is very 'plastic' and can be easily adapted.\nBy default, it will RECURSIVELY copy the CONTENT of 'path/to/SOURCE' to 'path/to/DESTINATION/' keeping the directory tree.\n\nPaying attention to comments, there are 4 main options that can be immediately change:\n\n1 - The LOOK of the progress bar: see COLORS and the PAIR of STYLE lines in 'def getPERCECENTprogress'(inside and after the 'while' loop);\n\n2 - The DESTINATION path: to get 'path/to/DESTINATION/SOURCE_NAME' as target, comment the 2nd 'DST =' definition on the top of the 'def CopyProgress(SOURCE, DESTINATION)' function;\n\n3 - If you don't want to RECURSIVELY copy from sub-directories but just the files in the root source directory to the root of destination, you can use os.listdir() instead of os.walk(). Read the comments inside 'def CopyProgress(SOURCE, DESTINATION)' function to disable RECURSION. Be aware that the RECURSION changes(4x2) must be made in both os.walk() loops;\n\n4 - Handling destination files: if you use this in a situation where the destination filename may already exist, by default, the file is skipped and the loop will jump to the next and so on. On the other way shutil.copy2(), by default, overwrites destination file if exists. Alternatively, you can handle files that exist by overwriting or renaming (according to current date and time). To do that read the comments after 'if os.path.exists(dstFILE): continue' both in the count bytes loop and the main loop. Be aware that the changes must match in both loops (as described in comments) or the progress function will not work properly.\n\n'''\n\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\n\nprogressCOLOR = '\\033[38;5;33;48;5;236m' #BLUEgreyBG\nfinalCOLOR = '\\033[48;5;33m' #BLUEBG\n# check the color codes below and paste above\n\n###### COLORS #######\n# WHITEblueBG = '\\033[38;5;15;48;5;33m'\n# BLUE = '\\033[38;5;33m'\n# BLUEBG = '\\033[48;5;33m'\n# ORANGEBG = '\\033[48;5;208m'\n# BLUEgreyBG = '\\033[38;5;33;48;5;236m'\n# ORANGEgreyBG = '\\033[38;5;208;48;5;236m' # = '\\033[38;5;FOREGROUND;48;5;BACKGROUNDm' # ver 'https://i.stack.imgur.com/KTSQa.png' para 256 color codes\n# INVERT = '\\033[7m'\n###### COLORS #######\n\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nCEND = '\\033[0m'\n\nFilesLeft = 0\n\ndef FullFolderSize(path):\n TotalSize = 0\n if os.path.exists(path):# to be safely used # if FALSE returns 0\n for root, dirs, files in os.walk(path):\n for file in files:\n TotalSize += os.path.getsize(os.path.join(root, file))\n return TotalSize\n\ndef getPERCECENTprogress(source_path, destination_path, bytes_to_copy):\n dstINIsize = FullFolderSize(destination_path)\n time.sleep(.25)\n print \" \"\n print (BOLD + UNDERLINE + \"FROM:\" + CEND + \" \"), source_path\n print (BOLD + UNDERLINE + \"TO:\" + CEND + \" \"), destination_path\n print \" \"\n if os.path.exists(destination_path):\n while bytes_to_copy != (FullFolderSize(destination_path)-dstINIsize):\n sys.stdout.write('\\r')\n percentagem = int((float((FullFolderSize(destination_path)-dstINIsize))/float(bytes_to_copy)) * 100)\n steps = int(percentagem/5)\n copiado = '{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000))# Should be 1024000 but this get's closer to the file manager report\n sizzz = '{:,}'.format(int(bytes_to_copy/1000000))\n sys.stdout.write((\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (BOLD + progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))) # STYLE 1 progress default # \n #BOLD# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + BOLD + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))+ CEND) # STYLE 2 progress BOLD # \n #classic B/W# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (\"|{:20s}|\".format('|'*steps)) + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))+ CEND) # STYLE 3 progress classic B/W #\n sys.stdout.flush()\n time.sleep(.01)\n sys.stdout.write('\\r')\n time.sleep(.05)\n sys.stdout.write((\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (BOLD + finalCOLOR + \"{:20s}\".format(' '*20) + CEND) + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\") # STYLE 1 progress default # \n #BOLD# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (finalCOLOR + \"{:20s}\".format(' '*20) + CEND) + BOLD + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\" + CEND ) # STYLE 2 progress BOLD # \n #classic B/W# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (\"|{:20s}|\".format('|'*20)) + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\" + CEND ) # STYLE 3 progress classic B/W # \n sys.stdout.flush()\n print \" \"\n print \" \"\n\ndef CopyProgress(SOURCE, DESTINATION):\n global FilesLeft\n DST = os.path.join(DESTINATION, os.path.basename(SOURCE))\n # &lt;- the previous will copy the Source folder inside of the Destination folder. Result Target: path/to/Destination/SOURCE_NAME\n # -&gt; UNCOMMENT the next (# DST = DESTINATION) to copy the CONTENT of Source to the Destination. Result Target: path/to/Destination\n DST = DESTINATION # UNCOMMENT this to specify the Destination as the target itself and not the root folder of the target \n #\n if DST.startswith(SOURCE):\n print \" \"\n print BOLD + UNDERLINE + 'Source folder can\\'t be changed.' + CEND\n print 'Please check your target path...'\n print \" \"\n print BOLD + ' CANCELED' + CEND\n print \" \"\n exit()\n #count bytes to copy\n Bytes2copy = 0\n for root, dirs, files in os.walk(SOURCE): # USE for filename in os.listdir(SOURCE): # if you don't want RECURSION #\n dstDIR = root.replace(SOURCE, DST, 1) # USE dstDIR = DST # if you don't want RECURSION #\n for filename in files: # USE if not os.path.isdir(os.path.join(SOURCE, filename)): # if you don't want RECURSION #\n dstFILE = os.path.join(dstDIR, filename)\n if os.path.exists(dstFILE): continue # must match the main loop (after \"threading.Thread\")\n # To overwrite delete dstFILE first here so the progress works properly: ex. change continue to os.unlink(dstFILE)\n # To rename new files adding date and time, instead of deleating and overwriting, \n # comment 'if os.path.exists(dstFILE): continue'\n Bytes2copy += os.path.getsize(os.path.join(root, filename)) # USE os.path.getsize(os.path.join(SOURCE, filename)) # if you don't want RECURSION #\n FilesLeft += 1\n # &lt;- count bytes to copy\n #\n # Treading to call the preogress\n threading.Thread(name='progresso', target=getPERCECENTprogress, args=(SOURCE, DST, Bytes2copy)).start()\n # main loop\n for root, dirs, files in os.walk(SOURCE): # USE for filename in os.listdir(SOURCE): # if you don't want RECURSION #\n dstDIR = root.replace(SOURCE, DST, 1) # USE dstDIR = DST # if you don't want RECURSION #\n if not os.path.exists(dstDIR):\n os.makedirs(dstDIR)\n for filename in files: # USE if not os.path.isdir(os.path.join(SOURCE, filename)): # if you don't want RECURSION #\n srcFILE = os.path.join(root, filename) # USE os.path.join(SOURCE, filename) # if you don't want RECURSION #\n dstFILE = os.path.join(dstDIR, filename)\n if os.path.exists(dstFILE): continue # MUST MATCH THE PREVIOUS count bytes loop \n # &lt;- &lt;- this jumps to the next file without copying this file, if destination file exists. \n # Comment to copy with rename or overwrite dstFILE\n #\n # RENAME part below\n head, tail = os.path.splitext(filename)\n count = -1\n year = int(time.strftime(\"%Y\"))\n month = int(time.strftime(\"%m\"))\n day = int(time.strftime(\"%d\"))\n hour = int(time.strftime(\"%H\"))\n minute = int(time.strftime(\"%M\"))\n while os.path.exists(dstFILE):\n count += 1\n if count == 0:\n dstFILE = os.path.join(dstDIR, '{:s}[{:d}.{:d}.{:d}]{:d}-{:d}{:s}'.format(head, year, month, day, hour, minute, tail))\n else:\n dstFILE = os.path.join(dstDIR, '{:s}[{:d}.{:d}.{:d}]{:d}-{:d}[{:d}]{:s}'.format(head, year, month, day, hour, minute, count, tail))\n # END of RENAME part\n shutil.copy2(srcFILE, dstFILE)\n FilesLeft -= 1\n #\n\n'''\nEx.\nCopyProgress('/path/to/SOURCE', '/path/to/DESTINATION')\n'''\n</code></pre>\n" }, { "answer_id": 66257068, "author": "JBroadway", "author_id": 9065959, "author_profile": "https://Stackoverflow.com/users/9065959", "pm_score": 0, "selected": false, "text": "<p>Alternatively, you can use <code>ROBOCOPY</code> with the <code>os</code> module. It won't give you a progress bar, but it'll give you a percentage indicator as well as a robust summary at the end.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\ndef robocopy(source, destination, extension=''):\n os.system(&quot;robocopy {} {} {} /xx /njh&quot;.format(source, destination, extension))\n\n# Usage example\nrobocopy(r'C:\\Users\\Example\\Downloads', r'C:\\Users\\Example\\Desktop', '*.mov')\n</code></pre>\n<p>The example above will copy all .mov files to the desktop</p>\n<p>Leaving <code>extension</code> blank will copy all files in the source folder to the destination folder.</p>\n<p><code>/xx</code> removes extra files/directories from being listed</p>\n<p><code>/njh</code> removes job header</p>\n<p>See documentation for more info:\n<a href=\"https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy</a></p>\n" }, { "answer_id": 70777816, "author": "every skills", "author_id": 15099592, "author_profile": "https://Stackoverflow.com/users/15099592", "pm_score": 0, "selected": false, "text": "<p>That is simple PySide app can copy any file from source to destination</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/python3\n\nimport os\nimport sys\nfrom PySide2.QtWidgets import QProgressBar, QApplication, QDialog, QMainWindow, QPushButton\nfrom PySide2.QtCore import QThread, Signal, Slot\n\n\nclass ProgressDialog(QDialog):\n def __init__(self, parent, source, destination):\n QDialog.__init__(self, parent)\n \n self.resize(400, 50)\n \n self.parent = parent\n self.source = source\n self.destination = destination\n \n self.prog = QProgressBar(self)\n self.prog.setMaximum(100)\n self.prog.setMinimum(0)\n self.prog.setFormat(&quot;%p%&quot;)\n\n def start(self):\n self.show()\n self.copy()\n\n def copy(self):\n copy_thread = CopyThread(self, self.source, self.destination)\n copy_thread.procPartDone.connect(self.update_progress)\n copy_thread.procDone.connect(self.finished_copy)\n copy_thread.start()\n\n def update_progress(self, progress):\n self.prog.setValue(progress)\n\n def finished_copy(self, state):\n self.close()\n\nclass CopyThread(QThread):\n\n procDone = Signal(bool)\n procPartDone = Signal(int)\n\n def __init__(self, parent, source: str, destination: str):\n QThread.__init__(self, parent)\n \n self.source = source\n self.destination = destination\n\n def run(self):\n self.copy()\n self.procDone.emit(True)\n\n def copy(self):\n source_size = os.stat(self.source).st_size\n copied = 0\n\n with open(self.source, &quot;rb&quot;) as source, open(self.destination, &quot;wb&quot;) as target:\n while True:\n chunk = source.read(1024)\n if not chunk:\n break\n\n target.write(chunk)\n copied += len(chunk)\n\n self.procPartDone.emit(copied * 100 / source_size)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self, parent: object = None) -&gt; None:\n super().__init__(parent)\n \n self.src = &quot;/path/to/file.ext&quot;\n self.dest = &quot;/path/to/file.ext&quot;\n\n self.btn = QPushButton(self)\n self.btn.setText(&quot;Start copy&quot;)\n self.btn.clicked.connect(self.run)\n \n self.setCentralWidget(self.btn)\n \n def run(self):\n self.prog = ProgressDialog(self, self.src, self.dest)\n self.prog.start()\n\n\ndef main(): \n app = QApplication(sys.argv)\n \n window = MainWindow()\n window.show()\n \n sys.exit(app.exec_())\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<h4>Save this script in the 'main.py' file and execute the command</h4>\n<pre class=\"lang-sh prettyprint-override\"><code>python3 main.py\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
When copying large files using `shutil.copy()`, you get no indication of how the operation is progressing.. I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of `open().read()` and `.write()` to do the actual copying. It displays the progress bar using `sys.stdout.write("\r%s\r" % (the_progress_bar))` which is a little hackish, but it works. You can see the code (in context) [on github here](http://github.com/dbr/checktveps/tree/1be8f4445fbf766eba25f98f78ec52e955571608/autoPathTv.py#L64-153) Is there any built-in module that will do this better? Is there any improvements that can be made to this code?
Two things: * I would make the default block size a *lot* larger than 512. I would start with 16384 and perhaps more. * For modularity, it might be better to have the `copy_with_prog` function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress. Perhaps something like this: ``` def copy_with_prog(src, dest, callback = None): while True: # copy loop stuff if callback: callback(pos, total) prog = ProgressBar(...) copy_with_prog(src, dest, lambda pos, total: prog.update(pos, total)) ```
274,496
<p>I've built web apps before that utilize phpBB session, and user data. The common move is to use code like this:</p> <pre><code>define('IN_PHPBB', true); //replace $phpbb_root_path with path to your forum $phpbb_root_path = '../forum/'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); // Start session management $user-&gt;session_begin(); $auth-&gt;acl($user-&gt;data); $user-&gt;setup(); </code></pre> <p>However, by including <code>common.php</code>, I bring along a crap-load of other methods that run into other methods I've got setup.</p> <p>In my example, I'm running the application using CodeIgniter, which already has a "redirect" method. This question should apply to anyone who has pre-built methods that may run into the phpBB methods.</p> <p>Basically, all I need to do is:</p> <ol> <li>Make sure the user is logged in <code>$user-&gt;data[username] == Anonymous</code></li> <li>Utilize data from '$user->data' such as the user's ID, screenname, etc.</li> </ol> <p>Could I grab the <code>$user-&gt;data</code> array, and somehow save it to my own session? Does anyone have any ideas on this? Thanks in advance!</p>
[ { "answer_id": 274497, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>Two things:</p>\n\n<ul>\n<li>I would make the default block size a <em>lot</em> larger than 512. I would start with 16384 and perhaps more.</li>\n<li>For modularity, it might be better to have the <code>copy_with_prog</code> function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress.</li>\n</ul>\n\n<p>Perhaps something like this:</p>\n\n<pre><code>def copy_with_prog(src, dest, callback = None):\n while True:\n # copy loop stuff\n if callback:\n callback(pos, total)\n\nprog = ProgressBar(...)\ncopy_with_prog(src, dest, lambda pos, total: prog.update(pos, total))\n</code></pre>\n" }, { "answer_id": 275945, "author": "Jim Carroll", "author_id": 35922, "author_profile": "https://Stackoverflow.com/users/35922", "pm_score": 3, "selected": false, "text": "<p>Overkill? Perhaps. But on almost any system, Linux, Mac, and With a quick wxWidgets install on Windows, you can have the real deal, with pause and cancel buttons in a gui setup. Macs ship with wxWidgets these days, and it's a common package on Linux.</p>\n\n<p>A single file is very quick (it will immediately finish and look broken) so you might consider creating a fileSet job that ticks along once per file instead of once per block. Enjoy!</p>\n\n<p>-Jim Carroll</p>\n\n<pre><code>\"\"\"\nThreaded Jobs.\n\nAny class that does a long running process can inherit\nfrom ThreadedJob. This enables running as a background\nthread, progress notification, pause and cancel. The\ntime remaining is also calculated by the ThreadedJob class.\n\"\"\"\nimport wx.lib.newevent\nimport thread\nimport exceptions\nimport time\n\n(RunEvent, EVT_RUN) = wx.lib.newevent.NewEvent()\n(CancelEvent, EVT_CANCEL) = wx.lib.newevent.NewEvent()\n(DoneEvent, EVT_DONE) = wx.lib.newevent.NewEvent()\n(ProgressStartEvent, EVT_PROGRESS_START) = wx.lib.newevent.NewEvent()\n(ProgressEvent, EVT_PROGRESS) = wx.lib.newevent.NewEvent()\n\nclass InterruptedException(exceptions.Exception):\n def __init__(self, args = None):\n self.args = args\n #\n#\n\nclass ThreadedJob:\n def __init__(self):\n # tell them ten seconds at first\n self.secondsRemaining = 10.0\n self.lastTick = 0\n\n # not running yet\n self.isPaused = False\n self.isRunning = False\n self.keepGoing = True\n\n def Start(self):\n self.keepGoing = self.isRunning = True\n thread.start_new_thread(self.Run, ())\n\n self.isPaused = False\n #\n\n def Stop(self):\n self.keepGoing = False\n #\n\n def WaitUntilStopped(self):\n while self.isRunning:\n time.sleep(0.1)\n wx.SafeYield()\n #\n #\n\n def IsRunning(self):\n return self.isRunning\n #\n\n def Run(self):\n # this is overridden by the\n # concrete ThreadedJob\n print \"Run was not overloaded\"\n self.JobFinished()\n\n pass\n #\n\n def Pause(self):\n self.isPaused = True\n pass\n #\n\n def Continue(self):\n self.isPaused = False\n pass\n #\n\n def PossibleStoppingPoint(self):\n if not self.keepGoing:\n raise InterruptedException(\"process interrupted.\")\n wx.SafeYield()\n\n # allow cancel while paused\n while self.isPaused:\n if not self.keepGoing:\n raise InterruptedException(\"process interrupted.\")\n\n # don't hog the CPU\n time.sleep(0.1)\n #\n #\n\n def SetProgressMessageWindow(self, win):\n self.win = win\n #\n\n def JobBeginning(self, totalTicks):\n\n self.lastIterationTime = time.time()\n self.totalTicks = totalTicks\n\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, ProgressStartEvent(total=totalTicks))\n #\n #\n\n def JobProgress(self, currentTick):\n dt = time.time() - self.lastIterationTime\n self.lastIterationTime = time.time()\n dtick = currentTick - self.lastTick\n self.lastTick = currentTick\n\n alpha = 0.92\n if currentTick &gt; 1:\n self.secondsPerTick = dt * (1.0 - alpha) + (self.secondsPerTick * alpha)\n else:\n self.secondsPerTick = dt\n #\n\n if dtick &gt; 0:\n self.secondsPerTick /= dtick\n\n self.secondsRemaining = self.secondsPerTick * (self.totalTicks - 1 - currentTick) + 1\n\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, ProgressEvent(count=currentTick))\n #\n #\n\n def SecondsRemaining(self):\n return self.secondsRemaining\n #\n\n def TimeRemaining(self):\n\n if 1: #self.secondsRemaining &gt; 3:\n minutes = self.secondsRemaining // 60\n seconds = int(self.secondsRemaining % 60.0)\n return \"%i:%02i\" % (minutes, seconds)\n else:\n return \"a few\"\n #\n\n def JobFinished(self):\n if hasattr(self, \"win\") and self.win:\n wx.PostEvent(self.win, DoneEvent())\n #\n\n # flag we're done before we post the all done message\n self.isRunning = False\n #\n#\n\nclass EggTimerJob(ThreadedJob):\n \"\"\" A sample Job that demonstrates the mechanisms and features of the Threaded Job\"\"\"\n def __init__(self, duration):\n self.duration = duration\n ThreadedJob.__init__(self)\n #\n\n def Run(self):\n \"\"\" This can either be run directly for synchronous use of the job,\n or started as a thread when ThreadedJob.Start() is called.\n\n It is responsible for calling JobBeginning, JobProgress, and JobFinished.\n And as often as possible, calling PossibleStoppingPoint() which will \n sleep if the user pauses, and raise an exception if the user cancels.\n \"\"\"\n self.time0 = time.clock()\n self.JobBeginning(self.duration)\n\n try:\n for count in range(0, self.duration):\n time.sleep(1.0)\n self.JobProgress(count)\n self.PossibleStoppingPoint()\n #\n except InterruptedException:\n # clean up if user stops the Job early\n print \"canceled prematurely!\"\n #\n\n # always signal the end of the job\n self.JobFinished()\n #\n #\n\n def __str__(self):\n \"\"\" The job progress dialog expects the job to describe its current state.\"\"\"\n response = []\n if self.isPaused:\n response.append(\"Paused Counting\")\n elif not self.isRunning:\n response.append(\"Will Count the seconds\")\n else:\n response.append(\"Counting\")\n #\n return \" \".join(response)\n #\n#\n\nclass FileCopyJob(ThreadedJob):\n \"\"\" A common file copy Job. \"\"\"\n\n def __init__(self, orig_filename, copy_filename, block_size=32*1024):\n\n self.src = orig_filename\n self.dest = copy_filename\n self.block_size = block_size\n ThreadedJob.__init__(self)\n #\n\n def Run(self):\n \"\"\" This can either be run directly for synchronous use of the job,\n or started as a thread when ThreadedJob.Start() is called.\n\n It is responsible for calling JobBeginning, JobProgress, and JobFinished.\n And as often as possible, calling PossibleStoppingPoint() which will \n sleep if the user pauses, and raise an exception if the user cancels.\n \"\"\"\n self.time0 = time.clock()\n\n try:\n source = open(self.src, 'rb')\n\n # how many blocks?\n import os\n (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime) = os.stat(self.src)\n num_blocks = st_size / self.block_size\n current_block = 0\n\n self.JobBeginning(num_blocks)\n\n dest = open(self.dest, 'wb')\n\n while 1:\n copy_buffer = source.read(self.block_size)\n if copy_buffer:\n dest.write(copy_buffer)\n current_block += 1\n self.JobProgress(current_block)\n self.PossibleStoppingPoint()\n else:\n break\n\n source.close()\n dest.close()\n\n except InterruptedException:\n # clean up if user stops the Job early\n dest.close()\n # unlink / delete the file that is partially copied\n os.unlink(self.dest)\n print \"canceled, dest deleted!\"\n #\n\n # always signal the end of the job\n self.JobFinished()\n #\n #\n\n def __str__(self):\n \"\"\" The job progress dialog expects the job to describe its current state.\"\"\"\n response = []\n if self.isPaused:\n response.append(\"Paused Copy\")\n elif not self.isRunning:\n response.append(\"Will Copy a file\")\n else:\n response.append(\"Copying\")\n #\n return \" \".join(response)\n #\n#\n\nclass JobProgress(wx.Dialog):\n \"\"\" This dialog shows the progress of any ThreadedJob.\n\n It can be shown Modally if the main application needs to suspend\n operation, or it can be shown Modelessly for background progress\n reporting.\n\n app = wx.PySimpleApp()\n job = EggTimerJob(duration = 10)\n dlg = JobProgress(None, job)\n job.SetProgressMessageWindow(dlg)\n job.Start()\n dlg.ShowModal()\n\n\n \"\"\"\n def __init__(self, parent, job):\n self.job = job\n\n wx.Dialog.__init__(self, parent, -1, \"Progress\", size=(350,200))\n\n # vertical box sizer\n sizeAll = wx.BoxSizer(wx.VERTICAL)\n\n # Job status text\n self.JobStatusText = wx.StaticText(self, -1, \"Starting...\")\n sizeAll.Add(self.JobStatusText, 0, wx.EXPAND|wx.ALL, 8)\n\n # wxGague\n self.ProgressBar = wx.Gauge(self, -1, 10, wx.DefaultPosition, (250, 15))\n sizeAll.Add(self.ProgressBar, 0, wx.EXPAND|wx.ALL, 8)\n\n # horiz box sizer, and spacer to right-justify\n sizeRemaining = wx.BoxSizer(wx.HORIZONTAL)\n sizeRemaining.Add((2,2), 1, wx.EXPAND)\n\n # time remaining read-only edit\n # putting wide default text gets a reasonable initial layout.\n self.remainingText = wx.StaticText(self, -1, \"???:??\")\n sizeRemaining.Add(self.remainingText, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 8)\n\n # static text: remaining\n self.remainingLabel = wx.StaticText(self, -1, \"remaining\")\n sizeRemaining.Add(self.remainingLabel, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 8)\n\n # add that row to the mix\n sizeAll.Add(sizeRemaining, 1, wx.EXPAND)\n\n # horiz box sizer &amp; spacer\n sizeButtons = wx.BoxSizer(wx.HORIZONTAL)\n sizeButtons.Add((2,2), 1, wx.EXPAND|wx.ADJUST_MINSIZE)\n\n # Pause Button\n self.PauseButton = wx.Button(self, -1, \"Pause\")\n sizeButtons.Add(self.PauseButton, 0, wx.ALL, 4)\n self.Bind(wx.EVT_BUTTON, self.OnPauseButton, self.PauseButton)\n\n # Cancel button\n self.CancelButton = wx.Button(self, wx.ID_CANCEL, \"Cancel\")\n sizeButtons.Add(self.CancelButton, 0, wx.ALL, 4)\n self.Bind(wx.EVT_BUTTON, self.OnCancel, self.CancelButton)\n\n # Add all the buttons on the bottom row to the dialog\n sizeAll.Add(sizeButtons, 0, wx.EXPAND|wx.ALL, 4)\n\n self.SetSizer(sizeAll)\n #sizeAll.Fit(self)\n sizeAll.SetSizeHints(self)\n\n # jobs tell us how they are doing\n self.Bind(EVT_PROGRESS_START, self.OnProgressStart)\n self.Bind(EVT_PROGRESS, self.OnProgress)\n self.Bind(EVT_DONE, self.OnDone)\n\n self.Layout()\n #\n\n def OnPauseButton(self, event):\n if self.job.isPaused:\n self.job.Continue()\n self.PauseButton.SetLabel(\"Pause\")\n self.Layout()\n else:\n self.job.Pause()\n self.PauseButton.SetLabel(\"Resume\")\n self.Layout()\n #\n #\n\n def OnCancel(self, event):\n self.job.Stop()\n #\n\n def OnProgressStart(self, event):\n self.ProgressBar.SetRange(event.total)\n self.statusUpdateTime = time.clock()\n #\n\n def OnProgress(self, event):\n # update the progress bar\n self.ProgressBar.SetValue(event.count)\n\n self.remainingText.SetLabel(self.job.TimeRemaining())\n\n # update the text a max of 20 times a second\n if time.clock() - self.statusUpdateTime &gt; 0.05:\n self.JobStatusText.SetLabel(str(self.job))\n self.statusUpdateTime = time.clock()\n self.Layout()\n #\n #\n\n # when a job is done\n def OnDone(self, event):\n self.ProgressBar.SetValue(0)\n self.JobStatusText.SetLabel(\"Finished\")\n self.Destroy()\n #\n#\n\nif __name__ == \"__main__\":\n app = wx.PySimpleApp()\n #job = EggTimerJob(duration = 10)\n job = FileCopyJob(\"VeryBigFile.mp4\", \"/tmp/test_junk.mp4\", 1024*1024*10)\n dlg = JobProgress(None, job)\n job.SetProgressMessageWindow(dlg)\n job.Start()\n dlg.ShowModal()\n#\n</code></pre>\n" }, { "answer_id": 24737210, "author": "frmdstryr", "author_id": 2362877, "author_profile": "https://Stackoverflow.com/users/2362877", "pm_score": 1, "selected": false, "text": "<p>If you want to use the Windows copy dialog with progress you can use these:</p>\n\n<ul>\n<li><a href=\"https://github.com/tjguk/winshell/\" rel=\"nofollow\">https://github.com/tjguk/winshell/</a></li>\n<li><a href=\"https://github.com/frmdstryr/pywinutils\" rel=\"nofollow\">https://github.com/frmdstryr/pywinutils</a></li>\n</ul>\n" }, { "answer_id": 51088330, "author": "Gabriel Coutinho De Miranda", "author_id": 8479907, "author_profile": "https://Stackoverflow.com/users/8479907", "pm_score": 2, "selected": false, "text": "<p>I have this shutil.copy() with progress bar made in a simple way just with built in modules.\nIf you are using utf-8 encoding you can get a progress like the second example in the gif image:\n<a href=\"https://i.stack.imgur.com/Qocmx.gif\" rel=\"nofollow noreferrer\">Progress bars examples for this:</a></p>\n\n<p>Read the comments to change style and colors. The first and last examples don't need utf-8.\nYou can use the command CPprogress(SOURCE, DESTINATION) just where you had shutil.copy(src, dst):</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nCPprogress(SOURCE, DESTINATION)\n\nI made this to give shutil.copy() [or shutil.copy2() in this case] a progress bar.\n\nYou can use CPprogress(SOURCE, DESTINATION) just like shutil.copy(src, dst). SOURCE must be a file path and DESTINATION a file or folder path.\n\nIt will give you a progress bar for each file copied. Just copy this code above the place where you want to use CPprogress(SOURCE, DESTINATION) in your code.\n\nYou can easily change the look of the progress bar:\n - To keep the style and just change the colors, replace the colors values of progressCOLOR and finalCOLOR (orange code at the end of the lines).\n - The use a solid block progress bar, # -*- coding: utf-8 -*- is required. Otherwise, you will get an encoding error. Some basic terminals, like xterm, may not show the progress bar because of the utf-8 characters.\n To use this style, remove the comments #STYLE# in lines ###COLORS### - BlueCOLOR and endBLOCK.\n In def getPERCECENTprogress() remove the comments #STYLE# AND COMMENT THE PREVIOUS line. Do the same in def CPprogress()\n If you don't want the utf-8 encoding, delete the four lines beginning with #STYLE#.\n\nNOTE: If you want to copy lots of small files, the copy process for file is so fast \n that all you will see is a lot of lines scrolling in you terminal window - not enough time for a 'progress'.\n In that case, I use an overall progress that shows only one progress bar to the complete job. nzX\n'''\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\n\n######## COLORS ######\nprogressCOLOR = '\\033[38;5;33;48;5;236m' #\\033[38;5;33;48;5;236m# copy inside '' for colored progressbar| orange:#\\033[38;5;208;48;5;235m\nfinalCOLOR = '\\033[38;5;33;48;5;33m' #\\033[38;5;33;48;5;33m# copy inside '' for colored progressbar| orange:#\\033[38;5;208;48;5;208m\n#STYLE#BlueCOLOR = '\\033[38;5;33m'#\\033[38;5;33m# copy inside '' for colored progressbar Orange#'\\033[38;5;208m'# # BG progress# #STYLE# \n#STYLE#endBLOCK = '' # ▌ copy OR '' for none # BG progress# #STYLE# requires utf8 coding header\n########\n\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nCEND = '\\033[0m'\n\ndef getPERCECENTprogress(source_path, destination_path):\n time.sleep(.24)\n if os.path.exists(destination_path):\n while os.path.getsize(source_path) != os.path.getsize(destination_path):\n sys.stdout.write('\\r')\n percentagem = int((float(os.path.getsize(destination_path))/float(os.path.getsize(source_path))) * 100)\n steps = int(percentagem/5)\n copiado = int(os.path.getsize(destination_path)/1000000)# Should be 1024000 but this get's equal to Thunar file manager report (Linux - Xfce)\n sizzz = int(os.path.getsize(source_path)/1000000)\n sys.stdout.write((\" {:d} / {:d} Mb \".format(copiado, sizzz)) + (BOLD + progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + (\" {:d}% \".format(percentagem))) # BG progress\n #STYLE#sys.stdout.write((\" {:d} / {:d} Mb \".format(copiado, sizzz)) + (BOLD + BlueCOLOR + \"▐\" + \"{:s}\".format('█'*steps) + CEND) + (\"{:s}\".format(' '*(20-steps))+ BOLD + BlueCOLOR + endBLOCK+ CEND) +(\" {:d}% \".format(percentagem))) #STYLE# # BG progress# closer to GUI but less compatible (no block bar with xterm) # requires utf8 coding header\n sys.stdout.flush()\n time.sleep(.01)\n\ndef CPprogress(SOURCE, DESTINATION):\n if os.path.isdir(DESTINATION):\n dst_file = os.path.join(DESTINATION, os.path.basename(SOURCE))\n else: dst_file = DESTINATION\n print \" \"\n print (BOLD + UNDERLINE + \"FROM:\" + CEND + \" \"), SOURCE\n print (BOLD + UNDERLINE + \"TO:\" + CEND + \" \"), dst_file\n print \" \"\n threading.Thread(name='progresso', target=getPERCECENTprogress, args=(SOURCE, dst_file)).start()\n shutil.copy2(SOURCE, DESTINATION)\n time.sleep(.02)\n sys.stdout.write('\\r')\n sys.stdout.write((\" {:d} / {:d} Mb \".format((int(os.path.getsize(dst_file)/1000000)), (int(os.path.getsize(SOURCE)/1000000)))) + (BOLD + finalCOLOR + \"{:20s}\".format('|'*20) + CEND) + (\" {:d}% \".format(100))) # BG progress 100%\n #STYLE#sys.stdout.write((\" {:d} / {:d} Mb \".format((int(os.path.getsize(dst_file)/1000000)), (int(os.path.getsize(SOURCE)/1000000)))) + (BOLD + BlueCOLOR + \"▐\" + \"{:s}{:s}\".format(('█'*20), endBLOCK) + CEND) + (\" {:d}% \".format(100))) #STYLE# # BG progress 100%# closer to GUI but less compatible (no block bar with xterm) # requires utf8 coding header\n sys.stdout.flush()\n print \" \"\n print \" \"\n\n'''\n#Ex. Copy all files from root of the source dir to destination dir\n\nfolderA = '/path/to/SOURCE' # SOURCE\nfolderB = '/path/to/DESTINATION' # DESTINATION\nfor FILE in os.listdir(folderA):\n if not os.path.isdir(os.path.join(folderA, FILE)):\n if os.path.exists(os.path.join(folderB, FILE)): continue # as we are using shutil.copy2() that overwrites destination, this skips existing files\n CPprogress(os.path.join(folderA, FILE), folderB) # use the command as if it was shutil.copy2() but with progress\n\n\n 75 / 150 Mb |||||||||| | 50%\n'''\n</code></pre>\n" }, { "answer_id": 51088424, "author": "Gabriel Coutinho De Miranda", "author_id": 8479907, "author_profile": "https://Stackoverflow.com/users/8479907", "pm_score": 0, "selected": false, "text": "<p>If you want an overall progress, you can use something like this (made for another script). Note that in this case, the 'threading.Thread' that calls the progress bar was placed outside the 'for' loop. Also, the measures need be taken in a different way. This is the third example (non utf-8) from the gif image in the previous answer. It adds a files 'ToGo’ counting:</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nEx.\nCopyProgress('/path/to/SOURCE', '/path/to/DESTINATION')\n\n\nI think this 'copy with overall progress' is very 'plastic' and can be easily adapted.\nBy default, it will RECURSIVELY copy the CONTENT of 'path/to/SOURCE' to 'path/to/DESTINATION/' keeping the directory tree.\n\nPaying attention to comments, there are 4 main options that can be immediately change:\n\n1 - The LOOK of the progress bar: see COLORS and the PAIR of STYLE lines in 'def getPERCECENTprogress'(inside and after the 'while' loop);\n\n2 - The DESTINATION path: to get 'path/to/DESTINATION/SOURCE_NAME' as target, comment the 2nd 'DST =' definition on the top of the 'def CopyProgress(SOURCE, DESTINATION)' function;\n\n3 - If you don't want to RECURSIVELY copy from sub-directories but just the files in the root source directory to the root of destination, you can use os.listdir() instead of os.walk(). Read the comments inside 'def CopyProgress(SOURCE, DESTINATION)' function to disable RECURSION. Be aware that the RECURSION changes(4x2) must be made in both os.walk() loops;\n\n4 - Handling destination files: if you use this in a situation where the destination filename may already exist, by default, the file is skipped and the loop will jump to the next and so on. On the other way shutil.copy2(), by default, overwrites destination file if exists. Alternatively, you can handle files that exist by overwriting or renaming (according to current date and time). To do that read the comments after 'if os.path.exists(dstFILE): continue' both in the count bytes loop and the main loop. Be aware that the changes must match in both loops (as described in comments) or the progress function will not work properly.\n\n'''\n\nimport os\nimport shutil\nimport sys\nimport threading\nimport time\n\nprogressCOLOR = '\\033[38;5;33;48;5;236m' #BLUEgreyBG\nfinalCOLOR = '\\033[48;5;33m' #BLUEBG\n# check the color codes below and paste above\n\n###### COLORS #######\n# WHITEblueBG = '\\033[38;5;15;48;5;33m'\n# BLUE = '\\033[38;5;33m'\n# BLUEBG = '\\033[48;5;33m'\n# ORANGEBG = '\\033[48;5;208m'\n# BLUEgreyBG = '\\033[38;5;33;48;5;236m'\n# ORANGEgreyBG = '\\033[38;5;208;48;5;236m' # = '\\033[38;5;FOREGROUND;48;5;BACKGROUNDm' # ver 'https://i.stack.imgur.com/KTSQa.png' para 256 color codes\n# INVERT = '\\033[7m'\n###### COLORS #######\n\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nCEND = '\\033[0m'\n\nFilesLeft = 0\n\ndef FullFolderSize(path):\n TotalSize = 0\n if os.path.exists(path):# to be safely used # if FALSE returns 0\n for root, dirs, files in os.walk(path):\n for file in files:\n TotalSize += os.path.getsize(os.path.join(root, file))\n return TotalSize\n\ndef getPERCECENTprogress(source_path, destination_path, bytes_to_copy):\n dstINIsize = FullFolderSize(destination_path)\n time.sleep(.25)\n print \" \"\n print (BOLD + UNDERLINE + \"FROM:\" + CEND + \" \"), source_path\n print (BOLD + UNDERLINE + \"TO:\" + CEND + \" \"), destination_path\n print \" \"\n if os.path.exists(destination_path):\n while bytes_to_copy != (FullFolderSize(destination_path)-dstINIsize):\n sys.stdout.write('\\r')\n percentagem = int((float((FullFolderSize(destination_path)-dstINIsize))/float(bytes_to_copy)) * 100)\n steps = int(percentagem/5)\n copiado = '{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000))# Should be 1024000 but this get's closer to the file manager report\n sizzz = '{:,}'.format(int(bytes_to_copy/1000000))\n sys.stdout.write((\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (BOLD + progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))) # STYLE 1 progress default # \n #BOLD# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (progressCOLOR + \"{:20s}\".format('|'*steps) + CEND) + BOLD + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))+ CEND) # STYLE 2 progress BOLD # \n #classic B/W# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format(copiado, sizzz)) + (\"|{:20s}|\".format('|'*steps)) + (\" {:d}% \".format(percentagem)) + (\" {:d} ToGo \".format(FilesLeft))+ CEND) # STYLE 3 progress classic B/W #\n sys.stdout.flush()\n time.sleep(.01)\n sys.stdout.write('\\r')\n time.sleep(.05)\n sys.stdout.write((\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (BOLD + finalCOLOR + \"{:20s}\".format(' '*20) + CEND) + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\") # STYLE 1 progress default # \n #BOLD# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (finalCOLOR + \"{:20s}\".format(' '*20) + CEND) + BOLD + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\" + CEND ) # STYLE 2 progress BOLD # \n #classic B/W# sys.stdout.write(BOLD + (\" {:s} / {:s} Mb \".format('{:,}'.format(int((FullFolderSize(destination_path)-dstINIsize)/1000000)), '{:,}'.format(int(bytes_to_copy/1000000)))) + (\"|{:20s}|\".format('|'*20)) + (\" {:d}% \".format( 100)) + (\" {:s} \".format(' ')) + \"\\n\" + CEND ) # STYLE 3 progress classic B/W # \n sys.stdout.flush()\n print \" \"\n print \" \"\n\ndef CopyProgress(SOURCE, DESTINATION):\n global FilesLeft\n DST = os.path.join(DESTINATION, os.path.basename(SOURCE))\n # &lt;- the previous will copy the Source folder inside of the Destination folder. Result Target: path/to/Destination/SOURCE_NAME\n # -&gt; UNCOMMENT the next (# DST = DESTINATION) to copy the CONTENT of Source to the Destination. Result Target: path/to/Destination\n DST = DESTINATION # UNCOMMENT this to specify the Destination as the target itself and not the root folder of the target \n #\n if DST.startswith(SOURCE):\n print \" \"\n print BOLD + UNDERLINE + 'Source folder can\\'t be changed.' + CEND\n print 'Please check your target path...'\n print \" \"\n print BOLD + ' CANCELED' + CEND\n print \" \"\n exit()\n #count bytes to copy\n Bytes2copy = 0\n for root, dirs, files in os.walk(SOURCE): # USE for filename in os.listdir(SOURCE): # if you don't want RECURSION #\n dstDIR = root.replace(SOURCE, DST, 1) # USE dstDIR = DST # if you don't want RECURSION #\n for filename in files: # USE if not os.path.isdir(os.path.join(SOURCE, filename)): # if you don't want RECURSION #\n dstFILE = os.path.join(dstDIR, filename)\n if os.path.exists(dstFILE): continue # must match the main loop (after \"threading.Thread\")\n # To overwrite delete dstFILE first here so the progress works properly: ex. change continue to os.unlink(dstFILE)\n # To rename new files adding date and time, instead of deleating and overwriting, \n # comment 'if os.path.exists(dstFILE): continue'\n Bytes2copy += os.path.getsize(os.path.join(root, filename)) # USE os.path.getsize(os.path.join(SOURCE, filename)) # if you don't want RECURSION #\n FilesLeft += 1\n # &lt;- count bytes to copy\n #\n # Treading to call the preogress\n threading.Thread(name='progresso', target=getPERCECENTprogress, args=(SOURCE, DST, Bytes2copy)).start()\n # main loop\n for root, dirs, files in os.walk(SOURCE): # USE for filename in os.listdir(SOURCE): # if you don't want RECURSION #\n dstDIR = root.replace(SOURCE, DST, 1) # USE dstDIR = DST # if you don't want RECURSION #\n if not os.path.exists(dstDIR):\n os.makedirs(dstDIR)\n for filename in files: # USE if not os.path.isdir(os.path.join(SOURCE, filename)): # if you don't want RECURSION #\n srcFILE = os.path.join(root, filename) # USE os.path.join(SOURCE, filename) # if you don't want RECURSION #\n dstFILE = os.path.join(dstDIR, filename)\n if os.path.exists(dstFILE): continue # MUST MATCH THE PREVIOUS count bytes loop \n # &lt;- &lt;- this jumps to the next file without copying this file, if destination file exists. \n # Comment to copy with rename or overwrite dstFILE\n #\n # RENAME part below\n head, tail = os.path.splitext(filename)\n count = -1\n year = int(time.strftime(\"%Y\"))\n month = int(time.strftime(\"%m\"))\n day = int(time.strftime(\"%d\"))\n hour = int(time.strftime(\"%H\"))\n minute = int(time.strftime(\"%M\"))\n while os.path.exists(dstFILE):\n count += 1\n if count == 0:\n dstFILE = os.path.join(dstDIR, '{:s}[{:d}.{:d}.{:d}]{:d}-{:d}{:s}'.format(head, year, month, day, hour, minute, tail))\n else:\n dstFILE = os.path.join(dstDIR, '{:s}[{:d}.{:d}.{:d}]{:d}-{:d}[{:d}]{:s}'.format(head, year, month, day, hour, minute, count, tail))\n # END of RENAME part\n shutil.copy2(srcFILE, dstFILE)\n FilesLeft -= 1\n #\n\n'''\nEx.\nCopyProgress('/path/to/SOURCE', '/path/to/DESTINATION')\n'''\n</code></pre>\n" }, { "answer_id": 66257068, "author": "JBroadway", "author_id": 9065959, "author_profile": "https://Stackoverflow.com/users/9065959", "pm_score": 0, "selected": false, "text": "<p>Alternatively, you can use <code>ROBOCOPY</code> with the <code>os</code> module. It won't give you a progress bar, but it'll give you a percentage indicator as well as a robust summary at the end.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\ndef robocopy(source, destination, extension=''):\n os.system(&quot;robocopy {} {} {} /xx /njh&quot;.format(source, destination, extension))\n\n# Usage example\nrobocopy(r'C:\\Users\\Example\\Downloads', r'C:\\Users\\Example\\Desktop', '*.mov')\n</code></pre>\n<p>The example above will copy all .mov files to the desktop</p>\n<p>Leaving <code>extension</code> blank will copy all files in the source folder to the destination folder.</p>\n<p><code>/xx</code> removes extra files/directories from being listed</p>\n<p><code>/njh</code> removes job header</p>\n<p>See documentation for more info:\n<a href=\"https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy</a></p>\n" }, { "answer_id": 70777816, "author": "every skills", "author_id": 15099592, "author_profile": "https://Stackoverflow.com/users/15099592", "pm_score": 0, "selected": false, "text": "<p>That is simple PySide app can copy any file from source to destination</p>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/python3\n\nimport os\nimport sys\nfrom PySide2.QtWidgets import QProgressBar, QApplication, QDialog, QMainWindow, QPushButton\nfrom PySide2.QtCore import QThread, Signal, Slot\n\n\nclass ProgressDialog(QDialog):\n def __init__(self, parent, source, destination):\n QDialog.__init__(self, parent)\n \n self.resize(400, 50)\n \n self.parent = parent\n self.source = source\n self.destination = destination\n \n self.prog = QProgressBar(self)\n self.prog.setMaximum(100)\n self.prog.setMinimum(0)\n self.prog.setFormat(&quot;%p%&quot;)\n\n def start(self):\n self.show()\n self.copy()\n\n def copy(self):\n copy_thread = CopyThread(self, self.source, self.destination)\n copy_thread.procPartDone.connect(self.update_progress)\n copy_thread.procDone.connect(self.finished_copy)\n copy_thread.start()\n\n def update_progress(self, progress):\n self.prog.setValue(progress)\n\n def finished_copy(self, state):\n self.close()\n\nclass CopyThread(QThread):\n\n procDone = Signal(bool)\n procPartDone = Signal(int)\n\n def __init__(self, parent, source: str, destination: str):\n QThread.__init__(self, parent)\n \n self.source = source\n self.destination = destination\n\n def run(self):\n self.copy()\n self.procDone.emit(True)\n\n def copy(self):\n source_size = os.stat(self.source).st_size\n copied = 0\n\n with open(self.source, &quot;rb&quot;) as source, open(self.destination, &quot;wb&quot;) as target:\n while True:\n chunk = source.read(1024)\n if not chunk:\n break\n\n target.write(chunk)\n copied += len(chunk)\n\n self.procPartDone.emit(copied * 100 / source_size)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self, parent: object = None) -&gt; None:\n super().__init__(parent)\n \n self.src = &quot;/path/to/file.ext&quot;\n self.dest = &quot;/path/to/file.ext&quot;\n\n self.btn = QPushButton(self)\n self.btn.setText(&quot;Start copy&quot;)\n self.btn.clicked.connect(self.run)\n \n self.setCentralWidget(self.btn)\n \n def run(self):\n self.prog = ProgressDialog(self, self.src, self.dest)\n self.prog.start()\n\n\ndef main(): \n app = QApplication(sys.argv)\n \n window = MainWindow()\n window.show()\n \n sys.exit(app.exec_())\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<h4>Save this script in the 'main.py' file and execute the command</h4>\n<pre class=\"lang-sh prettyprint-override\"><code>python3 main.py\n</code></pre>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24708/" ]
I've built web apps before that utilize phpBB session, and user data. The common move is to use code like this: ``` define('IN_PHPBB', true); //replace $phpbb_root_path with path to your forum $phpbb_root_path = '../forum/'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); // Start session management $user->session_begin(); $auth->acl($user->data); $user->setup(); ``` However, by including `common.php`, I bring along a crap-load of other methods that run into other methods I've got setup. In my example, I'm running the application using CodeIgniter, which already has a "redirect" method. This question should apply to anyone who has pre-built methods that may run into the phpBB methods. Basically, all I need to do is: 1. Make sure the user is logged in `$user->data[username] == Anonymous` 2. Utilize data from '$user->data' such as the user's ID, screenname, etc. Could I grab the `$user->data` array, and somehow save it to my own session? Does anyone have any ideas on this? Thanks in advance!
Two things: * I would make the default block size a *lot* larger than 512. I would start with 16384 and perhaps more. * For modularity, it might be better to have the `copy_with_prog` function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress. Perhaps something like this: ``` def copy_with_prog(src, dest, callback = None): while True: # copy loop stuff if callback: callback(pos, total) prog = ProgressBar(...) copy_with_prog(src, dest, lambda pos, total: prog.update(pos, total)) ```
274,523
<p>if Form.Release is called after using the form, it will free all related memory but not set the form variable to nil.</p> <pre><code>if not assigned (Form1) then begin Application.CreateForm(Tform1, Form1); try // Do something finally Form1.Release end; end; </code></pre> <p>To be able to call the same code again, Form1 would have to be set to nil at some point. From the description of Release I cannot do</p> <pre><code>Form1 := nil; </code></pre> <p>right after Release, because the Release procedure will return directly after being called and before the form is actually freed. I cannot detect when Form.Release is finished to set the form var to nil.</p> <p>What is the best way to do this?</p>
[ { "answer_id": 274535, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 1, "selected": false, "text": "<p>In Delphi Win32, the appropriate way to free objects is to call </p>\n\n<pre><code>FreeAndNil(Form1)\n</code></pre>\n\n<p>This does both jobs in a single call.</p>\n\n<p>However, I have a sneaking feeling there's more to your question than meets the eye. Are you using Delphi for .NET - and if so, which version?</p>\n" }, { "answer_id": 274546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>Put the line </p>\n\n<pre><code> Form1 := nil; \n</code></pre>\n\n<p>just after the call to Release.</p>\n\n<p>Release is just posting a CM_RELEASE message to the Form which allows the Form to finish what's in its queue (event handlers) before handling the CM_RELEASE message which means normally just calling Free.<br>\nSo, after calling Release, you should not assume that the Form variable still points to a valid Form, thus putting nil into the variable.</p>\n" }, { "answer_id": 274550, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 4, "selected": false, "text": "<p>Release is just a (potentially) deferred Free. The 1st thing you should do after calling Release is nilling the variable.<br>\nThen, you'll be safe even if some code tries to reference Form1 before it is actually destroyed. In a case like in your code, it would just safely recreate another Form1 for the new usage without bothering the one being destroyed.</p>\n" }, { "answer_id": 274734, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 2, "selected": false, "text": "<p>As is mentioned Release is only a deferred Free for a form to use if it wants to Close/Free itself. Other then being deferred it does nothing different from Release. So there is no use in calling Release in that example. Calling Free seems to be more logical. And you can set it to nil after calling Free or use FreeAndNil. </p>\n\n<p>If you still want to use Release that is fine. Just setting the variable value to nil works. Doing that does not make the forum behave differently. But remember that in this case it is more efficient and more deterministic to call Free instead of Release. My preference is to only use Release where is really needed.</p>\n" }, { "answer_id": 275106, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 2, "selected": false, "text": "<p>Of you could just always call this:</p>\n\n<pre><code>procedure FreeOrReleaseAndNil(var Obj);\nvar\n Temp: TObject;\nbegin\n Temp := TObject(Obj);\n Pointer(Obj) := nil;\n if Temp is TCustomForm then\n TCustomForm(Temp).Release\n else\n Temp.Free;\nend;\n</code></pre>\n\n<p>Be sure to check the type after casting to a TObject as you can't test the type of Obj. This <em>should</em> be safe since like Free, Release is non-virtual. </p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5015/" ]
if Form.Release is called after using the form, it will free all related memory but not set the form variable to nil. ``` if not assigned (Form1) then begin Application.CreateForm(Tform1, Form1); try // Do something finally Form1.Release end; end; ``` To be able to call the same code again, Form1 would have to be set to nil at some point. From the description of Release I cannot do ``` Form1 := nil; ``` right after Release, because the Release procedure will return directly after being called and before the form is actually freed. I cannot detect when Form.Release is finished to set the form var to nil. What is the best way to do this?
Put the line ``` Form1 := nil; ``` just after the call to Release. Release is just posting a CM\_RELEASE message to the Form which allows the Form to finish what's in its queue (event handlers) before handling the CM\_RELEASE message which means normally just calling Free. So, after calling Release, you should not assume that the Form variable still points to a valid Form, thus putting nil into the variable.
274,529
<p>Am working with django Publisher example, I want to list all the publishers in the db via my list_publisher.html template, my template looks like;</p> <pre><code>{% extends "admin/base_site.html" %} {% block title %}List of books by publisher{% endblock %} {% block content %} &lt;div id="content-main"&gt; &lt;h1&gt;List of publisher:&lt;/h1&gt; {%regroup publisher by name as pub_list %} {% for pub in pub_list %} &lt;li&gt;{{ pub.name }}&lt;/li&gt; {% endfor %} &lt;/div&gt; {% endblock %} </code></pre> <p>but when I run "<a href="http://127.0.0.1:8000/list_publisher/" rel="nofollow noreferrer">http://127.0.0.1:8000/list_publisher/</a>" the template just prints the page title with no error! What am I doing wrong?</p>
[ { "answer_id": 274537, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "<p>A few suggestions:</p>\n\n<ul>\n<li>check that your base_site.html does define a <code>{% block content %}{% endblock %}</code> section to be refine by your my list_publisher.html</li>\n<li>check the cardinality of your list: <code>{%regroup publisher by name as pub_list %}{{ pub_list|length }}</code>. That should at least display the length of your list. If is is '0'... you know why it does not display anything</li>\n<li>check that your list is indeed sorted by name before using regroup, or use a <code>{% regroup publisher|dictsort:\"name\" by name as pub_list %}</code> to be sure</li>\n</ul>\n\n<p>If the length is '0', you have to make sure publisher is defined (has been initialized from the database), and sorted appropriately.</p>\n\n<p>In other word, do you see anywhere (in your template or in the defined templates):</p>\n\n<pre><code>publisher = Publisher.objects.all().order_by(\"name\")\n</code></pre>\n\n<p>?<br>\n(again, the order by name is important, to ensure your regroup tag works properly)</p>\n" }, { "answer_id": 274975, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 0, "selected": false, "text": "<p>Good answer by VonC.</p>\n\n<p>A quick and dirty way to look at pub_list is to stick <code>[{{pub_list}}]</code> in your template. I put it in square brackets in case it's empty. BTW, you may get something that looks like <code>[,,,,,]</code>. This is because object references are wrapped in &lt;> and your browser is going WTF? Just do a View Source and you'll see the full result.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26143/" ]
Am working with django Publisher example, I want to list all the publishers in the db via my list\_publisher.html template, my template looks like; ``` {% extends "admin/base_site.html" %} {% block title %}List of books by publisher{% endblock %} {% block content %} <div id="content-main"> <h1>List of publisher:</h1> {%regroup publisher by name as pub_list %} {% for pub in pub_list %} <li>{{ pub.name }}</li> {% endfor %} </div> {% endblock %} ``` but when I run "<http://127.0.0.1:8000/list_publisher/>" the template just prints the page title with no error! What am I doing wrong?
A few suggestions: * check that your base\_site.html does define a `{% block content %}{% endblock %}` section to be refine by your my list\_publisher.html * check the cardinality of your list: `{%regroup publisher by name as pub_list %}{{ pub_list|length }}`. That should at least display the length of your list. If is is '0'... you know why it does not display anything * check that your list is indeed sorted by name before using regroup, or use a `{% regroup publisher|dictsort:"name" by name as pub_list %}` to be sure If the length is '0', you have to make sure publisher is defined (has been initialized from the database), and sorted appropriately. In other word, do you see anywhere (in your template or in the defined templates): ``` publisher = Publisher.objects.all().order_by("name") ``` ? (again, the order by name is important, to ensure your regroup tag works properly)
274,560
<p>Is there an easy way to verify that a given private key matches a given public key? I have a few <code>*.pub</code>and a few <code>*.key</code> files, and I need to check which go with which.</p> <p>Again, these are pub/key files, DSA.</p> <p>I would really prefer a one-liner of some sort...</p>
[ { "answer_id": 274562, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "<p>Encrypt something with the public key, and see which private key decrypts it.</p>\n<p>This <a href=\"http://www.codeproject.com/KB/security/SimpleEncryption.aspx\" rel=\"nofollow noreferrer\">Code Project article</a> by none other than <a href=\"https://en.wikipedia.org/wiki/Jeff_Atwood\" rel=\"nofollow noreferrer\">Jeff Atwood</a> implements a simplified wrapper around the .NET cryptography classes. Assuming these keys were created for use with RSA, use the asymmetric class with your public key to encrypt, and the same with your private key to decrypt.</p>\n" }, { "answer_id": 274570, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": false, "text": "<p>Assuming you have the public keys inside X.509 certificates, and assuming they are RSA keys, then for each public key, do</p>\n<pre><code> openssl x509 -in certfile -modulus -noout\n</code></pre>\n<p>For each private key, do</p>\n<pre><code> openssl rsa -in keyfile -modulus -noout\n</code></pre>\n<p>Then match the keys by modulus.</p>\n" }, { "answer_id": 274622, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 6, "selected": false, "text": "<p>For DSA keys, use</p>\n\n<pre><code> openssl dsa -pubin -in dsa.pub -modulus -noout\n</code></pre>\n\n<p>to print the public keys, then</p>\n\n<pre><code> openssl dsa -in dsa.key -modulus -noout\n</code></pre>\n\n<p>to display the public keys corresponding to a private key, then compare them.</p>\n" }, { "answer_id": 274662, "author": "Loki", "author_id": 17324, "author_profile": "https://Stackoverflow.com/users/17324", "pm_score": 9, "selected": true, "text": "<p>I found a way that seems to work better for me:</p>\n<pre><code>ssh-keygen -y -f &lt;private key file&gt;\n</code></pre>\n<p>That command will output the public key for the given private key, so then just compare the output to each *.pub file.</p>\n" }, { "answer_id": 274672, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>Delete the public keys and generate new ones from the private keys. Keep them in separate directories, or use a naming convention to keep them straight.</p>\n" }, { "answer_id": 280912, "author": "Robert", "author_id": 35675, "author_profile": "https://Stackoverflow.com/users/35675", "pm_score": 6, "selected": false, "text": "<p>I always compare an MD5 hash of the modulus using these commands:</p>\n\n<pre><code>Certificate: openssl x509 -noout -modulus -in server.crt | openssl md5\nPrivate Key: openssl rsa -noout -modulus -in server.key | openssl md5\nCSR: openssl req -noout -modulus -in server.csr | openssl md5\n</code></pre>\n\n<p>If the hashes match, then those two files go together.</p>\n" }, { "answer_id": 19950288, "author": "user2987067", "author_id": 2987067, "author_profile": "https://Stackoverflow.com/users/2987067", "pm_score": -1, "selected": false, "text": "<p>Just use <a href=\"http://www.chiark.greenend.org.uk/%7Esgtatham/putty/download.html\" rel=\"nofollow noreferrer\">puttygen</a> and load your private key into it. It offers different options, e.g. exporting the corresponding public key.</p>\n" }, { "answer_id": 22595408, "author": "John D.", "author_id": 2763030, "author_profile": "https://Stackoverflow.com/users/2763030", "pm_score": 4, "selected": false, "text": "<p>The check can be made easier with diff:</p>\n<pre><code>diff &lt;(ssh-keygen -y -f $private_key_file) $public_key_file\n</code></pre>\n<p>The only odd thing is that diff says nothing if the files are the same, so you'll only be told if the public and private <em>don't</em> match.</p>\n" }, { "answer_id": 39722686, "author": "Zac", "author_id": 971443, "author_profile": "https://Stackoverflow.com/users/971443", "pm_score": 2, "selected": false, "text": "<p>If you are in Windows and want use a GUI, with <a href=\"https://the.earth.li/~sgtatham/putty/latest/x86/puttygen.exe\" rel=\"nofollow noreferrer\">puttygen</a> you can import your private key into it:</p>\n\n<p><a href=\"https://i.stack.imgur.com/8MfK5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8MfK5.png\" alt=\"enter image description here\"></a></p>\n\n<p>Once imported, you can save its public key and compare it to yours.</p>\n" }, { "answer_id": 49099046, "author": "Bradley Allen", "author_id": 5318106, "author_profile": "https://Stackoverflow.com/users/5318106", "pm_score": 3, "selected": false, "text": "<p>Enter the following command to <strong>check if a private key and public key are a matched set</strong> (identical) or not a matched set (differ) in $USER/.ssh directory. The cut command prevents the comment at the end of the line in the public key from being compared, allowing only the key to be compared.</p>\n<pre><code>ssh-keygen -y -f ~/.ssh/id_rsa | diff -s - &lt;(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)\n</code></pre>\n<p>Output will look like either one of these lines.</p>\n<pre><code>Files - and /dev/fd/63 are identical\n\nFiles - and /dev/fd/63 differ\n</code></pre>\n<p>I wrote a shell script that users use to check file permission of their ~/.ssh/files and matched key set. It solves my challenges with user incidents setting up ssh. It may help you. <a href=\"https://github.com/BradleyA/docker-security-infrastructure/tree/master/ssh\" rel=\"nofollow noreferrer\">https://github.com/BradleyA/docker-security-infrastructure/tree/master/ssh</a></p>\n<p>Note: My previous answer (in Mar 2018) no longer works with the latest releases of openssh. Previous answer: diff -qs &lt;(ssh-keygen -yf ~/.ssh/id_rsa) &lt;(cut -d ' ' -f 1,2 ~/.ssh/id_rsa.pub)</p>\n" }, { "answer_id": 55571763, "author": "RoutesMaps.com", "author_id": 2085768, "author_profile": "https://Stackoverflow.com/users/2085768", "pm_score": 0, "selected": false, "text": "<p>If it returns nothing, then they match:</p>\n<pre><code>cat $HOME/.ssh/id_rsa.pub &gt;&gt; $HOME/.ssh/authorized_keys\nssh -i $HOME/.ssh/id_rsa localhost\n</code></pre>\n" }, { "answer_id": 67423640, "author": "Oliver", "author_id": 869951, "author_profile": "https://Stackoverflow.com/users/869951", "pm_score": 2, "selected": false, "text": "<p>The easiest is to compare fingerprints as the public and private keys have the same. Visual comparison is pretty easy by putting the two commands on same line:</p>\n<pre><code>ssh-keygen -l -f PRIVATE_KEY; ssh-keygen -l -f PUBLIC_KEY\n</code></pre>\n<p>Programmatically, you'll want to ignore the comment portion so</p>\n<pre><code>diff -s &lt;(ssh-keygen -l -f PRIVATE_KEY | cut -d' ' -f2) &lt;(ssh-keygen -l -f PUBLIC_KEY | cut -d' ' -f2)\n</code></pre>\n" }, { "answer_id": 72229472, "author": "Mikko Tuominen", "author_id": 1312559, "author_profile": "https://Stackoverflow.com/users/1312559", "pm_score": 0, "selected": false, "text": "<p>This answer should contain a warning:\n<a href=\"https://stackoverflow.com/a/67423640/1312559\">https://stackoverflow.com/a/67423640/1312559</a></p>\n<p><strong>WARNING!</strong> If the public and private key are in the same directory, the fingerprint is calculated for the public key even though the private key is given as a parameter.</p>\n<pre><code>-l' Show fingerprint of specified public key file. Private RSA1 keys are also supported. For RSA and DSA keys ssh-keygen tries to find the matching public key file and prints its fingerprint.\n</code></pre>\n<p><em>Unfortunately I don't have the reputation to comment.</em></p>\n" }, { "answer_id": 73365000, "author": "Blockchain Office", "author_id": 15125291, "author_profile": "https://Stackoverflow.com/users/15125291", "pm_score": 1, "selected": false, "text": "<p>A simple script to check matching of the keys with 3 options:</p>\n<pre><code> #!/bin/bash\n\n PRKEY=mysshkey\n PUKEY=mysshkey.pub\n\n echo &quot;1. OUTPUT&quot;\n diff &lt;( ssh-keygen -y -e -f &quot;${PRKEY}&quot; ) &lt;( ssh-keygen -y -e -f &quot;${PUKEY}&quot;)\n echo -e &quot;\\n&quot;\n\n echo &quot;2. OUTPUT&quot;\n diff &lt;( cut -d' ' -f 2 ${PUKEY} ) &lt;( ssh-keygen -y -f &quot;${PRKEY}&quot; | cut -d' ' -f 2)\n echo -e &quot;\\n&quot;\n\n echo &quot;3. OUTPUT&quot;\n DIFF=$(diff &lt;( cut -d' ' -f 2 ${PUKEY} ) &lt;( ssh-keygen -y -f &quot;${PRKEY}&quot; | cut -d' ' -f 2) )\n if [ &quot;$DIFF&quot; != &quot;&quot; ]; then\n echo &quot;ERROR KEY&quot;\n else\n echo &quot;TRUE KEY&quot;\n fi\n</code></pre>\n<p>If they keys not match you will get an output for output 1 and 2.</p>\n<p>If they keys match you get no output.</p>\n<p>Output 3 show's a message if keys fit or not.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17324/" ]
Is there an easy way to verify that a given private key matches a given public key? I have a few `*.pub`and a few `*.key` files, and I need to check which go with which. Again, these are pub/key files, DSA. I would really prefer a one-liner of some sort...
I found a way that seems to work better for me: ``` ssh-keygen -y -f <private key file> ``` That command will output the public key for the given private key, so then just compare the output to each \*.pub file.
274,567
<p>Can someone please derive a concrete example from the following:</p> <p><a href="http://www.urdalen.com/blog/?p=210" rel="nofollow noreferrer">http://www.urdalen.com/blog/?p=210</a></p> <p>..that shows how to deal with <code>one-to-many</code> and <code>many-to-many</code> relationships?</p> <p>I've emailed the author some time ago but received no reply. I like his idea, but can't figure out how to implement it beyond simple single table relations.</p> <p>Note: I don't want to use a full-blown ORM. I like doing my SQL by hand. I would like to improve the design of my app code though. Right now each domain object has its own class full of queries wrapped in static methods. They just return scalar, 1d-array (record) or 2d-array (recordset) depending on the query.</p>
[ { "answer_id": 274684, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 4, "selected": true, "text": "<p>The problem of ORM's (The impedance mismatch, as it's called) is precisely with relations. In an object graph (In-memory objects), relationships are pointers to other objects. In a relational database, relationships are reversed; This makes it impossible to do a simple mapping between the two models, and that is why ORM's are so complex.</p>\n\n<p>If you want to stay close to the database (avoiding an ORM), then you shouldn't try to abstract relationships away. The way I write datamappers is something like the following:</p>\n\n<pre><code>$car42 = $car_gateway-&gt;fetch(42);\n$wheels = $wheel_gateway-&gt;selectByCar($car42);\n</code></pre>\n\n<p>In contrast to the ORM way:</p>\n\n<pre><code>$car42 = $car_gateway-&gt;fetch(42);\n$wheels = $car42-&gt;selectWheels();\n</code></pre>\n\n<p>This does mean that the gateways end up in your client-code, but it also keeps things very transparent and close to the database.</p>\n" }, { "answer_id": 274696, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 0, "selected": false, "text": "<p>Given your response to Tom's answer, I would recommend that you look at something like Zend Framework. Its ORM has a take it or leave it architecture that can be implemented in stages.</p>\n\n<p>When I came to my present employer, they had an application that had just been completed months previously but had been through one or two prior versions and the current version had been in development six months longer than it was supposed to have been. However, the code base was mess. For example there was no abstraction between the database access logic and the business logic. And, they wanted me to move the site forward building new functionality, extending existing features, and fixing existing bugs in the code. To further complicate things they weren't using any form of sanitation on data inputs or outputs.</p>\n\n<p>As I started to wade into the problem, I realized that I would need a solution to abstract concerns that could be implemented in steps because they obviously weren't going to go for a complete rewrite. My initial approach was to write a custom ORM and DAL that would do the heavy lifting for me. It worked great because it didn't intrude on the existing code base, and so it allowed me to move entire portions of the application to the new architecture in an unobtrusive manner. </p>\n\n<p>However, after having ported a large portion of the user's area of our site to this new structure and having built an entire application on my custom framework (which has come to also include a custom front-end controller and mvc implementation), I am switching to Zend Framework (this is my choice though I am certain that some of the other frameworks would also work in this situation). </p>\n\n<p>In switching to the Zend Framework I have absolutely no concerns about the legacy code base because:</p>\n\n<ul>\n<li>I can build new models and refactor\nold models (built on my custom\nframework) unobtrusively.</li>\n<li>I can refactor the existing\ncontrollers (such as they are) to be\nwrapped within a class that behaves\nin a manner consistent with Zend's\nMVC framework so that it becomes a\nminor issue to actually begin using\nZend's Front-End Controller.</li>\n<li>Our views are already built in\nSmarty so I don't have to worry\nabout separating controller and view\nlogic, but I will be able to extend\nthe Zend Framework so that I can\nrender existing templates in Smarty\nwhile building new templates in\nstraight PHP.</li>\n</ul>\n\n<p>Basically, Zend Framework has a take it or leave architecture that makes its a joy to use within existing projects because new code and refactored code doesn't need to intrude on existing code.</p>\n" }, { "answer_id": 401665, "author": "Vance Lucas", "author_id": 50321, "author_profile": "https://Stackoverflow.com/users/50321", "pm_score": 1, "selected": false, "text": "<p>If you're looking for a simple and portable DataMapper ORM, have a look at <a href=\"http://phpdatamapper.com\" rel=\"nofollow noreferrer\">phpDataMapper</a>. It's only dependencies are PHP5 and PDO, and it's very small and lightweight. It supports table relations and some other very nice features as well.</p>\n" } ]
2008/11/08
[ "https://Stackoverflow.com/questions/274567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can someone please derive a concrete example from the following: <http://www.urdalen.com/blog/?p=210> ..that shows how to deal with `one-to-many` and `many-to-many` relationships? I've emailed the author some time ago but received no reply. I like his idea, but can't figure out how to implement it beyond simple single table relations. Note: I don't want to use a full-blown ORM. I like doing my SQL by hand. I would like to improve the design of my app code though. Right now each domain object has its own class full of queries wrapped in static methods. They just return scalar, 1d-array (record) or 2d-array (recordset) depending on the query.
The problem of ORM's (The impedance mismatch, as it's called) is precisely with relations. In an object graph (In-memory objects), relationships are pointers to other objects. In a relational database, relationships are reversed; This makes it impossible to do a simple mapping between the two models, and that is why ORM's are so complex. If you want to stay close to the database (avoiding an ORM), then you shouldn't try to abstract relationships away. The way I write datamappers is something like the following: ``` $car42 = $car_gateway->fetch(42); $wheels = $wheel_gateway->selectByCar($car42); ``` In contrast to the ORM way: ``` $car42 = $car_gateway->fetch(42); $wheels = $car42->selectWheels(); ``` This does mean that the gateways end up in your client-code, but it also keeps things very transparent and close to the database.