qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
332,705 | <p>I have double (or float) variables that might be "empty", as in holding no valid value. How can I represent this condition with the built in types float and double?</p>
<p>One option would be a wrapper that has a float and a boolean, but that can´t work, as my libraries have containers that store doubles and not objects that behave as doubles. Another would be using NaN (std::numeric_limits). But I see no way to check for a variable being NaN.</p>
<p>How can I solve the problem of needing a "special" float value to mean something other than the number?</p>
| [
{
"answer_id": 332712,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "double d = std::numeric_limits<double>::signaling_NaN();\nbool isNaN = (d != d);\n std::numeric_limits<double>::is_iec559 isnan math.h"
},
{
"answer_id": 332725,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 4,
"selected": true,
"text": "_isnan(double) float.h isnan(double) math.h cmath"
},
{
"answer_id": 332732,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 2,
"selected": false,
"text": "boost::optional"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78828/"
] |
332,709 | <p>This is for my DB class. I am new to OO, been a procedural lad for some time, so I'm still a bit murky.</p>
<p>My first idea was using a bunch of setter functions/methods.. but after writing a whole bunch, I thought about using PHP's define function, like so.</p>
<pre><code>define('MYSQL_USERNAME', 'jimbo');
</code></pre>
<p>Is this an accepted practice? What is the best practice? Should I really clutter my class with a bunch of setter functions (I am currently the only developer using these classes). What are your solutions?</p>
<p>Thank you!</p>
| [
{
"answer_id": 332724,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "$config = (object) array(\n 'prop1' => 'somevalue',\n 'prop2' => 'somevalue2',\n 'prop3' => 'somevalue3',\n);\n\n$db = new DB($config);\n class DB {\n const USER = 'mysqluser';\n}\n\necho DB::USER; // for example\n"
},
{
"answer_id": 332731,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "const define() class MyClass\n{\n const CONFIG_FILE = 'myapp.ini';\n protected protected $config = array(\n 'logfile' => 'err.out',\n 'debug' => false\n );\n parse_ini_file() array_merge() public function __construct() {\n $ini_data = parse_ini_file(self::CONFIG_FILE, __CLASS__);\n $this->config = array_merge($this->config, $ini_data);\n }\n\n}\n"
},
{
"answer_id": 28594164,
"author": "kieranajp",
"author_id": 1233112,
"author_profile": "https://Stackoverflow.com/users/1233112",
"pm_score": 0,
"selected": false,
"text": "class Config {\n const PASSWORD_LENGTH = 12;\n const SEND_PASSWORD_EMAILS = true;\n // ...\n}\n .env PASSWORD_LENGTH=12\nSEND_PASSWORD_EMAILS=1\n getenv() $_ENV Dotenv::load(__DIR__);\n $passwordLength = $_ENV['PASSWORD_LENGTH']\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
332,717 | <p>My app needs to build a buffer from all the selected cells on a worksheet. I have it working correctly when the selected cells are all one contiguous group, but if the user selects a group of cells, then holds down the control key and selects other cells that are not contiguous to the first set of cells, the Worksheet's Selected range only gives me information on that first group of cells. </p>
<p>I tried the Range "Next" property, but walking that seems to just return ranges containing cell-by-cell traversal of that first range. </p>
| [
{
"answer_id": 332750,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 2,
"selected": false,
"text": "\nfor i = 1 to selection.Areas.Count : debug.Print selection.areas(i).Address : next\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965047/"
] |
332,720 | <p>What replacements are available for pinging an ip address in Ruby? The stdlib "ping" library seems to be pretty limited in functionality. I'm not interested in rolling my own code here. Are there good gems available? Should I just suck it up and live with it?</p>
<p>(I'm coding in Ruby 1.8.6 on Linux)</p>
| [
{
"answer_id": 333305,
"author": "Gordon Wilson",
"author_id": 23071,
"author_profile": "https://Stackoverflow.com/users/23071",
"pm_score": 4,
"selected": true,
"text": "net-ping ping"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/757/"
] |
332,727 | <p>I'm using a UITableView to show some data from an array. This array can be changed at any time by other threads. (I believe that whether the array is mutable, or just replaced entirely, doesn't make a difference.) Access to the array itself is threadsafe.</p>
<p>What's the proper way to ensure thread safety with regard to the tableview? I'm worried, for example, that I might change the array to be shorter just before cellForRowAtIndexPath is called, leading to an NSRangeException.</p>
<p>Should I...</p>
<ol>
<li>Enforce that the array is only changed on the main thread? (Seems ugly.)</li>
<li>Maintain a shadow array and update this on the main thread through KVO observing?</li>
<li>??? There must be a better solution...</li>
</ol>
| [
{
"answer_id": 5683955,
"author": "Jon Shier",
"author_id": 272952,
"author_profile": "https://Stackoverflow.com/users/272952",
"pm_score": 2,
"selected": false,
"text": "dispatch_async(dispatch_get_main_queue(), ^{\n [array addObject:object];\n [tableView reloadData];\n });\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79/"
] |
332,734 | <p>The software base I am developing for uses a signficant amount of yacc which I don't need to deal with. Some times I think it would be helpful in understanding some problems I find but most of the time I can get away with my complete ignorance of yacc.</p>
<p>My question are there enough new projects out there that still use yacc to warrant the time I'll need to learn it?</p>
<p>Edit: Given the response is mostly in favour of learning Yacc, is there a similar language that you would recommend over yacc?</p>
| [
{
"answer_id": 332746,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "key=val server = \"mercury\" {\n ip = \"172.3.5.13\"\n gateway = \"172.3.5.1\"\n}\nserver = \"venus\" {\n ip = \"172.3.5.21\"\n gateway = \"172.3.5.1\"\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42303/"
] |
332,738 | <p>I'm trying to write a simple ruby function that can prompt the user for a value and if the user presses ENTER by itself, then a default value is used.
In the following example, the first call to the Prompt function can be handled by pressing ENTER by itself and the default value will be used. However, the second time I call Prompt and press ENTER, nothing happens, and it turns out I have to press some other character before ENTER to return from the 'gets' call.</p>
<p>There must be some way to flush the input buffer to avoid this problem. Anyone know what to do?</p>
<p>Thanks,</p>
<h2>David</h2>
<pre><code>def BlankString(aString)
return (aString == nil) ||
(aString.strip.length == 0)
end
#Display a message and accept the input
def Prompt(aMessage, defaultReponse = "")
found = false
result = ""
showDefault = BlankString(defaultReponse) ? "" : "(#{defaultReponse})"
while not found
puts "#{aMessage}#{showDefault}"
result = gets.chomp
result.strip!
found = result.length > 0
if !found
then if !BlankString(showDefault)
then
result = defaultReponse
found = true
end
end
end
return result
end
foo = Prompt("Prompt>", "sdfsdf")
puts foo
foo = Prompt("Prompt>", "default")
puts foo
</code></pre>
| [
{
"answer_id": 332921,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 0,
"selected": false,
"text": ":! ruby prompt.rb\nPrompt>(sdfsdf)\n\nsdfsdf\nPrompt>(default)\n\ndefault\n c = gets\nb = gets\na = gets\np [ a, b, c ]\n [\"\\n\", \"\\n\", \"\\n\"]\n defaultResponse"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
332,757 | <p>I get a 404 response from .Net MVC when I try to make a request where my search term ends with a <code>.</code> (period). This is the route that I'm using:</p>
<pre><code>routes.MapRoute(
"Json",
"Remote.mvc/{action}/{searchTerm}/{count}",
new { controller="Remote", count=10}
);
</code></pre>
<p>The search works fine with a <code>.</code> inside the search term, it just cannot end with it. Any thoughts on how to route this search request?</p>
| [
{
"answer_id": 3542524,
"author": "bkaid",
"author_id": 265570,
"author_profile": "https://Stackoverflow.com/users/265570",
"pm_score": 3,
"selected": false,
"text": "<httpRuntime relaxedUrlToFileSystemMapping=\"true\" />\n"
},
{
"answer_id": 7598759,
"author": "Kosau",
"author_id": 108645,
"author_profile": "https://Stackoverflow.com/users/108645",
"pm_score": 5,
"selected": false,
"text": " <add name=\"UrlRoutingHandler\" type=\"System.Web.Routing.UrlRoutingHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" path=\"Remote.mvc/*\" verb=\"GET\"/>\n <httpRuntime relaxedUrlToFileSystemMapping=\"true\" />\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
332,758 | <p>I have a desktop application having heavyweight components (JxBrowser) in a JFrame. How can I make a snapshot from the GUI and save it to for example a png file? </p>
<p>Note: The method using Graphics2d and Component.paint()/paintAll()/print/printAll works only for lightweight components. </p>
<p>Any answers appreciated!</p>
<p><strong>EDIT</strong></p>
<p>I have already tried this:</p>
<pre><code>robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
</code></pre>
<p>But I want the inner component to be captured...</p>
<p><strong>EDIT</strong></p>
<p>The situation seems to converge to this solution: if I have a bigger heavyweight component in my JFrame, so it is rendered on a JScrollPane then there exist no other method to get a snapshot of it programatically then to scroll it/screenshot it with screencapture?</p>
| [
{
"answer_id": 332765,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "Point p = yourAwtComponent.getLocationOnScreen();\nint w = yourAwtComponent.getWidth();\nint h = yourAwtComponent.getHeight();\n\nRectangle rectangle = new Rectangle( p.x, p.y, w, h );\n\nImage image = robot.createScreenCapture(rectangle);\n ImageIO.write( image, \"png\", file );\n"
},
{
"answer_id": 333492,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 0,
"selected": false,
"text": " int width = frameContainer.getWidth();\n int height = frameContainer.getHeight();\n\n BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\n Graphics2D g2 = image.createGraphics();\n\n frameContainer.paint(g2);\n\n return image;\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19621/"
] |
332,766 | <p>Here's a code snippet. . .</p>
<pre><code><form name="FinalAccept" method="get"><br>
<input type="radio" name="YesNo" value="Yes" onclick="/accept"> Yes<br>
<input type="radio" name="YesNo" value="No" onclick="/accept"> No<br>
</code></pre>
<p>Clearly, what I'm trying to do is call the routine linked to /accept when the user clicks on the radio button.</p>
<p>I know the routine is working because I call the same routine from another place in the program. </p>
<p>I'm trying to run it locally using google appserver. Is there something I'm missing? </p>
<p>Thanks</p>
| [
{
"answer_id": 332772,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 2,
"selected": false,
"text": "onclick=\"SomeJavaScriptCode\"\n onClick=\"myfunction('my value');\"\n onClick=\"location.href='http://www.example.com/accept';\"\nonClick=\"location.href='http://www.example.com/decline';\"\n onClick=\"this.form.submit();\"\n"
},
{
"answer_id": 333304,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 4,
"selected": false,
"text": "<form name=\"FinalAccept\" method=\"get\" action=\"accept\"><br>\n<input type=\"radio\" name=\"YesNo\" value=\"Yes\" onclick=\"this.form.submit();\"> Yes<br>\n<input type=\"radio\" name=\"YesNo\" value=\"No\" onclick=\"this.form.submit();\"> No<br>\n</form>\n <form name=\"FinalAccept\" method=\"get\" action=\"accept\"><br>\n<input id=\"rYes\" type=\"radio\" name=\"YesNo\" value=\"Yes\" onclick=\"this.form.submit();\">\n<label for=\"rYes\">Yes</label><br>\n<input id=\"rNo\" type=\"radio\" name=\"YesNo\" value=\"No\" onclick=\"this.form.submit();\">\n<label for=\"rNo\">No</label><br>\n</form>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1179/"
] |
332,767 | <p>I get this error when I do the make:</p>
<pre><code>relocation R_X86_64_32 against `vtable for Torch::MemoryDataSet' can not be used
when making a shared object; recompile with -fPIC
</code></pre>
<p>It says that I should recompile with the <code>-fPIC</code> option. I did that, adding
the <code>-fPIC</code> option to <code>CFLAGS</code> and <code>CXXFLAGS</code>, but I still get the same error. Is there any way to solve this? I have seen that this problem is related with the use of a 64-bit machine, and it is true that I am using one.</p>
| [
{
"answer_id": 14441697,
"author": "cmo",
"author_id": 1023645,
"author_profile": "https://Stackoverflow.com/users/1023645",
"pm_score": 3,
"selected": false,
"text": "CXX=g++\nCXXFLAGS= -O3 -Wall\n...\n... \n%.o: %.c\n $(CXX) $(CXXFLAGS) -fpic -c $< \n\nlibmylibrary.so: $(OBJECTS)\n $(CXX) -shared -Wl,-soname,$@ -o $@ $(OBJECTS)\n %.o: %.c\n $(CXX) -fPIC $(CXXFLAGS) -c $< \n CXX=g++ -fPIC\nCXXFLAGS= -g -O3 -Wall\n...\n%.o: %.c\n $(CXX) $(CXXFLAGS) -c -o $@ $< \n\nlibalglib.so: $(OBJECTS)\n $(CXX) -shared -Wl,-soname,$@ -o $@ $(OBJECTS)\n"
},
{
"answer_id": 16083042,
"author": "SoS",
"author_id": 2295053,
"author_profile": "https://Stackoverflow.com/users/2295053",
"pm_score": -1,
"selected": false,
"text": "$ ./configure 'CFLAGS=-g -O2 -fPIC ....' --enable-some-thing\n"
},
{
"answer_id": 26172073,
"author": "mmienko",
"author_id": 3161389,
"author_profile": "https://Stackoverflow.com/users/3161389",
"pm_score": 0,
"selected": false,
"text": "CFLAGS = -g -Wall\nSOURCES = $(wildcard *.c)\nOBJECTS = ...\n\nTARGET = libmyawesomelib.a\n\nall: $(TARGET) main\n $(TARGET): CFLAGS += -fPIC\n$(TARGET): $(OBJECTS)\n .\n .\n .\n"
},
{
"answer_id": 33072132,
"author": "jan",
"author_id": 5256114,
"author_profile": "https://Stackoverflow.com/users/5256114",
"pm_score": 0,
"selected": false,
"text": "CC=\"$CROSS/bin/arm-linux-androideabi-gcc -pie --sysroot=$SYSROOT\"\n -fPIC -fPIE"
},
{
"answer_id": 42293134,
"author": "Shuman",
"author_id": 2052889,
"author_profile": "https://Stackoverflow.com/users/2052889",
"pm_score": 0,
"selected": false,
"text": "CC=mipsel-unknown-linux-uclibc-gcc CXX=mipsel-unknown-linux-uclibc-g++ AR=mipsel-unknown-linux-uclibc-ar RANLIB=mipsel-unknown-linux-uclibc-ranlib make SHARED=1 CFLAGS=-fPIC\n CC=\"mipsel-unknown-linux-uclibc-gcc -fPIC\" CXX=\"mipsel-unknown-linux-uclibc-g++ -fPIC\" AR=mipsel-unknown-linux-uclibc-ar RANLIB=mipsel-unknown-linux-uclibc-ranlib make SHARED=1 \n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39160/"
] |
332,781 | <p>okee, I followed all instructions I could find <a href="https://stackoverflow.com/questions/279170/utf-8-all-the-way-through">here</a>
and i could display all kinds of multilingual characters on my pages...<br>
The problem is in phpmyadmin the japanese characters are replaced by question marks, as in a bunch of <code>???? ???</code> pieced together. I think there's a problem with my database's collation but I just wanted to verify that here.</p>
<p>We've had this database set before on a default collation which is <code>latin_swedish_ci</code>
and it already has a lot of data. Now we had to add some tables that require support for special characters, so I definitely just couldn't set the database's collation to <code>utf8</code>. My solution was to use <code>utf8</code> only on the tables which required such support and the specific columns where we expected special characters to be contained.<br>
But still phpmyadmin displayed them as <code>????</code>.</p>
<p>Another question that I have is will these fields be searchable?<br>
I mean if the field contains some japanese characters and I typed <code>sayuri</code> as keyword, will the japanese character equivalent to their syllables pronounced in english?</p>
| [
{
"answer_id": 332795,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": -1,
"selected": false,
"text": "SET CHARACTER SET utf8;\nSET NAMES utf8;\n default-character-set=utf8\nskip-character-set-client-handshake\n"
},
{
"answer_id": 6910102,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "mysqli_set_charset ( $mysqli,'utf8'); \n $mysqli->set_charset(\"utf8\");\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24744/"
] |
332,788 | <p>How can I maintain the scroll position of a treeview control in .NET application? For example, I have a treeview control and go through a process of adding various nodes to it tacking them on to the bottom. During this process, I can scroll through the treeview and view different nodes. The problem is when the process completes, the treeview scrolls to the very bottom.</p>
<p>It appears that calling treenode.Expand() is what is throwing me off track here. When a parent node is expanded, it gets the focus.</p>
<p>Is there a way around this? If I'm looking at a specific node while the process is running, I don't want it to jump around on me when the process is done.</p>
| [
{
"answer_id": 332841,
"author": "Matt Hanson",
"author_id": 5473,
"author_profile": "https://Stackoverflow.com/users/5473",
"pm_score": 5,
"selected": true,
"text": "If treeNodeParent.IsExpanded = False Then\n Dim currentNode As TreeNode = TreeViewHosts.GetNodeAt(0, 0)\n treeNodeParent.Expand()\n currentNode.EnsureVisible()\nEnd If\n"
},
{
"answer_id": 359896,
"author": "Stefan Koell",
"author_id": 33423,
"author_profile": "https://Stackoverflow.com/users/33423",
"pm_score": 5,
"selected": false,
"text": "[DllImport(\"user32.dll\", CharSet = CharSet.Unicode)]\npublic static extern int GetScrollPos(IntPtr hWnd, int nBar);\n\n[DllImport(\"user32.dll\", CharSet = CharSet.Unicode)]\npublic static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);\n\nprivate const int SB_HORZ = 0x0;\nprivate const int SB_VERT = 0x1;\n private Point GetTreeViewScrollPos(TreeView treeView)\n{\n return new Point(\n GetScrollPos(treeView.Handle, SB_HORZ), \n GetScrollPos(treeView.Handle, SB_VERT));\n}\n private void SetTreeViewScrollPos(TreeView treeView, Point scrollPosition)\n{\n SetScrollPos(treeView.Handle, SB_HORZ, scrollPosition.X, true);\n SetScrollPos(treeView.Handle, SB_VERT, scrollPosition.Y, true); \n}\n BeginUpdate();\nPoint ScrollPos = GetTreeViewScrollPos(treeMain);\n// write your update code here\nSetTreeViewScrollPos(treeMain, ScrollPos);\nEndUpdate();\n"
},
{
"answer_id": 2334877,
"author": "D Lyonnais",
"author_id": 281295,
"author_profile": "https://Stackoverflow.com/users/281295",
"pm_score": 2,
"selected": false,
"text": "SetTreeViewScrollPosition(point) BeginUpdate EndUpdate private void treeViewXml1_Scroll(object sender, ScrollEventArgs e)\n{\n Point point = treeViewXml1.GetTreeViewScrollPosition();\n\n treeViewXml2.BeginUpdate();\n treeViewXml2.SetTreeViewScrollPosition(point);\n treeViewXml2.EndUpdate();\n}\n\nprivate void treeViewXml2_Scroll(object sender, ScrollEventArgs e)\n{\n Point point = treeViewXml2.GetTreeViewScrollPosition();\n\n treeViewXml1.BeginUpdate();\n treeViewXml1.SetTreeViewScrollPosition(point);\n treeViewXml1.EndUpdate();\n}\n"
},
{
"answer_id": 4656562,
"author": "JM88",
"author_id": 571107,
"author_profile": "https://Stackoverflow.com/users/571107",
"pm_score": 1,
"selected": false,
"text": "BeginUpdate() EndUpdate() SetScrollPos() this.hierarchyTreeView.BeginUpdate();\nSetScrollPos(this.hierarchyTreeView.Handle, SB_VERT, 5, true);\nthis.hierarchyTreeView.EndUpdate();\n"
},
{
"answer_id": 9624778,
"author": "Alen",
"author_id": 1257981,
"author_profile": "https://Stackoverflow.com/users/1257981",
"pm_score": 0,
"selected": false,
"text": "myTreeView.Nodes[0].EnsureVisible();\n"
},
{
"answer_id": 10695101,
"author": "Josh Stribling",
"author_id": 464386,
"author_profile": "https://Stackoverflow.com/users/464386",
"pm_score": 3,
"selected": false,
"text": "TreeNode topNode = m_Tree.TopNode;\ntreenode.Expand();\nm_Tree.TopNode = topNode;\n string topNodePath = null;\nTreeNode topNode = null;\nif (m_Tree.TopNode != null)\n{\n topNodePath = m_Tree.TopNode.FullPath;\n}\n\nm_Tree.Clear();\n nodes.Add(node)\nif ((topNodePath != null) && (node.FullPath == topNodePath))\n{\n topNode = node;\n}\n if (topNode != null)\n{\n m_Tree.TopNode = topNode;\n}\n"
},
{
"answer_id": 16392731,
"author": "user2353540",
"author_id": 2353540,
"author_profile": "https://Stackoverflow.com/users/2353540",
"pm_score": -1,
"selected": false,
"text": "<asp:UpdatePanel id=\"UpdatePanel\">\n <ContentTemplate>\n <asp:TreeView id=\"TreeView\">\n\n </asp:TreeView>\n </ContentTemplate>\n</asp:UpdatePanel>\n"
},
{
"answer_id": 25447787,
"author": "peter70",
"author_id": 2063921,
"author_profile": "https://Stackoverflow.com/users/2063921",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Interop;\nusing System.Windows.Media;\n\npublic static class TreeViewExtension\n{\n #region Constants\n\n private const int ScrollBarHorizontal = 0x0;\n\n private const int ScrollBarVertical = 0x1;\n\n #endregion\n\n #region Public Methods and Operators\n\n [DllImport(\"user32.dll\", CharSet = System.Runtime.InteropServices.CharSet.Auto)]\n public static extern int GetScrollPos(int hWnd, int nBar);\n\n public static Point ScrollPosition(this TreeView treeView)\n {\n return new Point(\n GetScrollPos((int)treeView.Handle(), ScrollBarHorizontal), \n GetScrollPos((int)treeView.Handle(), ScrollBarVertical));\n }\n\n public static void ScrollTo(this TreeView treeView, Point scrollPosition)\n {\n SetScrollPos(treeView.Handle(), ScrollBarHorizontal, (int)scrollPosition.X, true);\n SetScrollPos(treeView.Handle(), ScrollBarVertical, (int)scrollPosition.Y, true);\n }\n\n [DllImport(\"user32.dll\")]\n public static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);\n\n #endregion\n\n #region Methods\n\n private static IntPtr Handle(this Visual treeView)\n {\n var handle = IntPtr.Zero;\n var hwndSource = PresentationSource.FromVisual(treeView) as HwndSource;\n if (hwndSource != null)\n {\n handle = hwndSource.Handle;\n }\n\n return handle;\n }\n\n #endregion\n}\n"
},
{
"answer_id": 53936287,
"author": "karrtojal",
"author_id": 3124995,
"author_profile": "https://Stackoverflow.com/users/3124995",
"pm_score": 0,
"selected": false,
"text": "this.treeView.BeginUpdate();\nTreeNode topNode = this.treeView.TopNode;\n\n// your code\nthis.treeView.Sort();\nthis.treeView.SelectedNode = auxNode;\n\nthis.treeView.TopNode = topNode;\nthis.treeView.EndUpdate();\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
] |
332,792 | <p>I currently have two XSD schemes and one is a "light" version of the other. Right now I have everything in the "light" version repeated in the "complete" schema, but this becomes a pain when I need to make a change, and it goes against the DRY principle anyways, so I was wondering if there was an element that served to include another schema into a schema, so I can have my "complete" inherit from the "light" schema to reduce maintenance hurdles.</p>
| [
{
"answer_id": 489385,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 7,
"selected": true,
"text": "<xsd:include schemaLocation=\"pathToFile\" /> <xsd:import namespace=\"namespace\" schemaLocation=\"pathToFile\" />"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
332,794 | <p>I'm thinking about exploring the idea of having our client software run as a service on a high port and listen for simple http GET requests from 127.0.0.1. The theory is that I would be able to access this service via js from a web page that is served from my site.</p>
<p>1) User installs client software that installs itself as a service and waits for authenticated requests on 127.0.0.1:8080</p>
<p>2) When the user hits my home page js on the page makes an xhtml request to 127.0.0.1:8080 and asks for the status</p>
<p>3) The home page then makes another js request back to my web server sending the status that it received.</p>
<p>This would allow my users to upload/download and edit files on a USB attached device in real-time from a browser. Polling could be the fallback method which is close to what we do today. </p>
<p>Has anyone done this and what potential pitfalls are there? Will this even work?</p>
| [
{
"answer_id": 332944,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<script>"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42317/"
] |
332,798 | <p>What is the equivalent of varchar(max) in MySQL?</p>
| [
{
"answer_id": 332805,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 9,
"selected": true,
"text": "VARCHAR(65535)\n VARCHAR(21844) CHARACTER SET utf8\n mysql> CREATE TABLE foo ( v VARCHAR(65534) );\nERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs\n mysql> CREATE TABLE foo ( v VARCHAR(65532) );\nQuery OK, 0 rows affected (0.01 sec)\n mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;\nERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead\n mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;\nERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs\n mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;\nQuery OK, 0 rows affected (0.32 sec)\n"
},
{
"answer_id": 332894,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 6,
"selected": false,
"text": "varchar(max) varchar(max) TEXT NTEXT BLOB READTEXT WRITETEXT UPDATETEXT varchar(max) varchar(max) TEXT NTEXT BLOB varchar(max) varchar(MAX) varchar(AS_MUCH_AS_I_WANT_TO_STUFF_IN_HERE_JUST_KEEP_GROWING) varchar(MAX_SIZE_OF_A_COLUMN) varchar(max) BLOB"
},
{
"answer_id": 30775596,
"author": "zloctb",
"author_id": 1673376,
"author_profile": "https://Stackoverflow.com/users/1673376",
"pm_score": 2,
"selected": false,
"text": "mysql> CREATE TABLE varchars1(ch3 varchar(6),ch1 varchar(3),ch varchar(4000000))\n;\nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n\nmysql> SHOW WARNINGS;\n+-------+------+---------------------------------------------+\n| Level | Code | Message |\n+-------+------+---------------------------------------------+\n| Note | 1246 | Converting column 'ch' from VARCHAR to TEXT |\n+-------+------+---------------------------------------------+\n1 row in set (0.00 sec)\n\nmysql>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
332,803 | <p>The current guidlelines for explicit member implementation recommend:</p>
<ul>
<li>Using explicit members to approximate private interface implementations. <em>If you need to implement an interface for only infrastructure reasons and you <strong>never</strong> expect developers to directly call methods on that interface from this type then implement the members explicitly to 'hide' them from public view</em>.</li>
<li>Expose an alternative way to access any explicitly implemented members that subclasses are allowed to override.</li>
</ul>
<p>A good example of this is when you want to implement the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="nofollow noreferrer">IXmlSerializable</a> interface. The <strong>ReadXml</strong> and <strong>WriteXml</strong> methods are expected to be called by the XmlSerializer and are not typically called directly by developers. </p>
<p>When providing an alternative way to access explicitly members you wish to allow to be overridden, it seems to make sense to call the explicitly implemented member so as to avoid code duplication. Consider the following:</p>
<pre><code>using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Demo
{
/// <summary>
/// Demonstrates explicit implementation of the IXmlSerializable interface.
/// </summary>
[Serializable(), XmlRoot(ElementName = "foo")]
public class Foo : IXmlSerializable
{
//============================================================
// IXmlSerializable Implementation
//============================================================
#region GetSchema()
/// <summary>
/// Returns an <see cref="XmlSchema"/> that describes the XML representation of the object.
/// </summary>
/// <returns>
/// An <see cref="XmlSchema"/> that describes the XML representation of the object that is
/// produced by the <see cref="IXmlSerializable.WriteXml(XmlWriter)"/> method and consumed by the <see cref="IXmlSerializable.ReadXml(XmlReader)"/> method.
/// </returns>
/// <remarks>This method is reserved and should not be used.</remarks>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
#endregion
#region ReadXml(XmlReader reader)
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="XmlReader"/> stream from which the object is deserialized.</param>
/// <exception cref="ArgumentNullException">The <paramref name="reader"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Class state values read from supplied XmlReader
}
#endregion
#region WriteXml(XmlWriter writer)
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="XmlWriter"/> stream to which the object is serialized.</param>
/// <exception cref="ArgumentNullException">The <paramref name="writer"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Current class state values written using supplied XmlWriter
}
#endregion
//============================================================
// Public Methods
//============================================================
#region WriteTo(XmlWriter writer)
/// <summary>
/// Saves the current <see cref="Foo"/> to the specified <see cref="XmlWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="XmlWriter"/> stream to which the <see cref="Foo"/> is serialized.</param>
/// <exception cref="ArgumentNullException">The <paramref name="writer"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>
public void WriteTo(XmlWriter writer)
{
writer.WriteStartElement("foo");
((IXmlSerializable)this).WriteXml(writer);
writer.WriteEndElement();
}
#endregion
}
}
</code></pre>
<p>My question is in regards to how expensive the boxing of the <strong>WriteXml</strong> method is in this implementation. Is <em>((IXmlSerializable)this).WriteXml(writer)</em> going to significantly hinder performance? </p>
| [
{
"answer_id": 332822,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "public void IXmlSerializable.WriteXml( XmlWriter writer )\n{\n InternalWriteXml( writer );\n}\n\npublic void WriteTo(XmlWriter writer)\n{\n writer.WriteStartElement(\"foo\");\n\n InternalWriteXml(writer);\n\n writer.WriteEndElement();\n}\n\nprivate void InternalWriteXml( XmlWriter writer )\n{\n ...\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2029/"
] |
332,809 | <p>I am trying to get a header that will work with Apache, IIS 6, and IIS 7. I won't go into the reason for that here. Let's just say that it's not as easy as I thought it would be :-)</p>
<p>Anyway, the problem has something to do with NPH. In our code (originally written for IIS 6) we have</p>
<pre><code>use CGI qw(:standard);
print "HTTP/1.0 200 OK\n";
print header;
</code></pre>
<p>at the top of every cgi script; I read that this is how you tell IIS that you want NPH.</p>
<p>Apache uses the filename to see if the output is nph (nph- must be the beginning of the filename) so what I did (which works in both IIS 6 and Apache) is the following:</p>
<pre><code>use CGI qw(:standard);
print header('text/html', '200 OK');
</code></pre>
<p>IIS 7, interestingly, seems to <em>require</em> NPH, so if I don't either do</p>
<pre><code>use CGI qw(:standard -nph);
</code></pre>
<p>or</p>
<pre><code>print "HTTP/1.0 200 OK\n";
print header('text/html', '200 OK'); #parameters are apparently optional
</code></pre>
<p>the browser tries to do something weird with the file, since it doesn't get the mimetype. </p>
<p>Also note: IIS 6 and 7 are ok without printing any header at all, but Apache doesn't like that.</p>
<p>Anyway, the best thing right now would be to make</p>
<pre><code>use CGI qw(:standard);
print header('text/html', '200 OK');
</code></pre>
<p>somehow work in IIS 7. Does anyone know how I can do that? I don't know all the details for our server configuration, but if you tell me how to get any details you might need, I can do that.</p>
<p>Thanks either way!</p>
| [
{
"answer_id": 332929,
"author": "Frew Schmidt",
"author_id": 12448,
"author_profile": "https://Stackoverflow.com/users/12448",
"pm_score": 1,
"selected": true,
"text": "sub header {\n return (($ENV{PERLXS})?\"HTTP/1.0 200 OK\\r\\n\":\"\").CGI->header(@_);\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
332,810 | <p>when I apply the tag above my methods I get the error </p>
<blockquote>
<p>Type System.Runtime.CompilerServices.Extension is not defined.</p>
</blockquote>
<p>Here is my sample</p>
<pre><code><System.Runtime.CompilerServices.Extension()> _
Public Sub test()
End Sub
</code></pre>
<p>Where am I going wrong?</p>
<p>Edit ~ Straight from the MSDN Article <a href="http://msdn.microsoft.com/en-us/library/bb384936.aspx" rel="noreferrer">here</a>, the same error</p>
<p><code></p>
<pre>
Imports System.Runtime.CompilerServices
Module StringExtensions
_
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
</pre>
<p></code></p>
<p>I am using Visual Studio 2008 and 3.5 Framework in my project.</p>
<blockquote>
<p>Solution ~ The project was on 2.0 Framework. Changed to 3.5 and it works.</p>
</blockquote>
| [
{
"answer_id": 332966,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 1,
"selected": false,
"text": "Imports System.Runtime.CompilerServices\n\n<Extension()> _\nPublic Sub Test(ByVal Value As String)\n\nEnd Sub\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
332,833 | <p>I'm doing this system <a href="http://stacked.ra-ajax.org/" rel="nofollow noreferrer">Stacked</a> and I am creating the search function. And in that process it occurs to me that <em>maybe</em> AR/nHibernate Expression.Like (and siblings) might maybe not be 100% "safe" in that you can create stuff like;
"\r\ndrop database xxx;---" and similar things...?</p>
<p>I would expect them to be safe, but I am not sure...</p>
| [
{
"answer_id": 332915,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 3,
"selected": true,
"text": "sp_executesql 'select blah from table where column = @p1', '@p1 varchar(10)', @p1 = 'drop database xxx;---'"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29746/"
] |
332,849 | <p>How can I parse integers passed to an application as command line arguments if the app is unicode?</p>
<p>Unicode apps have a main like this:</p>
<pre><code>int _tmain(int argc, _TCHAR* argv[])
</code></pre>
<p>argv[?] is a wchar_t*. That means i can't use atoi. How can I convert it to an integer? Is stringstream the best option?</p>
| [
{
"answer_id": 332900,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "std::basic_istringstream std::basic_istringstream<_TCHAR> ss(argv[x]);\nint number;\nss >> number;\n number char"
},
{
"answer_id": 332905,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "int value = _ttoi(argv[1]);\n"
},
{
"answer_id": 332907,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 1,
"selected": false,
"text": "stringstreams #include <sstream>\n#include <iostream>\n\nusing namespace std;\n\ntypedef basic_istringstream<_TCHAR> ITSS;\n\nint _tmain(int argc, _TCHAR *argv[]) {\n\n ITSS s(argv[0]);\n int i = 0;\n s >> i;\n if (s) {\n cout << \"i + 1 = \" << i + 1 << endl;\n }\n else {\n cerr << \"Bad argument - expected integer\" << endl;\n }\n}\n"
},
{
"answer_id": 14433806,
"author": "Sean",
"author_id": 736571,
"author_profile": "https://Stackoverflow.com/users/736571",
"pm_score": 2,
"selected": false,
"text": "TCLAP argv #include <iostream>\n\n#ifdef WINDOWS\n# define TCLAP_NAMESTARTSTRING \"~~\"\n# define TCLAP_FLAGSTARTSTRING \"/\"\n#endif\n#include \"tclap/CmdLine.h\"\n\nint main(int argc, _TCHAR *argv[]) {\n int myInt = -1;\n try {\n TCLAP::ValueArg<int> intArg;\n TCLAP::CmdLine cmd(\"this is a message\", ' ', \"0.99\" );\n cmd.add(intArg);\n cmd.parse(argc, argv);\n if (intArg.isSet())\n myInt = intArg.getValue();\n } catch (TCLAP::ArgException& e) {\n std::cout << \"ERROR: \" << e.error() << \" \" << e.argId() << endl;\n }\n std::cout << \"My Int: \" << myInt << std::endl;\n return 0;\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78828/"
] |
332,852 | <p>So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:</p>
<pre><code>//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
double user;
cin >> user; //user entering the number
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
</code></pre>
<p>Edit: I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.</p>
| [
{
"answer_id": 332886,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "std::istringstream #include <sstream> \n\nbool is_double(std::string const& str) {\n std::istringstream ss(str);\n\n // always keep the scope of variables as close as possible. we see\n // 'd' only within the following block.\n {\n double d;\n ss >> d;\n }\n\n /* eat up trailing whitespace if there was a double read, and ensure\n * there is no character left. the eof bit is set in the case that\n * `std::ws` tried to read beyond the stream. */\n return (ss && (ss >> std::ws).eof());\n}\n operator>> abc 3abc ss eof() std::ws eof 3abc && int boost::lexical_cast #include <cstdlib>\n#include <cctype> \n\nbool is_double(std::string const& s) {\n char * endptr;\n std::strtod(s.c_str(), &endptr);\n if(endptr != s.c_str()) // skip trailing whitespace\n while(std::isspace(*endptr)) endptr++;\n return (endptr != s.c_str() && *endptr == '\\0');\n}\n strtod endptr strtod std::sscanf #include <cstdio>\n\nbool is_double(std::string const& s) {\n int n;\n double d;\n return (std::sscanf(s.c_str(), \"%lf %n\", &d, &n) >= 1 && \n n == static_cast<int>(s.size()));\n}\n std::sscanf %n >= sscanf n std::stringstream"
},
{
"answer_id": 332898,
"author": "maccullt",
"author_id": 4945,
"author_profile": "https://Stackoverflow.com/users/4945",
"pm_score": 0,
"selected": false,
"text": "bool is_double(const char* strIn, double& dblOut) {\n char* lastConvert = NULL;\n double d = strtod(strIn, &lastConvert);\n if(lastConvert == strIn){\n return false;\n } else {\n dblOut = d;\n return true;\n }\n}\n"
},
{
"answer_id": 332910,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 4,
"selected": true,
"text": "#include <iostream>\n#include <boost/lexical_cast.hpp>\nusing namespace std;\nusing namespace boost;\n\ndouble cube(double n);\n\nint main()\n{\n while(true)\n {\n cout << \"Enter the number you want to cube: \";\n string user;\n cin >> user;\n\n try\n {\n // The following instruction tries to parse a double from the 'user' string.\n // If the parsing fails, it raises an exception of type bad_lexical_cast.\n // If an exception is raised within a try{ } block, the execution proceeds\n // with one of the following catch() blocks\n double d = lexical_cast <double> (user); \n\n cout << \"The cube of \" << d << \" is \" << cube(d) << \".\" << endl;\n break;\n }\n catch(bad_lexical_cast &e)\n {\n // This code is executed if the lexical_cast raised an exception; We\n // put an error message and continue with the loop\n cout << \"The inserted string was not a valid double!\" << endl;\n }\n }\n return 0;\n}\n\ndouble cube (double n)\n{\n return n*n*n;\n}\n"
},
{
"answer_id": 332922,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 1,
"selected": false,
"text": "//cubes a user entered number\n#include <iostream>\n#include <cstdio>\nusing namespace std;\n\ndouble cube(double n); //function prototype\n\nint main()\n{\n cout << \"Enter the number you want to cube: \"; //ask user to input number\n string user;\n cin >> user; //user entering the number\n\n // Convert the number to a double.\n double value;\n if(sscanf(user.c_str(), \"%lf\", &value) != 1)\n {\n cout << \"Bad! \" << user << \" isn't a number!\" << endl;\n return 1;\n }\n\n cout << \"The cube of \" << user << \" is \" << cube(user) << \".\" << endl; //displaying the cubed number\n\n return 0;\n}\n\ndouble cube (double n) //function that cubes the number\n{\n return n*n*n; // cubing the number and returning it\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265448/"
] |
332,859 | <p>Is it possible to have a WPF window/element detect the drag'n'dropping of a file from windows explorer in C# .Net 3.5? I've found solutions for WinForms, but none for WPF.</p>
| [
{
"answer_id": 332913,
"author": "NoizWaves",
"author_id": 38438,
"author_profile": "https://Stackoverflow.com/users/38438",
"pm_score": 2,
"selected": false,
"text": "private void btnFindType_Drop(object sender, DragEventArgs e)\n{\n if (e.Data is System.Windows.DataObject &&\n ((System.Windows.DataObject)e.Data).ContainsFileDropList())\n {\n foreach (string filePath in ((System.Windows.DataObject)e.Data).GetFileDropList())\n {\n // Processing here\n }\n } \n}\n"
},
{
"answer_id": 5755292,
"author": "AvSomeren",
"author_id": 720503,
"author_profile": "https://Stackoverflow.com/users/720503",
"pm_score": 3,
"selected": false,
"text": " private void MessageTextBox_Drop(object sender, DragEventArgs e)\n {\n if (e.Data is DataObject && ((DataObject)e.Data).ContainsFileDropList())\n {\n foreach (string filePath in ((DataObject)e.Data).GetFileDropList())\n {\n // Processing here \n }\n }\n }\n\n\n private void MessageTextBox_PreviewDragEnter(object sender, DragEventArgs e)\n {\n var dropPossible = e.Data != null && ((DataObject)e.Data).ContainsFileDropList();\n if (dropPossible)\n {\n e.Effects = DragDropEffects.Copy;\n }\n }\n\n private void MessageTextBox_PreviewDragOver(object sender, DragEventArgs e)\n {\n e.Handled = true;\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38438/"
] |
332,862 | <p>When in release it crashes with an unhandled exception: std::length error.</p>
<p>The call stack looks like this:</p>
<pre><code>msvcr90.dll!__set_flsgetvalue() Line 256 + 0xc bytes C
msvcr90.dll!__set_flsgetvalue() Line 256 + 0xc bytes C
msvcr90.dll!_getptd_noexit() Line 616 + 0x7 bytes C
msvcr90.dll!_getptd() Line 641 + 0x5 bytes C
msvcr90.dll!rand() Line 68 C
NEM.exe!CGAL::Random::Random() + 0x34 bytes C++
msvcr90.dll!_initterm(void (void)* * pfbegin=0x00000003, void (void)* * pfend=0x00345560) Line 903 C
NEM.exe!__tmainCRTStartup() Line 582 + 0x17 bytes C
kernel32.dll!7c817067()
</code></pre>
<p>Has anyone got any clues?</p>
| [
{
"answer_id": 333161,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "CGAL::Random::Random default_random CGAL::Random::Random default_random srand(time(NULL)) get_int rand() srand() __set_flsgetvalue"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78828/"
] |
332,864 | <p>In another question on SO I answered with code like the one below and got a comment that the LINQ-query probably was evaluated in every iteration of the for/each. Is that true?</p>
<p>I know that LINQ-querys does not executes before its items is evaluated so it seems possible that this way to iterate the result can make it run on every iteration? </p>
<pre><code>Dim d = New Dictionary(Of String, String)()
d.Add("Teststring", "Hello")
d.Add("1TestString1", "World")
d.Add("2TestString2", "Test")
For Each i As String In From e In d Where e.Value.StartsWith("W") Select e.Key
MsgBox("This key has a matching value:" & i)
Next
</code></pre>
| [
{
"answer_id": 332919,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 4,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n foreach (string item in MyCustomEnumerator()\n .Where(item => item.StartsWith(\"abc\")))\n {\n Console.WriteLine(item);\n }\n }\n\n static IEnumerable<string> MyCustomEnumerator()\n {\n Console.WriteLine(DateTime.Now);\n\n yield return \"abc1\";\n\n Console.WriteLine(DateTime.Now);\n\n yield return \"abc2\";\n\n Console.WriteLine(DateTime.Now);\n\n yield return \"abc3\";\n\n Console.WriteLine(DateTime.Now);\n\n yield return \"xxx\";\n }\n }\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19307/"
] |
332,871 | <p>this c# code is probably not the most efficient but gets what I want done. </p>
<p>How do I accomplish the same thing in F# code?</p>
<pre><code> string xml = " <EmailList> " +
" <Email>test@email.com</Email> " +
" <Email>test2@email.com</Email> " +
" </EmailList> ";
XmlDocument xdoc = new XmlDocument();
XmlNodeList nodeList;
String emailList = string.Empty;
xdoc.LoadXml(xml);
nodeList = xdoc.SelectNodes("//EmailList");
foreach (XmlNode item in nodeList)
{
foreach (XmlNode email in item)
{
emailList += email.InnerText.ToString() + Environment.NewLine ;
}
}
</code></pre>
| [
{
"answer_id": 332912,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 1,
"selected": false,
"text": "\nList<string> EmailAddresses(string xml)\n{\n XmlDocument xdoc = new XmlDocument();\n XmlNodeList nodeList;\n String emailList = string.Empty;\n xdoc.LoadXml(xml);\n nodeList = xdoc.SelectNodes(\"//EmailList\");\n foreach (XmlNode item in nodeList)\n {\n foreach (XmlNode email in item)\n {\n yield email.InnerText.ToString();\n } \n }\n}\n"
},
{
"answer_id": 332935,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 1,
"selected": false,
"text": "#light\nopen System.Xml\n\nlet xml = \"...\"\n\nlet emailList = \n let xdoc = new XmlDocument()\n xdoc.LoadXml(xml)\n\n let mutable list = []\n let addEmail e = list <- e :: emailList\n\n xdoc.SelectNodes(\"//EmailList\")\n |> IEnumerable.iter(fun(item:XmlNode) ->\n item\n |> IEnumerable.iter(fun(e:XmlNode) ->\n addEmail e.InnerText; ()))\n\n list\n"
},
{
"answer_id": 332941,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "open System.Xml\n\nlet getList x = \n let getDoc =\n let doc = new XmlDocument()\n doc.LoadXml(x) |> ignore\n doc\n let getEmail (n:XmlNode) = n.InnerText.ToString() \n let doc = getDoc\n let build = new System.Text.StringBuilder()\n doc.SelectNodes(\"//EmailList\") \n |> Seq.cast<XmlNode>\n |> Seq.map (fun n -> n.ChildNodes )\n |> Seq.map_concat (Seq.cast<XmlNode>)\n |> Seq.map(fun (n:XmlNode) -> getEmail n) \n |> Seq.iter (fun e -> build.AppendLine(e) |> ignore )\n build.ToString()\n"
},
{
"answer_id": 333077,
"author": "Derek Slager",
"author_id": 18636,
"author_profile": "https://Stackoverflow.com/users/18636",
"pm_score": 7,
"selected": true,
"text": "let doc = new XmlDocument() in\n doc.LoadXml xml;\n doc.SelectNodes \"/EmailList/Email/text()\"\n |> Seq.cast<XmlNode>\n |> Seq.map (fun node -> node.Value)\n |> String.concat Environment.NewLine\n"
},
{
"answer_id": 33896289,
"author": "marapet",
"author_id": 63733,
"author_profile": "https://Stackoverflow.com/users/63733",
"pm_score": 3,
"selected": false,
"text": "type EmailList = XmlProvider<\"\"\"<EmailList><Email>email</Email><Email>email</Email></EmailList>\"\"\">\nlet data = EmailList.Parse(\"\"\"\n <EmailList>\n <Email>test@email.com</Email>\n <Email>test2@email.com</Email>\n </EmailList>\n \"\"\")\n\nlet emailList = data.Emails |> String.concat Environment.NewLine\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72123/"
] |
332,872 | <p>How do you safely encode a URL using JavaScript such that it can be put into a GET string?</p>
<pre><code>var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
</code></pre>
<p>I assume that you need to encode the <code>myUrl</code> variable on that second line?</p>
| [
{
"answer_id": 332888,
"author": "Buu",
"author_id": 17815,
"author_profile": "https://Stackoverflow.com/users/17815",
"pm_score": 13,
"selected": true,
"text": "var myOtherUrl = \n \"http://example.com/index.html?url=\" + encodeURIComponent(myUrl);\n"
},
{
"answer_id": 332897,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 11,
"selected": false,
"text": "escape() @*/+ encodeURI() ~!@#$&*()=:/,;?+' encodeURIComponent() ~!*()' GET escape encodeURIComponent encodeURI"
},
{
"answer_id": 6171234,
"author": "Mike Brennan",
"author_id": 658138,
"author_profile": "https://Stackoverflow.com/users/658138",
"pm_score": 8,
"selected": false,
"text": "encodeURIComponent() encodeURI() escape() encodeURI() encodeURIComponent() encodeURIComponent()"
},
{
"answer_id": 11149802,
"author": "Asif Ashraf",
"author_id": 530794,
"author_profile": "https://Stackoverflow.com/users/530794",
"pm_score": 2,
"selected": false,
"text": "Response.Headers[\"land\"] = \"login\";\n $(function () {\n var $document = $(document);\n $document.ajaxSuccess(function (e, response, request) {\n var land = response.getResponseHeader('land');\n var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);\n if(land) {\n if (land.toString() === 'login') {\n window.location = redrUrl;\n }\n }\n });\n});\n"
},
{
"answer_id": 13890739,
"author": "Ryan Taylor",
"author_id": 845413,
"author_profile": "https://Stackoverflow.com/users/845413",
"pm_score": 7,
"selected": false,
"text": "encodeURIComponent const value = encodeURIComponent(value).replace('%20','+');\nconst url = 'http://example.com?lang=en&key=' + value\n escape encodeURI encodeURIComponent() + encodeURIComponent const escapedValue = encodeURIComponent(value).replace('%20','+');\nconst escapedFolder = encodeURIComponent('My Folder'); // no replace\nconst url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;\n"
},
{
"answer_id": 16514468,
"author": "Maksym Kozlenko",
"author_id": 171847,
"author_profile": "https://Stackoverflow.com/users/171847",
"pm_score": 5,
"selected": false,
"text": "qs.stringify({a:\"1=2\", b:\"Test 1\"}); // gets a=1%3D2&b=Test+1\n $.param $.param({a:\"1=2\", b:\"Test 1\"}) // gets a=1%3D2&b=Test+1\n"
},
{
"answer_id": 16536783,
"author": "Narayan Yerrabachu",
"author_id": 2379046,
"author_profile": "https://Stackoverflow.com/users/2379046",
"pm_score": 3,
"selected": false,
"text": "function fixedEncodeURIComponent(str){\n return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\\*/g, \"%2A\");\n}\n"
},
{
"answer_id": 32494888,
"author": "Sangeet Shah",
"author_id": 3539870,
"author_profile": "https://Stackoverflow.com/users/3539870",
"pm_score": 2,
"selected": false,
"text": "var encodedUrl = encodeURIComponent(url);\nconsole.log(encodedUrl);\n//outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes\n\n\nfor more info go http://www.sitepoint.com/jquery-decode-url-string\n"
},
{
"answer_id": 32882427,
"author": "Adam Fischer",
"author_id": 3472662,
"author_profile": "https://Stackoverflow.com/users/3472662",
"pm_score": 4,
"selected": false,
"text": "var myOtherUrl = \"http://example.com/index.html?url=\" + encodeURIComponent(myUrl);\n urlencode() phpencode() function urlencode(str) {\n str = (str + '').toString();\n\n // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current\n // PHP behavior, you would need to add \".replace(/~/g, '%7E');\" to the following.\n return encodeURIComponent(str)\n .replace('!', '%21')\n .replace('\\'', '%27')\n .replace('(', '%28')\n .replace(')', '%29')\n .replace('*', '%2A')\n .replace('%20', '+');\n}\n"
},
{
"answer_id": 39729290,
"author": "Mohith Maratt",
"author_id": 4977531,
"author_profile": "https://Stackoverflow.com/users/4977531",
"pm_score": 2,
"selected": false,
"text": "function encodeUrl(url)\n{\n String arr[] = url.split(\"/\");\n String encodedUrl = \"\";\n for(int i = 0; i<arr.length; i++)\n {\n encodedUrl = encodedUrl + ESAPI.encoder().encodeForHTML(ESAPI.encoder().encodeForURL(arr[i]));\n if(i<arr.length-1) encodedUrl = encodedUrl + \"/\";\n }\n return url;\n}\n"
},
{
"answer_id": 41492479,
"author": "serg",
"author_id": 20128,
"author_profile": "https://Stackoverflow.com/users/20128",
"pm_score": 3,
"selected": false,
"text": "abc%20xyz 123 encodeURI(\"abc%20xyz 123\") // Wrong: \"abc%2520xyz%20123\"\nencodeURI(decodeURI(\"abc%20xyz 123\")) // Correct: \"abc%20xyz%20123\"\n"
},
{
"answer_id": 41883359,
"author": "Gerard ONeill",
"author_id": 1331672,
"author_profile": "https://Stackoverflow.com/users/1331672",
"pm_score": 4,
"selected": false,
"text": "encodeURI()\n encodeURIComponent()\n"
},
{
"answer_id": 52464418,
"author": "Willem van der Veen",
"author_id": 8059459,
"author_profile": "https://Stackoverflow.com/users/8059459",
"pm_score": 3,
"selected": false,
"text": "console.log(encodeURIComponent('?notEncoded=&+')); notEncoded encodeURIComponent() encodeURI() encodeURIComponent() // for a whole URI don't use encodeURIComponent it will transform\n// the / characters and the URL won't fucntion properly\nconsole.log(encodeURIComponent(\"http://www.random.com/specials&char.html\"));\n\n// instead use encodeURI for whole URL's\nconsole.log(encodeURI(\"http://www.random.com/specials&char.html\")); encodeURIComponent encodeURIComponent encodeURI"
},
{
"answer_id": 54605332,
"author": "Jonathan Applebaum",
"author_id": 5718868,
"author_profile": "https://Stackoverflow.com/users/5718868",
"pm_score": 2,
"selected": false,
"text": "encodeURIComponent() decodeURIComponent() <!DOCTYPE html>\n<html>\n <head>\n <style>\n textarea{\n width: 30%;\n height: 100px;\n }\n </style>\n <script>\n // Encode string to Base64\n function encode()\n {\n var txt = document.getElementById(\"txt1\").value;\n var result = btoa(txt);\n document.getElementById(\"txt2\").value = result;\n }\n // Decode Base64 back to original string\n function decode()\n {\n var txt = document.getElementById(\"txt3\").value;\n var result = atob(txt);\n document.getElementById(\"txt4\").value = result;\n }\n </script>\n </head>\n <body>\n <div>\n <textarea id=\"txt1\">Some text to decode\n </textarea>\n </div>\n <div>\n <input type=\"button\" id=\"btnencode\" value=\"Encode\" onClick=\"encode()\"/>\n </div>\n <div>\n <textarea id=\"txt2\">\n </textarea>\n </div>\n <br/>\n <div>\n <textarea id=\"txt3\">U29tZSB0ZXh0IHRvIGRlY29kZQ==\n </textarea>\n </div>\n <div>\n <input type=\"button\" id=\"btndecode\" value=\"Decode\" onClick=\"decode()\"/>\n </div>\n <div>\n <textarea id=\"txt4\">\n </textarea>\n </div>\n </body>\n</html>\n"
},
{
"answer_id": 58252231,
"author": "Arthur",
"author_id": 9464680,
"author_profile": "https://Stackoverflow.com/users/9464680",
"pm_score": 2,
"selected": false,
"text": "fixedEncodeURIComponent function fixedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16);\n });\n}\n"
},
{
"answer_id": 58879100,
"author": "Qback",
"author_id": 7284582,
"author_profile": "https://Stackoverflow.com/users/7284582",
"pm_score": 5,
"selected": false,
"text": "const queryParams = { param1: 'value1', param2: 'value2' }\nconst queryString = new URLSearchParams(queryParams).toString()\n// 'param1=value1¶m2=value2'\n const myUrl = \"http://example.com/index.html?param=1&anotherParam=2\";\nconst myOtherUrl = new URL(\"http://example.com/index.html\");\nmyOtherUrl.search = new URLSearchParams({url: myUrl});\nconsole.log(myOtherUrl.toString());\n"
},
{
"answer_id": 61843371,
"author": "HoldOffHunger",
"author_id": 2430549,
"author_profile": "https://Stackoverflow.com/users/2430549",
"pm_score": 3,
"selected": false,
"text": "encodeURIComponent() encodeURIComponent() function fixedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16);\n });\n}\n"
},
{
"answer_id": 62340652,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 2,
"selected": false,
"text": "encodeURI escape function A(url) {\n return escape(url);\n}\n\nfunction B(url) {\n return encodeURI(url);\n}\n\nfunction C(url) {\n return encodeURIComponent(url);\n}\n\nfunction D(url) {\n return new URLSearchParams({url}).toString();\n}\n\nfunction E(url){\n return encodeURIComponent(url).replace(/[!'()]/g, escape).replace(/\\*/g, \"%2A\");\n}\n\nfunction F(url) {\n return encodeURIComponent(url).replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16);\n });\n}\n\n\n\n// ----------\n// TEST\n// ----------\n\nvar myUrl = \"http://example.com/index.html?param=1&anotherParam=2\";\n\n[A,B,C,D,E,F]\n .forEach(f=> console.log(`${f.name} ?url=${f(myUrl).replace(/^url=/,'')}`)); This snippet only presents code of choosen solutions"
},
{
"answer_id": 63477750,
"author": "gurpartap",
"author_id": 10090849,
"author_profile": "https://Stackoverflow.com/users/10090849",
"pm_score": 1,
"selected": false,
"text": "var myOtherUrl = \n \"http://example.com/index.html?url=\" + encodeURIComponent(myUrl).replace(/%20/g,'+');\n"
},
{
"answer_id": 65245370,
"author": "Pyzard",
"author_id": 13887747,
"author_profile": "https://Stackoverflow.com/users/13887747",
"pm_score": 0,
"selected": false,
"text": "function urlEncode(text) {\n let encoded = '';\n for (let char of text) {\n encoded += '%' + char.charCodeAt(0).toString(16);\n }\n return encoded;\n}\n"
},
{
"answer_id": 68210862,
"author": "m4heshd",
"author_id": 3378227,
"author_profile": "https://Stackoverflow.com/users/3378227",
"pm_score": 4,
"selected": false,
"text": "URL() const baseURL = 'http://example.com/index.html';\n\nconst myUrl = new URL(baseURL);\nmyUrl.searchParams.append('param', '1');\nmyUrl.searchParams.append('anotherParam', '2');\n\nconst myOtherUrl = new URL(baseURL);\nmyOtherUrl.searchParams.append('url', myUrl.href);\n\nconsole.log(myUrl.href);\n// Outputs: http://example.com/index.html?param=1&anotherParam=2\nconsole.log(myOtherUrl.href);\n// Outputs: http://example.com/index.html?url=http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2\nconsole.log(myOtherUrl.searchParams.get('url'));\n// Outputs: http://example.com/index.html?param=1&anotherParam=2\n const params = new URLSearchParams(myOtherUrl.search);\n\nconsole.log(params.get('url'));\n// Outputs: http://example.com/index.html?param=1&anotherParam=2\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
332,874 | <p>What is the purpose of the LongLength property for arrays in .Net. Using a standard integer for length, you could accommodate up to 2 billion indices. Are there really people using .Net to maintain a single array with more the 2 billion elements. Even if each element was a single byte, that would still be 2 GB of data. Is it feasible to use such a large array in .Net?</p>
| [
{
"answer_id": 333090,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": " 17,179,869,184 bytes of the\n18,446,744,073,709,551,616 bytes of 64-bit address space available.\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
] |
332,908 | <p>I'm administering a svn repo for a project where the source wasn't imported with a single top level directory. As a result, there are about 15 separate 'projects' instead of one. How can I merge these into one folder while maintaining the change history?</p>
<p>*hint: svn move doesn't work in this case.</p>
<p>[edit]
whoops, dupe of <a href="https://stackoverflow.com/questions/267256/combining-multiple-svn-repositories-into-one">Combining multiple SVN repositories into one</a></p>
| [
{
"answer_id": 332950,
"author": "Stewart Johnson",
"author_id": 6408,
"author_profile": "https://Stackoverflow.com/users/6408",
"pm_score": 0,
"selected": false,
"text": "svn propedit svn:externals top_dir"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2567/"
] |
332,920 | <p>In java, there's three levels of access:</p>
<ul>
<li>Public - Open to the world</li>
<li>Private - Open only to the class </li>
<li>Protected - Open only to the class and its subclasses (inheritance).</li>
</ul>
<p>So why does the java compiler allow this to happen?</p>
<p>TestBlah.java:</p>
<pre><code>public class TestBlah {
public static void main(String[] args) {
Blah a = new Blah("Blah");
Bloo b = new Bloo("Bloo");
System.out.println(a.getMessage());
System.out.println(b.getMessage()); //Works
System.out.println(a.testing);
System.out.println(b.testing); //Works
}
}
</code></pre>
<p>Blah.java:</p>
<pre><code>public class Blah {
protected String message;
public Blah(String msg) {
this.message = msg;
}
protected String getMessage(){
return(this.message);
}
}
</code></pre>
<p>Bloo.java:</p>
<pre><code>public class Bloo extends Blah {
public Bloo(String testing) {
super(testing);
}
}
</code></pre>
| [
{
"answer_id": 332933,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 4,
"selected": false,
"text": "protected public"
},
{
"answer_id": 332942,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "b.getMessage() b Bloo Blah getMessage() super() Bloo Blah new Blah() TestBlah main a.testing b.testing testing"
},
{
"answer_id": 332978,
"author": "Bob Cross",
"author_id": 5812,
"author_profile": "https://Stackoverflow.com/users/5812",
"pm_score": 3,
"selected": false,
"text": "protected protected public private final"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526/"
] |
332,930 | <p>I'm looking for something like: </p>
<pre><code>svnserve stop
</code></pre>
| [
{
"answer_id": 332940,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 6,
"selected": true,
"text": "kill"
},
{
"answer_id": 24862405,
"author": "JoDev",
"author_id": 2111078,
"author_profile": "https://Stackoverflow.com/users/2111078",
"pm_score": 3,
"selected": false,
"text": "start-stop-daemon /sbin/start-stop-daemon --stop --exec /usr/bin/svnserve\n /sbin/start-stop-daemon --start --chuid svn:svn --exec /usr/bin/svnserve -- -d -r /var/svn\n svn:svn /var/svn /etc/init.d/svnserve"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3966/"
] |
332,936 | <p>I recently signed up to shared web hosting with godaddy using Linux and PHP 5. I want to work with multiple RSS feeds. I previously had this all functioning under Apache, however, the host supplied the PEAR installation. Now I have to do this myself and I am in unfamiliar territory.I installed PEAR PHP and managed to get rss.php in the pear directory. It now asks for XML/Parser.php and I do not want to spend another week finding where and what to do.
Can you please inform me where i can find this routine and whther there is any problem in just copying it into the PEAR directory with ftp?</p>
| [
{
"answer_id": 334094,
"author": "Pawka",
"author_id": 33599,
"author_profile": "https://Stackoverflow.com/users/33599",
"pm_score": 0,
"selected": false,
"text": "get_include_path() set_include_path();"
},
{
"answer_id": 334972,
"author": "David",
"author_id": 9908,
"author_profile": "https://Stackoverflow.com/users/9908",
"pm_score": 0,
"selected": false,
"text": "echo ini_get('include_path');\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
332,948 | <p>I'm perplexed. At CodeRage today, Marco Cantu said that CharInSet was slow and I should try a Case statement instead. I did so in my parser and then checked with AQTime what the speedup was. I found the Case statement to be much slower.</p>
<p>4,894,539 executions of:</p>
<blockquote>
<p>while not CharInSet (P^, [' ', #10,#13, #0]) do inc(P);</p>
</blockquote>
<p>was timed at 0.25 seconds.</p>
<p>But the same number of executions of:</p>
<blockquote>
<p>while True do<br>
case P^ of<br>
' ', #10, #13, #0: break;<br>
else inc(P);<br>
end;</p>
</blockquote>
<p>takes .16 seconds for the "while True", .80 seconds for the first case, and .13 seconds for the else case, totaling 1.09 seconds, or over 4 times as long.</p>
<p>The assembler code for the CharInSet statement is:</p>
<blockquote>
<p>add edi,$02<br>
mov edx,$0064b290<br>
movzx eax,[edi]<br>
call CharInSet<br>
test a1,a1<br>
jz $00649f18 (back to the add statement)</p>
</blockquote>
<p>whereas the case logic is simply this:</p>
<blockquote>
<p>movzx eax,[edi]<br>
sub ax,$01<br>
jb $00649ef0<br>
sub ax,$09<br>
jz $00649ef0<br>
sub ax,$03<br>
jz $00649ef0<br>
add edi,$02<br>
jmp $00649ed6 (back to the movzx statement)</p>
</blockquote>
<p>The case logic looks to me to be using very efficient assembler, whereas the CharInSet statement actually has to make a call to the CharInSet function, which is in SysUtils and is also simple, being:</p>
<blockquote>
<p>function CharInSet(C: AnsiChar; const CharSet: TSysCharSet): Boolean;<br>
begin<br>
Result := C in CharSet;<br>
end;</p>
</blockquote>
<p>I think the only reason why this is done is because P^ in [' ', #10, #13, #0] is no longer allowed in Delphi 2009 so the call does the conversion of types to allow it.</p>
<p>None-the-less I am very surprised by this and still don't trust my result.</p>
<p>Is AQTime measuring something wrong, am I missing something in this comparison, or is CharInSet truly an efficient function worth using?</p>
<hr>
<p>Conclusion: </p>
<p>I think you got it, Barry. Thank you for taking the time and doing the detailed example. I tested your code on my machine and got .171, .066 and .052 seconds (I guess my desktop is a bit faster than your laptop).</p>
<p>Testing that code in AQTime, it gives: 0.79, 1.57 and 1.46 seconds for the three tests. There you can see the large overhead from the instrumentation. But what really surprises me is that this overhead changes the apparent "best" result to be the CharInSet function which is actually the worst.</p>
<p>So Marcu is correct and CharInSet is slower. But you've inadvertently (or maybe on purpose) given me a better way by pulling out what CharInSet is doing with the AnsiChar(P^) in Set method. Other than the minor speed advantage over the case method, it is also less code and more understandable than using the cases.</p>
<p>You've also made me aware of the possibility of incorrect optimization using AQTime (and other instrumenting profilers). Knowing this will help my decision re <a href="https://stackoverflow.com/questions/291631/profiler-and-memory-analysis-tools-for-delphi">Profiler and Memory Analysis Tools for Delphi</a> and it also is another answer to my question <a href="https://stackoverflow.com/questions/322315/how-does-aqtime-do-it">How Does AQTime Do It?</a>. Of course, AQTime doesn't change the code when it instruments, so it must use some other magic to do it.</p>
<p>So the answer is that AQTime is showing results that lead to the incorrect conclusion.</p>
<hr>
<p>Followup: I left this question with the "accusation" that AQTime results may be misleading. But to be fair, I should direct you to read through this question: <a href="https://stackoverflow.com/questions/1694001/is-there-a-fast-gettoken-routine-for-delphi">Is There A Fast GetToken Routine For Delphi?</a> which started off thinking AQTime gave misleading results, and concludes that it does not.</p>
| [
{
"answer_id": 332975,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 6,
"selected": true,
"text": "case CharInSet {$apptype console}\n\nuses Windows, SysUtils;\n\nconst\n SampleString = 'foo bar baz blah de;blah de blah.';\n\nprocedure P1;\nvar\n cp: PChar;\nbegin\n cp := PChar(SampleString);\n while not CharInSet(cp^, [#0, ';', '.']) do\n Inc(cp);\nend;\n\nprocedure P2;\nvar\n cp: PChar;\nbegin\n cp := PChar(SampleString);\n while True do\n case cp^ of\n '.', #0, ';':\n Break;\n else\n Inc(cp);\n end;\nend;\n\nprocedure P3;\nvar\n cp: PChar;\nbegin\n cp := PChar(SampleString);\n while not (AnsiChar(cp^) in [#0, ';', '.']) do\n Inc(cp);\nend;\n\nprocedure Time(const Title: string; Proc: TProc);\nvar\n i: Integer;\n start, finish, freq: Int64;\nbegin\n QueryPerformanceCounter(start);\n for i := 1 to 1000000 do\n Proc;\n QueryPerformanceCounter(finish);\n QueryPerformanceFrequency(freq);\n Writeln(Format('%20s: %.3f seconds', [Title, (finish - start) / freq]));\nend;\n\nbegin\n Time('CharInSet', P1);\n Time('case stmt', P2);\n Time('set test', P3);\nend.\n CharInSet: 0.261 seconds\ncase stmt: 0.077 seconds\n set test: 0.060 seconds\n"
},
{
"answer_id": 333502,
"author": "PatrickvL",
"author_id": 12170,
"author_profile": "https://Stackoverflow.com/users/12170",
"pm_score": 3,
"selected": false,
"text": "procedure P1;\nvar\n cp: PChar;\nbegin\n cp := PChar(SampleString);\n while True do\n if CharInSet(cp^, [#0, ';', '.']) then\n Break\n else\n Inc(cp);\nend;\n\nprocedure P2;\nvar\n cp: PChar;\nbegin\n cp := PChar(SampleString);\n while True do\n case cp^ of\n '.', #0, ';':\n Break;\n else\n Inc(cp);\n end;\nend;\n\nprocedure P3;\nvar\n cp: PChar;\nbegin\n cp := PChar(SampleString);\n while True do\n if AnsiChar(cp^) in [#0, ';', '.'] then\n Break\n else\n Inc(cp);\nend;\n CharInSet: 0.099 seconds\ncase stmt: 0.043 seconds\n set test: 0.043 seconds\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30176/"
] |
332,952 | <p>I have been noticing some very strange usage of O(1) in discussion of algorithms involving hashing and types of search, often in the context of using a dictionary type provided by the language system, or using dictionary or hash-array types used using array-index notation.</p>
<p>Basically, O(1) means bounded by a constant time and (typically) fixed space. Some pretty fundamental operations are O(1), although using intermediate languages and special VMs tends to distort ones thinking here (e.g., how does one amortize the garbage collector and other dynamic processes over what would otherwise be O(1) activities).</p>
<p>But ignoring amortization of latencies, garbage-collection, and so on, I still don't understand how the leap to assumption that certain techniques that involve some kind of searching can be O(1) except under very special conditions.</p>
<p>Although I have noticed this before, an example just showed up in the <a href="https://stackoverflow.com/questions/330978/proper-collection-to-use-to-obtain-items-in-o1-time-in-c-net">Pandincus question, "'Proper’ collection to use to obtain items in O(1) time in C# .NET?"</a>.</p>
<p>As I remarked there, the only collection I know of that provides O(1) access as a guaranteed bound is a fixed-bound array with an integer index value. The presumption is that the array is implemented by some mapping to random access memory that uses O(1) operations to locate the cell having that index.</p>
<p>For collections that involve some sort of searching to determine the location of a matching cell for a different kind of index (or for a sparse array with integer index), life is not so easy. In particular, if there are collisons and congestion is possible, access is not exactly O(1). And if the collection is flexible, one must recognize and amortize the cost of expanding the underlying structure (such as a tree or a hash table) for <strike>which</strike> congestion relief (e.g., high collision incidence or tree imbalance).</p>
<p>I would never have thought to speak of these flexible and dynamic structures as O(1). Yet I see them offered up as O(1) solutions without any identification of the conditions that must be maintained to actually have O(1) access be assured (as well as have that constant be negligibly small).</p>
<p>THE QUESTION: All of this preparation is really for a question. What is the casualness around O(1) and why is it accepted so blindly? Is it recognized that even O(1) can be undesirably large, even though near-constant? Or is O(1) simply the appropriation of a computational-complexity notion to informal use? I'm puzzled.</p>
<p>UPDATE: The Answers and comments point out where I was casual about defining O(1) myself, and I have repaired that. I am still looking for good answers, and some of the comment threads are rather more interesting than their answers, in a few cases.</p>
| [
{
"answer_id": 333011,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 3,
"selected": false,
"text": "(key, value) (Name, Bob) (Occupation, Student) (Location, Earth) key key value hash_function hash_function(\"Name\") hash_function(\"Occupation\") hash_function(\"Location\") (key, value) array[18] = (\"Name\", \"Bob\")\narray[32] = (\"Occupation\", \"Student\")\narray[74] = (\"Location\", \"Earth\")\n \"Name\" hash_function(\"Name\") (\"Pet\", \"Dog\") hash_function(\"Pet\") \"Name\" array[29] = (\"Pet\", \"Dog\")\n \"Pet\" \"Pet\" hash_function(\"Pet\") \"Name\" \"Pet\" \"Pet\""
},
{
"answer_id": 333106,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 6,
"selected": false,
"text": "O(1) O(1) O(N) O(1) O(N) O(1) O(N) O(1) O(1) O(N)"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33810/"
] |
332,955 | <p>As part of our unit tests, we restore a blank database when the tests start . The unit tests then perform their tests by calling web services (hosted in the Visual Studio ASP.NET host). </p>
<p>This works fine for us the first time the unit tests are run, however if they are re-run without restarting the web services, an exception is raised as all the connections have been reset as part of the restore.</p>
<p>The code below simulates what occurs:</p>
<pre><code>static void Main(string[] args)
{
DoDBStuff();
new Server("localhost").KillAllProcesses("Test");
DoDBStuff();
}
private static void DoDBStuff()
{
string constr = "Data Source=localhost;Initial Catalog=Test;Trusted_Connection=Yes";
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT TOP 1 id FROM sysobjects", con))
{
int? i = cmd.ExecuteScalar() as int?;
}
}
}
</code></pre>
<p>All the code, except for the KillAllProcesses runs in the web service's process, while the KillAllProcess runs in the Unit Test process. The same could be achieved by restarting the SQL server.</p>
<p>The problem we face is the webservices doesn't know when the connection is killed, and just picks a "bad" connection from the connection pool. Further, the creation of a connection and the execution of the command are several layers apart within the app.</p>
<p>How can we detect that a connection is "bad" before executing a command, without drastically affecting the performance of the application?</p>
| [
{
"answer_id": 333290,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": true,
"text": "static void Main(string[] args)\n{ \n DoDBStuff(); \n new Server(\"localhost\").KillAllProcesses(\"Test\");\n SqlConnection.ClearAllPools();\n DoDBStuff();\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10784/"
] |
332,972 | <p>I have Visual Studio 2008 with SP1 installed and it is crashing when I'm using lambda expressions in the Moq Framework.</p>
<p>At first I thought the problem was Resharper...but now that I have uninstalled it, VS 2008 still crashes. I'm able to replicate the issue every time.</p>
<p>I'm thinking perhaps it may be some other plugin that is causing the issue rather than VS 2008...but I can't be sure of that.</p>
<p>So what I'm trying to find is where Visual Studio logs the crashes that occur?</p>
<p>Unfortunately I'm unable to find it...does anyone out there know if it exists and if so where to look?</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 333514,
"author": "Arnout",
"author_id": 3496,
"author_profile": "https://Stackoverflow.com/users/3496",
"pm_score": 6,
"selected": true,
"text": "devenv.exe /log"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39532/"
] |
332,973 | <p>Any idea on how to check whether that list is a subset of another?</p>
<p>Specifically, I have</p>
<pre><code>List<double> t1 = new List<double> { 1, 3, 5 };
List<double> t2 = new List<double> { 1, 5 };
</code></pre>
<p>How to check that t2 is a subset of t1, using LINQ?</p>
| [
{
"answer_id": 332979,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": -1,
"selected": false,
"text": "static bool IsSubSet<A>(A[] set, A[] toCheck) {\n return set.Length == (toCheck.Intersect(set)).Count();\n}\n"
},
{
"answer_id": 333003,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "HashSet<double> t1 = new HashSet<double>{1,3,5};\nHashSet<double> t2 = new HashSet<double>{1,5};\n\nbool isSubset = t2.IsSubsetOf(t1);\n"
},
{
"answer_id": 333034,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 9,
"selected": true,
"text": "bool isSubset = !t2.Except(t1).Any();\n"
},
{
"answer_id": 9435708,
"author": "Neil",
"author_id": 148593,
"author_profile": "https://Stackoverflow.com/users/148593",
"pm_score": 3,
"selected": false,
"text": "public static bool IsSubsetOf<T>(this IEnumerable<T> a, IEnumerable<T> b)\n{\n return !a.Except(b).Any();\n}\n bool isSubset = t2.IsSubsetOf(t1);\n"
},
{
"answer_id": 25526211,
"author": "Géza",
"author_id": 999089,
"author_profile": "https://Stackoverflow.com/users/999089",
"pm_score": 4,
"selected": false,
"text": "CollectionAssert.IsSubsetOf(subset, superset);\n CollectionAssert.IsSubsetOf(t2, t1);\n"
},
{
"answer_id": 26697119,
"author": "user2325458",
"author_id": 2325458,
"author_profile": "https://Stackoverflow.com/users/2325458",
"pm_score": 4,
"selected": false,
"text": "bool isSubset = t2.All(elem => t1.Contains(elem));\n bool isSubset = true;\nforeach (var element in t2) {\n if (!t1.Contains(element)) {\n isSubset = false;\n break;\n }\n}\n"
},
{
"answer_id": 46885122,
"author": "sclarke81",
"author_id": 1326370,
"author_profile": "https://Stackoverflow.com/users/1326370",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Determines whether a sequence contains the specified elements by using the default equality comparer.\n/// </summary>\n/// <typeparam name=\"TSource\">The type of the elements of source.</typeparam>\n/// <param name=\"source\">A sequence in which to locate the values.</param>\n/// <param name=\"values\">The values to locate in the sequence.</param>\n/// <returns>true if the source sequence contains elements that have the specified values; otherwise, false.</returns>\npublic static bool ContainsAll<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> values)\n{\n return !values.Except(source).Any();\n}\n"
},
{
"answer_id": 50732843,
"author": "Lucifer",
"author_id": 6947385,
"author_profile": "https://Stackoverflow.com/users/6947385",
"pm_score": -1,
"selected": false,
"text": "t2 t1 bool isSubset = !(t2.Any(x => !t1.Contains(x)));\n"
},
{
"answer_id": 64401273,
"author": "zetroot",
"author_id": 6098419,
"author_profile": "https://Stackoverflow.com/users/6098419",
"pm_score": 3,
"selected": false,
"text": "!t2.Except(t1).Any() t2.IsSubsetOf(t1) t2.All(elem => t1.Contains(elem)) [0; Variability) [0; Variability) ToHashSet() prebuilt HashSet All(=>Contains) | Method | SupersetsInIteration | SubsetLength | Variability | Mean | Error | StdDev | Median |\n|------------------- |--------------------- |------------- |------------ |--------------:|-------------:|-------------:|--------------:|\n| Except().Any() | 1000 | 10 | 100 | 1,485.89 μs | 7.363 μs | 6.887 μs | 1,488.36 μs |\n| ToHashSet() | 1000 | 10 | 100 | 1,015.59 μs | 5.099 μs | 4.770 μs | 1,015.43 μs |\n| prebuilt HashSet | 1000 | 10 | 100 | 38.76 μs | 0.065 μs | 0.054 μs | 38.78 μs |\n| All(=>Contains) | 1000 | 10 | 100 | 105.46 μs | 0.320 μs | 0.267 μs | 105.38 μs |\n| Except().Any() | 1000 | 10 | 10000 | 1,912.17 μs | 38.180 μs | 87.725 μs | 1,890.72 μs |\n| ToHashSet() | 1000 | 10 | 10000 | 1,038.70 μs | 20.028 μs | 40.459 μs | 1,019.35 μs |\n| prebuilt HashSet | 1000 | 10 | 10000 | 28.22 μs | 0.165 μs | 0.155 μs | 28.24 μs |\n| All(=>Contains) | 1000 | 10 | 10000 | 81.47 μs | 0.117 μs | 0.109 μs | 81.45 μs |\n| Except().Any() | 1000 | 50 | 100 | 4,888.22 μs | 81.268 μs | 76.019 μs | 4,854.42 μs |\n| ToHashSet() | 1000 | 50 | 100 | 4,323.23 μs | 21.424 μs | 18.992 μs | 4,315.16 μs |\n| prebuilt HashSet | 1000 | 50 | 100 | 186.53 μs | 1.257 μs | 1.176 μs | 186.35 μs |\n| All(=>Contains) | 1000 | 50 | 100 | 1,173.37 μs | 2.667 μs | 2.227 μs | 1,173.08 μs |\n| Except().Any() | 1000 | 50 | 10000 | 7,148.22 μs | 20.545 μs | 19.218 μs | 7,138.22 μs |\n| ToHashSet() | 1000 | 50 | 10000 | 4,576.69 μs | 20.955 μs | 17.499 μs | 4,574.34 μs |\n| prebuilt HashSet | 1000 | 50 | 10000 | 33.87 μs | 0.160 μs | 0.142 μs | 33.85 μs |\n| All(=>Contains) | 1000 | 50 | 10000 | 131.34 μs | 0.569 μs | 0.475 μs | 131.24 μs |\n| Except().Any() | 10000 | 10 | 100 | 14,798.42 μs | 120.423 μs | 112.643 μs | 14,775.43 μs |\n| ToHashSet() | 10000 | 10 | 100 | 10,263.52 μs | 64.082 μs | 59.942 μs | 10,265.58 μs |\n| prebuilt HashSet | 10000 | 10 | 100 | 1,241.19 μs | 4.248 μs | 3.973 μs | 1,241.75 μs |\n| All(=>Contains) | 10000 | 10 | 100 | 1,058.41 μs | 6.766 μs | 6.329 μs | 1,059.22 μs |\n| Except().Any() | 10000 | 10 | 10000 | 16,318.65 μs | 97.878 μs | 91.555 μs | 16,310.02 μs |\n| ToHashSet() | 10000 | 10 | 10000 | 10,393.23 μs | 68.236 μs | 63.828 μs | 10,386.27 μs |\n| prebuilt HashSet | 10000 | 10 | 10000 | 1,087.21 μs | 2.812 μs | 2.631 μs | 1,085.89 μs |\n| All(=>Contains) | 10000 | 10 | 10000 | 847.88 μs | 1.536 μs | 1.436 μs | 847.34 μs |\n| Except().Any() | 10000 | 50 | 100 | 48,257.76 μs | 232.573 μs | 181.578 μs | 48,236.31 μs |\n| ToHashSet() | 10000 | 50 | 100 | 43,938.46 μs | 994.200 μs | 2,687.877 μs | 42,877.97 μs |\n| prebuilt HashSet | 10000 | 50 | 100 | 4,634.98 μs | 16.757 μs | 15.675 μs | 4,643.17 μs |\n| All(=>Contains) | 10000 | 50 | 100 | 10,256.62 μs | 26.440 μs | 24.732 μs | 10,243.34 μs |\n| Except().Any() | 10000 | 50 | 10000 | 73,192.15 μs | 479.584 μs | 425.139 μs | 73,077.26 μs |\n| ToHashSet() | 10000 | 50 | 10000 | 45,880.72 μs | 141.497 μs | 125.433 μs | 45,860.50 μs |\n| prebuilt HashSet | 10000 | 50 | 10000 | 1,620.61 μs | 3.507 μs | 3.280 μs | 1,620.52 μs |\n| All(=>Contains) | 10000 | 50 | 10000 | 1,460.01 μs | 1.819 μs | 1.702 μs | 1,459.49 μs |\n| Except().Any() | 100000 | 10 | 100 | 149,047.91 μs | 1,696.388 μs | 1,586.803 μs | 149,063.20 μs |\n| ToHashSet() | 100000 | 10 | 100 | 100,657.74 μs | 150.890 μs | 117.805 μs | 100,654.39 μs |\n| prebuilt HashSet | 100000 | 10 | 100 | 12,753.33 μs | 17.257 μs | 15.298 μs | 12,749.85 μs |\n| All(=>Contains) | 100000 | 10 | 100 | 11,238.79 μs | 54.228 μs | 50.725 μs | 11,247.03 μs |\n| Except().Any() | 100000 | 10 | 10000 | 163,277.55 μs | 1,096.107 μs | 1,025.299 μs | 163,556.98 μs |\n| ToHashSet() | 100000 | 10 | 10000 | 99,927.78 μs | 403.811 μs | 337.201 μs | 99,812.12 μs |\n| prebuilt HashSet | 100000 | 10 | 10000 | 11,671.99 μs | 6.753 μs | 5.986 μs | 11,672.28 μs |\n| All(=>Contains) | 100000 | 10 | 10000 | 8,217.51 μs | 67.959 μs | 56.749 μs | 8,225.85 μs |\n| Except().Any() | 100000 | 50 | 100 | 493,925.76 μs | 2,169.048 μs | 1,922.805 μs | 493,386.70 μs |\n| ToHashSet() | 100000 | 50 | 100 | 432,214.15 μs | 1,261.673 μs | 1,180.169 μs | 431,624.50 μs |\n| prebuilt HashSet | 100000 | 50 | 100 | 49,593.29 μs | 75.300 μs | 66.751 μs | 49,598.45 μs |\n| All(=>Contains) | 100000 | 50 | 100 | 98,662.71 μs | 119.057 μs | 111.366 μs | 98,656.00 μs |\n| Except().Any() | 100000 | 50 | 10000 | 733,526.81 μs | 8,728.516 μs | 8,164.659 μs | 733,455.20 μs |\n| ToHashSet() | 100000 | 50 | 10000 | 460,166.27 μs | 7,227.011 μs | 6,760.150 μs | 457,359.70 μs |\n| prebuilt HashSet | 100000 | 50 | 10000 | 17,443.96 μs | 10.839 μs | 9.608 μs | 17,443.40 μs |\n| All(=>Contains) | 100000 | 50 | 10000 | 14,222.31 μs | 47.090 μs | 44.048 μs | 14,217.94 μs |\n\n"
},
{
"answer_id": 64681752,
"author": "Valdas Zaramba",
"author_id": 2119656,
"author_profile": "https://Stackoverflow.com/users/2119656",
"pm_score": 0,
"selected": false,
"text": "array1 array2 array1 array2 array1.All(ar1 => array2.Any(ar2 => ar2.Equals(ar1)));\n ar2.Equals(ar1)"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
332,984 | <p>how do i get a list of user that have completed or not completed or not responded to a survey. </p>
<p>so i have a survey, lets say "survey A". in this survey i have a list of people or groups that must fill the survey. sharepoint already gives us a list of respondents, but i want to make a list of people that have not responded or not completed the survey.</p>
<p>i'm using c#, thanks..</p>
| [
{
"answer_id": 332979,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": -1,
"selected": false,
"text": "static bool IsSubSet<A>(A[] set, A[] toCheck) {\n return set.Length == (toCheck.Intersect(set)).Count();\n}\n"
},
{
"answer_id": 333003,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "HashSet<double> t1 = new HashSet<double>{1,3,5};\nHashSet<double> t2 = new HashSet<double>{1,5};\n\nbool isSubset = t2.IsSubsetOf(t1);\n"
},
{
"answer_id": 333034,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 9,
"selected": true,
"text": "bool isSubset = !t2.Except(t1).Any();\n"
},
{
"answer_id": 9435708,
"author": "Neil",
"author_id": 148593,
"author_profile": "https://Stackoverflow.com/users/148593",
"pm_score": 3,
"selected": false,
"text": "public static bool IsSubsetOf<T>(this IEnumerable<T> a, IEnumerable<T> b)\n{\n return !a.Except(b).Any();\n}\n bool isSubset = t2.IsSubsetOf(t1);\n"
},
{
"answer_id": 25526211,
"author": "Géza",
"author_id": 999089,
"author_profile": "https://Stackoverflow.com/users/999089",
"pm_score": 4,
"selected": false,
"text": "CollectionAssert.IsSubsetOf(subset, superset);\n CollectionAssert.IsSubsetOf(t2, t1);\n"
},
{
"answer_id": 26697119,
"author": "user2325458",
"author_id": 2325458,
"author_profile": "https://Stackoverflow.com/users/2325458",
"pm_score": 4,
"selected": false,
"text": "bool isSubset = t2.All(elem => t1.Contains(elem));\n bool isSubset = true;\nforeach (var element in t2) {\n if (!t1.Contains(element)) {\n isSubset = false;\n break;\n }\n}\n"
},
{
"answer_id": 46885122,
"author": "sclarke81",
"author_id": 1326370,
"author_profile": "https://Stackoverflow.com/users/1326370",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Determines whether a sequence contains the specified elements by using the default equality comparer.\n/// </summary>\n/// <typeparam name=\"TSource\">The type of the elements of source.</typeparam>\n/// <param name=\"source\">A sequence in which to locate the values.</param>\n/// <param name=\"values\">The values to locate in the sequence.</param>\n/// <returns>true if the source sequence contains elements that have the specified values; otherwise, false.</returns>\npublic static bool ContainsAll<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> values)\n{\n return !values.Except(source).Any();\n}\n"
},
{
"answer_id": 50732843,
"author": "Lucifer",
"author_id": 6947385,
"author_profile": "https://Stackoverflow.com/users/6947385",
"pm_score": -1,
"selected": false,
"text": "t2 t1 bool isSubset = !(t2.Any(x => !t1.Contains(x)));\n"
},
{
"answer_id": 64401273,
"author": "zetroot",
"author_id": 6098419,
"author_profile": "https://Stackoverflow.com/users/6098419",
"pm_score": 3,
"selected": false,
"text": "!t2.Except(t1).Any() t2.IsSubsetOf(t1) t2.All(elem => t1.Contains(elem)) [0; Variability) [0; Variability) ToHashSet() prebuilt HashSet All(=>Contains) | Method | SupersetsInIteration | SubsetLength | Variability | Mean | Error | StdDev | Median |\n|------------------- |--------------------- |------------- |------------ |--------------:|-------------:|-------------:|--------------:|\n| Except().Any() | 1000 | 10 | 100 | 1,485.89 μs | 7.363 μs | 6.887 μs | 1,488.36 μs |\n| ToHashSet() | 1000 | 10 | 100 | 1,015.59 μs | 5.099 μs | 4.770 μs | 1,015.43 μs |\n| prebuilt HashSet | 1000 | 10 | 100 | 38.76 μs | 0.065 μs | 0.054 μs | 38.78 μs |\n| All(=>Contains) | 1000 | 10 | 100 | 105.46 μs | 0.320 μs | 0.267 μs | 105.38 μs |\n| Except().Any() | 1000 | 10 | 10000 | 1,912.17 μs | 38.180 μs | 87.725 μs | 1,890.72 μs |\n| ToHashSet() | 1000 | 10 | 10000 | 1,038.70 μs | 20.028 μs | 40.459 μs | 1,019.35 μs |\n| prebuilt HashSet | 1000 | 10 | 10000 | 28.22 μs | 0.165 μs | 0.155 μs | 28.24 μs |\n| All(=>Contains) | 1000 | 10 | 10000 | 81.47 μs | 0.117 μs | 0.109 μs | 81.45 μs |\n| Except().Any() | 1000 | 50 | 100 | 4,888.22 μs | 81.268 μs | 76.019 μs | 4,854.42 μs |\n| ToHashSet() | 1000 | 50 | 100 | 4,323.23 μs | 21.424 μs | 18.992 μs | 4,315.16 μs |\n| prebuilt HashSet | 1000 | 50 | 100 | 186.53 μs | 1.257 μs | 1.176 μs | 186.35 μs |\n| All(=>Contains) | 1000 | 50 | 100 | 1,173.37 μs | 2.667 μs | 2.227 μs | 1,173.08 μs |\n| Except().Any() | 1000 | 50 | 10000 | 7,148.22 μs | 20.545 μs | 19.218 μs | 7,138.22 μs |\n| ToHashSet() | 1000 | 50 | 10000 | 4,576.69 μs | 20.955 μs | 17.499 μs | 4,574.34 μs |\n| prebuilt HashSet | 1000 | 50 | 10000 | 33.87 μs | 0.160 μs | 0.142 μs | 33.85 μs |\n| All(=>Contains) | 1000 | 50 | 10000 | 131.34 μs | 0.569 μs | 0.475 μs | 131.24 μs |\n| Except().Any() | 10000 | 10 | 100 | 14,798.42 μs | 120.423 μs | 112.643 μs | 14,775.43 μs |\n| ToHashSet() | 10000 | 10 | 100 | 10,263.52 μs | 64.082 μs | 59.942 μs | 10,265.58 μs |\n| prebuilt HashSet | 10000 | 10 | 100 | 1,241.19 μs | 4.248 μs | 3.973 μs | 1,241.75 μs |\n| All(=>Contains) | 10000 | 10 | 100 | 1,058.41 μs | 6.766 μs | 6.329 μs | 1,059.22 μs |\n| Except().Any() | 10000 | 10 | 10000 | 16,318.65 μs | 97.878 μs | 91.555 μs | 16,310.02 μs |\n| ToHashSet() | 10000 | 10 | 10000 | 10,393.23 μs | 68.236 μs | 63.828 μs | 10,386.27 μs |\n| prebuilt HashSet | 10000 | 10 | 10000 | 1,087.21 μs | 2.812 μs | 2.631 μs | 1,085.89 μs |\n| All(=>Contains) | 10000 | 10 | 10000 | 847.88 μs | 1.536 μs | 1.436 μs | 847.34 μs |\n| Except().Any() | 10000 | 50 | 100 | 48,257.76 μs | 232.573 μs | 181.578 μs | 48,236.31 μs |\n| ToHashSet() | 10000 | 50 | 100 | 43,938.46 μs | 994.200 μs | 2,687.877 μs | 42,877.97 μs |\n| prebuilt HashSet | 10000 | 50 | 100 | 4,634.98 μs | 16.757 μs | 15.675 μs | 4,643.17 μs |\n| All(=>Contains) | 10000 | 50 | 100 | 10,256.62 μs | 26.440 μs | 24.732 μs | 10,243.34 μs |\n| Except().Any() | 10000 | 50 | 10000 | 73,192.15 μs | 479.584 μs | 425.139 μs | 73,077.26 μs |\n| ToHashSet() | 10000 | 50 | 10000 | 45,880.72 μs | 141.497 μs | 125.433 μs | 45,860.50 μs |\n| prebuilt HashSet | 10000 | 50 | 10000 | 1,620.61 μs | 3.507 μs | 3.280 μs | 1,620.52 μs |\n| All(=>Contains) | 10000 | 50 | 10000 | 1,460.01 μs | 1.819 μs | 1.702 μs | 1,459.49 μs |\n| Except().Any() | 100000 | 10 | 100 | 149,047.91 μs | 1,696.388 μs | 1,586.803 μs | 149,063.20 μs |\n| ToHashSet() | 100000 | 10 | 100 | 100,657.74 μs | 150.890 μs | 117.805 μs | 100,654.39 μs |\n| prebuilt HashSet | 100000 | 10 | 100 | 12,753.33 μs | 17.257 μs | 15.298 μs | 12,749.85 μs |\n| All(=>Contains) | 100000 | 10 | 100 | 11,238.79 μs | 54.228 μs | 50.725 μs | 11,247.03 μs |\n| Except().Any() | 100000 | 10 | 10000 | 163,277.55 μs | 1,096.107 μs | 1,025.299 μs | 163,556.98 μs |\n| ToHashSet() | 100000 | 10 | 10000 | 99,927.78 μs | 403.811 μs | 337.201 μs | 99,812.12 μs |\n| prebuilt HashSet | 100000 | 10 | 10000 | 11,671.99 μs | 6.753 μs | 5.986 μs | 11,672.28 μs |\n| All(=>Contains) | 100000 | 10 | 10000 | 8,217.51 μs | 67.959 μs | 56.749 μs | 8,225.85 μs |\n| Except().Any() | 100000 | 50 | 100 | 493,925.76 μs | 2,169.048 μs | 1,922.805 μs | 493,386.70 μs |\n| ToHashSet() | 100000 | 50 | 100 | 432,214.15 μs | 1,261.673 μs | 1,180.169 μs | 431,624.50 μs |\n| prebuilt HashSet | 100000 | 50 | 100 | 49,593.29 μs | 75.300 μs | 66.751 μs | 49,598.45 μs |\n| All(=>Contains) | 100000 | 50 | 100 | 98,662.71 μs | 119.057 μs | 111.366 μs | 98,656.00 μs |\n| Except().Any() | 100000 | 50 | 10000 | 733,526.81 μs | 8,728.516 μs | 8,164.659 μs | 733,455.20 μs |\n| ToHashSet() | 100000 | 50 | 10000 | 460,166.27 μs | 7,227.011 μs | 6,760.150 μs | 457,359.70 μs |\n| prebuilt HashSet | 100000 | 50 | 10000 | 17,443.96 μs | 10.839 μs | 9.608 μs | 17,443.40 μs |\n| All(=>Contains) | 100000 | 50 | 10000 | 14,222.31 μs | 47.090 μs | 44.048 μs | 14,217.94 μs |\n\n"
},
{
"answer_id": 64681752,
"author": "Valdas Zaramba",
"author_id": 2119656,
"author_profile": "https://Stackoverflow.com/users/2119656",
"pm_score": 0,
"selected": false,
"text": "array1 array2 array1 array2 array1.All(ar1 => array2.Any(ar2 => ar2.Equals(ar1)));\n ar2.Equals(ar1)"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23491/"
] |
332,985 | <p>Trying to build a dashboard using Oracle's Brio. I have to access 6 different databases to grab the same type of data, aggregate it and display it. Except that when I do it, Brio grabs the data from the first source just fine. When I grab the data from the second data source, Brio replaces the original data with the second set. So I am not able to aggregate the data. Can anyone help me figure out how I can do this in Brio please?</p>
| [
{
"answer_id": 332979,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": -1,
"selected": false,
"text": "static bool IsSubSet<A>(A[] set, A[] toCheck) {\n return set.Length == (toCheck.Intersect(set)).Count();\n}\n"
},
{
"answer_id": 333003,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "HashSet<double> t1 = new HashSet<double>{1,3,5};\nHashSet<double> t2 = new HashSet<double>{1,5};\n\nbool isSubset = t2.IsSubsetOf(t1);\n"
},
{
"answer_id": 333034,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 9,
"selected": true,
"text": "bool isSubset = !t2.Except(t1).Any();\n"
},
{
"answer_id": 9435708,
"author": "Neil",
"author_id": 148593,
"author_profile": "https://Stackoverflow.com/users/148593",
"pm_score": 3,
"selected": false,
"text": "public static bool IsSubsetOf<T>(this IEnumerable<T> a, IEnumerable<T> b)\n{\n return !a.Except(b).Any();\n}\n bool isSubset = t2.IsSubsetOf(t1);\n"
},
{
"answer_id": 25526211,
"author": "Géza",
"author_id": 999089,
"author_profile": "https://Stackoverflow.com/users/999089",
"pm_score": 4,
"selected": false,
"text": "CollectionAssert.IsSubsetOf(subset, superset);\n CollectionAssert.IsSubsetOf(t2, t1);\n"
},
{
"answer_id": 26697119,
"author": "user2325458",
"author_id": 2325458,
"author_profile": "https://Stackoverflow.com/users/2325458",
"pm_score": 4,
"selected": false,
"text": "bool isSubset = t2.All(elem => t1.Contains(elem));\n bool isSubset = true;\nforeach (var element in t2) {\n if (!t1.Contains(element)) {\n isSubset = false;\n break;\n }\n}\n"
},
{
"answer_id": 46885122,
"author": "sclarke81",
"author_id": 1326370,
"author_profile": "https://Stackoverflow.com/users/1326370",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Determines whether a sequence contains the specified elements by using the default equality comparer.\n/// </summary>\n/// <typeparam name=\"TSource\">The type of the elements of source.</typeparam>\n/// <param name=\"source\">A sequence in which to locate the values.</param>\n/// <param name=\"values\">The values to locate in the sequence.</param>\n/// <returns>true if the source sequence contains elements that have the specified values; otherwise, false.</returns>\npublic static bool ContainsAll<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> values)\n{\n return !values.Except(source).Any();\n}\n"
},
{
"answer_id": 50732843,
"author": "Lucifer",
"author_id": 6947385,
"author_profile": "https://Stackoverflow.com/users/6947385",
"pm_score": -1,
"selected": false,
"text": "t2 t1 bool isSubset = !(t2.Any(x => !t1.Contains(x)));\n"
},
{
"answer_id": 64401273,
"author": "zetroot",
"author_id": 6098419,
"author_profile": "https://Stackoverflow.com/users/6098419",
"pm_score": 3,
"selected": false,
"text": "!t2.Except(t1).Any() t2.IsSubsetOf(t1) t2.All(elem => t1.Contains(elem)) [0; Variability) [0; Variability) ToHashSet() prebuilt HashSet All(=>Contains) | Method | SupersetsInIteration | SubsetLength | Variability | Mean | Error | StdDev | Median |\n|------------------- |--------------------- |------------- |------------ |--------------:|-------------:|-------------:|--------------:|\n| Except().Any() | 1000 | 10 | 100 | 1,485.89 μs | 7.363 μs | 6.887 μs | 1,488.36 μs |\n| ToHashSet() | 1000 | 10 | 100 | 1,015.59 μs | 5.099 μs | 4.770 μs | 1,015.43 μs |\n| prebuilt HashSet | 1000 | 10 | 100 | 38.76 μs | 0.065 μs | 0.054 μs | 38.78 μs |\n| All(=>Contains) | 1000 | 10 | 100 | 105.46 μs | 0.320 μs | 0.267 μs | 105.38 μs |\n| Except().Any() | 1000 | 10 | 10000 | 1,912.17 μs | 38.180 μs | 87.725 μs | 1,890.72 μs |\n| ToHashSet() | 1000 | 10 | 10000 | 1,038.70 μs | 20.028 μs | 40.459 μs | 1,019.35 μs |\n| prebuilt HashSet | 1000 | 10 | 10000 | 28.22 μs | 0.165 μs | 0.155 μs | 28.24 μs |\n| All(=>Contains) | 1000 | 10 | 10000 | 81.47 μs | 0.117 μs | 0.109 μs | 81.45 μs |\n| Except().Any() | 1000 | 50 | 100 | 4,888.22 μs | 81.268 μs | 76.019 μs | 4,854.42 μs |\n| ToHashSet() | 1000 | 50 | 100 | 4,323.23 μs | 21.424 μs | 18.992 μs | 4,315.16 μs |\n| prebuilt HashSet | 1000 | 50 | 100 | 186.53 μs | 1.257 μs | 1.176 μs | 186.35 μs |\n| All(=>Contains) | 1000 | 50 | 100 | 1,173.37 μs | 2.667 μs | 2.227 μs | 1,173.08 μs |\n| Except().Any() | 1000 | 50 | 10000 | 7,148.22 μs | 20.545 μs | 19.218 μs | 7,138.22 μs |\n| ToHashSet() | 1000 | 50 | 10000 | 4,576.69 μs | 20.955 μs | 17.499 μs | 4,574.34 μs |\n| prebuilt HashSet | 1000 | 50 | 10000 | 33.87 μs | 0.160 μs | 0.142 μs | 33.85 μs |\n| All(=>Contains) | 1000 | 50 | 10000 | 131.34 μs | 0.569 μs | 0.475 μs | 131.24 μs |\n| Except().Any() | 10000 | 10 | 100 | 14,798.42 μs | 120.423 μs | 112.643 μs | 14,775.43 μs |\n| ToHashSet() | 10000 | 10 | 100 | 10,263.52 μs | 64.082 μs | 59.942 μs | 10,265.58 μs |\n| prebuilt HashSet | 10000 | 10 | 100 | 1,241.19 μs | 4.248 μs | 3.973 μs | 1,241.75 μs |\n| All(=>Contains) | 10000 | 10 | 100 | 1,058.41 μs | 6.766 μs | 6.329 μs | 1,059.22 μs |\n| Except().Any() | 10000 | 10 | 10000 | 16,318.65 μs | 97.878 μs | 91.555 μs | 16,310.02 μs |\n| ToHashSet() | 10000 | 10 | 10000 | 10,393.23 μs | 68.236 μs | 63.828 μs | 10,386.27 μs |\n| prebuilt HashSet | 10000 | 10 | 10000 | 1,087.21 μs | 2.812 μs | 2.631 μs | 1,085.89 μs |\n| All(=>Contains) | 10000 | 10 | 10000 | 847.88 μs | 1.536 μs | 1.436 μs | 847.34 μs |\n| Except().Any() | 10000 | 50 | 100 | 48,257.76 μs | 232.573 μs | 181.578 μs | 48,236.31 μs |\n| ToHashSet() | 10000 | 50 | 100 | 43,938.46 μs | 994.200 μs | 2,687.877 μs | 42,877.97 μs |\n| prebuilt HashSet | 10000 | 50 | 100 | 4,634.98 μs | 16.757 μs | 15.675 μs | 4,643.17 μs |\n| All(=>Contains) | 10000 | 50 | 100 | 10,256.62 μs | 26.440 μs | 24.732 μs | 10,243.34 μs |\n| Except().Any() | 10000 | 50 | 10000 | 73,192.15 μs | 479.584 μs | 425.139 μs | 73,077.26 μs |\n| ToHashSet() | 10000 | 50 | 10000 | 45,880.72 μs | 141.497 μs | 125.433 μs | 45,860.50 μs |\n| prebuilt HashSet | 10000 | 50 | 10000 | 1,620.61 μs | 3.507 μs | 3.280 μs | 1,620.52 μs |\n| All(=>Contains) | 10000 | 50 | 10000 | 1,460.01 μs | 1.819 μs | 1.702 μs | 1,459.49 μs |\n| Except().Any() | 100000 | 10 | 100 | 149,047.91 μs | 1,696.388 μs | 1,586.803 μs | 149,063.20 μs |\n| ToHashSet() | 100000 | 10 | 100 | 100,657.74 μs | 150.890 μs | 117.805 μs | 100,654.39 μs |\n| prebuilt HashSet | 100000 | 10 | 100 | 12,753.33 μs | 17.257 μs | 15.298 μs | 12,749.85 μs |\n| All(=>Contains) | 100000 | 10 | 100 | 11,238.79 μs | 54.228 μs | 50.725 μs | 11,247.03 μs |\n| Except().Any() | 100000 | 10 | 10000 | 163,277.55 μs | 1,096.107 μs | 1,025.299 μs | 163,556.98 μs |\n| ToHashSet() | 100000 | 10 | 10000 | 99,927.78 μs | 403.811 μs | 337.201 μs | 99,812.12 μs |\n| prebuilt HashSet | 100000 | 10 | 10000 | 11,671.99 μs | 6.753 μs | 5.986 μs | 11,672.28 μs |\n| All(=>Contains) | 100000 | 10 | 10000 | 8,217.51 μs | 67.959 μs | 56.749 μs | 8,225.85 μs |\n| Except().Any() | 100000 | 50 | 100 | 493,925.76 μs | 2,169.048 μs | 1,922.805 μs | 493,386.70 μs |\n| ToHashSet() | 100000 | 50 | 100 | 432,214.15 μs | 1,261.673 μs | 1,180.169 μs | 431,624.50 μs |\n| prebuilt HashSet | 100000 | 50 | 100 | 49,593.29 μs | 75.300 μs | 66.751 μs | 49,598.45 μs |\n| All(=>Contains) | 100000 | 50 | 100 | 98,662.71 μs | 119.057 μs | 111.366 μs | 98,656.00 μs |\n| Except().Any() | 100000 | 50 | 10000 | 733,526.81 μs | 8,728.516 μs | 8,164.659 μs | 733,455.20 μs |\n| ToHashSet() | 100000 | 50 | 10000 | 460,166.27 μs | 7,227.011 μs | 6,760.150 μs | 457,359.70 μs |\n| prebuilt HashSet | 100000 | 50 | 10000 | 17,443.96 μs | 10.839 μs | 9.608 μs | 17,443.40 μs |\n| All(=>Contains) | 100000 | 50 | 10000 | 14,222.31 μs | 47.090 μs | 44.048 μs | 14,217.94 μs |\n\n"
},
{
"answer_id": 64681752,
"author": "Valdas Zaramba",
"author_id": 2119656,
"author_profile": "https://Stackoverflow.com/users/2119656",
"pm_score": 0,
"selected": false,
"text": "array1 array2 array1 array2 array1.All(ar1 => array2.Any(ar2 => ar2.Equals(ar1)));\n ar2.Equals(ar1)"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
332,988 | <p>By default, IIS6 does not serve .json (no wildcard <code>MIME</code> type).</p>
<p>Therefore a 404 not found is thrown. I then add a new MIME type <code>(.json, text/plain or application/x-javascript or application/json)</code> which works fine.</p>
<p>However, when you then add a new mapping <code>(Home Directory -> Configuration -> Add) with .json, C:\WINDOWS\system32\inetsrv\asp.dll</code>, "<code>GET,POST</code>" and try to browse to the file, you get a 404. </p>
<p>If you remove the mapping and try and <code>POST or GET</code> to it, you get a <code>405</code>.</p>
<p>...</p>
<p>Suggestions?</p>
| [
{
"answer_id": 1121114,
"author": "Evan Anderson",
"author_id": 40764,
"author_profile": "https://Stackoverflow.com/users/40764",
"pm_score": 7,
"selected": false,
"text": "open feature"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
332,992 | <p>I'm working on a site now that have to fetch users feeds. But how can I best optimize fetching if I have a database with, lets say, 300 feeds. I'm going to set up a cron-job to which fetches the feeds, but should I do it like 5 every second minute or something? </p>
<p>Any ideas on how to do this the best way in PHP?</p>
| [
{
"answer_id": 333080,
"author": "puzz",
"author_id": 11148,
"author_profile": "https://Stackoverflow.com/users/11148",
"pm_score": 2,
"selected": false,
"text": " public function updateRefreshInterval() {\n $sql = 'select count(*) _count ' .\n 'from article ' .\n 'where created>adddate(now(), interval -7 day) and feed_id = ' . (int) $this->getId();\n $array = Db::loadArray( $sql );\n\n $count = $array[ '_count' ];\n\n $interval = 7 * 24 * 60 * 60 / ( $count + 1 );\n $interval = $interval / 2;\n if( $interval < self::MIN_REFRESH_INTERVAL ) {\n $interval = self::MIN_REFRESH_INTERVAL;\n }\n if( $interval > self::MAX_REFRESH_INTERVAL ) {\n $interval = self::MAX_REFRESH_INTERVAL;\n }\n\n Db::execute( 'update feed set refresh_interval = ' . $interval . ' where id = ' . (int) $this->getId() );\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38254/"
] |
332,995 | <p>On Windows I can do <code>CreateProcess(..., CREATE_NEW_CONSOLE, ...)</code> and my child process (which is console app, not GUI) will be launched in a new window. What is the easiest way to emulate this on Mac OS?</p>
| [
{
"answer_id": 333167,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 4,
"selected": true,
"text": "open -a Terminal.app $(which program) execve() fork() man open xterm -e program & man xterm"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/332995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
333,029 | <p>I'll phrase this in the form of an example to make it more clear.</p>
<p>Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats?</p>
<pre><code>class Dog: public Animal{/*...*/};
class Cat: public Animal{/*...*/};
int main()
{
vector<Animal*> stuff;
//cramming the dogs and cats in...
for(/*all elements in stuff*/)
//Something to the effect of: if(stuff[i].getClass()==Dog) {/*do something*/}
}
</code></pre>
<p>I hope that's sort of clear. I know about typeid, but I don't really have any Dog object to compare it to and I would like to avoid creating a Dog object if I can.</p>
<p>Is there a way to do this? Thanks in advance.</p>
| [
{
"answer_id": 333036,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 2,
"selected": false,
"text": "dynamic_cast vector <Animal *> stuff;\n\nfor(int i=0;i<stuff.size();i++) {\n Dog *pDog = dynamic_cast <Dog *> (stuff[i]);\n if(pDog) {\n // do whatever with the dog\n }\n\n Cat *pCat = dynamic_cast <Cat *> (stuff[i]);\n if(pCat) {\n // and so on\n }\n}\n Animal Dog Cat dynamic_cast"
},
{
"answer_id": 333045,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 0,
"selected": false,
"text": "typeid if (typeid(stuff[i].getClass())==typeid(Dog))\n Dog dynamic_cast typeid dynamic_cast"
},
{
"answer_id": 333069,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "typeid dynamic_cast Animal* **it Animal& for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {\n if(typeid(**it) == typeid(Dog)) {\n // it's a dog\n } else if(typeid(**it) == typeid(Cat)) {\n // it's a cat\n }\n}\n typeid typeid(*it) typeid(Animal*) dynamic_cast for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {\n if(Dog * dog = dynamic_cast<Dog*>(*it)) {\n // it's a dog (or inherited from it). use the pointer\n } else if(Cat * cat = dynamic_cast<Cat*>(*it)) {\n // it's a cat (or inherited from it). use the pointer. \n }\n}\n"
},
{
"answer_id": 333092,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 1,
"selected": false,
"text": "dynamic_cast typeid for (size_t i = 0; i != v.size(); ++i) {\n if (v[i]->isDog()) { v->cleanupPoop(); }\n}\n isDog() needsPoopCleanup()"
},
{
"answer_id": 333112,
"author": "Alexander Bird",
"author_id": 10608,
"author_profile": "https://Stackoverflow.com/users/10608",
"pm_score": 0,
"selected": false,
"text": "#include<iostream>\n#include<vector>\nusing namespace std;\n\n/////////////\n\nclass Animal {\n public:\n virtual void move() { cout << \"animal just moved\" << endl; }\n};\nclass Dog : public Animal {\n public:\n void move() { cout << \"dog just moved\" << endl; }\n};\nclass Cat : public Animal {\n public:\n void move() { cout << \"cat just moved\" << endl; }\n};\n\nvoid doSomethingWithAnimal(Animal *a) {\n a->move();\n}\n\n/////////////\n\nint main() {\n vector<Animal*> vec;\n vector<Animal*>::iterator it;\n\n Animal *a = new Animal;\n Dog *d = new Dog;\n Cat *c = new Cat;\n\n vec.push_back(a);\n vec.push_back(d);\n vec.push_back(c);\n\n it = vec.begin();\n\n while( it != vec.end() ) {\n doSomethingWithAnimal(*it);\n\n it++;\n }\n\n return 0;\n}\n"
},
{
"answer_id": 333114,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "class Animal {\n /*...*/\npublic:\n virtual std::string type() const { return \"animal\"; }\n};\n\nclass Dog: public Animal{\n /*...*/\npublic:\n virtual std::string type() const { return \"dog\"; }\n};\n\nclass Cat: public Animal{\n /*...*/\npublic:\n virtual std::string type() const { return \"cat\"; }\n};\n if(array[i]->type() == \"dog\") { }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39189/"
] |
333,033 | <p>I was thinking it would be nice to create a base class for NUnit test fixtures that opens a TransactionScope during the SetUp phase, then rolls back the transaction during tear down.
Something like this:</p>
<pre><code> public abstract class TestFixtureBase
{
private TransactionScope _transaction;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
_transaction = new TransactionScope();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
if (_transaction != null)
{
_transaction.Dispose();
}
}
}
</code></pre>
<p>Do you think this is a good idea?</p>
<p>Obviously the database is just a test database, not a live database, but it would still be annoying if it filled up with junk data from the unit tests.</p>
<p>What do other people do when running unit tests that involve a lot of data access?</p>
| [
{
"answer_id": 333048,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "[TestSetup]\npublic void Setup()\n{\n foreach (string table in new string[] { \"table1\", \"table2\" })\n {\n ClearTable( table );\n }\n}\n\nprivate void ClearTable( string table )\n{\n ...standard stuff to set up connection...\n SqlCommand command = connection.CreateCommand() );\n command.CommandText = \"delete from \" + table;\n command.ExecuteNonQuery();\n ... stuff to clean up connection...\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21966/"
] |
333,043 | <p>Can you tell me how can I use threads in C++ programs, and how can I compile it as it will be multithreaded? Can you tell me some good site where I can start from root?</p>
<p>Thanks</p>
| [
{
"answer_id": 333204,
"author": "caglarozdag",
"author_id": 39473,
"author_profile": "https://Stackoverflow.com/users/39473",
"pm_score": 1,
"selected": false,
"text": "void main() \n{\n CThread t1(ChildThread1, ACTIVE, NULL) ; \n . . . \n t1.WaitForThread() ; // if thread already dead, then proceed, otherwise wait\n\n}\n UINT _ _stdcall ChildThread1(void *args) \n{\n\n . . . \n}\n #include “..\\wherever\\it\\is\\rt.h” //notice the windows notation\n\n int ThreadNum[8] = {0,1,2,3,4,5,6,7} ; // an array of thread numbers\n\n\n UINT _ _stdcall ChildThread (void *args) // A thread function \n { \n MyThreadNumber = *(int *)(args); \n\n for ( int i = 0; i < 100; i ++)\n printf( \"I am the Child thread: My thread number is [%d] \\n\", MyThreadNumber) ;\n\n return 0 ;\n }\nint main()\n{\n CThread *Threads[8] ; \n\n// Create 8 instances of the above thread code and let each thread know which number it is.\n\n\n for ( int i = 0; i < 8; i ++) {\n printf (\"Parent Thread: Creating Child Thread %d in Active State\\n\", i) ;\n Threads[i] = new CThread (ChildThread, ACTIVE, &ThreadNum[i]) ;\n }\n\n // wait for threads to terminate, then delete thread objects we created above\n\n for( i = 0; i < 8; i ++) {\n Threads[i]->WaitForThread() ;\n delete Threads[i] ; // delete the object created by ‘new’\n }\n return 0 ;\n}\n"
},
{
"answer_id": 33953558,
"author": "Yogeesh H T",
"author_id": 3725702,
"author_profile": "https://Stackoverflow.com/users/3725702",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n\nusing namespace std;\n\nextern \"C\" \n{\n #include <stdlib.h>\n #include <pthread.h>\n void *print_message_function( void *ptr );\n}\n\n\nint main()\n{\n pthread_t thread1, thread2;\n char *message1 = \"Thread 1\";\n char *message2 = \"Thread 2\";\n int iret1, iret2;\n\n iret1 = pthread_create( &thread1, NULL, print_message_function (void*) message1);\n iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);\n\n pthread_join( thread1, NULL);\n pthread_join( thread2, NULL); \n\n //printf(\"Thread 1 returns: %d\\n\",iret1);\n //printf(\"Thread 2 returns: %d\\n\",iret2);\n cout<<\"Thread 1 returns: %d\\n\"<<iret1;\n cout<<\"Thread 2 returns: %d\\n\"<<iret2;\n\n exit(0);\n}\n\nvoid *print_message_function( void *ptr )\n{\n char *message;\n message = (char *) ptr;\n //printf(\"%s \\n\", message);\n cout<<\"%s\"<<message;\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41522/"
] |
333,056 | <p>I have around 8-9 parameters to pass in a function which returns an array. I would like to know that its better to pass those parameters directly in the function or pass an array instead? Which will be a better way and why?</p>
| [
{
"answer_id": 333061,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 3,
"selected": false,
"text": "Array FireEmployee(string first, string middle, string last, int id) {...}\n Array FireEmployees(Employee[] unionWorkers) {...}\n"
},
{
"answer_id": 333062,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 5,
"selected": true,
"text": "public struct user \n{ \n public string FirstName; \n public string LastName; \n public string zilionotherproperties; \n public bool SearchByLastNameOnly; \n} \npublic user[] GetUserData(user usr) \n{ \n //search for users using passed data and return an array of users. \n} \n"
},
{
"answer_id": 333073,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "FireEmployee(\n first: \"Frank\",\n middle: \"\",\n last: \"Krueger\",\n id: 338);\n"
},
{
"answer_id": 333358,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 2,
"selected": false,
"text": "struct user \n{ \npublic user(string Username, string LastName) \n{ \n _username = Username; \n} \nprivate string _username; \npublic string UserName { \n get { return _username; } \n} \n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29515/"
] |
333,072 | <h2>Backstory</h2>
<p>I'm on Rails 2.1 and need to freeze the Capistrano gem to my vendor folder (as my host has broken their cap gem dependencies and I want to make myself as independent as possible).</p>
<p>On my local windows machine I've put the following my environment.rb</p>
<pre><code>config.gem "capistrano", :version => "2.5.2"
config.gem "net-ssh", :lib => "net/ssh", :version => "2.0.4"
config.gem "net-scp", :lib => "net/scp", :version => "1.0.1"
config.gem "net-sftp", :lib => "net/sftp", :version => "2.0.1"
config.gem "net-ssh-gateway", :lib => "net/ssh/gateway", :version => "1.0.0"
</code></pre>
<p>The gems were already installed and so I froze them. Checking ...</p>
<pre><code>>rake gems
...
[F] capistrano = 2.5.2
[F] net-ssh = 2.0.4
[F] net-scp = 1.0.1
[F] net-sftp = 2.0.1
[F]net-ssh-gateway = 1.0.0
</code></pre>
<p>I then commit to SVN locally and update on the prod Linux box.</p>
<h2>Problem</h2>
<p>When I try and run my frozen version of Capistrano I get the following error.</p>
<pre><code>$ ./vendor/gems/capistrano-2.5.2/bin/cap deploy-with-migrations
./vendor/gems/capistrano-2.5.2/bin/cap:3:in `require': no such file to load --capistrano/cli (LoadError)
from ./vendor/gems/capistrano-2.5.2/bin/cap:3
</code></pre>
<p>Any ideas what I've done wrong?</p>
<h2>Update</h2>
<p><a href="https://stackoverflow.com/questions/339613/how-do-i-use-frozen-capistrano-part-2">See new related question</a></p>
| [
{
"answer_id": 333279,
"author": "Gordon Wilson",
"author_id": 23071,
"author_profile": "https://Stackoverflow.com/users/23071",
"pm_score": 3,
"selected": true,
"text": "cap capistrano/bin/cap cap /usr/bin/cap rubygems capistrano/bin/cap require 'rubygems' #!/usr/bin/env ruby\nrequire 'rubygems'\nrequire 'capistrano/cli'\nCapistrano::CLI.execute\n capistrano/bin/cap $ ruby -r rubygems ./vendor/gems/capistrano-2.5.2/bin/cap deploy-with-migrations\n"
},
{
"answer_id": 642292,
"author": "nitecoder",
"author_id": 60145,
"author_profile": "https://Stackoverflow.com/users/60145",
"pm_score": 1,
"selected": false,
"text": "alias cap1='cap _1.4.2_ '\n cap1 deploy\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16779/"
] |
333,086 | <p>I have a page which work like a navigation and a iframe in this page which show the content. </p>
<p>Now there are some situation when the inner page is directly shown in the browser.
eg: if somebody types the inner page's url in the browser address bar, the page is displayed in the window. </p>
<p>I want to prevent this. </p>
<p>Better still, I would like to redirect to any other page.</p>
| [
{
"answer_id": 333115,
"author": "Ape-inago",
"author_id": 42082,
"author_profile": "https://Stackoverflow.com/users/42082",
"pm_score": 2,
"selected": false,
"text": "<script language=\"Javascript\"><!-- \nif (top.location == self.location) { \n top.location = \"index.html\" // must be viewed in main index\n}\n//--></script>\n"
},
{
"answer_id": 333277,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 3,
"selected": true,
"text": "if (window.top == window.self) {\n window.location = \"index.html\";\n}\n if (window.top == window) {\n window.location = \"index.html\";\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41968/"
] |
333,089 | <p>I have a goal to build an application with UI that would run on both Windows Mobile and "normal" desktop Windows. The priority is for it to "look good" under Windows Mobile, and for desktop Windows it is OK if it distorted. Before I invest days trying, I would like to hear if that is possible to begin with. There are several parts to this question:</p>
<ol>
<li><p>Is .NET Compact Framework a subset of "normal" (please, edit) .NET Framework? If not, does MSDN have any information anywhere on classes that are in .NET Compact Framework, but not in "normal" (again, please, edit) framework?</p></li>
<li><p>Is behavior of shared classes same in both frameworks?</p></li>
<li><p>Is it possible to have a single Visual Studio 2005 solution / project for both platforms? If yes, how do to set it up?</p></li>
<li><p>Any other comments and advice? Any relevant links?</p></li>
</ol>
| [
{
"answer_id": 333101,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<ItemGroup>\n <Compile Include=\"..\\protobuf-net\\**\\*.cs\" />\n</ItemGroup>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2877/"
] |
333,130 | <p>So I have a client who's current host does not allow me to use tar via exec()/passthru()/ect and I need to backup the site periodicly and programmaticly so is there a solution?</p>
<p>This is a linux server.</p>
| [
{
"answer_id": 333140,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 4,
"selected": true,
"text": "<?php\nrequire 'Archive/Tar.php';\n$obj = new Archive_Tar('archive.tar');\n$path = '/path/to/folder/';\n$handle=opendir($path); \n$files = array();\nwhile(false!==($file = readdir($handle)))\n {\n $files[] = $path . $file;\n }\n\nif ($obj->create($files))\n {\n //Sucess\n }\nelse\n {\n //Fail\n }\n?>\n"
},
{
"answer_id": 6601911,
"author": "naitsirch",
"author_id": 832247,
"author_profile": "https://Stackoverflow.com/users/832247",
"pm_score": 4,
"selected": false,
"text": "<?php\n$phar = new PharData('project.tar');\n// add all files in the project\n$phar->buildFromDirectory(dirname(__FILE__) . '/project');\n?>\n"
},
{
"answer_id": 16156508,
"author": "Paweł Bulwan",
"author_id": 889779,
"author_profile": "https://Stackoverflow.com/users/889779",
"pm_score": 0,
"selected": false,
"text": "// Compress all files in current directory and return via HTTP as a ZIP file\n// by buli, 2013 (http://buli.waw.pl)\n// requires TbsZip library from http://www.tinybutstrong.com\n\ninclude_once('tbszip.php'); // load the TbsZip library\n$zip = new clsTbsZip(); // instantiate the class\n$zip->CreateNew(); // create a virtual new zip archive\n\n// iterate through files, skipping directories\n$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));\nforeach($objects as $name => $object)\n{ \n $n = str_replace(\"/\", \"\\\\\", substr($name, 2)); // path format\n $zip->FileAdd($n, $n, TBSZIP_FILE); // add fileto zip archive\n}\n\n$archiveName = \"backup_\".date('m-d-Y H:i:s').\".zip\"; // name of the returned file \n$zip->Flush(TBSZIP_DOWNLOAD, $archiveName); // flush the result as an HTTP download\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
333,141 | <p>I have a master page with a search box and button at the top. This search functionality is taking over the "enter" key for all my web forms that use this master page. That is, if I have a login page that uses this master page and the user enters in their username/password and hits "enter", instead of logging in the user the system performs a search.</p>
<p>What's the best way to set up the default submit buttons. I could wrap everything in asp Panels and set the DefaultButton property, but that seems a bit tedious. Is there a better way?</p>
| [
{
"answer_id": 333172,
"author": "Ramesh Soni",
"author_id": 191,
"author_profile": "https://Stackoverflow.com/users/191",
"pm_score": 2,
"selected": false,
"text": "<form defaultbutton=“button1” runat=“server”> \n <asp:button id=“button1” text=“Same Page” runat=“server”/> \n <asp:panel defaultbutton=“button2” runat=“server”> \n <asp:textbox id=“foo” runat=“server”/> \n <asp:button id=“button2” runat=“server”/> \n </asp:panel> \n</form>\n"
},
{
"answer_id": 333522,
"author": "Steve Davies",
"author_id": 24209,
"author_profile": "https://Stackoverflow.com/users/24209",
"pm_score": 0,
"selected": false,
"text": "<iframe>"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
333,146 | <p>I would like to know how to setup an SVN repository with LDAP authentication.
I do not want to use Apache DAV though.</p>
| [
{
"answer_id": 5899198,
"author": "Mark",
"author_id": 740094,
"author_profile": "https://Stackoverflow.com/users/740094",
"pm_score": 3,
"selected": false,
"text": "/opt/CollabNet_Subversion/bin/Configure-CollabNet-Subversion repo/conf/svnserve.conf [sasl]\nuse-sasl=true\n /opt/CollabNet_Subversion/etc/saslauthd.conf ldap_servers: ldaps://...\nldap_search_base: ...\nldap_bind_dn: ...\nldap_bind_pw: ...\nldap_auth_method: bind\nldap_timeout: 10\n /etc/opt/CollabNet_Subversion/sasl2/svn.conf pwcheck_method: saslauthd\nauxprop_plugin: ldap\nmech_list: PLAIN LOGIN\nldapdb_mech: PLAIN LOGIN\n /etc/openldap/ldap.conf /etc/opt/CollabNet_Subversion/conf/openldap TLS_REQCERT allow mkdir -p /var/state/saslauthd /etc/init.d/collabnet_subversion /opt/CollabNet_Subversion/sbin/saslauthd -a ldap start() stop/start /etc/init.d/collabnet_subverison /opt/CollabNet_Subversion/sbin/testsaslauthd -u <userid> -p <password> svn://"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35392/"
] |
333,151 | <p>You can do it in .NET by using the keyword "ref". Is there any way to do so in Java?</p>
| [
{
"answer_id": 333166,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 3,
"selected": false,
"text": "class Counter\n{\n private int m_count = 0;\n public override string ToString()\n {\n return String.Format(\"Counter ID{0} : Value {1}\", this.GetHashCode(), m_count);\n }\n public void Increment()\n { m_count++; }\n}\nclass MakeAPass\n{\n public void PassByValueAndModify(int i)\n { i = 20; }\n\n public void PassByRefAndModify(ref int i)\n { i = 20; }\n\n public void PassByValueAndModify(Counter c)\n { c.Increment(); }\n\n public void PassByRefAndModify(ref Counter c)\n { c.Increment(); }\n\n public void PassByRefAndReassign(ref Counter c)\n {\n c = new Counter();\n for (int i=0; i<5; ++i)\n c.Increment();\n }\n}\n\nstatic void Main(string[] args)\n{\n MakeAPass obj = new MakeAPass();\n int intVal = 10;\n obj.PassByValueAndModify(intVal);\n Console.WriteLine(intVal); // => 10\n obj.PassByRefAndModify(ref intVal);\n Console.WriteLine(intVal); // => 20\n\n Counter obCounter = new Counter();\n obj.PassByValueAndModify(obCounter);\n Console.WriteLine(obCounter.ToString()); // => Counter ID58225482 : Value 1\n obj.PassByRefAndModify(ref obCounter);\n Console.WriteLine(obCounter.ToString()); // => Counter ID58225482 : Value 2\n obj.PassByRefAndReassign(ref obCounter);\n Console.WriteLine(obCounter.ToString()); // => Counter ID54267293 : Value 5\n}\n class MakeAPass\n{\n public void PassByValueAndModify(int i)\n { i = 20; }\n\n // can't be done.. Use Integer class which wraps primitive\n //public void PassByRefAndModify(ref int i)\n\n public void PassByValueAndModify(Counter c)\n { c.Increment(); }\n\n // same as above. no ref keyword though\n //public void PassByRefAndModify(ref Counter c)\n\n // this can't be done as in .net\n //public void PassByRefAndReassign(ref Counter c)\n public void PassAndReassign(Counter c)\n {\n c = new Counter();\n for (int i=0; i<5; ++i)\n c.Increment();\n }\n}\npublic static void main(String args[])\n{\n MakeAPass obj = new MakeAPass();\n int intVal = 10;\n obj.PassByValueAndModify(intVal);\n System.out.println(intVal); // => 10 \n //obj.PassByRefAndModify(ref intVal);\n //System.out.println(intVal); // can't get it to say 20\n\n Counter obCounter = new Counter();\n obj.PassByValueAndModify(obCounter);\n System.out.println(obCounter.ToString()); // => Counter ID3541984 : Value 1\n //obj.PassByRefAndModify(ref obCounter);\n //Console.WriteLine(obCounter.ToString()); // no ref. but can make it 2 by repeating prev call\n obj.PassAndReassign(obCounter);\n System.out.println(obCounter.ToString()); // => Counter ID3541984 : Value 1\n // can't get it to say 5 \n}\n"
},
{
"answer_id": 333174,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 4,
"selected": false,
"text": "byte[] new byte[length] public class PassByValue\n{\n public static void modifyArray(byte[] array)\n {\n System.out.println(\"Method Entry: Length: \" + array.length);\n array = new byte[16];\n System.out.println(\"Method Exit: Length: \" + array.length);\n }\n\n public static void main(String[] args)\n {\n byte[] array = new byte[8];\n System.out.println(\"Before Method: Length: \" + array.length);\n modifyArray(array);\n System.out.println(\"After Method: Length: \" + array.length);\n }\n}\n byte 8 main modifyArray byte 16 byte modifyArray byte main 16 Before Method: Length: 8\nMethod Entry: Length: 8\nMethod Exit: Length: 16\nAfter Method: Length: 8\n byte modifyArray 8 16 main modifyArray new byte[8] modifyArray new byte[16] modifyArray new byte[16] main new byte[8]"
},
{
"answer_id": 333217,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "public void doSomething(byte[] data)\n{\n for (int i=0; i < data.length; i++)\n {\n data[i] = (byte) i;\n }\n}\n public void createArray(byte[] data, int length)\n{\n // Eek! Change to parameter won't get seen by caller\n data = new byte[length]; \n for (int i=0; i < data.length; i++)\n {\n data[i] = (byte) i;\n }\n}\n public byte[] createArray(int length)\n{\n byte[] data = new byte[length]; \n for (int i=0; i < data.length; i++)\n {\n data[i] = (byte) i;\n }\n return data;\n}\n public class Holder<T>\n{\n public T value; // Use a property in real code!\n}\n\npublic void createArray(Holder<byte[]> holder, int length)\n{\n holder.value = new byte[length]; \n for (int i=0; i < length; i++)\n {\n holder.value[i] = (byte) i;\n }\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36816/"
] |
333,159 | <p>I have a solution of mixed VB.NET and C++ projects. When using Visual Studio 2005 you can set the "Tools->Option->Projects and Solutions->VC++ Directories" to help the compiler find your include files. When building the same solution with MSBuild I don't see how to pass these settings. The C++ won't compile without this path specified. When building this solution form Visual Studio it build perfectly.</p>
<p>What is the way to pass this path for MSBUild?</p>
<p>Edit: Looks like MSBuild doesn't pass the path (or the /u switch) to vcbuild. Starting from VCBuild instead fails on dependency.</p>
| [
{
"answer_id": 333195,
"author": "Paulius",
"author_id": 1353085,
"author_profile": "https://Stackoverflow.com/users/1353085",
"pm_score": 5,
"selected": true,
"text": "set INCLUDE=C:\\Libraries\\LibA\\Include\nset LIB=C:\\Libraries\\LibA\\Lib\\x86\n"
},
{
"answer_id": 4193355,
"author": "Gene Mayevsky",
"author_id": 509396,
"author_profile": "https://Stackoverflow.com/users/509396",
"pm_score": 3,
"selected": false,
"text": "set INCLUDE=C:\\Libraries\\LibA\\Include;%INCLUDE%\nset LIB=C:\\Libraries\\LibA\\Lib\\x86;%LIB%\n"
},
{
"answer_id": 20263549,
"author": "Sapien2",
"author_id": 542430,
"author_profile": "https://Stackoverflow.com/users/542430",
"pm_score": 3,
"selected": false,
"text": "/p[roperty]:useenv=true"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1363/"
] |
333,163 | <p>I get this error:</p>
<p>System.Reflection.TargetException: Object does not match target type.</p>
<p>when trying to bind a <code>List<IEvent></code> where an IEvent can be an appointment, a birthday, or a few other calendar related event types.</p>
| [
{
"answer_id": 333321,
"author": "Valentin V",
"author_id": 430254,
"author_profile": "https://Stackoverflow.com/users/430254",
"pm_score": 2,
"selected": false,
"text": " public class Event\n {\n public DateTime StartDate { get; set; }\n }\n public class Birthday : Event\n { \n\n public DateTime? EndDate { get; set; }\n } \n public class Appointment : Event\n { \n\n public string Place { get; set; }\n }\n public class EventCollection : Collection<Event>\n {\n public static EventCollection GetEvents()\n {\n var events = new EventCollection();\n events.Add(new Birthday\n {\n EndDate = DateTime.Now.AddDays(1),\n StartDate = DateTime.Now\n });\n events.Add(new Appointment\n {\n Place = \"Gallery\",\n StartDate = DateTime.Now\n });\n return events;\n }\n }\n"
},
{
"answer_id": 1272759,
"author": "Brandon Wood",
"author_id": 423,
"author_profile": "https://Stackoverflow.com/users/423",
"pm_score": 1,
"selected": false,
"text": "TypeDescriptionProvider"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
] |
333,169 | <p>I am using CODBCRecordset (a class found on CodeProject) to find a single record in a table with 39 columns. If no record is found then the call to CRecordset::Open is fine. If a record matches the conditions then I get an Out of Memory exception when CRecordset::Open is called. I am selecting all the columns in the query (if I change the query to select only one of the columns with the same where clause then no exception).</p>
<p>I assume this is because of some limitation in CRecordset, but I can't find anything telling me of any limitations. The table only has 39 columns.</p>
<p>Has anyone run into this problem? And if so, do you have a work around / solution?</p>
<p>This is a MFC project using Visual Studio 6.0 if it makes any difference.</p>
<p>Here's the query (formatted here so wold show up without a scrollbar):<br /></p>
<pre>
SELECT `id`, `member_id`, `member_id_last_four`, `card_number`, `first_name`,
`mi`, `last_name`, `participant_title_id`, `category_id`, `gender`,
`date_of_birth`, `address_line_1`, `address_line_2`, `city`, `state`,
`zip`, `phone`, `work_phone`, `mobile_phone`, `fax`, `email`,
`emergency_name`, `emergency_phone`, `job_title`, `mail_code`,
`comments`, `contract_unit`, `contract_length`, `start_date`,
`end_date`, `head_of_household`, `parent_id`, `added_by`, `im_active`,
`ct_active`, `organization`, `allow_members`, `organization_category_id`,
`modified_date`
FROM `participants`
WHERE `member_id` = '27F7D0982978B470C5CF94B1B833CC93F997EE23'
</pre>
<p>Copying and pasting into my query browser gives me only one result.</p>
<p>More info:</p>
<p>Commented out each column in the select statement except for id. Ran the query and no exception.</p>
<p>Then I systematically went through and uncommented each column, one at a time, and re-ran query in between each uncomment.</p>
<p>When I uncomment the comment column then I get the error.</p>
<p>This is defined as the following (Using MySQL): LONGTEXT</p>
| [
{
"answer_id": 333200,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "CDatabase db;\ndb.Open (NULL,FALSE,FALSE,\"ODBC;\",TRUE);\nCODBCRecordSet rs (&db);\nrs.Open (\"select blah, blah, blah from ...\");\n"
},
{
"answer_id": 333234,
"author": "Tony Fontenot",
"author_id": 42357,
"author_profile": "https://Stackoverflow.com/users/42357",
"pm_score": 2,
"selected": true,
"text": "'<blank>'"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42357/"
] |
333,171 | <p>I would like to be able to show a non-modal form in an already existing application. At the moment I can do something like:</p>
<pre><code>myform.ShowDialog(handleToApp);
</code></pre>
<p>but that will create a modal form parented to the application and what I'm really looking for something that isn't modal so when the form loses focus it won't break the flow of control and pester the user about not being closed.</p>
<p>Does anyone know how or if I can do what I'm looking for?</p>
| [
{
"answer_id": 333210,
"author": "Rad",
"author_id": 1349,
"author_profile": "https://Stackoverflow.com/users/1349",
"pm_score": -1,
"selected": false,
"text": "myForm.Show()"
},
{
"answer_id": 339689,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 3,
"selected": true,
"text": "public class MapinfoWindowHandle : System.Windows.Forms.IWin32Window\n {\n private IntPtr handle;\n public MapinfoWindowHandle(IntPtr hWnd)\n {\n handle = hWnd;\n }\n\n #region IWin32Window Members\n\n IntPtr System.Windows.Forms.IWin32Window.Handle\n {\n get { return handle; }\n }\n\n #endregion\n }\n IntPtr windowhandle = new IntPtr(hWnd);\nMyForm.Show(new MapinfoWindowHandle(windowhandle));\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
333,175 | <p>My program will take arbitrary strings from the internet and use them for file names. Is there a simple way to remove the bad characters from these strings or do I need to write a custom function for this?</p>
| [
{
"answer_id": 333268,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 9,
"selected": true,
"text": "foreach (var c in Path.GetInvalidFileNameChars()) \n{ \n fileName = fileName.Replace(c, '-'); \n}\n 'Clean just a filename\nDim filename As String = \"salmnas dlajhdla kjha;dmas'lkasn\"\nFor Each c In IO.Path.GetInvalidFileNameChars\n filename = filename.Replace(c, \"\")\nNext\n\n'See also IO.Path.GetInvalidPathChars\n"
},
{
"answer_id": 333297,
"author": "Aaron Wagner",
"author_id": 3909,
"author_profile": "https://Stackoverflow.com/users/3909",
"pm_score": 5,
"selected": false,
"text": "Path.GetInvalidFileNameChars() string file = @\"38?/.\\}[+=n a882 a.a*/|n^%$ ad#(-))\";\nArray.ForEach(Path.GetInvalidFileNameChars(), \n c => file = file.Replace(c.ToString(), String.Empty));\n"
},
{
"answer_id": 918973,
"author": "Keith",
"author_id": 36146,
"author_profile": "https://Stackoverflow.com/users/36146",
"pm_score": 3,
"selected": false,
"text": "string myCrazyName = \"q`w^e!r@t#y$u%i^o&p*a(s)d_f-g+h=j{k}l|z:x\\\"c<v>b?n[m]q\\\\w;e'r,t.y/u\";\nstring safeName = Regex.Replace(\n myCrazyName,\n \"\\W\", /*Matches any nonword character. Equivalent to '[^A-Za-z0-9_]'*/\n \"\",\n RegexOptions.IgnoreCase);\n// safeName == \"qwertyuiopasd_fghjklzxcvbnmqwertyu\"\n"
},
{
"answer_id": 3426334,
"author": "sidewinderguy",
"author_id": 214974,
"author_profile": "https://Stackoverflow.com/users/214974",
"pm_score": 4,
"selected": false,
"text": "public static string MakeSafeFilename(string filename, char replaceChar)\n{\n foreach (char c in System.IO.Path.GetInvalidFileNameChars())\n {\n filename = filename.Replace(c, replaceChar);\n }\n return filename;\n}\n"
},
{
"answer_id": 3678296,
"author": "Squirrel",
"author_id": 11835,
"author_profile": "https://Stackoverflow.com/users/11835",
"pm_score": 6,
"selected": false,
"text": "static readonly char[] invalidFileNameChars = Path.GetInvalidFileNameChars();\n\n// Builds a string out of valid chars\nvar validFilename = new string(filename.Where(ch => !invalidFileNameChars.Contains(ch)).ToArray());\n static readonly char[] invalidFileNameChars = Path.GetInvalidFileNameChars();\n\n// Builds a string out of valid chars and an _ for invalid ones\nvar validFilename = new string(filename.Select(ch => invalidFileNameChars.Contains(ch) ? '_' : ch).ToArray());\n static readonly IList<char> invalidFileNameChars = Path.GetInvalidFileNameChars();\n\n// Builds a string out of valid chars and replaces invalid chars with a unique letter (Moves the Char into the letter range of unicode, starting at \"A\")\nvar validFilename = new string(filename.Select(ch => invalidFileNameChars.Contains(ch) ? Convert.ToChar(invalidFileNameChars.IndexOf(ch) + 65) : ch).ToArray());\n"
},
{
"answer_id": 3678506,
"author": "Dour High Arch",
"author_id": 22437,
"author_profile": "https://Stackoverflow.com/users/22437",
"pm_score": 5,
"selected": false,
"text": "IO.Path.GetInvalidFileNameChars"
},
{
"answer_id": 15909702,
"author": "cjbarth",
"author_id": 271351,
"author_profile": "https://Stackoverflow.com/users/271351",
"pm_score": 1,
"selected": false,
"text": "<Extension()>\nPublic Function MakeSafeFileName(FileName As String) As String\n Return FileName.Where(Function(x) Not IO.Path.GetInvalidFileNameChars.Contains(x)).ToArray\nEnd Function\n string IEnumerable char string char"
},
{
"answer_id": 16083025,
"author": "Ronnie Overby",
"author_id": 64334,
"author_profile": "https://Stackoverflow.com/users/64334",
"pm_score": 3,
"selected": false,
"text": "static class Utils\n{\n public static string MakeFileSystemSafe(this string s)\n {\n return new string(s.Where(IsFileSystemSafe).ToArray());\n }\n\n public static bool IsFileSystemSafe(char c)\n {\n return !Path.GetInvalidFileNameChars().Contains(c);\n }\n}\n"
},
{
"answer_id": 17623014,
"author": "George Birbilis",
"author_id": 903783,
"author_profile": "https://Stackoverflow.com/users/903783",
"pm_score": 3,
"selected": false,
"text": "public static string ReplaceInvalidFileNameChars(this string s, string replacement = \"\")\n{\n return Regex.Replace(s,\n \"[\" + Regex.Escape(new String(System.IO.Path.GetInvalidPathChars())) + \"]\",\n replacement, //can even use a replacement string of any length\n RegexOptions.IgnoreCase);\n //not using System.IO.Path.InvalidPathChars (deprecated insecure API)\n}\n"
},
{
"answer_id": 18917438,
"author": "csells",
"author_id": 185286,
"author_profile": "https://Stackoverflow.com/users/185286",
"pm_score": 4,
"selected": false,
"text": "static string GetSafeFileName(string name, char replace = '_') {\n char[] invalids = Path.GetInvalidFileNameChars();\n return new string(name.Select(c => invalids.Contains(c) ? replace : c).ToArray());\n}\n"
},
{
"answer_id": 35512238,
"author": "ecklerpa",
"author_id": 390894,
"author_profile": "https://Stackoverflow.com/users/390894",
"pm_score": 2,
"selected": false,
"text": "private void textBoxFileName_KeyPress(object sender, KeyPressEventArgs e)\n{\n e.Handled = CheckFileNameSafeCharacters(e);\n}\n\n/// <summary>\n/// This is a good function for making sure that a user who is naming a file uses proper characters\n/// </summary>\n/// <param name=\"e\"></param>\n/// <returns></returns>\ninternal static bool CheckFileNameSafeCharacters(System.Windows.Forms.KeyPressEventArgs e)\n{\n if (e.KeyChar.Equals(24) || \n e.KeyChar.Equals(3) || \n e.KeyChar.Equals(22) || \n e.KeyChar.Equals(26) || \n e.KeyChar.Equals(25))//Control-X, C, V, Z and Y\n return false;\n if (e.KeyChar.Equals('\\b'))//backspace\n return false;\n\n char[] charArray = Path.GetInvalidFileNameChars();\n if (charArray.Contains(e.KeyChar))\n return true;//Stop the character from being entered into the control since it is non-numerical\n else\n return false; \n}\n"
},
{
"answer_id": 43671130,
"author": "Bart Vanseer",
"author_id": 4906499,
"author_profile": "https://Stackoverflow.com/users/4906499",
"pm_score": 3,
"selected": false,
"text": "string UnsafeFileName = \"salmnas dlajhdla kjha;dmas'lkasn\";\nstring SafeFileName = Convert.ToBase64String(Encoding.UTF8.GetBytes(UnsafeFileName));\n UnsafeFileName = Encoding.UTF8.GetString(Convert.FromBase64String(SafeFileName));\n"
},
{
"answer_id": 54148994,
"author": "AnonBird",
"author_id": 4394139,
"author_profile": "https://Stackoverflow.com/users/4394139",
"pm_score": 1,
"selected": false,
"text": "Path.GetInvalidFileNameChars() string whitelist = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.\";\n foreach (char c in filename)\n {\n if (!whitelist.Contains(c))\n {\n filename = filename.Replace(c, '-');\n }\n }\n"
},
{
"answer_id": 57893864,
"author": "Roni Tovi",
"author_id": 3344975,
"author_profile": "https://Stackoverflow.com/users/3344975",
"pm_score": 2,
"selected": false,
"text": " public string GetSafeFilename(string filename)\n {\n string res = string.Join(\"!\", filename.Split(Path.GetInvalidFileNameChars()));\n\n while (res.IndexOf(\"!!\") >= 0)\n res = res.Replace(\"!!\", \"!\");\n\n return res;\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13877/"
] |
333,181 | <p>I have 3 tables in database shown below. And I want to make a report just like shown link below. How can I do it with datagrid or datalist? Which one is the best chois? I have tried to do it for a week. </p>
<p><img src="https://i.stack.imgur.com/uZtmk.jpg" alt="http://img123.imageshack.us/my.php?image=61519307xx5.jpg"></p>
<blockquote>
<p><strong>COMPANY</strong>: ID_COMPANY, COMPANY_NAME</p>
<p><strong>PRODUCT</strong>: ID_PRODUCT, PRODUCT_NAME</p>
<p><strong>PRODUCT_SALE</strong>: ID_COMPANY, ID_PRODUCT, SALE_COUNT</p>
</blockquote>
<p><strong>Updated</strong> :</p>
<p>I could do it, with your helps. However Now I have a small problem too.</p>
<p>When I write query with pivot, products' name become column header. if a product name's length is bigger than 30 character, Oracle don't accept it as a column header. So I have croped and make the product names 30 character to solve this problem. After that a problem occured too.</p>
<p>When I crop product name as 30 character, some products become same name and "ORA-00918: column ambiguously defined" error message occured.</p>
<p>In this case what can be done?</p>
| [
{
"answer_id": 333203,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 2,
"selected": false,
"text": "http://www.tsqltutorials.com/pivot.php\n"
},
{
"answer_id": 333208,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 1,
"selected": false,
"text": "<asp:gridview>\n <columns>\n <asp:boundfield datafield=\"companyname\" itemstyle-headertext=\"\" />\n <asp:boundfield datafield=\"SALE_COUNT\" itemstyle-headertext='<%# FunctionToLoadurproduct(product1) %>' />\n <asp:boundfield datafield=\"SALE_COUNT\" itemstyle-headertext='<%# FunctionToLoadurproduct(product1) %>' />\n\n and so on...\n </columns>\n</gridview >\n"
},
{
"answer_id": 336334,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "''' <summary>\n''' Pivots columnX as new columns for the X axis (must be unique values) and the remaining columns as \n''' the Y axis. Optionally can include columns to exclude from the Y axis.\n''' </summary>\n''' <param name=\"dt\"></param>\n''' <param name=\"columnX\"></param>\n''' <param name=\"columnsToIgnore\"></param>\n''' <returns>DataTable</returns>\n''' <remarks></remarks>\nPublic Shared Function Pivot(ByVal dt As DataTable, ByVal columnX As String, ByVal ParamArray columnsToIgnore As String()) As DataTable\n\n Dim dt2 As New DataTable()\n\n If columnX = \"\" Then\n columnX = dt.Columns(0).ColumnName\n End If\n\n 'Add a Column at the beginning of the table \n dt2.Columns.Add(columnX)\n\n 'Read all DISTINCT values from columnX Column in the provided DataTable \n Dim columnXValues As New List(Of String)()\n\n 'Create the list of columns to ignore \n Dim listColumnsToIgnore As New List(Of String)()\n If columnsToIgnore.Length > 0 Then\n listColumnsToIgnore.AddRange(columnsToIgnore)\n End If\n\n If Not listColumnsToIgnore.Contains(columnX) Then\n listColumnsToIgnore.Add(columnX)\n End If\n\n ' Add the X axis columns\n For Each dr As DataRow In dt.Rows\n Dim columnXTemp As String = dr(columnX).ToString()\n If Not columnXValues.Contains(columnXTemp) Then\n columnXValues.Add(columnXTemp)\n dt2.Columns.Add(columnXTemp)\n Else\n Throw New Exception(\"The inversion used must have unique values for column \" + columnX)\n End If\n Next\n\n 'Add a row for each non-columnX of the DataTable \n For Each dc As DataColumn In dt.Columns\n If Not columnXValues.Contains(dc.ColumnName) AndAlso Not listColumnsToIgnore.Contains(dc.ColumnName) Then\n Dim dr As DataRow = dt2.NewRow()\n dr(0) = dc.ColumnName\n dt2.Rows.Add(dr)\n End If\n Next\n\n 'Complete the datatable with the values \n For i As Integer = 0 To dt2.Rows.Count - 1\n For j As Integer = 1 To dt2.Columns.Count - 1\n dt2.Rows(i)(j) = dt.Rows(j - 1)(dt2.Rows(i)(0).ToString()).ToString()\n Next\n Next\n\n Return dt2\n\nEnd Function\n\n''' <summary>\n''' Can pivot any column as X, any column as Y, and any column as Z. Sort on X, sort on Y and optionally, the \n''' values at the intersection of x and y (Z axis) can be summed.\n''' </summary>\n''' <param name=\"dt\"></param>\n''' <param name=\"columnX\"></param>\n''' <param name=\"columnY\"></param>\n''' <param name=\"columnZ\"></param>\n''' <param name=\"nullValue\"></param>\n''' <param name=\"sumValues\"></param>\n''' <param name=\"xSort\"></param>\n''' <param name=\"ySort\"></param>\n''' <returns>DataTable</returns>\n''' <remarks></remarks>\nPublic Shared Function Pivot(ByVal dt As DataTable, ByVal columnX As String, ByVal columnY As String, ByVal columnZ As String, _\n ByVal nullValue As String, ByVal sumValues As Boolean, ByVal xSort As Sort, ByVal ySort As Sort) As DataTable\n\n Dim dt2 As New DataTable()\n Dim tickList As List(Of Long) = Nothing\n\n If columnX = \"\" Then\n columnX = dt.Columns(0).ColumnName\n End If\n\n 'Add a Column at the beginning of the table \n dt2.Columns.Add(columnY)\n\n 'Read all DISTINCT values from columnX Column in the provided DataTable \n Dim columnXValues As New List(Of String)()\n Dim cols As Integer = 0\n\n For Each dr As DataRow In dt.Rows\n If dr(columnX).ToString.Contains(\"'\") Then\n dr(columnX) = dr(columnX).ToString.Replace(\"'\", \"\")\n End If\n If Not columnXValues.Contains(dr(columnX).ToString) Then\n 'Read each row value, if it's different from others provided, \n 'add to the list of values and creates a new Column with its value. \n columnXValues.Add(dr(columnX).ToString)\n End If\n Next\n\n 'Sort X if needed\n If Not xSort = Sort.None Then\n columnXValues = SortValues(columnXValues, xSort)\n End If\n\n 'Add columnX\n For Each s As String In columnXValues\n dt2.Columns.Add(s)\n Next\n\n 'Verify Y and Z Axis columns were provided \n If columnY <> \"\" AndAlso columnZ <> \"\" Then\n 'Read DISTINCT Values for Y Axis Column \n Dim columnYValues As New List(Of String)()\n\n For Each dr As DataRow In dt.Rows\n If dr(columnY).ToString.Contains(\"'\") Then\n dr(columnY) = dr(columnY).ToString.Replace(\"'\", \"\")\n End If\n If Not columnYValues.Contains(dr(columnY).ToString()) Then\n columnYValues.Add(dr(columnY).ToString())\n End If\n Next\n\n ' Now we can sort the Y axis if needed. \n If Not ySort = Sort.None Then\n columnYValues = SortValues(columnYValues, ySort)\n End If\n\n 'Loop all Distinct ColumnY Values\n For Each columnYValue As String In columnYValues\n 'Create a new Row \n Dim drReturn As DataRow = dt2.NewRow()\n drReturn(0) = columnYValue\n Dim rows As DataRow() = dt.[Select](columnY + \"='\" + columnYValue + \"'\")\n\n 'Read each row to fill the DataTable \n For Each dr As DataRow In rows\n Dim rowColumnTitle As String = dr(columnX).ToString()\n\n 'Read each column to fill the DataTable \n For Each dc As DataColumn In dt2.Columns\n If dc.ColumnName = rowColumnTitle Then\n 'If sumValues, try to perform a Sum \n 'If sum is not possible due to value types, use the nullValue string\n If sumValues Then\n If IsNumeric(dr(columnZ).ToString) Then\n drReturn(rowColumnTitle) = Val(drReturn(rowColumnTitle).ToString) + Val(dr(columnZ).ToString)\n Else\n drReturn(rowColumnTitle) = nullValue\n End If\n Else\n drReturn(rowColumnTitle) = dr(columnZ).ToString\n End If\n End If\n Next\n Next\n\n dt2.Rows.Add(drReturn)\n\n Next\n Else\n Throw New Exception(\"The columns to perform inversion are not provided\")\n End If\n\n 'if nullValue param was provided, fill the datable with it \n If nullValue <> \"\" Then\n For Each dr As DataRow In dt2.Rows\n For Each dc As DataColumn In dt2.Columns\n If dr(dc.ColumnName).ToString() = \"\" Then\n dr(dc.ColumnName) = nullValue\n End If\n Next\n Next\n End If\n\n Return dt2\n\nEnd Function\n\n''' <summary>\n''' Sorts a list of strings checking to see if they are numeric or date types.\n''' </summary>\n''' <param name=\"list\"></param>\n''' <param name=\"srt\"></param>\n''' <returns></returns>\n''' <remarks></remarks>\nPrivate Shared Function SortValues(ByVal list As List(Of String), ByVal srt As Sort) As List(Of String)\n\n Dim tickList As List(Of Long) = Nothing\n Dim dblList As List(Of Double) = Nothing\n\n ' Figure out how to sort columnX\n For Each s As String In list\n Dim colDate As Date = Nothing\n If Date.TryParse(s, colDate) Then\n tickList = New List(Of Long)\n Exit For\n End If\n Next\n\n Dim dateTicks As Long\n\n If Not tickList Is Nothing Then\n For Each s As String In list\n dateTicks = DateTime.Parse(s).Ticks\n If Not tickList.Contains(dateTicks) Then\n tickList.Add(dateTicks)\n End If\n Next\n\n If srt = Sort.DESC Then\n tickList.Sort()\n tickList.Reverse()\n ElseIf srt = Sort.ASC Then\n tickList.Sort()\n End If\n\n list.Clear()\n For Each lng As Long In tickList\n list.Add(New Date(lng).ToString(\"G\"))\n Next\n Else\n Dim dbl As Double = Nothing\n\n For Each s As String In list\n If IsNumeric(s) Then\n dblList = New List(Of Double)\n End If\n Next\n\n If Not dblList Is Nothing Then\n 'Doubles or Integers\n For Each s As String In list\n dbl = Val(s)\n If Not dblList.Contains(dbl) Then\n dblList.Add(dbl)\n End If\n Next\n\n If srt = Sort.DESC Then\n dblList.Sort()\n dblList.Reverse()\n ElseIf srt = Sort.ASC Then\n dblList.Sort()\n End If\n\n list.Clear()\n For Each d As Double In dblList\n list.Add(d.ToString)\n Next\n Else\n 'Strings\n If srt = Sort.DESC Then\n list.Sort()\n list.Reverse()\n ElseIf srt = Sort.ASC Then\n list.Sort()\n End If\n End If\n\n End If\n\n Return list\n\nEnd Function\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439507/"
] |
333,185 | <p>I'm trying to figure out if Haskell uses dynamic or static scoping.
I realize that, for example, if you define:</p>
<pre><code>let x = 10
</code></pre>
<p>then define the function</p>
<pre><code>let square x = x*x
</code></pre>
<p>You have 2 different "x's", and does that mean it is dynamically scoped? If not, what scoping does it use, and why?</p>
<p>Also, can Haskell variables have aliases (a different name for the same memory location/value)?</p>
<p>Thanks.</p>
| [
{
"answer_id": 333189,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 4,
"selected": false,
"text": "x = 10\n x square x = x * x\n x square = \\ x -> x * x\n"
},
{
"answer_id": 333219,
"author": "igorgue",
"author_id": 29253,
"author_profile": "https://Stackoverflow.com/users/29253",
"pm_score": 4,
"selected": true,
"text": "import Data.IORef\n\nmain :: IO ()\nmain = do x <- newIORef 0 -- write 0 into x\n readIORef x >>= print -- x contains 0\n let y = x\n readIORef y >>= print -- y contains 0\n writeIORef x 42 -- write 42 into x\n readIORef y >>= print -- y contains 42\n"
},
{
"answer_id": 333624,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "foo x y = x * y\nbar z = foo z z\n foo bar x y x y"
},
{
"answer_id": 334374,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "aliasing one name for another y = x\n y x type Function = Double -> Double\n Function Double -> Double"
},
{
"answer_id": 338325,
"author": "Nathan Shively-Sanders",
"author_id": 7851,
"author_profile": "https://Stackoverflow.com/users/7851",
"pm_score": 1,
"selected": false,
"text": "x = 1; y = x let ghci>"
},
{
"answer_id": 348071,
"author": "Magnus",
"author_id": 34996,
"author_profile": "https://Stackoverflow.com/users/34996",
"pm_score": 0,
"selected": false,
"text": "let x = 10"
},
{
"answer_id": 355552,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 2,
"selected": false,
"text": "evens = 0 : map (+1) odds\nodds = map : (+1) evens\n let x = 2 * n\n x = x + 1 -- watch out!\n"
},
{
"answer_id": 994240,
"author": "cjs",
"author_id": 107294,
"author_profile": "https://Stackoverflow.com/users/107294",
"pm_score": 0,
"selected": false,
"text": "import Data.IORef\n\nmain :: IO ()\nmain = do x <- newIORef 0 -- write 0 into x\n readIORef x >>= print -- x contains 0\n let y = x\n readIORef y >>= print -- y contains 0\n writeIORef x 42 -- write 42 into x\n readIORef y >>= print -- y contains 42\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83819/"
] |
333,221 | <p>Is there a widely accepted class for dealing with URLs in PHP?</p>
<p>Things like: getting/changing parts of an existing URL (e.g. path, scheme, etc), resolving relative paths from a base URL. Kind of like a two-way <a href="http://php.net/parse_url" rel="nofollow noreferrer">parse_url()</a>, encapsulated with a bunch of handy functions.</p>
<p>Does something like this exist?</p>
| [
{
"answer_id": 333223,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "$url =& new URL('http://www.domain.com/path/file.php?query=blah');\necho $url->get_scheme(),\"\\n\"; // http\necho $url->get_host(),\"\\n\"; // www.domain.com\necho $url->get_path(),\"\\n\"; // /path/file.php\necho $url->get_query(),\"\\n\"; // query=blah\n// Setting a relative URL against our existing URL\n$url->set_relative('../great.php');\necho $url->as_string(); // http://www.domain.com/great.php\n"
},
{
"answer_id": 334973,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": -1,
"selected": false,
"text": "Zend_Uri"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
333,242 | <p>I was thinking about making something like Linq for Lua, and I have a general idea how Linq works, but was wondering if there was a good article or if someone could explain how C# makes Linq possible</p>
<p>Note: I mean behind the scenes, like how it generates code bindings and all that, not end user syntax.</p>
| [
{
"answer_id": 333254,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "IEnumerable<T> var"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
333,249 | <p>What is the XPath expression that I would use to get the string following 'HarryPotter:' for each book.</p>
<p>ie. Given this XML:</p>
<pre><code><bookstore>
<book>
HarryPotter:Chamber of Secrets
</book>
<book>
HarryPotter:Prisoners in Azkabahn
</book>
</bookstore>
</code></pre>
<p>I would get back:</p>
<pre><code>Chamber of Secrets
Prisoners in Azkabahn
</code></pre>
<p>I have tried something like this:</p>
<pre><code>/bookstore/book/text()[substring-after(. , 'HarryPotter:')]
</code></pre>
<p>I think my syntax is incorrect...</p>
| [
{
"answer_id": 333265,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 3,
"selected": false,
"text": " Dim xml = <bookstore>\n <book>HarryPotter:Chamber of Secrets</book>\n <book>HarryPotter:Prisoners in Azkabahn</book>\n <book>MyDummyBook:Dummy Title</book>\n </bookstore>\n\n Dim xdoc As New Xml.XmlDocument\n xdoc.LoadXml(xml.ToString)\n\n Dim Nodes = xdoc.SelectNodes(\"/bookstore/book/text()[substring-after(., 'HarryPotter:')]\")\n\n Dim Iter = Nodes.GetEnumerator()\n While Iter.MoveNext\n With DirectCast(Iter.Current, Xml.XmlNode).Value\n Console.WriteLine(.Substring(.IndexOf(\":\") + 1))\n End With\n End While\n"
},
{
"answer_id": 333823,
"author": "Johan L",
"author_id": 40282,
"author_profile": "https://Stackoverflow.com/users/40282",
"pm_score": 2,
"selected": false,
"text": "/bookstore/book/text()[substring-after(. , 'HarryPotter:')]\n"
},
{
"answer_id": 334251,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 6,
"selected": true,
"text": "/*/*/substring-after(., 'HarryPotter:')"
},
{
"answer_id": 28265768,
"author": "Zahra Hnn",
"author_id": 4517109,
"author_profile": "https://Stackoverflow.com/users/4517109",
"pm_score": 0,
"selected": false,
"text": "substring-after(//book, 'HarryPotter:')\n"
},
{
"answer_id": 73337116,
"author": "raghava narasimman",
"author_id": 19748514,
"author_profile": "https://Stackoverflow.com/users/19748514",
"pm_score": 0,
"selected": false,
"text": "//bookstore/book/substring-after(text(),'HarryPotter')\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
333,260 | <p>We have a PageRoles xml file which contains the page path and the user role that can access that page.</p>
<p>We are maintaining a Dictionary in a static class, which gets loaded int static constructor for the class.
The class has a method CheckIfRoleAllowed that takes in a page path and returns a bool.</p>
<p>Each page call the CheckIfRoleAllowed on Page Init.</p>
<pre><code>static class PageAccessChecker
{
static Dictionary<string, UserRoleType[]> _PageAccessPermissions;
static FileSystemWatcher _XmlWatcher;
static PageAccessChecker()
{
// Load page access permissions from xml
// Set FileSystemWatcher watcher to watch for changes
}
public static CheckIfRoleAllowed(string pagePath)
{
}
}
</code></pre>
<p>Would we be better off doing this using the singleton pattern?
If yes, why?</p>
<p>Kind regards.</p>
| [
{
"answer_id": 333263,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 3,
"selected": true,
"text": "PageAccessChecker.CheckIfRoleAllowed(path);\n PageAccessChecker._default.CheckIfRoleAllowed(path);\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21586/"
] |
333,264 | <p>i want to get an ending html tag like <code></EM></code> only if somewhere before it i.e. before any previous tags or text there is no starting <code><EM></code> tag my sample string is </p>
<pre><code>ddd d<STRONG>dfdsdsd dsdsddd<EM>ss</EM>r and</EM>and strong</STRONG>
</code></pre>
<p>in this string the output should be <code></EM></code> and this also the second <code></EM></code> because it lacks the starting <code><EM></code>. i have tried </p>
<pre><code>(?!=<EM>.*)</EM>
</code></pre>
<p>but it doesnt seem to work please help thnks</p>
| [
{
"answer_id": 333276,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "(?<!<EM>[^<]+)</EM>\n </EM> ?! </EM> (?!=<EM>.*) =<EM>.* = ?<!"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40570/"
] |
333,285 | <p>I'm writing a little arcade-like game in C++ (a multidirectional 2d space shooter) and I'm finishing up the collision detection part.</p>
<p>Here's how I organized it (I just made it up so it might be a shitty system):</p>
<p>Every ship is composed of circular components - the amount of components in each ship is sort of arbitrary (more components, more CPU cycles). I have a maxComponent distance which I calculate upon creation of the ship which is basically the longest line I can draw from the center of the ship to the edge of the furthest component. I keep track of stuff onscreen and use this maxComponentDistance to see if they're even close enough to be colliding.</p>
<p>If they are in close proximity I start checking to see if the components of different ships intersect. Here is where my efficiency question comes in.</p>
<p>I have a (x,y) locations of the component relative to the ship's center, but it doesn't account for how the ship is currently rotated. I keep them relative because I don't want to have to recalculate components every single time the ship moves. So I have a little formula for the rotation calculation and I return a 2d-vector corresponding to rotation-considerate position relative to the ships center.</p>
<p>The collision detection is in the GameEngine and it uses the 2d-vector. My question is about the return types. Should I just create and return a 2d-vector object everytime that function is called
or
should I give that component object an additional private 2d-vector variable, edit the private variable when the function is called, and return a pointer to that object?</p>
<p>I'm not sure about the efficiency of memory allocation vs having a permanent, editable, private variable. I know that memory would also have to be allocated for the private variable, but not every time it was checked for collisions, only when a new component was created. Components are not constant in my environment as they are deleted when the ship is destroyed.</p>
<p>That's my main dilemma. I would also appreciate any pointers with the design of my actual collision detection system. It's my first time giving a hack at it (maybe should have read up a bit)</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 333334,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "vector point vector<int> f(int baz) {\n vector<int> ret;\n if (baz == 42)\n ret.push_back(42);\n return ret;\n}\n\nvector<int> g(int baz) {\n if (baz == 42)\n return vector<int>(1, 42);\n else\n return vector<int>();\n}\n f g"
},
{
"answer_id": 335976,
"author": "Mr.Ree",
"author_id": 37946,
"author_profile": "https://Stackoverflow.com/users/37946",
"pm_score": 1,
"selected": false,
"text": " class Vector2D { double x, y; };\n Vector2D function( ... );\n void function( Vector2D * theReturnedVector2D, ... );\n vector<double> function(...);\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39189/"
] |
333,287 | <p>Tried something like this:</p>
<pre><code>HttpApplication app = s as HttpApplication; //s is sender of the OnBeginRequest event
System.Web.UI.Page p = (System.Web.UI.Page)app.Context.Handler;
System.Web.UI.WebControls.Label lbl = new System.Web.UI.WebControls.Label();
lbl.Text = "TEST TEST TEST";
p.Controls.Add(lbl);
</code></pre>
<p>when running this I get "Object reference not set to an instance of an object." for the last line...</p>
<p>How do I get to insert two lines of text (asp.net/html) at specific loactions in the original file?
And how do I figure out the extension of the file (I only want to apply this on aspx files...?</p>
| [
{
"answer_id": 333439,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 0,
"selected": false,
"text": "string requestPath = HttpContext.Current.Request.Url.AbsolutePath;\nstring extension = System.IO.Path.GetExtension(requestPath);\nbool isAspx = extension.Equals(\".aspx\");\n public void Init(HttpApplication context)\n{\n context.BeginRequest += new EventHandler(BeginRequest);\n}\n\nvoid BeginRequest(object sender, EventArgs e)\n{\n\n HttpContext context = HttpContext.Current;\n HttpRequest request = context.Request;\n\n string requestPath = HttpContext.Current.Request.Url.AbsolutePath;\n string extension = System.IO.Path.GetExtension(requestPath);\n bool isAspx = extension.Equals(\".aspx\");\n\n if (isAspx)\n {\n // Add whatever you need of custom logic for adding the content here\n context.Items[\"custom\"] = \"anything here\";\n }\n\n}\n public class CustomPage : System.Web.UI.Page\n{\n public CustomPage()\n { }\n\n protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n\n if (Context.Items[\"custom\"] == null)\n {\n return;\n }\n\n PlaceHolder placeHolder = this.FindControl(\"pp\") as PlaceHolder;\n if (placeHolder == null)\n {\n return;\n }\n\n Label addedContent = new Label();\n addedContent.Text = Context.Items[\"custom\"].ToString();\n placeHolder .Controls.Add(addedContent);\n\n }\n\n}\n public partial class _Default : CustomPage\n"
},
{
"answer_id": 2975051,
"author": "haze4real",
"author_id": 132225,
"author_profile": "https://Stackoverflow.com/users/132225",
"pm_score": 3,
"selected": false,
"text": " public void Init(HttpApplication app)\n {\n app.PreRequestHandlerExecute += OnPreRequestHandlerExecute;\n }\n\n private void OnPreRequestHandlerExecute(object sender, EventArgs args)\n {\n HttpApplication app = sender as HttpApplication;\n if (app != null)\n {\n Page page = app.Context.Handler as Page;\n if (page != null)\n {\n page.PreRender += OnPreRender;\n }\n }\n }\n\n private void OnPreRender(object sender, EventArgs args)\n {\n Page page = sender as Page;\n if (page != null)\n {\n page.Controls.Clear(); // Or do whatever u want with ur page...\n }\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42108/"
] |
333,291 | <p>I read <a href="https://stackoverflow.com/questions/218123/what-was-the-strangest-coding-standard-rule-that-you-were-forced-to-follow#220591">this answer</a> and its comments and I'm curious: Are there any reasons for not using <code>this</code> / <code>Self</code> / <code>Me</code> ?</p>
<p>BTW: I'm sorry if this has been asked before, it seems that it is impossible to search for the word <code>this</code> on SO.</p>
| [
{
"answer_id": 333300,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "this."
},
{
"answer_id": 333310,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "this.Foo();\n Foo() public static void Foo(this SomeType obj) {...}\n"
},
{
"answer_id": 333319,
"author": "ken",
"author_id": 20300,
"author_profile": "https://Stackoverflow.com/users/20300",
"pm_score": 0,
"selected": false,
"text": "this self"
},
{
"answer_id": 333331,
"author": "sindre j",
"author_id": 37119,
"author_profile": "https://Stackoverflow.com/users/37119",
"pm_score": 3,
"selected": false,
"text": "public class SomeClass\n{\n private string stringvar = \"\";\n\n public SomeClass(string stringvar)\n {\n this.stringvar = stringvar;\n }\n}\n"
},
{
"answer_id": 333336,
"author": "user39603",
"author_id": 39603,
"author_profile": "https://Stackoverflow.com/users/39603",
"pm_score": 0,
"selected": false,
"text": "public class Foo\n{\n public string Bar\n {\n get\n {\n return this.bar;\n }\n /*set\n {\n this.bar = value;\n }*/\n }\n private readonly string bar;\n\n public Foo(string bar)\n {\n this.bar = bar;\n }\n}\n"
},
{
"answer_id": 333341,
"author": "Dan C.",
"author_id": 26391,
"author_profile": "https://Stackoverflow.com/users/26391",
"pm_score": 2,
"selected": false,
"text": "this.whatever this.variable this.othervariable this. this. \"m_\" \"_\""
},
{
"answer_id": 333361,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 0,
"selected": false,
"text": "string name; //should use something like _name or m_name\n\npublic void SetName(string name)\n{\n this.name = name;\n}\n"
},
{
"answer_id": 333436,
"author": "dr. evil",
"author_id": 40322,
"author_profile": "https://Stackoverflow.com/users/40322",
"pm_score": 0,
"selected": false,
"text": "Class Test\n Private IntVar AS Integer\n Public Function New(intVar As Integer)\n Me.Intvar = intvar\n End Function \nEnd Class\n"
},
{
"answer_id": 333501,
"author": "NikolaiDante",
"author_id": 39643,
"author_profile": "https://Stackoverflow.com/users/39643",
"pm_score": 2,
"selected": false,
"text": "this."
},
{
"answer_id": 333548,
"author": "James Camfield",
"author_id": 35033,
"author_profile": "https://Stackoverflow.com/users/35033",
"pm_score": 0,
"selected": false,
"text": "string name;\n\npublic void SetName(string name)\n{\n this.name = name;\n}\n this. super."
},
{
"answer_id": 333695,
"author": "Guge",
"author_id": 37771,
"author_profile": "https://Stackoverflow.com/users/37771",
"pm_score": 0,
"selected": false,
"text": "class Foo\n{\n private string bar;\n\n public int Compare(Foo that)\n {\n if(this.bar == that.bar)\n {\n ...\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
333,294 | <p>I'm in a basic programming class, and everything is done in pseudo code.</p>
<p>My question is this: How do you link two arrays? </p>
<p>I have a single-dimensional array that lists students names, and I have a two-dimensional array that lists the top eight scores of each student...this is all fine and dandy, but now I need to sort the arrays by the students name. I'm poked around online and read through the books chapter twice, it only briefly mentions linking two arrays but shows no examples.</p>
<p>If it's any help, we are using bubble-sorting, and that is what I am fairly familiar with...I can sort the names, that's the easy part, but I don't know how to sort the grades so they do not go out of order.</p>
<p>Thanks for the input!</p>
<p>Sidenote: I got it figured out! I ended up doing how Greg Hewgill had mentioned. As I put in my comment to his suggestion, I started randomly throwing in lines of code until that idea hit me...it doesn't look pretty (one module swapped the names, another to swap the grades, and a third even then to swap the individual students grades earlier on in a multidimensional array), but it indeed seemed to work...no way to test it in a language as I have no compiler nor have I enough knowledge to make the pseudo code into actual code if I were to download one, but it sounds really good on the paper I typed it out on!</p>
<p>As I also mentioned in the note, I do thank everyone for their speedy and helpful insight, I actually didn't even think I'd get a reply tonight, thank you everyone again for all your help!</p>
<p>Jeffrey</p>
| [
{
"answer_id": 333307,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "public class Record\n{\n public string Student;\n public int[] Scores;\n} \n"
},
{
"answer_id": 333368,
"author": "Petar Petrov",
"author_id": 42377,
"author_profile": "https://Stackoverflow.com/users/42377",
"pm_score": 2,
"selected": false,
"text": "public class Student : IComparable<Student>\n{\n public string Name { get; set; }\n public int[] Scores { get; set; }\n\n #region IComparable<Student> Members\n\n public int CompareTo(Student other)\n {\n // Assume Name cannot be null\n return this.Name.CompareTo(other.Name);\n }\n\n #endregion\n}\n var students = new[] {\n new Student(){ Name = \"B\", Scores = new [] { 1,2,3 } },\n new Student(){ Name = \"C\", Scores = new [] { 3,4,5 } },\n new Student(){ Name = \"A\", Scores = new [] { 5,6,7 } }\n };\n\n Array.Sort(students);\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42370/"
] |
333,315 | <p>Looking for a column formatting script, I have a feeling this could be a one line awk. Ideally, a small shell script is all I am after.</p>
<p>The data is tab separated, each cell in each row is of variable length, and of course, may have spaces in it.</p>
<p>So we have something like this</p>
<pre>
dasj dhsahdwe dhasdhajks ewqhehwq dsajkdhas
e dward das dsaw das daswf
fjdk ewf jken dsajkw dskdw
hklt ewq vn1 daskcn daskw
</pre>
<p>Should end up something like this:</p>
<pre>
dasj dhsahdwe dhasdhajks ewqhehwq dsajkdhas
e dward das dsaw das daswf
fjdk ewf jken dsajkw dskdw
hklt ewq vn1 daskcn daskw
</pre>
<p>Ideally, being able to adjust the amount of hard spaced between each one. Even better if it looks on a column by column basis, so leading short cells do not all get the same right padding.</p>
<p>Not ideal:</p>
<pre>
1 dhsahdwe dhasdhajks ewqhehwq dsajkdhas
2 das dsaw das daswf
3 ewf jken dsajkw dskdw
4 ewq vn1 daskcn daskw
</pre>
<p>Ideal:</p>
<pre>
1 dhsahdwe dhasdhajks ewqhehwq dsajkdhas
2 das dsaw das daswf
3 ewf jken dsajkw dskdw
4 ewq vn1 daskcn daskw
</pre>
| [
{
"answer_id": 333345,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/perl -w\n\nuse strict;\n\nmy (@data, @length);\nwhile (<>) {\n chomp;\n my @line = split(/\\t/);\n foreach my $i (0 .. $#line) {\n my $n = length($line[$i]);\n $length[$i] = $n if (!defined($length[$i]) || $n > $length[$i]);\n }\n push(@data, [ @line ]);\n}\n\n$length[$#length] = 0; # no need to pad the last column\nmy $fmt = join(\" \", map { \"%-${_}s\" } @length) . \"\\n\";\nforeach my $ref (@data) {\n printf $fmt, @$ref;\n}\n"
},
{
"answer_id": 333362,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 1,
"selected": false,
"text": "BEGIN {\n FS = \"\\t\";\n # max: Column width\n # fpl: Fields per line\n # data: Fields in every line\n}\n { # Note the blank before this brace\n fpl[FNR] = NF;\n for (i=1; i<=NF; i++) {\n data[FNR, i] = $i;\n if (length($i) > max[i]) {\n max[i] = length($i);\n }\n }\n}\nEND {\n for (l=1; l<=length(fpl); l++) {\n for (i=1; i<=fpl[l]; i++) {\n fmt = \"%-\" max[i] \"s\";\n if (i > 1) {\n printf \" \"; # This goes between columns\n }\n printf fmt, data[l, i];\n }\n printf \"\\n\";\n }\n}\n"
},
{
"answer_id": 917228,
"author": "hbn",
"author_id": 112681,
"author_profile": "https://Stackoverflow.com/users/112681",
"pm_score": 2,
"selected": false,
"text": "% column -t coltest \ndasj dhsahdwe dhasdhajks ewqhehwq dsajkdhas\ne dward das dsaw das daswf\nfjdk ewf jken dsajkw dskdw\nhklt ewq vn1 daskcn daskw\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
333,317 | <p>My Java application is saving stuff in 'user.home' but on windows this does not seem to be the correct path to save application information (as a friend told me). An other option is using the preferences api but it's not possible to set up the hsqldb location using the preferences api. Also, I want all files to be available in the same folder (local database, config, cache, ...).</p>
<p>I'm looking for some example code or a framework that takes care of os-specific stuff.</p>
| [
{
"answer_id": 333500,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "C:\\Documents and settings\\<username>"
},
{
"answer_id": 4026581,
"author": "orcus",
"author_id": 487945,
"author_profile": "https://Stackoverflow.com/users/487945",
"pm_score": 1,
"selected": false,
"text": "APPDATA %APPDATA%\\\\.myapp\\config"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42198/"
] |
333,328 | <p>I'm using caml query to select all documents which were modified or added by user. Query runs recursively on all subsites of specified site collection.</p>
<p>Now problem is I can't get rid of folders which are also part of result set. For now I'm filtering them from result datatable. But I'm wondering: Is it possible to filter out folders from result set just by using caml?</p>
| [
{
"answer_id": 333586,
"author": "Marian Polacek",
"author_id": 41545,
"author_profile": "https://Stackoverflow.com/users/41545",
"pm_score": 4,
"selected": false,
"text": "<Neq><FieldRef Name='ContentType' /><Value Type='Text'>Folder</Value></Neq>"
},
{
"answer_id": 1373910,
"author": "Johan Leino",
"author_id": 83283,
"author_profile": "https://Stackoverflow.com/users/83283",
"pm_score": 6,
"selected": true,
"text": "<Where>\n <Eq>\n <FieldRef Name='FSObjType' />\n <Value Type='Integer'>0</Value>\n </Eq>\n</Where>\n"
},
{
"answer_id": 2691787,
"author": "Peter Jacoby",
"author_id": 53472,
"author_profile": "https://Stackoverflow.com/users/53472",
"pm_score": 3,
"selected": false,
"text": "myQuery.ViewAttributes = \"Scope=\\\"Recursive\\\"\";\n"
},
{
"answer_id": 3367186,
"author": "Alex Nolasco",
"author_id": 65694,
"author_profile": "https://Stackoverflow.com/users/65694",
"pm_score": 0,
"selected": false,
"text": " <Where>\n <Eq>\n <FieldRef Name='FSObjType' />\n <Value Type='Number'>1</Value>\n </Eq>\n </Where>\n"
},
{
"answer_id": 8606519,
"author": "Dave T.",
"author_id": 65716,
"author_profile": "https://Stackoverflow.com/users/65716",
"pm_score": 0,
"selected": false,
"text": "<Where>\n <NotIncludes>\n <FieldRef Name='ContentTypeId' />\n <Value Type='ContentTypeId'>0x0120</Value>\n </NotIncludes>\n</Where>\n"
},
{
"answer_id": 16534795,
"author": "JohnC",
"author_id": 815175,
"author_profile": "https://Stackoverflow.com/users/815175",
"pm_score": 3,
"selected": false,
"text": "<Where>\n <Eq>\n <FieldRef Name='FSObjType' />\n <Value Type='Integer'>0</Value>\n </Eq>\n</Where>\n<QueryOptions>\n <ViewAttributes Scope='RecursiveAll' />\n</QueryOptions>\n $qry = new-object Microsoft.SharePoint.SPQuery\n$qry.Query = \"<Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq></Where><QueryOptions><ViewAttributes Scope='RecursiveAll' /></QueryOptions>\"\n\n$items = $lib.GetItems($qry)\n$items.Count\n <QueryOptions> $qry.ViewAttributes = “Scope=’RecursiveAll’\""
},
{
"answer_id": 35287710,
"author": "Atul",
"author_id": 5800500,
"author_profile": "https://Stackoverflow.com/users/5800500",
"pm_score": 0,
"selected": false,
"text": "<Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq></Where>\n"
},
{
"answer_id": 40906289,
"author": "Rustam",
"author_id": 1500805,
"author_profile": "https://Stackoverflow.com/users/1500805",
"pm_score": 2,
"selected": false,
"text": "<Where>\n <BeginsWith><FieldRef Name=\"ContentTypeId\" />\n <Value Type=\"ContentTypeId\">0x0101</Value>\n </BeginsWith>\n</Where>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41545/"
] |
333,329 | <p>I'm trying to make a pull down menu post a form when the user selects (releases the mouse) on one of the options from the menu. This code works fine in FF but Safari, for some reason, doesn't submit the form. I re-wrote the code using jquery to see if jquery's .submit() implementation handled the browser quirks better. Same result, works in FF doesn't work in safari. </p>
<p>The following snippets are from the same page, which has some django template language mixed in.</p>
<p>Here's the vanilla js attempt:</p>
<pre><code>function formSubmit(lang) {
if (lang != '{{ LANGUAGE_CODE }}') {
document.getElementById("setlang_form").submit();
}
}
</code></pre>
<p>Here's the jquery attempt:</p>
<pre><code>$(document).ready(function() {
$('#lang_submit').hide()
$('#setlang_form option').mouseup(function () {
if ($(this).attr('value') != '{{ LANGUAGE_CODE }}') {
$('#setlang_form').submit()
}
});
});
</code></pre>
<p>and here's the form:</p>
<pre><code><form id="setlang_form" method="post" action="{% url django.views.i18n.set_language %}">
<fieldset>
<select name="language">
{% for lang in interface_languages %}
<option value="{{ lang.code }}" onmouseup="formSubmit('{{ lang.name }}')" {% ifequal lang.code LANGUAGE_CODE %}selected="selected"{% endifequal %}>{{ lang.name }}</option>
{% endfor %}
</select>
</fieldset>
</form>
</code></pre>
<p>My question is, how can I get this working in Safari?</p>
| [
{
"answer_id": 333337,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "onchange <select>"
},
{
"answer_id": 333347,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 2,
"selected": true,
"text": "<form id=\"setlang_form\" method=\"post\" action=\"{% url django.views.i18n.set_language %}\">\n <fieldset>\n <select name=\"language\" onchange=\"formSubmit(this)\">\n {% for lang in interface_languages %}\n <option value=\"{{ lang.code }}\" {% ifequal lang.code LANGUAGE_CODE %}selected=\"selected\"{% endifequal %}>{{ lang.name }}</option>\n {% endfor %}\n </select>\n </fieldset>\n</form>\n function formSubmit(theForm)\n{\n .... theForm.options[theForm.selectedIndex].value\n}\n $(document).ready(function() {\n $('#lang_submit').hide()\n $('#setlang_form select').change(function () { \n .... $(\"select option:selected\").text() .... \n } \n });\n});\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27462/"
] |
333,340 | <p>Let's say I have a search page called Search.aspx that takes a search string as a url parameter ala Google (e.g. Search.aspx?q=This+is+my+search+string).</p>
<p>Currently, I have an asp:TextBox and an asp:Button on my page. I'm handling the button's OnClick event and redirecting in the codebehind file to Search.aspx?q=
<p>What about with ASP.NET MVC when you don't have a codebehind to redirect with? Would you create a GET form element instead that would post to Search.aspx? Or would you handle the redirect in some other manner (e.g. jQuery event attached to the button)?</p>
| [
{
"answer_id": 333642,
"author": "mapache",
"author_id": 41422,
"author_profile": "https://Stackoverflow.com/users/41422",
"pm_score": 0,
"selected": false,
"text": "Search <input type=\"text\" id=\"go\" size=\"4\" /><input type=\"button\" value=\"<%=Html.Encode(\">>\") %>\" onclick=\"javascript:window.location='<%=Url.Action(\"Search\", \"Home\") %>/' + document.getElementById('go').getAttribute('value')\" />\n"
},
{
"answer_id": 334303,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": false,
"text": "<% using (Html.BeginForm (\"Search\", \"Home\")) { %>\n <input name=\"search\" type=\"text\" size=\"16\" id=\"search\" />\n <input type=\"image\" name=\"search-image\" id=\"search-image\" src=\"search.gif\" />\n<% } %>\n public class HomeController : Controller\n{\n public ActionResult Search (string search)\n {\n throw new Exception (string.Format (\"Search: {0}\", search));\n }\n}\n <% Html.RenderPartial (\"Search\"); %>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
333,346 | <p>I have this code inside a class that is used by an application and by an applet.</p>
<pre><code>static
{
if (System.getProperty("os.name").startsWith("Windows"))
{
System.loadLibrary("extmapi");
}
}
</code></pre>
<p>Unfortunately, when the applet loads this code I get an error, because it can't load the "extmapi" library.</p>
<p>To avoid this error, I need to know if the code I'm running is an Applet or an application, so that I can do:</p>
<pre><code>if (isApplet)
return;
else
//load library
</code></pre>
<p>How can I know if I'm running inside an Applet?</p>
| [
{
"answer_id": 333642,
"author": "mapache",
"author_id": 41422,
"author_profile": "https://Stackoverflow.com/users/41422",
"pm_score": 0,
"selected": false,
"text": "Search <input type=\"text\" id=\"go\" size=\"4\" /><input type=\"button\" value=\"<%=Html.Encode(\">>\") %>\" onclick=\"javascript:window.location='<%=Url.Action(\"Search\", \"Home\") %>/' + document.getElementById('go').getAttribute('value')\" />\n"
},
{
"answer_id": 334303,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 2,
"selected": false,
"text": "<% using (Html.BeginForm (\"Search\", \"Home\")) { %>\n <input name=\"search\" type=\"text\" size=\"16\" id=\"search\" />\n <input type=\"image\" name=\"search-image\" id=\"search-image\" src=\"search.gif\" />\n<% } %>\n public class HomeController : Controller\n{\n public ActionResult Search (string search)\n {\n throw new Exception (string.Format (\"Search: {0}\", search));\n }\n}\n <% Html.RenderPartial (\"Search\"); %>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15173/"
] |
333,363 | <p>I need to read a properties files that's buried in my package structure in <code>com.al.common.email.templates</code>.</p>
<p>I've tried everything and I can't figure it out.</p>
<p>In the end, my code will be running in a servlet container, but I don't want to depend on the container for anything. I write JUnit test cases and it needs to work in both.</p>
| [
{
"answer_id": 333385,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 9,
"selected": true,
"text": "com.al.common.email.templates Properties prop = new Properties();\nInputStream in = getClass().getResourceAsStream(\"foo.properties\");\nprop.load(in);\nin.close();\n InputStream in = \n getClass().getResourceAsStream(\"/com/al/common/email/templates/foo.properties\");\n getResource() getResourceAsStream() java.lang.String.class.getResource(\"foo.txt\") /java/lang/String/foo.txt"
},
{
"answer_id": 333389,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 2,
"selected": false,
"text": "/com/al/common/email/templates/foo.properties"
},
{
"answer_id": 1077641,
"author": "cobra libre",
"author_id": 61108,
"author_profile": "https://Stackoverflow.com/users/61108",
"pm_score": 6,
"selected": false,
"text": "static {\n Properties prop = new Properties();\n InputStream in = CurrentClassName.class.getResourceAsStream(\"foo.properties\");\n prop.load(in);\n in.close()\n}\n"
},
{
"answer_id": 9167105,
"author": "user897493",
"author_id": 897493,
"author_profile": "https://Stackoverflow.com/users/897493",
"pm_score": 4,
"selected": false,
"text": "public class Test{ \n static {\n loadProperties();\n}\n static Properties prop;\n private static void loadProperties() {\n prop = new Properties();\n InputStream in = Test.class\n .getResourceAsStream(\"test.properties\");\n try {\n prop.load(in);\n in.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n}\n"
},
{
"answer_id": 16313425,
"author": "Vicky",
"author_id": 187570,
"author_profile": "https://Stackoverflow.com/users/187570",
"pm_score": 3,
"selected": false,
"text": "public class ReadPropertyDemo {\n public static void main(String[] args) {\n Properties properties = new Properties();\n\n try {\n properties.load(new FileInputStream(\n \"com/technicalkeeda/demo/application.properties\"));\n System.out.println(\"Domain :- \" + properties.getProperty(\"domain\"));\n System.out.println(\"Website Age :- \"\n + properties.getProperty(\"website_age\"));\n System.out.println(\"Founder :- \" + properties.getProperty(\"founder\"));\n\n // Display all the values in the form of key value\n for (String key : properties.stringPropertyNames()) {\n String value = properties.getProperty(key);\n System.out.println(\"Key:- \" + key + \"Value:- \" + value);\n }\n\n } catch (IOException e) {\n System.out.println(\"Exception Occurred\" + e.getMessage());\n }\n\n }\n}\n"
},
{
"answer_id": 18244456,
"author": "KulDeep",
"author_id": 2684384,
"author_profile": "https://Stackoverflow.com/users/2684384",
"pm_score": 4,
"selected": false,
"text": "TestLoadProperties ClassLoader InputStream inputStream = TestLoadProperties.class.getClassLoader()\n .getResourceAsStream(\"A.config\");\nproperties.load(inputStream);\n root/src ClassLoader InputStream inputStream = getClass().getResourceAsStream(\"A.config\");\nproperties.load(inputStream);\n TestLoadProperties.class TestLoadProperties.java TestLoadProperties.class .java src/ .class bin/"
},
{
"answer_id": 21534079,
"author": "Prithvish Mukherjee",
"author_id": 3266919,
"author_profile": "https://Stackoverflow.com/users/3266919",
"pm_score": -1,
"selected": false,
"text": "if(fs == null){\n System.err.println(\"Unable to load the properties file\");\n }\nelse{\n try{\n p.load(fs);\n } \ncatch (IOException e) {\n e.printStackTrace();\n }\n }\n"
},
{
"answer_id": 41428691,
"author": "Naramsim",
"author_id": 3482533,
"author_profile": "https://Stackoverflow.com/users/3482533",
"pm_score": 1,
"selected": false,
"text": "Properties props = PropertiesUtil.loadProperties(\"whatever.properties\");\n"
},
{
"answer_id": 44677557,
"author": "isaac.hazan",
"author_id": 1190830,
"author_profile": "https://Stackoverflow.com/users/1190830",
"pm_score": 1,
"selected": false,
"text": " Properties properties = new Properties();\n InputStream in = ClassLoader.getSystemResourceAsStream(\"myfile.properties\");\n properties.load(in);\n in.close();\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42375/"
] |
333,364 | <p>I have an interface method</p>
<pre><code> public void Execute(ICommand command);
</code></pre>
<p>which needs to pass known subtypes of <code>ICommand</code> to an apropriate <code>Handle(SpecificCommand command)</code> method implementation and do some generic handling of unknown types. I am looking for a universal (i.e. not requiring a giant switch) method of doing so, something similar to</p>
<pre><code> Handle(command as command.GetType()); // this obviously does not compile
</code></pre>
<p>I know I could register the handlers somehow, e.g. store them as delegates in a dictionary, but this still requires duplicating the handling logic (once in the specific <code>Handle(...)</code> method signature, once in the delegate reqistration). If I populate the dictionary by inspecting my class with reflection (looking for <code>Handle(XXX command)</code> methods), I'll get a performance hit.</p>
<p>To summarize: how can I downcast an object (upcasted by the call to <code>Execute(ICommand command)</code>) to invoke a method requiring a concrete type without knowing which type it is at compile time.</p>
| [
{
"answer_id": 333377,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "Handle(command) command.Handle()"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] |
333,391 | <p>I need to know how I can detect the current application pool I am running under, so I can do a Recycle on it programmatically.</p>
<p>Does anyone know how to do this for IIS6?</p>
<p>My current code for recycling the app-pool is:</p>
<pre><code> /// <summary>
/// Recycle an application pool
/// </summary>
/// <param name="IIsApplicationPool"></param>
public static void RecycleAppPool(string IIsApplicationPool) {
ManagementScope scope = new ManagementScope(@"\\localhost\root\MicrosoftIISv2");
scope.Connect();
ManagementObject appPool = new ManagementObject(scope, new ManagementPath("IIsApplicationPool.Name='W3SVC/AppPools/" + IIsApplicationPool + "'"), null);
appPool.InvokeMethod("Recycle", null, null);
}
</code></pre>
| [
{
"answer_id": 333475,
"author": "Wolf5",
"author_id": 37643,
"author_profile": "https://Stackoverflow.com/users/37643",
"pm_score": 4,
"selected": true,
"text": " public string GetAppPoolName() {\n\n string AppPath = Context.Request.ServerVariables[\"APPL_MD_PATH\"];\n\n AppPath = AppPath.Replace(\"/LM/\", \"IIS://localhost/\");\n DirectoryEntry root = new DirectoryEntry(AppPath);\n if ((root == null)) {\n return \" no object got\";\n }\n string AppPoolId = (string)root.Properties[\"AppPoolId\"].Value;\n return AppPoolId;\n }\n"
},
{
"answer_id": 12500847,
"author": "Jesse Alexander Romero",
"author_id": 1168226,
"author_profile": "https://Stackoverflow.com/users/1168226",
"pm_score": 2,
"selected": false,
"text": "using System.DirectoryServices private static string GetCurrentApplicationPoolId()\n {\n string virtualDirPath = AppDomain.CurrentDomain.FriendlyName;\n virtualDirPath = virtualDirPath.Substring(4);\n int index = virtualDirPath.Length + 1;\n index = virtualDirPath.LastIndexOf(\"-\", index - 1, index - 1);\n index = virtualDirPath.LastIndexOf(\"-\", index - 1, index - 1);\n virtualDirPath = \"IIS://localhost/\" + virtualDirPath.Remove(index);\n DirectoryEntry virtualDirEntry = new DirectoryEntry(virtualDirPath);\n return virtualDirEntry.Properties[\"AppPoolId\"].Value.ToString();\n }\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37643/"
] |
333,400 | <p>In my application, there are 10-20 classes that are instantiated once[*]. Here's an example:</p>
<pre><code>class SomeOtherManager;
class SomeManagerClass {
public:
SomeManagerClass(SomeOtherManager*);
virtual void someMethod1();
virtual void someMethod2();
};
</code></pre>
<p>Instances of the classes are contained in one object:</p>
<pre><code>class TheManager {
public:
virtual SomeManagerClass* someManagerClass() const;
virtual SomeOtherManager* someOtherManager() const;
/** More objects... up to 10-20 */
};
</code></pre>
<p>Currently TheManager uses the <em>new</em> operator in order to create objects. </p>
<p>My intention is to be able to replace, using plugins, the SomeManagerClass (or any other class) implementation with another one. In order to replace the implementation, 2 steps are needed:</p>
<ol>
<li>Define a class DerivedSomeManagerClass, which inherits SomeManagerClass [plugin]</li>
<li>Create the new class (DerivedSomeManagerClass) instead of the default (SomeManagerClass) [application]</li>
</ol>
<p>I guess I need some kind of object factory, but it should be fairly simple since there's always only one type to create (the default implementation or the user implementation).</p>
<p>Any idea about how to design a simple factory like I just described? Consider the fact that there might be more classes in the future, so it should be easy to extend.</p>
<p>[*] I don't care if it happens more than once.</p>
<p><strong>Edit:</strong> Please note that there are more than two objects that are contained in TheManager.</p>
| [
{
"answer_id": 333442,
"author": "boutta",
"author_id": 15108,
"author_profile": "https://Stackoverflow.com/users/15108",
"pm_score": 1,
"selected": false,
"text": "class Manager { // aka Interface\n public: virtual void someMethod() = 0;\n};\n\nclass Manager1 : public Manager {\n void someMethod() { return null; }\n};\n\nclass Manager2 : public Manager {\n void someMethod() { return null; }\n};\n\nenum ManagerTypes {\n Manager1, Manager2\n};\n\nclass ManagerFactory {\n public static Manager* createManager(ManagerTypes type) {\n Manager* result = null;\n switch (type) {\n case Manager1:\n result = new Manager1();\n break;\n case Manager2:\n result = new Manager2();\n break;\n default:\n // Do whatever error logging you want\n break;\n }\n return result;\n }\n };\n Manager* manager = ManagerFactory.createManager(ManagerTypes.Manager1);\n"
},
{
"answer_id": 333473,
"author": "kshahar",
"author_id": 33982,
"author_profile": "https://Stackoverflow.com/users/33982",
"pm_score": 2,
"selected": false,
"text": "class SomeManagerClassCreator {\npublic:\n virtual SomeManagerClass* create(SomeOtherManager* someOtherManager) { \n return new SomeManagerClass(someOtherManager); \n }\n};\n class SomeManagerClassCreator;\nclass SomeOtherManagerCreator;\n\nclass TheCreator {\npublic:\n void setSomeManagerClassCreator(SomeManagerClassCreator*);\n SomeManagerClassCreator* someManagerClassCreator() const;\n\n void setSomeOtherManagerCreator(SomeOtherManagerCreator*);\n SomeOtherManagerCreator* someOtherManagerCreator() const;\nprivate:\n SomeManagerClassCreator* m_someManagerClassCreator;\n SomeOtherManagerCreator* m_someOtherManagerCreator;\n};\n class TheManager {\npublic:\n TheManager(TheCreator*);\n /* Rest of code from above */\n};\n"
},
{
"answer_id": 333476,
"author": "Ronny Brendel",
"author_id": 14114,
"author_profile": "https://Stackoverflow.com/users/14114",
"pm_score": 0,
"selected": false,
"text": "template<class MemoryManagment>\nclass MyAwesomeClass\n{\n MemoryManagment m_memoryManager;\n};\n"
},
{
"answer_id": 333521,
"author": "Joris Timmermans",
"author_id": 33987,
"author_profile": "https://Stackoverflow.com/users/33987",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n//--------------------------------------------------------------------------------\nclass CSomeManager\n {\n public:\n virtual const char * ShoutOut() { return \"CSomeManager\";}\n };\n\n//--------------------------------------------------------------------------------\nclass COtherManager\n {\n };\n\n//--------------------------------------------------------------------------------\nclass TheManagerFactory\n {\n public:\n // Non-static, non-const to allow polymorphism-abuse\n virtual CSomeManager *CreateSomeManager() { return new CSomeManager(); }\n virtual COtherManager *CreateOtherManager() { return new COtherManager(); }\n };\n\n//--------------------------------------------------------------------------------\nclass CDerivedFromSomeManager : public CSomeManager\n {\n public:\n virtual const char * ShoutOut() { return \"CDerivedFromSomeManager\";}\n };\n\n//--------------------------------------------------------------------------------\nclass TheCustomManagerFactory : public TheManagerFactory\n {\n public:\n virtual CDerivedFromSomeManager *CreateSomeManager() { return new CDerivedFromSomeManager(); }\n\n };\n\n//--------------------------------------------------------------------------------\nclass CMetaManager\n {\n public:\n CMetaManager(TheManagerFactory *ip_factory)\n : mp_some_manager(ip_factory->CreateSomeManager()),\n mp_other_manager(ip_factory->CreateOtherManager())\n {}\n\n CSomeManager *GetSomeManager() { return mp_some_manager; }\n COtherManager *GetOtherManager() { return mp_other_manager; }\n\n private:\n CSomeManager *mp_some_manager;\n COtherManager *mp_other_manager;\n };\n\n//--------------------------------------------------------------------------------\nint _tmain(int argc, _TCHAR* argv[])\n {\n TheManagerFactory standard_factory;\n TheCustomManagerFactory custom_factory;\n\n CMetaManager meta_manager_1(&standard_factory);\n CMetaManager meta_manager_2(&custom_factory);\n\n std::cout << meta_manager_1.GetSomeManager()->ShoutOut() << \"\\n\";\n std::cout << meta_manager_2.GetSomeManager()->ShoutOut() << \"\\n\";\n return 0;\n }\n"
},
{
"answer_id": 333683,
"author": "David Allan Finch",
"author_id": 27417,
"author_profile": "https://Stackoverflow.com/users/27417",
"pm_score": 1,
"selected": false,
"text": "class SomeOtherManager;\n\nclass SomeManagerClass {\npublic:\n SomeManagerClass(SomeOtherManager*);\n virtual void someMethod1();\n virtual void someMethod2();\n};\n\n\nclass TheBaseManager {\npublic:\n // \n};\n\ntemplate <class ManagerClassOne, class ManagerClassOther> \nclass SpecialManager : public TheBaseManager {\n public:\n virtual ManagerClassOne* someManagerClass() const;\n virtual ManagerClassOther* someOtherManager() const;\n};\n\nTheBaseManager* ourManager = new SpecialManager<SomeManagerClass,SomeOtherManager>;\n"
},
{
"answer_id": 530573,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 0,
"selected": false,
"text": "class Manager\n{\npublic:\n virtual void doSomething() = 0;\n virtual int doSomethingElse() = 0;\n}\n\nextern \"C\" {\nManager* newManager();\nvoid deleteManager(Manager*);\n}\n #include \"Manager.h\"\n\nclass PluginManager : public Manager\n{\npublic:\n PluginManager();\n virtual ~PluginManager();\n\npublic:\n virtual void doSomething();\n virtual int doSomethingElse();\n}\n #include \"PluginManager.h\"\n\nManager* newManager()\n{\n return new PluginManager();\n}\nvoid deleteManager(Manager* pManager)\n{\n delete pManager;\n}\n\nPluginManager::PluginManager()\n{\n // ...\n}\n\nPluginManager::~PluginManager()\n{\n // ...\n}\n\nvoid PluginManager::doSomething()\n{\n // ...\n}\n\nint PluginManager::doSomethingElse()\n{\n // ...\n}\n"
},
{
"answer_id": 537165,
"author": "Emiliano",
"author_id": 62811,
"author_profile": "https://Stackoverflow.com/users/62811",
"pm_score": 4,
"selected": false,
"text": "class factory\n{\npublic:\n virtual SomeManagerClass* create() = 0;\n};\n\nclass plugin1_factory : public factory\n{\npublic:\n SomeManagerClass* create() { return new plugin1(); }\n};\n std::map<string, factory*> factory_map;\n...\nfactory_map[\"plugin1\"] = new plugin1_factory();\n SomeManagerClass* obj = factory_map[plugin_name]->create();\n template <class plugin_type>\nclass plugin_factory : public factory\n{\npublic:\n SomeManagerClass* create() { return new plugin_type(); }\n};\n\nfactory_map[\"plugin1\"] = new plugin_factory<plugin1>();\n"
},
{
"answer_id": 546330,
"author": "Dave Van den Eynde",
"author_id": 455874,
"author_profile": "https://Stackoverflow.com/users/455874",
"pm_score": 0,
"selected": false,
"text": "#include \"stdafx.h\"\n#include <map>\n#include <string>\n\nclass BaseClass\n{\npublic:\n virtual ~BaseClass() { }\n virtual void Test() = 0;\n};\n\nclass DerivedClass1 : public BaseClass \n{ \npublic:\n virtual void Test() { } // You can put a breakpoint here to test.\n};\n\nclass DerivedClass2 : public BaseClass \n{ \npublic:\n virtual void Test() { } // You can put a breakpoint here to test.\n};\n\nclass IFactory\n{\npublic:\n virtual BaseClass* CreateNew() const = 0;\n};\n\ntemplate <typename T>\nclass Factory : public IFactory\n{\npublic:\n T* CreateNew() const { return new T(); }\n};\n\nclass FactorySystem\n{\nprivate:\n typedef std::map<std::wstring, IFactory*> FactoryMap;\n FactoryMap m_factories;\n\npublic:\n ~FactorySystem()\n {\n FactoryMap::const_iterator map_item = m_factories.begin();\n for (; map_item != m_factories.end(); ++map_item) delete map_item->second;\n m_factories.clear();\n }\n\n template <typename T>\n void AddFactory(const std::wstring& name)\n {\n delete m_factories[name]; // Delete previous one, if it exists.\n m_factories[name] = new Factory<T>();\n }\n\n BaseClass* CreateNew(const std::wstring& name) const\n {\n FactoryMap::const_iterator found = m_factories.find(name);\n if (found != m_factories.end())\n return found->second->CreateNew();\n else\n return NULL; // or throw an exception, depending on how you want to handle it.\n }\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n FactorySystem system;\n system.AddFactory<DerivedClass1>(L\"derived1\");\n system.AddFactory<DerivedClass2>(L\"derived2\");\n\n BaseClass* b1 = system.CreateNew(L\"derived1\");\n b1->Test();\n delete b1;\n BaseClass* b2 = system.CreateNew(L\"derived2\");\n b2->Test();\n delete b2;\n\n return 0;\n}\n"
},
{
"answer_id": 549565,
"author": "vishvananda",
"author_id": 64381,
"author_profile": "https://Stackoverflow.com/users/64381",
"pm_score": 2,
"selected": false,
"text": "class ManagerFactory\n{\npublic:\n template <typename T> static BaseManager * getManager() { return new T();}\n};\n\nBaseManager * manager1 = ManagerFactory::template getManager<DerivedManager1>();\n #include <map>\n#include <string>\n\nclass BaseManager\n{\npublic:\n virtual void doSomething() = 0;\n};\n\nclass DerivedManager1 : public BaseManager\n{\npublic:\n virtual void doSomething() {};\n};\n\nclass DerivedManager2 : public BaseManager\n{\npublic:\n virtual void doSomething() {};\n};\n\nclass ManagerFactory\n{\npublic:\n typedef BaseManager * (*GetFunction)();\n typedef std::map<std::wstring, GetFunction> ManagerFunctionMap;\nprivate:\n static ManagerFunctionMap _managers;\n\npublic:\n template <typename T> static BaseManager * getManager() { return new T();}\n template <typename T> static void registerManager(const std::wstring& name)\n {\n _managers[name] = ManagerFactory::template getManager<T>;\n }\n static BaseManager * getManagerByName(const std::wstring& name)\n {\n if(_managers.count(name))\n {\n return _managers[name]();\n }\n return NULL;\n }\n};\n// the static map needs to be initialized outside the class\nManagerFactory::ManagerFunctionMap ManagerFactory::_managers;\n\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n // you can get with the templated function\n BaseManager * manager1 = ManagerFactory::template getManager<DerivedManager1>();\n manager1->doSomething();\n // or by registering with a string\n ManagerFactory::template registerManager<DerivedManager1>(L\"Derived1\");\n ManagerFactory::template registerManager<DerivedManager2>(L\"Derived2\");\n // and getting them\n BaseManager * manager2 = ManagerFactory::getManagerByName(L\"Derived2\");\n manager2->doSomething();\n BaseManager * manager3 = ManagerFactory::getManagerByName(L\"Derived1\");\n manager3->doSomething();\n return 0;\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33982/"
] |
333,431 | <p>How would you model these relationships in a db?</p>
<p>You have a Page entity that can contain PageElements.</p>
<p>A PageElement can for instance be an Article, or a Picture. An Article table obviously has other members / columns than a Picture. An article could have ie. "Title", "Lead", "Body" columns that are all of type nvarchar, while a Picture might have something like "AltText", "Path", "Width", "Height". I like this to be extensible, who knows what PageElements I might need in 3 months? So I guess I'd need a PageElementTypes table.</p>
<p>For the relationships, what about tables like these:</p>
<p><strong>Pages</strong> with an Id, and other mumbo jumbo. (Create Date, Visible, what not)</p>
<p><strong>Pages_PageElements</strong> with PageId and PageElementId.</p>
<p><strong>PageElements</strong> with an Id and a PageElementTypeId and more mumbojumbo (SortOrder, Visibility etc.).</p>
<p><strong>PageElementTypes</strong> with an Id and a Name (for instance "Article", "Picture", "AddressBlock")</p>
<p>Now, should I create a PageElementId column in every Articles, Pictures, AddressBlocks table to finish things up? That's where I'm a bit stuck, it's a simple 1:1 relationship so this should work, but somehow I might miss something.</p>
<p><em>Follow up:</em></p>
<p>The recommended solutions below with separate attributes would force me to store all attributes as the same type, or not? What If one PageElement has attributes that are nvarchar(255) and some are nvarchar(1000), what if some are integers?</p>
<p>If I got the EAV way I would have to create tons of tables for holding the attribute values for all the different data types out there. </p>
| [
{
"answer_id": 333444,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 0,
"selected": false,
"text": "PageElementType: ID, Name, [Mumbo Jumbo]\nPageElementTypeParameter: ID, PageElementTypeID, [Mumbo Jumbo]\nPage: ID, [Mumbo Jumbo]\nPageElement: ID, PageElementTypeID, [Mumbo Jumbo]\nPageElementParameters: ID, PageElementID, PageElementTypeParameterID, Value, [Mumbo Jumbo]\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13466/"
] |
333,435 | <p>I have an application where I open a log file for writing. At some point in time (while the application is running), I opened the file with Excel 2003, which said the file should be opened as read-only. That's OK with me.</p>
<p>But then my application threw this exception:</p>
<blockquote>
<p>System.IO.IOException: The process cannot access the file because another process has locked a portion of the file.</p>
</blockquote>
<p>I don't understand how Excel could lock the file (to which <em>my app</em> has write access), and cause my application to fail to write to it!</p>
<p>Why did this happen?</p>
<p>(Note: I didn't observe this behavior with Excel 2007.)</p>
| [
{
"answer_id": 333569,
"author": "Ramesh Soni",
"author_id": 191,
"author_profile": "https://Stackoverflow.com/users/191",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\n\nnamespace Owf.Logger\n{\n public class Logger\n {\n private static object syncContoller = string.Empty;\n private static Logger _logger;\n public static Logger Default\n {\n get\n {\n if (_logger == null)\n _logger = new Logger();\n\n return _logger;\n }\n }\n\n private Dictionary<Guid, DateTime> _starts = new Dictionary<Guid, DateTime>();\n\n private string _fileName = \"Log.txt\";\n\n public string FileName\n {\n get { return _fileName; }\n set { _fileName = value; }\n }\n\n public Guid LogStart(string mesaage)\n {\n lock (syncContoller)\n {\n Guid id = Guid.NewGuid();\n\n _starts.Add(id, DateTime.Now);\n\n LogMessage(string.Format(\"0.00\\tStart: {0}\", mesaage));\n\n return id;\n }\n }\n\n public void LogEnd(Guid id, string mesaage)\n {\n lock (syncContoller)\n {\n if (_starts.ContainsKey(id))\n {\n TimeSpan time = (TimeSpan)(DateTime.Now - _starts[id]);\n\n LogMessage(string.Format(\"{1}\\tEnd: {0}\", mesaage, time.TotalMilliseconds.ToString()));\n }\n else\n throw new ApplicationException(\"Logger.LogEnd: Key doesn't exisits.\");\n }\n }\n\n public void LogMessage(string message)\n {\n lock (syncContoller)\n {\n string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n\n if (!filePath.EndsWith(\"\\\\\"))\n filePath += \"\\\\owf\";\n else\n filePath += \"owf\";\n\n if (!Directory.Exists(filePath))\n Directory.CreateDirectory(filePath);\n\n filePath += \"\\\\Log.txt\";\n\n lock (syncContoller)\n {\n using (StreamWriter sw = new StreamWriter(filePath, true))\n {\n sw.WriteLine(DateTime.Now.ToString(\"yyyy-MM-dd HH:mm:ss.sss\") + \"\\t\" + message);\n }\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 1892605,
"author": "Heider Sati",
"author_id": 230166,
"author_profile": "https://Stackoverflow.com/users/230166",
"pm_score": 0,
"selected": false,
"text": " Dim FS As System.IO.FileStream\n Dim BR As System.IO.BinaryReader\n\n Dim FileBuffer(-1) As Byte\n\n If System.IO.File.Exists(FileName) Then\n Try\n FS = New System.IO.FileStream(FileName, System.IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)\n BR = New System.IO.BinaryReader(FS)\n\n Do While FS.Position < FS.Length\n FileBuffer = BR.ReadBytes(&H10000)\n\n If FileBuffer.Length > 0 Then\n ... do something with the file here... \n End If\n Loop\n\n BR.Close()\n FS.Close()\n\n Catch\n ErrorMessage = \"Error(\" & Err.Number & \") while reading file:\" & Err.Description\n End Try\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41283/"
] |
333,441 | <p>I'm trying to add a label to my toolbar. Button works great, however when I add the label object, it crashes. Any ideas?</p>
<pre><code>UIBarButtonItem *setDateRangeButton = [[UIBarButtonItem alloc] initWithTitle:@"Set date range"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(setDateRangeClicked:)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
label.text = @"test";
[toolbar setItems:[NSArray arrayWithObjects:setDateRangeButton,label, nil]];
// Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];
// Reload the table view
[self.tableView reloadData];
</code></pre>
| [
{
"answer_id": 333509,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 8,
"selected": true,
"text": "[[UIBarButtonItem alloc] initWithCustomView:yourCustomView];\n NSMutableArray *items = [[self.toolbar items] mutableCopy];\n\nUIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];\n[items addObject:spacer];\n[spacer release];\n\nself.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 11.0f, self.view.frame.size.width, 21.0f)];\n[self.titleLabel setFont:[UIFont fontWithName:@\"Helvetica-Bold\" size:18]];\n[self.titleLabel setBackgroundColor:[UIColor clearColor]];\n[self.titleLabel setTextColor:[UIColor colorWithRed:157.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0]];\n[self.titleLabel setText:@\"Title\"];\n[self.titleLabel setTextAlignment:NSTextAlignmentCenter];\n\nUIBarButtonItem *spacer2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];\n[items addObject:spacer2];\n[spacer2 release];\n\nUIBarButtonItem *title = [[UIBarButtonItem alloc] initWithCustomView:self.titleLabel];\n[items addObject:title];\n[title release];\n\n[self.toolbar setItems:items animated:YES];\n[items release];\n"
},
{
"answer_id": 523003,
"author": "Alasdair Allan",
"author_id": 53314,
"author_profile": "https://Stackoverflow.com/users/53314",
"pm_score": 3,
"selected": false,
"text": "UIActivityIndicatorView UIToolBar UIToolBar UIBarButtonItem FlexibleSpaceBarButtonItem UIBarButtonItem UIActivityIndicatorView UIToolBar RootViewController - (void)viewDidLoad {\n[super viewDidLoad];// Add an invisible UIActivityViewIndicator to the toolbar\nUIToolbar *toolbar = (UIToolbar *)[self.view viewWithTag:767];\nNSArray *items = [toolbar items];\n\nactivityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];\n[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite]; \n\nNSArray *newItems = [NSArray arrayWithObjects:[items objectAtIndex:0],[items objectAtIndex:1],[items objectAtIndex:2],\n [[UIBarButtonItem alloc] initWithCustomView:activityIndicator], [items objectAtIndex:3],nil];\n[toolbar setItems:newItems];}\n"
},
{
"answer_id": 4630361,
"author": "Matt R",
"author_id": 513968,
"author_profile": "https://Stackoverflow.com/users/513968",
"pm_score": 7,
"selected": false,
"text": "UIToolBar UILabel UIToolBar UIView UIToolBar UIView UIToolBar IB UIBarButtonItem UIView UILabel UIView UILabel UILabel UILabel UIView clearColor UIToolBar UILabel"
},
{
"answer_id": 12843621,
"author": "Todd Horst",
"author_id": 505829,
"author_profile": "https://Stackoverflow.com/users/505829",
"pm_score": 2,
"selected": false,
"text": "UIWebView IBOutlet html NSString *path = [[NSBundle mainBundle] bundlePath];\nNSURL *baseURL = [NSURL fileURLWithPath:path];\nNSString *html = [NSString stringWithFormat:@\"<html><head><style>body{font-size:11px;text-align:center;background-color:transparent;color:#fff;font-family:helvetica;vertical-align:middle;</style> </head><body><b>Updated</b> 10/11/12 <b>11:09</b> AM</body></html>\"];\n[myWebView loadHTMLString:html baseURL:baseURL];\n"
},
{
"answer_id": 15299090,
"author": "user1938695",
"author_id": 1938695,
"author_profile": "https://Stackoverflow.com/users/1938695",
"pm_score": 1,
"selected": false,
"text": "UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(140 , 0, 50, 250)];\n[label setBackgroundColor:[UIColor clearColor]];\nlabel.text = @\"TEXT\";\nUIView *view = (UIView *) label;\n[self.barItem setCustomView:view];\n self.barItem UIBarButtonItem [self.barItem setCustom:view] label"
},
{
"answer_id": 17467662,
"author": "Alessandro Ornano",
"author_id": 1894067,
"author_profile": "https://Stackoverflow.com/users/1894067",
"pm_score": 1,
"selected": false,
"text": "[self.navigationController.tabBarController.view addSubview:yourView];\n"
},
{
"answer_id": 25808958,
"author": "Frederic Adda",
"author_id": 1552730,
"author_profile": "https://Stackoverflow.com/users/1552730",
"pm_score": 5,
"selected": false,
"text": "@IBOutlet private weak var lastUpdateButton: UIBarButtonItem! // Dummy barButtonItem whose customView is lastUpdateLabel\n private var lastUpdateLabel = UILabel(frame: CGRectZero)\n // Dummy button containing the date of last update\nlastUpdateLabel.sizeToFit()\nlastUpdateLabel.backgroundColor = UIColor.clearColor()\nlastUpdateLabel.textAlignment = .Center\nlastUpdateButton.customView = lastUpdateLabel\n UILabel lastUpdateLabel.text = \"Updated: 9/12/14, 2:53\"\nlastUpdateLabel.sizeToFit() \n lastUpdateLabel.sizetoFit()"
},
{
"answer_id": 40854546,
"author": "Vasily Bodnarchuk",
"author_id": 4488252,
"author_profile": "https://Stackoverflow.com/users/4488252",
"pm_score": 2,
"selected": false,
"text": "import UIKit\n\nclass ViewController: UIViewController {\n\n private weak var toolBar: UIToolbar?\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n var bounds = UIScreen.main.bounds\n let bottomBarWithHeight = CGFloat(44)\n bounds.origin.y = bounds.height - bottomBarWithHeight\n bounds.size.height = bottomBarWithHeight\n let toolBar = UIToolbar(frame: bounds)\n view.addSubview(toolBar)\n\n var buttons = [UIBarButtonItem]()\n buttons.append(UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.action)))\n buttons.append(UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(ViewController.action)))\n buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))\n buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))\n buttons.append(ToolBarTitleItem(text: \"\\(NSDate())\", font: .systemFont(ofSize: 12), color: .lightGray))\n buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))\n buttons.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(ViewController.action)))\n toolBar.items = buttons\n\n self.toolBar = toolBar\n }\n @objc func action() { print(\"action\") }\n}\n\nclass ToolBarTitleItem: UIBarButtonItem {\n\n init(text: String, font: UIFont, color: UIColor) {\n let label = UILabel(frame: UIScreen.main.bounds)\n label.text = text\n label.sizeToFit()\n label.font = font\n label.textColor = color\n label.textAlignment = .center\n super.init()\n customView = label\n }\n required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }\n}\n"
},
{
"answer_id": 65244667,
"author": "Bassant Ashraf",
"author_id": 5459472,
"author_profile": "https://Stackoverflow.com/users/5459472",
"pm_score": 0,
"selected": false,
"text": "let resultsLabel = UIBarButtonItem(title: \"number of results\", style: .plain, target: self, action: nil)\nresultsLabel.isEnabled = false\n"
},
{
"answer_id": 68644829,
"author": "Demented07",
"author_id": 11029759,
"author_profile": "https://Stackoverflow.com/users/11029759",
"pm_score": 0,
"selected": false,
"text": "UILabel UIBarButtonItem class ViewController: UIViewController {\n\n override func viewDidLoad() {\n super.viewDidLoad()\n navigationController?.setToolbarHidden(false, animated: false)\n \n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 17)\n textLabel.text = \"Text Label\" // Change this to be any string you want\n let textButton = UIBarButtonItem(customView: textLabel)\n let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)\n setToolbarItems([spacer, textButton, spacer], animated: false)\n }\n \n}\n flexibleSpace"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
333,443 | <p>I'm a C programmer trying to understand C++. Many tutorials demonstrate object instantiation using a snippet such as:</p>
<pre><code>Dog* sparky = new Dog();
</code></pre>
<p>which implies that later on you'll do:</p>
<pre><code>delete sparky;
</code></pre>
<p>which makes sense. Now, in the case when dynamic memory allocation is unnecessary, is there any reason to use the above instead of</p>
<pre><code>Dog sparky;
</code></pre>
<p>and let the destructor be called once sparky goes out of scope?</p>
<p>Thanks!</p>
| [
{
"answer_id": 333541,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 8,
"selected": true,
"text": "std::unique_ptr std::shared_ptr"
},
{
"answer_id": 334752,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 4,
"selected": false,
"text": "void FeedTheDog(Dog* hungryDog);\n\nDog* badDog = new Dog;\nFeedTheDog(badDog);\ndelete badDog;\n\nDog goodDog;\nFeedTheDog(&goodDog);\n"
},
{
"answer_id": 17379543,
"author": "UniversE",
"author_id": 2534472,
"author_profile": "https://Stackoverflow.com/users/2534472",
"pm_score": 4,
"selected": false,
"text": "#include <iostream>\n\nclass A {\npublic:\n virtual void f();\n virtual ~A() {}\n};\n\nclass B : public A {\npublic:\n virtual void f();\n};\n\nvoid A::f() {cout << \"A\";}\nvoid B::f() {cout << \"B\";}\n\nint main(void) {\n A *a = new B();\n a->f();\n delete a;\n return 0;\n}\n int main(void) {\n A a = B();\n a.f();\n return 0;\n}\n B B a A a A A* A&"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42387/"
] |
333,462 | <p>I'm struggling here with a problem:
I have a controller <em>questions</em> which has action <em>new</em>.
Whenever I need to create new question, I'm typing </p>
<pre><code>/questions/new
</code></pre>
<p>What changes to routes.rb should I make to change the URI to </p>
<pre><code>/questions/ask
</code></pre>
<hr>
<p>Thank you.
Valve.</p>
| [
{
"answer_id": 333570,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 4,
"selected": true,
"text": "map.ask_question '/questions/ask', :controller => 'questions', :action => 'new'\n link_to \"Ask a question\", ask_question_path\n"
},
{
"answer_id": 504094,
"author": "ilpoldo",
"author_id": 260963,
"author_profile": "https://Stackoverflow.com/users/260963",
"pm_score": 3,
"selected": false,
"text": "map.resources :questions, :path_names => { :new => 'ask', :delete => 'withdraw' }"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/430254/"
] |
333,463 | <p>I know that XSLT does not work in procedural terms, but unfortunately I have been doing procedural languages for too long. Can anyone help me out by explaining in simple terms how things like apply-templates works and help a thicko like me to understand it.</p>
| [
{
"answer_id": 333480,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 3,
"selected": false,
"text": "xsl:for-each xsl:apply-templates"
},
{
"answer_id": 333912,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "apply-templates apply-templates this xsl:template match priority function apply-templates select <!-- all children of the context node regardless -->\n<xsl:apply-templates /> \n\n<!-- all children of the context node being \"data\" with a @name of \"Foo\" -->\n<xsl:apply-templates select=\"data[@name='Foo']\" /> \n <!-- all children of the context node being \"data\" with a @name of \"Foo\",\n ordered by their respective \"detail\" count -->\n<xsl:apply-templates select=\"data[@name='Foo']\"> \n <xsl:sort select=\"count(detail)\" data-type=\"number\" order=\"descending\"/>\n</xsl:apply-templates>\n <!-- pass in some parameter -->\n<xsl:apply-templates select=\"data[@name='Foo']\"> \n <xsl:with-param name=\"DateSetIcon\" select=\"$img_src\" />\n</xsl:apply-templates>\n apply-templates"
},
{
"answer_id": 334817,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 2,
"selected": false,
"text": "<xsl:for-each> <xsl:apply-templates> <xsl:sort> <xsl:for-each>"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] |
333,484 | <p>I have a GridView control on my page that I have defined a number of BoundFields for. Each row of the databound GridView has a CommandField (Select), for which I want to send the PostBack to a new page.</p>
<p>Of course I could easily send the NewSelectedIndex in a QueryString, but I'd rather keep that information hidden from the user. Suggestions?</p>
| [
{
"answer_id": 333862,
"author": "Sergiu Damian",
"author_id": 41345,
"author_profile": "https://Stackoverflow.com/users/41345",
"pm_score": 0,
"selected": false,
"text": "<asp:HyperLinkField AccessibleHeaderText=\"Edit\" DataNavigateUrlFields=\"ActivityId\" DataNavigateUrlFormatString=\"AcitivtyEdit.aspx?id={0}\" Text=\"Edit Activity\" />\n"
},
{
"answer_id": 334062,
"author": "Sergiu Damian",
"author_id": 41345,
"author_profile": "https://Stackoverflow.com/users/41345",
"pm_score": 2,
"selected": true,
"text": "<asp:TemplateField AccessibleHeaderText=\"Edit\">\n <ItemTemplate>\n <asp:Button runat=\"server\" ID=\"btnEdit\" PostBackUrl=\"~/Default.aspx\" OnClientClick='form1.ActivityId.value = this.Tag;' Tag='<%# Eval(\"ActivityId\") %>' Text=\"Edit\"/>\n </ItemTemplate>\n</asp:TemplateField>\n"
},
{
"answer_id": 894115,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "If e.Row.RowType = DataControlRowType.DataRow Then\n e.Row.Cells(12).Text = \"\"\n Dim img As New WebControls.ImageButton\n img.PostBackUrl = \"NecesidadesPostBack.aspx\"\n img.ImageUrl = \"imagenes/edit.png\"\n img.OnClientClick = HDLB.UniqueID.ToString & \".value = '\" & e.Row.Cells(0).Text & \"'; \" & HDPT.UniqueID.ToString & \".value = '\" & e.Row.Cells(1).Text & \"';\"\n img.AlternateText = \"Edit\"\n e.Row.Cells(12).Controls.Add(img)\nEnd If\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15609/"
] |
333,487 | <p>I've made this decorator, which results in an infinite redirect loop.</p>
<p>The problem is this: </p>
<pre><code>args[0].redirect(users.create_login_url(args[0].request.path))
</code></pre>
<p>It appears to be a perfectly valid URL. So why wouldn't it properly redirect?</p>
<pre><code>def admin_only(handler, *args):
def redirect_to_login(*args, **kwargs):
return args[0].redirect(users.create_login_url(args[0].request.path))
user = users.get_current_user()
if user:
if authorized(user):
return handler(args[0])
else:
logging.warning('An unauthorized user has attempted to enter an authorized page')
return redirect_to_login
else:
return redirect_to_login
</code></pre>
| [
{
"answer_id": 333658,
"author": "taleinat",
"author_id": 40076,
"author_profile": "https://Stackoverflow.com/users/40076",
"pm_score": 3,
"selected": true,
"text": "def redirect_to_login(*args, **kwargs):\n return args[0].redirect(users.create_login_url(args[0].request.path))\n\ndef admin_only(handler):\n def wrapped_handler(*args, **kwargs): \n user = users.get_current_user()\n if user:\n if authorized(user):\n return handler(args[0])\n else:\n logging.warning('An unauthorized user has attempted '\n 'to enter an authorized page')\n return redirect_to_login(*args, **kwargs)\n else:\n return redirect_to_login(*args, **kwargs)\n\n return wrapped_handler\n"
},
{
"answer_id": 334975,
"author": "JJ.",
"author_id": 9106,
"author_profile": "https://Stackoverflow.com/users/9106",
"pm_score": 0,
"selected": false,
"text": "return args[0].redirect(users.create_logout_url(args[0].request.uri))\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9106/"
] |
333,499 | <p>I'm just talking about JavaScript here, not CSS or implementation of the DOM.</p>
<p>I know getters and setters are now available in the latest release of all major browsers except IE. What other JavaScript features are available cross-browser if we have the latest versions of the other browsers and forget about IE for a minute?</p>
| [
{
"answer_id": 333631,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": false,
"text": "canvas"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37196/"
] |
333,508 | <p>By default, when you <code>sudo gem install thegemname</code> it will install executables into <code>/usr/bin/</code></p>
<p>Is there a way to change this? For example, to install them into <code>/usr/local/rubygems/bin</code> (or any other path)?</p>
<p>The path doesn't seem to be hard-coded into the gemspec file, so I don't see why this shouldn't be possible (although I have very little experience with Ruby/Gems)</p>
| [
{
"answer_id": 333519,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 5,
"selected": true,
"text": "~/.gemrc gemhome: /usr/local/rubygems\n /etc/gemrc GEM_HOME $ export GEM_HOME=/tmp/gemtest\n$ gem install bundler\n$ ls /tmp/gemtest/bin/\nbundle\n gem: --bindir /usr/bin\n"
},
{
"answer_id": 333639,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "/usr/bin /Library/Ruby/Site/1.8/rubygems/defaults.rb # The default directory for binaries\ndef self.default_bindir\n if defined? RUBY_FRAMEWORK_VERSION then # mac framework support\n '/usr/bin'\n else # generic install\n ConfigMap[:bindir]\n end\nend\n /usr/bin ~/.gemrc"
},
{
"answer_id": 2679036,
"author": "BryanH",
"author_id": 41688,
"author_profile": "https://Stackoverflow.com/users/41688",
"pm_score": 4,
"selected": false,
"text": "/var/lib/gems/1.8/bin/ /usr/bin/ $PATH ~/.gemrc gem: --bindir /usr/bin\n"
},
{
"answer_id": 55826717,
"author": "Sanjeev Sachdev",
"author_id": 6350321,
"author_profile": "https://Stackoverflow.com/users/6350321",
"pm_score": 0,
"selected": false,
"text": "--bindir sudo gem install thegemname --bindir /usr/local/rubygems/bin\n gem install --help"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
333,517 | <p>I want to implement an application (scholar exercise) over the AdventureWorks database. I have downloaded the diagram. Is there a less formal description of the database?</p>
<p>Thanks,
Lucian</p>
| [
{
"answer_id": 333519,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 5,
"selected": true,
"text": "~/.gemrc gemhome: /usr/local/rubygems\n /etc/gemrc GEM_HOME $ export GEM_HOME=/tmp/gemtest\n$ gem install bundler\n$ ls /tmp/gemtest/bin/\nbundle\n gem: --bindir /usr/bin\n"
},
{
"answer_id": 333639,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "/usr/bin /Library/Ruby/Site/1.8/rubygems/defaults.rb # The default directory for binaries\ndef self.default_bindir\n if defined? RUBY_FRAMEWORK_VERSION then # mac framework support\n '/usr/bin'\n else # generic install\n ConfigMap[:bindir]\n end\nend\n /usr/bin ~/.gemrc"
},
{
"answer_id": 2679036,
"author": "BryanH",
"author_id": 41688,
"author_profile": "https://Stackoverflow.com/users/41688",
"pm_score": 4,
"selected": false,
"text": "/var/lib/gems/1.8/bin/ /usr/bin/ $PATH ~/.gemrc gem: --bindir /usr/bin\n"
},
{
"answer_id": 55826717,
"author": "Sanjeev Sachdev",
"author_id": 6350321,
"author_profile": "https://Stackoverflow.com/users/6350321",
"pm_score": 0,
"selected": false,
"text": "--bindir sudo gem install thegemname --bindir /usr/local/rubygems/bin\n gem install --help"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11464/"
] |
333,518 | <p>In (Visual Basic, .NET):</p>
<pre><code> Dim result As Match = Regex.Match(aStr, aMatchStr)
If result.Success Then
Dim result0 As String = result.Groups(0).Value
Dim result1 As String = result.Groups(1).Value
End If
</code></pre>
<p>With: aStr equal to (whitespace is normal space and there are seven spaces between <code>n</code> and <code>(</code>):</p>
<pre><code>"AMEVDIEERPK + 7 Oxidation &nbsp; &nbsp; &nbsp; (M)"
</code></pre>
<p>Why does <code>result1</code> become an empty string for aMatchStr equal to</p>
<pre><code>"\s*(\d*).*?Oxidation\s+\(M\)"
</code></pre>
<p>but becomes "7" for <code>aMatchStr</code> equal to</p>
<pre><code>"\s*(\d*)\s*Oxidation\s+\(M\)"
</code></pre>
<p>?</p>
<p>(<code>result0</code> becomes equal to "AMEVDIEERPK + 7 Oxidation (M)")</p>
<p>(This is from <a href="http://msquant.sourceforge.net/" rel="nofollow noreferrer">MSQuant</a>, <a href="http://pmortensen.eu/1/MSQuant/MSQsrcWWW,1.5,2008-12-19/MascotResultParser.vb.html" rel="nofollow noreferrer">MascotResultParser.vb</a>, function <code>modificationParseMatch()</code>).</p>
| [
{
"answer_id": 333539,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "Does \"AMEVDIEERPK + 7 Oxidation (M)\" match \"\\s*(\\d*).*?Oxidation\\s+(M)\"? Yes.. stop matching.\n Does \"AMEVDIEERPK + 7 Oxidation (M)\" match \"\\s*(\\d*)\\s*Oxidation\\s+(M)\"? No...\nDoes \"MEVDIEERPK + 7 Oxidation (M)\" match \"\\s*(\\d*)\\s*Oxidation\\s+(M)\"? No...\nDoes \"EVDIEERPK + 7 Oxidation (M)\" match \"\\s*(\\d*)\\s*Oxidation\\s+(M)\"? No...\n...\nDoes \" 7 Oxidation (M)\" match \"\\s*(\\d*)\\s*Oxidation\\s+(M)\"? Yes\n \\d+ \\d*"
},
{
"answer_id": 333774,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "\\w*dation\\s+\\(M\\)"
},
{
"answer_id": 333887,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "\"\\s* // whitespace before +\n \\+ // The + sign itself\n \\s* // whitespace after +\n (\\d*) // optional digits\n .*? // any non-digit between the last digit and Oxidation (M)\n Oxidation\\s+\\(M\\)\"\n"
},
{
"answer_id": 333924,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "\\w* \\s*(\\d*)\\s*\\w*Oxidation\\s+\\(M\\)\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
333,529 | <p>I would like to migrate from Oracle to MySQL, and one of the important steps is to replace the actual job built on an Oracle environment.</p>
<p>Basically, every day I receive some 'oracle' dump files from another Oracle environment (mainly CTL or Oracle table exports). Today my Oracle jobs loaded the received data (CTL...) in my Oracle tables. Now I would like to replace my Oracle tables in MySQL tables, continuing to receive the file coming from the Oracle environment.</p>
<p>So. Do you have same tools or artifacts to read the Oracle CTL files (or
Oracle tables dump) from an MySQL environment?
I already used the mysqlimport GUI, but it does not meet my needs. I need the script/command to do these.</p>
| [
{
"answer_id": 333539,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "Does \"AMEVDIEERPK + 7 Oxidation (M)\" match \"\\s*(\\d*).*?Oxidation\\s+(M)\"? Yes.. stop matching.\n Does \"AMEVDIEERPK + 7 Oxidation (M)\" match \"\\s*(\\d*)\\s*Oxidation\\s+(M)\"? No...\nDoes \"MEVDIEERPK + 7 Oxidation (M)\" match \"\\s*(\\d*)\\s*Oxidation\\s+(M)\"? No...\nDoes \"EVDIEERPK + 7 Oxidation (M)\" match \"\\s*(\\d*)\\s*Oxidation\\s+(M)\"? No...\n...\nDoes \" 7 Oxidation (M)\" match \"\\s*(\\d*)\\s*Oxidation\\s+(M)\"? Yes\n \\d+ \\d*"
},
{
"answer_id": 333774,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "\\w*dation\\s+\\(M\\)"
},
{
"answer_id": 333887,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "\"\\s* // whitespace before +\n \\+ // The + sign itself\n \\s* // whitespace after +\n (\\d*) // optional digits\n .*? // any non-digit between the last digit and Oxidation (M)\n Oxidation\\s+\\(M\\)\"\n"
},
{
"answer_id": 333924,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "\\w* \\s*(\\d*)\\s*\\w*Oxidation\\s+\\(M\\)\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
333,532 | <p>I need to make an AJAX request from a website to a REST web service hosted in another domain.</p>
<p>Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.</p>
<p>The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.</p>
<p>Here is the JavaScript code that makes the asynchronous call:</p>
<pre><code>var serviceUrl = "http://myservicedomain";
var payload = "<myRequest><content>Some content</content></myRequest>";
var request = new XMLHttpRequest();
request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers
request.setRequestHeader("Content-type", "text/xml");
request.send(payload);
</code></pre>
<p>How can I have this work in other browsers beside Internet Explorer? </p>
| [
{
"answer_id": 333770,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "function ajaxWorkaroung() {\n var frm = gewtElementById(\"myIFrame\")\n frm.src = \"http://some_other_domain\"\n}\nfunction ajaxCallback(parameter){\n // this function will be called from myIFrame's content\n}\n"
},
{
"answer_id": 12129009,
"author": "Pablo Jomer",
"author_id": 1511332,
"author_profile": "https://Stackoverflow.com/users/1511332",
"pm_score": 0,
"selected": false,
"text": "require 'sinatra'\nrequire 'curb'\n\nset :views,lambda {\"views/\"+self.name.to_s.downcase.sub(\"controller\",\"\")}\nset :haml, :layout => :'../layout', :format => :html5, :escape_html=>true\ndisable :raise_errors\n\nget '/data/:brand' do\n data_link = \"https://externalsite.com/#{params[:brand]}\"\n c = Curl::Easy.perform(data_link)\n c.body_str\nend\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26396/"
] |
333,537 | <p>Is there any way to generate Excel/CSV through Javascript?
(It should be browser compaatible too)</p>
| [
{
"answer_id": 14846061,
"author": "digitaleagle",
"author_id": 920136,
"author_profile": "https://Stackoverflow.com/users/920136",
"pm_score": 5,
"selected": false,
"text": "var csv = \"\";\n$(\"table\").find(\"tr\").each(function () {\n var sep = \"\";\n $(this).find(\"input\").each(function () {\n csv += sep + $(this).val();\n sep = \",\";\n });\n csv += \"\\n\";\n});\n $(\"#csv\").text(csv);\n window.URL = window.URL || window.webkiURL;\nvar blob = new Blob([csv]);\nvar blobURL = window.URL.createObjectURL(blob);\n $(\"#downloadLink\").html(\"\");\n$(\"<a></a>\").\nattr(\"href\", blobURL).\nattr(\"download\", \"data.csv\").\ntext(\"Download Data\").\nappendTo('#downloadLink');\n"
},
{
"answer_id": 16664453,
"author": "Fireworm",
"author_id": 1505291,
"author_profile": "https://Stackoverflow.com/users/1505291",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\">\nfunction DownloadJSON2CSV(objArray)\n{\n var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;\n\n var str = '';\n\n for (var i = 0; i < array.length; i++) {\n var line = new Array();\n\n for (var index in array[i]) {\n line.push('\"' + array[i][index] + '\"');\n }\n\n str += line.join(';');\n str += '\\r\\n';\n }\n window.open( \"data:text/csv;charset=utf-8,\" + encodeURIComponent(str));\n}\n</script>\n"
},
{
"answer_id": 44690670,
"author": "Sujit Kumar Singh",
"author_id": 7666504,
"author_profile": "https://Stackoverflow.com/users/7666504",
"pm_score": 3,
"selected": false,
"text": "var sheet_1_data = [{Col_One:1, Col_Two:11}, {Col_One:2, Col_Two:22}];\nvar sheet_2_data = [{Col_One:10, Col_Two:110}, {Col_One:20, Col_Two:220}];\nvar opts = [{sheetid:'Sheet One',header:true},{sheetid:'Sheet Two',header:false}];\nvar result = alasql('SELECT * INTO XLSX(\"sample_file.xlsx\",?) FROM ?', [opts,[sheet_1_data ,sheet_2_data]]);\n <script src=\"http://alasql.org/console/alasql.min.js\"></script> \n<script src=\"http://alasql.org/console/xlsx.core.min.js\"></script> \n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21988/"
] |
333,557 | <p>If host my WCF services in IIS7 or WPAS, is it possible to load up two or more services into the same AppDomain so that they can share static variables?</p>
| [
{
"answer_id": 2706099,
"author": "Thomas",
"author_id": 198643,
"author_profile": "https://Stackoverflow.com/users/198643",
"pm_score": 2,
"selected": false,
"text": "namespace ServiceInterface\n{\n [ServiceContract]\n public interface IClass\n {\n [OperationContract]\n string GetMessage();\n }\n}\n MyService Service2 IClass serviceModel <system.serviceModel>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"WebService1.MyServiceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"false\" />\n </behavior>\n <behavior name=\"WebService1.Service2Behavior\">\n <serviceMetadata httpGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"false\" />\n </behavior>\n </serviceBehaviors>\n </behaviors>\n <services>\n <service behaviorConfiguration=\"WebService1.MyServiceBehavior\"\n name=\"WebService1.MyService\">\n <endpoint address=\"\" binding=\"wsHttpBinding\" contract=\"ServiceInterface.IClass\">\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" contract=\"IMetadataExchange\" />\n </service>\n <service behaviorConfiguration=\"WebService1.Service2Behavior\"\n name=\"WebService1.Service2\">\n <endpoint address=\"\" binding=\"wsHttpBinding\" contract=\"ServiceInterface.IClass\">\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" contract=\"IMetadataExchange\" />\n </service>\n </services>\n </system.serviceModel>\n <client>\n <endpoint address=\"http://mymachinename.local/MyService.svc\"\n binding=\"wsHttpBinding\" bindingConfiguration=\"WSHttpBinding_IClass\"\n contract=\"ServiceReference1.IClass\" name=\"WSHttpBinding_IClass\">\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n <endpoint address=\"http://mymachinename.local/Service2.svc\"\n binding=\"wsHttpBinding\" bindingConfiguration=\"WSHttpBinding_IClass1\"\n contract=\"ServiceReference2.IClass\" name=\"WSHttpBinding_IClass1\">\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n</client>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16387/"
] |
333,563 | <p>I can go to a specific line number by double clicking in the status bar in Visual Studio. Is there a keyboard shortcut that does the same thing?</p>
| [
{
"answer_id": 333567,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 4,
"selected": false,
"text": "Edit.GoTo"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] |
333,571 | <p>I have an ASP.NET web application which does the following:</p>
<ol>
<li>Reads an Excel file.</li>
<li>The excel file will have an image URL located in it that points to somewhere on the internet.</li>
<li>The program reads each image URL and store it into a temporary folder in the web server.</li>
<li>The application then resizes (changes the width and height) of the image.</li>
<li><p>Finally, the application will save that image to another folder.</p>
<p>I am getting the following exception: </p></li>
</ol>
<blockquote>
<p>System.Net.WebException: An exception
occurred during a WebClient request.
---> System.UnauthorizedAccessException:
Access to the path
'\abcserver\target03\3111\35644\www.testing.com\web\content\images\TempStorage\tempImage.jpg'
is denied. at
System.IO.__Error.WinIOError(Int32
errorCode, String maybeFullPath) at
System.IO.FileStream.Init(String path,
FileMode mode, FileAccess access,
Int32 rights, Boolean useRights,
FileShare share, Int32 bufferSize,
FileOptions options,
SECURITY_ATTRIBUTES secAttrs, String
msgPath, Boolean bFromProxy) at
System.IO.FileStream..ctor(String
path, FileMode mode, FileAccess
access) at
System.Net.WebClient.DownloadFile(Uri
address, String fileName) --- End
of inner exception stack trace ---<br>
at ProcessImage.GetFileFromUrl(String
imageFileUrl, String newFileName)<br>
at
uploadexceldata.UploadExcelData(String
fileName)</p>
</blockquote>
<pre><code> foreach (DataRow dr in dt.Rows) // Reading each excel row
{
if (dr[0].ToString() != "")
{
id= "";
path = "";
manuId = "";
id= dr[0].ToString();
path = dr[1].ToString();
fileNameOnly = iProImg.GetFileNameOnly(path);
objDb.openConnection();
strSqlGroupInfo = "select ManufacturerID from manufacturers where id='" + id+ "'";
dTblManu = objDb.BuildDT(strSqlGroupInfo); // To Fill data to Datatable
objDb.closeConnection();
if (dTblManu.Rows.Count > 0)
{
manuId = dTblManu.Rows[0][0].ToString();
}
if (manuId != "")
{
tempUploadPath = "images/TempStorage/";
tempUploadPath = Server.MapPath(tempUploadPath);
if (!Directory.Exists(tempUploadPath))
{
Directory.CreateDirectory(tempUploadPath);
}
tempFilePath = tempUploadPath + "\\tempImage.jpg";
tempFilePath = tempFilePath.Replace("/", "\\");
previewPath = Server.MapPath("images/previews/" + manuId);
thumbNailPath = Server.MapPath("images/thumbnails/" + manuId);
if (!Directory.Exists(previewPath))
{
Directory.CreateDirectory(previewPath);
}
if (!Directory.Exists(thumbNailPath))
{
Directory.CreateDirectory(thumbNailPath);
}
fileNameOnly = "\\preview" + id+ ".jpg";
fileNameOnly = fileNameOnly.Replace("/", "\\");
previewPath = previewPath + fileNameOnly;
tempPartialPathP = "images\\previews\\" + manuId + fileNameOnly;
fileNameOnly = "\\thumbnail" + id+ ".jpg";
thumbNailPath = thumbNailPath + fileNameOnly;
tempPartialPathT = "images\\thumbnails\\" + manuId + fileNameOnly;
try
{
iProImg.GetFileFromUrl(path, tempFilePath);
rowCounter++;
iProImg.ReSizeImage(tempFilePath, previewPath, previewSize);
iProImg.ReSizeImage(previewPath, thumbNailPath, thumbNailSize);
}
catch (Exception ec)
{
errorRowCount++;
iLog.LogErrorToFile("uploadExcel", ec.ToString(), "path : " + path + ",tempFilePath :" + tempFilePath);
}
finally
{
if(File.Exists(tempFilePath))
{
File.Delete(tempFilePath);
}
}
} // If manuid!=""
} //if (dr[0].ToString() != "")
</code></pre>
<p>Does anyone have any suggestions on how to fix this exception?</p>
| [
{
"answer_id": 333592,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 2,
"selected": false,
"text": "OK"
},
{
"answer_id": 339440,
"author": "MatthewMartin",
"author_id": 33264,
"author_profile": "https://Stackoverflow.com/users/33264",
"pm_score": 2,
"selected": false,
"text": "<identity impersonate=\"true\" userName=\"accountname\" password=\"password\" />\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40521/"
] |
333,589 | <p>I've got some C# code that resizes images that I think is pretty typical:</p>
<pre><code>Bitmap bmp = new Bitmap(image, new Size(width, height));
Graphics graphics = Graphics.FromImage(bmp);
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawImage(bmp, width, height);
</code></pre>
<p>The problem is that the resultant images are clearly aliased and changes to the InterpolationMode and SmoothingMode properties seem to make no difference.</p>
<p>Any pointers?</p>
| [
{
"answer_id": 333608,
"author": "martinlund",
"author_id": 1808,
"author_profile": "https://Stackoverflow.com/users/1808",
"pm_score": 0,
"selected": false,
"text": "ImageCodecInfo[] codecs=ImageCodecInfo.GetImageEncoders();\nImageCodecInfo codec = null;\nfor (int i = 0; i<codecs.Length;i++)\n{\n if(codecs[i].MimeType.Equals(\"image/jpeg\"))\n codec = codecs[i];\n}\n\nEncoderParameters encoderParametersInstance = null;\n\nif (codec!=null)\n{\n Encoder encoderInstance=Encoder.Quality;\n encoderParametersInstance = new EncoderParameters(2);\n //100% quality, try different values, around 80-90 gives good results.\n EncoderParameter encoderParameterInstance=new EncoderParameter(encoderInstance, 100L);\n encoderParametersInstance.Param[0]=encoderParameterInstance;\n encoderInstance=Encoder.ColorDepth;\n encoderParameterInstance=new EncoderParameter(encoderInstance, 24L);\n encoderParametersInstance.Param[1]=encoderParameterInstance;\n}\n\nMemoryStream ms = new MemoryStream();\nresizedImage.Save(ms, codec, encoderParametersInstance);\n"
},
{
"answer_id": 333743,
"author": "Nick Higgs",
"author_id": 3187,
"author_profile": "https://Stackoverflow.com/users/3187",
"pm_score": 4,
"selected": false,
"text": "Bitmap bmp = new Bitmap(width, height);\nGraphics graph = Graphics.FromImage(bmp);\ngraph.InterpolationMode = InterpolationMode.High;\ngraph.CompositingQuality = CompositingQuality.HighQuality;\ngraph.SmoothingMode = SmoothingMode.AntiAlias;\ngraph.DrawImage(image, new Rectangle(0, 0, width, height));\n graph.InterpolationMode"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3187/"
] |
333,593 | <p>If I would write:</p>
<pre>
int selectedChannels = selector.select();
Set selectedKeys = selector.selectedKeys();
if ( selectedChannels != selectedKeys.size() ) {
// Selector.select() returned because of a call to Selector.wakeup()
// so do synchronization.
}
// Continue with handling selected channels.
</pre>
<p>would it correctly detect the wakeup-call?</p>
<p><strong>Backgroundinformation:</strong></p>
<p>I'm writing a server which most of the time just receives packets and stores them in a file. Very rarely the application has the need to send itself a special packet. For this it initiates a connection (from a different thread) to the server socket:</p>
<pre>
SocketChannel channel = SocketChannel.open();
channel.configureBlocking( false );
channel.connect( new InetSocketAddress( InetAddress.getLocalHost(), PORT ));
selector.wakeup();
SelectionKey key = channel.register( selector, SelectionKey.OP_CONNECT );
</pre>
<p>The problem is that SelectableChannel.register() might block if the main thread is already in Selector.select(). To prevent this from happening I'm calling Selector.wakeup() which let's the main thread return prematurely from select(). To make sure the other thread has the chance to complete the register-call, I would have to synchronize the main thread, but I would have to do it after <strong>every</strong> return from select(). If I could detect whether it returned from select() because of a wakeup() call, then I could optimize it for just this case.</p>
<p>So, in theory the top code snippet should work, but I was wondering whether it would only do so, because it relies on some unspecified behavior?</p>
<p>Thanks for any hints.</p>
| [
{
"answer_id": 333752,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 0,
"selected": false,
"text": "volatile select"
},
{
"answer_id": 334717,
"author": "Greg Case",
"author_id": 462,
"author_profile": "https://Stackoverflow.com/users/462",
"pm_score": 3,
"selected": true,
"text": "Selector#select() Selector#selectedKeys() selectedKeys select selectedKeys select wakeup Selector ReentrantLock ReentrantLock selectorGuard;\nSelector selector;\n\nprivate void doSelect() {\n // Don't enter a select if another thread is in a critical block\n selectorGuard.lock();\n selectorGuard.unlock();\n\n selector.select();\n Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();\n\n while(keyIter.hasNext()) {\n\n SelectionKey key = keyIter.next();\n keyIter.remove();\n\n // Process key\n }\n}\n\nprivate void addToSelector() {\n\n // Lock the selector guard to prevent another select until complete\n selectorGuard.lock();\n\n try {\n selector.wakeup();\n\n // Do logic that registers channel with selector appropriately\n\n } finally {\n selectorGuard.unlock();\n }\n}\n"
},
{
"answer_id": 43728085,
"author": "user207421",
"author_id": 207421,
"author_profile": "https://Stackoverflow.com/users/207421",
"pm_score": 1,
"selected": false,
"text": "select()"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
333,595 | <p>How to include COM components on a published .Net site?</p>
| [
{
"answer_id": 333878,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<object/>"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/333595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29515/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.