qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
325,301 | <p>You are given a heap of code in your favorite language which combines to form a rather complicated application. It runs rather slowly, and your boss has asked you to optimize it. <strong>What are the steps you follow to most efficiently optimize the code?</strong> </p>
<p>What strategies have you found to be <strong>unsuccessful</strong> when optimizing code?</p>
<p><strong>Re-writes</strong>: At what point do you decide to stop optimizing and say "This is as fast as it'll get without a complete re-write." In what cases would you advocate a simple complete re-write anyway? How would you go about designing it?</p>
| [
{
"answer_id": 797848,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 1,
"selected": false,
"text": "call _main foo.cpp:96 call std::vector::iterator:++"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
325,305 | <p>I just set up SSHd through Cygwin on a Windows XP Pro box overseas using a RAT and discluded the openssh package from the install.
I ran the cywin shell (from c:\cywin) and ran
Now, It's under a port I know is safe and fowarded properly, but I won't share it's number. It's not a common port, but it's under 40000.
Firewalls are off etc etc.
I'm on the first Admin account made on the box. (It's full admin)
I've run the following commands</p>
<p><code>chmod +r /etc/passwd<br>
chmod +r /etc/group<br>
hmod 777 /var<br>
/*Created New Admin User Account To Be Used via SSH*/<br>
mkpasswd -cl > /etc/passwd<br>
mkgroup --local > /etc/group</code> </p>
<p>I can connect locally, but not externally.
I know my ports etc are fine.</p>
<p>Any possible problems, as i really need this tunnel up :P</p>
| [
{
"answer_id": 797848,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 1,
"selected": false,
"text": "call _main foo.cpp:96 call std::vector::iterator:++"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36076/"
] |
325,323 | <p>I was just working on a localizable Lua string solution, when I came up with this hack, problem is I don't know how to avoid getting hacked by it :)
So I was wondering if anyone, has done something similar and or knows how to protect from this kind of attack. (in user code)</p>
<p>Since we can do this:</p>
<pre><code>=("foo"):upper() -->output: FOO
</code></pre>
<p>It can be hacked like this:</p>
<pre><code>getmetatable("foo").__index.upper = function() print("bye bye sucker");os.exit() end
=("foo"):upper() -->output: bye bye sucker (application quits)
-- or this way
=string.upper("bar") -->output: bye bye sucker (application quits)
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 326323,
"author": "Alexander Gladysh",
"author_id": 6236,
"author_profile": "https://Stackoverflow.com/users/6236",
"pm_score": 4,
"selected": true,
"text": "__metatable __metatable getmetatable setmetatable > mt = { __metatable = true } \n> t = {}\n> setmetatable(t, mt)\n> setmetatable(t, mt)\nstdin:1: cannot change a protected metatable\nstack traceback:\n [C]: in function 'setmetatable'\n stdin:1: in main chunk\n [C]: ? \n getmetatable(\"\").__metatable = true\n"
},
{
"answer_id": 359081,
"author": "akauppi",
"author_id": 14455,
"author_profile": "https://Stackoverflow.com/users/14455",
"pm_score": 1,
"selected": false,
"text": "upper os.exit"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
325,325 | <p>I have an intermittent problem with some code that writes to a Windows Event Log, using C# and .Net's <code>EventLog</code> class.</p>
<p>Basically, this code works day-to-day perfectly, but very occasionally, we start getting errors like this:</p>
<blockquote>
<p>"System.ArgumentException: Only the
first eight characters of a custom log
name are significant, and there is
already another log on the system
using the first eight characters of
the name given. Name given:
'Application', name of existing log:
'Application'."</p>
</blockquote>
<p>I can identify from the other information on our logs that the call stack affected is like this - You can clearly see I am in fact trying to write to an existing <code>LB_Email</code> log (<code>LogEmail</code> is called first):</p>
<pre><code>public static void LogEmail(string to, string type)
{
string message = String.Format("{0}\t{1}\t{2}", DateTime.Now, to, type);
Log(message, "LB_Email", EventLogEntryType.Information);
}
private static void Log(string message, string logName, EventLogEntryType type)
{
using (EventLog aLog = new EventLog())
{
aLog.Source = logName;
aLog.WriteEntry(message, type);
}
}
</code></pre>
<p>Once the errors start occurring, it seems like access to our <code>LB_Email</code> eventlog is locked somehow - viewing properties on the particular eventlog shows most information greyed-out and unchangeable, and other processes appear to be prevented from logging to that log too. However, I am seeing the error (which uses the same Log method above) via a try-catch that logs to an 'LB_Error' log, and that continues to function as expected.</p>
<p>I am calling this code from a multi-threaded application, but I have been unable to identify if the code above is thread-safe or not.</p>
<p>I can also confirm that the log in question is working again fine after killing and restarting the process... and it had appropriate settings to reuse entries when it got full... though I don't think that was the issue.</p>
<p>I'd love to hear your thoughts and suggestions.</p>
| [
{
"answer_id": 325381,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 3,
"selected": true,
"text": "Log static readonly object lockObj = new object();\n\n public static void LogEmail(string to, string type)\n {\n string message = String.Format(\"{0}\\t{1}\\t{2}\", DateTime.Now, to, type);\n Log(message, \"LB_Email\", EventLogEntryType.Information);\n }\n\n private static void Log(string message, string logName, EventLogEntryType type)\n {\n lock (lockObj)\n {\n using (EventLog aLog = new EventLog())\n {\n aLog.Source = logName;\n aLog.WriteEntry(message, type);\n }\n }\n }\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6004/"
] |
325,328 | <p>Do you know any documentation about the rules of using update sites? I have managed the last 2 and a half years the update site of our company, and these are the problems I have to address:</p>
<ul>
<li>Not all projects use the same eclipse version. We had projects that used eclipse 2.1 (WSAD), eclipse 3.0 (RAD 6), eclipse 3.2 (RAD 7), eclipse 3.3 and eclipse 3.4.</li>
<li>The update site of our company mostly packages things together. So I have written litte plugins (sometimes fragements) to package e.g. the configuration of Checkstyle for our company together with the current version of Checkstyle.</li>
<li>We release two times a year new versions of what has changed. So if I have 1 update site or 4, this will change dramatically the load I have to take.</li>
</ul>
<p>So the question is: How many update sites should we use, and if the number is more than 1, how can I minimize the work to do to maintain the update sites?</p>
| [
{
"answer_id": 325422,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 1,
"selected": false,
"text": "|\n+-WSAD-2-1 Category\n| |\n| +- Checkstyle 3.1 Feature\n| |\n| `- Team Checkstyle configuration for Checkstyle 3.1\n| \n`-Eclipse-3-4 Category\n |\n +- Checkstyle 4.4 Feature\n |\n `- Tema Checkstyle configuration for Checkstyle 4.4\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2603665/"
] |
325,337 | <p>I have below a list of text, it is from a popular online game called EVE Online and this basically gets mailed to you when you kill a person in-game. I'm building a tool to parse these using PHP to extract all relevant information. I will need all pieces of information shown and i'm writting classes to nicely break it into relevant encapsulated data.</p>
<pre><code>2008.06.19 20:53:00
Victim: Massi
Corp: Cygnus Alpha Syndicate
Alliance: NONE
Faction: NONE
Destroyed: Raven
System: Jan
Security: 0.4
Damage Taken: 48436
Involved parties:
Name: Kale Kold
Security: -10.0
Corp: Vicious Little Killers
Alliance: NONE
Faction: NONE
Ship: Drake
Weapon: Hobgoblin II
Damage Done: 22093
Name: Harulth (laid the final blow)
Security: -10.0
Corp: Vicious Little Killers
Alliance: NONE
Faction: NONE
Ship: Drake
Weapon: Caldari Navy Scourge Heavy Missile
Damage Done: 16687
Name: Gistatis Tribuni / Angel Cartel
Damage Done: 9656
Destroyed items:
Capacitor Power Relay II, Qty: 2
Paradise Cruise Missile, Qty: 23
Cataclysm Cruise Missile, Qty: 12
Small Tractor Beam I
Alloyed Tritanium Bar, Qty: 2 (Cargo)
Paradise Cruise Missile, Qty: 1874 (Cargo)
Contaminated Nanite Compound (Cargo)
Capacitor Control Circuit I, Qty: 3
Ballistic Deflection Field I
'Malkuth' Cruise Launcher I, Qty: 3
Angel Electrum Tag, Qty: 2 (Cargo)
Dropped items:
Ballistic Control System I
Shield Boost Amplifier I, Qty: 2
Charred Micro Circuit, Qty: 4 (Cargo)
Capacitor Power Relay II, Qty: 2
Paradise Cruise Missile, Qty: 10
Cataclysm Cruise Missile, Qty: 21
X-Large Shield Booster II
Cataclysm Cruise Missile, Qty: 3220 (Cargo)
Fried Interface Circuit (Cargo)
F-S15 Braced Deflection Shield Matrix, Qty: 2
Salvager I
'Arbalest' Cruise Launcher I
'Malkuth' Cruise Launcher I, Qty: 2
</code></pre>
<p>I'm thinking about using regular expressions to parse the data but how would you approach this? Would you collapse the mail into a one line string or parse each line from an array? The trouble is there are a few anomalies to account for.</p>
<p>First, the 'Involved parties:' section is dynamic and can contain lots of people all with the similar structure as below but if a computer controlled enemy takes a shot at the victim too, it gets shortened to only the 'Name' and 'Damage Done' fields, as shown above (Gistatis Tribuni / Angel Cartel).</p>
<p>Second, the 'Destroyed' and 'Dropped' items are dynamic and will be different lengths on each mail and i will also need to get the quantity and wether or not they are in cargo.</p>
<p>Ideas for an approach are welcome.</p>
| [
{
"answer_id": 325477,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 3,
"selected": true,
"text": "<?php\n\nclass Parser \n{\n /* Enclosing the parser in a class is not mandatory but it' clean */\n\n function Parser()\n {\n\n /* data holder */\n $this->date = '';\n $this->parties = array();\n $this->victim = array();\n $this->items = array(\"Destroyed\" => array(),\n \"Dropped\" => array());\n\n /* Map you states on actions. Sub states can be necessary (and sub parsers too :-) */ \n $this->states = array('Victim' => 'victim_parsing',\n 'Involved' => 'parties_parsing' ,\n 'items:' => \"item_parsing\");\n\n\n $this->state = 'start'; \n $this->item_parsing_state = 'Destroyed'; \n $this->partie_parsing_state = ''; \n $this->parse_tools = array('start' => 'start_parsing',\n 'parties_parsing' =>'parties_parsing',\n 'item_parsing' => 'item_parsing',\n 'victim_parsing' => 'victim_parsing');\n\n\n }\n\n /* the magic job is done here */\n\n function checkLine($line) \n {\n foreach ($this->states as $keyword => $state) \n if (strpos($line, $keyword) !== False)\n $this->state = $this->states[$keyword];\n\n return trim($line);\n }\n\n function parse($file)\n {\n $this->file = new SplFileObject($file);\n foreach ($this->file as $line) \n if ($line = $this->checkLine($line))\n $this->{$this->parse_tools[$this->state]}($line);\n }\n\n\n /* then here you can define as much as parsing rules as you want */\n\n function victim_parsing($line) \n {\n $victim_caract = explode(': ', $line);\n $this->victim[$victim_caract[0]] = $victim_caract[1];\n }\n\n function start_parsing($line)\n {\n $this->date = $line;\n }\n\n function item_parsing($line) \n {\n if (strpos($line, 'items:') !== False)\n {\n $item_state = explode(' ', $line);\n $this->item_parsing_state = $item_state[0];\n } \n else \n {\n $item_caract = explode(', Qty: ', $line);\n $this->items[$this->item_parsing_state][$item_caract[0]] = array();\n $item_infos = explode(' ', $item_caract[1]);\n $this->items[$this->item_parsing_state][$item_caract[0]] ['qty'] = empty($item_infos[0]) ? 1 : $item_infos[0];\n $this->items[$this->item_parsing_state][$item_caract[0]] ['cargo'] = !empty( $item_infos[1]) ? \"True\": \"False\";\n if (empty( $this->items[$this->item_parsing_state][$item_caract[0]] ['qty'] ))\n print $line;\n }\n }\n\n function parties_parsing($line) \n { \n\n $partie_caract = explode(': ', $line);\n\n if ($partie_caract[0] == \"Name\")\n {\n $this->partie_parsing_state = $partie_caract[1];\n $this->parties[ $this->partie_parsing_state ] = array();\n }\n else\n $this->parties[ $this->partie_parsing_state ][$partie_caract[0]] = $partie_caract[1];\n\n }\n\n}\n\n/* a little test */\n\n$parser = new Parser();\n$parser->parse('test.txt');\n\necho \"======== Fight report - \".$parser->date.\" ==========\\n\\n\";\necho \"Victim :\\n\\n\";\nprint_r($parser->victim);\necho \"Parties :\\n\\n\";\nprint_r($parser->parties);\necho \"Items: \\n\\n\";\nprint_r($parser->items);\n\n?>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
325,346 | <p>There's one thing I haven't found in <a href="https://www.rfc-editor.org/rfc/rfc2616" rel="nofollow noreferrer">RFC 2616</a> ("Hypertext Transfer Protocol -- HTTP/1.1") and that's a "canonical" name for a request/response pair. Is there such thing?</p>
<p><a href="https://www.rfc-editor.org/rfc/rfc2616#section-4.1" rel="nofollow noreferrer">4.1 Message Types</a>:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>4.1 Message Types
HTTP messages consist of requests from client to server and responses
from server to client.
HTTP-message = Request | Response ; HTTP/1.1 messages
</code></pre>
</blockquote>
<p>Taking this as a template, which word would you put in the following sentence?</p>
<pre class="lang-none prettyprint-override"><code>A single complete HTTP ... consists of one HTTP Request and one HTTP Response
HTTP-... = Request Response
</code></pre>
<p>roundtrip? cycle?</p>
| [
{
"answer_id": 58045247,
"author": "Cœur",
"author_id": 1033581,
"author_profile": "https://Stackoverflow.com/users/1033581",
"pm_score": 3,
"selected": false,
"text": "Exchange RequestResponse Operation"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4833/"
] |
325,366 | <p>I am trying to make a form in which the user fills in values. It is quite long. I wish to use an expandable tree to fit it into my one form. Is there any way to give each TreeView Node a TextBox by its side? Having the node text edited by itself is not enough.</p>
| [
{
"answer_id": 325412,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "TreeListView"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41392/"
] |
325,367 | <p>I am having trouble getting my ASP.NET application to start an application. For example when I type:
<a href="http://my.domain.com/virtualdir" rel="nofollow noreferrer">http://my.domain.com/virtualdir</a> or </p>
<p><a href="http://my.domain.com/virtualdir/default.aspx" rel="nofollow noreferrer">http://my.domain.com/virtualdir/default.aspx</a> </p>
<p>My application will start but I cannot get ASP.NET to start when I type <a href="http://my.domain.com" rel="nofollow noreferrer">http://my.domain.com</a>. </p>
<p>I have tried to set the default document to default.aspx with no luck. I am sure there is something obvious I a missing here.</p>
| [
{
"answer_id": 325412,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "TreeListView"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
] |
325,370 | <p>In SQL, How we make a check to filter all row which contain a column data is null or empty ?<br>
For examile </p>
<pre><code>Select Name,Age from MEMBERS
</code></pre>
<p>We need a check Name should not equal to null or empty.</p>
| [
{
"answer_id": 325378,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "select name,age from members where name is not null and name <> ''\n"
},
{
"answer_id": 325379,
"author": "Fuangwith S.",
"author_id": 24550,
"author_profile": "https://Stackoverflow.com/users/24550",
"pm_score": 1,
"selected": false,
"text": "SELECT Name,Age FROM MEMBERS WHERE name IS NOT null OR name <> ''"
},
{
"answer_id": 325465,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "select name,age from members where name is not null and name <> ''\n select name,age from members where name is not null\n"
},
{
"answer_id": 325485,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 0,
"selected": false,
"text": "select name,age from members where COALESCE(name, '') <> ''\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34588/"
] |
325,375 | <p>I'm building a small Winform in which I can view types of food in my kitchen.</p>
<p>My entire stock can be displayed by a datagrid view.</p>
<p>Now, I have a filtermenu which contains a dropdownlist of items that can be checked and unchecked.</p>
<p>Based on which items in that list are checked, the display in the datagridview is changed. Only items which are selected are displayed.</p>
<p>At least, that's how I want it to be.
The menu currently has 5 items: Meat, Fish, Fruit, Vegetable and Other.</p>
<p>I'm using a abstract class Food and all the other classes are derived from it.
Eventually I make a string representation of each piece of food which looks a bit like this</p>
<p>FoodType*FoodName*AmountInStock*...</p>
<p>So a star * as seperator.</p>
<p>Then I do this</p>
<pre><code>foreach(Food f in this.kitchen.FoodList)
{
string[] s = f.ToString().Split('*');
Object o = filterMenu.DropDownItems[s[0]];
}
</code></pre>
<p>With FoodList being an ArrayList.
Then I debug that with VisualStudio 2008</p>
<p>The Object o always contains null.</p>
<p>Yet s[0] always contains the name of the food type.
What I want is to be able to find out wheter an item on that menulist is checked. If checked, the datagridview must display it. If not, don't display it.</p>
<p>I fill it up in the constructor with this:</p>
<pre><code>public static void Fill(ToolStripMenuItem item, Type food)
{
foreach (string element in Enum.GetNames(food))
{
if (element != "nothing")
{
ToolStripMenuItem it = (ToolStripMenuItem)item.DropDownItems.Add(element);
it.Checked = true;
it.CheckOnClick = true;
}
}
}
</code></pre>
<p>I've tried the object browser but I can't find anything that helps, so I turn here.</p>
| [
{
"answer_id": 325378,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "select name,age from members where name is not null and name <> ''\n"
},
{
"answer_id": 325379,
"author": "Fuangwith S.",
"author_id": 24550,
"author_profile": "https://Stackoverflow.com/users/24550",
"pm_score": 1,
"selected": false,
"text": "SELECT Name,Age FROM MEMBERS WHERE name IS NOT null OR name <> ''"
},
{
"answer_id": 325465,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "select name,age from members where name is not null and name <> ''\n select name,age from members where name is not null\n"
},
{
"answer_id": 325485,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 0,
"selected": false,
"text": "select name,age from members where COALESCE(name, '') <> ''\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
325,383 | <p>I am getting a runtime error 13 at the end of the following code:</p>
<pre><code>Sub plausibilitaet_check()
Dim rs As DAO.Recordset
Dim rs2 As ADODB.Recordset
Dim db As database
Dim strsql As String
Dim strsql2 As String
Dim tdf As TableDef
Set db = opendatabase("C:\Codebook.mdb")
Set rs = db.OpenRecordset("plausen1")
Set rs2 = CreateObject("ADODB.Recordset")
rs2.ActiveConnection = CurrentProject.Connection
For Each tdf In CurrentDb.TableDefs
If Left(tdf.Name, 4) <> "MSys" Then
rs.MoveFirst
strsql = "SELECT * From [" & tdf.Name & "] WHERE "
Do While Not rs.EOF
On Error Resume Next
strsql2 = "select * from table where GHds <> 0"
Set rs2 = CurrentDb.OpenRecordset(strsql2)
</code></pre>
<p>The error occurs at Set rs2 = CurrentDb.OpenRecordset(strsql2)</p>
<p>Can someone see where I am going wrong?</p>
| [
{
"answer_id": 325394,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 2,
"selected": false,
"text": "\ndim rs2 as DAO.Recordset\n"
},
{
"answer_id": 325395,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 3,
"selected": true,
"text": "Sub plausibilitaet_check()\n\nDim rs As DAO.Recordset\nDim rs2 As DAO.Recordset\nDim db As database\nDim strsql As String\nDim strsql2 As String\nDim tdf As TableDef\n\nSet db = opendatabase(\"C:\\Codebook.mdb\")\nSet rs = db.OpenRecordset(\"plausen1\")\n\n\nFor Each tdf In CurrentDb.TableDefs\n\n If Left(tdf.Name, 4) <> \"MSys\" Then\n rs.MoveFirst\n strsql = \"SELECT * From [\" & tdf.Name & \"] WHERE \"\n\n Do While Not rs.EOF\n On Error Resume Next\n\n strsql2 = \"select * from table where GHds <> 0\"\n Set rs2 = CurrentDb.OpenRecordset(strsql2)\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
325,392 | <p>I am calling a .txt file from a jquery ajax call. It has some special characters like <code>±</code>. This <code>±</code> is a delimiter for a set of array; data I want to split out and push into a JavaScript array.</p>
<p>It is not treated as <code>±</code> symbol when interpreted like this.</p>
<p>How do I get that data as just like browser content?</p>
| [
{
"answer_id": 325418,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "escape() var string = escape('test±test2±test3');\nvar split = string.split('%C2%B1');\n\nalert(split); // test,test2,test3\n\n// %B1%0A is the value i found for ±\n// %C2%B1 is the value escape() gives me when i just copy and paste that char :)\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38578/"
] |
325,399 | <pre><code>% rails
...
General Options:
...
-c, --svn Modify files with subversion. (Note: svn must be in path)
-g, --git Modify files with git. (Note: git must be in path)
</code></pre>
<p>What do these "Modify files" options do for me?</p>
<p>Edit: It is unclear to me what using one (or both?) of these options actually does. As in, how do they alter workflow? What svn/git commands would I then not be issuing myself, or possibly what type of more esoteric commands will I now end up having to issue? Fundamentally, where are the docs on this feature?</p>
| [
{
"answer_id": 2219820,
"author": "keturn",
"author_id": 9585,
"author_profile": "https://Stackoverflow.com/users/9585",
"pm_score": 2,
"selected": true,
"text": "--git svn add git add script/generate rm reset script/destroy --git"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10841/"
] |
325,404 | <p>I am using oracle wallet to store the oracle database passwords,
the batch file to create the wallet asks for password when you run it.
is there any way to modify the batch file , and provide the password before hand </p>
<p>so that i can avoid inputtting the password every time i run that.</p>
<p>so to generalize the problem, is there any way i can write to input stream of another program.</p>
<p>so that i can avoid prompts from my automation scripts.</p>
| [
{
"answer_id": 325444,
"author": "cjanssen",
"author_id": 2950,
"author_profile": "https://Stackoverflow.com/users/2950",
"pm_score": 3,
"selected": true,
"text": "echo mypassword\n myscript | wallet\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32670/"
] |
325,407 | <p>Essentially i want to have a generic function which accepts a LINQ anonymous list and returns an array back. I was hoping to use generics but i just can seem to get it to work.</p>
<p>hopefully the example below helps</p>
<p>say i have a person object with id, fname, lname and dob.
i have a generic class with contains a list of objects.</p>
<p>i return an array of persons back</p>
<p>my code snippet will be something like</p>
<pre><code>dim v = from p in persons.. select p.fname,p.lname
</code></pre>
<p>i now have an anonymous type from system.collections.generic.ineumerable(of t)</p>
<p>to bind this to a grid i would have to iterate and add to an array
e.g.</p>
<pre><code>dim ar() as array
for each x in v
ar.add(x)
next
grid.datasource = ar
</code></pre>
<p>i dont want to do the iteration continually as i might have different objects</p>
<p>i would like a function which does something like below:</p>
<pre><code>function getArrayList(of T)(dim x as T) as array()
dim ar() as array
for each x in t
ar.add(x)
next
return ar
end
</code></pre>
<p>hope that clarifies. how can i get a generic function with accepts an anonymous list of ienumearable and returns an array back.
unfortunately, the one i have does not work.</p>
<p>many thanks in advance as any and all pointers/help will be VASTLY appreciated.</p>
<p>regards</p>
<p>azad</p>
| [
{
"answer_id": 325438,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 1,
"selected": false,
"text": "object IEnumerable ToArray() DataBind IEnumerable DataTable"
},
{
"answer_id": 331086,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": " packages _\n .Select(Function(pkg) pkg.Company) _\n .ToArray()\n"
},
{
"answer_id": 331136,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 2,
"selected": false,
"text": " var qry = from a in Enumerable.Range(0, 100)\n select new { SomeField1 = a, SomeField2 = a * 2, SomeField3 = a * 3 };\n object[] objs = qry.ToArray();\n dataGridView1.DataSource = objs;\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,414 | <p>To follow on from my question yesterday....</p>
<p><a href="https://stackoverflow.com/questions/323842/mysql-table-design-for-a-questionnaire">MySQL Table Design for a Questionnaire</a></p>
<p>I sat down with my boss yesterday afternoon to run through how I was proposing to design the database. However, now I am more confused than ever.</p>
<p>He has been using Access for many years, and has questioned whether I will be able to produce reports from only using one column for the answer (ENUM). He feels from his experience with Access that each possible response (i.e. Very Satisfied, Fairly Satified, Fairly Unsatisfied, Very Unsatisfied), should have it's own column and numerical value(i.e. 100, 66.6, 33.3, 0).</p>
<p>This is so that the database can produce reports that show the average satisfaction nationally and for each retailer individually.</p>
<p>I would really appreciate some guidence, as I really don't want to get this wrong?</p>
<p>Thank you</p>
| [
{
"answer_id": 325458,
"author": "J.D. Fitz.Gerald",
"author_id": 11542,
"author_profile": "https://Stackoverflow.com/users/11542",
"pm_score": 2,
"selected": true,
"text": "userid, questionid, score\n1,1,4\n1,2,4\n1,3,3\n2,1,1\n2,2,4\n...\n select 25*avg(score) from Blah\n select 25*avg(score), questionid from Blah group by questionid\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41378/"
] |
325,419 | <p>I am a newbie for Visual Basic 6 project. I downloaded some tutorials for testing; however, I am not able to drag, move, or edit the UI form designer objects in those projects.</p>
<p>Does anybody know there is an object lock function in VB6?<br />
If there is, how can I unlock it?</p>
| [
{
"answer_id": 325458,
"author": "J.D. Fitz.Gerald",
"author_id": 11542,
"author_profile": "https://Stackoverflow.com/users/11542",
"pm_score": 2,
"selected": true,
"text": "userid, questionid, score\n1,1,4\n1,2,4\n1,3,3\n2,1,1\n2,2,4\n...\n select 25*avg(score) from Blah\n select 25*avg(score), questionid from Blah group by questionid\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,421 | <p>Hiya - been pointed at you guys by a friend of mine.</p>
<p>I have an MDI application (C#, Winforms, .NET 2.0, VS2005, DevExpress 8.2) and one of my forms is behaving very strangely - not repainting itself properly where it overlaps with another instance of the same form class.</p>
<p>The forms contain a custom control (which contains various DevExpress controls), and are inherited from a base form (which is itself inherited).</p>
<p>Due to issues with form inheritance (that old chestnut) there is a bit of control rearranging going on in the constructor. </p>
<p>Problem 1 (minor): None of this control repositioning/resizing seems to take effect unless the form is resized, so I nudge the width up and down by one pixel after the rearranging. Ugly, hacky and I'd really like to not have to do this.</p>
<p>Problem 2 (major):
If forms are shown then attached to the MDI form using the API call SetParent, when I display the 2nd instance, various parts of the two forms are not correctly drawn where they overlap - bits of the top one are behind the existing one - and this problem gets worse when the forms are moved around, rendering them basically unuseable. Other child forms (if present) of a different type seem unaffected...</p>
<p>STOP PRESS: I've established that it doesn't have to be 2 instances of the child form. With only one there are still problems - mainly round the edges of the form, like the area that's being refreshed is smaller than the form itself.</p>
<p>The problem does not occur if the parent is set using the .MDIParent property of the child form - but we cannot do this as the form may be being displayed by a control hosted in a non-.Net application. Also I need to display the child forms non-maximised even if the existing children (of a different type) are maximised, and that only happens using SetParent.</p>
<p>I have tried Refresh() on all the forms of this type (I have a controller that keeps a list of them), but no joy. I have tried to reproduce this effect form a basic app with the same inheritance structure, but I can't. Clearly it is something about the form - since I recreated the form from scratch yesterday and it is still the same it must be the code - but what?? </p>
<p>I am not the hottest on form painting events etc. so have I missed something?</p>
| [
{
"answer_id": 24235861,
"author": "acoustique",
"author_id": 2566589,
"author_profile": "https://Stackoverflow.com/users/2566589",
"pm_score": 0,
"selected": false,
"text": "::SetWindowLong(hwnd, GWL_STYLE, WS_VISIBLE | WS_CLIPCHILDREN));\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41557/"
] |
325,426 | <p>I'm using reflection to loop through a <code>Type</code>'s properties and set certain types to their default. Now, I could do a switch on the type and set the <code>default(Type)</code> explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?</p>
| [
{
"answer_id": 325527,
"author": "kpollock",
"author_id": 41557,
"author_profile": "https://Stackoverflow.com/users/41557",
"pm_score": 2,
"selected": false,
"text": "//in MessageHeader \n private void SetValuesDefault()\n {\n MessageHeader header = this; \n Framework.ObjectPropertyHelper.SetPropertiesToDefault<MessageHeader>(this);\n }\n\n//in ObjectPropertyHelper\n public static void SetPropertiesToDefault<T>(T obj) \n {\n Type objectType = typeof(T);\n\n System.Reflection.PropertyInfo [] props = objectType.GetProperties();\n\n foreach (System.Reflection.PropertyInfo property in props)\n {\n if (property.CanWrite)\n {\n string propertyName = property.Name;\n Type propertyType = property.PropertyType;\n\n object value = TypeHelper.DefaultForType(propertyType);\n property.SetValue(obj, value, null);\n }\n }\n }\n\n//in TypeHelper\n public static object DefaultForType(Type targetType)\n {\n return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;\n }\n"
},
{
"answer_id": 353073,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 11,
"selected": true,
"text": "public static object GetDefault(Type type)\n{\n if(type.IsValueType)\n {\n return Activator.CreateInstance(type);\n }\n return null;\n}\n type.IsValueType type.GetTypeInfo().IsValueType"
},
{
"answer_id": 3950430,
"author": "BSick7",
"author_id": 388977,
"author_profile": "https://Stackoverflow.com/users/388977",
"pm_score": 3,
"selected": false,
"text": "string test = null;\nstring test2 = \"\";\nif (test is string)\n Console.WriteLine(\"This will never be hit.\");\nif (test2 is string)\n Console.WriteLine(\"Always hit.\");\n string test = GetDefault(typeof(string));\nif (test is string)\n Console.WriteLine(\"This will never be hit.\");\n"
},
{
"answer_id": 4027869,
"author": "Rob Fonseca-Ensor",
"author_id": 21433,
"author_profile": "https://Stackoverflow.com/users/21433",
"pm_score": 5,
"selected": false,
"text": " public static object GetDefault(Type t)\n {\n Func<object> f = GetDefault<object>;\n return f.Method.GetGenericMethodDefinition().MakeGenericMethod(t).Invoke(null, null);\n }\n\n private static T GetDefault<T>()\n {\n return default(T);\n }\n"
},
{
"answer_id": 8022677,
"author": "Drakarah",
"author_id": 694640,
"author_profile": "https://Stackoverflow.com/users/694640",
"pm_score": 7,
"selected": false,
"text": " public object GetDefault(Type t)\n {\n return this.GetType().GetMethod(\"GetDefaultGeneric\").MakeGenericMethod(t).Invoke(this, null);\n }\n\n public T GetDefaultGeneric<T>()\n {\n return default(T);\n }\n"
},
{
"answer_id": 8632260,
"author": "Konstantin Isaev",
"author_id": 1026676,
"author_profile": "https://Stackoverflow.com/users/1026676",
"pm_score": 2,
"selected": false,
"text": " private static Dictionary<Type, Delegate> lambdasMap = new Dictionary<Type, Delegate>();\n\n private object GetTypedNull(Type type)\n {\n Delegate func;\n if (!lambdasMap.TryGetValue(type, out func))\n {\n var body = Expression.Default(type);\n var lambda = Expression.Lambda(body);\n func = lambda.Compile();\n lambdasMap[type] = func;\n }\n return func.DynamicInvoke();\n }\n"
},
{
"answer_id": 10288816,
"author": "JoelFan",
"author_id": 16012,
"author_profile": "https://Stackoverflow.com/users/16012",
"pm_score": 7,
"selected": false,
"text": "PropertyInfo.SetValue(obj, null)"
},
{
"answer_id": 11211129,
"author": "Paul Fleming",
"author_id": 967315,
"author_profile": "https://Stackoverflow.com/users/967315",
"pm_score": 2,
"selected": false,
"text": "namespace System\n{\n public static class TypeExtensions\n {\n public static object Default(this Type type)\n {\n object output = null;\n\n if (type.IsValueType)\n {\n output = Activator.CreateInstance(type);\n }\n\n return output;\n }\n }\n}\n"
},
{
"answer_id": 12733445,
"author": "casperOne",
"author_id": 50776,
"author_profile": "https://Stackoverflow.com/users/50776",
"pm_score": 6,
"selected": false,
"text": "Expression Type default(T) Default Expression public static T GetDefaultValue<T>()\n{\n // We want an Func<T> which returns the default.\n // Create that expression here.\n Expression<Func<T>> e = Expression.Lambda<Func<T>>(\n // The default value, always get what the *code* tells us.\n Expression.Default(typeof(T))\n );\n\n // Compile and return the value.\n return e.Compile()();\n}\n\npublic static object GetDefaultValue(this Type type)\n{\n // Validate parameters.\n if (type == null) throw new ArgumentNullException(\"type\");\n\n // We want an Func<object> which returns the default.\n // Create that expression here.\n Expression<Func<object>> e = Expression.Lambda<Func<object>>(\n // Have to convert to object.\n Expression.Convert(\n // The default value, always get what the *code* tells us.\n Expression.Default(type), typeof(object)\n )\n );\n\n // Compile and return the value.\n return e.Compile()();\n}\n Type Type"
},
{
"answer_id": 13376599,
"author": "cuft",
"author_id": 1823317,
"author_profile": "https://Stackoverflow.com/users/1823317",
"pm_score": 5,
"selected": false,
"text": "using System.Collections.Concurrent;\n\nnamespace System\n{\n public static class TypeExtension\n {\n //a thread-safe way to hold default instances created at run-time\n private static ConcurrentDictionary<Type, object> typeDefaults =\n new ConcurrentDictionary<Type, object>();\n\n public static object GetDefaultValue(this Type type)\n {\n return type.IsValueType\n ? typeDefaults.GetOrAdd(type, Activator.CreateInstance)\n : null;\n }\n }\n}\n"
},
{
"answer_id": 22769803,
"author": "Kaz-LA",
"author_id": 1914022,
"author_profile": "https://Stackoverflow.com/users/1914022",
"pm_score": -1,
"selected": false,
"text": " /// <summary>\n /// returns the default value of a specified type\n /// </summary>\n /// <param name=\"type\"></param>\n public static object GetDefault(this Type type)\n {\n return type.IsValueType ? (!type.IsGenericType ? Activator.CreateInstance(type) : type.GenericTypeArguments[0].GetDefault() ) : null;\n }\n"
},
{
"answer_id": 54125660,
"author": "thomasgalliker",
"author_id": 3090156,
"author_profile": "https://Stackoverflow.com/users/3090156",
"pm_score": 2,
"selected": false,
"text": "public static class TypeExtensions\n{\n public static object GetDefault(this Type t)\n {\n var defaultValue = typeof(TypeExtensions)\n .GetRuntimeMethod(nameof(GetDefaultGeneric), new Type[] { })\n .MakeGenericMethod(t).Invoke(null, null);\n return defaultValue;\n }\n\n public static T GetDefaultGeneric<T>()\n {\n return default(T);\n }\n}\n [Fact]\npublic void GetDefaultTest()\n{\n // Arrange\n var type = typeof(DateTime);\n\n // Act\n var defaultValue = type.GetDefault();\n\n // Assert\n defaultValue.Should().Be(default(DateTime));\n}\n"
},
{
"answer_id": 62207124,
"author": "dancer42",
"author_id": 1212480,
"author_profile": "https://Stackoverflow.com/users/1212480",
"pm_score": -1,
"selected": false,
"text": "Nullable<T> a = new Nullable<T>().GetValueOrDefault();"
},
{
"answer_id": 74638815,
"author": "Mina chen",
"author_id": 6756837,
"author_profile": "https://Stackoverflow.com/users/6756837",
"pm_score": 0,
"selected": false,
"text": "var yourObj = new yourObj();\nvar properties = yourObj.GetType().GetProperties();\n\nforeach (var p in properties)\n{\n // you can get default value for each property\n var defaultValue = p.GetValue(yourObj, null);\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
325,443 | <p>If I'm using <code>Long uuid = UUID.randomUUID().getMostSignificantBits()</code> how likely is it to get a collision. It cuts off the least significant bits, so there is a possibility that you run into a collision, right?</p>
| [
{
"answer_id": 325457,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 9,
"selected": true,
"text": "UUID.randomUUID()"
},
{
"answer_id": 16349840,
"author": "Dr Bob",
"author_id": 2345188,
"author_profile": "https://Stackoverflow.com/users/2345188",
"pm_score": 3,
"selected": false,
"text": "YYYYDDDD byte[40] varbinary(85) Int private static final DecimalFormat timeFormat4 = new DecimalFormat(\"0000;0000\");\n\npublic static byte[] getSidWithCalendar() {\n Calendar cal = Calendar.getInstance();\n String val = String.valueOf(cal.get(Calendar.YEAR));\n val += timeFormat4.format(cal.get(Calendar.DAY_OF_YEAR));\n val += UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n return val.getBytes();\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198/"
] |
325,446 | <p>In my application I need to hash a string before I save it to a text file. Does anyone know how to do that?</p>
| [
{
"answer_id": 326225,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 0,
"selected": false,
"text": "static unsigned long\nsdbm(str)\nunsigned char *str;\n{\n unsigned long hash = 0;\n int c;\n\n while (c = *str++)\n hash = c + (hash << 6) + (hash << 16) - hash;\n\n return hash;\n}\n newHash = the character (c) + (previousHashValue * 2^6) + \n (previousHashValue * 2^16) - \n previousHashValue**\npreviousHashValue = newHash\n"
},
{
"answer_id": 363881,
"author": "Gary Kindel",
"author_id": 44597,
"author_profile": "https://Stackoverflow.com/users/44597",
"pm_score": 2,
"selected": false,
"text": "CAPICOM.DLL uses \n DIM key As String\n DIM sValue As String\n\n Dim sEncrypedValue as String \n\nDim oCAP As CAPICOM.EncryptedData\nSet oCAP = New CAPICOM.EncryptedData\n\nWith oCAP.\n .Algorithm.KeyLength = CAPICOM_ENCRYPTION_KEY_LENGTH_56_BITS\n .Algorithm.Name = CAPICOM_ENCRYPTION_ALGORITHM_RC4 \n .SetSecret key\n .Content = sValue \nend with\n\nsEncrypedValue = objCAP.Encrypt(CAPICOM_ENCODE_BASE64)\n\n\nTo Decrypt:\noCAP.SetSecret key\noCAP.Content = sEncrypedValue \nsValue = oCAP.Decrypt(CAPICOM_ENCODE_BASE64)\n"
},
{
"answer_id": 560590,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Optional ByVal Seed As Long = &HEDB88320\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,453 | <p>When I first started programming, I wrote everything in main. But as I learned, I tried to do as little as possible in my <code>main()</code> methods.</p>
<p>But where do you decide to give the other Class/Method the responsibility to take over the program from <code>main()</code>? How do you do it?</p>
<p>I've seen many ways of doing it, like this:</p>
<pre><code>class Main
{
public static void main(String[] args)
{
new Main();
}
}
</code></pre>
<p>and some like:</p>
<pre><code>class Main {
public static void main(String[] args) {
GetOpt.parse(args);
// Decide what to do based on the arguments passed
Database.initialize();
MyAwesomeLogicManager.initialize();
// And main waits for all others to end or shutdown signal to kill all threads.
}
}
</code></pre>
<p>What should and should not be done in <code>main()</code>? Or are there no silver bullets?</p>
<p>Thanks for the time!</p>
| [
{
"answer_id": 325462,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 2,
"selected": false,
"text": "class Main Main()"
},
{
"answer_id": 348518,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 2,
"selected": false,
"text": "public static void main() def main(args=None):\n #argument processing\n #construct instances of your top level objects\n #do stuff\n\nif __name__ == \"__main__\":\n try:\n main(Sys.Argv)\n except: # everything\n # clean up as much as you can\n else:\n # normal cleanup, no exceptions\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7205/"
] |
325,461 | <p>I have strange problem with sharepoint and ajax functionality. We have an UpdatePanel placed inside webpart. When partial postback occurs, page title gets missing.</p>
<p>We have found that temporary partial solution is to write title element into one line and not use any spaces or controls inside it..not even a literal control.</p>
<p>But we need some way to provide sommon title for all pages, so title would look like this:
My default title - Current page title</p>
<p>Any ideas how to solve this?</p>
| [
{
"answer_id": 458389,
"author": "James",
"author_id": 56753,
"author_profile": "https://Stackoverflow.com/users/56753",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\">\n\n// This script is to fix the issue where AJAX causes SharePoint \n// publishing pages to sometimes make the page title something \n// whacky. \nvar app = Sys.Application;\nvar origTitle = \"\";\napp.add_init(SPCustomAppnInit);\n\n\nfunction SPCustomAppnInit(sender) {\n origTitle = document.title; // grab the original title.\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n if (!prm.get_isInAsyncPostBack())\n {\n prm.add_pageLoaded(SPCustomPageLoaded); // wire up loaded handler.\n }\n}\n\nfunction SPCustomPageLoaded(sender, args) {\n\n document.title = origTitle; // put the original title back on the document.\n}\n\n<script>\n"
},
{
"answer_id": 2484828,
"author": "Miss ZerOne",
"author_id": 298173,
"author_profile": "https://Stackoverflow.com/users/298173",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\"> \n\n// This script is to fix the issue where AJAX causes SharePoint \n// publishing pages to sometimes make the page title something \n// whacky. \nvar app = Sys.Application; \nvar origTitle = \"\"; \napp.add_init(SPCustomAppnInit); \n\n\nfunction SPCustomAppnInit(sender) { \n origTitle = document.title; // grab the original title. \n var prm = Sys.WebForms.PageRequestManager.getInstance(); \n if (!prm.get_isInAsyncPostBack()) \n { \n prm.add_pageLoaded(SPCustomPageLoaded); // wire up loaded handler. \n } \n} \n\nfunction SPCustomPageLoaded(sender, args) { \n\n document.title = origTitle; // put the original title back on the document. \n} \n\n</script> \n"
},
{
"answer_id": 4148557,
"author": "Steve J",
"author_id": 50568,
"author_profile": "https://Stackoverflow.com/users/50568",
"pm_score": 2,
"selected": false,
"text": "<title>\n<sharepointwebcontrols:listitemproperty property=\"Title\" ...>\n</title>\n <title><sharepointwebcontrols:listitemproperty property=\"Title\" ...></title>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41545/"
] |
325,463 | <p>I've a python script that has to launch a shell command for every file in a dir:</p>
<pre><code>import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
</code></pre>
<p>This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.</p>
<p>How can I do? Do I have to <code>fork()</code> before <code>calling os.execlp()</code>?</p>
| [
{
"answer_id": 325467,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "os.exec*() os.system()"
},
{
"answer_id": 325474,
"author": "user39307",
"author_id": 39307,
"author_profile": "https://Stackoverflow.com/users/39307",
"pm_score": 8,
"selected": true,
"text": "subprocess import subprocess\nprocess = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\nprocess.wait()\nprint process.returncode\n"
},
{
"answer_id": 325488,
"author": "M. Utku ALTINKAYA",
"author_id": 40948,
"author_profile": "https://Stackoverflow.com/users/40948",
"pm_score": 2,
"selected": false,
"text": "import os\nos.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')\n"
},
{
"answer_id": 325495,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 6,
"selected": false,
"text": "subprocess.Popen import subprocess\ncmd = ['/run/myscript', '--arg', 'value']\np = subprocess.Popen(cmd, stdout=subprocess.PIPE)\nfor line in p.stdout:\n print line\np.wait()\nprint p.returncode\n cmd = ['/run/myscript', '--arg', 'value']\nsubprocess.Popen(cmd).wait()\n"
},
{
"answer_id": 5184921,
"author": "deft_code",
"author_id": 28817,
"author_profile": "https://Stackoverflow.com/users/28817",
"pm_score": 4,
"selected": false,
"text": "check_call check_output check_* import os\nimport subprocess\n\nfiles = os.listdir('.')\nfor f in files:\n subprocess.check_call( [ 'myscript', f ] )\n myscript myscript check_call( [ 'myscript', f ], stdout=subprocess.PIPE ) myscript stderr=subprocess.PIPE check_output( [ 'myscript', f ] ) check_output stderr=subprocess.STDOUT"
},
{
"answer_id": 49182274,
"author": "Nikolay Frick",
"author_id": 434448,
"author_profile": "https://Stackoverflow.com/users/434448",
"pm_score": 2,
"selected": false,
"text": "import os\nos.system(\"pdftoppm -png {} {}\".format(path2pdf, os.path.join(tmpdirname, \"temp\")))\n"
},
{
"answer_id": 53584912,
"author": "kabrapankaj32",
"author_id": 3364687,
"author_profile": "https://Stackoverflow.com/users/3364687",
"pm_score": 1,
"selected": false,
"text": "shell_command = \"ls -l\"\nsubprocess.call(shell_command.split())\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
325,464 | <p>I want a way to list files in a directory and putting a check box beside each one of them so I can select some of them and perform operations with each selected file, what's the best way to do this?</p>
| [
{
"answer_id": 325480,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 2,
"selected": false,
"text": "CheckedListBox"
},
{
"answer_id": 325491,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 4,
"selected": true,
"text": "System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(\"c:\\\\\");\nSystem.IO.FileSystemInfo[] files = di.GetFileSystemInfos();\ncheckedListBox1.Items.AddRange(files);\n"
},
{
"answer_id": 325505,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 1,
"selected": false,
"text": "OpenFileDialog fileDialog = new OpenFileDialog();\nfileDialog.InitialDirectory =@\"C:\\temp\\\";\nfileDialog.Multiselect = true;\nif (fileDialog.ShowDialog() == DialogResult.OK)\n{\n string[] files = fileDialog.FileNames;\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36532/"
] |
325,475 | <p>I am trying to comment an API (.Net) that I am exposing to a customer.
I am doing this by using XML comments, and extracting via SandCastle.</p>
<p>This is all fine and dandy, however I have unittesting for the API, and thought the code from these would be good to place in the example tags.</p>
<p>So does anyone know of a good way to extract unit test code and place in the example tags?
Or does anyone have better ideas?</p>
<p>Of course I redistribute the unit tests with the API, but it would be good to have them in the documentation.</p>
| [
{
"answer_id": 341910,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": " /// <summary>\n /// Returns a string representation of an object.\n /// </summary>\n /// <returns>Comma separated string.</returns>\n /// <example>\n /// <code source=\"UnitM.CentrallProcessingLib.Tests\\Data\\CSVDataRowTests.cs\" region=\"ToString_a\" />\n /// </example>\n public override string ToString()\n {\n return this.Data;\n }\n #region ToString_a\n\n [Test]\n public void ToString_a()\n {\n CSVDataRow res = new CSVDataRow \n {\n Data = \"1;2;3\"\n };\n\n Assert.AreEqual(res.ToString(), res.Data);\n }\n\n #endregion\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189/"
] |
325,479 | <p>Basically I have a small template that looks like:</p>
<pre><code><xsl:template name="templt">
<xsl:param name="filter" />
<xsl:variable name="numOrders" select="count(ORDERS/ORDER[$filter])" />
</xsl:template>
</code></pre>
<p>And I'm trying to call it using</p>
<pre><code><xsl:call-template name="templt">
<xsl:with-param name="filter" select="PRICE &lt; 15" />
</xsl:call-template>
</code></pre>
<p>Unfortunately it seems to evaluate it before the template is called (So effectively "false" is being passed in) Enclosing it in quotes only makes it a string literal so that doesn't work either. Does anybody know if what I'm trying to achive is possible? If so could you shed some light on it? Cheers</p>
| [
{
"answer_id": 325518,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 4,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"xml\" indent=\"yes\"/>\n\n <xsl:template name=\"templt\">\n <xsl:param name=\"filterNodeName\" />\n <xsl:param name=\"filterValue\" />\n <xsl:variable name=\"orders\" select=\"ORDERS/ORDER/child::*[name() = $filterNodeName and number(text()) < $filterValue]\" />\n <xsl:for-each select=\"$orders\">\n <xsl:value-of select=\".\"/>\n </xsl:for-each>\n </xsl:template>\n\n <xsl:template match=\"/\">\n <xsl:call-template name=\"templt\">\n <xsl:with-param name=\"filterNodeName\" select=\"'PRICE'\" />\n <xsl:with-param name=\"filterValue\" select=\"15\" />\n </xsl:call-template>\n </xsl:template>\n</xsl:stylesheet>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601/"
] |
325,508 | <p>I'm wanting to write a method that I can use to initialise a Map. First cut:</p>
<pre><code>Map map(Object ... o) {for (int i = 0; i < o.length; i+=2){result.put(o[i], o[i+1])}}
</code></pre>
<p>Simple, but not type-safe. Using generics, maybe something like:</p>
<pre><code><TKey, TValue> HashMap<TKey, TValue> map(TKey ... keys, TValue ... values)
</code></pre>
<p>but that syntax isn't supported. So eventually I come to this:</p>
<pre><code>public static <TKey, TValue, TMap extends Map<? super TKey, ? super TValue>> TMap map(TMap map, Pair<? extends TKey, ? extends TValue> ... pairs) {
for (Pair<? extends TKey, ? extends TValue> pair: pairs) {
map.put(pair.getKey(), pair.getValue());
}
return map;
}
public static <TKey, TValue> HashMap<? super TKey, ? super TValue> map(Pair<? extends TKey, ? extends TValue> ... pairs) {
return map(new HashMap<TKey, TValue>(), pairs);
}
public static <TKey, TValue> Pair<TKey, TValue> pair(TKey key, TValue value) {
return new Pair<TKey, TValue>(key, value);
}
public static final class Pair<TKey, TValue> {
private final TKey key;
private final TValue value;
Pair(TKey key, TValue value) {this.key = key; this.value = value; }
public TKey getKey() {return key;}
public TValue getValue() {return value;}
}
</code></pre>
<p>But when I try it out, I need to cast it:</p>
<pre><code>private static final Map<? extends Class<? extends Serializable>, ? super TypeHandler<? extends Serializable > > validCodeTypes =
/* (Map<? extends Class<? extends Serializable>, ? super TypeHandler<? extends Serializable >>) */
map(
pair(Integer.class, new IntHandler()),
pair(Integer.TYPE, new IntHandler()),
pair(Character.class, new CharHandler()),
pair(Character.TYPE, new CharHandler()),
pair(String.class, new StringHandler())
);
private interface TypeHandler<TType extends Serializable> {}
private static class CharHandler implements TypeHandler<Character> {}
private static class IntHandler implements TypeHandler<Integer> {}
private static class StringHandler implements TypeHandler<String> {}
</code></pre>
<p>Can anyone tell me how to code my map() methods so that it is entirely general yet doesn't need to be casted?</p>
| [
{
"answer_id": 325526,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "public static <TKey, TValue, TMap extends Map<TKey, TValue>> TMap map(TMap map, Pair<? extends TKey, ? extends TValue>... pairs) {\n for (Pair<? extends TKey, ? extends TValue> pair: pairs) {\n map.put(pair.getKey(), pair.getValue());\n }\n return map;\n}\n\npublic static <TKey, TValue> HashMap<TKey, TValue> map(Pair<? extends TKey, ? extends TValue>... pairs) {\n return map(new HashMap<TKey, TValue>(), pairs);\n}\n Pair Map.Entry"
},
{
"answer_id": 325983,
"author": "Pål GD",
"author_id": 40058,
"author_profile": "https://Stackoverflow.com/users/40058",
"pm_score": 1,
"selected": false,
"text": "import java.util.HashMap;\nimport java.util.Map;\n\npublic class ToHash {\n public static <K, V> Map<K, V> toHash(Object... objects) {\n Map<K, V> map = new HashMap<K, V>(objects.length / 2);\n if (objects.length % 2 != 0) {\n throw new IllegalArgumentException(\"Odd number of elements: \" + objects.length);\n }\n for (int i = 0; i < objects.length; i += 2) {\n map.put((K) objects[i], (V) objects[i + 1]);\n }\n return map;\n }\n}\n"
},
{
"answer_id": 328172,
"author": "Adrian Pronk",
"author_id": 41861,
"author_profile": "https://Stackoverflow.com/users/41861",
"pm_score": 0,
"selected": false,
"text": "Map<Long, Date> map = toHash(\"hello\", \"world\");\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,511 | <p>I am wondering how you would approach this problem</p>
<p>I have two Taxrates that can apply to my products. I specifically want to avoid persisting the Taxrates into the database while still being able to change them in a central place (like Taxrate from 20% to 19% etc).</p>
<p>so I decided it would be great to have them just compiled into my application (It's internal). The problem is that I want to not only to know the Rate but also the Name of the Taxrate.</p>
<p>I could go with an Enum that maps to the value. But then I'd have to create some method that retrieves the German Name of that Taxrate for the English enum-value (I write my code in english, the App is in german).</p>
<p>I thought about just using hardcoded objects to reflect this,</p>
<pre><code>public interface Taxrate
{
string Name { get; }
decimal Rate { get; }
}
public class NormalTaxRate : Taxrate
{
public string Name
{ get { return "Regelsteuersatz"; } }
public decimal Rate
{ get { return 20m; } }
}
</code></pre>
<p>But then I'd have to create some sort of list that holds two instances of those two objects. Doing it static may work, but still I'd have to keep some sort of list.
Also I'd have to find a way to map my POCO Domain Object to this, because I doubt NHibernate can instantiate the right Object depending on a value in a field.</p>
<p>It doesn't really feel right, and I think I'm missing something here. Hope somebody has a better solution, I can't think of one.</p>
<p>greetings, Daniel</p>
<p><em>Ps: also please retag this question if you find something fitting, I can't think of more meaningful tags right now.</em></p>
| [
{
"answer_id": 325538,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 1,
"selected": false,
"text": "<appSettings>\n <add key=\"BaseTaxRate\" value=20\"/>\n <add key=\"HigherTaxRate\" value=40\"/>\n</appSettings>\n string baseTaxRate = ConfigurationSettings.AppSettings[\"BaseTaxRate\"];\n"
},
{
"answer_id": 325542,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": " public abstract class TaxRate\n {\n public static readonly TaxRate Normal = new NormalTaxRate();\n public static readonly TaxRate Whatever = new OtherTaxRate();\n\n // Only allow nested classes to derive from this - and we trust those!\n private TaxRate() {}\n\n public abstract string Name { get; }\n public abstract decimal Rate { get; }\n\n private class NormalTaxRate : TaxRate\n {\n public override string Name { get { return \"Regelsteuersatz\"; } }\n public override decimal Rate { get { return 20m; } }\n }\n\n private class OtherTaxRate : TaxRate\n {\n public override string Name { get { return \"Something else\"; } }\n public override decimal Rate { get { return 120m; } }\n }\n }\n // TaxRate.cs\npublic partial abstract class TaxRate\n{\n // All the stuff apart from the nested classes\n}\n\n// TaxRate.Normal.cs\npublic partial abstract class TaxRate\n{\n private class NormalTaxRate : TaxRate\n {\n public override string Name { get { return \"Regelsteuersatz\"; } }\n public override decimal Rate { get { return 20m; } }\n }\n}\n\n// TaxRate.Other.cs\npublic partial abstract class TaxRate\n{\n private class OtherTaxRate : TaxRate\n {\n public override string Name { get { return \"Something else\"; } }\n public override decimal Rate { get { return 120m; } }\n }\n}\n"
},
{
"answer_id": 325601,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 2,
"selected": false,
"text": "public class TaxRate\n{\n public readonly string Name;\n public readonly decimal Rate;\n\n private TaxRate(string name, decimal rate)\n {\n this.Name = name;\n this.Rate = rate;\n }\n\n\n public static readonly TaxRate NormalRate = new TaxRate(\"Normal rate\", 20);\n public static readonly TaxRate HighRate = new TaxRate(\"High rate\", 80);\n}\n TaxRate"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21699/"
] |
325,512 | <p>Does anyone know if it's possible to open a file in the file system via a link in a WebBrowser component? I'm writing a little reporting tool in which I display a summary as HTML in a WebBrowser component with a link to a more detailed analysis which is saved as an Excel file on disk. </p>
<p>I want the user to be able to click that link within the web-browser (currently just a standard href tag with file://path.xls as the target) and get a prompt to open the file.
If I open my page in IE, this works, but in the WebBrowser control (C# Windows Forms, .Net 2.0) nothing happens.</p>
<p>I don't know if I need some additional permissions/trust or somesuch - has anyone done this successfully or could anyone suggest how to debug this?</p>
| [
{
"answer_id": 325585,
"author": "rfgamaral",
"author_id": 40480,
"author_profile": "https://Stackoverflow.com/users/40480",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Windows.Forms;\nusing System.Security.Permissions;\n\n[PermissionSet(SecurityAction.Demand, Name=\"FullTrust\")]\n[System.Runtime.InteropServices.ComVisibleAttribute(true)]\npublic class Form1 : Form\n{\n private WebBrowser webBrowser1 = new WebBrowser();\n private Button button1 = new Button();\n\n [STAThread]\n public static void Main()\n {\n Application.EnableVisualStyles();\n Application.Run(new Form1());\n }\n\n public Form1()\n {\n button1.Text = \"call script code from client code\";\n button1.Dock = DockStyle.Top;\n button1.Click += new EventHandler(button1_Click);\n webBrowser1.Dock = DockStyle.Fill;\n Controls.Add(webBrowser1);\n Controls.Add(button1);\n Load += new EventHandler(Form1_Load);\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n webBrowser1.AllowWebBrowserDrop = false;\n webBrowser1.IsWebBrowserContextMenuEnabled = false;\n webBrowser1.WebBrowserShortcutsEnabled = false;\n webBrowser1.ObjectForScripting = this;\n // Uncomment the following line when you are finished debugging.\n //webBrowser1.ScriptErrorsSuppressed = true;\n\n webBrowser1.DocumentText =\n \"<html><head><script>\" +\n \"function test(message) { alert(message); }\" +\n \"</script></head><body><button \" +\n \"onclick=\\\"window.external.Test('called from script code')\\\">\" +\n \"call client code from script code</button>\" +\n \"</body></html>\";\n }\n\n public void Test(String message)\n {\n MessageBox.Show(message, \"client code\");\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n webBrowser1.Document.InvokeScript(\"test\",\n new String[] { \"called from client code\" });\n }\n\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4019/"
] |
325,516 | <p>Is it possible to provide Unicode input to a console app, and read the Unicode char/string via Console.ReadKey()?</p>
<p>I know Unicode works when reading the input via other methods, but unfortunately I need to use the 'interception' feature provided by ReadKey.</p>
<p>Update:</p>
<p>When pasting a Unicode character such as U+03BB (λ) into the console, 3 keys are read.</p>
<ol>
<li>Alt + NumPad1</li>
<li>Alt + NumPad1</li>
<li>Alt + NumPad8</li>
</ol>
<p>I have tried to see if this is some kind of encoding, but can not see anything.</p>
| [
{
"answer_id": 326243,
"author": "Eric Rosenberger",
"author_id": 41624,
"author_profile": "https://Stackoverflow.com/users/41624",
"pm_score": 0,
"selected": false,
"text": "char c = Console.ReadKey().KeyChar;\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15541/"
] |
325,524 | <p>I use Eclipse (3.4) and my class compiles without warning or errors.
My project uses an external jar file.</p>
<p>Where do I need to put this external jar file in order not to get a <code>java.lang.NoClassDefFoundError</code> when using this class from another project (not in Eclipse)?</p>
<p>I could just extract the jar into the project folder, but that does not feel right.</p>
<p>Edit: this question is not about importing jars in Eclipse, but using them outside of Eclipse.</p>
| [
{
"answer_id": 325539,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "-classpath java -jar -cp"
},
{
"answer_id": 325540,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 5,
"selected": false,
"text": "jre/lib/ext"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860/"
] |
325,555 | <p>Here is a little test program: </p>
<pre><code>#include <iostream>
class Test
{
public:
static void DoCrash(){ std::cout<< "TEST IT!"<< std::endl; }
};
int main()
{
Test k;
k.DoCrash(); // calling a static method like a member method...
std::system("pause");
return 0;
}
</code></pre>
<p>On VS2008 + SP1 (vc9) it compiles fine: the console just display "TEST IT!".</p>
<p>As far as I know, static member methods shouldn't be called on instanced object.</p>
<ol>
<li>Am I wrong? Is this code correct from the standard point of view?</li>
<li>If it's correct, why is that? I can't find why it would be allowed, or maybe it's to help using "static or not" method in templates?</li>
</ol>
| [
{
"answer_id": 325569,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "Test::DoCrash(); namespace Test {\n void DoCrash() {\n std::cout << \"Crashed!!\" << std::endl;\n }\n};\n Test::DoCrash(); using directive/declaration"
},
{
"answer_id": 325572,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 7,
"selected": true,
"text": "class process {\npublic:\n static void reschedule();\n};\n\nprocess& g();\n\nvoid f()\n{\n process::reschedule(); // OK: no object necessary \n g().reschedule(); // g() is called\n}\n"
},
{
"answer_id": 325581,
"author": "jab",
"author_id": 20367,
"author_profile": "https://Stackoverflow.com/users/20367",
"pm_score": 4,
"selected": false,
"text": "k.DoCrash();\n Test::DoCrash();\n this"
},
{
"answer_id": 31131333,
"author": "Tony Delroy",
"author_id": 410767,
"author_profile": "https://Stackoverflow.com/users/410767",
"pm_score": 2,
"selected": false,
"text": "this virtual static var.f() var Type::f() static . decltype ::"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2368/"
] |
325,558 | <p>Can anyone post an example of Aspect-oriented programming (AOP) that is <em>not</em> logging?</p>
<p>I've looked at several resources but all the examples are trivial logging. What is it useful for?</p>
| [
{
"answer_id": 325584,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 3,
"selected": false,
"text": "[NotNull]\npublic string Property1 { get; set; }\n\n[Length(Min = 10, Max = 20)]\npublic string Property2 { get; set; }\n\n[Regex(Expression = @\"[abc]{2}\")]\npublic string Property3 { get; set; }\n"
},
{
"answer_id": 383338,
"author": "namenlos",
"author_id": 13477,
"author_profile": "https://Stackoverflow.com/users/13477",
"pm_score": 3,
"selected": false,
"text": " void foo()\n {\n int id = lib.create_undo_context();\n try\n {\n lib.performsomeaction();\n lib.performsomeaction();\n lib.performsomeaction();\n\n }\n finally\n {\n lib.destroy_undo_context(id);\n }\n }\n [Undo]\n void foo()\n {\n lib.performsomeaction();\n lib.performsomeaction();\n lib.performsomeaction();\n }\n"
},
{
"answer_id": 11519849,
"author": "wolle23",
"author_id": 1531244,
"author_profile": "https://Stackoverflow.com/users/1531244",
"pm_score": 3,
"selected": false,
"text": "public class Car:IDisposable\n{\n [Inject]\n public IGearBox Gearbox { get; set; }\n ...\n}\n"
},
{
"answer_id": 27092500,
"author": "Amlesh Kumar",
"author_id": 2650920,
"author_profile": "https://Stackoverflow.com/users/2650920",
"pm_score": 2,
"selected": false,
"text": "namespace Examples\\Forum\\Domain\\Model;\n\nclass Forum {\n\n /**\n * @Flow\\Inject\n * @var \\Examples\\Forum\\Logger\\ApplicationLoggerInterface\n */\n protected $applicationLogger;\n\n /**\n * Delete a forum post and log operation\n *\n * @param \\Examples\\Forum\\Domain\\Model\\Post $post\n * @return void\n */\n public function deletePost(Post $post) {\n $this->applicationLogger->log('Removing post ' . $post->getTitle(), LOG_INFO);\n $this->posts->remove($post);\n }\n\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1575281/"
] |
325,559 | <p>I've a table with two columns are a unique key together and i cannot change the schema.</p>
<p>I'm trying to execute an update using psql in which i change the value of one of the column that are key. The script is similar to the following:</p>
<pre><code>BEGIN;
UPDATE t1 SET P1='23' where P1='33';
UPDATE t1 SET P1='23' where P1='55';
COMMIT;
</code></pre>
<p>Using psql with the command:</p>
<pre><code>psql -U user -f file
</code></pre>
<p>I've got the error</p>
<pre><code>ERROR: duplicate key violates unique constraint "<key_name>"
</code></pre>
<p>But the column is in key with another column and changing it doesn't "break" any unique constraint. <strong>The same query inside pgAdmin3 runs fine with no errors</strong>. </p>
<p>I'm not a dba it seems to me that i'm missing something obvious. </p>
<p>Thanks</p>
| [
{
"answer_id": 325584,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 3,
"selected": false,
"text": "[NotNull]\npublic string Property1 { get; set; }\n\n[Length(Min = 10, Max = 20)]\npublic string Property2 { get; set; }\n\n[Regex(Expression = @\"[abc]{2}\")]\npublic string Property3 { get; set; }\n"
},
{
"answer_id": 383338,
"author": "namenlos",
"author_id": 13477,
"author_profile": "https://Stackoverflow.com/users/13477",
"pm_score": 3,
"selected": false,
"text": " void foo()\n {\n int id = lib.create_undo_context();\n try\n {\n lib.performsomeaction();\n lib.performsomeaction();\n lib.performsomeaction();\n\n }\n finally\n {\n lib.destroy_undo_context(id);\n }\n }\n [Undo]\n void foo()\n {\n lib.performsomeaction();\n lib.performsomeaction();\n lib.performsomeaction();\n }\n"
},
{
"answer_id": 11519849,
"author": "wolle23",
"author_id": 1531244,
"author_profile": "https://Stackoverflow.com/users/1531244",
"pm_score": 3,
"selected": false,
"text": "public class Car:IDisposable\n{\n [Inject]\n public IGearBox Gearbox { get; set; }\n ...\n}\n"
},
{
"answer_id": 27092500,
"author": "Amlesh Kumar",
"author_id": 2650920,
"author_profile": "https://Stackoverflow.com/users/2650920",
"pm_score": 2,
"selected": false,
"text": "namespace Examples\\Forum\\Domain\\Model;\n\nclass Forum {\n\n /**\n * @Flow\\Inject\n * @var \\Examples\\Forum\\Logger\\ApplicationLoggerInterface\n */\n protected $applicationLogger;\n\n /**\n * Delete a forum post and log operation\n *\n * @param \\Examples\\Forum\\Domain\\Model\\Post $post\n * @return void\n */\n public function deletePost(Post $post) {\n $this->applicationLogger->log('Removing post ' . $post->getTitle(), LOG_INFO);\n $this->posts->remove($post);\n }\n\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41572/"
] |
325,561 | <p>I have used extension methods to extend html helpers to make an RSS repeater:</p>
<pre><code> public static string RSSRepeater(this HtmlHelper html, IEnumerable<IRSSable> rss)
{
string result="";
foreach (IRSSable item in rss)
{
result += "<item>" + item.GetRSSItem().InnerXml + "</item>";
}
return result;
}
</code></pre>
<p>So I make one of my business objects implement IRSSable, and try to pass this to the HTML helper. But I just cannot seem to make it work, I have tried:</p>
<pre><code><%=Html.RSSRepeater(ViewData.Model.GetIssues(null, null, "") as IEnumerable<IRSSable>) %>
</code></pre>
<p>Compiles fine, but null is passed</p>
<pre><code><%=Html.RSSRepeater(ViewData.Model.GetIssues(null, null, "")) %>
</code></pre>
<p>Intellisense moans about not being able to pass IEnumerable issue to IEnumberable IRSSable</p>
<ul>
<li>So how do you do it? That method I am calling definitly returns <code>IEnumberable<Issue></code> and Issue definitly implements IRSSAble</li>
</ul>
| [
{
"answer_id": 325567,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "IEnumerable<Issue> IEnumerable<IRssable> IEnumerable IEnumerable.Cast<IRssable>"
},
{
"answer_id": 325568,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": " public static string RSSRepeater<T>(this HtmlHelper html, IEnumerable<T> rss)\n where T : IRSSable\n {\n ...\n }\n IRSSable T Issue StringBuilder StringBuilder result = new StringBuilder();\n\n foreach (IRSSable item in rss)\n {\n result.Append(\"<item>\").Append(item.GetRSSItem().InnerXml).Append(\"</item>\");\n }\n\n return result.ToString();\n"
},
{
"answer_id": 325571,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 0,
"selected": false,
"text": "<%=Html.RSSRepeater(ViewData.Model.GetIssues(null, null, \"\").Cast<IRSSable>()) %>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3193/"
] |
325,583 | <p>Strange error specific to a particular machine...</p>
<p>I have a app in which a combo box's text value is set to the path of a document (i.e...</p>
<pre><code>cmbAIDFile.Text = clsTonyToolkit.GetSetting("ExportAIDFile",gtypmetadata.gcnnCentral) & ""
</code></pre>
<p>Forget about all the GetSetting procedure etc, just that it returns a line of text and works fine.</p>
<p>This works properly on all machines except one. This particular Vista machine throws the error Run-time error 0 and throws the user out of the program regardless of the ErrorHandling on the procedure. Other Vista machines work fine.</p>
<p>Any answers to this confusing issue would be gratefully received.</p>
<hr>
<p>Thanks for your help.</p>
<p>The machine is running Vista Business 64 bit.</p>
<p>User has the ability to get admin rights through User Account Control which is turned on.</p>
<p>Following your prompts I have tried running the app as admin and getting all sorts of strange responses (missing files, dependencies not registered etc). Have uninstalled the app and will try reinstalling. I think shadow copies of the folder might be confusing things too.</p>
| [
{
"answer_id": 328554,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 3,
"selected": false,
"text": "Text ComboBox ComboBox Change LostFocus Validate Change LostFocus Validate Private Sub Combo1_Change()\n\n Dim a As Long\n a = 1/0 '<-- this will cause a divide-by-zero runtime error'\n\nEnd Sub\n\nPrivate Sub Command1_Click()\n\n On Error GoTo MyErrorHandler\n\n 'Change the combobox text.'\n 'This will cause the Change event to fire' \n\n Combo1.Text = \"test\"\n\n Exit Sub\n\nMyErrorHandler:\n 'This code will not be executed if an error occurs in Combo1_Change...'\n MsgBox \"My error-handler called.\"\n\nEnd Sub\n MyErrorHandler Combo1_Change cmbAIDFile_Change Erl Private Sub cmbAIDFile_Change()\n\n1000 On Error Goto ErrorHandler\n\n1010 DoSomething\n1020 DoSomethingElse\n\nErrorHandler:\n\n1030 Dim sErrMsg As String\n sErrMsg = \"A fatal error occurred.\" & vbCrLf & vbCrLf & _\n \"Method: cmbAIDFile_Change\" & vbCrLf & _\n \"Line: \" & Erl & vbCrLf & _ \n \"Err.Number: \" & Err.Number & vbCrLf & _\n \"Err.Description: \" & Err.Description\n\n1040 MsgBox sErrMsg, vbCritical+vbOKOnly, \"Fatal error\"\n\nEnd Sub \n"
},
{
"answer_id": 330795,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 1,
"selected": false,
"text": "Dim TempS as String\nTempS = clsTonyToolkit.GetSetting(\"ExportAIDFile\",gtypmetadata.gcnnCentral) & \"\"\ncmbAIDFile.Text = TempS\n"
},
{
"answer_id": 37267018,
"author": "Asitha Yomal",
"author_id": 5778565,
"author_profile": "https://Stackoverflow.com/users/5778565",
"pm_score": 0,
"selected": false,
"text": "Private Sub Command1_Click()\n On Error Resume Next\n 'Your combo-box code here\n On Error GoTo 0\nEnd Sub\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28959/"
] |
325,587 | <p>When working with MSSQL on Windows I was used to a very convenient feature called integrated authentication. In short, being authenticated in Windows can give you access to the database, so no need to give any specific password. Now I am developing an application on Linux with no user interaction; this application needs to access a mysql database for its own purposes, so how do I let it login? I have found that even though by default a root account is created in mysql, this root account has no connection with unix root, I can use it even if I am not a superuser in Linux, and the password is blank. Of course I can create a dedicated user account in mysql for the needs of my application, but in this case I need to hard-code the password somewhere, which is not nice. Once again - there is no user interaction in my application, so no chance for someone to enter the password. I have a distinct feeling that I am missing something important here. Thanks for any advice!</p>
| [
{
"answer_id": 325633,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 0,
"selected": false,
"text": "[Client]\nuser=ken\npassword=ken\nhost=localhost\ndatabase=foo\n"
},
{
"answer_id": 325638,
"author": "Ben",
"author_id": 11522,
"author_profile": "https://Stackoverflow.com/users/11522",
"pm_score": 0,
"selected": false,
"text": " $connection = mysql_connect('HOSTNAME', 'USERNAME', 'PASSWORD')\n or die('Could not connect: ' . mysql_error());\n\n mysql_select_db('DATABASE') or die('Could not select database');\n"
},
{
"answer_id": 52775775,
"author": "sdittmar",
"author_id": 6265950,
"author_profile": "https://Stackoverflow.com/users/6265950",
"pm_score": 0,
"selected": false,
"text": "CREATE USER 'user'@'localhost' IDENTIFIED WITH auth_socket;\n mysql -u user\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40548/"
] |
325,590 | <p>I write a Text Editor with Java , and I want to add Undo function to it </p>
<p>but without UndoManager Class , I need to use a Data Structure like Stack or LinkedList but the Stack class in Java use Object parameters e.g : push(Object o) , Not Push(String s)
I need some hints or links .
Thanks</p>
| [
{
"answer_id": 325596,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 4,
"selected": true,
"text": "Stack<String> stack = new Stack<String>();\nString string = \"someString\";\nstack.push(string);\n Stack stack = new Stack();\nString string = \"someString\";\nstack.push(string);\n\nString popString = (String) stack.pop(); // pop() returns an Object which needs to be downcasted\n"
},
{
"answer_id": 325609,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 1,
"selected": false,
"text": "Command cmd = (Command) stack.pop(); // same for peek() etc.\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22634/"
] |
325,602 | <p>I need a byte buffer class in Java for single-threaded use. I should be able to insert data at the back of the buffer and read data at the front, with an amortized cost of O(1). The buffer should resize when it's full, rather than throw an exception or something.</p>
<p>I could write one myself, but I'd be very surprised if this didn't exist yet in a standard Java package, and if it doesn't, I'd expect it to exist in some well-tested public library.</p>
<p>What would you recommend?</p>
| [
{
"answer_id": 907530,
"author": "dfa",
"author_id": 89266,
"author_profile": "https://Stackoverflow.com/users/89266",
"pm_score": 2,
"selected": false,
"text": "java.util.ArrayDeque<Byte> Queue"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7927/"
] |
325,616 | <p>What is the difference between the value and itemValue attribute of the radiobutton in Jsf?</p>
| [
{
"answer_id": 1328658,
"author": "Chris Dale",
"author_id": 39268,
"author_profile": "https://Stackoverflow.com/users/39268",
"pm_score": 3,
"selected": true,
"text": " <h:selectOneRadio value=\"\">\n <f:selectItem itemValue=\"TestValue\" itemLabel=\"TestLabel\" />\n</h:selectOneRadio>\n <table>\n <tr>\n <td>\n <input type=\"radio\" name=\"j_id_id9\" id=\"j_id_id9:0\" value=\"TestValue\" />\n <label for=\"j_id_id9:0\"> TestLabel</label>\n </td>\n </tr>\n</table>\n <h:selectOneRadio value=\"\">\n <f:selectItem itemValue=\"TestValue\" itemLabel=\"TestLabel\" value=\"#{TestBean.mySelect}\"/>\n</h:selectOneRadio> \n <h:selectOneRadio value=\"#{TestBean.selectedRadioValue}\">\n<f:selectItem itemValue=\"1\" itemLabel=\"1. radio one\" />\n<f:selectItem itemValue=\"2\" itemLabel=\"2. radio two\" />\n</h:selectOneRadio>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40933/"
] |
325,628 | <p>A typical approach to avoid two instances of the same script running simultaneously looks like this:</p>
<pre><code>[ -f ".lock" ] && exit 1
touch .lock
# do something
rm .lock
</code></pre>
<p>Is there a better way to lock on files from a shell-script, avoiding a race condition? Must directories be used instead?</p>
| [
{
"answer_id": 325645,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 6,
"selected": true,
"text": "noclobber -f touch if (set -o noclobber; echo \"$$\" > \"$lockfile\") 2> /dev/null; \nthen\n # This will cause the lock-file to be deleted in case of a\n # premature exit.\n trap 'rm -f \"$lockfile\"; exit $?' INT TERM EXIT\n\n # Critical Section: Here you'd place the code/commands you want\n # to be protected (i.e., not run in multiple processes at once).\n\n rm -f \"$lockfile\"\n trap - INT TERM EXIT\nelse\n echo \"Failed to acquire lock-file: $lockfile.\" \n echo \"Held by process $(cat $lockfile).\"\nfi\n"
},
{
"answer_id": 1571711,
"author": "jpastuszek",
"author_id": 42412,
"author_profile": "https://Stackoverflow.com/users/42412",
"pm_score": 3,
"selected": false,
"text": "exec 200>\"$LOCK_FILE\"\nflock -e -n 200 || exit 1\n #!/bin/bash\n\nexec 200>/nfs/mount/testlock\nflock -e 200\n\nNO=`cat /nfs/mount/counter`\necho \"$NO\"\nlet NO=NO+1\necho \"$NO\" > /nfs/mount/counter\n"
},
{
"answer_id": 63345758,
"author": "Paul Hodges",
"author_id": 8656552,
"author_profile": "https://Stackoverflow.com/users/8656552",
"pm_score": 0,
"selected": false,
"text": "-p mkdir $lockName || exit 1\n flock"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] |
325,629 | <p>[continued from <a href="https://stackoverflow.com/questions/323289">Is there a way to tell whether two COM interface references point at the same instance?</a>]</p>
<p>I've got references to <code>Inspector</code> objects from two different sources and need to be able to tell which item from one source corresponds to which item from the other source. However, none of the approaches I have been able to come up with so far worked (reliably):</p>
<ul>
<li><p>I couldn't simply <a href="https://stackoverflow.com/questions/323289">compare the <code>IUnknown</code> interfaces</a> as it seems that the <code>Inspectors.Item()</code> method is returning a reference to a created-on-the-fly proxy object rather than the inspector instance itself. Try it: Accessing the same index twice will return two distinctly different pointers.</p></li>
<li><p>Comparing <code>Inspector.CurrentItem.EntryID</code> is no good either. A new/unsaved items' <code>EntryID</code> is always blank and there could potentially be more than one unsaved item open at a time.</p></li>
<li><p><code>Inspector.Caption</code> or <code>Inspector.CurrentItem.Subject</code> is likewise ambiguous.</p></li>
<li><p>Temporarily setting <code>Inspector.CurrentItem.Subject</code> (or any other item property really) to an unambiguous value and then looking for that in the other list kind of works but has the annoying side-effect of marking the item in the inspector as "dirty", i.e. upon closing the inspector again the user will be asked to save the item (even if he was just viewing a received mail).</p></li>
</ul>
<p>Any other ideas?</p>
<hr>
<p><em>Context:</em></p>
<p>I'm trying to work around the well-known bug/feature that new email messages initiated via Simple MAPI (e.g. Send to>Mail recipient in Explorer context menu) do not generate an <code>Inspectors.NewInspector</code> event thus making it impossible to add any addin functionality to those inspectors (e.g. adding toolbar buttons or executing code on message creation). In my COM-addin I've got an internal list of wrapper objects to catch <code>Inspector</code>-events. Items are added and removed to this list by monitoring the <code>Inspectors.NewInspector</code> and <code>Inspector.Close</code> events.</p>
<p>As an alternative approach I'm using a shell hook: I am now able to get notified whenever a new inspector window is created or destroyed so that appears to be a good spot to jump in and match my internal list of wrapper objects with the <code>Application.Inspectors</code> collection and add or remove new or orphaned wrapper objects accordingly.</p>
| [
{
"answer_id": 2779812,
"author": "Oliver Giesen",
"author_id": 9784,
"author_profile": "https://Stackoverflow.com/users/9784",
"pm_score": 2,
"selected": true,
"text": "Inspector.CurrentItem.CreationTime"
},
{
"answer_id": 8040995,
"author": "JimmyPena",
"author_id": 190829,
"author_profile": "https://Stackoverflow.com/users/190829",
"pm_score": 0,
"selected": false,
"text": "Debug.Print InspectorObj1 Is InspectorObj2\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9784/"
] |
325,648 | <p>Java 1.5, Linux</p>
<p>I do have a screen which contains different textareas and textfields.
I do have acess to the application frame, but not to the components inside the frame, because i only get an implementation of an interface.</p>
<p>When i try to add german umlauts i see a rectangle in the text component, because the character is not supported.
Which font or which system-propertiy i have to set to support "umlauts" under linux.
On windows the characters are shown correctly.</p>
| [
{
"answer_id": 325855,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 0,
"selected": false,
"text": "echo $TERM --> vt100\n 'find / | grep font'\n"
},
{
"answer_id": 330437,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 0,
"selected": false,
"text": "Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39062/"
] |
325,654 | <p>I want to change background color of Datagrid header in Silverlight.</p>
| [
{
"answer_id": 330697,
"author": "David Padbury",
"author_id": 26401,
"author_profile": "https://Stackoverflow.com/users/26401",
"pm_score": 3,
"selected": false,
"text": "<data:DataGrid x:Name=\"grid\">\n <data:DataGrid.ColumnHeaderStyle>\n <Style \n xmlns:primitives=\"clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data\" \n xmlns:vsm=\"clr-namespace:System.Windows;assembly=System.Windows\"\n TargetType=\"primitives:DataGridColumnHeader\" >\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"primitives:DataGridColumnHeader\">\n <Grid Name=\"Root\">\n <vsm:VisualStateManager.VisualStateGroups>\n <vsm:VisualStateGroup x:Name=\"SortStates\" >\n <vsm:VisualStateGroup.Transitions>\n <vsm:VisualTransition GeneratedDuration=\"00:00:0.1\" />\n </vsm:VisualStateGroup.Transitions>\n <vsm:VisualState x:Name=\"Unsorted\" />\n <vsm:VisualState x:Name=\"SortAscending\">\n <Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"SortIcon\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"1.0\" />\n </Storyboard>\n </vsm:VisualState>\n <vsm:VisualState x:Name=\"SortDescending\">\n <Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"SortIcon\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"1.0\" />\n <DoubleAnimation Storyboard.TargetName=\"SortIconTransform\" Storyboard.TargetProperty=\"ScaleY\" Duration=\"0\" To=\"-.9\" />\n </Storyboard>\n </vsm:VisualState>\n </vsm:VisualStateGroup>\n </vsm:VisualStateManager.VisualStateGroups>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"Auto\" />\n </Grid.RowDefinitions>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"Auto\" />\n </Grid.ColumnDefinitions>\n <Rectangle x:Name=\"BackgroundRectangle\" Stretch=\"Fill\" Fill=\"LightBlue\" Grid.ColumnSpan=\"2\" Grid.RowSpan=\"2\" />\n <ContentPresenter Grid.RowSpan=\"2\" Content=\"{TemplateBinding Content}\" Cursor=\"{TemplateBinding Cursor}\" HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\" Margin=\"{TemplateBinding Padding}\" />\n <Rectangle Name=\"VerticalSeparator\" Grid.RowSpan=\"2\" Grid.Column=\"2\" Width=\"1\" VerticalAlignment=\"Stretch\" Fill=\"{TemplateBinding SeparatorBrush}\" Visibility=\"{TemplateBinding SeparatorVisibility}\" />\n <Path Grid.RowSpan=\"2\" Name=\"SortIcon\" RenderTransformOrigin=\".5,.5\" HorizontalAlignment=\"Left\" VerticalAlignment=\"Center\" Opacity=\"0\" Grid.Column=\"1\" Stretch=\"Uniform\" Width=\"8\" Data=\"F1 M -5.215,6.099L 5.215,6.099L 0,0L -5.215,6.099 Z \">\n <Path.Fill>\n <SolidColorBrush Color=\"#FF444444\" />\n </Path.Fill>\n <Path.RenderTransform>\n <TransformGroup>\n <ScaleTransform x:Name=\"SortIconTransform\" ScaleX=\".9\" ScaleY=\".9\" />\n </TransformGroup>\n </Path.RenderTransform>\n </Path>\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n </data:DataGrid.ColumnHeaderStyle>\n</data:DataGrid>\n"
},
{
"answer_id": 884011,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Extends the DataGrid so that it's possible to access the template objects\n/// </summary>\npublic class DataGridEx : System.Windows.Controls.DataGrid\n{\n /// <summary>\n /// Exposes Template items\n /// </summary>\n public Object GetTemplateObject(String name)\n {\n return this.GetTemplateChild(name);\n }\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,667 | <p>Does anyone of you know, if and if so, how can I check, with my application code, if a server has ssl enabled or not?</p>
| [
{
"answer_id": 325681,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 2,
"selected": false,
"text": "public bool IsSecureConnection()\n{\n return HttpContext.Current.Request.IsSecureConnection || \n HttpContext.Current.Request.Headers[\"HTTP_X_SSL_REQUEST\"].Equals(\"1\");\n}\n"
},
{
"answer_id": 325833,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 5,
"selected": true,
"text": "stackoverflow.com stackoverflow.com >>> import urllib2\n>>> urllib2.urlopen('https://stackoverflow.com')\nTraceback (most recent call last):\n...\nurllib2.URLError: <urlopen error (10060, 'Operation timed out')>\n>>> html = urllib2.urlopen('http://stackoverflow.com').read()\n>>> len(html)\n146271\n>>> \n stackoverflow.com stackoverflow.com"
},
{
"answer_id": 3666025,
"author": "johnsyweb",
"author_id": 78845,
"author_profile": "https://Stackoverflow.com/users/78845",
"pm_score": 3,
"selected": false,
"text": "bash-3.2$ echo ^D | telnet www.google.com https\nTrying 66.102.11.104...\nConnected to www.l.google.com.\nEscape character is '^]'.\nConnection closed by foreign host.\nbash-3.2$ echo ^D | telnet www.stackoverflow.com https\nTrying 69.59.196.211...\ntelnet: connect to address 69.59.196.211: Connection refused\ntelnet: Unable to connect to remote host\n"
},
{
"answer_id": 38318254,
"author": "Guy Lowe",
"author_id": 748133,
"author_profile": "https://Stackoverflow.com/users/748133",
"pm_score": 2,
"selected": false,
"text": " [TestMethod]\n public void DetectSslSupport()\n {\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"https://www.someinsecuresite.com\");\n try\n {\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n //some sites like stackoverflow will perform a service side redirect to the http site before the browser/request can throw an errror.\n Assert.IsTrue(response.ResponseUri.Scheme == \"https\");\n }\n }\n catch (WebException)//\"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.\"}\n {\n Assert.IsTrue(false);\n }\n }\n"
},
{
"answer_id": 58754527,
"author": "Yan Foto",
"author_id": 2295964,
"author_profile": "https://Stackoverflow.com/users/2295964",
"pm_score": 2,
"selected": false,
"text": "s_client openssl openssl s_client -quiet -connect google.com:443\n 0 echo \"$?\" 443"
},
{
"answer_id": 69614078,
"author": "Petr Javorik",
"author_id": 5216949,
"author_profile": "https://Stackoverflow.com/users/5216949",
"pm_score": 0,
"selected": false,
"text": "http.parsed 10.31.11.5:443\n10.31.11.25:443\n10.31.11.37:55000\n10.31.11.116:80\n parallel -j10 'curl -k https://{} 1> /dev/null 2> /dev/null && echo https://{}' :::: http.parsed\n https://10.31.11.5:443\nhttps://10.31.11.25:443\nhttps://10.31.11.37:55000\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40077/"
] |
325,669 | <p>I think I might be approaching this in the wrong way, so I would appreciate any comments/guidance. Hopefully I can explain coherently enough what I am trying to achieve:</p>
<ul>
<li><p>I want to create a block of HTML
(e.g. a box containing a user's
profile), which I will load as part
of my layout on most pages that I
generate.</p></li>
<li><p>I would also like to be able to
re-generate the content within this
box on its own from a separate URL. This is so I can update the box with an AJAX call.</p></li>
<li><p>I don't want to duplicate the code
that creates this HTML.</p></li>
</ul>
<p>I appreciate that I could initally load this box using an AJAX call, but that would seem to me to add an unnecessary call to the server?</p>
<p>The way I thought I could do it is by having a method in my controller that just renders this block of HTML, but how would I then request the output from this method within another controller / view?</p>
<p>How would you approach this?</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 325707,
"author": "foxy",
"author_id": 30119,
"author_profile": "https://Stackoverflow.com/users/30119",
"pm_score": 4,
"selected": true,
"text": "$user_html = $this->load->view('user_view', $user_data, true);\n $data['user_block'] = $user_html;\n$this->load->view('page_view', $data);\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22224/"
] |
325,677 | <p>I need to receive the key press events during cell editing in <code>DataGridView</code> control.</p>
<p>From what I have found on the net the <code>DataGridView</code> is designed to pass all key events from <code>DataGridView</code> to the cell editing control and you cannot get these events easily.</p>
<p>I found this <a href="http://www.codeproject.com/KB/grid/DataGridCellEvents.aspx" rel="noreferrer">piece of code</a> that traps those events for <code>DataGrid</code> control, but that does not work for <code>DataGridView</code>.</p>
| [
{
"answer_id": 328055,
"author": "Eren Aygunes",
"author_id": 27980,
"author_profile": "https://Stackoverflow.com/users/27980",
"pm_score": 2,
"selected": false,
"text": "class KeyPressAwareDataGridView : DataGridView\n{\n protected override void OnControlAdded(ControlEventArgs e)\n {\n SubscribeEvents(e.Control);\n base.OnControlAdded(e);\n }\n\n protected override void OnControlRemoved(ControlEventArgs e)\n {\n UnsubscribeEvents(e.Control);\n base.OnControlRemoved(e);\n }\n\n private void SubscribeEvents(Control control)\n { \n control.KeyPress += new KeyPressEventHandler(control_KeyPress);\n control.ControlAdded += new ControlEventHandler(control_ControlAdded);\n control.ControlRemoved += new ControlEventHandler(control_ControlRemoved);\n\n foreach (Control innerControl in control.Controls)\n {\n SubscribeEvents(innerControl);\n }\n }\n\n private void UnsubscribeEvents(Control control)\n {\n control.KeyPress -= new KeyPressEventHandler(control_KeyPress);\n control.ControlAdded -= new ControlEventHandler(control_ControlAdded);\n control.ControlRemoved -= new ControlEventHandler(control_ControlRemoved);\n\n foreach (Control innerControl in control.Controls)\n {\n UnsubscribeEvents(innerControl);\n }\n }\n\n private void control_ControlAdded(object sender, ControlEventArgs e)\n {\n SubscribeEvents(e.Control);\n }\n\n private void control_ControlRemoved(object sender, ControlEventArgs e)\n {\n UnsubscribeEvents(e.Control);\n }\n\n private void control_KeyPress(object sender, KeyPressEventArgs e)\n {\n // Apply your logic here whether this is the key pressed event you need.\n // (e.g. \"if(SelectedCells != null)\")\n MessageBox.Show(e.KeyChar.ToString());\n }\n}\n"
},
{
"answer_id": 334098,
"author": "Viesturs",
"author_id": 1660,
"author_profile": "https://Stackoverflow.com/users/1660",
"pm_score": 3,
"selected": true,
"text": "class KeyPressAwareDataGridView : DataGridView\n{\n\n protected override void OnControlAdded(ControlEventArgs e)\n {\n this.subscribeEvents(e.Control);\n base.OnControlAdded(e);\n }\n\n protected override void OnControlRemoved(ControlEventArgs e)\n {\n this.unsubscribeEvents(e.Control);\n base.OnControlRemoved(e);\n }\n\n protected override bool ProcessDataGridViewKey(KeyEventArgs e)\n {\n bool procesedInternally = false;\n\n if (this.keyPressHook != null)\n {\n this.keyPressHook(this, e);\n procesedInternally = e.SuppressKeyPress;\n }\n\n if (procesedInternally)\n {\n return true;\n }\n else\n {\n return base.ProcessDataGridViewKey(e);\n }\n }\n\n\n private void subscribeEvents(Control control)\n {\n control.KeyDown += new KeyEventHandler(this.control_KeyDown);\n control.ControlAdded += new ControlEventHandler(this.control_ControlAdded);\n control.ControlRemoved += new ControlEventHandler(this.control_ControlRemoved);\n\n foreach (Control innerControl in control.Controls)\n {\n this.subscribeEvents(innerControl);\n }\n }\n\n private void unsubscribeEvents(Control control)\n {\n control.KeyDown -= new KeyEventHandler(this.control_KeyDown);\n control.ControlAdded -= new ControlEventHandler(this.control_ControlAdded);\n control.ControlRemoved -= new ControlEventHandler(this.control_ControlRemoved);\n\n foreach (Control innerControl in control.Controls)\n {\n this.unsubscribeEvents(innerControl);\n }\n }\n\n private void control_ControlAdded(object sender, ControlEventArgs e)\n {\n this.subscribeEvents(e.Control);\n }\n\n private void control_ControlRemoved(object sender, ControlEventArgs e)\n {\n this.unsubscribeEvents(e.Control);\n }\n\n private void control_KeyDown(object sender, KeyEventArgs e)\n {\n if (this.keyPressHook != null)\n {\n this.keyPressHook(this, e);\n }\n }\n\n public event KeyEventHandler keyPressHook;\n\n}\n"
},
{
"answer_id": 395502,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "private: System::Boolean fIsNonNumeric;\nprivate: static System::Windows::Forms::KeyEventHandler^ EventKeyDown = nullptr;\nprivate: static System::Windows::Forms::KeyPressEventHandler^ EventKeyPress = nullptr;\nprivate: System::Void dataGridView_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) \n{\n fIsNonNumeric= false;\n\n // Determine whether the keystroke is a number from the top of the keyboard.\n if ( e->KeyCode < Keys::D0 || e->KeyCode > Keys::D9 )\n {\n // Determine whether the keystroke is a number from the keypad.\n if ( e->KeyCode < Keys::NumPad0 || e->KeyCode > Keys::NumPad9 )\n {\n // Determine whether the keystroke is a backspace.\n if ( e->KeyCode != Keys::Back )\n {\n // A non-numerical keystroke was pressed.\n // Set the flag to true and evaluate in KeyPress event.\n fIsNonNumeric = true;\n }\n }\n }\n}\n\nprivate: System::Void dataGridView_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) \n{\n // Should we stop the character from being entered...?\n if ( fIsNonNumeric == true )\n e->Handled = true;\n}\n\nprivate: System::Void dataGridView_Machines_EditingControlShowing(System::Object^ sender, System::Windows::Forms::DataGridViewEditingControlShowingEventArgs^ e) \n{\n if (nullptr == EventKeyDown)\n EventKeyDown = (gcnew System::Windows::Forms::KeyEventHandler( this, &ProjectForm::dataGridView_KeyDown ));\n\n if (nullptr == EventKeyPress)\n EventKeyPress = (gcnew System::Windows::Forms::KeyPressEventHandler( this, &ProjectForm::dataGridView_KeyPress ));\n\n e->Control->KeyDown -= EventKeyDown;\n e->Control->KeyPress -= EventKeyPress;\n\n e->Control->KeyDown += EventKeyDown;\n e->Control->KeyPress += EventKeyPress;\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1660/"
] |
325,682 | <p>I need a RegExp which matches a word or multiple words in quotes.</p>
<p>[\w]* matches a word</p>
<p>"[\w\W&&[^"]]*" matches multiple words in quotes.</p>
<p>(btw, not sure why \w\W works, but not a simple . (which should match all characters)</p>
<p>So how do i combine these two regexp?</p>
| [
{
"answer_id": 325694,
"author": "genehack",
"author_id": 39933,
"author_profile": "https://Stackoverflow.com/users/39933",
"pm_score": 3,
"selected": false,
"text": "\"[^\"]+\""
},
{
"answer_id": 325716,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "\"\\s*((?:\\w(?!\\s+\")+|\\s(?!\\s*\"))+\\w)\\s*\"\n \"[^\"]+\" ^\" \\w [a-zA-Z_0-9] \\w \" ee eee e ee \"\n ee eee e ee\n (?!\\s+\")"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40254/"
] |
325,685 | <p>I am new to Ajax.Net.</p>
<p>I want to know how to access data send from Ajax POST method.
(ie)AjaxObject.send("Some Data")</p>
<p>How to access that "Some Data" in form?</p>
<p>I can access same when i used GET method and passed data in Querystring.
like Request.Querystring("name") in ASP.</p>
| [
{
"answer_id": 1542033,
"author": "kristian",
"author_id": 20377,
"author_profile": "https://Stackoverflow.com/users/20377",
"pm_score": 0,
"selected": false,
"text": "Request.Form(\"name\")\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
325,690 | <p>how can access the binary data file(.DAT). i am using geonames API. can anyone help me? </p>
| [
{
"answer_id": 327183,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "BinaryReader FileStream fs = File.Open(Environment.CurrentDirectory + @\"\\settings.bin\", FileMode.Open);\nBinaryReader reader = new BinaryReader(fs);\n\nlong number = reader.ReadInt64();\nbyte[] bytes = reader.ReadBytes(3);\nstring s = reader.ReadString();\n\nreader.Close();\nfs.Close();\n\nConsole.WriteLine(number);\nforeach (byte b in bytes)\n{\n Console.Write(\"[{0}]\", b);\n}\nConsole.WriteLine();\nConsole.WriteLine(s);\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41584/"
] |
325,692 | <p>I am dealing with a large codebase that has a lot of classes and a lot of abstract methods on these classes. I am interested in peoples opinions about what I should do in the following situation.</p>
<p>If I have a class Parent-A with an abstract method. There will only be 2 children. If Child-B implements AbstractMethodA but Child-B does not as it doesnt apply.</p>
<p>Should I</p>
<ol>
<li>Remove the abstract keyword from parent and use virtual or dynamic?</li>
<li>Provide a empty implementation of the method.</li>
<li>Provide an implementation that raises an error if called.</li>
<li>Ignore the warning.</li>
</ol>
<p>Edit: Thanks for all the answers. It confirmed my suspicion that this shouldn't happen. After further investigation it turns out the methods weren't used at all so I have removed them entirely.</p>
| [
{
"answer_id": 325771,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 1,
"selected": false,
"text": "[Obsolete(\"This class does not implement this method\", true)]\npublic override string MyReallyImportantMethod()\n{\n throw new NotImplementedException(\"This class does not implement this method.\");\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6244/"
] |
325,706 | <p>The following code produces an error hr=0x80020005 (wrong type).</p>
<pre><code>#import <msi.dll>
using namespace WindowsInstaller;
main()
{
::CoInitialize(NULL);
InstallerPtr pInstaller("WindowsInstaller.Installer");
DatabasePtr pDB = pInstaller->OpenDatabase(
"c:\\foo\\bar.msi",
msiOpenDatabaseModeTransact);
}
</code></pre>
<p>I think the reason is that behind the scene, there is MsiOpenDatabase(), which
take a LPCTSTR as second argument.
This second argument can be MSIDBOPEN_TRANSACT whose definition is</p>
<pre><code>#define MSIDBOPEN_TRANSACT (LPCTSTR)1
</code></pre>
<p>I do not know if it is possible to give a variant with the good inner type as second argument. The <code>_variant_t</code> constructor does many checks, so I can't disguise an int into
a char* so easily.</p>
<p>Has anyone tried to use this method in C++?</p>
<p><strong>Edit:</strong></p>
<p>My version of msi.dll is 3.1.4000.2805, my system is XP SP 2, and the code is supposed to run on any machine with XP or Vista.</p>
<p>urls to MSDN articles are welcome.</p>
<p>On the same machine, the call to the low-level equivalent:</p>
<pre><code>MsiOpenDatabase("c:\\foo\\bar.msi", MSIDBOPEN_TRANSACT);
</code></pre>
<p>works perfectly.</p>
| [
{
"answer_id": 507783,
"author": "Fabien",
"author_id": 21132,
"author_profile": "https://Stackoverflow.com/users/21132",
"pm_score": 3,
"selected": true,
"text": "DatabasePtr pDB = pInstaller->OpenDatabase(\n \"c:\\\\foo\\\\bar.msi\", \n (long)msiOpenDatabaseModeTransact);\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21132/"
] |
325,725 | <p>Starting with the following LINQ query:</p>
<pre><code>from a in things
where a.Id == b.Id &&
a.Name == b.Name &&
a.Value1 == b.Value1 &&
a.Value2 == b.Value2 &&
a.Value3 == b.Value3
select a;
</code></pre>
<p>How can I remove (at runtime) one or more of the conditions in the where clause in order to obtain queries similar to the following ones:</p>
<pre><code>from a in things
where a.Id == b.Id &&
a.Name == b.Name &&
a.Value2 == b.Value2 &&
a.Value3 == b.Value3
select a;
</code></pre>
<p>Or</p>
<pre><code>from a in things
where
a.Name == b.Name &&
a.Value3 == b.Value3
select a;
</code></pre>
| [
{
"answer_id": 325739,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "from a in things \nwhere a.Id == b.Id \nwhere a.Name == b.Name \nwhere a.Value1 == b.Value1\nwhere a.Value2 == b.Value2\nwhere a.Value3 == b.Value3 \nselect a;\n things.Where(a => a.Id == b.Id)\n .Where(a => a.Name == b.Name)\n .Where(a => a.Value1 == b.Value1)\n .Where(a => a.Value2 == b.Value2)\n .Where(a => a.Value1 == b.Value3);\n IQueryable<Whatever> query = things;\nif (useId) {\n query = query.Where(a => a.Id == b.Id);\n}\nquery = query.Where(a => a.Name == b.Name);\nif (checkValue1) {\n query = query.Where(a => a.Value1 == b.Value1);\n}\n// etc\n"
},
{
"answer_id": 325758,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 1,
"selected": false,
"text": "bool executeValue1Condition = true;\nbool executeValue2Condition = true;\nbool executeValue3Condition = true;\n\nvar q = from a in things \nwhere a.Id == b.Id && \na.Name == b.Name && \n(a.Value1 == b.Value1 || executeValue1Condition) && \n(a.Value2 == b.Value2 || executeValue2Condition) && \n(a.Value3 == b.Value3 || executeValue3Condition) \nselect a;\n\nexecuteValue1Condition = false;\nq = q.Select(i => i);\n"
},
{
"answer_id": 325766,
"author": "Adrian Zanescu",
"author_id": 35128,
"author_profile": "https://Stackoverflow.com/users/35128",
"pm_score": 0,
"selected": false,
"text": " IQueryable<MyClass> things = null;\n MyClass b = new MyClass();\n\n Expression<Func<MyClass, bool>> whereExp = a => a.Id == b.Id && a.Name == b.Name;\n // process where expression here. it's just an expression tree. traverse it and\n // remove nodes as desired.\n var result = things.Where(whereExp).Select(a => a);\n IQueryable<MyClass> things = null;\nMyClass b = new MyClass();\n\nExpression<Func<MyClass, bool>> whereExp;\nExpression<Func<MyClass, bool>> exp1 = a => a.Id == b.Id;\nExpression<Func<MyClass, bool>> exp2 = a => a.Name == b.Name;\nwhereExp = Expression.Lambda<Func<MyClass, bool>>(Expression.And(exp1, exp2), Expression.Parameter(typeof(MyClass), \"a\"));\n\nvar result = things.Where(whereExp).Select(a => a);\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
] |
325,733 | <p>In Apple's NSObject documentation, NSZoneFree is called in the - (void)dealloc example code:</p>
<pre><code>- (void)dealloc {
[companion release];
NSZoneFree(private, [self zone])
[super dealloc];
}
</code></pre>
<p>You can find it in context <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/doc/uid/20000050-dealloc" rel="nofollow noreferrer">over here</a>.</p>
<p>I never had the notion that I should be calling NSZoneFree in my own NSObject subclasses (or what NS_WhateverClass_ subclasses) and can't find anything conclusive on the topic anywhere in the docs.</p>
<p>All I can find about using NSZoneFree is a brief mention in the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Concepts/Zones.html" rel="nofollow noreferrer">Memory Management Programming Guide</a>, and an explanation of the function in the <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSZoneFree" rel="nofollow noreferrer">Foundation Functions Reference</a>, but none of these docs make it clear to me whether I should worry about it in the context of a dealloc method.</p>
<p>Can anybody clarify when I should put an NSZoneFree call in my own classes' dealloc implementations?</p>
<p>Edit: Thanks for your replies, it's clearer to me now :) — Dirk</p>
| [
{
"answer_id": 327114,
"author": "Jim Puls",
"author_id": 6010,
"author_profile": "https://Stackoverflow.com/users/6010",
"pm_score": 3,
"selected": true,
"text": "NSZoneFree() NSZoneMalloc() -release -alloc -copy CFRelease() CFRetain() CF*Create*() free() malloc() calloc() private NSZoneMalloc()"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24051/"
] |
325,734 | <p>When writing a class do you group members variables of the same type together? Is there any benefit to doing so? For example:</p>
<pre><code>class Foo
{
private:
bool a_;
bool b_;
int c_;
int d_;
std::string e_;
std::string f_;
...
};
</code></pre>
<p>As opposed to:</p>
<pre><code>class Bar
{
private:
std::string e_;
bool a_;
int d_;
bool b_;
std::string f_;
int c_;
.
</code></pre>
<p>..
};</p>
<p>Or do you simply have them in the order they were added?</p>
| [
{
"answer_id": 325740,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 5,
"selected": true,
"text": "class Foo\n{\nprivate:\n std::string peach;\n bool banana;\n int apple;\n\n int red;\n std::string green;\n std::string blue;\n ...\n};\n"
},
{
"answer_id": 326030,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 1,
"selected": false,
"text": "bool a_, b_, c_;\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
325,756 | <p>I need a Guid property in some attribute class like this:</p>
<pre><code>public class SomeAttribute : Attribute {
private Guid foreignIdentificator;
public Guid ForeignIdentificator {
get { return this.foreignIdentificator; }
set { this.foreignIdentificator = value; }
}
}
</code></pre>
<p>But in attribute definition I can use only primitive types, which are constants ( I understand why, and it's make me sense ). The workaround can be definition "ForeignIdentificator" as string, and creating Guid in runtime:</p>
<pre><code>public class SomeAttribute : Attribute {
private string foreignIdentificator;
public string ForeignIdentificator {
get { return this.foreignIdentificator; }
set { this.foreignIdentificator = value; }
}
public Guid ForeignIdentificatorGuid {
get { return new Guid( ForeignIdentificator ); }
}
}
</code></pre>
<p>Unahppily I loose check for type safety. The "ForeignIdentificator" property can contains any string value and during creating Guid will be thrown exception at runtime, not at compile time.</p>
<p>I know the compiler checks string value for "System.Runtime.InteropServices.GuidAttribute" for "Guid compatibility". This check is exactly what I need, but I don't know if this check i hardcoded in compiler or can me explicitly defined ( and how ).</p>
<p>Do you know some way, how to secure "Guid compatibilty" check for attributes? Or some another way, how to reach type safe Guid definition in attributes?
Thanks.</p>
| [
{
"answer_id": 325798,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "System.Guid [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\nsealed class MyGuidAttribute : Attribute\n{\n public Guid Guid { get; private set; }\n\n //\n // Summary:\n // Initializes a new instance of the System.Guid class using the specified array\n // of bytes.\n //\n // Parameters:\n // b:\n // A 16 element byte array containing values with which to initialize the GUID.\n //\n // Exceptions:\n // System.ArgumentNullException:\n // b is null.\n //\n // System.ArgumentException:\n // b is not 16 bytes long.\n public MyGuidAttribute(byte[] b)\n {\n this.Guid = new Guid(b);\n }\n //\n // Summary:\n // Initializes a new instance of the System.Guid class using the value represented\n // by the specified string.\n //\n // Parameters:\n // g:\n // A System.String that contains a GUID in one of the following formats ('d'\n // represents a hexadecimal digit whose case is ignored): 32 contiguous digits:\n // dddddddddddddddddddddddddddddddd -or- Groups of 8, 4, 4, 4, and 12 digits\n // with hyphens between the groups. The entire GUID can optionally be enclosed\n // in matching braces or parentheses: dddddddd-dddd-dddd-dddd-dddddddddddd -or-\n // {dddddddd-dddd-dddd-dddd-dddddddddddd} -or- (dddddddd-dddd-dddd-dddd-dddddddddddd)\n // -or- Groups of 8, 4, and 4 digits, and a subset of eight groups of 2 digits,\n // with each group prefixed by \"0x\" or \"0X\", and separated by commas. The entire\n // GUID, as well as the subset, is enclosed in matching braces: {0xdddddddd,\n // 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} All braces, commas,\n // and \"0x\" prefixes are required. All embedded spaces are ignored. All leading\n // zeroes in a group are ignored. The digits shown in a group are the maximum\n // number of meaningful digits that can appear in that group. You can specify\n // from 1 to the number of digits shown for a group. The specified digits are\n // assumed to be the low order digits of the group.\n //\n // Exceptions:\n // System.ArgumentNullException:\n // g is null.\n //\n // System.FormatException:\n // The format of g is invalid.\n //\n // System.OverflowException:\n // The format of g is invalid.\n public MyGuidAttribute(string g)\n {\n this.Guid = new Guid(g);\n }\n //\n // Summary:\n // Initializes a new instance of the System.Guid class using the specified integers\n // and byte array.\n //\n // Parameters:\n // a:\n // The first 4 bytes of the GUID.\n //\n // b:\n // The next 2 bytes of the GUID.\n //\n // c:\n // The next 2 bytes of the GUID.\n //\n // d:\n // The remaining 8 bytes of the GUID.\n //\n // Exceptions:\n // System.ArgumentNullException:\n // d is null.\n //\n // System.ArgumentException:\n // d is not 8 bytes long.\n public MyGuidAttribute(int a, short b, short c, byte[] d)\n {\n this.Guid = new Guid(a, b, c, d);\n }\n //\n // Summary:\n // Initializes a new instance of the System.Guid class using the specified integers\n // and bytes.\n //\n // Parameters:\n // a:\n // The first 4 bytes of the GUID.\n //\n // b:\n // The next 2 bytes of the GUID.\n //\n // c:\n // The next 2 bytes of the GUID.\n //\n // d:\n // The next byte of the GUID.\n //\n // e:\n // The next byte of the GUID.\n //\n // f:\n // The next byte of the GUID.\n //\n // g:\n // The next byte of the GUID.\n //\n // h:\n // The next byte of the GUID.\n //\n // i:\n // The next byte of the GUID.\n //\n // j:\n // The next byte of the GUID.\n //\n // k:\n // The next byte of the GUID.\n public MyGuidAttribute(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)\n {\n this.Guid = new Guid(a, b, c, d, e, f, g, h, i, j, k);\n }\n //\n // Summary:\n // Initializes a new instance of the System.Guid class using the specified unsigned\n // integers and bytes.\n //\n // Parameters:\n // a:\n // The first 4 bytes of the GUID.\n //\n // b:\n // The next 2 bytes of the GUID.\n //\n // c:\n // The next 2 bytes of the GUID.\n //\n // d:\n // The next byte of the GUID.\n //\n // e:\n // The next byte of the GUID.\n //\n // f:\n // The next byte of the GUID.\n //\n // g:\n // The next byte of the GUID.\n //\n // h:\n // The next byte of the GUID.\n //\n // i:\n // The next byte of the GUID.\n //\n // j:\n // The next byte of the GUID.\n //\n // k:\n // The next byte of the GUID.\n [CLSCompliant(false)]\n public MyGuidAttribute(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)\n {\n this.Guid = new Guid(a, b, c, d, e, f, g, h, i, j, k);\n }\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20382/"
] |
325,765 | <p>Can jQuery ajax made browser request a new location in redirect header send by server?</p>
| [
{
"answer_id": 326041,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 2,
"selected": false,
"text": "$.get('page.php', { GETvar : 'redirectUrl' }, function(data, textString){ \n if (textString == \"succes\") { //Succes!\n document.location = data;\n }\n else{ // failure }\n});\n var first = true;\nfunction setRedirect (url) {\n hiddenframe.location = url;\n}\nfunction readyLoad() {\n if( first == true ) { first = false; return false; }\n else {\n alert( 'ready loading, was redireced too:' + myFrame.location.href );\n //Use new location code\n}\n}\n"
},
{
"answer_id": 326129,
"author": "Victor",
"author_id": 14514,
"author_profile": "https://Stackoverflow.com/users/14514",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"http://jqueryjs.googlecode.com/files/jquery-1.2.6.js\"/>\n $.get(\"http://jigsaw.w3.org/HTTP/300/301.html\", function(r){\n alert(r);\n});\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441493/"
] |
325,788 | <p>I'm trying to change assembly binding (from one version to another) dynamically.</p>
<p>I've tried this code but it doesn't work:</p>
<pre><code> Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection assemblyBindingSection = config.Sections["assemblyBinding"];
assemblyBindingSection.SectionInformation.ConfigSource = "bindingConf.xml";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("assemblyBinding");
</code></pre>
<p>with <code>bindingConf.xml</code> containing the assemblyBinding section configuration.</p>
<p>So can a change this section at runtime? how to do it? What alternatives do I have?</p>
| [
{
"answer_id": 326011,
"author": "Eric Rosenberger",
"author_id": 41624,
"author_profile": "https://Stackoverflow.com/users/41624",
"pm_score": 6,
"selected": true,
"text": "AppDomain.AssemblyResolve using System.Reflection;\n\nstatic Program()\n{\n AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)\n {\n AssemblyName requestedName = new AssemblyName(e.Name);\n\n if (requestedName.Name == \"AssemblyNameToRedirect\")\n {\n // Put code here to load whatever version of the assembly you actually have\n\n return Assembly.LoadFrom(\"RedirectedAssembly.DLL\");\n }\n else\n {\n return null;\n }\n };\n}\n"
},
{
"answer_id": 330283,
"author": "Julien Hoarau",
"author_id": 12248,
"author_profile": "https://Stackoverflow.com/users/12248",
"pm_score": 2,
"selected": false,
"text": "private void ModifyRuntimeAppConfig()\n{\n XmlDocument modifiedRuntimeSection = GetResource(\"Framework35Rebinding\");\n\n if(modifiedRuntimeSection != null)\n {\n Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n ConfigurationSection assemblyBindingSection = config.Sections[\"runtime\"];\n\n assemblyBindingSection.SectionInformation.SetRawXml(modifiedRuntimeSection.InnerXml);\n config.Save(ConfigurationSaveMode.Modified);\n ConfigurationManager.RefreshSection(\"runtime\");\n }\n}\n <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"Microsoft.Build.Framework\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\"/>\n <bindingRedirect oldVersion=\"0.0.0.0-99.9.9.9\" newVersion=\"3.5.0.0\"/>\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"Microsoft.CompactFramework.Build.Tasks\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\"/>\n <bindingRedirect oldVersion=\"0.0.0.0-99.9.9.9\" newVersion=\"9.0.0.0\"/>\n </dependentAssembly>\n </assemblyBinding>\n</runtime>\n <?xml version=\"1.0\"?>\n<configuration>\n <startup>\n <supportedRuntime version=\"v2.0.50727\"/>\n </startup>\n <runtime>\n </runtime>\n</configuration>\n RefreshSection(\"runtime\")"
},
{
"answer_id": 55246142,
"author": "Josh Mouch",
"author_id": 127175,
"author_profile": "https://Stackoverflow.com/users/127175",
"pm_score": 2,
"selected": false,
"text": "AppDomain.CurrentDomain.AssemblyResolve += delegate (object sender2, ResolveEventArgs e2)\n {\n var requestedNameAssembly = new AssemblyName(e2.Name);\n var requestedName = requestedNameAssembly.Name;\n if (requestedName.EndsWith(\".resources\")) return null;\n var binFolder = System.Web.Hosting.HostingEnvironment.MapPath(\"~/bin\");\n var fullPath = Path.Combine(binFolder, requestedName) + \".dll\";\n if (File.Exists(fullPath))\n {\n return Assembly.LoadFrom(fullPath);\n }\n\n return null;\n };\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12248/"
] |
325,791 | <p>Here is the scenario. 2 web servers in two separate locations having two mysql databases with identical tables. The data within the tables is also expected to be identical in real time. </p>
<p>Here is the problem. if a user in either location simultaneously enters a new record into identical tables, as illustrated in the two first tables below, where the third record in each table has been entered simultaneously by the different people. The data in the tables is no longer identical. Which is the best way to maintain that the data remains identical in real time as illustrated in the third table below regardless of where the updates take place? That way in the illustrations below instead of ending up with 3 rows in each table, the new records are replicated bi-directionally and they are inserted in both tables to create 2 identical tables again with 4 columns this time?</p>
<pre><code>Server A in Location A
==============
Table Names
| ID| NAME |
|-----------|
| 1 | Tom |
| 2 | Scott |
|-----------|
| 3 | John |
|-----------|
Server B in Location B
==============
Table Names
| ID| NAME |
|-----------|
| 1 | Tom |
| 2 | Scott |
|-----------|
| 3 | Peter |
|-----------|
Expected Scenario
===========
Table Names
| ID| NAME |
|-----------|
| 1 | Tom |
| 2 | Scott |
| 3 | Peter |
| 4 | John |
|-----------|
</code></pre>
| [
{
"answer_id": 325850,
"author": "Amadiere",
"author_id": 7828,
"author_profile": "https://Stackoverflow.com/users/7828",
"pm_score": 5,
"selected": true,
"text": "auto_increment_increment = 2\nauto_increment_offset = 1 \n auto_increment_increment = 2\nauto_increment_offset = 2\n SHOW SLAVE STATUS Slave_IO_Running Slave_SQL_Running"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11190/"
] |
325,803 | <p>Is it better to use a stored procedure or doing it the old way with a connection string and all that good stuff? Our system has been running slow lately and our manager wants us to try to see if we can speed things up a little and we were thinking about changing some of the old database calls over to stored procedures. Is it worth it?</p>
| [
{
"answer_id": 325919,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 2,
"selected": false,
"text": "1/(1-X)"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] |
325,806 | <p>I'm trying to update a variable in APC, and will be many processes trying to do that.</p>
<p>APC doesn't provide locking functionality, so I'm considering using other mechanisms... what I've found so far is mysql's GET_LOCK(), and php's flock(). Anything else worth considering?</p>
<p>Update: I've found sem_acquire, but it seems to be a blocking lock.</p>
| [
{
"answer_id": 329585,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 2,
"selected": false,
"text": "$f = fopen(\"lockFile.txt\", 'x');\nif($f) {\n $me = getmypid();\n $now = date('Y-m-d H:i:s');\n fwrite($f, \"Locked by $me at $now\\n\");\n fclose($f);\n doStuffInLock();\n unlink(\"lockFile.txt\"); // unlock \n}\nelse {\n echo \"File is locked: \" . file_get_contents(\"lockFile.txt\");\n exit;\n}\n"
},
{
"answer_id": 335212,
"author": "Sean McSomething",
"author_id": 39413,
"author_profile": "https://Stackoverflow.com/users/39413",
"pm_score": 3,
"selected": false,
"text": "\n $value = apc_fetch($KEY);\n\n if ($value === FALSE) {\n shm_acquire($SEMAPHORE);\n\n $recheck_value = apc_fetch($KEY);\n if ($recheck_value !== FALSE) {\n $new_value = expensive_operation();\n apc_store($KEY, $new_value);\n $value = $new_value;\n } else {\n $value = $recheck_value;\n }\n\n shm_release($SEMAPHORE);\n }\n"
},
{
"answer_id": 2165502,
"author": "jsdalton",
"author_id": 99289,
"author_profile": "https://Stackoverflow.com/users/99289",
"pm_score": 1,
"selected": false,
"text": "function acquire_lock($key, $expire=60) {\n if (is_locked($key)) {\n return null;\n }\n return apc_store($key, true, $expire);\n}\n\nfunction release_lock($key) {\n if (!is_locked($key)) {\n return null;\n }\n return apc_delete($key);\n}\n\nfunction is_locked($key) {\n return apc_fetch($key);\n}\n\n// example use\nif (acquire_lock(\"foo\")) {\n do_something_that_requires_a_lock();\n release_lock(\"foo\");\n}\n function key_for_lock($str) {\n return md5($str.\"locked\");\n}\n $expire"
},
{
"answer_id": 3922765,
"author": "harry",
"author_id": 365999,
"author_profile": "https://Stackoverflow.com/users/365999",
"pm_score": 4,
"selected": false,
"text": "/*\nCLASS ExclusiveLock\nDescription\n==================================================================\nThis is a pseudo implementation of mutex since php does not have\nany thread synchronization objects\nThis class uses flock() as a base to provide locking functionality.\nLock will be released in following cases\n1 - user calls unlock\n2 - when this lock object gets deleted\n3 - when request or script ends\n==================================================================\nUsage:\n\n//get the lock\n$lock = new ExclusiveLock( \"mylock\" );\n\n//lock\nif( $lock->lock( ) == FALSE )\n error(\"Locking failed\");\n//--\n//Do your work here\n//--\n\n//unlock\n$lock->unlock();\n===================================================================\n*/\nclass ExclusiveLock\n{\n protected $key = null; //user given value\n protected $file = null; //resource to lock\n protected $own = FALSE; //have we locked resource\n\n function __construct( $key ) \n {\n $this->key = $key;\n //create a new resource or get exisitng with same key\n $this->file = fopen(\"$key.lockfile\", 'w+');\n }\n\n\n function __destruct() \n {\n if( $this->own == TRUE )\n $this->unlock( );\n }\n\n\n function lock( ) \n {\n if( !flock($this->file, LOCK_EX | LOCK_NB)) \n { //failed\n $key = $this->key;\n error_log(\"ExclusiveLock::acquire_lock FAILED to acquire lock [$key]\");\n return FALSE;\n }\n ftruncate($this->file, 0); // truncate file\n //write something to just help debugging\n fwrite( $this->file, \"Locked\\n\");\n fflush( $this->file );\n\n $this->own = TRUE;\n return TRUE; // success\n }\n\n\n function unlock( ) \n {\n $key = $this->key;\n if( $this->own == TRUE ) \n {\n if( !flock($this->file, LOCK_UN) )\n { //failed\n error_log(\"ExclusiveLock::lock FAILED to release lock [$key]\");\n return FALSE;\n }\n ftruncate($this->file, 0); // truncate file\n //write something to just help debugging\n fwrite( $this->file, \"Unlocked\\n\");\n fflush( $this->file );\n $this->own = FALSE;\n }\n else\n {\n error_log(\"ExclusiveLock::unlock called on [$key] but its not acquired by caller\");\n }\n return TRUE; // success\n }\n};\n"
},
{
"answer_id": 5856432,
"author": "cweiske",
"author_id": 282601,
"author_profile": "https://Stackoverflow.com/users/282601",
"pm_score": 0,
"selected": false,
"text": "eaccelerator_lock eaccelerator_unlock"
},
{
"answer_id": 12766003,
"author": "erik258",
"author_id": 1726083,
"author_profile": "https://Stackoverflow.com/users/1726083",
"pm_score": 3,
"selected": false,
"text": "apc_add apc_add apc_add Memcache Redis"
},
{
"answer_id": 36884059,
"author": "sanmai",
"author_id": 93540,
"author_profile": "https://Stackoverflow.com/users/93540",
"pm_score": 0,
"selected": false,
"text": "function WhileLocked($pathname, callable $function, $proj = ' ')\n{\n // create a semaphore for a given pathname and optional project id\n $semaphore = sem_get(ftok($pathname, $proj)); // see ftok for details\n sem_acquire($semaphore);\n try {\n // capture result\n $result = call_user_func($function);\n } catch (Exception $e) {\n // release lock and pass on all errors\n sem_release($semaphore);\n throw $e;\n }\n\n // also release lock if all is good\n sem_release($semaphore);\n return $result;\n}\n $result = WhileLocked(__FILE__, function () use ($that) {\n $this->doSomethingNonsimultaneously($that->getFoo());\n});\n"
},
{
"answer_id": 41481141,
"author": "Pascal Hofmann",
"author_id": 578273,
"author_profile": "https://Stackoverflow.com/users/578273",
"pm_score": 0,
"selected": false,
"text": "apcu_entry apcu_entry() apcu_entry() generator"
},
{
"answer_id": 68404053,
"author": "benbai123",
"author_id": 1042731,
"author_profile": "https://Stackoverflow.com/users/1042731",
"pm_score": 0,
"selected": false,
"text": "/** get a lock, will wait until the lock is available,\n * make sure handle deadlock yourself :p\n * \n * useage : $lock = lock('THE_LOCK_KEY', uniqid(), 50);\n * \n * @param $lock_key : the lock you want to get it\n * @param $lock_value : the unique value to specify lock owner\n * @param $retry_millis : wait befor retry\n * @return ['lock_key'=>$lock_key, 'lock_value'=>$lock_value]\n */\nfunction lock($lock_key, $lock_value, $retry_millis) {\n $got_lock = false;\n while (!$got_lock) {\n $fetched_lock_value = apcu_entry($lock_key, function ($key) use ($lock_value) {\n return $lock_value;\n }, 100);\n $got_lock = ($fetched_lock_value == $lock_value);\n if (!$got_lock) usleep($retry_millis*1000);\n }\n return ['lock_key'=>$lock_key, 'lock_value'=>$lock_value];\n}\n\n/** release a lock\n * \n * usage : unlock($lock);\n * \n * @param $lock : return value of function lock\n */\nfunction unlock($lock) {\n apcu_delete($lock['lock_key']);\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8437/"
] |
325,818 | <p>I have to analyse some existing Erlang code.</p>
<p>Does anybody knows about a tool able to visually / graphically trace the modules calls ?</p>
<p>The behaviour should be : give a directory containing the source code, and get a gui / picture / file of the calls (module1->module2->module3....).</p>
<p>Something like an UML reverse-engineering, but <em>ala</em> Erlang ?</p>
<p>Thanks.</p>
| [
{
"answer_id": 326119,
"author": "Adam Lindberg",
"author_id": 2457,
"author_profile": "https://Stackoverflow.com/users/2457",
"pm_score": 4,
"selected": true,
"text": "xref xref"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15539/"
] |
325,826 | <p>I'm pre-compiling a C program containing Pro*C code with Oracle 10.2 and AIX 5.2</p>
<p>The Oracle precompiler reads the <code>$ORACLE_HOME/precomp/admin/pcscfg.cfg file</code> which contains the definition of the sys_include variable (set to <code>/usr/include</code>).</p>
<p>The Pro*C compiler complains that it doesn't know what the <code>size_t</code> type is and the Oracle header files that use the <code>size_t</code> type are reporting errors.</p>
<p>Here's an example error being reported on the <code>sqlcpr.h</code> file:</p>
<pre><code>extern void sqlglm( char*, size_t*, size_t* );
...........................1
PCC-S-02201, Encountered the symbol "size_t" when expecting one of the following
</code></pre>
<p><code>size_t</code> is defined in the <code>stdio.h</code> header file in the <code>/usr/include</code> directory. I'm including the <code>stdio.h</code> header in my <code>example.pc</code> file before I include the <code>sqlcpr.h</code> header.</p>
<p>I'm issuing the proc command as follows:</p>
<pre><code>proc iname=example parse=full
</code></pre>
<p>Any ideas what I'm doing wrong?</p>
| [
{
"answer_id": 326173,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 4,
"selected": true,
"text": "PCC-S-02201, Encountered the symbol \"size_t\" when expecting one of the \nfollowing\n:\n ... auto, char, const, double, enum, float, int, long,\n ulong_varchar, OCIBFileLocator OCIBlobLocator,\n OCIClobLocator, OCIDateTime, OCIExtProcContext, OCIInterval,\n OCIRowid, OCIDate, OCINumber, OCIRaw, OCIString, register,\n short, signed, sql_context, sql_cursor, static, struct,\n union, unsigned, utext, uvarchar, varchar, void, volatile,\n a typedef name, exec oracle, exec oracle begin, exec,\n exec sql, exec sql begin, exec sql type, exec sql var,\nThe symbol \"enum,\" was substituted for \"size_t\" to continue.\nSyntax error at line 88, column 7, file /usr/include/gconv.h:\nError at line 88, column 7 in file /usr/include/gconv.h\n size_t *);\n sys_include=($ORACLE_HOME/precomp/public,\n /usr/lib/gcc-lib/i386-redhat-linux7/2.96/include, \n /usr/include)\n\ninclude=(/u02/app/oracle/product/8.1.5/precomp/public)\ninclude=(/u02/app/oracle/product/8.1.5/rdbms/demo)\ninclude=(/u02/app/oracle/product/8.1.5/network/public)\ninclude=(/u02/app/oracle/product/8.1.5/plsql/public)\n"
},
{
"answer_id": 14029330,
"author": "AERYEN",
"author_id": 1927950,
"author_profile": "https://Stackoverflow.com/users/1927950",
"pm_score": 1,
"selected": false,
"text": "SYS_INCLUDE=D:\\Progra~1\\Micros~1.0\\VC\\include define=(WIN32_LEAN_AND_MEAN)\nparse=full\nSYS_INCLUDE=D:\\Progra~1\\Micros~1.0\\VC\\include\n define=(WIN32_LEAN_AND_MEAN)\nSYS_INCLUDE=D:\\Progra~1\\Micros~1.0\\VC\\include\nparse=full\n"
},
{
"answer_id": 16324902,
"author": "maxschlepzig",
"author_id": 427158,
"author_profile": "https://Stackoverflow.com/users/427158",
"pm_score": 2,
"selected": false,
"text": "pcscfg.cf sys_include=$ORACLE_HOME/sdk/include\nsys_include=/usr/include\nsys_include=/usr/lib/gcc/x86_64-redhat-linux/4.4.7/include\nsys_include=/usr/include/linux\nltype=short\ndefine=__x86_64__\n proc $ORACLE_HOME/precomp/admin/pcscfg.cfg size_t <limits.h> proc sys_include proc lines=yes \\\ncode=ANSI_C \\\nsqlcheck=full \\\nparse=full \\\nsys_include=$(ORACLE_HOME)/precomp/public \\\nsys_include=/usr/include \\\nsys_include=/usr/lib/gcc/x86_64-redhat-linux/4.4.7/include \\\nsys_include=/usr/include/linux\n"
},
{
"answer_id": 16412372,
"author": "yogmk",
"author_id": 2356843,
"author_profile": "https://Stackoverflow.com/users/2356843",
"pm_score": 1,
"selected": false,
"text": "sys_include gcc -v -c <prog.c> COMPILER_PATH sys_include"
},
{
"answer_id": 41988988,
"author": "Ben Abarbanel",
"author_id": 7502616,
"author_profile": "https://Stackoverflow.com/users/7502616",
"pm_score": 0,
"selected": false,
"text": "pcscfg.cfg define=_POSIX_C_SOURCE\n"
},
{
"answer_id": 56486066,
"author": "user11611523",
"author_id": 11611523,
"author_profile": "https://Stackoverflow.com/users/11611523",
"pm_score": 0,
"selected": false,
"text": "[me@somesys:~/proC]$ proc sys_include='(/usr/include,/usr/include/linux,/usr/include/c++/4.8.2/x86_64-redhat-linux,/usr/include/c++/4.8.2/tr1,/usr/include/c++/4.8.2)' copy.pc\n\nPro*C/C++: Release 12.1.0.2.0 - Production on Thu Jun 6 17:47:11 2019\n\nCopyright (c) 1982, 2014, Oracle and/or its affiliates. All rights reserved.\n\nSystem default option values taken from: /oracle/app/oracle/product/12.1.0.2/precomp/admin/pcscfg.cfg\n\nSyntax error at line 307, column 3, file /usr/include/libio.h:\nError at line 307, column 3 in file /usr/include/libio.h\n size_t __pad5;\n..1\nPCC-S-02201, Encountered the symbol \"size_t\" when expecting one of the following\n:\n\n } char, const, double, enum, float, int, long, ulong_varchar,\n OCIBFileLocator OCIBlobLocator, OCIClobLocator, OCIDateTime,\n OCIExtProcContext, OCIInterval, OCIRowid, OCIDate, OCINumber,\n...\n [me@somesys:~/proC]$ gcc -v -c borrame.c\nUsing built-in specs.\nCOLLECT_GCC=gcc\nTarget: x86_64-redhat-linux\nConfigured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux\nThread model: posix\ngcc version 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)\nCOLLECT_GCC_OPTIONS='-v' '-c' '-mtune=generic' '-march=x86-64'\n /usr/libexec/gcc/x86_64-redhat-linux/4.8.5/cc1 -quiet -v borrame.c -quiet -dumpbase borrame.c -mtune=generic -march=x86-64 -auxbase borrame -version -o /tmp/cc2WTuu6.s\nGNU C (GCC) version 4.8.5 20150623 (Red Hat 4.8.5-36) (x86_64-redhat-linux)\n compiled by GNU C version 4.8.5 20150623 (Red Hat 4.8.5-36), GMP version 6.0.0, MPFR version 3.1.1, MPC version 1.0.1\nGGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072\nignoring nonexistent directory \"/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include-fixed\"\nignoring nonexistent directory \"/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../x86_64-redhat-linux/include\"\n#include \"...\" search starts here:\n#include <...> search starts here:\n /usr/lib/gcc/x86_64-redhat-linux/4.8.5/include\n /usr/local/include\n /usr/include\nEnd of search list.\nGNU C (GCC) version 4.8.5 20150623 (Red Hat 4.8.5-36) (x86_64-redhat-linux)\n...\n COMPILER_PATH #include <...> search starts here: [me@somesys:~/proC]$ proc sys_include='(/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include,/usr/include)' copy.pc\n\nPro*C/C++: Release 12.1.0.2.0 - Production on Thu Jun 6 17:54:50 2019\n\nCopyright (c) 1982, 2014, Oracle and/or its affiliates. All rights reserved.\n\nSystem default option values taken from: /oracle/app/oracle/product/12.1.0.2/precomp/admin/pcscfg.cfg\n\n[me@somesys:~/proC]$\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] |
325,836 | <p>I am attempting to integrate an existing payment platform into my webshop. After making a succesful transaction, the payment platform sends a request to an URL in my application with the transaction ID included in the query parameters.</p>
<p>However, I need to do some post-processing like sending an order confirmation, etc. In order to do this, I'd need access to the user's session, since a lot of order-related information is stored there. To do this, I include the session_id in the intial request XML and do the following after the transaction is complete:</p>
<pre><code>$sessionId = 'foo'; // the sessionId is succesfully retrieved from the XML response
session_id($sessionId);
session_start();
</code></pre>
<p>The above code works fine, but <code>$_SESSION</code> is still empty. Am I overlooking something or this simply not possible?</p>
<p><strong>EDIT:</strong></p>
<p>Thanks for all the answers. The problem has not been solved yet. As said, the strange thing is that I can succesfully start a new session using the session_id that belongs to the user that placed the order. Any other ideas?</p>
| [
{
"answer_id": 325868,
"author": "benlumley",
"author_id": 39161,
"author_profile": "https://Stackoverflow.com/users/39161",
"pm_score": -1,
"selected": false,
"text": "http://yourdomain.com/callbackurl.php?PHPSESSID=SESSIONIDHERE\n"
},
{
"answer_id": 327058,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$id = 'abc123';\nsession_write_close();\nsession_id($id);\nsession_start();\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11568/"
] |
325,838 | <p>I have a php page that displays rows from a mysql db as a table. One of the fields contains HTML markup, and I would like to amke this row clickable and the html would open in a new popup window. What is the best way to do it, and is there a way to do it without writing the html to a file?</p>
<p>edit: this php page is actually part of an ajax app, so that is not a problem. I do not want to use jquery, as I would have to rewrite the application.</p>
<p>edit:</p>
<p>I have tried this again using the example below, and have failed. I know my script tag is wrong, but I am just echoing out row2 at the moment, so I think my logic is wrong before it ever gets to the javascript.</p>
<pre><code>$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
$sql2="SELECT ARTICLE_DESC FROM Auctions WHERE ARTICLE_NO ='$pk'";
$htmlset = mysql_query($sql2);
$row2 = mysql_fetch_array($htmlset);
echo $row2;
/*echo '<script> child1 = window.open ("about:blank")
child1.document.write("$row2['ARTICLE_DESC']");
child1.document.close()*/
</code></pre>
| [
{
"answer_id": 325858,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 3,
"selected": true,
"text": "child1 = window.open (\"about:blank\")\nchild1.document.write(\"Moo!\");\nchild1.document.close()\n"
},
{
"answer_id": 325893,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "$(document).ready( function() {\n\n$('#clicker').click( function() {\n myWindow=window.open('','','width=200,height=100')\n myWindow.document.write($(\"#content\"));\n return false;\n});\n\n});\n <table>\n <tr>\n <td><div id=\"clicker\">Click Here</div></td>\n <td><div id=\"content\">This is the content</div></td>\n </tr>\n </table>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
325,840 | <p>What is the Constant Value of the Underline font in Java ?</p>
<p>Font.BOLD <strong>bold</strong> font</p>
<p>Font.ITALIC <em>italic</em> font</p>
<p>What is the UNDERLINE font Constant ?
I try all the available constants but it didn't work .</p>
| [
{
"answer_id": 325867,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 0,
"selected": false,
"text": "StyledText text = new StyledText(shell, SWT.BORDER);\ntext.setText(\"0123456789 ABCDEFGHIJKLM NOPQRSTUVWXYZ\");\n// make 0123456789 appear underlined\nStyleRange style1 = new StyleRange();\nstyle1.start = 0;\nstyle1.length = 10;\nstyle1.underline = true;\ntext.setStyleRange(style1);\n"
},
{
"answer_id": 325878,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 4,
"selected": false,
"text": "Font Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes) Map TextAttribute TextAttribute AttributedCharacterIterator.Attribute TextAttribute.UNDERLINE TextAttribute TextAttribute"
},
{
"answer_id": 438220,
"author": "Blake",
"author_id": 54488,
"author_profile": "https://Stackoverflow.com/users/54488",
"pm_score": 4,
"selected": false,
"text": "Map<TextAttribute, Integer> fontAttributes = new HashMap<TextAttribute, Integer>();\nfontAttributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);\nFont boldUnderline = new Font(\"Serif\",Font.BOLD, 12).deriveFont(fontAttributes);\n Map<TextAttribute,?>"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22634/"
] |
325,871 | <p>I'm trying to find out the most efficient (best performance) way to check date field for current date. Currently we are using:</p>
<pre><code>SELECT COUNT(Job) AS Jobs
FROM dbo.Job
WHERE (Received BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0)
AND DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1))
</code></pre>
| [
{
"answer_id": 325905,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": "Where DateDiff(day, received, getdate()) = 0\n Where Received >= DateAdd(day, DateDiff(Day, 0, getDate()), 0) \n"
},
{
"answer_id": 325907,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "WHERE\n DateDiff(d, Received, GETDATE()) = 0\n"
},
{
"answer_id": 325978,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": " WHERE\n DATEDIFF(d, Received, GETDATE()) = 0\n"
},
{
"answer_id": 326031,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 0,
"selected": false,
"text": "declare @today as datetime\nset @today = datediff(d, 0, getdate())\n\nselect \n count(job) as jobs\nfrom \n dbo.job\nwhere \n received_DatePartOnly = @today\n"
},
{
"answer_id": 330106,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "// ... where @When is the date-and-time we have (perhaps from GETDATE())\nDECLARE @DayStart datetime, @DayEnd datetime\nSET @DayStart = CAST(FLOOR(CAST(@When as float)) as datetime) -- get day only\nSET @DayEnd = DATEADD(d, 1, @DayStart)\n\nSELECT COUNT(Job) AS Jobs\nFROM dbo.Job\nWHERE (Received >= @DayStart AND Received < @DayEnd)\n"
},
{
"answer_id": 60222059,
"author": "saurabh_hcl",
"author_id": 1670324,
"author_profile": "https://Stackoverflow.com/users/1670324",
"pm_score": 0,
"selected": false,
"text": "where CONVERT(varchar, createddate, 1) = CONVERT(varchar, getdate(), 1);\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491425/"
] |
325,872 | <p>I've been using a 3G wireless card for a while and every time I connect, my anti-virus fires up the updates.</p>
<p>I'm wondering what is the Win32 API set of functions that I can use to, either, get notified or query about the event of an Internet Connection coming up?</p>
<p>And is there already a set of ported headers for Delphi?</p>
| [
{
"answer_id": 327190,
"author": "eKek0",
"author_id": 32173,
"author_profile": "https://Stackoverflow.com/users/32173",
"pm_score": 4,
"selected": false,
"text": "uses WinInet;\n\nfunction IsConnected: boolean;\nconst\n // local system uses a modem to connect to the Internet.\n INTERNET_CONNECTION_MODEM = 1;\n // local system uses a local area network to connect to the Internet.\n INTERNET_CONNECTION_LAN = 2;\n // local system uses a proxy server to connect to the Internet.\n INTERNET_CONNECTION_PROXY = 4;\n // local system's modem is busy with a non-Internet connection.\n INTERNET_CONNECTION_MODEM_BUSY = 8;\n\nvar\n dwConnectionTypes : DWORD;\nbegin\n dwConnectionTypes := INTERNET_CONNECTION_MODEM +\n INTERNET_CONNECTION_LAN +\n INTERNET_CONNECTION_PROXY;\n Result := InternetGetConnectedState(@dwConnectionTypes,0);\nend;\n"
},
{
"answer_id": 331421,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 5,
"selected": true,
"text": "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces unit uAdapterInfo;\n\ninterface\n\nuses\n Classes,\n SysUtils;\n\nconst\n MAX_INTERFACE_NAME_LEN = $100;\n ERROR_SUCCESS = 0;\n MAXLEN_IFDESCR = $100;\n MAXLEN_PHYSADDR = 8;\n\n MIB_IF_OPER_STATUS_NON_OPERATIONAL = 0;\n MIB_IF_OPER_STATUS_UNREACHABLE = 1;\n MIB_IF_OPER_STATUS_DISCONNECTED = 2;\n MIB_IF_OPER_STATUS_CONNECTING = 3;\n MIB_IF_OPER_STATUS_CONNECTED = 4;\n MIB_IF_OPER_STATUS_OPERATIONAL = 5;\n\n MIB_IF_TYPE_OTHER = 1;\n MIB_IF_TYPE_ETHERNET = 6;\n MIB_IF_TYPE_TOKENRING = 9;\n MIB_IF_TYPE_FDDI = 15;\n MIB_IF_TYPE_PPP = 23;\n MIB_IF_TYPE_LOOPBACK = 24;\n MIB_IF_TYPE_SLIP = 28;\n\n MIB_IF_ADMIN_STATUS_UP = 1;\n MIB_IF_ADMIN_STATUS_DOWN = 2;\n MIB_IF_ADMIN_STATUS_TESTING = 3;\n\n _MAX_ROWS_ = 20;\n ANY_SIZE = 1;\n\n\ntype\n MIB_IFROW = record\n wszName: array[0 .. (MAX_INTERFACE_NAME_LEN * 2 - 1)] of ansichar;\n dwIndex: longint;\n dwType: longint;\n dwMtu: longint;\n dwSpeed: longint;\n dwPhysAddrLen: longint;\n bPhysAddr: array[0 .. (MAXLEN_PHYSADDR - 1)] of byte;\n dwAdminStatus: longint;\n dwOperStatus: longint;\n dwLastChange: longint;\n dwInOctets: longint;\n dwInUcastPkts: longint;\n dwInNUcastPkts: longint;\n dwInDiscards: longint;\n dwInErrors: longint;\n dwInUnknownProtos: longint;\n dwOutOctets: longint;\n dwOutUcastPkts: longint;\n dwOutNUcastPkts: longint;\n dwOutDiscards: longint;\n dwOutErrors: longint;\n dwOutQLen: longint;\n dwDescrLen: longint;\n bDescr: array[0 .. (MAXLEN_IFDESCR - 1)] of ansichar;\n end;\n\ntype\n MIB_IPADDRROW = record\n dwAddr: longint;\n dwIndex: longint;\n dwMask: longint;\n dwBCastAddr: longint;\n dwReasmSize: longint;\n unused1: word;\n unused2: word;\n end;\n\ntype\n _IfTable = record\n nRows: longint;\n ifRow: array[1.._MAX_ROWS_] of MIB_IFROW;\n end;\n\ntype\n _IpAddrTable = record\n dwNumEntries: longint;\n table: array[1..ANY_SIZE] of MIB_IPADDRROW;\n end;\n\n\n\nfunction GetIfTable(pIfTable: Pointer; var pdwSize: longint; bOrder: longint): longint;\n stdcall;\nfunction GetIpAddrTable(pIpAddrTable: Pointer; var pdwSize: longint;\n bOrder: longint): longint; stdcall;\n\nfunction Get_if_type(iType: integer): string;\nfunction Get_if_admin_status(iStatus: integer): string;\nfunction Get_if_oper_status(iStatus: integer): string;\n\n\nimplementation\n\nfunction GetIfTable; stdcall; external 'IPHLPAPI.DLL';\nfunction GetIpAddrTable; stdcall; external 'IPHLPAPI.DLL';\n\nfunction Get_if_type(iType: integer): string;\nvar\n sResult: string;\nbegin\n sResult := 'UNKNOWN';\n case iType of\n 1: sResult := 'Other';\n 6: sResult := 'Ethernet';\n 9: sResult := 'Tokenring';\n 15: sResult := 'FDDI';\n 23: sResult := 'PPP';\n 24: sResult := 'Local loopback';\n 28: sResult := 'SLIP';\n 37: sResult := 'ATM';\n 71: sResult := 'IEEE 802.11';\n 131: sResult := 'Tunnel';\n 144: sResult := 'IEEE 1394 (Firewire)';\n end;\n\n Result := sResult;\nend;\n\nfunction Get_if_admin_status(iStatus: integer): string;\nvar\n sResult: string;\nbegin\n sResult := 'UNKNOWN';\n\n case iStatus of\n 1: sResult := 'UP';\n 2: sResult := 'DOWN';\n 3: sResult := 'TESTING';\n end;\n\n Result := sResult;\nend;\n\nfunction Get_if_oper_status(iStatus: integer): string;\nvar\n sResult: string;\nbegin\n sResult := 'UNKNOWN';\n\n case iStatus of\n 0: sResult := 'NON_OPERATIONAL';\n 1: sResult := 'UNREACHABLE';\n 2: sResult := 'DISCONNECTED';\n 3: sResult := 'CONNECTING';\n 4: sResult := 'CONNECTED';\n 5: sResult := 'OPERATIONAL';\n end;\n\n Result := sResult;\nend;\n\nend.\n TAdapterInfo type\n TAdapterInfo = array of record\n dwIndex: longint;\n dwType: longint;\n dwMtu: longint;\n dwSpeed: extended;\n dwPhysAddrLen: longint;\n bPhysAddr: string;\n dwAdminStatus: longint;\n dwOperStatus: longint;\n dwLastChange: longint;\n dwInOctets: longint;\n dwInUcastPkts: longint;\n dwInNUcastPkts: longint;\n dwInDiscards: longint;\n dwInErrors: longint;\n dwInUnknownProtos: longint;\n dwOutOctets: longint;\n dwOutUcastPkts: longint;\n dwOutNUcastPkts: longint;\n dwOutDiscards: longint;\n dwOutErrors: longint;\n dwOutQLen: longint;\n dwDescrLen: longint;\n bDescr: string;\n sIpAddress: string;\n sIpMask: string;\n end;\n function Get_EthernetAdapterDetail(var AdapterDataFound: TAdapterInfo): boolean;\nvar\n pIfTable: ^_IfTable;\n pIpTable: ^_IpAddrTable;\n ifTableSize, ipTableSize: longint;\n tmp: string;\n i, j, k, m: integer;\n ErrCode: longint;\n sAddr, sMask: in_addr;\n IPAddresses, IPMasks: TStringList;\n sIPAddressLine, sIPMaskLine: string;\n bResult: boolean;\nbegin\n bResult := True; //default return value\n pIfTable := nil;\n pIpTable := nil;\n\n IPAddresses := TStringList.Create;\n IPMasks := TStringList.Create;\n\n try\n // First: just get the buffer size.\n // TableSize returns the size needed.\n ifTableSize := 0; // Set to zero so the GetIfTabel function\n // won't try to fill the buffer yet,\n // but only return the actual size it needs.\n GetIfTable(pIfTable, ifTableSize, 1);\n if (ifTableSize < SizeOf(MIB_IFROW) + Sizeof(longint)) then\n begin\n bResult := False;\n Result := bResult;\n Exit; // less than 1 table entry?!\n end;\n\n ipTableSize := 0;\n GetIpAddrTable(pIpTable, ipTableSize, 1);\n if (ipTableSize < SizeOf(MIB_IPADDRROW) + Sizeof(longint)) then\n begin\n bResult := False;\n Result := bResult;\n Exit; // less than 1 table entry?!\n end;\n\n // Second:\n // allocate memory for the buffer and retrieve the\n // entire table.\n GetMem(pIfTable, ifTableSize);\n ErrCode := GetIfTable(pIfTable, ifTableSize, 1);\n\n if ErrCode <> ERROR_SUCCESS then\n begin\n bResult := False;\n Result := bResult;\n Exit; // OK, that did not work. \n // Not enough memory i guess.\n end;\n\n GetMem(pIpTable, ipTableSize);\n ErrCode := GetIpAddrTable(pIpTable, ipTableSize, 1);\n\n if ErrCode <> ERROR_SUCCESS then\n begin\n bResult := False;\n Result := bResult;\n Exit;\n end;\n\n for k := 1 to pIpTable^.dwNumEntries do\n begin\n sAddr.S_addr := pIpTable^.table[k].dwAddr;\n sMask.S_addr := pIpTable^.table[k].dwMask;\n\n sIPAddressLine := Format('0x%8.8x', [(pIpTable^.table[k].dwIndex)]) +\n '=' + Format('%s', [inet_ntoa(sAddr)]);\n sIPMaskLine := Format('0x%8.8x', [(pIpTable^.table[k].dwIndex)]) +\n '=' + Format('%s', [inet_ntoa(sMask)]);\n\n IPAddresses.Add(sIPAddressLine);\n IPMasks.Add(sIPMaskLine);\n end;\n\n SetLength(AdapterDataFound, pIfTable^.nRows); //initialize the array or records\n for i := 1 to pIfTable^.nRows do\n try\n //if pIfTable^.ifRow[i].dwType=MIB_IF_TYPE_ETHERNET then\n //begin\n m := i - 1;\n AdapterDataFound[m].dwIndex := 4;//(pIfTable^.ifRow[i].dwIndex);\n AdapterDataFound[m].dwType := (pIfTable^.ifRow[i].dwType);\n AdapterDataFound[m].dwIndex := (pIfTable^.ifRow[i].dwIndex);\n AdapterDataFound[m].sIpAddress :=\n IPAddresses.Values[Format('0x%8.8x', [(pIfTable^.ifRow[i].dwIndex)])];\n AdapterDataFound[m].sIpMask :=\n IPMasks.Values[Format('0x%8.8x', [(pIfTable^.ifRow[i].dwIndex)])];\n AdapterDataFound[m].dwMtu := (pIfTable^.ifRow[i].dwMtu);\n AdapterDataFound[m].dwSpeed := (pIfTable^.ifRow[i].dwSpeed);\n AdapterDataFound[m].dwAdminStatus := (pIfTable^.ifRow[i].dwAdminStatus);\n AdapterDataFound[m].dwOperStatus := (pIfTable^.ifRow[i].dwOperStatus);\n AdapterDataFound[m].dwInUcastPkts := (pIfTable^.ifRow[i].dwInUcastPkts);\n AdapterDataFound[m].dwInNUcastPkts := (pIfTable^.ifRow[i].dwInNUcastPkts);\n AdapterDataFound[m].dwInDiscards := (pIfTable^.ifRow[i].dwInDiscards);\n AdapterDataFound[m].dwInErrors := (pIfTable^.ifRow[i].dwInErrors);\n AdapterDataFound[m].dwInUnknownProtos := (pIfTable^.ifRow[i].dwInUnknownProtos);\n AdapterDataFound[m].dwOutNUcastPkts := (pIfTable^.ifRow[i].dwOutNUcastPkts);\n AdapterDataFound[m].dwOutUcastPkts := (pIfTable^.ifRow[i].dwOutUcastPkts);\n AdapterDataFound[m].dwOutDiscards := (pIfTable^.ifRow[i].dwOutDiscards);\n AdapterDataFound[m].dwOutErrors := (pIfTable^.ifRow[i].dwOutErrors);\n AdapterDataFound[m].dwOutQLen := (pIfTable^.ifRow[i].dwOutQLen);\n AdapterDataFound[m].bDescr := (pIfTable^.ifRow[i].bDescr);\n\n tmp := '';\n for j := 0 to pIfTable^.ifRow[i].dwPhysAddrLen - 1 do\n begin\n if Length(tmp) > 0 then\n tmp := tmp + '-' + format('%.2x', [pIfTable^.ifRow[i].bPhysAddr[j]])\n else\n tmp := tmp + format('%.2x', [pIfTable^.ifRow[i].bPhysAddr[j]]);\n end;\n\n if Length(tmp) > 0 then\n begin\n AdapterDataFound[m].bPhysAddr := tmp;\n end;\n except\n bResult := False;\n Result := bResult;\n Exit;\n end;\n finally\n if Assigned(pIfTable) then\n begin\n FreeMem(pIfTable, ifTableSize);\n end;\n\n FreeAndNil(IPMasks);\n FreeAndNil(IPAddresses);\n end;\n\n Result := bResult;\nend;\n ifconfig -a"
},
{
"answer_id": 333880,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 2,
"selected": false,
"text": "program ifconfig;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n Classes,\n Winsock,\n uAdapterInfo in 'uAdapterInfo.pas';\n\ntype\n TAdapterInfo = array of record\n dwIndex: longint;\n dwType: longint;\n dwMtu: longint;\n dwSpeed: extended;\n dwPhysAddrLen: longint;\n bPhysAddr: string;\n dwAdminStatus: longint;\n dwOperStatus: longint;\n dwLastChange: longint;\n dwInOctets: longint;\n dwInUcastPkts: longint;\n dwInNUcastPkts: longint;\n dwInDiscards: longint;\n dwInErrors: longint;\n dwInUnknownProtos: longint;\n dwOutOctets: longint;\n dwOutUcastPkts: longint;\n dwOutNUcastPkts: longint;\n dwOutDiscards: longint;\n dwOutErrors: longint;\n dwOutQLen: longint;\n dwDescrLen: longint;\n bDescr: string;\n sIpAddress: string;\n sIpMask: string;\n end;\n\n\n\n\n function Get_EthernetAdapterDetail(var AdapterDataFound: TAdapterInfo): boolean;\n var\n pIfTable: ^_IfTable;\n pIpTable: ^_IpAddrTable;\n ifTableSize, ipTableSize: longint;\n tmp: string;\n i, j, k, m: integer;\n ErrCode: longint;\n sAddr, sMask: in_addr;\n IPAddresses, IPMasks: TStringList;\n sIPAddressLine, sIPMaskLine: string;\n bResult: boolean;\n begin\n bResult := True; //default return value\n pIfTable := nil;\n pIpTable := nil;\n\n IPAddresses := TStringList.Create;\n IPMasks := TStringList.Create;\n\n try\n // First: just get the buffer size.\n // TableSize returns the size needed.\n ifTableSize := 0; // Set to zero so the GetIfTabel function\n // won't try to fill the buffer yet, \n // but only return the actual size it needs.\n GetIfTable(pIfTable, ifTableSize, 1);\n if (ifTableSize < SizeOf(MIB_IFROW) + Sizeof(longint)) then\n begin\n bResult := False;\n Result := bResult;\n Exit; // less than 1 table entry?!\n end;\n\n ipTableSize := 0;\n GetIpAddrTable(pIpTable, ipTableSize, 1);\n if (ipTableSize < SizeOf(MIB_IPADDRROW) + Sizeof(longint)) then\n begin\n bResult := False;\n Result := bResult;\n Exit; // less than 1 table entry?!\n end;\n\n // Second:\n // allocate memory for the buffer and retrieve the \n // entire table.\n GetMem(pIfTable, ifTableSize);\n ErrCode := GetIfTable(pIfTable, ifTableSize, 1);\n\n if ErrCode <> ERROR_SUCCESS then\n begin\n bResult := False;\n Result := bResult;\n Exit; // OK, that did not work. \n // Not enough memory i guess.\n end;\n\n GetMem(pIpTable, ipTableSize);\n ErrCode := GetIpAddrTable(pIpTable, ipTableSize, 1);\n\n if ErrCode <> ERROR_SUCCESS then\n begin\n bResult := False;\n Result := bResult;\n Exit;\n end;\n\n for k := 1 to pIpTable^.dwNumEntries do\n begin\n sAddr.S_addr := pIpTable^.table[k].dwAddr;\n sMask.S_addr := pIpTable^.table[k].dwMask;\n\n sIPAddressLine := Format('0x%8.8x', [(pIpTable^.table[k].dwIndex)]) +\n '=' + Format('%s', [inet_ntoa(sAddr)]);\n sIPMaskLine := Format('0x%8.8x', [(pIpTable^.table[k].dwIndex)]) +\n '=' + Format('%s', [inet_ntoa(sMask)]);\n\n IPAddresses.Add(sIPAddressLine);\n IPMasks.Add(sIPMaskLine);\n end;\n\n SetLength(AdapterDataFound, pIfTable^.nRows); //initialize the array or records\n for i := 1 to pIfTable^.nRows do\n try\n //if pIfTable^.ifRow[i].dwType=MIB_IF_TYPE_ETHERNET then\n //begin\n m := i - 1;\n AdapterDataFound[m].dwIndex := 4;//(pIfTable^.ifRow[i].dwIndex);\n AdapterDataFound[m].dwType := (pIfTable^.ifRow[i].dwType);\n AdapterDataFound[m].dwIndex := (pIfTable^.ifRow[i].dwIndex);\n AdapterDataFound[m].sIpAddress :=\n IPAddresses.Values[Format('0x%8.8x', [(pIfTable^.ifRow[i].dwIndex)])];\n AdapterDataFound[m].sIpMask :=\n IPMasks.Values[Format('0x%8.8x', [(pIfTable^.ifRow[i].dwIndex)])];\n AdapterDataFound[m].dwMtu := (pIfTable^.ifRow[i].dwMtu);\n AdapterDataFound[m].dwSpeed := (pIfTable^.ifRow[i].dwSpeed);\n AdapterDataFound[m].dwAdminStatus := (pIfTable^.ifRow[i].dwAdminStatus);\n AdapterDataFound[m].dwOperStatus := (pIfTable^.ifRow[i].dwOperStatus);\n AdapterDataFound[m].dwInUcastPkts := (pIfTable^.ifRow[i].dwInUcastPkts);\n AdapterDataFound[m].dwInNUcastPkts := (pIfTable^.ifRow[i].dwInNUcastPkts);\n AdapterDataFound[m].dwInDiscards := (pIfTable^.ifRow[i].dwInDiscards);\n AdapterDataFound[m].dwInErrors := (pIfTable^.ifRow[i].dwInErrors);\n AdapterDataFound[m].dwInUnknownProtos := (pIfTable^.ifRow[i].dwInUnknownProtos);\n AdapterDataFound[m].dwOutNUcastPkts := (pIfTable^.ifRow[i].dwOutNUcastPkts);\n AdapterDataFound[m].dwOutUcastPkts := (pIfTable^.ifRow[i].dwOutUcastPkts);\n AdapterDataFound[m].dwOutDiscards := (pIfTable^.ifRow[i].dwOutDiscards);\n AdapterDataFound[m].dwOutErrors := (pIfTable^.ifRow[i].dwOutErrors);\n AdapterDataFound[m].dwOutQLen := (pIfTable^.ifRow[i].dwOutQLen);\n AdapterDataFound[m].bDescr := (pIfTable^.ifRow[i].bDescr);\n\n tmp := '';\n for j := 0 to pIfTable^.ifRow[i].dwPhysAddrLen - 1 do\n begin\n if Length(tmp) > 0 then\n tmp := tmp + '-' + format('%.2x', [pIfTable^.ifRow[i].bPhysAddr[j]])\n else\n tmp := tmp + format('%.2x', [pIfTable^.ifRow[i].bPhysAddr[j]]);\n end;\n\n if Length(tmp) > 0 then\n begin\n AdapterDataFound[m].bPhysAddr := tmp;\n end;\n except\n bResult := False;\n Result := bResult;\n Exit;\n end;\n finally\n if Assigned(pIfTable) then\n begin\n FreeMem(pIfTable, ifTableSize);\n end;\n\n FreeAndNil(IPMasks);\n FreeAndNil(IPAddresses);\n end;\n\n Result := bResult;\n end;\n\n\n\nvar\n AdapterData: TAdapterInfo;\n i: integer;\nbegin\n try\n WriteLn('');\n if Get_EthernetAdapterDetail(AdapterData) then\n begin\n for i := 0 to Length(AdapterData) - 1 do\n begin\n WriteLn(Format('0x%8.8x', [AdapterData[i].dwIndex]));\n WriteLn('\"' + AdapterData[i].bDescr + '\"');\n Write(Format(#9 + 'Link encap: %s ', [Get_if_type(AdapterData[i].dwType)]));\n\n if Length(AdapterData[i].bPhysAddr) > 0 then\n Write('HWaddr: ' + AdapterData[i].bPhysAddr);\n\n Write(#13 + #10 + #9 + 'inet addr:' + AdapterData[i].sIpAddress);\n WriteLn(' Mask: ' + AdapterData[i].sIpMask);\n WriteLn(Format(#9 + 'MTU: %d Speed:%.2f Mbps', [AdapterData[i].dwMtu,\n (AdapterData[i].dwSpeed) / 1000 / 1000]));\n Write(#9 + 'Admin status:' + Get_if_admin_status(AdapterData[i].dwAdminStatus));\n WriteLn(' Oper status:' + Get_if_oper_status(AdapterData[i].dwOperStatus));\n WriteLn(#9 + Format('RX packets:%d dropped:%d errors:%d unkown:%d',\n [AdapterData[i].dwInUcastPkts + AdapterData[i].dwInNUcastPkts,\n AdapterData[i].dwInDiscards, AdapterData[i].dwInErrors,\n AdapterData[i].dwInUnknownProtos]));\n WriteLn(#9 + Format('TX packets:%d dropped:%d errors:%d txqueuelen:%d',\n [AdapterData[i].dwOutUcastPkts + AdapterData[i].dwOutNUcastPkts,\n AdapterData[i].dwOutDiscards, AdapterData[i].dwOutErrors,\n AdapterData[i].dwOutQLen]));\n\n WriteLn('');\n end;\n end\n else\n begin\n WriteLn(#13+#10+'*** Error retrieving adapter information');\n end;\n except\n on E: Exception do\n Writeln(E.ClassName, ': ', E.Message);\n end;\nend.\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
] |
325,873 | <p>I use an SQL statement to remove records that exist on another database but this takes a very long time.</p>
<p>Is there any other alternative to the code below that can be faster? Database is Access.</p>
<p>email_DB.mdb is from where I want to remove the email addresses that exist on the other database (table Newsletter_Subscribers)
customers.mdb is the other database (table Customers)</p>
<pre><code>SQLRemoveDupes = "DELETE FROM Newsletter_Subscribers WHERE EXISTS (select * from [" & strDBPath & "Customers].Customers " _
& "where Subscriber_Email = Email or Subscriber_Email = EmailO)"
NewsletterConn = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" & strDBPath & "email_DB.mdb"
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = NewsletterConn
MM_editCmd.CommandText = SQLRemoveDupes
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
Set MM_editCmd = Nothing
</code></pre>
<p>EDIT: Tried the SQL below from one of the answers but I keep getting an error when running it:</p>
<p>SQL: DELETE FROM Newsletter_Subscribers WHERE CustID IN (select CustID from [" & strDBPath & "Customers].Customers where Subscriber_Email = Email or Subscriber_Email = EmailO) </p>
<p>I get a "Too few parameters. Expected 1." error message on the Execute line. </p>
| [
{
"answer_id": 327190,
"author": "eKek0",
"author_id": 32173,
"author_profile": "https://Stackoverflow.com/users/32173",
"pm_score": 4,
"selected": false,
"text": "uses WinInet;\n\nfunction IsConnected: boolean;\nconst\n // local system uses a modem to connect to the Internet.\n INTERNET_CONNECTION_MODEM = 1;\n // local system uses a local area network to connect to the Internet.\n INTERNET_CONNECTION_LAN = 2;\n // local system uses a proxy server to connect to the Internet.\n INTERNET_CONNECTION_PROXY = 4;\n // local system's modem is busy with a non-Internet connection.\n INTERNET_CONNECTION_MODEM_BUSY = 8;\n\nvar\n dwConnectionTypes : DWORD;\nbegin\n dwConnectionTypes := INTERNET_CONNECTION_MODEM +\n INTERNET_CONNECTION_LAN +\n INTERNET_CONNECTION_PROXY;\n Result := InternetGetConnectedState(@dwConnectionTypes,0);\nend;\n"
},
{
"answer_id": 331421,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 5,
"selected": true,
"text": "HKLM\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces unit uAdapterInfo;\n\ninterface\n\nuses\n Classes,\n SysUtils;\n\nconst\n MAX_INTERFACE_NAME_LEN = $100;\n ERROR_SUCCESS = 0;\n MAXLEN_IFDESCR = $100;\n MAXLEN_PHYSADDR = 8;\n\n MIB_IF_OPER_STATUS_NON_OPERATIONAL = 0;\n MIB_IF_OPER_STATUS_UNREACHABLE = 1;\n MIB_IF_OPER_STATUS_DISCONNECTED = 2;\n MIB_IF_OPER_STATUS_CONNECTING = 3;\n MIB_IF_OPER_STATUS_CONNECTED = 4;\n MIB_IF_OPER_STATUS_OPERATIONAL = 5;\n\n MIB_IF_TYPE_OTHER = 1;\n MIB_IF_TYPE_ETHERNET = 6;\n MIB_IF_TYPE_TOKENRING = 9;\n MIB_IF_TYPE_FDDI = 15;\n MIB_IF_TYPE_PPP = 23;\n MIB_IF_TYPE_LOOPBACK = 24;\n MIB_IF_TYPE_SLIP = 28;\n\n MIB_IF_ADMIN_STATUS_UP = 1;\n MIB_IF_ADMIN_STATUS_DOWN = 2;\n MIB_IF_ADMIN_STATUS_TESTING = 3;\n\n _MAX_ROWS_ = 20;\n ANY_SIZE = 1;\n\n\ntype\n MIB_IFROW = record\n wszName: array[0 .. (MAX_INTERFACE_NAME_LEN * 2 - 1)] of ansichar;\n dwIndex: longint;\n dwType: longint;\n dwMtu: longint;\n dwSpeed: longint;\n dwPhysAddrLen: longint;\n bPhysAddr: array[0 .. (MAXLEN_PHYSADDR - 1)] of byte;\n dwAdminStatus: longint;\n dwOperStatus: longint;\n dwLastChange: longint;\n dwInOctets: longint;\n dwInUcastPkts: longint;\n dwInNUcastPkts: longint;\n dwInDiscards: longint;\n dwInErrors: longint;\n dwInUnknownProtos: longint;\n dwOutOctets: longint;\n dwOutUcastPkts: longint;\n dwOutNUcastPkts: longint;\n dwOutDiscards: longint;\n dwOutErrors: longint;\n dwOutQLen: longint;\n dwDescrLen: longint;\n bDescr: array[0 .. (MAXLEN_IFDESCR - 1)] of ansichar;\n end;\n\ntype\n MIB_IPADDRROW = record\n dwAddr: longint;\n dwIndex: longint;\n dwMask: longint;\n dwBCastAddr: longint;\n dwReasmSize: longint;\n unused1: word;\n unused2: word;\n end;\n\ntype\n _IfTable = record\n nRows: longint;\n ifRow: array[1.._MAX_ROWS_] of MIB_IFROW;\n end;\n\ntype\n _IpAddrTable = record\n dwNumEntries: longint;\n table: array[1..ANY_SIZE] of MIB_IPADDRROW;\n end;\n\n\n\nfunction GetIfTable(pIfTable: Pointer; var pdwSize: longint; bOrder: longint): longint;\n stdcall;\nfunction GetIpAddrTable(pIpAddrTable: Pointer; var pdwSize: longint;\n bOrder: longint): longint; stdcall;\n\nfunction Get_if_type(iType: integer): string;\nfunction Get_if_admin_status(iStatus: integer): string;\nfunction Get_if_oper_status(iStatus: integer): string;\n\n\nimplementation\n\nfunction GetIfTable; stdcall; external 'IPHLPAPI.DLL';\nfunction GetIpAddrTable; stdcall; external 'IPHLPAPI.DLL';\n\nfunction Get_if_type(iType: integer): string;\nvar\n sResult: string;\nbegin\n sResult := 'UNKNOWN';\n case iType of\n 1: sResult := 'Other';\n 6: sResult := 'Ethernet';\n 9: sResult := 'Tokenring';\n 15: sResult := 'FDDI';\n 23: sResult := 'PPP';\n 24: sResult := 'Local loopback';\n 28: sResult := 'SLIP';\n 37: sResult := 'ATM';\n 71: sResult := 'IEEE 802.11';\n 131: sResult := 'Tunnel';\n 144: sResult := 'IEEE 1394 (Firewire)';\n end;\n\n Result := sResult;\nend;\n\nfunction Get_if_admin_status(iStatus: integer): string;\nvar\n sResult: string;\nbegin\n sResult := 'UNKNOWN';\n\n case iStatus of\n 1: sResult := 'UP';\n 2: sResult := 'DOWN';\n 3: sResult := 'TESTING';\n end;\n\n Result := sResult;\nend;\n\nfunction Get_if_oper_status(iStatus: integer): string;\nvar\n sResult: string;\nbegin\n sResult := 'UNKNOWN';\n\n case iStatus of\n 0: sResult := 'NON_OPERATIONAL';\n 1: sResult := 'UNREACHABLE';\n 2: sResult := 'DISCONNECTED';\n 3: sResult := 'CONNECTING';\n 4: sResult := 'CONNECTED';\n 5: sResult := 'OPERATIONAL';\n end;\n\n Result := sResult;\nend;\n\nend.\n TAdapterInfo type\n TAdapterInfo = array of record\n dwIndex: longint;\n dwType: longint;\n dwMtu: longint;\n dwSpeed: extended;\n dwPhysAddrLen: longint;\n bPhysAddr: string;\n dwAdminStatus: longint;\n dwOperStatus: longint;\n dwLastChange: longint;\n dwInOctets: longint;\n dwInUcastPkts: longint;\n dwInNUcastPkts: longint;\n dwInDiscards: longint;\n dwInErrors: longint;\n dwInUnknownProtos: longint;\n dwOutOctets: longint;\n dwOutUcastPkts: longint;\n dwOutNUcastPkts: longint;\n dwOutDiscards: longint;\n dwOutErrors: longint;\n dwOutQLen: longint;\n dwDescrLen: longint;\n bDescr: string;\n sIpAddress: string;\n sIpMask: string;\n end;\n function Get_EthernetAdapterDetail(var AdapterDataFound: TAdapterInfo): boolean;\nvar\n pIfTable: ^_IfTable;\n pIpTable: ^_IpAddrTable;\n ifTableSize, ipTableSize: longint;\n tmp: string;\n i, j, k, m: integer;\n ErrCode: longint;\n sAddr, sMask: in_addr;\n IPAddresses, IPMasks: TStringList;\n sIPAddressLine, sIPMaskLine: string;\n bResult: boolean;\nbegin\n bResult := True; //default return value\n pIfTable := nil;\n pIpTable := nil;\n\n IPAddresses := TStringList.Create;\n IPMasks := TStringList.Create;\n\n try\n // First: just get the buffer size.\n // TableSize returns the size needed.\n ifTableSize := 0; // Set to zero so the GetIfTabel function\n // won't try to fill the buffer yet,\n // but only return the actual size it needs.\n GetIfTable(pIfTable, ifTableSize, 1);\n if (ifTableSize < SizeOf(MIB_IFROW) + Sizeof(longint)) then\n begin\n bResult := False;\n Result := bResult;\n Exit; // less than 1 table entry?!\n end;\n\n ipTableSize := 0;\n GetIpAddrTable(pIpTable, ipTableSize, 1);\n if (ipTableSize < SizeOf(MIB_IPADDRROW) + Sizeof(longint)) then\n begin\n bResult := False;\n Result := bResult;\n Exit; // less than 1 table entry?!\n end;\n\n // Second:\n // allocate memory for the buffer and retrieve the\n // entire table.\n GetMem(pIfTable, ifTableSize);\n ErrCode := GetIfTable(pIfTable, ifTableSize, 1);\n\n if ErrCode <> ERROR_SUCCESS then\n begin\n bResult := False;\n Result := bResult;\n Exit; // OK, that did not work. \n // Not enough memory i guess.\n end;\n\n GetMem(pIpTable, ipTableSize);\n ErrCode := GetIpAddrTable(pIpTable, ipTableSize, 1);\n\n if ErrCode <> ERROR_SUCCESS then\n begin\n bResult := False;\n Result := bResult;\n Exit;\n end;\n\n for k := 1 to pIpTable^.dwNumEntries do\n begin\n sAddr.S_addr := pIpTable^.table[k].dwAddr;\n sMask.S_addr := pIpTable^.table[k].dwMask;\n\n sIPAddressLine := Format('0x%8.8x', [(pIpTable^.table[k].dwIndex)]) +\n '=' + Format('%s', [inet_ntoa(sAddr)]);\n sIPMaskLine := Format('0x%8.8x', [(pIpTable^.table[k].dwIndex)]) +\n '=' + Format('%s', [inet_ntoa(sMask)]);\n\n IPAddresses.Add(sIPAddressLine);\n IPMasks.Add(sIPMaskLine);\n end;\n\n SetLength(AdapterDataFound, pIfTable^.nRows); //initialize the array or records\n for i := 1 to pIfTable^.nRows do\n try\n //if pIfTable^.ifRow[i].dwType=MIB_IF_TYPE_ETHERNET then\n //begin\n m := i - 1;\n AdapterDataFound[m].dwIndex := 4;//(pIfTable^.ifRow[i].dwIndex);\n AdapterDataFound[m].dwType := (pIfTable^.ifRow[i].dwType);\n AdapterDataFound[m].dwIndex := (pIfTable^.ifRow[i].dwIndex);\n AdapterDataFound[m].sIpAddress :=\n IPAddresses.Values[Format('0x%8.8x', [(pIfTable^.ifRow[i].dwIndex)])];\n AdapterDataFound[m].sIpMask :=\n IPMasks.Values[Format('0x%8.8x', [(pIfTable^.ifRow[i].dwIndex)])];\n AdapterDataFound[m].dwMtu := (pIfTable^.ifRow[i].dwMtu);\n AdapterDataFound[m].dwSpeed := (pIfTable^.ifRow[i].dwSpeed);\n AdapterDataFound[m].dwAdminStatus := (pIfTable^.ifRow[i].dwAdminStatus);\n AdapterDataFound[m].dwOperStatus := (pIfTable^.ifRow[i].dwOperStatus);\n AdapterDataFound[m].dwInUcastPkts := (pIfTable^.ifRow[i].dwInUcastPkts);\n AdapterDataFound[m].dwInNUcastPkts := (pIfTable^.ifRow[i].dwInNUcastPkts);\n AdapterDataFound[m].dwInDiscards := (pIfTable^.ifRow[i].dwInDiscards);\n AdapterDataFound[m].dwInErrors := (pIfTable^.ifRow[i].dwInErrors);\n AdapterDataFound[m].dwInUnknownProtos := (pIfTable^.ifRow[i].dwInUnknownProtos);\n AdapterDataFound[m].dwOutNUcastPkts := (pIfTable^.ifRow[i].dwOutNUcastPkts);\n AdapterDataFound[m].dwOutUcastPkts := (pIfTable^.ifRow[i].dwOutUcastPkts);\n AdapterDataFound[m].dwOutDiscards := (pIfTable^.ifRow[i].dwOutDiscards);\n AdapterDataFound[m].dwOutErrors := (pIfTable^.ifRow[i].dwOutErrors);\n AdapterDataFound[m].dwOutQLen := (pIfTable^.ifRow[i].dwOutQLen);\n AdapterDataFound[m].bDescr := (pIfTable^.ifRow[i].bDescr);\n\n tmp := '';\n for j := 0 to pIfTable^.ifRow[i].dwPhysAddrLen - 1 do\n begin\n if Length(tmp) > 0 then\n tmp := tmp + '-' + format('%.2x', [pIfTable^.ifRow[i].bPhysAddr[j]])\n else\n tmp := tmp + format('%.2x', [pIfTable^.ifRow[i].bPhysAddr[j]]);\n end;\n\n if Length(tmp) > 0 then\n begin\n AdapterDataFound[m].bPhysAddr := tmp;\n end;\n except\n bResult := False;\n Result := bResult;\n Exit;\n end;\n finally\n if Assigned(pIfTable) then\n begin\n FreeMem(pIfTable, ifTableSize);\n end;\n\n FreeAndNil(IPMasks);\n FreeAndNil(IPAddresses);\n end;\n\n Result := bResult;\nend;\n ifconfig -a"
},
{
"answer_id": 333880,
"author": "Mick",
"author_id": 12458,
"author_profile": "https://Stackoverflow.com/users/12458",
"pm_score": 2,
"selected": false,
"text": "program ifconfig;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n Classes,\n Winsock,\n uAdapterInfo in 'uAdapterInfo.pas';\n\ntype\n TAdapterInfo = array of record\n dwIndex: longint;\n dwType: longint;\n dwMtu: longint;\n dwSpeed: extended;\n dwPhysAddrLen: longint;\n bPhysAddr: string;\n dwAdminStatus: longint;\n dwOperStatus: longint;\n dwLastChange: longint;\n dwInOctets: longint;\n dwInUcastPkts: longint;\n dwInNUcastPkts: longint;\n dwInDiscards: longint;\n dwInErrors: longint;\n dwInUnknownProtos: longint;\n dwOutOctets: longint;\n dwOutUcastPkts: longint;\n dwOutNUcastPkts: longint;\n dwOutDiscards: longint;\n dwOutErrors: longint;\n dwOutQLen: longint;\n dwDescrLen: longint;\n bDescr: string;\n sIpAddress: string;\n sIpMask: string;\n end;\n\n\n\n\n function Get_EthernetAdapterDetail(var AdapterDataFound: TAdapterInfo): boolean;\n var\n pIfTable: ^_IfTable;\n pIpTable: ^_IpAddrTable;\n ifTableSize, ipTableSize: longint;\n tmp: string;\n i, j, k, m: integer;\n ErrCode: longint;\n sAddr, sMask: in_addr;\n IPAddresses, IPMasks: TStringList;\n sIPAddressLine, sIPMaskLine: string;\n bResult: boolean;\n begin\n bResult := True; //default return value\n pIfTable := nil;\n pIpTable := nil;\n\n IPAddresses := TStringList.Create;\n IPMasks := TStringList.Create;\n\n try\n // First: just get the buffer size.\n // TableSize returns the size needed.\n ifTableSize := 0; // Set to zero so the GetIfTabel function\n // won't try to fill the buffer yet, \n // but only return the actual size it needs.\n GetIfTable(pIfTable, ifTableSize, 1);\n if (ifTableSize < SizeOf(MIB_IFROW) + Sizeof(longint)) then\n begin\n bResult := False;\n Result := bResult;\n Exit; // less than 1 table entry?!\n end;\n\n ipTableSize := 0;\n GetIpAddrTable(pIpTable, ipTableSize, 1);\n if (ipTableSize < SizeOf(MIB_IPADDRROW) + Sizeof(longint)) then\n begin\n bResult := False;\n Result := bResult;\n Exit; // less than 1 table entry?!\n end;\n\n // Second:\n // allocate memory for the buffer and retrieve the \n // entire table.\n GetMem(pIfTable, ifTableSize);\n ErrCode := GetIfTable(pIfTable, ifTableSize, 1);\n\n if ErrCode <> ERROR_SUCCESS then\n begin\n bResult := False;\n Result := bResult;\n Exit; // OK, that did not work. \n // Not enough memory i guess.\n end;\n\n GetMem(pIpTable, ipTableSize);\n ErrCode := GetIpAddrTable(pIpTable, ipTableSize, 1);\n\n if ErrCode <> ERROR_SUCCESS then\n begin\n bResult := False;\n Result := bResult;\n Exit;\n end;\n\n for k := 1 to pIpTable^.dwNumEntries do\n begin\n sAddr.S_addr := pIpTable^.table[k].dwAddr;\n sMask.S_addr := pIpTable^.table[k].dwMask;\n\n sIPAddressLine := Format('0x%8.8x', [(pIpTable^.table[k].dwIndex)]) +\n '=' + Format('%s', [inet_ntoa(sAddr)]);\n sIPMaskLine := Format('0x%8.8x', [(pIpTable^.table[k].dwIndex)]) +\n '=' + Format('%s', [inet_ntoa(sMask)]);\n\n IPAddresses.Add(sIPAddressLine);\n IPMasks.Add(sIPMaskLine);\n end;\n\n SetLength(AdapterDataFound, pIfTable^.nRows); //initialize the array or records\n for i := 1 to pIfTable^.nRows do\n try\n //if pIfTable^.ifRow[i].dwType=MIB_IF_TYPE_ETHERNET then\n //begin\n m := i - 1;\n AdapterDataFound[m].dwIndex := 4;//(pIfTable^.ifRow[i].dwIndex);\n AdapterDataFound[m].dwType := (pIfTable^.ifRow[i].dwType);\n AdapterDataFound[m].dwIndex := (pIfTable^.ifRow[i].dwIndex);\n AdapterDataFound[m].sIpAddress :=\n IPAddresses.Values[Format('0x%8.8x', [(pIfTable^.ifRow[i].dwIndex)])];\n AdapterDataFound[m].sIpMask :=\n IPMasks.Values[Format('0x%8.8x', [(pIfTable^.ifRow[i].dwIndex)])];\n AdapterDataFound[m].dwMtu := (pIfTable^.ifRow[i].dwMtu);\n AdapterDataFound[m].dwSpeed := (pIfTable^.ifRow[i].dwSpeed);\n AdapterDataFound[m].dwAdminStatus := (pIfTable^.ifRow[i].dwAdminStatus);\n AdapterDataFound[m].dwOperStatus := (pIfTable^.ifRow[i].dwOperStatus);\n AdapterDataFound[m].dwInUcastPkts := (pIfTable^.ifRow[i].dwInUcastPkts);\n AdapterDataFound[m].dwInNUcastPkts := (pIfTable^.ifRow[i].dwInNUcastPkts);\n AdapterDataFound[m].dwInDiscards := (pIfTable^.ifRow[i].dwInDiscards);\n AdapterDataFound[m].dwInErrors := (pIfTable^.ifRow[i].dwInErrors);\n AdapterDataFound[m].dwInUnknownProtos := (pIfTable^.ifRow[i].dwInUnknownProtos);\n AdapterDataFound[m].dwOutNUcastPkts := (pIfTable^.ifRow[i].dwOutNUcastPkts);\n AdapterDataFound[m].dwOutUcastPkts := (pIfTable^.ifRow[i].dwOutUcastPkts);\n AdapterDataFound[m].dwOutDiscards := (pIfTable^.ifRow[i].dwOutDiscards);\n AdapterDataFound[m].dwOutErrors := (pIfTable^.ifRow[i].dwOutErrors);\n AdapterDataFound[m].dwOutQLen := (pIfTable^.ifRow[i].dwOutQLen);\n AdapterDataFound[m].bDescr := (pIfTable^.ifRow[i].bDescr);\n\n tmp := '';\n for j := 0 to pIfTable^.ifRow[i].dwPhysAddrLen - 1 do\n begin\n if Length(tmp) > 0 then\n tmp := tmp + '-' + format('%.2x', [pIfTable^.ifRow[i].bPhysAddr[j]])\n else\n tmp := tmp + format('%.2x', [pIfTable^.ifRow[i].bPhysAddr[j]]);\n end;\n\n if Length(tmp) > 0 then\n begin\n AdapterDataFound[m].bPhysAddr := tmp;\n end;\n except\n bResult := False;\n Result := bResult;\n Exit;\n end;\n finally\n if Assigned(pIfTable) then\n begin\n FreeMem(pIfTable, ifTableSize);\n end;\n\n FreeAndNil(IPMasks);\n FreeAndNil(IPAddresses);\n end;\n\n Result := bResult;\n end;\n\n\n\nvar\n AdapterData: TAdapterInfo;\n i: integer;\nbegin\n try\n WriteLn('');\n if Get_EthernetAdapterDetail(AdapterData) then\n begin\n for i := 0 to Length(AdapterData) - 1 do\n begin\n WriteLn(Format('0x%8.8x', [AdapterData[i].dwIndex]));\n WriteLn('\"' + AdapterData[i].bDescr + '\"');\n Write(Format(#9 + 'Link encap: %s ', [Get_if_type(AdapterData[i].dwType)]));\n\n if Length(AdapterData[i].bPhysAddr) > 0 then\n Write('HWaddr: ' + AdapterData[i].bPhysAddr);\n\n Write(#13 + #10 + #9 + 'inet addr:' + AdapterData[i].sIpAddress);\n WriteLn(' Mask: ' + AdapterData[i].sIpMask);\n WriteLn(Format(#9 + 'MTU: %d Speed:%.2f Mbps', [AdapterData[i].dwMtu,\n (AdapterData[i].dwSpeed) / 1000 / 1000]));\n Write(#9 + 'Admin status:' + Get_if_admin_status(AdapterData[i].dwAdminStatus));\n WriteLn(' Oper status:' + Get_if_oper_status(AdapterData[i].dwOperStatus));\n WriteLn(#9 + Format('RX packets:%d dropped:%d errors:%d unkown:%d',\n [AdapterData[i].dwInUcastPkts + AdapterData[i].dwInNUcastPkts,\n AdapterData[i].dwInDiscards, AdapterData[i].dwInErrors,\n AdapterData[i].dwInUnknownProtos]));\n WriteLn(#9 + Format('TX packets:%d dropped:%d errors:%d txqueuelen:%d',\n [AdapterData[i].dwOutUcastPkts + AdapterData[i].dwOutNUcastPkts,\n AdapterData[i].dwOutDiscards, AdapterData[i].dwOutErrors,\n AdapterData[i].dwOutQLen]));\n\n WriteLn('');\n end;\n end\n else\n begin\n WriteLn(#13+#10+'*** Error retrieving adapter information');\n end;\n except\n on E: Exception do\n Writeln(E.ClassName, ': ', E.Message);\n end;\nend.\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36544/"
] |
325,874 | <p>I have a TSqlDataSet which has a blob field, I need to get the data of this blob field in the BeforeUpdateRecord event of the provider and execute an update command, I've tried this:</p>
<pre><code>Cmd := TSQLQuery.Create(nil);
try
Cmd.SQLConnection := SQLConnection;
Cmd.CommandText := 'UPDATE MYTABLE SET IMAGE = :PIMAGE WHERE ID = :PID';
Cmd.Params.CreateParam(ftBlob, 'PIMAGE ', ptInput).Value := DeltaDS.FieldByName('IMAGE').NewValue; //blob field
Cmd.Params.CreateParam(ftString, 'PID', ptInput).Value := DeltaDS.FieldByName('ID').NewValue;
Cmd.ExecSQL;
finally
Cmd.Free;
end;
</code></pre>
<p>When I execute that I get an EDatabaseError with message: 'No value for parameter PIMAGE.</p>
<p>What am I missing?</p>
| [
{
"answer_id": 330647,
"author": "Fabio Gomes",
"author_id": 727,
"author_profile": "https://Stackoverflow.com/users/727",
"pm_score": 3,
"selected": true,
"text": "const\n SQL = 'UPDATE MYTABLE SET IMAGE = :PIMAGE WHERE ID = :PID;';\nvar\n Params: TParams;\nbegin\n Params := TParams.Create(nil);\n try\n Params.CreateParam(ftBlob, 'PIMAGE', ptInput).AsBlob := DeltaDS.FieldByName('IMAGE').NewValue;\n Params.CreateParam(ftString, 'PID', ptInput).Value := DeltaDS.FieldByName('ID').NewValue;\n SQLConnection.Execute(SQL, Params);\n finally\n Params.Free;\n end;\nend;\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] |
325,879 | <p>I'm not looking for a general discussion on <a href="https://stackoverflow.com/questions/157354/is-mathematics-necessary-for-programming">if math is important or not for programming</a>. </p>
<p>Instead I'm looking for real world scenarios where you have actually used some branch of math to solve some particular problem during your career as a software developer.</p>
<p>In particular, I'm looking for concrete examples. </p>
| [
{
"answer_id": 325900,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 4,
"selected": true,
"text": "showAll s.ShowToUser bool // Before\n(showAll ? (s.ShowToUser || s.ShowToUser == false) : s.ShowToUser)\n\n// After!\nshowAll || s.ShowToUser\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
325,887 | <p>I have this code</p>
<pre><code><?php
session_start();
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
die("You should have a 'cmd' parameter in your URL");
$pk = $_GET["pk"];
$con = mysql_connect("localhost","root","geheim");
if(!$con)
{
die('Connection failed because of' .mysql_error());
}
mysql_select_db("ebay",$con);
if($cmd=="GetAuctionData")
{
echo "<table border='1' width='100%'>
<tr>
<th>Username</th>
<th>Start Date</th>
<th>Description</th>
</tr>";
$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
echo "<tr>
<td>".$row['USERNAME']."</td>
<td>".$row['ARTICLE_NO']."</td>
<td>".$row['ARTICLE_NAME']."</td>
<td>".$row['SUBTITLE']."</td>
<td>".$row['CURRENT_BID']."</td>
<td>".$row['START_PRICE']."</td>
<td>".$row['BID_COUNT']."</td>
<td>".$row['QUANT_TOTAL']."</td>
<td>".$row['QUANT_SOLD']."</td>
<td>".$row['ACCESSSTARTS']."</td>
<td>".$row['ACCESSENDS']."</td>
<td>".$row['ACCESSORIGIN_END']."</td>
<td>".$row['USERNAME']."</td>
<td>".$row['BEST_BIDDER_ID']."</td>
<td>".$row['FINISHED']."</td>
<td>".$row['WATCH']."</td>
<td>".$row['BUYITNOW_PRICE']."</td>
<td>".$row['PIC_URL']."</td>
<td>".$row['PRIVATE_AUCTION']."</td>
<td>".$row['AUCTION_TYPE']."</td>
<td>".$row['ACCESSINSERT_DATE']."</td>
<td>".$row['ACCESSUPDATE_DATE']."</td>
<td>".$row['CAT_1_ID']."</td>
<td>".$row['CAT_2_ID']."</td>
<td>".$row['ARTICLE_DESC']."</td>
<td>".$row['COUNTRYCODE']."</td>
<td>".$row['LOCATION']."</td>
<td>".$row['CONDITIONS']."</td>
<td>".$row['REVISED']."</td>
<td>".$row['PAYPAL_ACCEPT']."</td>
<td>".$row['PRE_TERMINATED']."</td>
<td>".$row['SHIPPING_TO']."</td>
<td>".$row['FEE_INSERTION']."</td>
<td>".$row['FEE_FINAL']."</td>
<td>".$row['FEE_LISTING']."</td>
<td>".$row['PIC_XXL']."</td>
<td>".$row['PIC_DIASHOW']."</td>
<td>".$row['PIC_COUNT']."</td>
<td>".$row['ITEM_SITE_ID']."</td>
<td>".$row['STARTS']."</td>
<td>".$row['ENDS']."</td>
<td>".$row['ORIGIN_END']."</td>
</tr>
<tr><td></td></tr>";
}
echo "</table>";
echo "<img src=".$row['PIC_URL'].">";
}
mysql_close($con);
?>
</code></pre>
<p>Here is the generated html:</p>
<pre><code><table border='1' width='100%'>
<tr>
<th>Username</th>
<th>Start Date</th>
<th>Description</th>
</tr><tr>
<td>fashionticker1</td>
<td>220288560247</td>
<td>Ed Hardy Herren Shirt Rock & Roll Weiss XXL Neu & OVP</td>
<td></td>
<td>0.00</td>
<td>49.00</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>1.10.2008 16:22:09</td>
<td>6.10.2008 16:22:09</td>
<td>6.10.2008 16:22:09</td>
<td>fashionticker1</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>59.00</td>
<td>http://storage.supremeauction.com/flash/ebay2/10/49/76/10497654/13895964e.jpg</td>
<td>0</td>
<td>1</td>
<td>6.10.2008 16:21:47</td>
<td>6.10.2008 16:28:31</td>
<td>32315</td>
<td>0</td>
<td><!-- +++++++++++++++++++++++++ Bitte ändern Sie im eigenen Interesse nichts an diesem Code! ++++++++++++++++++++++++ -->
<!-- +++++++++++++++++++++++++ Das kann massive Fehldarstellungen ihrer Auktion zur Folge haben! +++++++++++++++++++ -->
<!-- +++++++++++++++++++++++++ ++++++++++++++++++++++++++ Ihr Supreme Team +++++++++++++++++++++++++++++++++++++++++ -->
</td>
<td>
<br>
<br>
<style ty</td>
<td>float: right;
</td>
<td>margin: 0px;
</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>padding:5px;
</td>
<td>0.00</td>
<td>0.00</td>
<td>0.00</td>
<td>0</td>
<td>0</td>
<td>font-size: 12px;
</td>
<td>color: #333333;
}
#h</td>
<td>0000-00-00 00:00:00</td>
<td>0000-00-00 00:00:00</td>
<td>0000-00-00 00:00:00</td>
</tr>
<tr><td></td></tr></table><img src=>
</code></pre>
<p>Whatever I do, I can not get an image to display, and when PIC_URL is empty, it only displays a placeholder image above the table, and I want it below.</p>
| [
{
"answer_id": 325934,
"author": "Philip Morton",
"author_id": 21709,
"author_profile": "https://Stackoverflow.com/users/21709",
"pm_score": 2,
"selected": true,
"text": "echo \"<img src=\\\"\".$row['PIC_URL'].\"\\\">\";\n"
},
{
"answer_id": 325942,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "<style ty</td>"
},
{
"answer_id": 326044,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 0,
"selected": false,
"text": "while ($row = mysql_fetch_array($result))\n{\n*snip*\n}\necho \"</table>\";\necho \"<img src=\".$row['PIC_URL'].\">\";\n while ($row = mysql_fetch_array($result))\n{\n*snip*\n$lastImg = $row['PIC_URL'];\n}\necho \"</table>\";\necho \"<img src=\\\"$lastImg\\\">\";\n while ($row = mysql_fetch_array($result))\n{\n *snip*\n $images[] = $row['PIC_URL'];\n}\necho \"</table>\";\n?><p>Are these valid urls you can open in yer browser?</p><pre><?php\n print_r($images);\n?></pre><?php\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
325,892 | <p>I've inherited a BizTalk 2006 application that uses several SOAP ports to request data from a 3rd party web service. The web service is secured by "basic" authentication - username / password. After making a few enhancements to the application I deployed to an integration test server which has access to the 3rd party web service. The BizTalk app was unable to retrieve the data and I soon realised that I had forgotten to set the username / password on the SOAP send ports. I wanted the make deployment of the BizTalk app as automated as possible because I may not be present when it is deployed to the live server. I opened up the binding file, located the 1st of the problem SOAP send ports and looked for the <strong>* that BizTalk uses to replace the password - except that it doesn't! It seems that the password for SOAP ports is set to NULL rather than *</strong>, see here for more details:
<a href="http://msdn.microsoft.com/en-us/library/aa547319.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa547319.aspx</a></p>
<p>I proceeded to update the binding but when I came to test, after importing my amended binding file, I found that I had the same problem as before. I've double checked and can confirm that the correct password is now present in the binding file but, although BizTalk doesn't complain during the import, when I run the app I get the following exception:</p>
<p><em>Details:"ArgumentNullException: String reference not set to an instance of a String.
Parameter name: s
".</em></p>
<p>If I then manually amend the password through the BizTalk admin console everything work fine. </p>
<p>Has anyone else had a similar problem with the bindings for a SOAP port - does anyone have a solution?</p>
| [
{
"answer_id": 326982,
"author": "David Hall",
"author_id": 2660,
"author_profile": "https://Stackoverflow.com/users/2660",
"pm_score": 0,
"selected": false,
"text": "<TransportTypeData>\n<CustomProps>\n<AuthenticationScheme vt=\"8\">Basic</AuthenticationScheme>\n<AssemblyName vt=\"8\">WebService.ProxyClass, Version=1.0.0.0, \nCulture=neutral, PublicKeyToken=xyz</AssemblyName>\n<Username vt=\"8\">soapUser</Username>\n<UseProxy vt=\"11\">0</UseProxy>\n<UseSoap12 vt=\"11\">0</UseSoap12><UsingOrchestration vt=\"11\">0</UsingOrchestration>\n<UseSSO vt=\"11\">0</UseSSO>\n<Password vt=\"8\">MYPASSWORD</Password>\n<ProxyPort vt=\"3\">80</ProxyPort><AssemblyPath\nvt=\"8\">C:\\ProxyClass\\bin\\Debug\\ProxyClass.dll</AssemblyPath>\n<TypeName vt=\"8\">ProxyClass.Webservice.servicesService</TypeName>\n<MethodName vt=\"8\">PickupRequest</MethodName>\n<UseHandlerSetting vt=\"11\">-1</UseHandlerSetting>\n</CustomProps>\n</TransportTypeData>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41169/"
] |
325,906 | <p>When I discovered <a href="http://www.boost.org/doc/libs/1_47_0/libs/conversion/lexical_cast.htm" rel="noreferrer"><code>boost::lexical_cast</code></a> I thought to myself "why didn't I know about this sooner!" - I hated having to write code like </p>
<pre><code>stringstream ss;
ss << anIntVal;
mystring = ss.str();
</code></pre>
<p>Now I write</p>
<pre><code>mystring = boost::lexical_cast<string>(anIntVal);
</code></pre>
<p>Yesterday, on stackoverflow, I came across boost split (another gem that will save me writing code).</p>
<pre><code>string stringtobesplit = "AA/BB-CC")
vector<string> tokens;
boost::split(tokens, stringtobesplit, boost::is_any_of("/-"));
// tokens now holds 3 items: AA BB CC
</code></pre>
<p>I am going to start looking through boost documentation looking for other functions that I will be able to use regularly, but I feel that it will be very easy to miss things. </p>
<p>What boost functions do you use most / would hate not to have? </p>
| [
{
"answer_id": 326874,
"author": "Alessandro Jacopson",
"author_id": 15485,
"author_profile": "https://Stackoverflow.com/users/15485",
"pm_score": 4,
"selected": false,
"text": "BOOST_STATIC_ASSERT static_assert"
},
{
"answer_id": 328046,
"author": "D.Shawley",
"author_id": 41747,
"author_profile": "https://Stackoverflow.com/users/41747",
"pm_score": 3,
"selected": false,
"text": "boost::shared_ptr boost::program_options boost::bind boost::signal"
},
{
"answer_id": 328339,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 4,
"selected": false,
"text": "boost::optional shared_ptr scoped_ptr"
},
{
"answer_id": 533295,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 2,
"selected": false,
"text": "stricmp( \"avalue\", mystr.c_str() ) == 0\n equals( \"avalue\", mystr, is_iequal() ) \n #include <boost/algorithm/string.hpp>\nusing namespace boost::algorithm;\n"
},
{
"answer_id": 2384439,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 5,
"selected": false,
"text": "shared_ptr FILE* void safeclose(FILE*fp) {\n if(fp) {\n fclose(fp);\n }\n}\nvoid some_fn() {\n boost::shared_ptr<FILE> fp( fopen(myfilename, \"a+t\"), safeclose );\n //body of the function, and when ever it exits the file gets closed\n fprintf( fp.get(), \"a message\\n\" );\n}\n"
},
{
"answer_id": 2384503,
"author": "Jon Reid",
"author_id": 246895,
"author_profile": "https://Stackoverflow.com/users/246895",
"pm_score": 3,
"selected": false,
"text": "std::for_each(some_container.begin(), some_container.end(), do_something());\n adobe::for_each(some_container, do_something());\n"
},
{
"answer_id": 3108342,
"author": "amit kumar",
"author_id": 19501,
"author_profile": "https://Stackoverflow.com/users/19501",
"pm_score": 3,
"selected": false,
"text": "shared_ptr"
},
{
"answer_id": 4221016,
"author": "rodrigob",
"author_id": 191068,
"author_profile": "https://Stackoverflow.com/users/191068",
"pm_score": 1,
"selected": false,
"text": "boost::numeric::ublas"
},
{
"answer_id": 8868341,
"author": "Paul Fultz II",
"author_id": 375343,
"author_profile": "https://Stackoverflow.com/users/375343",
"pm_score": 3,
"selected": false,
"text": "string key, value;\nBOOST_FOREACH(tie(key, value), my_map) { ... }\n map<string, string> my_map = map_list_of(\"key1\", \"value1\")(\"key2\", \"value2\")(\"key3\", \"value3\");\n BOOST_FOREACH(string value, my_multimap.equal_range(\"X\") | map_values | reversed) { ... }\n"
},
{
"answer_id": 12288770,
"author": "Zeks",
"author_id": 1143162,
"author_profile": "https://Stackoverflow.com/users/1143162",
"pm_score": 2,
"selected": false,
"text": "boost::icl BOOST_FOREACH boost::function boost::bind std::function std::bind boost::interprocess::message_queue boost::junkie"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3590/"
] |
325,918 | <p>I've got an executable file, and I would like to know which version(s) of the Microsoft .NET Framework this file needs to be started.</p>
<p>Is there an easy way to find this information somewhere?</p>
<p>(So far I tried <a href="https://en.wikipedia.org/wiki/ILDASM#Metadata_storage" rel="noreferrer">ILDASM</a> and <a href="https://support.microsoft.com/kb/177429" rel="noreferrer">DUMPBIN</a> without any luck.)</p>
| [
{
"answer_id": 325966,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 7,
"selected": true,
"text": "// Metadata version: v2.0.50727\n.assembly extern mscorlib\n{\n .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\\V.4..\n .ver 2:0:0:0\n}\n.assembly extern System\n{\n .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\\V.4..\n .ver 2:0:0:0\n}\n .module WindowsFormsApplication1.exe\n.subsystem 0x0002\n// MVID: {CA3D2090-16C5-4899-953E-4736D6BC0FA8}\n// Target Runtime Version: v2.0.50727\n .assembly extern System.Drawing\n{\n .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....:\n .ver 2:0:0:0\n}\n.assembly extern System.Core\n{\n .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\\V.4..\n .ver 3:5:0:0\n}\n .assembly extern System.Core\n{\n .ver 3:5:0:0\n .publickeytoken = (B7 7A 5C 56 19 34 E0 89)\n}\n"
},
{
"answer_id": 1792221,
"author": "Andrew Hare",
"author_id": 34211,
"author_profile": "https://Stackoverflow.com/users/34211",
"pm_score": 4,
"selected": false,
"text": "Assembly.ImageRuntimeVersion mscorlib"
},
{
"answer_id": 17044651,
"author": "tsandhol",
"author_id": 1014595,
"author_profile": "https://Stackoverflow.com/users/1014595",
"pm_score": 5,
"selected": false,
"text": "[assembly: TargetFramework(\".NETFramework,Version=v4.5\", FrameworkDisplayName = \".NET Framework 4.5\")]\n"
},
{
"answer_id": 40211399,
"author": "Asain Kujovic",
"author_id": 838197,
"author_profile": "https://Stackoverflow.com/users/838197",
"pm_score": 6,
"selected": false,
"text": "notepad appname.exe framework F3 .NET Framework,version=vX.Y v2. netstandard netframework"
},
{
"answer_id": 42034182,
"author": "Sean B",
"author_id": 599180,
"author_profile": "https://Stackoverflow.com/users/599180",
"pm_score": 4,
"selected": false,
"text": "find \"Framework\" MyApp.exe"
},
{
"answer_id": 47075766,
"author": "Pierz",
"author_id": 436794,
"author_profile": "https://Stackoverflow.com/users/436794",
"pm_score": 2,
"selected": false,
"text": "strings that_app.exe | grep 'v2.\\|Framework'\n"
},
{
"answer_id": 60891621,
"author": "Mark Walker",
"author_id": 5468279,
"author_profile": "https://Stackoverflow.com/users/5468279",
"pm_score": 3,
"selected": false,
"text": "$path=’.\\’\n$ErrorActionPreference = \"SilentlyContinue\"\n$files=Get-ChildItem -Path $path -Recurse -include *.dll,*.exe\nforeach($file in $files)\n{\n $filename = $file.BaseName\n $version = $([System.Reflection.Assembly]::ReflectionOnlyLoadFrom($file.FullName).GetCustomAttributesData() |\n select-object -ExpandProperty ConstructorArguments | \n select-object -ExpandProperty Value | \n select-string -Pattern '.NET')\n Write-Output \"$filename,$version\"\n}\n"
},
{
"answer_id": 73629123,
"author": "Gaspard Leon",
"author_id": 32601,
"author_profile": "https://Stackoverflow.com/users/32601",
"pm_score": 0,
"selected": false,
"text": "\"runtimeTarget\": {\n \"name\": \".NETCoreApp,Version=v6.0/win-x86\"\n .NETCoreApp,Version=v6.0\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
] |
325,929 | <p>In HTML, you can send data from one page to another using a GET request in a couple of ways:</p>
<pre><code>http://www.example.com/somepage.php?data=1
</code></pre>
<p>...or...</p>
<pre><code><form action="somepage.php" method="get">
<input type="hidden" name="data" value="1" />
<input type="submit" value="Submit">
</form>
</code></pre>
<p>With a POST request though, I've only seen data being sent through form elements like this:</p>
<pre><code><form action="somepage.php" method="post">
<input type="hidden" name="data" value="1" />
<input type="submit" value="Submit">
</form>
</code></pre>
<p>If I only have one parameter I want to send to another page using POST, is there an easier way than wrapping it in a form?</p>
| [
{
"answer_id": 326073,
"author": "Ed Lucas",
"author_id": 12551,
"author_profile": "https://Stackoverflow.com/users/12551",
"pm_score": 2,
"selected": false,
"text": "GET POST HEAD GET POST <form> GET foo.html?a=1&b=2 POST POST <form> GET POST GET POST POST"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
325,931 | <p>I want to do exactly the same as in <a href="https://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windows">this question</a>:</p>
<blockquote>
<p>Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the actual name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)?</p>
</blockquote>
<p>But I need to do it in .NET and I want the full path (<code>D:/Temp/Foobar.xml</code> and not just <code>Foobar.xml</code>).</p>
<p>I see that <code>FullName</code> on the <code>FileInfo</code> class doesn't do the trick.</p>
| [
{
"answer_id": 326153,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 6,
"selected": true,
"text": " public static string GetExactPathName(string pathName)\n {\n if (!(File.Exists(pathName) || Directory.Exists(pathName)))\n return pathName;\n\n var di = new DirectoryInfo(pathName);\n\n if (di.Parent != null) {\n return Path.Combine(\n GetExactPathName(di.Parent.FullName), \n di.Parent.GetFileSystemInfos(di.Name)[0].Name);\n } else {\n return di.Name.ToUpper();\n }\n }\n static void Main(string[] args)\n {\n string file1 = @\"c:\\documents and settings\\administrator\\ntuser.dat\";\n string file2 = @\"c:\\pagefile.sys\";\n string file3 = @\"c:\\windows\\system32\\cmd.exe\";\n string file4 = @\"c:\\program files\\common files\";\n string file5 = @\"ddd\";\n\n Console.WriteLine(GetExactPathName(file1));\n Console.WriteLine(GetExactPathName(file2));\n Console.WriteLine(GetExactPathName(file3));\n Console.WriteLine(GetExactPathName(file4));\n Console.WriteLine(GetExactPathName(file5));\n\n Console.ReadLine();\n }\n"
},
{
"answer_id": 5359874,
"author": "Ivan Ferrer Villa",
"author_id": 382515,
"author_profile": "https://Stackoverflow.com/users/382515",
"pm_score": -1,
"selected": false,
"text": " Public Function gfnProperPath(ByVal sPath As String) As String\n If Not IO.File.Exists(sPath) AndAlso Not IO.Directory.Exists(sPath) Then Return sPath\n Dim sarSplitPath() As String = sPath.Split(\"\\\")\n Dim sAddPath As String = sarSplitPath(0).ToUpper & \"\\\"\n For i = 1 To sarSplitPath.Length - 1\n sPath = sAddPath & \"\\\" & sarSplitPath(i)\n If IO.File.Exists(sPath) Then\n Return IO.Directory.GetFiles(sAddPath, sarSplitPath(i), IO.SearchOption.TopDirectoryOnly)(0)\n ElseIf IO.Directory.Exists(sPath) Then\n sAddPath = IO.Directory.GetDirectories(sAddPath, sarSplitPath(i), IO.SearchOption.TopDirectoryOnly)(0)\n End If\n Next\n Return sPath\nEnd Function\n"
},
{
"answer_id": 11436327,
"author": "Ivan Ferrer Villa",
"author_id": 382515,
"author_profile": "https://Stackoverflow.com/users/382515",
"pm_score": 2,
"selected": false,
"text": "private string fnRealCAPS(string sDirOrFile)\n{\n string sTmp = \"\";\n foreach (string sPth in sDirOrFile.Split(\"\\\\\")) {\n if (string.IsNullOrEmpty(sTmp)) {\n sTmp = sPth + \"\\\\\";\n continue;\n }\n sTmp = System.IO.Directory.GetFileSystemEntries(sTmp, sPth)[0];\n }\n return sTmp;\n}"
},
{
"answer_id": 28919652,
"author": "bingles",
"author_id": 20489,
"author_profile": "https://Stackoverflow.com/users/20489",
"pm_score": 3,
"selected": false,
"text": "public string FixFilePathCasing(string filePath)\n{\n string fullFilePath = Path.GetFullPath(filePath);\n\n string fixedPath = \"\";\n foreach(string token in fullFilePath.Split('\\\\'))\n {\n //first token should be drive token\n if(fixedPath == \"\")\n {\n //fix drive casing\n string drive = string.Concat(token, \"\\\\\");\n drive = DriveInfo.GetDrives()\n .First(driveInfo => driveInfo.Name.Equals(drive, StringComparison.OrdinalIgnoreCase)).Name;\n\n fixedPath = drive;\n }\n else\n {\n fixedPath = Directory.GetFileSystemEntries(fixedPath, token).First();\n }\n }\n\n return fixedPath;\n}\n"
},
{
"answer_id": 29578292,
"author": "Bill Menees",
"author_id": 1882616,
"author_profile": "https://Stackoverflow.com/users/1882616",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Gets the exact case used on the file system for an existing file or directory.\n/// </summary>\n/// <param name=\"path\">A relative or absolute path.</param>\n/// <param name=\"exactPath\">The full path using the correct case if the path exists. Otherwise, null.</param>\n/// <returns>True if the exact path was found. False otherwise.</returns>\n/// <remarks>\n/// This supports drive-lettered paths and UNC paths, but a UNC root\n/// will be returned in title case (e.g., \\\\Server\\Share).\n/// </remarks>\npublic static bool TryGetExactPath(string path, out string exactPath)\n{\n bool result = false;\n exactPath = null;\n\n // DirectoryInfo accepts either a file path or a directory path, and most of its properties work for either.\n // However, its Exists property only works for a directory path.\n DirectoryInfo directory = new DirectoryInfo(path);\n if (File.Exists(path) || directory.Exists)\n {\n List<string> parts = new List<string>();\n\n DirectoryInfo parentDirectory = directory.Parent;\n while (parentDirectory != null)\n {\n FileSystemInfo entry = parentDirectory.EnumerateFileSystemInfos(directory.Name).First();\n parts.Add(entry.Name);\n\n directory = parentDirectory;\n parentDirectory = directory.Parent;\n }\n\n // Handle the root part (i.e., drive letter or UNC \\\\server\\share).\n string root = directory.FullName;\n if (root.Contains(':'))\n {\n root = root.ToUpper();\n }\n else\n {\n string[] rootParts = root.Split('\\\\');\n root = string.Join(\"\\\\\", rootParts.Select(part => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(part)));\n }\n\n parts.Add(root);\n parts.Reverse();\n exactPath = Path.Combine(parts.ToArray());\n result = true;\n }\n\n return result;\n}\n [TestMethod]\npublic void TryGetExactPathNameTest()\n{\n string machineName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Environment.MachineName.ToLower());\n string[] testPaths = new[]\n {\n @\"C:\\Users\\Public\\desktop.ini\",\n @\"C:\\pagefile.sys\",\n @\"C:\\Windows\\System32\\cmd.exe\",\n @\"C:\\Users\\Default\\NTUSER.DAT\",\n @\"C:\\Program Files (x86)\\Microsoft.NET\\Primary Interop Assemblies\",\n @\"C:\\Program Files (x86)\",\n @\"Does not exist\",\n @\"\\\\Nas\\Main\\Setups\",\n @\"\\\\Nas\\Main\\Setups\\Microsoft\\Visual Studio\\VS 2015\\vssdk_full.exe\",\n @\"\\\\\" + machineName + @\"\\C$\\Windows\\System32\\ActionCenter.dll\",\n @\"..\",\n };\n Dictionary<string, string> expectedExactPaths = new Dictionary<string, string>()\n {\n { @\"..\", Path.GetDirectoryName(Environment.CurrentDirectory) },\n };\n\n foreach (string testPath in testPaths)\n {\n string lowercasePath = testPath.ToLower();\n bool expected = File.Exists(lowercasePath) || Directory.Exists(lowercasePath);\n string exactPath;\n bool actual = FileUtility.TryGetExactPath(lowercasePath, out exactPath);\n actual.ShouldEqual(expected);\n if (actual)\n {\n string expectedExactPath;\n if (expectedExactPaths.TryGetValue(testPath, out expectedExactPath))\n {\n exactPath.ShouldEqual(expectedExactPath);\n }\n else\n {\n exactPath.ShouldEqual(testPath);\n }\n }\n else\n {\n exactPath.ShouldBeNull();\n }\n }\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] |
325,933 | <p>Given two date ranges, what is the simplest or most efficient way to determine whether the two date ranges overlap?</p>
<p>As an example, suppose we have ranges denoted by DateTime variables <code>StartDate1</code> to <code>EndDate1</code> <em>and</em> <code>StartDate2</code> to <code>EndDate2</code>.</p>
| [
{
"answer_id": 325939,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 9,
"selected": false,
"text": "(StartDate1 <= EndDate2) and (StartDate2 <= EndDate1)\n"
},
{
"answer_id": 325943,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 3,
"selected": false,
"text": "StartDate1.IsBetween(StartDate2, EndDate2) || EndDate1.IsBetween(StartDate2, EndDate2)\n IsBetween public static bool IsBetween(this DateTime value, DateTime left, DateTime right) {\n return (value > left && value < right) || (value < left && value > right);\n }\n"
},
{
"answer_id": 325964,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 12,
"selected": true,
"text": "_ |---- DateRange A ------|\n|---Date Range B -----| _\n StartA > EndB |---- DateRange A -----| _ \n_ |---Date Range B ----|\n EndA < StartB Not (A Or B) Not A And Not B (StartA <= EndB) and (EndA >= StartB) >= > <= < endA-startA endA - startB endB-startA endB - startB (StartA <= EndB) and (EndA >= StartB) (StartA <= EndB) and (StartB <= EndA) DateRangesOverlap = max(start1, start2) < min(end1, end2) startA > endA startB > endB (StartA <= EndB) and (StartB <= EndA) and (StartA <= EndA) and (StartB <= EndB) (StartA <= EndB) and (StartA <= EndA) and (StartB <= EndA) and (StartB <= EndB) (StartA <= Min(EndA, EndB) and (StartB <= Min(EndA, EndB)) (Max(StartA, StartB) <= Min(EndA, EndB) Min() Max() (StartA > StartB? Start A: StartB) <= (EndA < EndB? EndA: EndB)"
},
{
"answer_id": 328558,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 7,
"selected": false,
"text": "A B .start .end .start <= .end A.end >= B.start AND A.start <= B.end\n >= > <= < ----------------------|-------A-------|----------------------\n |----B1----|\n |----B2----|\n |----B3----|\n |----------B4----------|\n |----------------B5----------------|\n |----B6----|\n----------------------|-------A-------|----------------------\n |------B7-------|\n |----------B8-----------|\n |----B9----|\n |----B10-----|\n |--------B11--------|\n |----B12----|\n |----B13----|\n----------------------|-------A-------|----------------------\n"
},
{
"answer_id": 743098,
"author": "staceyw",
"author_id": 90124,
"author_profile": "https://Stackoverflow.com/users/90124",
"pm_score": -1,
"selected": false,
"text": " // Takes a list and returns all records that have overlapping time ranges.\n public static IEnumerable<T> GetOverlappedTimes<T>(IEnumerable<T> list, Func<T, bool> filter, Func<T,DateTime> start, Func<T, DateTime> end)\n {\n // Selects all records that match filter() on left side and returns all records on right side that overlap.\n var overlap = from t1 in list\n where filter(t1)\n from t2 in list\n where !object.Equals(t1, t2) // Don't match the same record on right side.\n let in1 = start(t1)\n let out1 = end(t1)\n let in2 = start(t2)\n let out2 = end(t2)\n where in1 <= out2 && out1 >= in2\n let totover = GetMins(in1, out1, in2, out2)\n select t2;\n\n return overlap;\n }\n\n public static void TestOverlap()\n {\n var tl1 = new TempTimeEntry() { ID = 1, Name = \"Bill\", In = \"1/1/08 1:00pm\".ToDate(), Out = \"1/1/08 4:00pm\".ToDate() };\n var tl2 = new TempTimeEntry() { ID = 2, Name = \"John\", In = \"1/1/08 5:00pm\".ToDate(), Out = \"1/1/08 6:00pm\".ToDate() };\n var tl3 = new TempTimeEntry() { ID = 3, Name = \"Lisa\", In = \"1/1/08 7:00pm\".ToDate(), Out = \"1/1/08 9:00pm\".ToDate() };\n var tl4 = new TempTimeEntry() { ID = 4, Name = \"Joe\", In = \"1/1/08 3:00pm\".ToDate(), Out = \"1/1/08 8:00pm\".ToDate() };\n var tl5 = new TempTimeEntry() { ID = 1, Name = \"Bill\", In = \"1/1/08 8:01pm\".ToDate(), Out = \"1/1/08 8:00pm\".ToDate() };\n var list = new List<TempTimeEntry>() { tl1, tl2, tl3, tl4, tl5 };\n var overlap = GetOverlappedTimes(list, (TempTimeEntry t1)=>t1.ID==1, (TempTimeEntry tIn) => tIn.In, (TempTimeEntry tOut) => tOut.Out);\n\n Console.WriteLine(\"\\nRecords overlap:\");\n foreach (var tl in overlap)\n Console.WriteLine(\"Name:{0} T1In:{1} T1Out:{2}\", tl.Name, tl.In, tl.Out);\n Console.WriteLine(\"Done\");\n\n /* Output:\n Records overlap:\n Name:Joe T1In:1/1/2008 3:00:00 PM T1Out:1/1/2008 8:00:00 PM\n Name:Lisa T1In:1/1/2008 7:00:00 PM T1Out:1/1/2008 9:00:00 PM\n Done\n */\n }\n"
},
{
"answer_id": 3420667,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": false,
"text": "> |-----| range 1, lines below are all range 2.\n|--> : overlap.\n |--> : overlap.\n |---> overlap (no overlap in exclusive-of-end case).\n |---> no overlap.\n s <= e def overlaps(r1, r2):\n if r1.s > r2.s:\n swap r1, r2\n return r2.s <= r1.e\n def overlaps(r1, r2):\n if r1.s <= r2.s:\n return r2.s <= r1.e\n return overlaps(r2, r1)\n <= < InclusiveRange class InclusiveRange:\n \"\"\"InclusiveRange class to represent a lower and upper bound.\"\"\"\n\n def __init__(self, start, end):\n \"\"\"Initialisation, ensures start <= end.\n Args:\n start: The start of the range.\n end: The end of the range.\n \"\"\"\n self.start = min(start, end)\n self.end = max(start, end)\n\n def __repr__(self):\n \"\"\"Return representation for f-string.\"\"\"\n return f\"({self.start}, {self.end})\"\n\n def overlaps(self, other):\n \"\"\"True if range overlaps with another.\n Args:\n other: The other InclusiveRange to check against.\n \"\"\"\n\n # Very limited recursion to ensure start of first range\n # isn't after start of second.\n\n if self.start > other.start:\n return other.overlaps(self)\n\n # Greatly simplified check for overlap.\n\n return other.start <= self.end\n def test_case(range1, range2):\n \"\"\"Single test case checker.\"\"\"\n\n # Get low and high value for \"graphic\" output.\n\n low = min(range1.start, range2.start)\n high = max(range1.end, range2.end)\n\n # Output ranges and graphic.\n\n print(f\"r1={range1} r2={range2}: \", end=\"\")\n for val in range(low, high + 1):\n is_in_first = range1.start <= val <= range1.end\n is_in_second = range2.start <= val <= range2.end\n\n if is_in_first and is_in_second:\n print(\"|\", end=\"\")\n elif is_in_first:\n print(\"'\", end=\"\")\n elif is_in_second:\n print(\",\", end=\"\")\n else:\n print(\" \", end=\"\")\n\n # Finally, output result of overlap check.\n\n print(f\" - {range1.overlaps(range2)}\\n\")\n # Various test cases, add others if you doubt the correctness.\n\ntest_case(InclusiveRange(0, 1), InclusiveRange(8, 9))\ntest_case(InclusiveRange(0, 4), InclusiveRange(5, 9))\ntest_case(InclusiveRange(0, 4), InclusiveRange(4, 9))\ntest_case(InclusiveRange(0, 7), InclusiveRange(2, 9))\ntest_case(InclusiveRange(0, 4), InclusiveRange(0, 9))\ntest_case(InclusiveRange(0, 9), InclusiveRange(0, 9))\ntest_case(InclusiveRange(0, 9), InclusiveRange(4, 5))\n\ntest_case(InclusiveRange(8, 9), InclusiveRange(0, 1))\ntest_case(InclusiveRange(5, 9), InclusiveRange(0, 4))\ntest_case(InclusiveRange(4, 9), InclusiveRange(0, 4))\ntest_case(InclusiveRange(2, 9), InclusiveRange(0, 7))\ntest_case(InclusiveRange(0, 9), InclusiveRange(0, 4))\ntest_case(InclusiveRange(0, 9), InclusiveRange(0, 9))\ntest_case(InclusiveRange(4, 5), InclusiveRange(0, 9))\n r1=(0, 1) r2=(8, 9): '' ,, - False\nr1=(0, 4) r2=(5, 9): ''''',,,,, - False\nr1=(0, 4) r2=(4, 9): ''''|,,,,, - True\nr1=(0, 7) r2=(2, 9): ''||||||,, - True\nr1=(0, 4) r2=(0, 9): |||||,,,,, - True\nr1=(0, 9) r2=(0, 9): |||||||||| - True\nr1=(0, 9) r2=(4, 5): ''''||'''' - True\nr1=(8, 9) r2=(0, 1): ,, '' - False\nr1=(5, 9) r2=(0, 4): ,,,,,''''' - False\nr1=(4, 9) r2=(0, 4): ,,,,|''''' - True\nr1=(2, 9) r2=(0, 7): ,,||||||'' - True\nr1=(0, 9) r2=(0, 4): |||||''''' - True\nr1=(0, 9) r2=(0, 9): |||||||||| - True\nr1=(4, 5) r2=(0, 9): ,,,,||,,,, - True\n ' , | |"
},
{
"answer_id": 5601502,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "// ------------------------------------------------------------------------\npublic enum PeriodRelation\n{\n After,\n StartTouching,\n StartInside,\n InsideStartTouching,\n EnclosingStartTouching,\n Enclosing,\n EnclosingEndTouching,\n ExactMatch,\n Inside,\n InsideEndTouching,\n EndInside,\n EndTouching,\n Before,\n} // enum PeriodRelation\n"
},
{
"answer_id": 8968195,
"author": "Syam",
"author_id": 1164445,
"author_profile": "https://Stackoverflow.com/users/1164445",
"pm_score": -1,
"selected": false,
"text": "if (StartDate1 > StartDate2) swap(StartDate, EndDate);\n\n(StartDate1 <= EndDate2) and (StartDate2 <= EndDate1);\n"
},
{
"answer_id": 12292052,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 5,
"selected": false,
"text": "overlap = max(0, min(EndDate1, EndDate2) - max(StartDate1, StartDate2))\nif (overlap > 0) { \n ...\n}\n"
},
{
"answer_id": 18773767,
"author": "Ignacio Pascual",
"author_id": 629486,
"author_profile": "https://Stackoverflow.com/users/629486",
"pm_score": 3,
"selected": false,
"text": "// Current row dates\nvar dateStart = moment(\"2014-08-01\", \"YYYY-MM-DD\");\nvar dateEnd = moment(\"2014-08-30\", \"YYYY-MM-DD\");\n\n// Check with dates above\nvar rangeUsedStart = moment(\"2014-08-02\", \"YYYY-MM-DD\");\nvar rangeUsedEnd = moment(\"2014-08-015\", \"YYYY-MM-DD\");\n\n// Range covers other ?\nif((dateStart <= rangeUsedStart) && (rangeUsedEnd <= dateEnd)) {\n return false;\n}\n// Range intersects with other start ?\nif((dateStart <= rangeUsedStart) && (rangeUsedStart <= dateEnd)) {\n return false;\n}\n// Range intersects with other end ?\nif((dateStart <= rangeUsedEnd) && (rangeUsedEnd <= dateEnd)) {\n return false;\n}\n\n// All good\nreturn true;\n"
},
{
"answer_id": 22636418,
"author": "Ilya",
"author_id": 3459922,
"author_profile": "https://Stackoverflow.com/users/3459922",
"pm_score": 0,
"selected": false,
"text": "//custom date for example\n$d1 = new DateTime(\"2012-07-08\");\n$d2 = new DateTime(\"2012-07-11\");\n$d3 = new DateTime(\"2012-07-08\");\n$d4 = new DateTime(\"2012-07-15\");\n\n//create a date period object\n$interval = new DateInterval('P1D');\n$daterange = iterator_to_array(new DatePeriod($d1, $interval, $d2));\n$daterange1 = iterator_to_array(new DatePeriod($d3, $interval, $d4));\narray_map(function($v) use ($daterange1) { if(in_array($v, $daterange1)) print \"Bingo!\";}, $daterange);\n"
},
{
"answer_id": 22694048,
"author": "jack",
"author_id": 3310896,
"author_profile": "https://Stackoverflow.com/users/3310896",
"pm_score": 2,
"selected": false,
"text": "(Startdate BETWEEN '\".$startdate2.\"' AND '\".$enddate2.\"') //overlap: starts between start2/end2\nOR (Startdate < '\".$startdate2.\"' \n AND (enddate = '0000-00-00' OR enddate >= '\".$startdate2.\"')\n) //overlap: starts before start2 and enddate not set 0000-00-00 (still on going) or if enddate is set but higher then startdate2\n"
},
{
"answer_id": 24587032,
"author": "Prasenjit Banerjee",
"author_id": 3807810,
"author_profile": "https://Stackoverflow.com/users/3807810",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION IsOverlapDates \n(\n @startDate1 as datetime,\n @endDate1 as datetime,\n @startDate2 as datetime,\n @endDate2 as datetime\n)\nRETURNS int\nAS\nBEGIN\nDECLARE @Overlap as int\nSET @Overlap = (SELECT CASE WHEN (\n (@startDate1 BETWEEN @startDate2 AND @endDate2) -- caters for inner and end date outer\n OR\n (@endDate1 BETWEEN @startDate2 AND @endDate2) -- caters for inner and start date outer\n OR\n (@startDate2 BETWEEN @startDate1 AND @endDate1) -- only one needed for outer range where dates are inside.\n ) THEN 1 ELSE 0 END\n )\n RETURN @Overlap\n\nEND\nGO\n\n--Execution of the above code\nDECLARE @startDate1 as datetime\nDECLARE @endDate1 as datetime\nDECLARE @startDate2 as datetime\nDECLARE @endDate2 as datetime\nDECLARE @Overlap as int\nSET @startDate1 = '2014-06-01 01:00:00' \nSET @endDate1 = '2014-06-01 02:00:00'\nSET @startDate2 = '2014-06-01 01:00:00' \nSET @endDate2 = '2014-06-01 01:30:00'\n\nSET @Overlap = [dbo].[IsOverlapDates] (@startDate1, @endDate1, @startDate2, @endDate2)\n\nSELECT Overlap = @Overlap\n"
},
{
"answer_id": 24830438,
"author": "mmarjeh",
"author_id": 2991677,
"author_profile": "https://Stackoverflow.com/users/2991677",
"pm_score": 0,
"selected": false,
"text": "public static class NumberExtensionMethods\n {\n public static Boolean IsBetween(this Int64 value, Int64 Min, Int64 Max)\n {\n if (value >= Min && value <= Max) return true;\n else return false;\n }\n\n public static Boolean IsBetween(this DateTime value, DateTime Min, DateTime Max)\n {\n Int64 numricValue = value.Ticks;\n Int64 numericStartDate = Min.Ticks;\n Int64 numericEndDate = Max.Ticks;\n\n if (numricValue.IsBetween(numericStartDate, numericEndDate) )\n {\n return true;\n }\n\n return false;\n }\n }\n\npublic static Boolean IsOverlap(DateTime startDate1, DateTime endDate1, DateTime startDate2, DateTime endDate2)\n {\n Int64 numericStartDate1 = startDate1.Ticks;\n Int64 numericEndDate1 = endDate1.Ticks;\n Int64 numericStartDate2 = startDate2.Ticks;\n Int64 numericEndDate2 = endDate2.Ticks;\n\n if (numericStartDate2.IsBetween(numericStartDate1, numericEndDate1) ||\n numericEndDate2.IsBetween(numericStartDate1, numericEndDate1) ||\n numericStartDate1.IsBetween(numericStartDate2, numericEndDate2) ||\n numericEndDate1.IsBetween(numericStartDate2, numericEndDate2))\n {\n return true;\n }\n\n return false;\n } \n\n\nif (IsOverlap(startdate1, enddate1, startdate2, enddate2))\n {\n Console.WriteLine(\"IsOverlap\");\n }\n"
},
{
"answer_id": 27174072,
"author": "Fez Vrasta",
"author_id": 2059996,
"author_profile": "https://Stackoverflow.com/users/2059996",
"pm_score": 0,
"selected": false,
"text": "TEST1: (X <= A || X >= B)\n &&\nTEST2: (Y >= B || Y <= A) \n && \nTEST3: (X >= B || Y <= A)\n\n\nX-------------Y\n A-----B\n\nTEST1: TRUE\nTEST2: TRUE\nTEST3: FALSE\nRESULT: FALSE\n\n---------------------------------------\n\nX---Y\n A---B\n\nTEST1: TRUE\nTEST2: TRUE\nTEST3: TRUE\nRESULT: TRUE\n\n---------------------------------------\n\n X---Y\nA---B\n\nTEST1: TRUE\nTEST2: TRUE\nTEST3: TRUE\nRESULT: TRUE\n\n---------------------------------------\n\n X----Y\nA---------------B\n\nTEST1: FALSE\nTEST2: FALSE\nTEST3: FALSE\nRESULT: FALSE\n"
},
{
"answer_id": 28359077,
"author": "Shehan Simen",
"author_id": 3059896,
"author_profile": "https://Stackoverflow.com/users/3059896",
"pm_score": 1,
"selected": false,
"text": " public static boolean checkTimeOverlaps(Date startDate1, Date endDate1, Date startDate2, Date endDate2)\n {\n if (startDate1 == null || endDate1 == null || startDate2 == null || endDate2 == null)\n return false;\n\n if ((startDate1.getTime() <= endDate2.getTime()) && (startDate2.getTime() <= endDate1.getTime()))\n return true;\n\n return false;\n }\n"
},
{
"answer_id": 29033282,
"author": "yankee",
"author_id": 327301,
"author_profile": "https://Stackoverflow.com/users/327301",
"pm_score": 4,
"selected": false,
"text": "/**\n * Compares to comparable objects to find out whether they overlap.\n * It is assumed that the interval is in the format [from,to) (read: from is inclusive, to is exclusive).\n * A null value is interpreted as infinity\n */\nfunction intervalsOverlap(from1, to1, from2, to2) {\n return (to2 === null || from1 < to2) && (to1 === null || to1 > from2);\n}\n describe('', function() {\n function generateTest(firstRange, secondRange, expected) {\n it(JSON.stringify(firstRange) + ' and ' + JSON.stringify(secondRange), function() {\n expect(intervalsOverlap(firstRange[0], firstRange[1], secondRange[0], secondRange[1])).toBe(expected);\n });\n }\n\n describe('no overlap (touching ends)', function() {\n generateTest([10,20], [20,30], false);\n generateTest([20,30], [10,20], false);\n\n generateTest([10,20], [20,null], false);\n generateTest([20,null], [10,20], false);\n\n generateTest([null,20], [20,30], false);\n generateTest([20,30], [null,20], false);\n });\n\n describe('do overlap (one end overlaps)', function() {\n generateTest([10,20], [19,30], true);\n generateTest([19,30], [10,20], true);\n\n generateTest([10,20], [null,30], true);\n generateTest([10,20], [19,null], true);\n generateTest([null,30], [10,20], true);\n generateTest([19,null], [10,20], true);\n });\n\n describe('do overlap (one range included in other range)', function() {\n generateTest([10,40], [20,30], true);\n generateTest([20,30], [10,40], true);\n\n generateTest([10,40], [null,null], true);\n generateTest([null,null], [10,40], true);\n });\n\n describe('do overlap (both ranges equal)', function() {\n generateTest([10,20], [10,20], true);\n\n generateTest([null,20], [null,20], true);\n generateTest([10,null], [10,null], true);\n generateTest([null,null], [null,null], true);\n });\n});\n"
},
{
"answer_id": 33324544,
"author": "mahatmanich",
"author_id": 316408,
"author_profile": "https://Stackoverflow.com/users/316408",
"pm_score": 1,
"selected": false,
"text": "class Interval < ActiveRecord::Base\n\n validates_presence_of :start_date, :end_date\n\n # Check if a given interval overlaps this interval \n def overlaps?(other)\n (start_date - other.end_date) * (other.start_date - end_date) >= 0\n end\n\n # Return a scope for all interval overlapping the given interval, including the given interval itself\n named_scope :overlapping, lambda { |interval| {\n :conditions => [\"id <> ? AND (DATEDIFF(start_date, ?) * DATEDIFF(?, end_date)) >= 0\", interval.id, interval.end_date, interval.start_date]\n }}\n\nend\n"
},
{
"answer_id": 34887727,
"author": "Shravan Ramamurthy",
"author_id": 4058910,
"author_profile": "https://Stackoverflow.com/users/4058910",
"pm_score": 0,
"selected": false,
"text": "select id from table_name where (START_DT_TM >= 'END_DATE_TIME' OR \n(END_DT_TM BETWEEN 'START_DATE_TIME' AND 'END_DATE_TIME'))\n"
},
{
"answer_id": 40433114,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "someInterval.overlaps( anotherInterval )\n java.time Interval language-agnostic Interval org.threeten.extra.Interval java.time.Instant Instant start = Instant.parse( \"2016-01-01T00:00:00Z\" );\nInstant stop = Instant.parse( \"2016-02-01T00:00:00Z\" );\n Interval Interval interval_A = Interval.of( start , stop );\n Interval Duration Instant start_B = Instant.parse( \"2016-01-03T00:00:00Z\" );\nInterval interval_B = Interval.of( start_B , Duration.of( 3 , ChronoUnit.DAYS ) );\n Boolean overlaps = interval_A.overlaps( interval_B );\n Interval Interval Instant abuts contains encloses equals isAfter isBefore overlaps Half-Open"
},
{
"answer_id": 41064604,
"author": "Tom McDonough",
"author_id": 4965921,
"author_profile": "https://Stackoverflow.com/users/4965921",
"pm_score": 2,
"selected": false,
"text": "SELECT DISTINCT T1.EmpID\nFROM Table1 T1\nINNER JOIN Table2 T2 ON T1.EmpID = T2.EmpID \n AND T1.JobID <> T2.JobID\n AND (\n (T1.DateFrom >= T2.DateFrom AND T1.dateFrom <= T2.DateTo) \n OR (T1.DateTo >= T2.DateFrom AND T1.DateTo <= T2.DateTo)\n OR (T1.DateFrom < T2.DateFrom AND T1.DateTo IS NULL)\n )\n AND NOT (T1.DateFrom = T2.DateFrom)\n"
},
{
"answer_id": 41721554,
"author": "Gus",
"author_id": 2272346,
"author_profile": "https://Stackoverflow.com/users/2272346",
"pm_score": 2,
"selected": false,
"text": " (startB <= startA && endB > startA)\n|| (startB >= startA && startB < endA)\n"
},
{
"answer_id": 41757253,
"author": "sorry_I_wont",
"author_id": 4522920,
"author_profile": "https://Stackoverflow.com/users/4522920",
"pm_score": -1,
"selected": false,
"text": "compare the two dates: \n A = the one with smaller start date, B = the one with bigger start date\nif(A.end < B.start)\n return false\nreturn true\n"
},
{
"answer_id": 42361538,
"author": "Khaled.K",
"author_id": 2128327,
"author_profile": "https://Stackoverflow.com/users/2128327",
"pm_score": 3,
"selected": false,
"text": "private Boolean overlap (Timestamp startA, Timestamp endA,\n Timestamp startB, Timestamp endB)\n{\n return (endB == null || startA == null || !startA.after(endB))\n && (endA == null || startB == null || !endA.before(startB));\n}\n"
},
{
"answer_id": 43315879,
"author": "Meno Hochschild",
"author_id": 2491410,
"author_profile": "https://Stackoverflow.com/users/2491410",
"pm_score": 2,
"selected": false,
"text": "MomentInterval a = MomentInterval.between(Instant.now(), Instant.now().plusSeconds(2));\nMomentInterval b = a.collapse(); // make b an empty interval out of a\n\nSystem.out.println(a); // [2017-04-10T05:28:11,909000000Z/2017-04-10T05:28:13,909000000Z)\nSystem.out.println(b); // [2017-04-10T05:28:11,909000000Z/2017-04-10T05:28:11,909000000Z)\n System.out.println(\n \"startA < endB: \" + a.getStartAsInstant().isBefore(b.getEndAsInstant())); // false\nSystem.out.println(\n \"endA > startB: \" + a.getEndAsInstant().isAfter(b.getStartAsInstant())); // true\n\nSystem.out.println(\"a overlaps b: \" + a.intersects(b)); // a overlaps b: false\n"
},
{
"answer_id": 44552629,
"author": "user2314737",
"author_id": 2314737,
"author_profile": "https://Stackoverflow.com/users/2314737",
"pm_score": 2,
"selected": false,
"text": "A = [StartA, EndA]\nB = [StartB, EndB]\n\n [---- DateRange A ------] (True if StartA > EndB)\n[--- Date Range B -----] \n\n\n[---- DateRange A -----] (True if EndA < StartB)\n [--- Date Range B ----]\n (StartA <= EndB) and (EndA >= StartB) A = (StartA, EndA)\nB = (StartB, EndB)\n\n (---- DateRange A ------) (True if StartA >= EndB)\n(--- Date Range B -----) \n\n(---- DateRange A -----) (True if EndA <= StartB)\n (--- Date Range B ----)\n (StartA < EndB) and (EndA > StartB) A = [StartA, EndA)\nB = [StartB, EndB)\n\n [---- DateRange A ------) (True if StartA >= EndB) \n[--- Date Range B -----) \n\n[---- DateRange A -----) (True if EndA <= StartB)\n [--- Date Range B ----)\n (StartA < EndB) and (EndA > StartB) A = (StartA, EndA]\nB = (StartB, EndB]\n\n (---- DateRange A ------] (True if StartA >= EndB)\n(--- Date Range B -----] \n\n(---- DateRange A -----] (True if EndA <= StartB)\n (--- Date Range B ----]\n (StartA < EndB) and (EndA > StartB) A = [StartA, EndA)\nB = [StartB, EndB]\n\n [---- DateRange A ------) (True if StartA > EndB)\n[--- Date Range B -----] \n\n\n[---- DateRange A -----) (True if EndA <= StartB) \n [--- Date Range B ----]\n (StartA <= EndB) and (EndA > StartB)"
},
{
"answer_id": 46580523,
"author": "AL-zami",
"author_id": 3138436,
"author_profile": "https://Stackoverflow.com/users/3138436",
"pm_score": 1,
"selected": false,
"text": "@StartDate @EndDate @StartDate existingStartDate existingEndDate @StartDate @StartDate >=existing.StartDate And @StartDate <= existing.EndDate) \n @StartDate existingStartDate @EndDate existingStartDate (@StartDate <= existing.StartDate And @EndDate >= existing.StartDate)\n @StartDate existingStartDate @EndDate existingEndDate (@StartDate <= existing.StartDate And @EndDate >= existing.EndDate))\n"
},
{
"answer_id": 46992092,
"author": "sandeep talabathula",
"author_id": 212661,
"author_profile": "https://Stackoverflow.com/users/212661",
"pm_score": 4,
"selected": false,
"text": " var isOverlapping = ((A == null || D == null || A <= D) \n && (C == null || B == null || C <= B)\n && (A == null || B == null || A <= B)\n && (C == null || D == null || C <= D));\n"
},
{
"answer_id": 51408081,
"author": "Nitin Jadhav",
"author_id": 741251,
"author_profile": "https://Stackoverflow.com/users/741251",
"pm_score": 3,
"selected": false,
"text": "function isOverlapping(startDate1, endDate1, startDate2, endDate2){ \n return moment(startDate1).isSameOrBefore(endDate2) && \n moment(startDate2).isSameOrBefore(endDate1);\n}\n"
},
{
"answer_id": 54098722,
"author": "Radacina",
"author_id": 1251938,
"author_profile": "https://Stackoverflow.com/users/1251938",
"pm_score": 4,
"selected": false,
"text": "min(ends)>max(starts)"
},
{
"answer_id": 55651642,
"author": "Roberto77",
"author_id": 4248575,
"author_profile": "https://Stackoverflow.com/users/4248575",
"pm_score": -1,
"selected": false,
"text": "class ValidityRuleRange {\n private final Date from;\n private final Date to;\n ...\n private boolean isOverlap(ValidityRuleRange vrr) {\n int c1 = from.compareTo(vrr.getTo());\n int c2 = to.compareTo(vrr.getFrom());\n return c1 == 0 || c2 == 0 || c1 + c2 == 0;\n }\n"
},
{
"answer_id": 62739853,
"author": "Bilal Ahmed Yaseen",
"author_id": 1846656,
"author_profile": "https://Stackoverflow.com/users/1846656",
"pm_score": 0,
"selected": false,
"text": "public boolean doesIntersect(DateRangeModel daterange1, DateRangeModel daterange2) {\n return !(\n (daterange1.getStartDate().isBefore(daterange2.getStartDate())\n && daterange1.getEndDate().isBefore(daterange2.getStartDate())) ||\n (daterange1.getStartDate().isAfter(daterange2.getStartDate())\n && daterange1.getEndDate().isAfter(daterange2.getEndDate())));\n}\n"
},
{
"answer_id": 66102940,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 3,
"selected": false,
"text": "(StartDate1, EndDate1) overlaps (StartDate2, EndDate2)\n DATE TIMESTAMP DATE daterange(StartDate1, EndDate1) @> daterange(StartDate2, EndDate2)\n"
},
{
"answer_id": 72640552,
"author": "John",
"author_id": 8542004,
"author_profile": "https://Stackoverflow.com/users/8542004",
"pm_score": 0,
"selected": false,
"text": "date-fns areIntervalsOverlapping areIntervalsOverlapping(intervalLeft, intervalRight, [options])\n // For overlapping time intervals:\nareIntervalsOverlapping(\n { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }\n)\n//=> true\n"
},
{
"answer_id": 73858654,
"author": "Umer",
"author_id": 4360616,
"author_profile": "https://Stackoverflow.com/users/4360616",
"pm_score": 0,
"selected": false,
"text": "if ( ($startTime1->between($startTime2, $endTime2, true) || $endTime1->between($startTime2, $endTime2, true)) || (($startTime1 <= $endTime2) && ($endTime2 <= $endTime1)) ){\n//Complete Overlap, Partial Left Overlap, Partial Right Overlap. \n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2084/"
] |
325,952 | <p>I need to loop through all the matches in say the following string:</p>
<p><code><a href='/Product/Show/{ProductRowID}'>{ProductName}</a></code></p>
<p>I am looking to capture the values in the {} including them, so I want {ProductRowID} and {ProductName}</p>
<p>Here is my code so far:</p>
<pre><code>Dim r As Regex = New Regex("{\w*}", RegexOptions.IgnoreCase)
Dim m As Match = r.Match("<a href='/Product/Show/{ProductRowID}'>{ProductName}</a>")
</code></pre>
<p>Is my RegEx pattern correct? How do I loop through the matched values? I feel like this should be super easy but I have been stumped on this this morning!</p>
| [
{
"answer_id": 325967,
"author": "RickL",
"author_id": 7261,
"author_profile": "https://Stackoverflow.com/users/7261",
"pm_score": 1,
"selected": false,
"text": "\\{\\w*\\}"
},
{
"answer_id": 325968,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "\\{\\w*?\\}\n \"{ProductRowID}'>{ProductName}\" Dim r As Regex = New Regex(\"\\{\\w*?\\}\")\nDim input As String = \"<a href='/Product/Show/{ProductRowID}'>{ProductName}</a>\"\nDim mc As MatchCollection = Regex.Matches(input, r)\nFor Each m As Match In mc\n MsgBox.Show(m.ToString())\nNext m\n RegexOptions.IgnoreCase"
},
{
"answer_id": 325976,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 2,
"selected": false,
"text": "<a href='/Product/Show/(.+)'\\>(.+)</a>\n <a href='/Product/Show/(?<rowid>.+)'\\>(?<name>.+)</a>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34548/"
] |
325,953 | <p>Given <em>test.txt</em> containing:</p>
<pre><code>test
message
</code></pre>
<p>I want to end up with:</p>
<pre><code>testing
a message
</code></pre>
<p>I think the following should work, but it doesn't:</p>
<pre><code>Get-Content test.txt |% {$_-replace "t`r`n", "ting`r`na "}
</code></pre>
<p>How can I do a find and replace where what I'm finding contains CRLF?</p>
| [
{
"answer_id": 326082,
"author": "Don Jones",
"author_id": 40405,
"author_profile": "https://Stackoverflow.com/users/40405",
"pm_score": 7,
"selected": true,
"text": "`n PS C:\\> $x = \"Hello\n>> World\"\n\nPS C:\\> $x\nHello\nWorld\nPS C:\\> $x.contains(\"`n\")\nTrue\nPS C:\\> $x.contains(\"`r\")\nFalse\nPS C:\\> $x.replace(\"o`nW\",\"o There`nThe W\")\nHello There\nThe World\nPS C:\\>\n `r `r `n"
},
{
"answer_id": 332446,
"author": "Peter Seale",
"author_id": 25911,
"author_profile": "https://Stackoverflow.com/users/25911",
"pm_score": 5,
"selected": false,
"text": "$text = [string]::Join(\"`n\", (Get-Content test.txt))\n[regex]::Replace($text, \"t`n\", \"ting`na \", \"Singleline\")\n"
},
{
"answer_id": 16802950,
"author": "nik.shornikov",
"author_id": 938472,
"author_profile": "https://Stackoverflow.com/users/938472",
"pm_score": 5,
"selected": false,
"text": "-Raw"
},
{
"answer_id": 51524753,
"author": "Tarun Khariwal",
"author_id": 4527615,
"author_profile": "https://Stackoverflow.com/users/4527615",
"pm_score": 1,
"selected": false,
"text": "\"\\\\r\\\\n\" powershell \"\\r\\n\" \"\\\\r\\\\n\" \"\\\" powershell"
},
{
"answer_id": 63717401,
"author": "Gaurav Singh",
"author_id": 5096834,
"author_profile": "https://Stackoverflow.com/users/5096834",
"pm_score": 3,
"selected": false,
"text": "(Get-Content test.txt) -join \",\"\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5993/"
] |
325,979 | <p>We are contracting an external consultant out to generate XHTML (Transitional) and CSS for most of the major pages of a new project we are currently working on.</p>
<p>I've been asked to put together a list of guidelines for them so that we can be sure that a certain level of quality can be expected. As a bit of technical background, we will be incorperating the raw HTML they provide into an ASP.NET web forms application (utilising the usual master pages / external stylesheets / jquery). Javascript should not be a consideration, but formatting and organisation of CSS should be.</p>
<p>I've made a start but quickly realised that this is probably not a unique situation and that a tried and tested list might be out there somewhere that I can at least use as a template! Has anyone got any experience of this?</p>
| [
{
"answer_id": 326114,
"author": "Jan Aagaard",
"author_id": 37147,
"author_profile": "https://Stackoverflow.com/users/37147",
"pm_score": 2,
"selected": false,
"text": "<form>"
},
{
"answer_id": 3598171,
"author": "HandiworkNYC.com",
"author_id": 220761,
"author_profile": "https://Stackoverflow.com/users/220761",
"pm_score": 2,
"selected": false,
"text": " <body>\n <div id=\"first\">\n <p>\n Some text goes in here...\n <p>\n\n <ul>\n <li>A list item</li>\n <li>A list item</li>\n <li>A list item</li>\n <li>\n <ul>\n <li>\n <a href=\"#\">A link</a>\n </li>\n </ul>\n </li>\n </ul>\n </div> <!-- #first ends -->\n </body>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
] |
325,981 | <p>Does anyone know if the AjaxHelper in the ASP.NET MVC framework deals with degradation?</p>
<p>For example, if you have an ActionLink that updates the content of a div, if JavaScript unavailable, will the page do a full postback by renderubg the page (via an action on a controller) and call the action specified in the ActionLink?</p>
<p>If not, how would you suggest making a page function correctly for browsers with JavaScript enabled and those who have it disabled within the context of an MVC app?</p>
| [
{
"answer_id": 31995919,
"author": "Maria Ines Parnisari",
"author_id": 1623249,
"author_profile": "https://Stackoverflow.com/users/1623249",
"pm_score": 0,
"selected": false,
"text": "Url AjaxOptions Ajax.ActionLink @Ajax.ActionLink(role, \"GetPeopleData\",\n new { selectedRole = role },\n new AjaxOptions\n {\n UpdateTargetId = \"tbody\",\n Url = Url.Action(\"GetPeopleData\", new { selectedRole = role })\n })\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5791/"
] |
325,990 | <p>I need to write a row to the database regardless of whether it already exists or not. Before using NHibernate this was done with a stored procedure. The procedure would attempt an update and if no rows were modified it would fallback to an insert. This worked well because the application doesn't care if the record exists.</p>
<p>With NHibernate, the solutions I have found require loading the entity and modifying it, or deleting the entity so the new one can be inserted. The application does have to care if the record already exists. Is there a way around that?</p>
<h2>Does the Id Matter?</h2>
<h3>Assigned Id</h3>
<p>The object has a keyword as an assigned id and is the primary key in the table.</p>
<p>I understand that SaveOrUpdate() will call the Save() or Update() method as appropriate based on the Id. Using an assigned id, this won't work because the id isn't an unsaved-value. However a Version or Timestamp field could be used as an indicator instead. In reality, this isn't relevant because this only reflects on whether the object in memory has been associated with a record in the database; it does not indicate if the record exists or not in the database.</p>
<h3>Generated Id</h3>
<p>If the assigned id were truly the cause of the problem, I could use a generated id instead of the keyword as the primary key. This would avoid the NHibernate Insert/Update issue as it would effectively always insert. However, I still need to prevent duplicate keywords. With a unique index on the keyword column it will still throw an exception for a duplicate keyword even if the primary key is different.</p>
<h2>Another Approach?</h2>
<p>Perhaps the problem isn't really with NHibernate, but the way this is modeled. Unlike other areas of the application, this is more data-centric rather object-centric. It is nice that NHibernate makes it easy to read/write and eliminates the stored procedures. But the desire to simply write without regard to existing values doesn't fit well with the model of an object's identity model. Is there a better way to approach this?</p>
| [
{
"answer_id": 326189,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 0,
"selected": false,
"text": "Obj j = session.get(Object.class(), id);\nif (j != null)\n session.merge(myObj);\nelse\n session.saveOrUpdate(myObj);\n"
},
{
"answer_id": 482684,
"author": "ShDev",
"author_id": 59253,
"author_profile": "https://Stackoverflow.com/users/59253",
"pm_score": 3,
"selected": false,
"text": " public IList<T> GetByExample<T>(T exampleInstance)\n {\n return _session.CreateCriteria(typeof(T))\n .Add(Example.Create(exampleInstance))\n .List<T>();\n }\n\n public void InsertOrUpdate<T>(T target)\n {\n ITransaction transaction = _session.BeginTransaction();\n try\n {\n var res=GetByExample<T>(target);\n if( res!=null && res.Count>0 )\n _session.SaveOrUpdate(target);\n else\n _session.Save(target); \n transaction.Commit();\n }\n catch (Exception)\n {\n transaction.Rollback();\n throw;\n }\n finally\n {\n transaction.Dispose();\n }\n }\n session.get(Object.class(), id);\n"
},
{
"answer_id": 68577979,
"author": "punteriaCero",
"author_id": 12737921,
"author_profile": "https://Stackoverflow.com/users/12737921",
"pm_score": 0,
"selected": false,
"text": " public void InsertOrUpdate<TEntity, TId>(TEntity entity) where TEntity : IIdentificableNh<TId>\n {\n var anyy = session.Get<TEntity>(entity.Id);\n if (anyy != null)\n {\n session.Evict(anyy); //dispatch all data loaded, to allow updating 'entity' object.\n session.Update(entity);\n } \n else\n {\n session.Save(entity);\n }\n \n session.Flush();\n }\n public class Caracteristica : IIdentificableNh<int>\n{\n public virtual int Id { get; set; }\n\n public virtual string Descripcion { get; set; }\n}\n session.InsertOrUpdate<Caracteristica, int>(new Caracteristica { Id = 2, Descripcion = \"Caracteristica2\" });\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/325990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6944/"
] |
326,015 | <p>Am new to Lucene.Net
Which is the best Analyzer to use in Lucene.Net?
Also,I want to know how to use Stop words and word stemming features ?</p>
| [
{
"answer_id": 6250248,
"author": "Febin J S",
"author_id": 669225,
"author_profile": "https://Stackoverflow.com/users/669225",
"pm_score": 0,
"selected": false,
"text": " string indexFileLocation = @\"C:\\Index\";\n string stopWordsLocation = @\"C:\\Stopwords.txt\";\n var directory = FSDirectory.Open(new DirectoryInfo(indexFileLocation));\n Analyzer analyzer = new StandardAnalyzer(\n Lucene.Net.Util.Version.LUCENE_29, new FileInfo(stopWordsLocation));\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41625/"
] |
326,053 | <p>Is there a way to get a list ordered by two fields, say last and first names?</p>
<p>I know <code>.listOrderByLastAndFirst</code> and <code>.list(sort:'last, first')</code> won't work.</p>
| [
{
"answer_id": 326152,
"author": "Hates_",
"author_id": 3410,
"author_profile": "https://Stackoverflow.com/users/3410",
"pm_score": 4,
"selected": true,
"text": "MyDomain.find(\"from Domain as d order by last,first desc\")\n def c = MyDomain.createCriteria()\ndef results = c.list {\n order(\"last,first\", \"desc\")\n}\n"
},
{
"answer_id": 1633716,
"author": "mattlary",
"author_id": 130502,
"author_profile": "https://Stackoverflow.com/users/130502",
"pm_score": 6,
"selected": false,
"text": "\"last,first\" \"Property 'last,first' not found\" def c = MyDomain.createCriteria()\ndef results = c.list {\n and{\n order('last','desc')\n order('first','desc')\n }\n}\n"
},
{
"answer_id": 1671767,
"author": "Nakul",
"author_id": 202338,
"author_profile": "https://Stackoverflow.com/users/202338",
"pm_score": 2,
"selected": false,
"text": "order('last','desc')\norder('first','desc')\n"
},
{
"answer_id": 7278202,
"author": "Arnar B",
"author_id": 924458,
"author_profile": "https://Stackoverflow.com/users/924458",
"pm_score": 4,
"selected": false,
"text": "def c = MyDomain.withCriteria {\n and {\n order('last', 'desc')\n order('first', 'desc')\n }\n}\n"
},
{
"answer_id": 12388332,
"author": "chim",
"author_id": 673282,
"author_profile": "https://Stackoverflow.com/users/673282",
"pm_score": 3,
"selected": false,
"text": "def c = MyDomain.withCriteria {\n property {\n order('last', 'desc')\n }\n order('first', 'desc')\n}\n"
},
{
"answer_id": 23925829,
"author": "maq",
"author_id": 3686157,
"author_profile": "https://Stackoverflow.com/users/3686157",
"pm_score": 2,
"selected": false,
"text": "def results=MyDomain.findAll([sort:\"last\",order:'desc'],[sort:\"first\",order:'desc']);\n"
},
{
"answer_id": 50174056,
"author": "gerrit-hntschl",
"author_id": 1549207,
"author_profile": "https://Stackoverflow.com/users/1549207",
"pm_score": 3,
"selected": false,
"text": "MyDomain.findAll(sort: ['first': 'desc','last':'desc'])\n"
},
{
"answer_id": 51194801,
"author": "Philippe Rostaing-Tayard",
"author_id": 4764888,
"author_profile": "https://Stackoverflow.com/users/4764888",
"pm_score": 0,
"selected": false,
"text": "def listCalendar (Calendar calendar) {\n respond CalendarData.where {\n calendar == calendar\n }.list().sort{ \"$it.attraction.type?:' '$it.attraction.name\" }\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12803/"
] |
326,059 | <p>I'm trying to create a "workflow" bar on a web page.</p>
<p>The items in the workflow might be of different lengths.</p>
<p>There might be enough items to fill the width of the screen, hence the flow needs to wrap onto the next line.</p>
<p>I'm using left floating divs to do this. </p>
<p>However, I'd like the divs to take an appropriate amount of screen width.</p>
<p>If only three items can fit on one line, then I'd like those items to fit evenly on the line, taking into account each individual items width.</p>
<p>All I can get at the moment is for the final div on a line to fill up the remaining space, which often means my items are all left aligned, e.g. I can get a layout like this:</p>
<pre>
AAAA -> BBBBB ->
CCCCCCCCCCCCCCCCCCC -> DD -> EEE ->
FFFFF -> GGGG -> HHHHH
</pre>
<p>but I actually want it to look something like this:</p>
<pre>
AAAA -> BBBBB ->
CCCCCCCCCCCCCCCCCCC -> DD -> EEE ->
FFFFF -> GGGG -> HHHHH
</pre>
<p>if you see what I mean.</p>
<p>Do I need to use tables for this rather than floating divs?</p>
| [
{
"answer_id": 326065,
"author": "John Polling",
"author_id": 41609,
"author_profile": "https://Stackoverflow.com/users/41609",
"pm_score": 1,
"selected": false,
"text": "margin: 0 auto;"
},
{
"answer_id": 326134,
"author": "A_M",
"author_id": 7144,
"author_profile": "https://Stackoverflow.com/users/7144",
"pm_score": 0,
"selected": false,
"text": "<html>\n<body>\n\n<STYLE>\n#nav, #nav ul {\n list-style: none;\n margin: 0px;\n width: 700px;\n}\n\n#nav li {\n list-style: none;\n float: left;\n padding-left: 10px;\n padding-right: 10px;\n width: auto;\n background-image: url(/lookandfeel/images/navMenuDiv.gif);\n background-repeat: repeat-x;\n}\n\nli#ending {\n background-image: url(/lookandfeel/images/navMenuRight.gif);\n background-repeat: no-repeat;\n}\n\nli#start {\n background-image: url(/lookandfeel/images/navMenuLeft.gif);\n background-repeat: no-repeat;\n}\n\n.navigation a {\n background-image: url(/pdr/images/navigation.gif);\n}\n</STYLE>\n\n<ul id=\"nav\" style=\"width: 100%;border: 1px solid\">\n <li id=\"start\" />\n <LI >\n <SPAN class=\"navigation\" >AAAAAAAAAA</SPAN>\n </li>\n <LI >\n <SPAN class=navigation >BBBB</SPAN>\n </li>\n <LI >\n <SPAN class=navigation>CCCCCCCCCCCCCCCCC</SPAN>\n </li>\n <LI>\n <SPAN class=navigation>DDDDDDDDD</SPAN>\n </li>\n <LI>\n <SPAN class=navigation>EEEEEEEE</SPAN>\n </li>\n <LI>\n <SPAN class=navigation>FFFFFFFFFFFFFF</SPAN>\n </li>\n <li>\n <SPAN class=navigation>GGGGGGGGGGGGGGGGGGGGGGGGGGGGG</SPAN\n </LI>\n <li id=\"ending\" />\n </ul>\n</body>\n</html>\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7144/"
] |
326,060 | <p>Let's say I have an integer that I need to convert to a string (I might be displaying the value to the user by means of a TextBox, for example.</p>
<p>Should I prefer <code>.ToString()</code> or <code>Convert.ToString()</code>. They both do the same thing (don't they?).</p>
<pre><code>int someValue = 4;
// You can do this
txtSomeValue.Text = someValue.ToString();
// Or this...
txtSomeValue.Text = Convert.ToString(someValue);
</code></pre>
<p>Assuming that there is no runtime difference between the two, then my reasons come down to aesthetics and consistency. Recently I have been favouring <code>Convert.ToString()</code> as to me it says "hey, I want the <em>value</em> of this thing as a string". However I know that this is not strictly true...</p>
| [
{
"answer_id": 326071,
"author": "rajesh pillai",
"author_id": 34644,
"author_profile": "https://Stackoverflow.com/users/34644",
"pm_score": 5,
"selected": true,
"text": "//This will set the variable test to null:\nstring test = Convert.ToString(ConfigurationSettings.AppSettings[\"Missing.Value\"]);\n\n//This will throw an exception:\nstring test = ConfigurationSettings.AppSettings[\"Missing.Value\"].ToString();\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39709/"
] |
326,062 | <p>A while ago, I had a discussion with a colleague about how to insert values in STL <a href="http://www.sgi.com/tech/stl/Map.html" rel="noreferrer">maps</a>. I preferred <code>map[key] = value;</code> because it feels natural and is clear to read whereas he preferred <code>map.insert(std::make_pair(key, value))</code>.</p>
<p>I just asked him and neither of us can remember the reason why insert is better, but I am sure it was not just a style preference rather there was a technical reason such as efficiency. The <a href="http://www.sgi.com/tech/stl/Map.html" rel="noreferrer">SGI STL reference</a> simply says: "Strictly speaking, this member function is unnecessary: it exists only for convenience."</p>
<p>Can anybody tell me that reason, or am I just dreaming that there is one?</p>
| [
{
"answer_id": 327289,
"author": "netjeff",
"author_id": 41191,
"author_profile": "https://Stackoverflow.com/users/41191",
"pm_score": 9,
"selected": true,
"text": "map[key] = value;\n value key key value map::insert() using std::cout; using std::endl;\ntypedef std::map<int, std::string> MyMap;\nMyMap map;\n// ...\nstd::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));\nif ( ! res.second ) {\n cout << \"key \" << key << \" already exists \"\n << \" with value \" << (res.first)->second << endl;\n} else {\n cout << \"created key \" << key << \" with value \" << value << endl;\n}\n map[key] = value"
},
{
"answer_id": 682003,
"author": "rlbond",
"author_id": 72631,
"author_profile": "https://Stackoverflow.com/users/72631",
"pm_score": 2,
"selected": false,
"text": "using namespace std;\nusing namespace boost::assign; // bring 'map_list_of()' into scope\n\nvoid something()\n{\n map<int,int> my_map = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);\n}\n"
},
{
"answer_id": 860959,
"author": "Hawkeye Parker",
"author_id": 99717,
"author_profile": "https://Stackoverflow.com/users/99717",
"pm_score": 5,
"selected": false,
"text": "std::map myMap[nonExistingKey]; nonExistingKey map.find()"
},
{
"answer_id": 14040726,
"author": "dk123",
"author_id": 1709725,
"author_profile": "https://Stackoverflow.com/users/1709725",
"pm_score": 1,
"selected": false,
"text": "map< const key, const val> Map;\n const_cast< T >Map[]=val;\n [] insert"
},
{
"answer_id": 15485188,
"author": "bobobobo",
"author_id": 111307,
"author_profile": "https://Stackoverflow.com/users/111307",
"pm_score": 1,
"selected": false,
"text": "operator[] .insert void mapTest()\n{\n map<int,float> m;\n\n\n for( int i = 0 ; i <= 2 ; i++ )\n {\n pair<map<int,float>::iterator,bool> result = m.insert( make_pair( 5, (float)i ) ) ;\n\n if( result.second )\n printf( \"%d=>value %f successfully inserted as brand new value\\n\", result.first->first, result.first->second ) ;\n else\n printf( \"! The map already contained %d=>value %f, nothing changed\\n\", result.first->first, result.first->second ) ;\n }\n\n puts( \"All map values:\" ) ;\n for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )\n printf( \"%d=>%f\\n\", iter->first, iter->second ) ;\n\n /// now watch this.. \n m[5]=900.f ; //using operator[] OVERWRITES map values\n puts( \"All map values:\" ) ;\n for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )\n printf( \"%d=>%f\\n\", iter->first, iter->second ) ;\n\n}\n"
},
{
"answer_id": 16883456,
"author": "Rampal Chaudhary",
"author_id": 824615,
"author_profile": "https://Stackoverflow.com/users/824615",
"pm_score": 4,
"selected": false,
"text": "class Sample\n{\n static int _noOfObjects;\n\n int _objectNo;\npublic:\n Sample() :\n _objectNo( _noOfObjects++ )\n {\n std::cout<<\"Inside default constructor of object \"<<_objectNo<<std::endl;\n }\n\n Sample( const Sample& sample) :\n _objectNo( _noOfObjects++ )\n {\n std::cout<<\"Inside copy constructor of object \"<<_objectNo<<std::endl;\n }\n\n ~Sample()\n {\n std::cout<<\"Destroying object \"<<_objectNo<<std::endl;\n }\n};\nint Sample::_noOfObjects = 0;\n\n\nint main(int argc, char* argv[])\n{\n Sample sample;\n std::map<int,Sample> map;\n\n map.insert( std::make_pair<int,Sample>( 1, sample) );\n //map[1] = sample;\n return 0;\n}\n"
},
{
"answer_id": 27026678,
"author": "GutiMac",
"author_id": 4211031,
"author_profile": "https://Stackoverflow.com/users/4211031",
"pm_score": 3,
"selected": false,
"text": "typedef std::map<int, std::string> MyMap;\nMyMap map;\n\nauto& result = map.emplace(3,\"Hello\");\n"
},
{
"answer_id": 31172709,
"author": "mechatroner",
"author_id": 2898283,
"author_profile": "https://Stackoverflow.com/users/2898283",
"pm_score": 1,
"selected": false,
"text": "insert() string word;\nmap<string, size_t> dict;\nwhile(getline(cin, word)) {\n dict.insert(make_pair(word, dict.size()));\n}\n operator[] string word;\nmap<string, size_t> dict;\nwhile(getline(cin, word)) {\n size_t sz = dict.size();\n if (!dict.count(word))\n dict[word] = sz; \n} \n"
},
{
"answer_id": 33280854,
"author": "anton_rh",
"author_id": 5447906,
"author_profile": "https://Stackoverflow.com/users/5447906",
"pm_score": 4,
"selected": false,
"text": "insert map[key] = value map[key] = value value insert insert"
},
{
"answer_id": 63340234,
"author": "honk",
"author_id": 2675154,
"author_profile": "https://Stackoverflow.com/users/2675154",
"pm_score": 0,
"selected": false,
"text": "insert() operator[] std::map emplace() insert_or_assign() try_emplace() emplace() insert() insert_or_assign() operator[] operator[] insert_or_assign() try_emplace() emplace() emplace() try_emplace() insert_or_assign() try_emplace()"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12663/"
] |
326,068 | <p>I was discussing multiple inheritance vs. single inheritance with a friend of mine, and discovered that plainly, my conception of Object-Oriented design is completely different than his. I am mostly an Obj-C programmer, so Multiple Inheritance is not something I use daily. He is mostly a C++ programmer under Windows/PSP, so we probably use different concepts on a day-to-day basis.</p>
<p>He actually brought the following subject : What does a new human being inherit from?</p>
<p>My conception of that was that there would be a Human class, and the new being would inherit from that class and get some instance variables (such as his DNA and others) from his two parents.</p>
<p>His conception was that the child would inherit from his two parents, in order to get the methods of his parents.</p>
<p>And now I'm kind of confused, because honestly... Inheriting from objects? Isn't inheritance used to inherit from classes which contain methods common to a certain group of objects? This argument really confused me to no end.</p>
| [
{
"answer_id": 326094,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 4,
"selected": true,
"text": "public class Human extends Mammal implements HunterGatherer, Speech, CognitiveThought {\n\n public Human(Human mother, Human father) {\n super(mother, father);\n // ...\n }\n\n // ...\n}\n public class Human extends Mother, Father { ... }\n"
},
{
"answer_id": 326107,
"author": "James Orr",
"author_id": 41457,
"author_profile": "https://Stackoverflow.com/users/41457",
"pm_score": 2,
"selected": false,
"text": "public Class HumanFactory(Human mother, Human father)\n{\n public Human NewHuman()\n {\n while(!mother.IsPregnant) // may loop infinitely in the infertile case\n father.Mate(mother)\n while(mother.IsPregnant)\n System.Threading.Sleep(1000); // may take some months, get comfortable\n return mother.DeliverBaby();\n }\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23623/"
] |
326,069 | <p>I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?</p>
| [
{
"answer_id": 326076,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 11,
"selected": true,
"text": "window.top function inIframe () {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n}\n top self window parent"
},
{
"answer_id": 326316,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 5,
"selected": false,
"text": "MainPage.html\n IframedPage1.html (named \"foo\")\n IframedPage2.html (named \"bar\")\n IframedPage3.html (named \"baz\")\n if(window.parent && window.parent.name == 'bar'){\n window.parent.location = self.location;\n}\n if(self == top){\n //this returns true!\n}\n"
},
{
"answer_id": 7493951,
"author": "Rolf",
"author_id": 945827,
"author_profile": "https://Stackoverflow.com/users/945827",
"pm_score": 2,
"selected": false,
"text": "function isNoIframeOrIframeInMyHost() {\n// Validation: it must be loaded as the top page, or if it is loaded in an iframe \n// then it must be embedded in my own domain.\n// Info: IF top.location.href is not accessible THEN it is embedded in an iframe \n// and the domains are different.\nvar myresult = true;\ntry {\n var tophref = top.location.href;\n var tophostname = top.location.hostname.toString();\n var myhref = location.href;\n if (tophref === myhref) {\n myresult = true;\n } else if (tophostname !== \"www.yourdomain.com\") {\n myresult = false;\n }\n} catch (error) { \n // error is a permission error that top.location.href is not accessible \n // (which means parent domain <> iframe domain)!\n myresult = false;\n}\nreturn myresult;\n}\n"
},
{
"answer_id": 7769187,
"author": "magnoz",
"author_id": 81231,
"author_profile": "https://Stackoverflow.com/users/81231",
"pm_score": 4,
"selected": false,
"text": " (window !== window.top) : false \n (window.self !== window.top) : true\n console.log(window.frames.length + ':' + parent.frames.length);\n 0:0 1:1 0:1"
},
{
"answer_id": 7884532,
"author": "Error601",
"author_id": 1012056,
"author_profile": "https://Stackoverflow.com/users/1012056",
"pm_score": -1,
"selected": false,
"text": "if (parent.location.href == self.location.href) {\n window.location.href = 'https://www.facebook.com/pagename?v=app_1357902468';\n}\n"
},
{
"answer_id": 11117190,
"author": "mikewolf78",
"author_id": 1393350,
"author_profile": "https://Stackoverflow.com/users/1393350",
"pm_score": 3,
"selected": false,
"text": "var isIframe = (self.frameElement && (self.frameElement+\"\").indexOf(\"HTMLIFrameElement\") > -1);\n"
},
{
"answer_id": 13101530,
"author": "Vova Popov",
"author_id": 724533,
"author_profile": "https://Stackoverflow.com/users/724533",
"pm_score": -1,
"selected": false,
"text": "if (window.frames.length != parent.frames.length) { page loaded in iframe }\n"
},
{
"answer_id": 14766775,
"author": "shibin",
"author_id": 2053367,
"author_profile": "https://Stackoverflow.com/users/2053367",
"pm_score": -1,
"selected": false,
"text": "if (self == top)\n { window.location = \"Home.aspx\"; }\n"
},
{
"answer_id": 17153970,
"author": "Joao Belchior",
"author_id": 744010,
"author_profile": "https://Stackoverflow.com/users/744010",
"pm_score": -1,
"selected": false,
"text": "$signed_request = $facebook->getSignedRequest();\n"
},
{
"answer_id": 18678703,
"author": "Konstantin Smolyanin",
"author_id": 1823469,
"author_profile": "https://Stackoverflow.com/users/1823469",
"pm_score": 7,
"selected": false,
"text": "window.frameElement iframe object null window.frameElement\n ? 'embedded in iframe or object'\n : 'not embedded or cross-origin'\n"
},
{
"answer_id": 22162487,
"author": "Jabran Saeed",
"author_id": 1648831,
"author_profile": "https://Stackoverflow.com/users/1648831",
"pm_score": 2,
"selected": false,
"text": "window === window.parent;\n"
},
{
"answer_id": 33799884,
"author": "portal TheAnGeLs",
"author_id": 3042804,
"author_profile": "https://Stackoverflow.com/users/3042804",
"pm_score": 5,
"selected": false,
"text": "var iFrameDetection = (window === window.parent) ? false : true;\n"
},
{
"answer_id": 49792828,
"author": "Albert Olivé Corbella",
"author_id": 3507464,
"author_profile": "https://Stackoverflow.com/users/3507464",
"pm_score": 2,
"selected": false,
"text": "<style id=\"antiClickjack\">body{display:none !important;}</style>\n <script type=\"text/javascript\">\n if (self === top) {\n var antiClickjack = document.getElementById(\"antiClickjack\");\n antiClickjack.parentNode.removeChild(antiClickjack);\n } else {\n top.location = self.location;\n }\n</script>\n"
},
{
"answer_id": 51509563,
"author": "Alex Roseland",
"author_id": 5421071,
"author_profile": "https://Stackoverflow.com/users/5421071",
"pm_score": -1,
"selected": false,
"text": " <p id=\"demofsdfsdfs\"></p>\n\n<script>\n\nif(window.self !== window.top) {\n\n//run this code if in an iframe\ndocument.getElementById(\"demofsdfsdfs\").innerHTML = \"in frame\";\n\n}else{\n\n//run code if not in an iframe\ndocument.getElementById(\"demofsdfsdfs\").innerHTML = \"no frame\";\n}\n\n</script>\n"
},
{
"answer_id": 61596084,
"author": "Beweelam",
"author_id": 11809801,
"author_profile": "https://Stackoverflow.com/users/11809801",
"pm_score": 5,
"selected": false,
"text": "if ( window !== window.parent ) \n{\n // The page is in an iframe \n} \nelse \n{ \n // The page is not in an iframe \n}\n"
},
{
"answer_id": 65034154,
"author": "Karthikeyan",
"author_id": 1142763,
"author_profile": "https://Stackoverflow.com/users/1142763",
"pm_score": 0,
"selected": false,
"text": "function amiLoadedInIFrame() {\n try {\n // Introduce a new propery in window.top\n window.top.dummyAttribute = true;\n // If window.dummyAttribute is there.. then window and window.top are same intances\n return !window.dummyAttribute;\n } catch(e) {\n // Exception will be raised when the top is in different domain\n return true;\n }\n}\n"
},
{
"answer_id": 65381881,
"author": "James",
"author_id": 5646334,
"author_profile": "https://Stackoverflow.com/users/5646334",
"pm_score": 0,
"selected": false,
"text": "constructor() {\n let windowLen = window.frames.length;\n let parentLen = parent.frames.length;\n\n if (windowLen == 0 && parentLen >= 1) {\n this.isInIframe = true\n console.log('Is in Iframe!')\n } else {\n console.log('Is in main window!')\n }\n}\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29653/"
] |
326,098 | <p>This is my code:</p>
<pre><code>internal enum WindowsMessagesFlags {
WM_EXITSIZEMOVE = 0x00000232,
WM_DISPLAYCHANGE = 0x0000007e,
WM_MOVING = 0x00000216,
}
protected override void WndProc(ref Message m) {
switch(m.Msg) {
case (int)WindowsMessagesFlags.WM_DISPLAYCHANGE:
FixWindowSnapping();
break;
case (int)WindowsMessagesFlags.WM_EXITSIZEMOVE:
SaveWindowProperties();
break;
case (int)WindowsMessagesFlags.WM_MOVING:
KeepProperLocation(ref m);
break;
}
}
</code></pre>
<p>Is there anyway to prevent the casting?</p>
| [
{
"answer_id": 326104,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "protected override void WndProc(ref Message m) {\n switch((WindowsMessagesFlags) m.Msg) {\n case WindowsMessagesFlags.WM_DISPLAYCHANGE:\n FixWindowSnapping();\n break;\n case WindowsMessagesFlags.WM_EXITSIZEMOVE:\n SaveWindowProperties();\n break;\n case WindowsMessagesFlags.WM_MOVING:\n KeepProperLocation(ref m);\n break;\n }\n}\n HttpStatusCode status = someWindowsMessageFlag;\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40480/"
] |
326,103 | <p>I'm writing a function that fishes out the src from the first image tag it finds in an html file. Following the instructions in <a href="https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php">this thread</a> on here, I got something that seemed to be working:</p>
<pre><code>preg_match_all('#<img[^>]*>#i', $content, $match);
foreach ($match as $value) {
$img = $value[0];
}
$stuff = simplexml_load_string($img);
$stuff = $stuff[src];
return $stuff;
</code></pre>
<p>But after a few minutes of using the function, it started returning errors like this:</p>
<blockquote>
<p>warning: simplexml_load_string() [0function.simplexml-load-string0]: Entity: line 1: parser error : Premature end of data in tag img line 1 in path/to/script on line 42.</p>
</blockquote>
<p>and </p>
<blockquote>
<p>warning: simplexml_load_string() [0function.simplexml-load-string0]: tp://feeds.feedburner.com/~f/ChicagobusinesscomBreakingNews?i=KiStN" border="0"> in path/to/script on line 42.</p>
</blockquote>
<p>I'm kind of new to PHP but it seems like my regex is chopping up the HTML incorrectly. How can I make it more "airtight"?</p>
| [
{
"answer_id": 326117,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<img[^>]*src\\s*=\\s*['|\"]?([^>]*?)['|\"]?[^>]*>\n"
},
{
"answer_id": 326131,
"author": "angus",
"author_id": 36925,
"author_profile": "https://Stackoverflow.com/users/36925",
"pm_score": 0,
"selected": false,
"text": "&(?!amp;) &"
},
{
"answer_id": 326176,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 0,
"selected": false,
"text": "foreach ($match as $value) {\n $img = $value[0];\n } \n $img = $match[count($match) - 1][0];\n if (preg_match('#<img\\s[^>]*>#i', $content, $match)) {\n $img = $match[0]; //first image in file only\n $stuff = simplexml_load_string($img);\n $stuff = $stuff[src];\n return $stuff;\n} else {\n return null; //no match found\n}\n"
},
{
"answer_id": 327359,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 3,
"selected": true,
"text": "preg_match_all('/<img\\s+[^<>]*src=[\"\\']?([^\"\\'<>\\s]+)[\"\\']?/i', $content, $result, PREG_PATTERN_ORDER);\n$result = $result[1];\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
326,112 | <p>Is there a single algorithm that removes elements from a container as happens in the following code?</p>
<pre><code>vec_it = std::remove_if( vec.begin(), vec.end(), pred );
vec.erase( vec_it, vec.end() );
</code></pre>
| [
{
"answer_id": 326149,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 3,
"selected": false,
"text": "vec.erase( std::remove_if( vec.begin(), vec.end(), pred ), vec.end() );\n"
},
{
"answer_id": 326166,
"author": "Cyrille Ka",
"author_id": 39622,
"author_profile": "https://Stackoverflow.com/users/39622",
"pm_score": 4,
"selected": true,
"text": "template<typename T, typename Pred> void erase_if(T &vec, Pred pred)\n{\n vec.erase(std::remove_if(vec.begin(), vec.end(), pred), vec.end());\n}\n std::vector<int> myVec;\n// (...) fill the vector. (...)\nerase_if(myVec, myPred);\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38892/"
] |
326,128 | <p>Imagine I have a document (word document).</p>
<p>I have an enumeration which will indicate how to extract data from the document. So if I want just text, the images, or both (3 members of the enumeration).</p>
<p>I have a case statement based on this enumeration, but without falling into a code smell, how can I write code which isn't too repetitive? For every condition in the switch, should I have a seperate method (the easiest way), or a method accepting a paremeter (like the value of the enumeration), and then use if statements to say if(xyz) do abc, and so on.</p>
<p>Or is there a quicker, more efficient way?</p>
| [
{
"answer_id": 326142,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "public interface IExtractionStrategy\n{\n object Extract( Document doc ); // or what ever result is best\n}\n\npublic class TextExtractionStrategy : IExtractionStrategy\n{\n public object Extract( Document doc )\n {\n .... algorithm for extracting text...\n }\n}\n\npublic class ImageExtractionStrategy : IExtractionStrategy\n{\n public object Extract( Document doc )\n {\n .... algorithm for extracting images...\n }\n}\n\n\npublic static class StrategyFactory\n{\n IExtractionStrategy GetStrategy( ExtractionEnum strategyType )\n {\n switch (strategyType)\n {\n case ExtractionEnum.Text:\n return new TextExtractionStrategy();\n break;\n case ExtractionEnum.Image:\n return new ImageExtractionStrategy();\n break;\n\n ...\n }\n }\n}\n"
},
{
"answer_id": 326146,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 1,
"selected": false,
"text": "Map<Enum, Strategy>"
},
{
"answer_id": 326226,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 1,
"selected": false,
"text": "use constant EXTRACT_TEXT => 1, EXTRACT_IMAGES => 2, EXTRACT_BOTH => 3;\nmy %extractor = (\n (EXTRACT_TEXT) => \\&extract_text,\n (EXTRACT_IMAGES) => \\&extract_images,\n (EXTRACT_BOTH) => \\&extract_both,\n);\n...\ndie \"no extractor found for $enum_value\" if ! $extractor{ $enum_value };\n$extractor{ $enum_value }->( $document_info );\n"
},
{
"answer_id": 326250,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 1,
"selected": false,
"text": "\nswitch(enum)\n case images:\n extractImages();\n break;\n case text:\n extractText();\n break;\n case both:\n extractImages();\n extractText();\n break;\n"
},
{
"answer_id": 326260,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 1,
"selected": false,
"text": "enum ExtractionEnum {\n IMAGE {\n public byte[] extract(InputStream is) { ... }\n },\n\n TEXT {\n public byte[] extract(InputStream is) { ... }\n };\n\n public abstract byte[] extract(InputStream is);\n}\n\n// ...\npublic void doSomething(ExtractionEnum type) {\n byte[] data = type.extract(getInputStream());\n ...\n}\n switch case"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
326,136 | <p>I am trying to get a <code>MethodInfo</code> object for the method:</p>
<pre><code>Any<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)
</code></pre>
<p>The problem I'm having is working out how you specify the type parameter for the <code>Func<TSource, Boolean></code> bit... </p>
<pre><code>MethodInfo method = typeof(Enumerable).GetMethod("Any", new[] { typeof(Func<what goes here?, Boolean>) });
</code></pre>
<p>Help appreciated.</p>
| [
{
"answer_id": 4036219,
"author": "Dustin Campbell",
"author_id": 56959,
"author_profile": "https://Stackoverflow.com/users/56959",
"pm_score": 2,
"selected": false,
"text": "public static class TypeExtensions\n{\n private class SimpleTypeComparer : IEqualityComparer<Type>\n {\n public bool Equals(Type x, Type y)\n {\n return x.Assembly == y.Assembly &&\n x.Namespace == y.Namespace &&\n x.Name == y.Name;\n }\n\n public int GetHashCode(Type obj)\n {\n throw new NotImplementedException();\n }\n }\n\n public static MethodInfo GetGenericMethod(this Type type, string name, Type[] parameterTypes)\n {\n var methods = type.GetMethods();\n foreach (var method in methods.Where(m => m.Name == name))\n {\n var methodParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();\n\n if (methodParameterTypes.SequenceEqual(parameterTypes, new SimpleTypeComparer()))\n {\n return method;\n }\n }\n\n return null;\n }\n}\n MethodInfo method = typeof(Enumerable).GetGenericMethod(\"Any\", new[] { typeof(IEnumerable<>), typeof(Func<,>) });\n"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27805/"
] |
326,186 | <p>Is there a way to query or just access newly added object (using ObjectContext.AddObject method) in Entity Framework? I mean situation when it is not yet saved to data store using SaveChanges</p>
<p>I understand that queries are translated to underlying SQL and executed against data store, and it don't have this new object yet. But anyway, I'm curious - if it is not oficially supported, maybe it is possible in theory. If it's not, how developer can deal with it? Manually track new objects and query them using Linq to objects?</p>
<p>The same question also applies to LinqToSql.</p>
| [
{
"answer_id": 491091,
"author": "Johann Blais",
"author_id": 363385,
"author_profile": "https://Stackoverflow.com/users/363385",
"pm_score": 4,
"selected": true,
"text": "context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Select(o => o.Entity).OfType<YourObjectType>()\n"
},
{
"answer_id": 491101,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "DataContext.GetChangeSet() .Inserts .Updates .Deletes ChangeSet GetChangeSet()"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37366/"
] |
326,194 | <p>I know there is a similar problem on this forum, but the solutions did not really work for me. I am populating form controls with fields from a few different data sources, and the data shows up great.</p>
<p>I have an <code>ImageButton</code> control, which has an <code>OnClick</code> Event set to grab all of the data from the form. Unfortunately, when I click the button, it seems as though the page is reloading first, and THEN is executes the <code>OnClick</code> call. The data that was hand-entered, or hard-coded seems to be pulled fine from the controls it was entered in, but anything that was pulled from a datasource is not able to be read. Any ideas. this is the last hurdle in a project that I have been working on for 6 months.</p>
| [
{
"answer_id": 491091,
"author": "Johann Blais",
"author_id": 363385,
"author_profile": "https://Stackoverflow.com/users/363385",
"pm_score": 4,
"selected": true,
"text": "context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Select(o => o.Entity).OfType<YourObjectType>()\n"
},
{
"answer_id": 491101,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "DataContext.GetChangeSet() .Inserts .Updates .Deletes ChangeSet GetChangeSet()"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
326,196 | <p>I'm stuck on what appears to be a CSS/z-index conflict with the YouTube player. In Firefox 3 under Windows XP, Take a look at this page: <a href="http://spokenword.org/program/21396" rel="noreferrer">http://spokenword.org/program/21396</a> Click on the Collect button and note that the pop-up <div> appears <em>under</em> the YouTube player. On other browsers the <div> appears on top. It has a z-index value of 999999. I've tried setting the z-index of the <object> element containing the player to a lower value, but that didn't work. Any idea how to get the pop-up to appear over the player?</p>
| [
{
"answer_id": 326220,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": true,
"text": "wmode opaque <param> wmode <embed> <object width='425' height='344'> \n <param name='movie' value='http://www.youtube.com/v/Wj_JNwNbETA&hl=en&fs=1'> \n <param name='type' value='application/x-shockwave-flash'> \n <param name='allowfullscreen' value='true'> \n <param name='allowscriptaccess' value='always'> \n <param name=\"wmode\" value=\"opaque\" />\n <embed width='425' height='344'\n src='http://www.youtube.com/v/Wj_JNwNbETA&hl=en&fs=1'\n type='application/x-shockwave-flash'\n allowfullscreen='true'\n allowscriptaccess='always'\n wmode=\"opaque\"\n ></embed> \n </object> \n"
},
{
"answer_id": 1202199,
"author": "Matthew Kuehn",
"author_id": 121383,
"author_profile": "https://Stackoverflow.com/users/121383",
"pm_score": 2,
"selected": false,
"text": "$('a[href^=\"http://www.youtube.com\"]').flash(\n { width: nnn, height: nnn, wmode: 'opaque' }\n);\n"
},
{
"answer_id": 4281828,
"author": "danfromisrael",
"author_id": 303114,
"author_profile": "https://Stackoverflow.com/users/303114",
"pm_score": 3,
"selected": false,
"text": "function fix_flash() {\n // loop through every embed tag on the site\n var embeds = document.getElementsByTagName('embed');\n for (i = 0; i < embeds.length; i++) {\n embed = embeds[i];\n var new_embed;\n // everything but Firefox & Konqueror\n if (embed.outerHTML) {\n var html = embed.outerHTML;\n // replace an existing wmode parameter\n if (html.match(/wmode\\s*=\\s*('|\")[a-zA-Z]+('|\")/i))\n new_embed = html.replace(/wmode\\s*=\\s*('|\")window('|\")/i, \"wmode='transparent'\");\n // add a new wmode parameter\n else\n new_embed = html.replace(/<embed\\s/i, \"<embed wmode='transparent' \");\n // replace the old embed object with the fixed version\n embed.insertAdjacentHTML('beforeBegin', new_embed);\n embed.parentNode.removeChild(embed);\n } else {\n // cloneNode is buggy in some versions of Safari & Opera, but works fine in FF\n new_embed = embed.cloneNode(true);\n if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window')\n new_embed.setAttribute('wmode', 'transparent');\n embed.parentNode.replaceChild(new_embed, embed);\n }\n }\n // loop through every object tag on the site\n var objects = document.getElementsByTagName('object');\n for (i = 0; i < objects.length; i++) {\n object = objects[i];\n var new_object;\n // object is an IE specific tag so we can use outerHTML here\n if (object.outerHTML) {\n var html = object.outerHTML;\n // replace an existing wmode parameter\n if (html.match(/<param\\s+name\\s*=\\s*('|\")wmode('|\")\\s+value\\s*=\\s*('|\")[a-zA-Z]+('|\")\\s*\\/?\\>/i))\n new_object = html.replace(/<param\\s+name\\s*=\\s*('|\")wmode('|\")\\s+value\\s*=\\s*('|\")window('|\")\\s*\\/?\\>/i, \"<param name='wmode' value='transparent' />\");\n // add a new wmode parameter\n else\n new_object = html.replace(/<\\/object\\>/i, \"<param name='wmode' value='transparent' />\\n</object>\");\n // loop through each of the param tags\n var children = object.childNodes;\n for (j = 0; j < children.length; j++) {\n try {\n if (children[j] != null) {\n var theName = children[j].getAttribute('name');\n if (theName != null && theName.match(/flashvars/i)) {\n new_object = new_object.replace(/<param\\s+name\\s*=\\s*('|\")flashvars('|\")\\s+value\\s*=\\s*('|\")[^'\"]*('|\")\\s*\\/?\\>/i, \"<param name='flashvars' value='\" + children[j].getAttribute('value') + \"' />\");\n }\n }\n }\n catch (err) {\n }\n }\n // replace the old embed object with the fixed versiony\n object.insertAdjacentHTML('beforeBegin', new_object);\n object.parentNode.removeChild(object);\n }\n }\n}\n $(document).ready(function () {\n fix_flash(); \n });\n"
},
{
"answer_id": 6850574,
"author": "ılǝ",
"author_id": 350478,
"author_profile": "https://Stackoverflow.com/users/350478",
"pm_score": 4,
"selected": false,
"text": "?wmode=transparent &wmode=transparent"
}
] | 2008/11/28 | [
"https://Stackoverflow.com/questions/326196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17307/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.