qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
348,320 | <p>Here's the deal. I have a big class hierarchy and I have this one method that is extended all the way through. The method always has to look at one or two more variable at each new level and these variable depend on the actual class in the hierarchy. What I want to do is check those two extra variables then call the superclass's version of that same function. I want to be able to define this function as all it's immediate children will use it, but I want to force any children of that class to have to redefine that method (because they will have to look at their new data members)</p>
<p>So how would I write this? I usually use =0; in the .h file, but I assume I can't use that and define it...</p>
| [
{
"answer_id": 348452,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 0,
"selected": false,
"text": "// this could be loaded from a file potentially\n// notice that the keys have been sorted.\nconst char* keys[] = { \"10\", \"12\", \"13 1/4\", \"15 1/4\", \"8\", 0 };\nfloat values[] = { 61, 92, 109, 151, 37, 0 };\nint key_count = 0;\nwhile (keys[key_count]) ++key_count;\n\nbool find(const char* key, float* val) {\n int idx = bsearch(key, keys, sizeof(const char*), key_count, strcmp);\n if (idx < 0) return false;\n *val = values[idx];\n return true;\n}\n"
},
{
"answer_id": 351331,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 1,
"selected": false,
"text": "IN maps to Key\n-- --- \n8 32 \n10 40\n12 48 \n13 1/4 53\n15 1/4 61 \n\nKeyMin= 32\n"
},
{
"answer_id": 352024,
"author": "eaanon01",
"author_id": 36986,
"author_profile": "https://Stackoverflow.com/users/36986",
"pm_score": 0,
"selected": false,
"text": "typedef struct{\n float input;\n int output;\n}m_lookup;\nm_lookup in_out[] = \n{ \n (float) 8 , 37,\n (float)10 , 61,\n (float)12 , 92,\n (float)13.25,109,\n (float)15.25,151,\n};\n\nint get_Var(float input)\n{\n int i=0;\n for(i=0;i<sizeof(in_out);i++)\n if(in_out[i].input == input)\n return in_out[i].output;\n // Here you could make some special code for your compiler\n return 0;\n}\nint main(void)\n{\n printf(\"Input 15.25 : Output %d\\n\",get_Var(15.25));\n printf(\"Input 13,25 : Output %d\\n\",get_Var(13.25));\n printf(\"Illegal input:\\n\");\n printf(\"Input 5 : Output %d\\n\",get_Var(5));\n system( \"pause\" );\n return 0;\n}\n enum Size\n{\n i_8=37,\n i_10=61,\n i_12=92,\n i_13_25=109,\n i_15_25=151,\n // etc\n}\n"
},
{
"answer_id": 354111,
"author": "RossFabricant",
"author_id": 20754,
"author_profile": "https://Stackoverflow.com/users/20754",
"pm_score": 1,
"selected": false,
"text": "class Size\n{\n public decimal Val{get;set;}\n private Size(decimal val){this.val = val;}\n public static Size _8 = new Size(8.0); \n //...\n public Dictionary<Size, Size> sizeMap = new Dictionary<Size, Size>\n {\n {_8, _37}, \n //...\n };\n}\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39189/"
] |
348,321 | <p>I'm going to make a space/trading/combat game that is completely procedurally generated. But, I know that storing all of the details of the whole galaxy in memory is unfeasable. As a result, I've been think that I can use a seed to generate a solar system, and from that solar system, you can use jumpgates to travel to other solar systems. The problem is that if I jump to another solar system from the starting one, I need to be able to get back to the exact same starting solar system with the exact the same features (planets, asteroids, etc.).</p>
<p>Essentially, I need to be able to generate a whole galaxy from one number. And from that one number, which generates one solar system, I need to be able to generate all of the other solar systems that link from the first one and all of the solar systems that link from those, and so on. And each solar system has to stay exactly the same feature-wise, if I return to them. Also, the number of links from each solar system can be either random, or fixed, your choice. Random would be better though.</p>
| [
{
"answer_id": 348486,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 3,
"selected": false,
"text": "nplanets >>> star_system = 42\n>>> nplanets = hash('nplanets%d' % star_system) % (10 + 1)\n>>> nplanets\n4\n >>> planet = 2\n>>> nstations = hash('nstations%d/%d' % (star_system, planet)) % (3 + 1)\n>>> nstations\n1\n"
},
{
"answer_id": 5488469,
"author": "Tom Gullen",
"author_id": 356635,
"author_profile": "https://Stackoverflow.com/users/356635",
"pm_score": 3,
"selected": false,
"text": "Sha1(1) = 356a192b7913b04c54574d18c28d46e6395428ab\n Sha1(2) = da4b9237bacccdf19c0760cab7aec4a8359010b0\n Sha1(3) = 77de68daecd823babbb58edb1c8e14d7106e83bb\n 356a\nda4b\n77de\n Sha1('1:340') = bc02ab36f163baee2a04cebaed8b141505cc26b5\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27677/"
] |
348,328 | <p>I recently upgraded to Eclipse Ganymede from Europa and now I'm finding that when I'm editing JSP files the IDE crawls when editing HTML attributes (but not JSP attributes).</p>
<p>Has anyone experienced this, or have any suggestions?</p>
<p>Also if you can point me to a better place to ask Eclipse related questions, do tell.</p>
<p>Thanks!</p>
| [
{
"answer_id": 6994301,
"author": "Ben Barkay",
"author_id": 885681,
"author_profile": "https://Stackoverflow.com/users/885681",
"pm_score": 3,
"selected": false,
"text": "attribute_name=\"\" attribute_name=\"..."
},
{
"answer_id": 38842103,
"author": "Flavio",
"author_id": 6693818,
"author_profile": "https://Stackoverflow.com/users/6693818",
"pm_score": -1,
"selected": false,
"text": "Project > Properties > JavaScript > Include Path > Source\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34859/"
] |
348,342 | <p>I'm currently trying to read text from a file and append it to a element in my html page using the DOM and Javascript. I can't get the text to format though. I've tried using innerHtml but isn't formating at all( no line breaks ).</p>
<p>Here is the javascript:</p>
<pre><code>http = new XMLHttpRequest();
http.open("GET",FILE,false);
http.send();
document.getElementById("tbody").innerHTML = http.responseText
</code></pre>
<p>Like I said the text gets added to the tbody element but isn't formatted what so ever.</p>
<hr>
<p>I got it working with this code( with the pre tag ), but like I said it works on my pc but not on the server which doesn't help.</p>
<pre><code> http.open("GET",FILE ,false);
http.send();
var newtext = document.createTextNode(http.responseText);
var para = document.getElementById("tbody");
para.appendChild(newtext);
</code></pre>
<hr>
<p>Here is all my javascript code:</p>
<p>function getHTTPObject()
{
var http = false;</p>
<pre><code>/*@cc_on
@if (@_jscript_version >= 5)
try
{
http = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
http = false;
}
}
@else
{
http = false;
}
@end @*/
if (!http && typeof XMLHttpRequest != 'undefined')
{
try
{
http = new XMLHttpRequest();
}
catch (e)
{
http = false;
}
}
return http
</code></pre>
<p>}</p>
<pre><code> function loadData()
{
http = getHTTPObject();
if (http)
{
http.open("GET","my file name",false);
http.send();
var newtext = document.createTextNode(http.responseText);
var para = document.getElementById("tbody");
para.appendChild(newtext);
}
}
</code></pre>
| [
{
"answer_id": 348343,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 1,
"selected": false,
"text": "<pre> responseXML http = new XMLHttpRequest();\nhttp.open(\"GET\",FILE,false);\nhttp.send(); \ndocument.getElementById(\"tbody\").appendChild(http.responseXML);\n"
},
{
"answer_id": 348349,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 0,
"selected": false,
"text": "<tbody>{responseText}</tbody>\n"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44160/"
] |
348,363 | <p>I'm writing an application that allows users to upload images onto the server. I expect about 20 images per day all jpeg and probably not edited/resized. (This is another question, how to resize the images on the server side before storing. Maybe someone can please drop a .NET resource for that in the comment or so).
I wonder now what the best place for storing uploaded images is.</p>
<ul>
<li><p>Store the images as a file in the file system and create a record in a table with the exact path to that image.</p></li>
<li><p>Or, store the image itself in a table using an "image" or "binary data" data type of the database server.</p></li>
</ul>
<p>I see advantages and disadvantages in both.
I like a) because I can easily relocate the files and just have to change the table entry. On the other hand I don't like storing business data on the web server and I don't really want to connect the web server to any other datasource that holds business data (for security reasons)
I like b) because all the information is in one place and easily accessible by a query. On the other hand the database will get very big very soon. Outsourcing that data could be more difficult.</p>
| [
{
"answer_id": 38105092,
"author": "Uday Hiwarale",
"author_id": 2790983,
"author_profile": "https://Stackoverflow.com/users/2790983",
"pm_score": 3,
"selected": false,
"text": "id image file name path id path /var/web-content/{{path}}/{{id}}/image-file-name.sm.jpg"
}
] | 2008/12/07 | [
"https://Stackoverflow.com/questions/348363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14027/"
] |
348,371 | <p>I've got MS Access database with linked tables, whenever each table is linked to a table in the same SQL Server database. I have a query inside Access that joins two tables (in particular I'm updating a table based on another using a join).</p>
<p>The question is does Access "download" all the table data before doing a join? Or is smart and joining it on the SQL Server?</p>
<p>The query is:</p>
<pre><code>UPDATE TBL_INVOICE_CHARGES INNER JOIN TBL_ANI
ON (TBL_INVOICE_CHARGES.CH_CUST_ID = TBL_ANI.ANI_CUST_ID)
AND (TBL_INVOICE_CHARGES.CH_ANI = TBL_ANI.ANI_NZ_ANI)
SET TBL_INVOICE_CHARGES.ANI_NOTES = TBL_ANI.ANI_NOTES;
</code></pre>
| [
{
"answer_id": 348439,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 2,
"selected": false,
"text": " WHERE Format(MyDate,\"YYYY\") = 2008\n WHERE MyDate Between #1/1/2008# And #12/31/2008#\n SELECT Format(MyDate,\"MM-DD\")\n FROM MyTable\n WHERE MyDate Between #1/1/2008# And #12/31/2008#\n SELECT MyDate\n FROM MyTable\n WHERE MyDate Between #1/1/2008# And #12/31/2008#\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10793/"
] |
348,392 | <p>How can I receive and send email in python? A 'mail server' of sorts.</p>
<p>I am looking into making an app that listens to see if it receives an email addressed to foo@bar.domain.com, and sends an email to the sender.</p>
<p>Now, am I able to do this all in python, would it be best to use 3rd party libraries? </p>
| [
{
"answer_id": 348551,
"author": "Manuel Ceron",
"author_id": 23657,
"author_profile": "https://Stackoverflow.com/users/23657",
"pm_score": 6,
"selected": true,
"text": "import smtplib\n\nserver = 'mail.server.com'\nuser = ''\npassword = ''\n\nrecipients = ['user@mail.com', 'other@mail.com']\nsender = 'you@mail.com'\nmessage = 'Hello World'\n\nsession = smtplib.SMTP(server)\n# if your SMTP server doesn't need authentications,\n# you don't need the following line:\nsession.login(user, password)\nsession.sendmail(sender, recipients, message)\n"
},
{
"answer_id": 349352,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 4,
"selected": false,
"text": "~/.forward \"|/path/to/program\" |path/to/program"
},
{
"answer_id": 26783166,
"author": "jakebrinkmann",
"author_id": 1533001,
"author_profile": "https://Stackoverflow.com/users/1533001",
"pm_score": 4,
"selected": false,
"text": "import imaplib\nmail = imaplib.IMAP4_SSL('imap.gmail.com')\nmail.login('myusername@gmail.com', 'mypassword')\nmail.list()\n# Out: list of \"folders\" aka labels in gmail.\nmail.select(\"inbox\") # connect to inbox.\nresult, data = mail.search(None, \"ALL\")\n\nids = data[0] # data is a list.\nid_list = ids.split() # ids is a space separated string\nlatest_email_id = id_list[-1] # get the latest\n\n# fetch the email body (RFC822) for the given ID\nresult, data = mail.fetch(latest_email_id, \"(RFC822)\") \n\nraw_email = data[0][1] # here's the body, which is raw text of the whole email\n# including headers and alternate payloads\n"
},
{
"answer_id": 30649434,
"author": "ambassallo",
"author_id": 2616446,
"author_profile": "https://Stackoverflow.com/users/2616446",
"pm_score": 2,
"selected": false,
"text": "import win32service\nimport win32event\nimport servicemanager\nimport socket\nimport imaplib2, time\nfrom threading import *\nimport smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEText import MIMEText\nimport datetime\nimport email\n\nclass Idler(object):\n def __init__(self, conn):\n self.thread = Thread(target=self.idle)\n self.M = conn\n self.event = Event()\n\n def start(self):\n self.thread.start()\n\n def stop(self):\n self.event.set()\n\n def join(self):\n self.thread.join()\n\n def idle(self):\n while True:\n if self.event.isSet():\n return\n self.needsync = False\n def callback(args):\n if not self.event.isSet():\n self.needsync = True\n self.event.set()\n self.M.idle(callback=callback)\n self.event.wait()\n if self.needsync:\n self.event.clear()\n self.dosync()\n\n\n def dosync(self):\n #DO SOMETHING HERE WHEN YOU RECEIVE YOUR EMAIL\n\nclass AppServerSvc (win32serviceutil.ServiceFramework):\n _svc_name_ = \"receiveemail\"\n _svc_display_name_ = \"receiveemail\"\n\n\n def __init__(self,args):\n win32serviceutil.ServiceFramework.__init__(self,args)\n self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n def SvcDoRun(self):\n servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,\n servicemanager.PYS_SERVICE_STARTED,\n (self._svc_name_,''))\n self.main()\n\n def main(self):\n M = imaplib2.IMAP4_SSL(\"imap.gmail.com\", 993)\n M.login(\"YourID\", \"password\")\n M.select(\"INBOX\")\n idler = Idler(M)\n idler.start()\n while True:\n time.sleep(1*60)\n idler.stop()\n idler.join()\n M.close()\n M.logout()\n\nif __name__ == '__main__':\n win32serviceutil.HandleCommandLine(AppServerSvc)\n"
},
{
"answer_id": 65892857,
"author": "3DCoded",
"author_id": 14923260,
"author_profile": "https://Stackoverflow.com/users/14923260",
"pm_score": 0,
"selected": false,
"text": "pip3 install emailpy import emailpy\nmanager = emailpy.EmailManager('your email', 'your password')\nmsg = manager.send(['who you are sending to', 'the other email you are sending to', subject='hello', body='this email is sent from Python', html='<h1>Hello World!</h1>', attachments=['yourfile.txt', 'yourotherfile.py'])\nwhile not msg.sent:\n pass\nprint('sent')\nmessages = manager.read()\nfor message in messages:\n print(message.sender, message.date, message.subject, message.body, message.html, message.attachments)\n for attachment in message.attachments:\n print(attachment.name)\n attachment.download()\n"
},
{
"answer_id": 73921465,
"author": "miksus",
"author_id": 13696660,
"author_profile": "https://Stackoverflow.com/users/13696660",
"pm_score": 0,
"selected": false,
"text": "from redbox import EmailBox\nfrom redmail import EmailSender\n\nUSERNAME = \"me@example.com\"\nPASSWORD = \"<PASSWORD>\"\n\nbox = EmailBox(\n host=\"imap.example.com\", \n port=993,\n username=USERNAME,\n password=PASSWORD\n)\n\nsender = EmailSender(\n host=\"smtp.example.com\", \n port=587,\n username=USERNAME,\n password=PASSWORD\n)\n from redbox.query import UNSEEN\n\n# Select an email folder\ninbox = box[\"INBOX\"]\n\n# Search and process messages\nfor msg in inbox.search(UNSEEN):\n # Set the message as read/seen\n msg.read()\n \n # Get attribute of the message\n sender = msg.from_\n subject = msg.subject\n sender.send(\n subject='You sent a message',\n receivers=[sender],\n text=f\"Hi, you sent this: '{subject}'.\",\n)\n pip install redbox redmail\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] |
348,408 | <p>I'm a little new to the Java 5 annotations and I'm curious if either of these are possible:</p>
<p>This annotation would generate a simple getter and setter for you.</p>
<pre><code>@attribute
private String var = "";
</code></pre>
<p>The <code>@NotNull</code> annotation indicates that a variable connot be null so you don't have to write that boilerplate code every time.</p>
<pre><code>/*
* @param s @NotNull
*/
public void setString(String s){
...
}
</code></pre>
<p>Will either of these work? They seem like the first things I would write annotations for if I could. Since I don't see much about these when I read the docs I'm assuming that it's not really what annotations are about. Any direction here would be appreciated.</p>
| [
{
"answer_id": 349104,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 5,
"selected": true,
"text": "@NonNull @NonNull @CheckForNull"
},
{
"answer_id": 681825,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 2,
"selected": false,
"text": "package sample;\nimport com.javadude.annotation.Bean;\nimport com.javadude.annotation.Property;\nimport com.javadude.annotation.PropertyKind; \n\n@Bean(properties={\n @Property(name=\"name\"),\n @Property(name=\"phone\", bound=true),\n @Property(name=\"friend\", type=Person.class, kind=PropertyKind.LIST)\n})\npublic class Person extends PersonGen {}\n"
},
{
"answer_id": 2186433,
"author": "Jirka",
"author_id": 264596,
"author_profile": "https://Stackoverflow.com/users/264596",
"pm_score": 4,
"selected": false,
"text": "@lombok.Data;\npublic class Person {\n private final String name;\n private int age;\n}\n getName getAge setAge equals hashCode toString name @AllArgsConstructor @Value @Data getName() name()"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42994/"
] |
348,410 | <p>Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.</p>
<pre><code>$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
</code></pre>
<p>And I'd like to do something like </p>
<pre><code>$properOrderedArray = sortArrayByArray($customer, array('name', 'dob', 'address'));
</code></pre>
<p>Because at the end I use a foreach() and they're not in the right order (because I append the values to a string which needs to be in the correct order and I don't know in advance all of the array keys/values).</p>
<p>I've looked through PHP's internal array functions but it seems you can only sort alphabetically or numerically. </p>
| [
{
"answer_id": 348418,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 7,
"selected": false,
"text": "function sortArrayByArray(array $array, array $orderArray) {\n $ordered = array();\n foreach ($orderArray as $key) {\n if (array_key_exists($key, $array)) {\n $ordered[$key] = $array[$key];\n unset($array[$key]);\n }\n }\n return $ordered + $array;\n}\n"
},
{
"answer_id": 348721,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 5,
"selected": false,
"text": "function sortArrayByArray(array $toSort, array $sortByValuesAsKeys)\n{\n $commonKeysInOrder = array_intersect_key(array_flip($sortByValuesAsKeys), $toSort);\n $commonKeysWithValue = array_intersect_key($toSort, $commonKeysInOrder);\n $sorted = array_merge($commonKeysInOrder, $commonKeysWithValue);\n return $sorted;\n}\n"
},
{
"answer_id": 1646634,
"author": "Boombastic",
"author_id": 199253,
"author_profile": "https://Stackoverflow.com/users/199253",
"pm_score": 2,
"selected": false,
"text": "function sortArrayByArray($array,$orderArray) {\n $ordered = array();\n foreach($orderArray as $key => $value) {\n if(array_key_exists($key,$array)) {\n $ordered[$key] = $array[$key];\n unset($array[$key]);\n }\n }\n return $ordered + $array;\n}\n"
},
{
"answer_id": 8659674,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 4,
"selected": false,
"text": "$order = array('north', 'east', 'south', 'west');\n array_intersect /* sort by value: */\n$array = array('south', 'west', 'north');\n$sorted = array_intersect($order, $array);\nprint_r($sorted);\n array_intersect_key /* sort by key: */\n$array = array_flip($array);\n$sorted = array_intersect_key(array_flip($order), $array);\nprint_r($sorted);\n"
},
{
"answer_id": 9098675,
"author": "Darkwaltz4",
"author_id": 1183064,
"author_profile": "https://Stackoverflow.com/users/1183064",
"pm_score": 10,
"selected": true,
"text": "array_merge array_replace array_merge $customer['address'] = '123 fake st';\n$customer['name'] = 'Tim';\n$customer['dob'] = '12/08/1986';\n$customer['dontSortMe'] = 'this value doesnt need to be sorted';\n\n$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);\n// or\n$properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer);\n\n// $properOrderedArray: array(\n// 'name' => 'Tim',\n// 'dob' => '12/08/1986',\n// 'address' => '123 fake st',\n// 'dontSortMe' => 'this value doesnt need to be sorted')\n"
},
{
"answer_id": 12470924,
"author": "user1653711",
"author_id": 1653711,
"author_profile": "https://Stackoverflow.com/users/1653711",
"pm_score": 1,
"selected": false,
"text": "function sortArrayByArray($array,$orderArray) {\n $ordered = array();\n foreach($orderArray as $key) {\n if(array_key_exists($key,$array)) {\n $ordered[$key] = $array[$key];\n unset($array[$key]);\n }\n }\n return $ordered + $array;\n}\n $properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);\n"
},
{
"answer_id": 15068383,
"author": "Pageii Studio",
"author_id": 2091104,
"author_profile": "https://Stackoverflow.com/users/2091104",
"pm_score": 1,
"selected": false,
"text": "Array[0] ...\n['dob'] = '12/08/1986';\n['some_key'] = 'some value';\n\nArray[1] ...\n['dob'] = '12/08/1986';\n\nArray[2] ...\n['dob'] = '12/08/1986';\n['some_key'] = 'some other value';\n $master_key = array( 'dob' => ' ' , 'some_key' => ' ' );\n foreach ($customer as $customer) {\n $modified_key = array_intersect_key($master_key, $unordered_array);\n $properOrderedArray = array_merge($modified_key, $customer);\n}\n"
},
{
"answer_id": 15730056,
"author": "abyrvalg",
"author_id": 2229299,
"author_profile": "https://Stackoverflow.com/users/2229299",
"pm_score": 5,
"selected": false,
"text": "$customer['address'] = '123 fake st';\n$customer['name'] = 'Tim';\n$customer['dob'] = '12/08/1986';\n$customer['dontSortMe'] = 'this value doesnt need to be sorted';\n\n$customerSorted = array_replace(array_flip(array('name', 'dob', 'address')), $customer);\n Array (\n [name] => Tim\n [dob] => 12/08/1986\n [address] => 123 fake st\n [dontSortMe] => this value doesnt need to be sorted\n)\n"
},
{
"answer_id": 26563870,
"author": "danielcraigie",
"author_id": 554206,
"author_profile": "https://Stackoverflow.com/users/554206",
"pm_score": 2,
"selected": false,
"text": "$arrayToBeSorted = array('west', 'east', 'south', 'north');\n$order = array('north', 'south', 'east', 'west');\n\n// sort array\nusort($arrayToBeSorted, function($a, $b) use ($order){\n // sort using the numeric index of the second array\n $valA = array_search($a, $order);\n $valB = array_search($b, $order);\n\n // move items that don't match to end\n if ($valA === false)\n return -1;\n if ($valB === false)\n return 0;\n\n if ($valA > $valB)\n return 1;\n if ($valA < $valB)\n return -1;\n return 0;\n});\n"
},
{
"answer_id": 27128691,
"author": "Peter de Groot",
"author_id": 4078558,
"author_profile": "https://Stackoverflow.com/users/4078558",
"pm_score": 6,
"selected": false,
"text": "$order = array(1,5,2,4,3,6);\n\n$array = array(\n 1 => 'one',\n 2 => 'two',\n 3 => 'three',\n 4 => 'four',\n 5 => 'five',\n 6 => 'six'\n);\n\nuksort($array, function($key1, $key2) use ($order) {\n return (array_search($key1, $order) > array_search($key2, $order));\n});\n"
},
{
"answer_id": 33415239,
"author": "DJules",
"author_id": 5300401,
"author_profile": "https://Stackoverflow.com/users/5300401",
"pm_score": 1,
"selected": false,
"text": "$customer['address'] = '123 fake st';\n$customer['name'] = 'Tim';\n$customer['dob'] = '12/08/1986';\n$customer['dontSortMe'] = 'this value doesnt need to be sorted';\n\n$order = array('name', 'dob', 'address');\n\n$keys= array_flip($order);\nuksort($customer, function($a, $b)use($keys){\n return $keys[$a] - $keys[$b];\n});\nprint_r($customer);\n"
},
{
"answer_id": 41377670,
"author": "Grain",
"author_id": 1262663,
"author_profile": "https://Stackoverflow.com/users/1262663",
"pm_score": 2,
"selected": false,
"text": " /**\n * sort keys like in key list\n * filter: remove keys are not listed in keyList\n * ['c'=>'red', 'd'=>'2016-12-29'] = sortAndFilterKeys(['d'=>'2016-12-29', 'c'=>'red', 'a'=>3 ]], ['c', 'd', 'z']){\n *\n * @param array $inputArray\n * @param string[]|int[] $keyList\n * @param bool $removeUnknownKeys\n * @return array\n */\nstatic public function sortAndFilterKeys($inputArray, $keyList, $removeUnknownKeys=true){\n $keysAsKeys = array_flip($keyList);\n $result = array_replace($keysAsKeys, $inputArray); // result = sorted keys + values from input + \n $result = array_intersect_key($result, $inputArray); // remove keys are not existing in inputArray \n if( $removeUnknownKeys ){\n $result = array_intersect_key($result, $keysAsKeys); // remove keys are not existing in keyList \n }\n return $result;\n}\n"
},
{
"answer_id": 41771807,
"author": "Doglas",
"author_id": 3620727,
"author_profile": "https://Stackoverflow.com/users/3620727",
"pm_score": 2,
"selected": false,
"text": "function array_sub_sort(array $values, array $keys){\n $keys = array_flip($keys);\n return array_merge(array_intersect_key($keys, $values), array_intersect_key($values, $keys));\n}\n $array_complete = [\n 'a' => 1,\n 'c' => 3,\n 'd' => 4,\n 'e' => 5,\n 'b' => 2\n];\n\n$array_sub_sorted = array_sub_sort($array_complete, ['a', 'b', 'c']);//return ['a' => 1, 'b' => 2, 'c' => 3];\n"
},
{
"answer_id": 44774818,
"author": "Baptiste Bernard",
"author_id": 7052950,
"author_profile": "https://Stackoverflow.com/users/7052950",
"pm_score": 4,
"selected": false,
"text": "array_fill_keys array_flip NULL $array $properOrderedArray = array_replace(array_fill_keys($keys, null), $array);\n"
},
{
"answer_id": 49689975,
"author": "Jenovai Matyas",
"author_id": 6920814,
"author_profile": "https://Stackoverflow.com/users/6920814",
"pm_score": 3,
"selected": false,
"text": "$array=array(28=>c,4=>b,5=>a);\n$seq=array(5,4,28); \nSortByKeyList($array,$seq) result: array(5=>a,4=>b,28=>c);\n\nfunction sortByKeyList($array,$seq){\n $ret=array();\n if(empty($array) || empty($seq)) return false;\n foreach($seq as $key){$ret[$key]=$dataset[$key];}\n return $ret;\n}\n"
},
{
"answer_id": 68577908,
"author": "Farid shahidi",
"author_id": 7657364,
"author_profile": "https://Stackoverflow.com/users/7657364",
"pm_score": 0,
"selected": false,
"text": "$order = ['a', 'b', 'c', 'd', 'e'];\n$needToSortArray = ['d', 'c', 'e'];\n\nuksort($needToSortArray, function($key1, $key2) use ($order, $needToSortArray) {\n return (array_search($needToSortArray[$key1], $order) > array_search($needToSortArray[$key2], $order));\n});\n\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
348,417 | <p>Some time ago I wrote a piece of code to update multiple rows in a database table. The code was like this</p>
<pre><code>var db = new MyDataContext();
db.Execute("UPDATE Details SET IsActive = 0 WHERE MasterId = 1");
</code></pre>
<p>Then the other day when I got the latest version of the file I saw that somebody changed the code to something like this</p>
<pre><code>var details = from d in db.details where d.MasterId == 1 select d;
foreach (var detail in details)
detail.IsActive = false;
db.SubmitChanges();
</code></pre>
<p>So my question is: What is the better way to update multiple rows? Using Linq or SQL?</p>
| [
{
"answer_id": 1718317,
"author": "Shannon Davidson",
"author_id": 103596,
"author_profile": "https://Stackoverflow.com/users/103596",
"pm_score": 2,
"selected": false,
"text": "context.Task.Update(t => t.Id == 1, t2 => new Task {StatusId = 2});\n Update Task Set StatusId = 2 Where Id = 1"
},
{
"answer_id": 3355796,
"author": "knowwebapp.com",
"author_id": 393058,
"author_profile": "https://Stackoverflow.com/users/393058",
"pm_score": 1,
"selected": false,
"text": "for (int i = 0; i < pListOrderDetail.Count; i++)\n{\n for (int j = 0; j < stempdata.Count; j++)\n {\n pListOrderDetail[i].OrderID = pOrderID;\n pListOrderDetail[i].ProductID = stempdata[j].pProductID;\n pListOrderDetail[i].Quantity = stempdata[j].pQuantity;\n pListOrderDetail[i].UnitPrice = stempdata[j].pUnitPrice;\n pListOrderDetail[i].Discount = stempdata[j].pDiscount;\n db.SubmitChanges();\n break;\n }\n continue;\n}\n"
},
{
"answer_id": 8818373,
"author": "Rory MacLeod",
"author_id": 1016,
"author_profile": "https://Stackoverflow.com/users/1016",
"pm_score": 0,
"selected": false,
"text": "SELECT details UPDATE WHERE SELECT"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24293/"
] |
348,419 | <p>I have a sorted list that contains the column headers, how do I rearrange my datagridview so it is in the same order as my sorted list?</p>
<p>I've tried the code below but this doesn't always work, some columns are not sorted correctly. Thanks for any help with this.</p>
<pre><code>sortedColumnNames.Sort();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
col.DisplayIndex = sortedColumnNames.IndexOf(col.HeaderText);
}
</code></pre>
<p>sortedColumnNames:
athens
crete
corfu
kefalonia
mykonos
rhodes
santorini
skiathos
zante</p>
| [
{
"answer_id": 348474,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 3,
"selected": false,
"text": "SortedColumnNames void SortDataGridViewColumns(DataGridView dgv)\n{\n var list = from DataGridViewColumn c in dgv.Columns\n orderby c.HeaderText\n select c;\n\n int i = 0;\n foreach (DataGridViewColumn c in list)\n {\n c.DisplayIndex = i++;\n }\n}\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,421 | <p>I am having problems running my Junit tests via Ant. I can't seem to get Ant to see the properties file it needs to load a dll my project needs. All my tests work using the Junit GUI in Elcipse, so I'm pretty sure it's not a problem with the tests themselves. I think my problem is something classpath-related, but I can't seem to find the problem.</p>
<p>jar strucure:
/root/folder/../Foo.properties</p>
<h2>This is how the properties file is loaded in the library:</h2>
<pre><code>// load class properties
props = PropertyLoader.loadProperties(Foo.class);
public static Properties loadProperties(Class className) {
return loadProperties(className.getName());
}
public static Properties loadProperties(final String propsName) {
Properties props = null;
InputStream in = null;
try {
ClassLoader cl = ClassLoader.getSystemClassLoader();
String name = propsName.replace('.', '/').concat(".properties");
in = cl.getResourceAsStream(name);
if (in != null) {
props = new Properties();
props.load(in);
}
}
catch (Exception e) {
props = null;
}
finally {
if (props == null) {
System.err.print("Property file " + propsName + " doesn't exist. System terminated.");
System.exit(0);
}
}
return props;
}
</code></pre>
<h2>Except from build file in question:</h2>
<pre><code><!-- Pattern of source files to copy into classpath-->
<property name="source.files.tocopy"
value="**/*.properties,**/*.dtd,**/*.xml,**/*.jpg" />
<path id="compile.classpath">
<fileset dir="lib">
<include name="*.jar" />
</fileset>
</path>
<!-- Generate Class-Path entry for the JAR's Manifest -->
<pathconvert property="manifest.classpath"
pathsep=" " dirsep="\">
<map from="${basedir}/" to="" />
<fileset dir="lib">
<include name="*.jar" />
</fileset>
</pathconvert>
<!-- Run tests against the JAR -->
<path id="test.compile.classpath">
<path refid="compile.classpath" />
<pathelement location="${target.jar}" />
</path>
<path id="test.classpath">
<path refid="test.compile.classpath" />
<pathelement location="${test.classes.dir}" />
</path>
<!-- - - - - - - - - - - - - - - - - -
target: test-compile
- - - - - - - - - - - - - - - - - -->
<target name="test-compile" depends="compile, test-init"
description="Compiles our testing code">
<javac destdir="${test.classes.dir}"
debug="true"
includeAntRuntime="true"
srcdir="test">
<classpath refid="test.compile.classpath" />
</javac>
<copy todir="${test.classes.dir}">
<fileset dir="test" includes="${source.files.tocopy}"/>
<fileset dir="resources" includes="${source.files.tocopy}"/>
</copy>
</target>
<!-- =================================
target: test
================================= -->
<target name="test" depends="test-compile, optional-tests">
<description>
Runs our tests, generates reports, and stops
the build on failure. Optionally runs one test.
</description>
<junit printsummary="false"
errorProperty="test.failed"
failureProperty="test.failed">
<classpath>
<path refid="test.classpath" />
</classpath>
<sysproperty key="test.properties" value="${test.properties.file}"/>
<formatter type="brief" usefile="false" />
<formatter type="xml" />
<test name="${testcase}" todir="${test.data.dir}" if="testcase" />
<batchtest todir="${test.data.dir}" unless="testcase">
<fileset dir="${test.classes.dir}">
<patternset>
<include name="**/test/*Test.class" />
<exclude name="**/test/*Printer*.class" unless="test.properties.file" />
</patternset>
</fileset>
</batchtest>
</junit>
</code></pre>
<p>I could really use a second set of eyes, so any help is appreciated. Thanks in advance!</p>
<p>--Charly</p>
| [
{
"answer_id": 349029,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 2,
"selected": false,
"text": "clazz.getResource(clazz.getName()+\".class\")\n"
},
{
"answer_id": 349825,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 0,
"selected": false,
"text": "ant ant -verbose ant -debug junit"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,428 | <p>I've been trying with limited success to export a crosstab query result set to Excel using Access 2003. Occasionally, the export works correctly, and Excel shows with no errors. Other times, using the exact same query parameters, I get a 3190 error - too many fields. I am using the TransferSpreadsheet option in a macro that is called from VB code.</p>
<p>The macro has the following parameters:
Transfer type: Export
Spreadsheet type: Microsoft Excel 8-10
Table Name: (this is my query name)
File Name: (Excel output file, which exists in the directory)
Has Field Names: Yes</p>
<p>The query should not produce any more than 14 columns worth of information, so the Excel 255 col limit should not be a problem. Also,the data in the database is not changing during the time I am querying, so the same query will produce the same result set.</p>
<p>One of the only solutions I have read on the net thus far is to close the recordset before running the macro, but this is hit or miss.</p>
<p>Your thoughts/help are greatly appreciated!</p>
| [
{
"answer_id": 356492,
"author": "Jon Wilson",
"author_id": 27876,
"author_profile": "https://Stackoverflow.com/users/27876",
"pm_score": 0,
"selected": false,
"text": "DoCmd.SetWarnings False\n DoCmd.OpenQuery \"TempTable-Make\" \n DoCmd.RunSQL \"DROP TABLE TempTable\" \n ExportToExcel()\nDoCmd.SetWarnings True\n"
},
{
"answer_id": 618864,
"author": "mavnn",
"author_id": 68457,
"author_profile": "https://Stackoverflow.com/users/68457",
"pm_score": 1,
"selected": false,
"text": "Sub OutputQuery(ws As excel.Worksheet, CellRef As String, QueryString As String, Optional Transpose As Boolean = False)\n\n Dim q As New ADODB.Recordset\n Dim i, j As Integer\n\n i = 1\n\n q.Open QueryString, CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly\n\n\n If Transpose Then\n For j = 0 To q.Fields.Count - 1\n ws.Range(CellRef).Offset(j, 0).Value = q(j).Name\n If InStr(1, q(j).Name, \"Date\") > 0 Or InStr(1, q(j).Name, \"DOB\") > 0 Then\n ws.Range(CellRef).Offset(j, 0).EntireRow.NumberFormat = \"dd/mm/yyyy\"\n End If\n Next\n\n Do Until q.EOF\n For j = 0 To q.Fields.Count - 1\n ws.Range(CellRef).Offset(j, i).Value = q(j)\n Next\n i = i + 1\n q.MoveNext\n Loop\n Else\n For j = 0 To q.Fields.Count - 1\n ws.Range(CellRef).Offset(0, j).Value = q(j).Name\n If InStr(1, q(j).Name, \"Date\") > 0 Or InStr(1, q(j).Name, \"DOB\") > 0 Then\n ws.Range(CellRef).Offset(0, j).EntireColumn.NumberFormat = \"dd/mm/yyyy\"\n End If\n Next\n\n Do Until q.EOF\n For j = 0 To q.Fields.Count - 1\n ws.Range(CellRef).Offset(i, j).Value = q(j)\n Next\n i = i + 1\n q.MoveNext\n Loop\n End If\n\n q.Close\n\nEnd Sub\n Sub Example1()\n Dim ex As excel.Application\n Dim wb As excel.Workbook\n Dim ws As excel.Worksheet\n\n 'Create workbook\n Set ex = CreateObject(\"Excel.Application\")\n ex.Visible = True\n Set wb = ex.Workbooks.Add\n Set ws = wb.Sheets(1)\n\n OutputQuery ws, \"A1\", \"Select * From [TestQuery]\"\nEnd Sub\n Sub Example2()\n Dim ex As excel.Application\n Dim wb As excel.Workbook\n Dim ws As excel.Worksheet\n\n 'Create workbook\n Set ex = CreateObject(\"Excel.Application\")\n ex.Visible = True\n Set wb = ex.Workbooks.Open(\"H:\\Book1.xls\")\n Set ws = wb.Sheets(\"DataSheet\")\n\n OutputQuery ws, \"E11\", \"Select * From [TestQuery]\"\nEnd Sub\n"
},
{
"answer_id": 57090569,
"author": "rohrl77",
"author_id": 1540019,
"author_profile": "https://Stackoverflow.com/users/1540019",
"pm_score": 0,
"selected": false,
"text": "CopyFromRecordset '---------------------------------------------------------------------------------------\n' Method : MoveQueryToWorksheet\n' Author : ROLU\n' Date : 09.05.2018\n' Purpose: Moves queries to specific worksheet in an Excel Workbook\n'---------------------------------------------------------------------------------------\nFunction MoveQueryToWorksheet(wkb As Excel.Workbook, wks As Variant, strSQL As Variant) As Boolean\nOn Error GoTo MoveQueryToWorksheet_Error\n\n'Dim rs As New ADODB.Recordset\n'rs.Open strSQL, CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly\n\nDim dbs As DAO.Database\nSet dbs = CurrentDb\nDim rs\nSet rs = dbs.OpenRecordset(strSQL)\n\nDim lCol As Long\nFor lCol = 0 To rs.Fields.Count - 1\n wkb.Worksheets(wks).Cells(1, lCol + 1).Value = rs.Fields(lCol).Name\nNext lCol\nwkb.Worksheets(wks).Range(\"A2\").CopyFromRecordset rs\n\n'Close out and clean\nSet rs = Nothing\nMoveQueryToWorksheet = True\n\n Exit Function\n\nMoveQueryToWorksheet_Error:\nOn Error GoTo 0\nSet rs = Nothing\nMoveQueryToWorksheet = False\n\nEnd Function\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,440 | <p>Is there an easy way to move around controls on a form exactly the same way as the tab key? This includes moving around cells on a datagridview etc.</p>
| [
{
"answer_id": 348492,
"author": "Marioh",
"author_id": 24293,
"author_profile": "https://Stackoverflow.com/users/24293",
"pm_score": 3,
"selected": true,
"text": "private void Form1_KeyPress(object sender, KeyPressEventArgs e)\n{\n if (e.KeyChar == 13)\n GetNextControl(ActiveControl, true).Focus();\n}\n"
},
{
"answer_id": 348521,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 2,
"selected": false,
"text": "Public Class MyCustomDataGrid\n Inherits DataGridView\n\n Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)\n If e.KeyCode = Keys.Enter Then\n e.Handled = True\n Me.ProcessTabKey(Keys.Tab)\n Else\n MyBase.OnKeyUp(e)\n End If\n End Sub\nEnd Class\n Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)\n If e.KeyCode = Keys.Enter AndAlso Not ActiveControl.GetType() Is GetType(Class1) Then\n e.Handled = True\n Me.ProcessTabKey(Not e.Shift)\n Else\n MyBase.OnKeyUp(e)\n End If\n End Sub\n"
},
{
"answer_id": 45704237,
"author": "xudong",
"author_id": 4976681,
"author_profile": "https://Stackoverflow.com/users/4976681",
"pm_score": 0,
"selected": false,
"text": "protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\nKeys keyPressed = (Keys)msg.WParam.ToInt32();\nswitch (keyPressed)\n{\n case Keys.Enter:\n case Keys.Tab:\n Control ctrl = this.GetNextControl(this.ActiveControl, true);\n while (ctrl is TextBox == false) \n {\n ctrl = this.GetNextControl(ctrl, true);\n }\n ctrl.Focus();\n return true;\n default:\n return base.ProcessCmdKey(ref msg, keyData);\n}\n}\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29823/"
] |
348,465 | <p>I have the following code that I need to run over a matrix with over 20000 rows. It takes several minutes to run and the datenum and str2double functions appear to be the bottlenecks. Since no calculation depends on previous ones is there a way to break the loop into multiple parts and have them execute in parallel? Any advice on optimising this code would be appreciated.</p>
<pre>
for i=1:length(DJI)
DJI2(i,1)=datenum(char(DJI(i,2)),'yyyy-mm-dd');
for j=3:7
DJI2(i,j-1)=str2double(char(DJI(i,j)));
end
end
</pre>
| [
{
"answer_id": 471420,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 2,
"selected": true,
"text": "octave-3.0.3.exe:15> s=sprintf('1 2\\n3 4');\noctave-3.0.3.exe:16> m=str2double(s)\nm =\n\n 1 2\n 3 4\n\n\noctave-3.0.3.exe:35> s=randn(5000,5);\noctave-3.0.3.exe:36> z=num2str(s);\noctave-3.0.3.exe:37> tic; s2=str2double(z); toc\nElapsed time is 18.9837 seconds.\n"
},
{
"answer_id": 2423362,
"author": "mtrw",
"author_id": 120261,
"author_profile": "https://Stackoverflow.com/users/120261",
"pm_score": 0,
"selected": false,
"text": "textread function [DJI2] = InterpretFile(datafile)\n [txtdates, c2, c3, c4, c5, c6] = textread(datafile, '%* %s %f %f %f %f %f');\n dates = datenum(strvcat(txtdates),'yyyy-mm-dd');\n DJI2 = [dates c2 c3 c4 c5 c6];\n textread skip 1990-01-01 1.234 2.345 3.456 4.012 5.345\nskipme2 1990-01-02 1 2 3 4 5\njunk 1990-01-03 1.9 2.1 3.2 4.3 5.4\n str2num str2double"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14744/"
] |
348,469 | <p>While the J2EE module reference feature allows your to create common Java library projects, I can't find a neat way to do this for web content.</p>
<p>I have common JSPs, CSS files, JavaScript libraries and even descriptor fragments that I would like to use across a number of Dynamic Web Projects, so that these artefacts are edited i only one place, but will be exported into each of the Dynamic WebProject WAR files.</p>
<p>I am surprised that I can't find a way to promote reusability in the web space without writing my own scripts and hooking into the export process.</p>
<p>Is there a way to do this?
Thanks.
Matt.</p>
| [
{
"answer_id": 366802,
"author": "Paul Fisher",
"author_id": 39808,
"author_profile": "https://Stackoverflow.com/users/39808",
"pm_score": 2,
"selected": false,
"text": "svn up"
},
{
"answer_id": 15404702,
"author": "JZ.Hunt",
"author_id": 1273270,
"author_profile": "https://Stackoverflow.com/users/1273270",
"pm_score": -1,
"selected": false,
"text": "a.jsp svn://myhome.com/svn/myproject/trunk/a.jsp\n xml svn://myhome.com/svn/myproject/trunk/xml\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,491 | <p>I have a code igniter project, and I wanted to try debugging it using Zend Studio. WHen I start debugging, I immediately run ino</p>
<p>"The URI you submitted has disallowed characters."</p>
<p>Does anyone have any idea?</p>
| [
{
"answer_id": 348548,
"author": "Cody Caughlan",
"author_id": 25398,
"author_profile": "https://Stackoverflow.com/users/25398",
"pm_score": 5,
"selected": false,
"text": "$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\\-';\n"
},
{
"answer_id": 17566966,
"author": "Stelian",
"author_id": 739436,
"author_profile": "https://Stackoverflow.com/users/739436",
"pm_score": 3,
"selected": false,
"text": "if ( ! preg_match(\"|^[\" . preg_quote($this->config->item('permitted_uri_chars')) . \"]+$|i\", $str)) {\n if (FALSE === preg_match(\"|^[\" . preg_quote($this->config->item('permitted_uri_chars')) . \"]+$|i\", $str)) {\n /system/libraries/URI.php"
},
{
"answer_id": 18066355,
"author": "Andreas",
"author_id": 257001,
"author_profile": "https://Stackoverflow.com/users/257001",
"pm_score": 2,
"selected": false,
"text": "$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\\\\-';\n $config['permitted_uri_chars'] = ''; \n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,502 | <p>I have created an application that writes some data to the root folder of the directory in which it was installed (in Program Files). But under Windows Vista, the program is unable to write to the directory because the UAC restricts administrative privileges.</p>
<p>I need to be able to do the following</p>
<ol>
<li>Write a file in the folder where the program was installed in program files.</li>
</ol>
<p>That's possible if the software is run with administrative privileges. But I don't know how to modify my setup to always run it with administrative privileges.</p>
<p>Are there any ways or suggestions I can accomplish this?</p>
| [
{
"answer_id": 348549,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 2,
"selected": true,
"text": "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestversion=\"1.0\">\n<assemblyidentity version=\"1.0.0.0\" processorarchitecture=\"X86\" name=\"app.exe\" type=\"win32\">\n<description>My Application</description>\n<trustinfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n<security>\n<requestedprivileges>\n<requestedexecutionlevel level=\"requireAdministrator\">\n</requestedexecutionlevel>\n</requestedprivileges>\n</security>\n</trustinfo>\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33052/"
] |
348,530 | <p>I have an asp:DropDownList on a page that, due to the 1024x768 development standard can truncate some of the text values in the dropdown (not enough of them, apparently, to redesign the layout ), so I need to display a tooltip of the selected value <em>when</em> a dropdown item is being selected (i.e. when the dropdown is shown and an item is being hovered over), preferably only when the text for that item is being truncated.</p>
<p>Is this possible by default, javascript hacking or only my imagination?</p>
| [
{
"answer_id": 348668,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 0,
"selected": false,
"text": "<asp:DropDownList id=\"ddl1\" runat=\"server\">\n <asp:ListItem Text=\"Display text\" Value=\"1\" Title=\"This is my tooltip\"></asp:ListItem>\n</asp:DropDownList>\n"
},
{
"answer_id": 6883960,
"author": "Peter Bromberg",
"author_id": 5571,
"author_profile": "https://Stackoverflow.com/users/5571",
"pm_score": 3,
"selected": true,
"text": "foreach (ListItem _listItem in this.DropDownList1.Items) \n{ \n _listItem.Attributes.Add(\"title\", _listItem.Text); \n\n}\n DropDownList1.Attributes.Add(\"onmouseover\", this.title=this.options[this.selectedIndex].title\");\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
348,533 | <p>I am trying to make a graph in java that would have different nodes. some nodes would be connected to others and some wont. If they are connected then some boolean value for that node will be true and another variable will hold the value of the node it is connected to. </p>
<p>...any suggestions on what you guys think is the best way to approach this?</p>
| [
{
"answer_id": 348543,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 1,
"selected": false,
"text": "Node Node ArrayList"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41685/"
] |
348,562 | <p>I have a messy function that needs refactoring, it has too many nested IF's and it makes me nervous just to look at it!</p>
<p><b>Please ignore what the functions are doing, I'm more concerned with the structure/flow and how it can be refactored so it has less nested IF statements</b></p>
<p>The basic flow is as follows:</p>
<pre><code>public static void HandleUploadedFile(string filename)
{
try
{
if(IsValidFileFormat(filename)
{
int folderID = GetFolderIDFromFilename(filename);
if(folderID > 0)
{
if(HasNoViruses(filename)
{
if(VerifyFileSize(filename)
{
// file is OK
MoveToSafeFolder(filename);
}
else
{
DeleteFile(filename);
}
}
else
{
DeleteFile(filename);
}
}
else
{
DeleteFile(filename);
}
}
else
{
DeleteFile(filename);
}
}
catch (Exception ex)
{
}
finally
{
// do some things
}
}
</code></pre>
| [
{
"answer_id": 348575,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 3,
"selected": false,
"text": " private static bool CanMoveToSafeFolder(string filename)\n {\n return IsValidFileFormat(filename)\n && GetFolderIDFromFilename(filename) > 0\n && HasNoViruses(filename)\n && VerifyFileSize(filename);\n }\n\n public static void HandleUploadedFile(string filename)\n {\n\n try\n {\n\n if (CanMoveToSafeFolder(filename))\n {\n // file is OK\n MoveToSafeFolder(filename);\n }\n else\n {\n DeleteFile(filename);\n }\n }\n catch (Exception ex)\n {\n\n }\n finally\n {\n // do some things\n }\n\n }\n"
},
{
"answer_id": 348581,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "public static void HandleUploadedFile(string filename)\n{\n try\n {\n if( IsValidFileFormat(filename) && \n (GetFolderIDFromFilename(filename) > 0) && \n HasNoViruses(filename) &&\n VerifyFileSize(filename) )\n {\n MoveToSafeFolder(filename);\n }\n else\n {\n DeleteFile(filename);\n }\n }\n catch (Exception ex)\n {\n // do some things\n }\n finally\n {\n // do some cleanup\n }\n}\n"
},
{
"answer_id": 348588,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 0,
"selected": false,
"text": "public static void HandleUploadedFile(string filename) {\n try {\n if(IsValidFileFormat(filename) \n && GetFolderIDFromFilename(filename)>0 \n && HasNoViruses(filename) \n && VerifyFileSize(filename)) {\n MoveToSafeFolder(filename); // file is OK\n }\n else {\n DeleteFile(filename);\n }\n }\n catch (Exception ex) {\n // HANDLE THE EXCEPTION; AT LEAST LOG IT!\n }\n finally {\n // do some things\n }\n }\n"
},
{
"answer_id": 6144452,
"author": "Genzer",
"author_id": 495558,
"author_profile": "https://Stackoverflow.com/users/495558",
"pm_score": 0,
"selected": false,
"text": "UploadedFileChecker private class UploadedFileChecker {\n String fileName;\n\n UploadedFileChecker(String fileName) {\n this.fileName = fileName;\n }\n\n public void check() throws BadUploadedFileException {\n checkNameFormat();\n checkFolderId();\n scanVirus();\n checkFileSize();\n }\n\n private void checkFolderId() {\n // throw BadUploadedFileException if not passed.\n }\n\n private void checkNameFormat() {\n // throw BadUploadedFileException if not passed.\n }\n\n private void scanVirus() {\n // throw BadUploadedFileException if not passed.\n }\n\n private void checkFileSize() {\n // throw BadUploadedFileException if not passed.\n }\n}\n public class BadUploadedFileException extends RuntimeException {\n\n}\n public static void handleUploadedFile(string filename) {\n\n try {\n checkFile(fileName);\n } catch (BadUploadedFileException ex) {\n deleteFile(fileName);\n } catch (Exception ex) {\n\n } finally {\n\n }\n}\n\nprivate static void checkFile(String fileName) {\n new UploadedFileChecker(fileName).check();\n}\n\nprivate static void deleteFile(String fileName) {\n\n}\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,573 | <p>I was wondering what people thought about the decision to support Entity Framework over LINQ-to-SQL? I have an application I'm developing originally in LINQ-to-SQL. I found it the perfect solution for our application. </p>
<p>While attempting to port to Entity Framework I was surprised how rough it was. IMHO, not even close to being ready for prime time. No lazy loading, no POCOs, horrible dependency on inheritance. I found it largely unusable in my case and instead decided to stick with LINQ-to-SQL until somehow this Entity Framework can get more polished.</p>
<p>Anyone else have similar experience with it?</p>
| [
{
"answer_id": 348694,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "Expression.Invoke"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37591/"
] |
348,576 | <p>I'm using QUnit to test some JQuery, and I've got Watin to load up the test page and parse out the test results, but I'm wondering if there's a way to dynamically generate the tests from the page using the MS Test suite rather than having to write a Test function for each test?</p>
<p>I'm just trying to reduce the amount of code having to be written</p>
| [
{
"answer_id": 348694,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "Expression.Invoke"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] |
348,582 | <p>We use Log4j (and Commons Logging) to log our error messages. Now we want to set up an additional log appender that outputs fatal errors to syslog, but without the exceptionally long Java stacktraces (those will still be available in the full log file).</p>
<p>How would one configure this (using log4j.xml)? Is there a filter available to ignore the stack traces?</p>
| [
{
"answer_id": 1788778,
"author": "Totach",
"author_id": 209622,
"author_profile": "https://Stackoverflow.com/users/209622",
"pm_score": 4,
"selected": false,
"text": "import org.apache.log4j.PatternLayout;\n\npublic class NoStackTracePatterLayout extends PatternLayout {\n\n @Override\n public boolean ignoresThrowable(){\n return false;\n }\n}\n"
},
{
"answer_id": 29261945,
"author": "boumbh",
"author_id": 1722982,
"author_profile": "https://Stackoverflow.com/users/1722982",
"pm_score": 3,
"selected": false,
"text": "%throwable{0} log4j.appender.XXX.layout=org.apache.log4j.EnhancedPatternLayout\nlog4j.appender.XXX.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n%throwable{0}\n"
},
{
"answer_id": 50009881,
"author": "Dasmowenator",
"author_id": 367544,
"author_profile": "https://Stackoverflow.com/users/367544",
"pm_score": 2,
"selected": false,
"text": "\"%ex{0}\""
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14955/"
] |
348,586 | <p>After installing the F# September CTP (1.9.6.2), Visual Studio 2008 frequently gives an error "Microsoft Visual C# IntelliSense has stopped working" which promptly crashes all of Visual Studio. I tried the tips mentioned in a <a href="https://stackoverflow.com/questions/178846/visual-studio-intellisense-stopped-working">similar SO article</a> such as "devenv.exe /ResetSettings", deleting the ncb file (which actually didn't exist), and installing the latest service pack (SP1) but no luck. Also tried reinstalling F#, nothing. This specifically happens in a C# unit test project that references my F# project and when I start to type things like [TestMethod] or "= new Tuple<List<int>,int,int> { Item1 = ". That's why I'm guessing it's related to F#. Incidentally I have ReSharper installed but disabled. Anyway, wondering if anyone else has had this problem and/or solved it. Otherwise any thoughts/ideas would be much appreciated.</p>
| [
{
"answer_id": 1788778,
"author": "Totach",
"author_id": 209622,
"author_profile": "https://Stackoverflow.com/users/209622",
"pm_score": 4,
"selected": false,
"text": "import org.apache.log4j.PatternLayout;\n\npublic class NoStackTracePatterLayout extends PatternLayout {\n\n @Override\n public boolean ignoresThrowable(){\n return false;\n }\n}\n"
},
{
"answer_id": 29261945,
"author": "boumbh",
"author_id": 1722982,
"author_profile": "https://Stackoverflow.com/users/1722982",
"pm_score": 3,
"selected": false,
"text": "%throwable{0} log4j.appender.XXX.layout=org.apache.log4j.EnhancedPatternLayout\nlog4j.appender.XXX.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n%throwable{0}\n"
},
{
"answer_id": 50009881,
"author": "Dasmowenator",
"author_id": 367544,
"author_profile": "https://Stackoverflow.com/users/367544",
"pm_score": 2,
"selected": false,
"text": "\"%ex{0}\""
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40783/"
] |
348,589 | <p>I need to make some code to talk to a SOAP web service. Unfortunately I'm unable to get a connection to the service as it requires a SSL connection encrypted with a special certificate. I've been given a pk12 certificate which when installed into my keychain allows me to access the SOAP service manually via Safari, but I'm unable to get a connection from the Cocoa web services stuff :(
Does anybody have any ideas on what I might have to do to get this to work?</p>
| [
{
"answer_id": 367254,
"author": "Nick R.",
"author_id": 373524,
"author_profile": "https://Stackoverflow.com/users/373524",
"pm_score": 0,
"selected": false,
"text": "using System.Security.Cryptography.X509Certificates;\n\npublic partial class _Default : System.Web.UI.Page \n{\n protected void Page_Load(object sender, EventArgs e)\n {\n //some code creating your soap client\n\n string cert_file = \"C:\\\\prf_res.pem\"; //You'll probably use the PEM format here, not the .p12 format\n X509Certificate cert = new X509Certificate(cert_file);\n soap_client.ClientCertificates.Add(cert);\n\n //now you're set!\n $cert = \"myCert.pem\"; //notice it's in PEM format. \n\n $client = new SoapClient($wsdl, array('local_cert' => $cert));\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6852/"
] |
348,606 | <p>As you can see below, in the constructor I'm instantiating a validation object so I can validate a user's email in a set method. Is this architecture best practice or flawed? Can I avoid making my User class directly dependent on my Validation class?</p>
<pre><code>Class User {
Private Email
//constructor
User() {
Validation = new Validation
}
SetEmail(NewValue) {
if (Validation.isEmail(NewValue)) {
Email = NewValue
}
}
</code></pre>
<p>And a related question: When a set method receives an invalid value, what is the proper response? I see 2 options</p>
<ol>
<li>Don't set the value and return false</li>
<li>Set the value anyway, but set an error property for the object. (so if User.Error is set I know something went wrong)</li>
</ol>
<p>I suspect #1 is best practice because you can then assure the value of any object property is always valid. Correct?</p>
| [
{
"answer_id": 348746,
"author": "Rob Williams",
"author_id": 26682,
"author_profile": "https://Stackoverflow.com/users/26682",
"pm_score": 4,
"selected": true,
"text": "User EmailAddress User EmailAddress EmailAddress EmailAddress EmailUserId InternetDomain valid(input) isValid(input) EmailAddress PhoneNumber PersonName"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26180/"
] |
348,630 | <p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
| [
{
"answer_id": 641843,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/env python\n\"\"\"Save all attachments for given gmail account.\"\"\"\nimport os, sys\nfrom libgmail import GmailAccount\n\nga = GmailAccount(\"your.account@gmail.com\", \"pA$$w0Rd_\")\nga.login()\n\n# folders: inbox, starred, all, drafts, sent, spam\nfor thread in ga.getMessagesByFolder('all', allPages=True):\n for msg in thread:\n sys.stdout.write('.')\n if msg.attachments:\n print \"\\n\", msg.id, msg.number, msg.subject, msg.sender\n for att in msg.attachments:\n if att.filename and att.content:\n attdir = os.path.join(thread.id, msg.id)\n if not os.path.isdir(attdir):\n os.makedirs(attdir) \n with open(os.path.join(attdir, att.filename), 'wb') as f:\n f.write(att.content)\n"
},
{
"answer_id": 642988,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": true,
"text": "import email, getpass, imaplib, os\n\ndetach_dir = '.' # directory where to save attachments (default: current)\nuser = raw_input(\"Enter your GMail username:\")\npwd = getpass.getpass(\"Enter your password: \")\n\n# connecting to the gmail imap server\nm = imaplib.IMAP4_SSL(\"imap.gmail.com\")\nm.login(user,pwd)\nm.select(\"[Gmail]/All Mail\") # here you a can choose a mail box like INBOX instead\n# use m.list() to get all the mailboxes\n\nresp, items = m.search(None, \"ALL\") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)\nitems = items[0].split() # getting the mails id\n\nfor emailid in items:\n resp, data = m.fetch(emailid, \"(RFC822)\") # fetching the mail, \"`(RFC822)`\" means \"get the whole stuff\", but you can ask for headers only, etc\n email_body = data[0][1] # getting the mail content\n mail = email.message_from_string(email_body) # parsing the mail content to get a mail object\n\n #Check if any attachments at all\n if mail.get_content_maintype() != 'multipart':\n continue\n\n print \"[\"+mail[\"From\"]+\"] :\" + mail[\"Subject\"]\n\n # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach\n for part in mail.walk():\n # multipart are just containers, so we skip them\n if part.get_content_maintype() == 'multipart':\n continue\n\n # is this part an attachment ?\n if part.get('Content-Disposition') is None:\n continue\n\n filename = part.get_filename()\n counter = 1\n\n # if there is no filename, we create one with a counter to avoid duplicates\n if not filename:\n filename = 'part-%03d%s' % (counter, 'bin')\n counter += 1\n\n att_path = os.path.join(detach_dir, filename)\n\n #Check if its already there\n if not os.path.isfile(att_path) :\n # finally write the stuff\n fp = open(att_path, 'wb')\n fp.write(part.get_payload(decode=True))\n fp.close()\n m.list() m.select(\"the mailbox name\")"
},
{
"answer_id": 643366,
"author": "JDrago",
"author_id": 29060,
"author_profile": "https://Stackoverflow.com/users/29060",
"pm_score": 3,
"selected": false,
"text": "get_indv_email # Creates an array of references to every attachment in your account\nmy $messages = $gmail->get_messages();\nmy @attachments;\n\nforeach ( @{ $messages } ) {\n my $email = $gmail->get_indv_email( msg => $_ );\n if ( defined( $email->{ $_->{ 'id' } }->{ 'attachments' } ) ) {\n foreach ( @{ $email->{ $_->{ 'id' } }->{ 'attachments' } } ) {\n push( @attachments, $gmail->get_attachment( attachment => $_ ) );\n if ( $gmail->error() ) {\n print $gmail->error_msg();\n }\n }\n }\n}\n #retrieve specific attachment\nmy $msgid = 'F000000000';\nmy $attachid = '0.1';\nmy $attach_ref = $gmail->get_attachment( attid => $attachid, msgid => $msgid );\n"
},
{
"answer_id": 4172062,
"author": "msanjay",
"author_id": 392985,
"author_profile": "https://Stackoverflow.com/users/392985",
"pm_score": 1,
"selected": false,
"text": "import javax.mail.*\nimport java.util.Properties\n\nString gmailServer\nint gmailPort\ndef user, password, LIMIT\ndef inboxFolder, root, StartDate, EndDate\n\n\n// Downloads all attachments from a gmail mail box as per some criteria\n// to a specific folder\n// Based on code from\n// http://agileice.blogspot.com/2008/10/using-groovy-to-connect-to-gmail.html\n// http://stackoverflow.com/questions/155504/download-mail-attachment-with-java\n//\n// Requires: \n// java mail jars in the class path (mail.jar and activation.jar)\n// openssl, with gmail certificate added to java keystore (see agileice blog)\n// \n// further improvement: maybe findAll could be used to filter messages\n// subject could be added as another criteria\n////////////////////// <CONFIGURATION> //////////////////////\n// Maximm number of emails to access in case parameter range is too high\nLIMIT = 10000\n\n// gmail credentials\ngmailServer = \"imap.gmail.com\"\ngmailPort = 993\n\nuser = \"gmailuser@gmail.com\"\npassword = \"gmailpassword\"\n\n// gmail label, or \"INBOX\" for inbox\ninboxFolder = \"finance\"\n\n// local file system where the attachment files need to be stored\nroot = \"D:\\\\AttachmentStore\" \n\n// date range dd-mm-yyyy\nStartDate= \"31-12-2009\"\nEndDate = \"1-6-2010\" \n////////////////////// </CONFIGURATION> //////////////////////\n\nStartDate = Date.parse(\"dd-MM-yyyy\", StartDate)\nEndDate = Date.parse(\"dd-MM-yyyy\", EndDate)\n\nProperties props = new Properties();\nprops.setProperty(\"mail.store.protocol\", \"imaps\");\nprops.setProperty(\"mail.imaps.host\", gmailServer);\nprops.setProperty(\"mail.imaps.port\", gmailPort.toString());\nprops.setProperty(\"mail.imaps.partialfetch\", \"false\");\n\ndef session = javax.mail.Session.getDefaultInstance(props,null)\ndef store = session.getStore(\"imaps\")\n\nstore.connect(gmailServer, user, password)\n\nint i = 0;\ndef folder = store.getFolder(inboxFolder)\n\nfolder.open(Folder.READ_ONLY)\n\nfor(def msg : folder.messages) {\n\n //if (msg.subject?.contains(\"bank Statement\"))\n println \"[$i] From: ${msg.from} Subject: ${msg.subject} -- Received: ${msg.receivedDate}\"\n\n if (msg.receivedDate < StartDate || msg.receivedDate > EndDate) {\n println \"Ignoring due to date range\"\n continue\n }\n\n\n if (msg.content instanceof Multipart) {\n Multipart mp = (Multipart)msg.content;\n\n for (int j=0; j < mp.count; j++) {\n\n Part part = mp.getBodyPart(j);\n\n println \" ---- ${part.fileName} ---- ${part.disposition}\"\n\n if (part.disposition?.equalsIgnoreCase(Part.ATTACHMENT)) {\n\n if (part.content) {\n\n def name = msg.receivedDate.format(\"yyyy_MM_dd\") + \" \" + part.fileName\n println \"Saving file to $name\"\n\n def f = new File(root, name)\n\n //f << part.content\n try {\n if (!f.exists())\n f << part.content\n }\n catch (Exception e) {\n println \"*** Error *** $e\" \n }\n }\n else {\n println \"NO Content Found!!\"\n }\n }\n }\n }\n\n if (i++ > LIMIT)\n break;\n\n}\n"
},
{
"answer_id": 18259764,
"author": "Eric Thomas",
"author_id": 2615521,
"author_profile": "https://Stackoverflow.com/users/2615521",
"pm_score": 2,
"selected": false,
"text": "# Something in lines of http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail\n# Make sure you have IMAP enabled in your gmail settings.\n# Right now it won't download same file name twice even if their contents are different.\n# Gmail as of now returns in bytes but just in case they go back to string this line is left here.\n\nimport email\nimport getpass, imaplib\nimport os\nimport sys\nimport time\n\ndetach_dir = '.'\nif 'attachments' not in os.listdir(detach_dir):\n os.mkdir('attachments')\n\nuserName = input('Enter your GMail username:\\n')\npasswd = getpass.getpass('Enter your password:\\n')\n\n\ntry:\n imapSession = imaplib.IMAP4_SSL('imap.gmail.com',993)\n typ, accountDetails = imapSession.login(userName, passwd)\n if typ != 'OK':\n print ('Not able to sign in!')\n raise\n\n imapSession.select('Inbox')\n typ, data = imapSession.search(None, 'ALL')\n if typ != 'OK':\n print ('Error searching Inbox.')\n raise\n\n # Iterating over all emails\n for msgId in data[0].split():\n typ, messageParts = imapSession.fetch(msgId, '(RFC822)')\n\n if typ != 'OK':\n print ('Error fetching mail.')\n raise \n\n #print(type(emailBody))\n emailBody = messageParts[0][1]\n #mail = email.message_from_string(emailBody)\n mail = email.message_from_bytes(emailBody)\n\n for part in mail.walk():\n #print (part)\n if part.get_content_maintype() == 'multipart':\n # print part.as_string()\n continue\n if part.get('Content-Disposition') is None:\n # print part.as_string()\n continue\n\n fileName = part.get_filename()\n\n if bool(fileName):\n filePath = os.path.join(detach_dir, 'attachments', fileName)\n if not os.path.isfile(filePath) :\n print (fileName)\n fp = open(filePath, 'wb')\n fp.write(part.get_payload(decode=True))\n fp.close()\n\n imapSession.close()\n imapSession.logout()\n\nexcept :\n print ('Not able to download all attachments.')\n time.sleep(3)\n"
},
{
"answer_id": 26009465,
"author": "jechaviz",
"author_id": 551477,
"author_profile": "https://Stackoverflow.com/users/551477",
"pm_score": 1,
"selected": false,
"text": "/*based on http://www.codejava.net/java-ee/javamail/using-javamail-for-searching-e-mail-messages*/\npackage getMailsWithAtt;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Properties;\n\nimport javax.mail.Address;\nimport javax.mail.Folder;\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.Multipart;\nimport javax.mail.NoSuchProviderException;\nimport javax.mail.Part;\nimport javax.mail.Session;\nimport javax.mail.Store;\nimport javax.mail.internet.MimeBodyPart;\nimport javax.mail.search.AndTerm;\nimport javax.mail.search.SearchTerm;\nimport javax.mail.search.ReceivedDateTerm;\nimport javax.mail.search.ComparisonTerm;\n\npublic class EmailReader {\n private String saveDirectory;\n\n /**\n * Sets the directory where attached files will be stored.\n * \n * @param dir\n * absolute path of the directory\n */\n public void setSaveDirectory(String dir) {\n this.saveDirectory = dir;\n }\n\n /**\n * Downloads new messages and saves attachments to disk if any.\n * \n * @param host\n * @param port\n * @param userName\n * @param password\n * @throws IOException\n */\n public void downloadEmailAttachments(String host, String port,\n String userName, String password, Date startDate, Date endDate) {\n Properties props = System.getProperties();\n props.setProperty(\"mail.store.protocol\", \"imaps\");\n try {\n Session session = Session.getDefaultInstance(props, null);\n Store store = session.getStore(\"imaps\");\n store.connect(\"imap.gmail.com\", userName, password);\n // ...\n Folder inbox = store.getFolder(\"INBOX\");\n inbox.open(Folder.READ_ONLY);\n SearchTerm olderThan = new ReceivedDateTerm (ComparisonTerm.LT, startDate);\n SearchTerm newerThan = new ReceivedDateTerm (ComparisonTerm.GT, endDate);\n SearchTerm andTerm = new AndTerm(olderThan, newerThan);\n //Message[] arrayMessages = inbox.getMessages(); <--get all messages\n Message[] arrayMessages = inbox.search(andTerm);\n for (int i = arrayMessages.length; i > 0; i--) { //from newer to older\n Message msg = arrayMessages[i-1];\n Address[] fromAddress = msg.getFrom();\n String from = fromAddress[0].toString();\n String subject = msg.getSubject();\n String sentDate = msg.getSentDate().toString();\n String receivedDate = msg.getReceivedDate().toString();\n\n String contentType = msg.getContentType();\n String messageContent = \"\";\n\n // store attachment file name, separated by comma\n String attachFiles = \"\";\n\n if (contentType.contains(\"multipart\")) {\n // content may contain attachments\n Multipart multiPart = (Multipart) msg.getContent();\n int numberOfParts = multiPart.getCount();\n for (int partCount = 0; partCount < numberOfParts; partCount++) {\n MimeBodyPart part = (MimeBodyPart) multiPart\n .getBodyPart(partCount);\n if (Part.ATTACHMENT.equalsIgnoreCase(part\n .getDisposition())) {\n // this part is attachment\n String fileName = part.getFileName();\n attachFiles += fileName + \", \";\n part.saveFile(saveDirectory + File.separator + fileName);\n } else {\n // this part may be the message content\n messageContent = part.getContent().toString();\n }\n }\n if (attachFiles.length() > 1) {\n attachFiles = attachFiles.substring(0,\n attachFiles.length() - 2);\n }\n } else if (contentType.contains(\"text/plain\")\n || contentType.contains(\"text/html\")) {\n Object content = msg.getContent();\n if (content != null) {\n messageContent = content.toString();\n }\n }\n\n // print out details of each message\n System.out.println(\"Message #\" + (i + 1) + \":\");\n System.out.println(\"\\t From: \" + from);\n System.out.println(\"\\t Subject: \" + subject);\n System.out.println(\"\\t Received: \" + sentDate);\n System.out.println(\"\\t Message: \" + messageContent);\n System.out.println(\"\\t Attachments: \" + attachFiles);\n }\n\n // disconnect\n inbox.close(false);\n store.close();\n\n } catch (NoSuchProviderException e) {\n e.printStackTrace();\n System.exit(1);\n } catch (MessagingException e) {\n e.printStackTrace();\n System.exit(2);\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n\n /**\n * Runs this program with Gmail POP3 server\n * @throws ParseException \n */\n public static void main(String[] args) throws ParseException {\n String host = \"pop.gmail.com\";\n String port = \"995\";\n String userName = \"user@gmail.com\";\n String password = \"pass\";\n Date startDate = new SimpleDateFormat(\"yyyy-MM-dd\").parse(\"2014-06-30\");\n Date endDate = new SimpleDateFormat(\"yyyy-MM-dd\").parse(\"2014-06-01\");\n String saveDirectory = \"C:\\\\Temp\";\n\n EmailReader receiver = new EmailReader();\n receiver.setSaveDirectory(saveDirectory);\n receiver.downloadEmailAttachments(host, port, userName, password,startDate,endDate);\n\n }\n}\n <dependency>\n <groupId>com.sun.mail</groupId>\n <artifactId>javax.mail</artifactId>\n <version>1.5.1</version>\n</dependency>\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,657 | <p>I have a string from which I wish to extract a single word, but with a numerical appended to it, which might be different in each line:</p>
<pre><code>This is string1 this is string
This is string11
This is string6 and it is in this line
</code></pre>
<p>I want to parse this file and get the values of "stringXXX", starting from 0 to 100</p>
<pre><code># suppose ABC.txt contains the above lines
FH1 = open "Abc.txt";
@abcFile = <FH1>;
foreach $line(@abcFile) {
if ($pattern =~ s/string.(d{0}d{100});
print $pattern;
</code></pre>
<p>The above prints the whole line, I wish to get only stringXXX</p>
| [
{
"answer_id": 348670,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 5,
"selected": true,
"text": "while ($pattern =~/(string(100|\\d{1,2}))/g) {\n print $1;\n}\n"
},
{
"answer_id": 348735,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/perl -w \nwhile(<>) {\n while (/(string(\\d{1,3}))/g) { \n print \"$1\\n\" if $2 <= 100;\n } \n}\n $ cat Abc.txt \nThis is string1 this is string\nThis is string11 \nThis is string6 and it is in this line\nstring1 asdfa string2\nstring101 string3 string100 string1000\nstring9999 string001 string0001\n\n$ perl Abc.pl Abc.txt\nstring1\nstring11\nstring6\nstring1\nstring2\nstring3\nstring100\nstring100\nstring001\nstring000\n\n$ perl -nE\"say $1 while /(string(?:100|\\d{1,2}(?!\\d)))/g\" Abc.txt\nstring1\nstring11\nstring6\nstring1\nstring2\nstring3\nstring100\nstring100\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
348,680 | <p>I am working with a wrapper class for <code>CFHTTPMessage</code>, which contains a <code>CFHTTPMessageRef</code> object to which is added the method (GET), the URL of the web application server, and a few custom headers containing the date and an authentication nonce.</p>
<p>I'm having some problems getting the method and URL to return certain data. I think I've worked out the authentication nonce. </p>
<p>I'd like to troubleshoot this by looking at the raw request going to the web application, and making sure everything is formatted properly. </p>
<p>My question is: If I have a <code>CFHTTPMessageRef</code> object (e.g. <code>messageRef</code>), is there a way to log the raw HTTP request that comes out of this message?</p>
<p>I've tried the following but I get a <code>EXC_BAD_ACCESS</code> signal when I try to access its bytes:</p>
<pre><code>CFDataRef messageData = CFHTTPMessageCopyBody(messageRef);
</code></pre>
<p>Thanks for any advice.</p>
<p>As an alternative, is it possible to use a packet sniffer on a switched network? I can run <code>ettercap</code> on a laptop device, but don't know how to sniff what my iPhone is doing on the local wireless network.</p>
| [
{
"answer_id": 351335,
"author": "Alex Reynolds",
"author_id": 19410,
"author_profile": "https://Stackoverflow.com/users/19410",
"pm_score": 4,
"selected": true,
"text": "NSData *d = (NSData *)CFHTTPMessageCopySerializedMessage(messageRef);\nNSLog(@\"%@\",[[[NSString alloc] initWithBytes:[d bytes] length:[d length] encoding:NSUTF8StringEncoding] autorelease]);\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19410/"
] |
348,684 | <p>I've got an NSBrowser hooked up to an NSTreeController bound to an array of NSTreeNode objects. It's easy enough to get the text portion working by setting the Content and Content Value bindings to properly reference the tree controller, but how do I set the image for each cell using bindings?</p>
| [
{
"answer_id": 351335,
"author": "Alex Reynolds",
"author_id": 19410,
"author_profile": "https://Stackoverflow.com/users/19410",
"pm_score": 4,
"selected": true,
"text": "NSData *d = (NSData *)CFHTTPMessageCopySerializedMessage(messageRef);\nNSLog(@\"%@\",[[[NSString alloc] initWithBytes:[d bytes] length:[d length] encoding:NSUTF8StringEncoding] autorelease]);\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
348,688 | <p>I'm using a hosting service which allows me to backup my SQL 2008 database and download the BAK file via a web interface only--and I have access to the database via Management Studio. I can execute the backup command from Management Studio,but I don't have rights to the path where the backups are located. Is there any way via SQL or script to pull down a full copy of the database--can I generate the script required to recreate the database using code? It's only a few thousand records.</p>
<p>Thanks.</p>
| [
{
"answer_id": 5413233,
"author": "anthonyvscode",
"author_id": 79254,
"author_profile": "https://Stackoverflow.com/users/79254",
"pm_score": 2,
"selected": false,
"text": "::Run dbbackup.bat and append all output to log.txt\n\nmd C:\\[directory]\\%date:~-4,4%%date:~-7,2%%date:~-10,2%\n\n\"dbbackup.bat\" >> \"C:\\[Directory]\\%date:~-4,4%%date:~-7,2%%date:~-10,2%\\log.txt\"\n echo off\ncls\necho %date% %time%\necho ***************************************************************************\necho ** Script all objects in databases and save them in 'yyyymmdd' folder **\necho ***************************************************************************\ncd C:\\[directory]\\%date:~-4,4%%date:~-7,2%%date:~-10,2%\n\"C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\sqlpubwiz.exe\" script -C \"[ConnectionString]\" [dbname]_%date:~-4,4%%date:~-7,2%%date:~-10,2%.sql\necho ***************************************************************************\necho ** RAR compress all .sql script files **\necho ***************************************************************************\n\"C:\\Program Files\\WinRAR\\WinRAR.exe\" -ibck a [dbname]_%date:~-4,4%%date:~-7,2%%date:~-10,2%.rar [dbname]_%date:~-4,4%%date:~-7,2%%date:~-10,2%.sql\necho WinRAR has completed execution\necho ***************************************************************************\necho ** Delete all .sql script files **\necho ***************************************************************************\ndel *.sql\necho .SQL files deleted\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5592/"
] |
348,689 | <p>I'm doing some simple tests (in preparation for a larger project) to call an ASP.NET WebMethod using JQuery AJAX. In my example, my WebMethod returns a simple string. However, when I attempt to call it using JQuery, I get the entire HTML page content returned instead of just my string. What am I missing?</p>
<p>Client Side :</p>
<pre><code>$(document).ready(function ready() {
$("#MyButton").click(function clicked(e) {
$.post("Default.aspx/TestMethod",
{name:"Bob"},
function(msg) {
alert("Data Recieved: " + msg);
},
"html"
);
});
});
</code></pre>
<p>Server Side:</p>
<pre><code>using System;
using System.Web.Services;
namespace JqueryAjaxText
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestMethod(string name)
{
return "The value submitted was " + name;
}
}
}
</code></pre>
| [
{
"answer_id": 348770,
"author": "JoshBerke",
"author_id": 26160,
"author_profile": "https://Stackoverflow.com/users/26160",
"pm_score": 6,
"selected": true,
"text": " $(\"#Result\").click(function() {\n $.ajax({\n type: \"POST\",\n url: \"Default.aspx/GetDate\",\n data: \"{}\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function(msg) {\n $(\"#Result\").text(msg.d);\n }\n });\n});\n"
},
{
"answer_id": 42029809,
"author": "BernieSF",
"author_id": 1689852,
"author_profile": "https://Stackoverflow.com/users/1689852",
"pm_score": 0,
"selected": false,
"text": "settings.AutoRedirectMode = RedirectMode.Permanent;\n settings.AutoRedirectMode = RedirectMode.Off;\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44197/"
] |
348,690 | <p>How do I compare two dates in Lingo? To be specific, I want to know if today's date is after some fixed date. I know I can create the fixed date by using:</p>
<pre><code>date("20090101")
</code></pre>
<p>and I can get the current date using:</p>
<pre><code>_system.date()
</code></pre>
<p>but I can't seem to directly compare the two. Do I have to parse the _system.date() to determine if it's after my fixed date? I tried:</p>
<pre><code>if(_system.date() > date("20090101") then
--do something
end if
</code></pre>
<p>but that doesn't seem to work. Any ideas?</p>
| [
{
"answer_id": 348712,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 0,
"selected": false,
"text": " if (_system.date().char[1..2] >= 01 and _system.date().char[4..5] >= 01 and _system.date().char[7..10] >= 2010) then\n alert(\"Your license has expired. Please contact the Company to renew your license.\")\n _player.quit()\n end if\n"
},
{
"answer_id": 1839035,
"author": "luna1999",
"author_id": 2573986,
"author_profile": "https://Stackoverflow.com/users/2573986",
"pm_score": 3,
"selected": true,
"text": "--do something\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23249/"
] |
348,708 | <p>Ok, what I'm trying to do is build a web app that allows students to visually organize their class calendar using drag and drop. but They have to be able to drag and drop to specific locations (when those classes are available), not just anywhere.</p>
<p>This would be a 'fixed week' calendar. I was considering using a table, but was wondering if anyone thought this might be an issue for the drag and drop and if you had suggestions for a better implementation. Would love to hear your thoughts. I'm a very visual thinker and know this sort of app would help me.</p>
<p>Alternatively, if you know of something like this already implemented which I can use, Let me know!</p>
| [
{
"answer_id": 348874,
"author": "Tuminoid",
"author_id": 40657,
"author_profile": "https://Stackoverflow.com/users/40657",
"pm_score": 3,
"selected": true,
"text": "<body style=\"font-size: 12px;\">\n<h1>A Simple Example</h1>\n<table><tbody><tr>\n<td>\n<!-- Create a source with two nodes -->\n<div dojoType=\"dojo.dnd.Source\" jsId=\"c1\" class=\"source\">\n SOURCE\n <div class=\"dojoDndItem\" dndType=\"blue\">\n <div class=\"bluesquare\">BLUE</div>\n </div>\n <div class=\"dojoDndItem\" dndType=\"red,darkred\">\n <div class=\"redsquare\">RED</div>\n </div>\n</div>\n</td>\n<td>\n<!-- Create a target that accepts nodes of type red and blue. -->\n<div dojoType=\"dojo.dnd.Target\" jsId=\"c2\" class=\"target\" accept=\"blue,darkred\">\n TARGET\n</div>\n</td>\n</tr><tbody/></table>\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43510/"
] |
348,724 | <p>I have a situation where I'm populating a gridview with a bound data source, and want two additional rows at the very bottom; one to show the sum of values in the columns and one to show the average of values in the columns. I can quite easily calculate these values by aggregating information taken from the rowDataBound event, but don't know how to go about manually adding the additional two rows to the gridview. Any help much appreciated.</p>
| [
{
"answer_id": 348762,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 2,
"selected": false,
"text": "UNION\n"
},
{
"answer_id": 348778,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "IList"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,730 | <p>What does the "class" part of a template statement do?</p>
<p>Example:</p>
<pre><code>template <class T>
class Something
{
public:
Something(const T &something);
}
</code></pre>
<p>And what else can go there? I usually only see "class".</p>
| [
{
"answer_id": 348740,
"author": "AlfaZulu",
"author_id": 44060,
"author_profile": "https://Stackoverflow.com/users/44060",
"pm_score": 4,
"selected": true,
"text": "class typename class typename class typename template<template <class T> class U> // must be \"class\"\nstd::string to_string(const U<char>& u)\n{\n return std::string(u.begin(),u.end());\n}\n class typename template<std::size_t max>\nclass Foo{...};\n...\nFoo<10> f;\n std::bitset<N>"
},
{
"answer_id": 348774,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 2,
"selected": false,
"text": "short, int, long, bool template<typename T, int N=4, bool Flag>\nclass myClass { /*...*/ };\n\ntemplate<typename T, const int& Reference, myClass * Pointer>\nclass someClass { /*...*/ };\n\ntemplate<typename T, int (T::*MemberFunctionPtr)(int, int)>\nclass anotherClass { /*...*/ };"
},
{
"answer_id": 354479,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 3,
"selected": false,
"text": "template<int I>\nint getTwice()\n{\n return I * 2 ;\n}\n\ntemplate<class T>\nstd::string getType(const T & t)\n{\n return typeid(t).name() ;\n}\n\nvoid doSomething()\n{\n std::cout << \"25 : \" << getTwice<25>() << std::endl ;\n std::cout << \"5 : \" << getTwice<5>() << std::endl ;\n\n std::cout << \"type(25) : \" << getType(25) << std::endl ;\n std::cout << \"type(25.5) : \" << getType(25.5) << std::endl ;\n std::cout << \"type(abc) : \" << getType(\"abc\") << std::endl ;\n}\n 25 : 50\n5 : 10\ntype(25) : i\ntype(25.5) : d\ntype(abc) : A4_c\n // \"I\" is the value, and \"int\" is the type of the value\ntemplate <int I>\n // \"T\" is a type... And \"class\" is the \"this-is-a-type\" keyword\ntemplate <class T> \n template<class T> // T could be any STL container, for example a vector<char>\nvoid printContainerData(const T & t)\n{\n std::cout << \"aVector:\" ;\n\n for(T::const_iterator it = t.begin(), itEnd = t.end(); it != itEnd; ++it)\n {\n std::cout << \" \" << (*it) ;\n }\n\n std::cout << std::endl ;\n}\n for(class T::const_iterator it = t.begin(), // etc.\n for(typename T::const_iterator it = t.begin(), // etc.\n template <typename T>\n template <class T>\n template<template <class T> class U> // must be \"class\"\nstd::string to_string(const U<char>& u)\n{\n return std::string(u.begin(),u.end());\n}\n template <class T> class U\n template <typename T> class U\n std::string to_string(const U<char>& u)\n template<typename T>\nclass U\n{\n // Etc.\n} ;\n U<char> u ;\n// etc.\nto_string(u)\n template<template <class T> class U>\nstd::string to_string(const U<char>& u)\n\ntemplate<template <typename T> class U>\nstd::string to_string(const U<char>& u)\n template<typename U>\nstd::string to_string(const U & u)\n{\n return std::string(u.begin(),u.end());\n}\n std::list<char> myList ;\n// etc.\nstd::cout << to_string(myList) << std:endl ;\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43496/"
] |
348,736 | <p>I have noticed jQuery (or is it Firefox) will turn some of my <code><span class="presentational"></span> into <span class="presentational" /></code></p>
<p>Now my question is, is this okay to write my markup like this? Will any browsers choke on it?</p>
<p>Personally, I think it looks cleaner to do <code><span class="presentational" /></code> if it's going to be empty.</p>
| [
{
"answer_id": 348767,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 3,
"selected": false,
"text": "<script type='text/javascript' src='script.js' />\n <script>"
},
{
"answer_id": 348781,
"author": "Elle H",
"author_id": 23666,
"author_profile": "https://Stackoverflow.com/users/23666",
"pm_score": 0,
"selected": false,
"text": "<script> </script> <meta> <meta></meta> <meta /> <div></div> <div /> <div> </div>"
},
{
"answer_id": 1573341,
"author": "Tim Down",
"author_id": 96100,
"author_profile": "https://Stackoverflow.com/users/96100",
"pm_score": 4,
"selected": false,
"text": "<span /> <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n <title>Test</title>\n <script type=\"text/javascript\">\n function show() {\n var span = document.getElementById(\"span\");\n alert(span.innerHTML);\n }\n </script>\n</head>\n<body onload=\"show();\">\n<p id=\"p1\">Paragraph containing some text followed by\n an empty span<span id=\"span\"/></p>\n<p id=\"p2\">Second paragraph just containing text</p>\n</body>\n</html>\n </P>\n<P id=p2>Second paragraph just containing text</P>\n <p> childNodes <p> childNodes"
},
{
"answer_id": 2193643,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<?xml ...?>"
},
{
"answer_id": 3396586,
"author": "Erich Kitzmueller",
"author_id": 65464,
"author_profile": "https://Stackoverflow.com/users/65464",
"pm_score": 1,
"selected": false,
"text": "<img> <span>"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
348,756 | <p>Modifying the HTTP Response Using Filters</p>
| [
{
"answer_id": 348766,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 0,
"selected": false,
"text": "HttpServletResponse class BookController {\n def downloadFile = {\n byte[] bytes = // read bytes\n response.outputStream << bytes\n }\n}\n HttpServletResponse"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42791/"
] |
348,760 | <p>What is the simplest way to get the machine's time zone as a positive or negative UTC offset, preferably using some time of shell command?</p>
| [
{
"answer_id": 348824,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 3,
"selected": false,
"text": "date +%z"
},
{
"answer_id": 348848,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 1,
"selected": false,
"text": "date -d 'Jan 1' +%z\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,763 | <p>I have a template class like below.</p>
<pre><code>template<int S> class A
{
private:
char string[S];
public:
A()
{
for(int i =0; i<S; i++)
{
.
.
}
}
int MaxLength()
{
return S;
}
};
</code></pre>
<p>If i instantiate the above class with different values of S, will the compiler create different instances of A() and MaxLenth() function? Or will it create one instance and pass the S as some sort of argument?</p>
<p>How will it behave if i move the definition of A and Maxlength to a different cpp file.</p>
| [
{
"answer_id": 348772,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "A() MaxLength() return S;"
},
{
"answer_id": 348780,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 4,
"selected": true,
"text": ".ipp .ipp"
},
{
"answer_id": 348935,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 3,
"selected": false,
"text": "template <int S>\nclass A\n{\n char s_[S];\npublic:\n A()\n {\n for(int i = 0; i < S; ++i)\n {\n s_[i] = 'A';\n }\n }\n int MaxLength() const\n {\n return S;\n }\n};\n\nextern void useA(A<5> &a, int n); // to fool the optimizer\nextern void useA(A<25> &a, int n);\n\nvoid test()\n{\n A<5> a5;\n useA(a5, a5.MaxLength());\n A<25> a25;\n useA(a25, a25.MaxLength());\n}\n ?test@@YAXXZ PROC ; test, COMDAT\n\n[snip]\n\n; 25 : A<5> a5;\n\nmov eax, 1094795585 ; 41414141H\nmov DWORD PTR _a5$[esp+40], eax\nmov BYTE PTR _a5$[esp+44], al\n\n; 26 : useA(a5, a5.MaxLength());\n\nlea eax, DWORD PTR _a5$[esp+40]\npush 5\npush eax\ncall ?useA@@YAXAAV?$A@$04@@H@Z ; useA\n ; 28 : A<25> a25;\n\nmov eax, 1094795585 ; 41414141H\n\n; 29 : useA(a25, a25.MaxLength());\n\nlea ecx, DWORD PTR _a25$[esp+48]\npush 25 ; 00000019H\npush ecx\nmov DWORD PTR _a25$[esp+56], eax\nmov DWORD PTR _a25$[esp+60], eax\nmov DWORD PTR _a25$[esp+64], eax\nmov DWORD PTR _a25$[esp+68], eax\nmov DWORD PTR _a25$[esp+72], eax\nmov DWORD PTR _a25$[esp+76], eax\nmov BYTE PTR _a25$[esp+80], al\ncall ?useA@@YAXAAV?$A@$0BJ@@@H@Z ; useA\n"
},
{
"answer_id": 348989,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "A<S>::MaxLength() A<S>::A()"
},
{
"answer_id": 349732,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "S A MaxLength MaxLength S template<int S> class A {\npublic:\n A() { /* .... */ }\n int MaxLength(); /* not defined here in the header file */\n};\n template<int S> int\nA<S>::MaxLength() { /* ... */ }\n MaxLength S MaxLength template class A<25>;\n A<25> S=25"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39615/"
] |
348,777 | <p>I have to read a COM port and the data should be displayed inside the TextArea dynamically (data will come every minute), which I have created inside JPanel.</p>
<p>Advance Thanks for reply.</p>
| [
{
"answer_id": 349797,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 0,
"selected": false,
"text": "javax.comm gnu"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,785 | <p>I know the use of server-side controls is a no-no in ASP.NET MVC, however we have a long list of crystal reports that the company has already produced for a previous application that I would like to utilize for our new ASP.NET MVC application.</p>
<p>Is there an appropriate way to use crystal reports in ASP.NET MVC? If so, how?</p>
| [
{
"answer_id": 2747571,
"author": "coderguy123",
"author_id": 73496,
"author_profile": "https://Stackoverflow.com/users/73496",
"pm_score": 6,
"selected": false,
"text": "using CrystalDecisions.CrystalReports.Engine;\n\npublic ActionResult Report()\n {\n ReportClass rptH = new ReportClass();\n rptH.FileName = Server.MapPath(\"[reportName].rpt\");\n rptH.Load();\n rptH.SetDataSource([datatable]);\n Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);\n return File(stream, \"application/pdf\"); \n }\n Imports CrystalDecisions.CrystalReports.Engine\n\n Public Function Report() As ActionResult\n Dim rptH As New ReportClass()\n rptH.FileName = Server.MapPath(\"[reportName].rpt\")\n rptH.Load()\n rptH.SetDataSource([datatable])\n Dim stream As IO.Stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat)\n Return File(stream, \"application/pdf\")\n End Function\n"
},
{
"answer_id": 44145017,
"author": "Sofia",
"author_id": 7703600,
"author_profile": "https://Stackoverflow.com/users/7703600",
"pm_score": 2,
"selected": false,
"text": "using CrystalDecisions.CrystalReports.Engine; \n public ActionResult Report()\n {\n List<Table> table = new List<Table>();\n ReportDocument rd = new ReportDocument();\n rd.Load(Path.Combine(Server.MapPath(\"~/Repport/CrystalReport1.rpt\")));\n\n Response.Buffer = false;\n Response.ClearContent();\n Response.ClearHeaders();\n Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);\n stream.Seek(0, SeekOrigin.Begin);\n\n\n return File(stream, \"application/pdf\", \"Suivie Historique.pdf\");\n\n\n }\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11908/"
] |
348,792 | <p>How do you tell if caps lock is on using JavaScript?</p>
<p>One caveat though: I did google it and the best solution I could find was to attach an <code>onkeypress</code> event to every input, then check each time if the letter pressed was uppercase, and if it was, then check if shift was also held down. If it wasn't, therefore caps lock must be on. This feels really dirty and just... <em>wasteful</em> - surely there's a better way than this?</p>
| [
{
"answer_id": 348802,
"author": "rajesh pillai",
"author_id": 34644,
"author_profile": "https://Stackoverflow.com/users/34644",
"pm_score": 8,
"selected": true,
"text": "function isCapslock(e) {\n const IS_MAC = /Mac/.test(navigator.platform);\n\n const charCode = e.charCode;\n const shiftKey = e.shiftKey;\n\n if (charCode >= 97 && charCode <= 122) {\n capsLock = shiftKey;\n } else if (charCode >= 65 && charCode <= 90\n && !(shiftKey && IS_MAC)) {\n capsLock = !shiftKey;\n }\n\n return capsLock;\n}\n function isCapslock(e) {\n e = (e) ? e : window.event;\n\n var charCode = false;\n if (e.which) {\n charCode = e.which;\n } else if (e.keyCode) {\n charCode = e.keyCode;\n }\n\n var shifton = false;\n if (e.shiftKey) {\n shifton = e.shiftKey;\n } else if (e.modifiers) {\n shifton = !!(e.modifiers & 4);\n }\n\n if (charCode >= 97 && charCode <= 122 && shifton) {\n return true;\n }\n\n if (charCode >= 65 && charCode <= 90 && !shifton) {\n return true;\n }\n\n return false;\n}\n"
},
{
"answer_id": 348803,
"author": "rz.",
"author_id": 7407,
"author_profile": "https://Stackoverflow.com/users/7407",
"pm_score": -1,
"selected": false,
"text": "$('some_element').keypress(function(e){\n if(e.keyCode == 20){\n //caps lock was pressed\n }\n});\n"
},
{
"answer_id": 351326,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 5,
"selected": false,
"text": "document.onkeypress = function ( e ) {\n e = e || window.event;\n var s = String.fromCharCode( e.keyCode || e.which );\n if ( (s.toUpperCase() === s) !== e.shiftKey ) {\n // alert('caps is on')\n }\n}\n toUpperCase()"
},
{
"answer_id": 896515,
"author": "user110902",
"author_id": 110902,
"author_profile": "https://Stackoverflow.com/users/110902",
"pm_score": 7,
"selected": false,
"text": "$('#example').keypress(function(e) { \n var s = String.fromCharCode( e.which );\n if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {\n alert('caps is on');\n }\n});\n s.toLowerCase() !== s"
},
{
"answer_id": 3815931,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 4,
"selected": false,
"text": "<input id=\"password\" type=\"password\" name=\"whatever\"/> capsLockWarning $('#password').keypress(function(e) {\n e = e || window.event;\n\n // An empty field resets the visibility.\n if (this.value === '') {\n $('#capsLockWarning').hide();\n return;\n }\n\n // We need alphabetic characters to make a match.\n var character = String.fromCharCode(e.keyCode || e.which);\n if (character.toUpperCase() === character.toLowerCase()) {\n return;\n }\n\n // SHIFT doesn't usually give us a lowercase character. Check for this\n // and for when we get a lowercase character when SHIFT is enabled. \n if ((e.shiftKey && character.toLowerCase() === character) ||\n (!e.shiftKey && character.toUpperCase() === character)) {\n $('#capsLockWarning').show();\n } else {\n $('#capsLockWarning').hide();\n }\n});\n"
},
{
"answer_id": 4333349,
"author": "Naga Harish M",
"author_id": 486119,
"author_profile": "https://Stackoverflow.com/users/486119",
"pm_score": 0,
"selected": false,
"text": "$('#password').keypress(function(e) { \n // e.keyCode is not work in FF, SO, it will\n // automatically get the value of e.which. \n var s = String.fromCharCode( e.keyCode || e.which );\n if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {\n alert('caps is on');\n return false;\n }\nelse if ( s.toUpperCase() !== s) {\n alert('caps is on and Shiftkey pressed');\n return false;\n }\n});\n"
},
{
"answer_id": 8222652,
"author": "Zappa",
"author_id": 1040842,
"author_profile": "https://Stackoverflow.com/users/1040842",
"pm_score": 3,
"selected": false,
"text": "function capsCheck(e,obj){ \n kc = e.keyCode?e.keyCode:e.which; \n sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false); \n if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)){\n document.getElementById('#'+obj.id).style.visibility = 'visible';\n } \n else document.getElementById('#'+obj.id).style.visibility = 'hidden';\n}\n <input type=\"password\" name=\"txtPassword\" onkeypress=\"capsCheck(event,this);\" />\n<div id=\"capsWarningDiv\" style=\"visibility:hidden\">Caps Lock is on.</div> \n"
},
{
"answer_id": 13233539,
"author": "sourabh kasliwal",
"author_id": 1501138,
"author_profile": "https://Stackoverflow.com/users/1501138",
"pm_score": 0,
"selected": false,
"text": " <script language=\"Javascript\">\nfunction capLock(e){\n kc = e.keyCode?e.keyCode:e.which;\n sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);\n if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))\n document.getElementById('divMayus').style.visibility = 'visible';\n else\n document.getElementById('divMayus').style.visibility = 'hidden';\n}\n</script>\n <input type=\"password\" name=\"txtPassword\" onkeypress=\"capLock(event)\" />\n <div id=\"divMayus\" style=\"visibility:hidden\">Caps Lock is on.</div> \n"
},
{
"answer_id": 18905053,
"author": "joshuahedlund",
"author_id": 890308,
"author_profile": "https://Stackoverflow.com/users/890308",
"pm_score": 4,
"selected": false,
"text": "$(\"#password\").keypress(function(e) { \n var s = String.fromCharCode( e.which );\n if ((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey)|| //caps is on\n (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) {\n $(\"#CapsWarn\").show();\n } else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||\n (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { //caps is off\n $(\"#CapsWarn\").hide();\n } //else upper and lower are both same (i.e. not alpha key - so do not hide message if already on but do not turn on if alpha keys not hit yet)\n });\n"
},
{
"answer_id": 21150216,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "/* check for CAPS LOCK on all password fields */\n$(\"input[type='password']\").keypress(function(e) {\n\n var $warn = $(this).next(\".capsWarn\"); // handle the warning mssg\n var kc = e.which; //get keycode\n var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase\n var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase\n // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-\n var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed\n\n // uppercase w/out shift or lowercase with shift == caps lock\n if ( (isUp && !isShift) || (isLow && isShift) ) {\n $warn.show();\n } else {\n $warn.hide();\n }\n\n}).after(\"<span class='capsWarn error' style='display:none;'>Is your CAPSLOCK on?</span>\");\n document.onkeypress = function ( e ) {\n e = (e) ? e : window.event;\n\n var kc = ( e.keyCode ) ? e.keyCode : e.which; // get keycode\n var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase\n var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase\n var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed -- works for IE8-\n\n // uppercase w/out shift or lowercase with shift == caps lock\n if ( (isUp && !isShift) || (isLow && isShift) ) {\n alert(\"CAPSLOCK is on.\"); // do your thing here\n } else {\n // no CAPSLOCK to speak of\n }\n\n}\n"
},
{
"answer_id": 21289237,
"author": "formixian",
"author_id": 780036,
"author_profile": "https://Stackoverflow.com/users/780036",
"pm_score": 2,
"selected": false,
"text": "$('#password').keypress(function(e) { \n var s = String.fromCharCode( e.which );\n if ( (s.toUpperCase() === s && !e.shiftKey) || \n (s.toLowerCase() === s && e.shiftKey) ) {\n alert('caps is on');\n }\n});\n"
},
{
"answer_id": 21679062,
"author": "awe",
"author_id": 109392,
"author_profile": "https://Stackoverflow.com/users/109392",
"pm_score": 3,
"selected": false,
"text": "toUpperCase() toLowerCase() $(function(){\n //Initialize to hide caps-lock-warning\n $('.caps-lock-warning').hide();\n\n //Sniff for Caps-Lock state\n $(\"#password\").keypress(function(e) {\n var s = String.fromCharCode( e.which );\n if((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey)||\n (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) {\n this.caps = true; // Enables to do something on Caps-Lock keypress\n $(this).next('.caps-lock-warning').show();\n } else if((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||\n (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) {\n this.caps = false; // Enables to do something on Caps-Lock keypress\n $(this).next('.caps-lock-warning').hide();\n }//else else do nothing if not a letter we can use to differentiate\n });\n\n //Toggle warning message on Caps-Lock toggle (with some limitation)\n $(document).keydown(function(e){\n if(e.which==20){ // Caps-Lock keypress\n var pass = document.getElementById(\"password\");\n if(typeof(pass.caps) === 'boolean'){\n //State has been set to a known value by keypress\n pass.caps = !pass.caps;\n $(pass).next('.caps-lock-warning').toggle(pass.caps);\n }\n }\n });\n\n //Disable on window lost focus (because we loose track of state)\n $(window).blur(function(e){\n // If window is inactive, we have no control on the caps lock toggling\n // so better to re-set state\n var pass = document.getElementById(\"password\");\n if(typeof(pass.caps) === 'boolean'){\n pass.caps = null;\n $(pass).next('.caps-lock-warning').hide();\n }\n });\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<input type=\"password\" id=\"password\" />\n<span class=\"caps-lock-warning\" title=\"Caps lock is on!\">CAPS</span> caps"
},
{
"answer_id": 23981757,
"author": "Oday Fraiwan",
"author_id": 3540036,
"author_profile": "https://Stackoverflow.com/users/3540036",
"pm_score": 0,
"selected": false,
"text": "$('selectorOnTheInputTextBox').keypress(function (e) {\n var charCode = e.target.value.charCodeAt(e.target.value.length - 1)\n var capsOn = \n e.keyCode && \n !e.shiftKey &&\n !e.ctrlKey &&\n charCode >= 65 && \n charCode <= 90;\n\n if (capsOn) \n //action if true\n else\n //action if false\n});\n"
},
{
"answer_id": 24038811,
"author": "Aadit M Shah",
"author_id": 783743,
"author_profile": "https://Stackoverflow.com/users/783743",
"pm_score": 2,
"selected": false,
"text": "<script src=\"https://rawgit.com/aaditmshah/capsLock/master/capsLock.js\"></script>\n alert(capsLock.status);\n\ncapsLock.observe(function (status) {\n alert(status);\n});\n false"
},
{
"answer_id": 24782909,
"author": "enigment",
"author_id": 736006,
"author_profile": "https://Stackoverflow.com/users/736006",
"pm_score": 2,
"selected": false,
"text": "document.onkeypress = function (e)\n{\n e = e || window.event;\n if (e.charCode === 0 || e.ctrlKey || document.onkeypress.punctuation.indexOf(e.charCode) >= 0)\n return;\n var s = String.fromCharCode(e.charCode); // or e.keyCode for compatibility, but then have to handle MORE non-character keys\n var s2 = e.shiftKey ? s.toUpperCase() : s.toLowerCase();\n var capsLockOn = (s2 !== s);\n document.getElementById('capslockWarning').style.display = capsLockOn ? '' : 'none';\n}\ndocument.onkeypress.punctuation = [33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,91,92,93,94,95,96,123,124,125,126];\n"
},
{
"answer_id": 25719879,
"author": "ramiz4",
"author_id": 3466032,
"author_profile": "https://Stackoverflow.com/users/3466032",
"pm_score": 2,
"selected": false,
"text": "/* check for CAPS LOCK on all password fields */\n$(\"input[type='password']\").keypress(function(e) {\n var kc = e.which; // get keycode\n\n var isUpperCase = ((kc >= 65 && kc <= 90) || (kc >= 33 && kc <= 34) || (kc >= 36 && kc <= 39) || (kc >= 40 && kc <= 42) || kc == 47 || (kc >= 58 && kc <= 59) || kc == 61 || kc == 63 || kc == 167 || kc == 196 || kc == 214 || kc == 220) ? true : false; // uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '\"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';'\n var isLowerCase = ((kc >= 97 && kc <= 122) || (kc >= 48 && kc <= 57) || kc == 35 || (kc >= 43 && kc <= 44) || kc == 46 || kc == 228 || kc == 223 || kc == 246 || kc == 252) ? true : false; // lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ','\n\n // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-\n var isShift = (e.shiftKey) ? e.shiftKey : ((kc == 16) ? true : false); // shift is pressed\n\n // uppercase w/out shift or lowercase with shift == caps lock\n if ((isUpperCase && !isShift) || (isLowerCase && isShift)) {\n $(this).next('.form-control-feedback').show().parent().addClass('has-warning has-feedback').next(\".capsWarn\").show();\n } else {\n $(this).next('.form-control-feedback').hide().parent().removeClass('has-warning has-feedback').next(\".capsWarn\").hide();\n }\n}).after('<span class=\"glyphicon glyphicon-warning-sign form-control-feedback\" style=\"display:none;\"></span>').parent().after(\"<span class='capsWarn text-danger' style='display:none;'>Is your CAPSLOCK on?</span>\");\n"
},
{
"answer_id": 28543159,
"author": "Cedric Simon",
"author_id": 2838910,
"author_profile": "https://Stackoverflow.com/users/2838910",
"pm_score": 1,
"selected": false,
"text": "<html>\n<head>\n<script language=\"javascript\" type=\"text/javascript\" >\nfunction checkCapsLock(e, divId) { \n if(e){\n e = e;\n } else {\n e = window.event;\n }\n var s = String.fromCharCode( e.which );\n if ((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey)|| //caps is on\n (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) {\n $(divId).style.display='block';\n } else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||\n (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { //caps is off\n $(divId).style.display='none';\n } //else upper and lower are both same (i.e. not alpha key - so do not hide message if already on but do not turn on if alpha keys not hit yet)\n }\n</script>\n<style> \n.errorDiv {\n display: none;\n font-size: 12px;\n color: red;\n word-wrap: break-word;\n text-overflow: clip;\n max-width: 200px;\n font-weight: normal;\n}\n</style>\n</head>\n<body onkeypress=\"checkCapsLock(event, 'CapsWarn');\" >\n...\n<input name=\"password\" id=\"password\" type=\"password\" autocomplete=\"off\">\n<div id=\"CapsWarn\" class=\"errorDiv\">Capslock is ON !</div>\n...\n</body>\n</html>\n"
},
{
"answer_id": 34277417,
"author": "Mottie",
"author_id": 145346,
"author_profile": "https://Stackoverflow.com/users/145346",
"pm_score": 7,
"selected": false,
"text": "KeyboardEvent getModifierState passwordField.addEventListener( 'keydown', function( event ) {\n var caps = event.getModifierState && event.getModifierState( 'CapsLock' );\n console.log( caps ); // true when you press the keyboard CapsLock key\n});\n"
},
{
"answer_id": 34687411,
"author": "Ben Gripka",
"author_id": 530658,
"author_profile": "https://Stackoverflow.com/users/530658",
"pm_score": 0,
"selected": false,
"text": "(function ($) {\n $.fn.capsLockAlert = function () {\n return this.each(function () {\n var capsLockOn = false;\n var t = $(this);\n var updateStatus = function () {\n if (capsLockOn) {\n t.tooltip('open');\n } else {\n t.tooltip('close');\n }\n }\n t.tooltip({\n items: \"input\",\n position: { my: \"left top\", at: \"left bottom+10\" },\n open: function (event, ui) {\n ui.tooltip.css({ \"min-width\": \"100px\", \"white-space\": \"nowrap\" }).addClass('ui-state-error');\n if (!capsLockOn) t.tooltip('close');\n },\n content: function () {\n return $('<p style=\"white-space: nowrap;\"/>')\n .append($('<span class=\"ui-icon ui-icon-alert\" style=\"display: inline-block; margin-right: 5px; vertical-align: text-top;\" />'))\n .append('Caps Lock On');\n }\n })\n .off(\"mouseover mouseout\")\n .keydown(function (e) {\n if (e.keyCode !== 20) return;\n capsLockOn = !capsLockOn;\n updateStatus();\n })\n .keypress(function (e) {\n var kc = e.which; //get keycode\n\n var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase\n var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase\n if (!isUp && !isLow) return; //This isn't a character effected by caps lock\n\n // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-\n var isShift = (e.shiftKey) ? e.shiftKey : ((kc === 16) ? true : false); // shift is pressed\n\n // uppercase w/out shift or lowercase with shift == caps lock\n if ((isUp && !isShift) || (isLow && isShift)) {\n capsLockOn = true;\n } else {\n capsLockOn = false;\n }\n updateStatus();\n });\n });\n };\n})(jQuery);\n $(function () {\n $(\":password\").capsLockAlert();\n});\n"
},
{
"answer_id": 37981116,
"author": "ron tornambe",
"author_id": 731453,
"author_profile": "https://Stackoverflow.com/users/731453",
"pm_score": -1,
"selected": false,
"text": "function isCapsLockOn(event) {\n var s = String.fromCharCode(event.which);\n if (s.toUpperCase() === s && s.toLowerCase() !== s && !event.shiftKey) {\n return true;\n }\n}\n"
},
{
"answer_id": 38611590,
"author": "M Arfan",
"author_id": 1109197,
"author_profile": "https://Stackoverflow.com/users/1109197",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\n function isCapLockOn(e){\n kc = e.keyCode?e.keyCode:e.which;\n sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);\n if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))\n document.getElementById('alert').style.visibility = 'visible';\n else\n document.getElementById('alert').style.visibility = 'hidden';\n }\n</script>\n <input type=\"password\" name=\"txtPassword\" onkeypress=\"isCapLockOn(event)\" />\n<div id=\"alert\" style=\"visibility:hidden\">Caps Lock is on.</div> \n"
},
{
"answer_id": 45189632,
"author": "Alice Rocheman",
"author_id": 3422031,
"author_profile": "https://Stackoverflow.com/users/3422031",
"pm_score": 2,
"selected": false,
"text": "let isCapsLockOn = false;\n\ndocument.addEventListener( 'keydown', function( event ) {\n var caps = event.getModifierState && event.getModifierState( 'CapsLock' );\n if(isCapsLockOn !== caps) isCapsLockOn = caps;\n});\n\ndocument.addEventListener( 'keyup', function( event ) {\n var caps = event.getModifierState && event.getModifierState( 'CapsLock' );\n if(isCapsLockOn !== caps) isCapsLockOn = caps;\n});\n"
},
{
"answer_id": 46008107,
"author": "José Araújo",
"author_id": 3845227,
"author_profile": "https://Stackoverflow.com/users/3845227",
"pm_score": 2,
"selected": false,
"text": "onKeyPress(event) { \n let self = this;\n self.setState({\n capsLock: isCapsLockOn(self, event)\n });\n }\n\n onKeyUp(event) { \n let self = this;\n let key = event.key;\n if( key === 'Shift') {\n self.shift = false;\n }\n }\n <div>\n <input name={this.props.name} onKeyDown={(e)=>this.onKeyPress(e)} onKeyUp={(e)=>this.onKeyUp(e)} onChange={this.props.onChange}/>\n {this.capsLockAlert()}\n</div>\n function isCapsLockOn(component, event) {\n let key = event.key;\n let keyCode = event.keyCode;\n\n component.lastKeyPressed = key;\n\n if( key === 'Shift') {\n component.shift = true;\n } \n\n if (key === 'CapsLock') {\n let newCapsLockState = !component.state.capsLock;\n component.caps = newCapsLockState;\n return newCapsLockState;\n } else {\n if ((component.lastKeyPressed !== 'Shift' && (key === key.toUpperCase() && (keyCode >= 65 && keyCode <= 90)) && !component.shift) || component.caps ) {\n component.caps = true;\n return true;\n } else {\n component.caps = false;\n return false;\n }\n }\n }\n"
},
{
"answer_id": 49411927,
"author": "Chris",
"author_id": 4934902,
"author_profile": "https://Stackoverflow.com/users/4934902",
"pm_score": 1,
"selected": false,
"text": "var capsLockIsOnKeyDown = {shiftWasDownDuringLastChar: false,\n capsLockIsOnKeyDown: function(event) {\n var eventWasShiftKeyDown = event.which === 16;\n var capsLockIsOn = false;\n var shifton = false;\n if (event.shiftKey) {\n shifton = event.shiftKey;\n } else if (event.modifiers) {\n shifton = !!(event.modifiers & 4);\n }\n\n if (event.target.value.length > 0 && !eventWasShiftKeyDown) {\n var lastChar = event.target.value[event.target.value.length-1];\n var isAlpha = /^[a-zA-Z]/.test(lastChar);\n\n if (isAlpha) {\n if (lastChar.toUpperCase() === lastChar && lastChar.toLowerCase() !== lastChar\n && !event.shiftKey && !capsLockIsOnKeyDown.shiftWasDownDuringLastChar) {\n capsLockIsOn = true;\n }\n }\n }\n capsLockIsOnKeyDown.shiftWasDownDuringLastChar = shifton;\n return capsLockIsOn;\n }\n}\n capsLockIsOnKeyDown.capsLockIsOnKeyDown(event)"
},
{
"answer_id": 51384804,
"author": "SebasSBM",
"author_id": 3692177,
"author_profile": "https://Stackoverflow.com/users/3692177",
"pm_score": 2,
"selected": false,
"text": "$('#example').keypress(function(e) { \n var s = String.fromCharCode( e.which );\n if (( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey )\n || ( s.toLowerCase() === s && s.toUpperCase() !== s && e.shiftKey )) {\n alert('caps is on');\n }\n});\n"
},
{
"answer_id": 51554059,
"author": "nadir",
"author_id": 3248989,
"author_profile": "https://Stackoverflow.com/users/3248989",
"pm_score": 0,
"selected": false,
"text": "function (s,e)\n{\n var key = e.htmlEvent.key;\n\n var upperCases = 'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZXWQ';\n var lowerCases = 'abcçdefgğhıijklmnoöprsştuüvyzxwq';\n var digits = '0123456789';\n\n if (upperCases.includes(key))\n {\n document.getElementById('spanLetterCase').innerText = '[A]';\n }\n\n else if (lowerCases.includes(key))\n {\n document.getElementById('spanLetterCase').innerText = '[a]';\n }\n\n else if (digits.includes(key))\n {\n document.getElementById('spanLetterCase').innerText = '[1]';\n }\n\n else\n {\n document.getElementById('spanLetterCase').innerText = '';\n }\n}\n"
},
{
"answer_id": 52418434,
"author": "Ryan Marin",
"author_id": 10063563,
"author_profile": "https://Stackoverflow.com/users/10063563",
"pm_score": 3,
"selected": false,
"text": "getModifierState onfocus onclick onkeyup <input type=\"password\" id=\"password\" onclick=\"checkCapsLock(event)\" onkeyup=\"checkCapsLock(event)\" />\n function checkCapsLock(e) {\n if (e.getModifierState(\"CapsLock\")) {\n console.log(\"Caps\");\n }\n}\n"
},
{
"answer_id": 52765144,
"author": "Mike Sraj",
"author_id": 9576898,
"author_profile": "https://Stackoverflow.com/users/9576898",
"pm_score": 0,
"selected": false,
"text": "let capsIsOn=false;\nlet capsChecked=false;\n\nlet capsCheck=(e)=>{\n let letter=e.key;\n if(letter.length===1 && letter.match(/[A-Za-z]/)){\n if(letter!==letter.toLowerCase()){\n capsIsOn=true;\n console.log('caps is on');\n }else{\n console.log('caps is off');\n }\n capsChecked=true;\n window.removeEventListener(\"keyup\",capsCheck);\n }else{\n console.log(\"not a letter, not capsCheck was performed\");\n }\n\n}\n\nwindow.addEventListener(\"keyup\",capsCheck);\n\nwindow.addEventListener(\"keyup\",(e)=>{\n if(capsChecked && e.keyCode===20){\n capsIsOn=!capsIsOn;\n }\n});"
},
{
"answer_id": 70013486,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 1,
"selected": false,
"text": "function checkIfCapsLockIsOn(event) {\n var capsLockIsOn = event.getModifierState(\"CapsLock\");\n console.log(\"Caps Lock activated: \" + capsLockIsOn);\n}\n <input type=\"text\" onkeydown=\"checkIfCapsLockIsOn(event)\">\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
348,807 | <p>I have defined a new dialog and its controls in an already existing resource file. I have also created a new file which will handle the events being generated from this dialog. But I am not sure how to connect these two. </p>
<p>Is the statement <code>enum { IDD=IDD_NEW_DIALOG };</code> all that is required to connect the two? Or should we add some other statement?</p>
| [
{
"answer_id": 348810,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 1,
"selected": false,
"text": "DoModal() Create"
},
{
"answer_id": 349093,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": 5,
"selected": true,
"text": "CMyDlg::CMyDlg(CWnd* pParent /*=NULL*/) : CDialog(CMyDlg::IDD, pParent)\n CMyDlg::CMyDlg(CWnd* pParent /*=NULL*/) : CDialog(IDD_NEW_DIALOG, pParent)\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41518/"
] |
348,821 | <p>This question is coded in pseudo-PHP, but I really don't mind what language I get answers in (except for Ruby :-P), as this is purely hypothetical. In fact, PHP is quite possibly the worst language to be doing this type of logic in. Unfortunately, I have never done this before, so I can't provide a real-world example. Therefore, hypothetical answers are completely acceptable.</p>
<p>Basically, I have lots of objects performing a task. For this example, let's say each object is a class that downloads a file from the Internet. Each object will be downloading a different file, and the downloads are run in parallel. Obviously, some objects may finish downloading before others. The actual grabbing of data may run in threads, but that is not relevant to this question.</p>
<p>So we can define the object as such:</p>
<pre><code>class DownloaderObject() {
var $url = '';
var $downloading = false;
function DownloaderObject($v){ // constructor
$this->url = $v;
start_downloading_in_the_background(url=$this->$url, callback=$this->finished);
$this->downloading = true;
}
function finished() {
save_the_data_somewhere();
$this->downloading = false;
$this->destroy(); // actually destroys the object
}
}
</code></pre>
<p>Okay, so we have lots of these objects running:</p>
<pre><code>$download1 = new DownloaderObject('http://somesite.com/latest_windows.iso');
$download2 = new DownloaderObject('http://somesite.com/kitchen_sink.iso');
$download3 = new DownloaderObject('http://somesite.com/heroes_part_1.rar');
</code></pre>
<p>And we can store them in an array:</p>
<pre><code>$downloads = array($download1, $download2, $download3);
</code></pre>
<p>So we have an array full of the downloads:</p>
<pre><code>array(
1 => $download1,
2 => $download2,
3 => $download3
)
</code></pre>
<p>And we can iterate through them like this:</p>
<pre><code>print('Here are the downloads that are running:');
foreach ($downloads as $d) {
print($d->url . "\n");
}
</code></pre>
<p>Okay, now suppose download 2 finishes, and the object is destroyed. Now we should have two objects in the array:</p>
<pre><code>array(
1 => $download1,
3 => $download3
)
</code></pre>
<p>But there is a hole in the array! Key #2 is being unused. Also, if I wanted to start a new download, it is unclear where to insert the download into the array. The following could work:</p>
<pre><code>$i = 0;
while ($i < count($downloads) - 1) {
if (!is_object($downloads[$i])) {
$downloads[$i] = new DownloaderObject('http://somesite.com/doctorwho.iso');
break;
}
$i++;
}
</code></pre>
<p>However, that is terribly inefficient (and <code>while $i++</code> loops are nooby). So, another approach is to keep a counter.</p>
<pre><code>function add_download($url) {
global $downloads;
static $download_counter;
$download_counter++;
$downloads[$download_counter] = new DownloaderObject($url);
}
</code></pre>
<p>That would work, but we still get holes in the array:</p>
<pre><code>array(
1 => DownloaderObject,
3 => DownloaderObject,
7 => DownloaderObject,
13 => DownloaderObject
)
</code></pre>
<p>That's ugly. However, is that acceptable? Should the array be "defragmented", i.e. the keys rearranged to eliminate blank spaces?</p>
<p>Or is there another programmatic structure I should be aware of? I want a structure that I can add stuff to, remove stuff from, refer to keys in a variable, iterate through, etc., that is not an array. Does such a thing exist?</p>
<p>I have been coding for years, but this question has bugged me for very many of those years, and I am still not aware of an answer. This may be obvious to some programmers, but is extremely non-trivial to me.</p>
| [
{
"answer_id": 348830,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 1,
"selected": false,
"text": "$i = 0;\nwhile ($i < count($downloads) - 1) {\n if (!is_object($downloads[$i])) {\n $downloads[$i] = new DownloaderObject('http://somesite.com/doctorwho.iso');\n break;\n }\n $i++;\n}\n for($i=0;$i<count($downloads)-1;++$i){\n if (!is_object($downloads[$i])) {\n $downloads[$i] = new DownloaderObject('http://somesite.com/doctorwho.iso');\n break;\n }\n}\n"
},
{
"answer_id": 352643,
"author": "Jeremy Visser",
"author_id": 10839,
"author_profile": "https://Stackoverflow.com/users/10839",
"pm_score": 1,
"selected": true,
"text": "pop() array_pop() >>> x = ['baa', 'ram', 'ewe'] # our starting point\n>>> x[1] # making sure element 1 is 'ram'\n'ram'\n>>> x.pop(1) # let's arbitrarily pop an element in the middle\n'ram'\n>>> x # the one we popped ('ram') is now gone\n['baa', 'ewe']\n>>> x[1] # and there are no holes: item 2 has become item 1\n'ewe'\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10839/"
] |
348,833 | <p>If I generate an exception on my own, I can include any info into the exception: a number of code line and name of source file. Something like this:</p>
<pre><code>throw std::exception("myFile.cpp:255");
</code></pre>
<p>But what's with unhandled exceptions or with exceptions that were not generated by me?</p>
| [
{
"answer_id": 348843,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "#define throw_line(msg) \\\n throw std::exception(msg \" \" __FILE__ \":\" __LINE__)\n\nvoid f() {\n throw_line(\"Oh no!\");\n}\n"
},
{
"answer_id": 348862,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": false,
"text": "#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n\nclass my_exception : public std::runtime_error {\n std::string msg;\npublic:\n my_exception(const std::string &arg, const char *file, int line) :\n std::runtime_error(arg) {\n std::ostringstream o;\n o << file << \":\" << line << \": \" << arg;\n msg = o.str();\n }\n ~my_exception() throw() {}\n const char *what() const throw() {\n return msg.c_str();\n }\n};\n#define throw_line(arg) throw my_exception(arg, __FILE__, __LINE__);\n\nvoid f() {\n throw_line(\"Oh no!\");\n}\n\nint main() {\n try {\n f();\n }\n catch (const std::runtime_error &ex) {\n std::cout << ex.what() << std::endl;\n }\n}\n"
},
{
"answer_id": 348930,
"author": "vividos",
"author_id": 23740,
"author_profile": "https://Stackoverflow.com/users/23740",
"pm_score": 5,
"selected": false,
"text": "__FILE__ __LINE__ throw std::runtime_error(msg \" at \" `__FILE__` \":\" `__LINE__`);\n class my_custom_exception {\n my_custom_exception(const char* msg, const char* file, unsigned int line)\n...\n"
},
{
"answer_id": 1184703,
"author": "Daniel Pinyol",
"author_id": 145289,
"author_profile": "https://Stackoverflow.com/users/145289",
"pm_score": 1,
"selected": false,
"text": "std::set_terminate std::set_unexpected throw(MyControlledException) unexpected_handler"
},
{
"answer_id": 52285844,
"author": "aquirdturtle",
"author_id": 1971306,
"author_profile": "https://Stackoverflow.com/users/1971306",
"pm_score": 2,
"selected": false,
"text": "#include \"Thrower.h\"\n#include <iostream>\n// runs the sample function above and prints the caught exception\nint main ( )\n{\n try {\n // [Doing important stuff...]\n try {\n std::string s = \"Hello, world!\";\n try {\n int i = std::stoi ( s );\n }\n catch ( ... ) {\n thrower ( \"Failed to convert string \\\"\" + s + \"\\\" to an integer!\" );\n }\n }\n catch ( Error& e ) {\n thrower ( \"Failed to [Do important stuff]!\" );\n }\n }\n catch ( Error& e ) {\n std::cout << Error::getErrorStack ( e );\n }\n std::cin.get ( );\n}\n ERROR: Failed to [Do important stuff]!\n@ Location:c:\\path\\main.cpp; line 33\n ERROR: Failed to convert string \"Hello, world!\" to an integer!\n @ Location:c:\\path\\main.cpp; line 28\n ERROR: invalid stoi argument\n #include <sstream>\n#include <stdexcept>\n#include <regex>\n\nclass Error : public std::runtime_error\n{\n public:\n Error ( const std::string &arg, const char *file, int line ) : std::runtime_error( arg )\n {\n loc = std::string ( file ) + \"; line \" + std::to_string ( line );\n std::ostringstream out;\n out << arg << \"\\n@ Location:\" << loc;\n msg = out.str( );\n bareMsg = arg; \n }\n ~Error( ) throw() {}\n\n const char * what( ) const throw()\n {\n return msg.c_str( );\n }\n std::string whatBare( ) const throw()\n {\n return bareMsg;\n }\n std::string whatLoc ( ) const throw( )\n {\n return loc;\n }\n static std::string getErrorStack ( const std::exception& e, unsigned int level = 0)\n {\n std::string msg = \"ERROR: \" + std::string(e.what ( ));\n std::regex r ( \"\\n\" );\n msg = std::regex_replace ( msg, r, \"\\n\"+std::string ( level, ' ' ) );\n std::string stackMsg = std::string ( level, ' ' ) + msg + \"\\n\";\n try\n {\n std::rethrow_if_nested ( e );\n }\n catch ( const std::exception& e )\n {\n stackMsg += getErrorStack ( e, level + 1 );\n }\n return stackMsg;\n }\n private:\n std::string msg;\n std::string bareMsg;\n std::string loc;\n};\n\n// (Important modification here)\n// the following gives any throw call file and line information.\n// throw_with_nested makes it possible to chain thrower calls and get a full error stack traceback\n#define thrower(arg) std::throw_with_nested( Error(arg, __FILE__, __LINE__) )\n"
},
{
"answer_id": 58913556,
"author": "Dominic",
"author_id": 971953,
"author_profile": "https://Stackoverflow.com/users/971953",
"pm_score": 2,
"selected": false,
"text": "#include <boost/exception/diagnostic_information.hpp>\n#include <exception>\n#include <iostream>\n\nstruct MyException : std::exception {};\n\nint main()\n{\n try\n {\n BOOST_THROW_EXCEPTION(MyException());\n }\n catch (MyException &ex)\n {\n std::cerr << \"Unexpected exception, diagnostic information follows:\\n\"\n << boost::current_exception_diagnostic_information();\n }\n return 0;\n}\n Unexpected exception, diagnostic information follows:\nmain.cpp(10): Throw in function int main()\nDynamic exception type: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<MyException> >\nstd::exception::what: std::exception\n"
},
{
"answer_id": 61992467,
"author": "Spixmaster",
"author_id": 10821497,
"author_profile": "https://Stackoverflow.com/users/10821497",
"pm_score": 1,
"selected": false,
"text": "valgrind --leak-check=full /path/to/your/software"
},
{
"answer_id": 65043535,
"author": "mrts",
"author_id": 258772,
"author_profile": "https://Stackoverflow.com/users/258772",
"pm_score": 1,
"selected": false,
"text": "#define THROW(ExceptionType, message) \\\n throw ExceptionType(std::string(message) + \" in \" + __FILE__ + ':' \\\n + std::to_string(__LINE__) + ':' + __func__)\n\nTHROW(Error, \"An error occurred\");\n std::to_string()"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44217/"
] |
348,849 | <p>I am writing a batch file, in which I call an EXE to execute. Now, statements after the call to the EXE should not execute till the EXE completes its execution. How can I do it in the batch file (on Windows)?</p>
| [
{
"answer_id": 348851,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 0,
"selected": false,
"text": "PAUSE\n"
},
{
"answer_id": 348857,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": false,
"text": "first.exe\nnext.exe\n"
},
{
"answer_id": 348861,
"author": "kdmurray",
"author_id": 28491,
"author_profile": "https://Stackoverflow.com/users/28491",
"pm_score": 3,
"selected": false,
"text": "PING 127.0.0.1 -n 1 -w 120000 >NUL\n"
},
{
"answer_id": 349610,
"author": "aphoria",
"author_id": 2441,
"author_profile": "https://Stackoverflow.com/users/2441",
"pm_score": 4,
"selected": false,
"text": "START /WAIT First.exe\nSTART /WAIT Second.exe\n"
},
{
"answer_id": 4326298,
"author": "Raghu",
"author_id": 526812,
"author_profile": "https://Stackoverflow.com/users/526812",
"pm_score": 2,
"selected": false,
"text": "TIMEOUT /T 10"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,853 | <p>Inspired by <a href="https://stackoverflow.com/questions/40845/how-do-f-units-of-measurement-work">Units of Measure in F#</a>, and despite asserting (<a href="https://stackoverflow.com/questions/39492/where-can-f-actually-save-time-and-money#71112">here</a>) that you couldn't do it in C#, I had an idea the other day which I've been playing around with.</p>
<pre><code>namespace UnitsOfMeasure
{
public interface IUnit { }
public static class Length
{
public interface ILength : IUnit { }
public class m : ILength { }
public class mm : ILength { }
public class ft : ILength { }
}
public class Mass
{
public interface IMass : IUnit { }
public class kg : IMass { }
public class g : IMass { }
public class lb : IMass { }
}
public class UnitDouble<T> where T : IUnit
{
public readonly double Value;
public UnitDouble(double value)
{
Value = value;
}
public static UnitDouble<T> operator +(UnitDouble<T> first, UnitDouble<T> second)
{
return new UnitDouble<T>(first.Value + second.Value);
}
//TODO: minus operator/equality
}
}
</code></pre>
<p>Example usage:</p>
<pre><code>var a = new UnitDouble<Length.m>(3.1);
var b = new UnitDouble<Length.m>(4.9);
var d = new UnitDouble<Mass.kg>(3.4);
Console.WriteLine((a + b).Value);
//Console.WriteLine((a + c).Value); <-- Compiler says no
</code></pre>
<p>The next step is trying to implement conversions (snippet):</p>
<pre><code>public interface IUnit { double toBase { get; } }
public static class Length
{
public interface ILength : IUnit { }
public class m : ILength { public double toBase { get { return 1.0;} } }
public class mm : ILength { public double toBase { get { return 1000.0; } } }
public class ft : ILength { public double toBase { get { return 0.3048; } } }
public static UnitDouble<R> Convert<T, R>(UnitDouble<T> input) where T : ILength, new() where R : ILength, new()
{
double mult = (new T() as IUnit).toBase;
double div = (new R() as IUnit).toBase;
return new UnitDouble<R>(input.Value * mult / div);
}
}
</code></pre>
<p>(I would have liked to avoid instantiating objects by using static, but as we all know you <a href="https://stackoverflow.com/questions/259026/why-doesnt-c-allow-static-methods-to-implement-an-interface">can't declare a static method in an interface</a>)
You can then do this:</p>
<pre><code>var e = Length.Convert<Length.mm, Length.m>(c);
var f = Length.Convert<Length.mm, Mass.kg>(d); <-- but not this
</code></pre>
<p>Obviously, there is a gaping hole in this, compared to F# Units of measure (I'll let you work it out).</p>
<p>Oh, the question is: what do you think of this? Is it worth using? Has someone else already done better?</p>
<p><strong>UPDATE</strong> for people interested in this subject area, <a href="http://www.cs.utexas.edu/users/novak/units95.pdf" rel="noreferrer">here</a> is a link to a paper from 1997 discussing a different kind of solution (not specifically for C#)</p>
| [
{
"answer_id": 348868,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "Length length = Length.FromMillimeters(n1);\ndecimal lengthInFeet = length.Feet;\nLength length2 = length.AddFeet(n2);\nLength length3 = length + Length.FromMeters(n3);\n"
},
{
"answer_id": 348891,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 5,
"selected": false,
"text": "let g = 9.8<m/s^2>\n class Unit\n{\n double scalar;\n int kg;\n int m;\n int s;\n // ... for each basic unit\n\n public Unit(double scalar, int kg, int m, int s)\n {\n this.scalar = scalar;\n this.kg = kg;\n this.m = m;\n this.s = s;\n ...\n }\n\n // For addition/subtraction, exponents must match\n public static Unit operator +(Unit first, Unit second)\n {\n if (UnitsAreCompatible(first, second))\n {\n return new Unit(\n first.scalar + second.scalar,\n first.kg,\n first.m,\n first.s,\n ...\n );\n }\n else\n {\n throw new Exception(\"Units must match for addition\");\n }\n }\n\n // For multiplication/division, add/subtract the exponents\n public static Unit operator *(Unit first, Unit second)\n {\n return new Unit(\n first.scalar * second.scalar,\n first.kg + second.kg,\n first.m + second.m,\n first.s + second.s,\n ...\n );\n }\n\n public static bool UnitsAreCompatible(Unit first, Unit second)\n {\n return\n first.kg == second.kg &&\n first.m == second.m &&\n first.s == second.s\n ...;\n }\n}\n class Speed : Unit\n{\n public Speed(double x) : base(x, 0, 1, -1, ...); // m/s => m^1 * s^-1\n {\n }\n}\n\nclass Acceleration : Unit\n{\n public Acceleration(double x) : base(x, 0, 1, -2, ...); // m/s^2 => m^1 * s^-2\n {\n }\n}\n"
},
{
"answer_id": 2949803,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 4,
"selected": false,
"text": "var mass = 1.Kilogram();\nvar length = (1.2).Kilometres();\n"
},
{
"answer_id": 4198506,
"author": "John Alexiou",
"author_id": 380384,
"author_profile": "https://Stackoverflow.com/users/380384",
"pm_score": 2,
"selected": false,
"text": "Unit lbf = 4.44822162*N;\nUnit fps = feet/sec;\nUnit hp = 550*lbf*fps\n (m/s)*(m*s)=m^2 <DefinedUnits>\n <DirectUnits>\n<!-- Base Units -->\n<DirectUnit Symbol=\"kg\" Scale=\"1\" Dims=\"(1,0,0,0,0)\" />\n<DirectUnit Symbol=\"m\" Scale=\"1\" Dims=\"(0,1,0,0,0)\" />\n<DirectUnit Symbol=\"s\" Scale=\"1\" Dims=\"(0,0,1,0,0)\" />\n...\n<!-- Derived Units -->\n<DirectUnit Symbol=\"N\" Scale=\"1\" Dims=\"(1,1,-2,0,0)\" />\n<DirectUnit Symbol=\"R\" Scale=\"1.8\" Dims=\"(0,0,0,0,1)\" />\n...\n </DirectUnits>\n <IndirectUnits>\n<!-- Composite Units -->\n<IndirectUnit Symbol=\"m/s\" Scale=\"1\" Lhs=\"m\" Op=\"Divide\" Rhs=\"s\"/>\n<IndirectUnit Symbol=\"km/h\" Scale=\"1\" Lhs=\"km\" Op=\"Divide\" Rhs=\"hr\"/>\n...\n<IndirectUnit Symbol=\"hp\" Scale=\"550.0\" Lhs=\"lbf\" Op=\"Multiply\" Rhs=\"fps\"/>\n </IndirectUnits>\n</DefinedUnits>\n"
},
{
"answer_id": 7564096,
"author": "Mafu Josh",
"author_id": 119418,
"author_profile": "https://Stackoverflow.com/users/119418",
"pm_score": 0,
"selected": false,
"text": "Dim myLength1 as New Length(of Miles, Int16)(123)\n Dim myLength2 = 123.miles\n Dim myLength3 = myLength1 + myLength2\nDim myArea1 = myLength1 * myLength2\n Dim myValue = 123.miles + 234.kilograms\n"
},
{
"answer_id": 17777775,
"author": "angularsen",
"author_id": 134761,
"author_profile": "https://Stackoverflow.com/users/134761",
"pm_score": 4,
"selected": false,
"text": "Length meter = Length.FromMeters(1);\ndouble cm = meter.Centimeters; // 100\ndouble yards = meter.Yards; // 1.09361\ndouble feet = meter.Feet; // 3.28084\ndouble inches = meter.Inches; // 39.3701\n"
},
{
"answer_id": 67511063,
"author": "Stelios Adamantidis",
"author_id": 1303323,
"author_profile": "https://Stackoverflow.com/users/1303323",
"pm_score": 1,
"selected": false,
"text": "[<Measure>] / ^ struct class Newton [<Measure>] type N = kg m/sec^2 square N^2 R 8.31446261815324 J /(K mol) UnitDouble<T> IUnit new T() Activator.CreateInstance<T>() Convert<T, R>() var c = new Unit<Length.mm>(123);\nvar e = c.Convert<Length.m>();\n var e = Length.Convert<Length.mm, Length.m>(c);\n Speed<TLength, TTime> Unit<T1, T2> Unit<T1, T2, T3> public readonly struct Length<T> where T : struct, ILength\n{\n private static readonly double SiFactor = new T().ToSiFactor;\n public Length(double value)\n {\n if (value < 0) throw new ArgumentException(nameof(value));\n Value = value;\n }\n\n public double Value { get; }\n\n public static Length<T> operator +(Length<T> first, Length<T> second)\n {\n return new Length<T>(first.Value + second.Value);\n }\n\n public static Length<T> operator -(Length<T> first, Length<T> second)\n {\n // I don't know any application where negative length makes sense,\n // if it does feel free to remove Abs() and the exception in the constructor\n return new Length<T>(System.Math.Abs(first.Value - second.Value));\n }\n \n // You can add more like\n // public static Area<T> operator *(Length<T> x, Length<T> y)\n // or\n //public static Volume<T> operator *(Length<T> x, Length<T> y, Length<T> z)\n // etc\n\n public Length<R> To<R>() where R : struct, ILength\n {\n //notice how I got rid of the Activator invocations by moving them in a static field;\n //double mult = new T().ToSiFactor;\n //double div = new R().ToSiFactor;\n return new Length<R>(Value * SiFactor / Length<R>.SiFactor);\n }\n}\n new T().ToSiFactor Length<mm> Length<Km> ToSiFactor toBase var accel = new Acceleration<m, s, s>(1.2);\n let accel = 1.2<m/sec^2>\n LengthUnit UnitBase struct LengthUnit l1 = new Meters(12);\nLengthUnit l2 = new Feet(15.4);\nLengthUnit sum = l1 + l2;\n sum sum.To<Kilometers>()"
},
{
"answer_id": 67587454,
"author": "realbart",
"author_id": 1677285,
"author_profile": "https://Stackoverflow.com/users/1677285",
"pm_score": 1,
"selected": false,
"text": " public struct TypedInt<T>\n {\n public int Value { get; }\n\n public TypedInt(int value) => Value = value;\n\n public static TypedInt<T> operator -(TypedInt<T> a, TypedInt<T> b) => new TypedInt<T>(a.Value - b.Value);\n public static TypedInt<T> operator +(TypedInt<T> a, TypedInt<T> b) => new TypedInt<T>(a.Value + b.Value);\n public static TypedInt<T> operator *(int a, TypedInt<T> b) => new TypedInt<T>(a * b.Value);\n public static TypedInt<T> operator *(TypedInt<T> a, int b) => new TypedInt<T>(a.Value * b);\n public static TypedInt<T> operator /(TypedInt<T> a, int b) => new TypedInt<T>(a.Value / b);\n\n // todo: m² or m/s\n // todo: more than just ints\n // todo: other operations\n public override string ToString() => $\"{Value} {typeof(T).Name}\";\n }\n public static class TypedInt\n {\n public static TypedInt<T> Of<T>(this int value) => new TypedInt<T>(value);\n }\n public class Mile\n {\n // todo: conversion from mile to/from meter\n // maybe define an interface like ITypedConvertible<Meter>\n // conversion probably needs reflection, but there may be\n // a faster way\n };\n\n public class Second\n {\n }\n var distance1 = 10.Of<Mile>();\n var distance2 = 15.Of<Mile>();\n var timespan1 = 4.Of<Second>();\n\n Console.WriteLine(distance1 + distance2);\n //Console.WriteLine(distance1 + 5); // this will be blocked by the compiler\n //Console.WriteLine(distance1 + timespan1); // this will be blocked by the compiler\n Console.WriteLine(3 * distance1);\n Console.WriteLine(distance1 / 3);\n //Console.WriteLine(distance1 / timespan1); // todo!\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
348,864 | <p>F
Is there a way to monitor the FTP port so that I can know what commands my FTP application is sending to a FTP server?</p>
<p>I am using a closed-source FTP client application, which is not working with a closed-source FTP application server. The client and the server are not communicating well with each other, and I would like to find out why. I wish to reverse-engineer the client to see what commends the client are sending to the sever. I used a web test tool before that allowed me to monitor the content transferring through HTTP, but I can't seem to find such tool for FTP. I appreciate it if you can help me out, thanks. </p>
| [
{
"answer_id": 1012046,
"author": "cjs",
"author_id": 107294,
"author_profile": "https://Stackoverflow.com/users/107294",
"pm_score": 0,
"selected": false,
"text": "ktrace strace"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23637/"
] |
348,867 | <p>can anyone think of a better way to do this?</p>
<pre><code> [AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveAction()
{
NameValueDeserializer value = new NameValueDeserializer();
// selected messages
MemberMessageSaveAction[] messages = (MemberMessageSaveAction[])value.Deserialize(Request.Form, "value", typeof(MemberMessageSaveAction[]));
// selected action
MemberMessageAction action = (MemberMessageAction)Enum.Parse(typeof(MemberMessageAction), Request.Form["action"]);
// determine action
if (action != MemberMessageAction.MarkRead &&
action != MemberMessageAction.MarkUnRead &&
action != MemberMessageAction.Delete)
{
// selected action requires special processing
IList<MemberMessage> items = new List<MemberMessage>();
// add selected messages to list
for (int i = 0; i < messages.Length; i++)
{
foreach (int id in messages[i].Selected)
{
items.Add(MessageRepository.FetchByID(id));
}
}
// determine action further
if (action == MemberMessageAction.MoveToFolder)
{
// folders
IList<MemberMessageFolder> folders = FolderRepository.FetchAll(new MemberMessageFolderCriteria
{
MemberID = Identity.ID,
ExcludedFolder = Request.Form["folder"]
});
if (folders.Total > 0)
{
ViewData["messages"] = items;
ViewData["folders"] = folders;
return View("move");
}
return Url<MessageController>(c => c.Index("inbox", 1)).Redirect();
}
else if (action == MemberMessageAction.ExportXml)
{
return new MemberMessageDownload(Identity.ID, items, MemberMessageDownloadType.Xml);
}
else if (action == MemberMessageAction.ExportCsv)
{
return new MemberMessageDownload(Identity.ID, items, MemberMessageDownloadType.Csv);
}
else
{
return new MemberMessageDownload(Identity.ID, items, MemberMessageDownloadType.Text);
}
}
else if (action == MemberMessageAction.Delete)
{
for (int i = 0; i < messages.Length; i++)
{
foreach (int id in messages[i].Selected)
{
MemberMessage message = MessageRepository.FetchByID(id);
if (message.Sender.ID == Identity.ID || message.Receiver.ID == Identity.ID)
{
if (message.Sender.ID == Identity.ID)
{
message.SenderActive = false;
}
else
{
message.ReceiverActive = false;
}
message.Updated = DateTime.Now;
MessageRepository.Update(message);
if (message.SenderActive == false && message.ReceiverActive == false)
{
MessageRepository.Delete(message);
}
}
}
}
}
else
{
for (int i = 0; i < messages.Length; i++)
{
foreach (int id in messages[i].Selected)
{
MemberMessage message = MessageRepository.FetchByID(id);
if (message.Receiver.ID == Identity.ID)
{
if (action == MemberMessageAction.MarkRead)
{
message.ReceiverRead = true;
}
else
{
message.ReceiverRead = false;
}
message.Updated = DateTime.Now;
MessageRepository.Update(message);
}
}
}
}
return Url<MessageController>(c => c.Index("inbox", 1)).Redirect();
}
</code></pre>
| [
{
"answer_id": 348870,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 2,
"selected": false,
"text": "[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult SaveAction() {\n // SNIP \n if (action == MemberMessageAction.Delete) {\n return DoDeleteAction(...);\n }\n else if (action == MemberMessageAction.MoveToFolder) {\n return DoMoveToFolderAction(...);\n }\n else if (action == MemberMessageAction.ExportXml) {\n return DoExportXmlAction(...);\n }\n else if (action == MemberMessageAction.ExportCsv) {\n return DoExportCsvAction(...);\n }\n else {\n return HandleUnknownAction(...);\n }\n}\n"
},
{
"answer_id": 348884,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult SaveAction()\n{\n NameValueDeserializer value = new NameValueDeserializer();\n MemberMessageSaveAction[] messages = (MemberMessageSaveAction[])value.Deserialize(Request.Form, \"value\", typeof(MemberMessageSaveAction[]));\n MemberMessageAction action = MemberMessageAction.FromName(\n messages,\n Request.Form[\"action\"]));\n return action.Perform();\n}\n\nclass MoveToFolder : SpecialAction { /*...*/ }\nclass ExportXml : SpecialAction { /*...*/ }\nclass ExportCsv : SpecialAction { /*...*/ }\n\nclass Delete : MemberMessageAction { /*...*/ }\nclass MarkRead : MemberMessageAction { /*...*/ }\nclass MarkUnRead : MemberMessageAction { /*...*/ }\n\nabstract class MemberMessageAction {\n protected MemberMessageSaveAction[] messages;\n public MemberMessageAction(MemberMessageSaveAction[] ms) { messages = ms; }\n public abstract ActionResult Perform();\n public static MemberMessageAction FromName(MemberMessageSaveAction[] ms, string action) {\n // stupid code\n // return new Delete(ms);\n }\n}\n\nabstract class SpecialAction : MemberMessageAction {\n protected IList<MemberMessage> items;\n public SpecialAction(MemberMessageSaveAction[] ms) : base(ms) {\n // Build items\n }\n}\n"
},
{
"answer_id": 348936,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": 3,
"selected": true,
"text": "[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult SaveMemberAction(SelectList selectedMessages, MemberMessageAction actionType){\n //Refactors mentioned by others \n}\n"
},
{
"answer_id": 349091,
"author": "Mike Geise",
"author_id": 43380,
"author_profile": "https://Stackoverflow.com/users/43380",
"pm_score": 0,
"selected": false,
"text": " [AcceptVerbs(HttpVerbs.Post)]\n public ActionResult Update(MemberMessageUpdate[] messages, MemberMessage.Action action)\n {\n var actions = new List<MemberMessage.Action>\n {\n MemberMessage.Action.MoveToFolder,\n MemberMessage.Action.ExportCsv,\n MemberMessage.Action.ExportText,\n MemberMessage.Action.ExportText\n };\n\n if (actions.Contains(action))\n {\n IList<MemberMessage> items = new List<MemberMessage>();\n\n for (var i = 0; i < messages.Length; i++)\n {\n if (messages[i].Selected == false)\n {\n continue;\n }\n\n items.Add(MessageRepository.FetchByID(messages[i].ID));\n }\n\n if (action == MemberMessage.Action.MoveToFolder)\n {\n var data = new MessageMoveViewData\n {\n Messages = items\n };\n\n return View(\"move\", data);\n }\n\n return new MessageDownloadResult(Identity.ID, items, action);\n }\n\n MessageRepository.Update(messages, action);\n\n return Url<MessageController>(c => c.Index(null, null, null, null)).Redirect();\n }\n"
},
{
"answer_id": 349157,
"author": "user44259",
"author_id": 44259,
"author_profile": "https://Stackoverflow.com/users/44259",
"pm_score": 1,
"selected": false,
"text": "MessageRepository.FetchByID(messages[i].ID)\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43380/"
] |
348,880 | <p>Is it possible to create an sql statement that selects the week number (NOT the day of week - or the day number in a week). I'm creating a view to select this extra information along with a couple of other fields and thus can not use a stored procedure. I'm aware that it's possible to create a UDF to do the trick, but if at all possible i'd rather only have to add a view to this database, than both a view and a function.</p>
<p>Any ideas? Also where i come from, the week starts monday and week 1 is the first week of the year with atleast 4 days.</p>
<h3>Related:</h3>
<blockquote>
<p><a href="https://stackoverflow.com/questions/274861/how-do-i-calculate-the-week-number-given-a-date">How do I calculate the week number given a date?</a></p>
</blockquote>
| [
{
"answer_id": 348894,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "DATEPART(wk, ‘Jan 1, xxxx’) = 1\n SET DATEFIRST 1 -- for monday\n"
},
{
"answer_id": 348896,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 1,
"selected": false,
"text": "SELECT DATEPART( wk, 'enter the date over here' )\n"
},
{
"answer_id": 348938,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "DATEPART() CREATE FUNCTION ISOweek (@DATE DATETIME)\nRETURNS INT\nAS\nBEGIN\n DECLARE @ISOweek INT\n SET @ISOweek = DATEPART(wk,@DATE) \n +1 \n -DATEPART(wk,CAST(DATEPART(yy,@DATE) AS CHAR(4))+'0104')\n -- Special cases: Jan 1-3 may belong to the previous year\n IF (@ISOweek=0)\n SET @ISOweek = dbo.ISOweek(CAST(DATEPART(yy,@DATE) - 1\n AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1\n -- Special case: Dec 29-31 may belong to the next year\n IF ((DATEPART(mm,@DATE)=12) AND\n ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28))\n SET @ISOweek=1\n RETURN(@ISOweek)\nEND\nGO\n"
},
{
"answer_id": 348945,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 4,
"selected": false,
"text": "drop function dbo.F_ISO_WEEK_OF_YEAR\ngo\ncreate function dbo.F_ISO_WEEK_OF_YEAR\n (\n @Date datetime\n )\nreturns int\nas\n/*\nFunction F_ISO_WEEK_OF_YEAR returns the\nISO 8601 week of the year for the date passed.\n*/\nbegin\n\ndeclare @WeekOfYear int\n\nselect\n -- Compute week of year as (days since start of year/7)+1\n -- Division by 7 gives whole weeks since start of year.\n -- Adding 1 starts week number at 1, instead of zero.\n @WeekOfYear =\n (datediff(dd,\n -- Case finds start of year\n case\n when NextYrStart <= @date\n then NextYrStart\n when CurrYrStart <= @date\n then CurrYrStart\n else PriorYrStart\n end,@date)/7)+1\nfrom\n (\n select\n -- First day of first week of prior year\n PriorYrStart =\n dateadd(dd,(datediff(dd,-53690,dateadd(yy,-1,aa.Jan4))/7)*7,-53690),\n -- First day of first week of current year\n CurrYrStart =\n dateadd(dd,(datediff(dd,-53690,aa.Jan4)/7)*7,-53690),\n -- First day of first week of next year\n NextYrStart =\n dateadd(dd,(datediff(dd,-53690,dateadd(yy,1,aa.Jan4))/7)*7,-53690)\n from\n (\n select\n --Find Jan 4 for the year of the input date\n Jan4 = \n dateadd(dd,3,dateadd(yy,datediff(yy,0,@date),0))\n ) aa\n ) a\n\nreturn @WeekOfYear\n\nend\ngo\n"
},
{
"answer_id": 349053,
"author": "Doctor Jones",
"author_id": 39277,
"author_profile": "https://Stackoverflow.com/users/39277",
"pm_score": 0,
"selected": false,
"text": "SELECT { fn WEEK(GETDATE()) } AS WeekNumber, { fn WEEK(CONVERT(DATETIME, '2008-01-01 00:00:00', 102)) } AS FirstWeekOfYear, { fn WEEK(CONVERT(DATETIME, '2008-12-31 00:00:00', 102)) } AS LastWeekOfYear\n"
},
{
"answer_id": 34179435,
"author": "Ian",
"author_id": 2456110,
"author_profile": "https://Stackoverflow.com/users/2456110",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION ISOweek (@DATE DATETIME)\nRETURNS INT\nAS\nBEGIN\n RETURN (datepart(DY, datediff(d, 0, @DATE) / 7 * 7 + 3)+6) / 7\nEND\nGO\n"
},
{
"answer_id": 38885301,
"author": "Fandango68",
"author_id": 2181188,
"author_profile": "https://Stackoverflow.com/users/2181188",
"pm_score": 0,
"selected": false,
"text": "select DATEPART(wk, GETDATE())\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11619/"
] |
348,892 | <p>I normally in my projects use such these code:</p>
<pre><code>If user.IsInRole("Admin") Then
deleteButton.Visible = True
else
deleteButton.Visible = False
</code></pre>
<p>But I want to control roles, which can see this button in database.</p>
<p>For this purpose how should database design be?</p>
<p>Thanks.</p>
| [
{
"answer_id": 348901,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 1,
"selected": false,
"text": "user.isInRole(\"Admin\")"
},
{
"answer_id": 348927,
"author": "BobbyShaftoe",
"author_id": 38426,
"author_profile": "https://Stackoverflow.com/users/38426",
"pm_score": 0,
"selected": false,
"text": "User(UserID, ...) PK = UserID\n\nRole(RoleID, RoleName, ...) PK = RoleID\n\nUserHasRole(UserHasRoleID, UserID, RoleID) PK=UserHasRoleID ; Unique= (UserID, RoleID)\n"
},
{
"answer_id": 348940,
"author": "mavera",
"author_id": 439507,
"author_profile": "https://Stackoverflow.com/users/439507",
"pm_score": 0,
"selected": false,
"text": "if user.isInRole(\"Admin\") then \n deleteButton.visible = true \nelse \n deleteButton.visible = false\n if user.isInRole(\"Admin\",\"Moderator\") then \n deleteButton.visible = true \nelse \n deleteButton.visible = false\n"
},
{
"answer_id": 349074,
"author": "Pete OHanlon",
"author_id": 43635,
"author_profile": "https://Stackoverflow.com/users/43635",
"pm_score": -1,
"selected": true,
"text": "public interface ICustomRole\n{\n bool IsInRole(string userName, object[] params roles);\n}\n\npublic class MyCustomRole : RoleProvider, ICustomRole\n{\n public IsInRole(MembershipUser user, object[] params roles)\n {\n if (roles == null || roles.Length == 0)\n throw new ArgumentException(\"roles\");\n // Put your logic here for accessing the roles\n }\n}\n bool isValid = ((ICustomRole)Roles.Provider).IsInRole(\n User, new[] { \"Admin\", \"Moderator\", \"Validator\" });\n"
},
{
"answer_id": 4013752,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 0,
"selected": false,
"text": "public class YourSqlRoleProvider : System.Web.Security.RoleProvider\n{\n private string ConnectionString { get; set; }\n\n public override void AddUsersToRoles(string[] userNames, string[] roleNames)\n {\n // logic here\n }\n\n public override string ApplicationName\n {\n get\n {\n throw new NotSupportedException();\n }\n set\n {\n throw new NotSupportedException();\n }\n }\n\n public override void CreateRole(string roleName)\n {\n throw new NotSupportedException();\n }\n\n public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)\n {\n throw new NotSupportedException();\n }\n\n public override string[] FindUsersInRole(string roleName, string userNameToMatch)\n {\n throw new NotSupportedException();\n }\n\n public override string[] GetAllRoles()\n {\n // logic here\n }\n\n public override string[] GetRolesForUser(string userName)\n {\n // logic here\n }\n\n public override string[] GetUsersInRole(string roleName)\n {\n throw new NotSupportedException();\n }\n\n public override bool IsUserInRole(string userName, string roleName)\n {\n return GetRolesForUser(userName).Contains(roleName);\n }\n\n public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)\n {\n this.ConnectionString = ConfigurationManager.ConnectionStrings[config[\"connectionStringName\"]].ConnectionString;\n\n base.Initialize(name, config);\n }\n\n public override void RemoveUsersFromRoles(string[] userNames, string[] roleNames)\n {\n throw new NotSupportedException();\n }\n\n public override bool RoleExists(string roleName)\n {\n throw new NotSupportedException();\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <connectionStrings>\n <clear />\n <add name=\"YourConnectionString\" providerName=\"System.Data.SqlClient\" connectionString=\"connection string here\" />\n </connectionStrings>\n <system.web>\n <roleManager defaultProvider=\"YourSqlRoleProvider\" enabled=\"true\">\n <providers>\n <clear />\n <add name=\"YourSqlRoleProvider\" type=\"YourSqlRoleProvider\" connectionStringName=\"YourConnectionString\" />\n </providers>\n </roleManager>\n </system.web>\n</configuration>\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439507/"
] |
348,900 | <p>There are a few questions on SO already regarding LINQ pivots and while a couple of them outline my exact problem, I can't successfully translate them to a working solution. I feel that this is mostly due to a join in my tables.</p>
<p>So for the benefit of all the LINQ junkies out there who love a problem, here's another puzzle for you to work out. Please help me out (and earn some reputation points and much respect from me) by converting the following SQL stored proc script to LINQ:</p>
<pre><code>ALTER PROCEDURE [dbo].[GetTimesheetForWeekById]
@timesheetid int,
@begindate VarChar(20),
@enddate VarChar(20)
AS
BEGIN
SELECT T.TaskName,
SUM(
case DATEPART(weekday, TE.StartTime)
WHEN 1 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Sunday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 2 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Monday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 3 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Tuesday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 4 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Wednesday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 5 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Thursday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 6 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Friday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 6 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Saturday
FROM Tasks T
INNER JOIN TimeEntries TE on T.TaskID = TE.TaskID
WHERE TE.StartTime BETWEEN
(CONVERT(datetime, @begindate, 103)) AND (CONVERT(datetime, @enddate, 103))
AND TE.TimesheetID = @timesheetid
GROUP BY T.TaskName
END
</code></pre>
| [
{
"answer_id": 348901,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 1,
"selected": false,
"text": "user.isInRole(\"Admin\")"
},
{
"answer_id": 348927,
"author": "BobbyShaftoe",
"author_id": 38426,
"author_profile": "https://Stackoverflow.com/users/38426",
"pm_score": 0,
"selected": false,
"text": "User(UserID, ...) PK = UserID\n\nRole(RoleID, RoleName, ...) PK = RoleID\n\nUserHasRole(UserHasRoleID, UserID, RoleID) PK=UserHasRoleID ; Unique= (UserID, RoleID)\n"
},
{
"answer_id": 348940,
"author": "mavera",
"author_id": 439507,
"author_profile": "https://Stackoverflow.com/users/439507",
"pm_score": 0,
"selected": false,
"text": "if user.isInRole(\"Admin\") then \n deleteButton.visible = true \nelse \n deleteButton.visible = false\n if user.isInRole(\"Admin\",\"Moderator\") then \n deleteButton.visible = true \nelse \n deleteButton.visible = false\n"
},
{
"answer_id": 349074,
"author": "Pete OHanlon",
"author_id": 43635,
"author_profile": "https://Stackoverflow.com/users/43635",
"pm_score": -1,
"selected": true,
"text": "public interface ICustomRole\n{\n bool IsInRole(string userName, object[] params roles);\n}\n\npublic class MyCustomRole : RoleProvider, ICustomRole\n{\n public IsInRole(MembershipUser user, object[] params roles)\n {\n if (roles == null || roles.Length == 0)\n throw new ArgumentException(\"roles\");\n // Put your logic here for accessing the roles\n }\n}\n bool isValid = ((ICustomRole)Roles.Provider).IsInRole(\n User, new[] { \"Admin\", \"Moderator\", \"Validator\" });\n"
},
{
"answer_id": 4013752,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 0,
"selected": false,
"text": "public class YourSqlRoleProvider : System.Web.Security.RoleProvider\n{\n private string ConnectionString { get; set; }\n\n public override void AddUsersToRoles(string[] userNames, string[] roleNames)\n {\n // logic here\n }\n\n public override string ApplicationName\n {\n get\n {\n throw new NotSupportedException();\n }\n set\n {\n throw new NotSupportedException();\n }\n }\n\n public override void CreateRole(string roleName)\n {\n throw new NotSupportedException();\n }\n\n public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)\n {\n throw new NotSupportedException();\n }\n\n public override string[] FindUsersInRole(string roleName, string userNameToMatch)\n {\n throw new NotSupportedException();\n }\n\n public override string[] GetAllRoles()\n {\n // logic here\n }\n\n public override string[] GetRolesForUser(string userName)\n {\n // logic here\n }\n\n public override string[] GetUsersInRole(string roleName)\n {\n throw new NotSupportedException();\n }\n\n public override bool IsUserInRole(string userName, string roleName)\n {\n return GetRolesForUser(userName).Contains(roleName);\n }\n\n public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)\n {\n this.ConnectionString = ConfigurationManager.ConnectionStrings[config[\"connectionStringName\"]].ConnectionString;\n\n base.Initialize(name, config);\n }\n\n public override void RemoveUsersFromRoles(string[] userNames, string[] roleNames)\n {\n throw new NotSupportedException();\n }\n\n public override bool RoleExists(string roleName)\n {\n throw new NotSupportedException();\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <connectionStrings>\n <clear />\n <add name=\"YourConnectionString\" providerName=\"System.Data.SqlClient\" connectionString=\"connection string here\" />\n </connectionStrings>\n <system.web>\n <roleManager defaultProvider=\"YourSqlRoleProvider\" enabled=\"true\">\n <providers>\n <clear />\n <add name=\"YourSqlRoleProvider\" type=\"YourSqlRoleProvider\" connectionStringName=\"YourConnectionString\" />\n </providers>\n </roleManager>\n </system.web>\n</configuration>\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15609/"
] |
348,919 | <p>I'd like to be able to send a Ruby app to some colleagues without requiring them to install a Ruby interpreter. A single exe would be preferable.</p>
<p>I googled and found "RubyScript2Exe".</p>
<p>What are your experiences with that? Are there other such tools or are there better approaches altogether than building an exe?</p>
| [
{
"answer_id": 682780,
"author": "JasonSmith",
"author_id": 2938,
"author_profile": "https://Stackoverflow.com/users/2938",
"pm_score": 0,
"selected": false,
"text": "exerb .so ruby -r exerb/mkrbc ruby -r exerb/mkexy"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15323/"
] |
348,920 | <p>I am new to php.
I made a member registration on login page and adm too. So inside admin I wanted to get the list of the members and delete the members I dont want. So I took the a code from a sample code for phone book from <a href="http://localhost/xamp" rel="nofollow noreferrer">http://localhost/xamp</a> and editted it to my requirement I am able to retrieve the members but unable to delete the members. See the code below:</p>
<pre><code><?php
require_once('auth.php');
require_once('../config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
?>
<html>
<head>
<meta name="author" content="Kai Oswald Seidler">
<link href="../loginmodule.css" rel="stylesheet" type="text/css">
<title></title>
</head>
<body>
&nbsp;<p>
<h2><?php echo "User list"; ?></h2>
<table border="0" cellpadding="0" cellspacing="0">
<tr bgcolor="#f87820">
<td><img src="img/blank.gif" alt="" width="10" height="25"></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib1']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib2']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib3']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="50" height="6"><br><b><?php echo $TEXT['phonebook-attrib4']; ?></b></td>
<td><img src="img/blank.gif" alt="" width="10" height="25"></td>
</tr>
<?php
$firstname=$_REQUEST['firstname'];
$lastname=$_REQUEST['lastname'];
$phone=$_REQUEST['phone'];
if($_REQUEST['action']=="del")
{
$result=mysql_query("DELETE FROM members WHERE member_id={$_REQUEST['member_id']}");
}
$result=mysql_query("SELECT member_id,firstname,lastname,login FROM members ORDER BY lastname");
$i = 0;
while($row = mysql_fetch_array($result)) {
if ($i > 0) {
echo "<tr valign='bottom'>";
echo "<td bgcolor='#ffffff' height='1' style='background-image:url(img/strichel.gif)' colspan='6'></td>";
echo "</tr>";
}
echo "<tr valign='middle'>";
echo "<td class='tabval'><img src='img/blank.gif' alt='' width='10' height='20'></td>";
echo "<td class='tabval'><b>".$row['lastname']."</b></td>";
echo "<td class='tabval'>".$row['firstname']."&nbsp;</td>";
echo "<td class='tabval'>".$row['member_id']."&nbsp;</td>";
echo "<td class='tabval'><a onclick=\"return confirm('".$TEXT['userlist-sure']."');\" href='userlist.php?action=del&amp;member_1d=".$row['member_id']."'><span class='red'>[".$TEXT['userlist-button1']."]</span></a></td>";
echo "<td class='tabval'></td>";
echo "</tr>";
$i++;
}
echo "<tr valign='bottom'>";
echo "<td bgcolor='#fb7922' colspan='6'><img src='img/blank.gif' alt='' width='1' height='8'></td>";
echo "</tr>";
?>
</table>
</body>
</html>
</code></pre>
<p>I haven't editted it that properly and the looks in all.</p>
<p>Please help me in making it able to delete the members also.</p>
<p>I didn't understand what .$TEXT['userlist-button1'].,'".$TEXT['userlist-sure']. variables are?
I also want to include an approved and disapproved radio button in table for each members.</p>
<p>How can I do that?</p>
<p>Please if you can help me.</p>
| [
{
"answer_id": 348941,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 1,
"selected": false,
"text": "&member_1d &member_id"
},
{
"answer_id": 348942,
"author": "markus",
"author_id": 11995,
"author_profile": "https://Stackoverflow.com/users/11995",
"pm_score": 1,
"selected": false,
"text": "&"
},
{
"answer_id": 9041039,
"author": "crmepham",
"author_id": 888990,
"author_profile": "https://Stackoverflow.com/users/888990",
"pm_score": 0,
"selected": false,
"text": "$query = mysql_query(\"SELECT member_id,firstname,lastname,login FROM members ORDER BY lastname\");\nif(mysql_num_row($query)!= 0){ //only continue if there are members in the database\nwhile($row = mysql_fetch_assoc($query)){ //loop through each row in the database\n$member_id = $row['member_id'];\n$firstname = $row['firstname'];\n$lastname = $row['lastname'];\n\necho '<p>' . $firstname . ' - <a href=\"delete_member.php?id='$member_id'\">' delete '</a></p>';\n\n}\n}\n if(isset($_GET['id'])){\n$member_id = $_GET['id'];\n$query = mysql_query(\"DELETE FROM members WHERE member_id='$member_id'\");\necho '<p>This user was deleted from database</p>';\n}\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40975/"
] |
348,928 | <p>Parser Error Message: The entry 'SiteSqlServer' has already been added.</p>
<p>Source Error:</p>
<blockquote>
<pre><code>Line 23: providerName="System.Data.SqlClient"/> -->
Line 24: < ! -- Connection String for SQL Server 2000/2005 -->
Line 25: <add name="SiteSqlServer" connectionString="Server=(local);
</code></pre>
<p>abase=DotNetNuke2; uid=nukeuser;pwd=dotnetnuke;" providerName="System.Data.SqlClient" / ></p>
<pre><code>Line 26: </connectionStrings>
Line 27: <appSettings>
</code></pre>
</blockquote>
<p>Does anyone know the work around???</p>
| [
{
"answer_id": 351961,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 2,
"selected": true,
"text": "<connectionStrings>\n\n<remove name=\"SiteSqlServer\" />\n\n<add name=\"SiteSqlServer\" connectionString=\"server=(local);uid=;pwd=;Trusted_Connection=yes;database=communityserver\" />\n\n</connectionStrings>\n <connectionStrings>\n<clear />\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29515/"
] |
348,953 | <p>I am extending a template class using C++ in Visual Studio 2005.
It is giving me an error when I try to extend the template base class with:</p>
<pre><code>template <class K, class D>
class RedBlackTreeOGL : public RedBlackTree<K, D>::RedBlackTree // Error 1
{
public:
RedBlackTreeOGL();
~RedBlackTreeOGL();
</code></pre>
<p>and a second error when I try to instantiate the object:</p>
<pre><code>RedBlackTreeOGL<double, std::string> *tree = new RedBlackTreeOGL<double, std::string>; // error 2
</code></pre>
<p><strong>Error 1:</strong></p>
<p>**redblacktreeopengl.hpp(27) : error C2039: '{ctor}' : is not a member of 'RedBlackTree'
with
[
K=double,
D=std::string
]
**</p>
<p><strong>Error 2:</strong></p>
<p>main.cpp(50) : see reference to class template instantiation 'RedBlackTreeOGL' being compiled</p>
| [
{
"answer_id": 348955,
"author": "Sandeep Datta",
"author_id": 39648,
"author_profile": "https://Stackoverflow.com/users/39648",
"pm_score": 1,
"selected": false,
"text": "RedBlackTree<K, D>::RedBlackTree"
},
{
"answer_id": 348968,
"author": "Brock Woolf",
"author_id": 40002,
"author_profile": "https://Stackoverflow.com/users/40002",
"pm_score": 0,
"selected": false,
"text": "template <class K, class D>\nclass RedBlackTree\n {\n public:\n RedBlackTree();\n // Deleting a storage object clears all remaining nodes\n ~RedBlackTree();\n"
},
{
"answer_id": 348972,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 4,
"selected": true,
"text": "template <class K, class D>\nclass RedBlackTreeOGL : public RedBlackTree<K, D>\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40002/"
] |
348,964 | <p>Can someone share a simple example of using the <code>foreach</code> keyword with custom objects?</p>
| [
{
"answer_id": 348977,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "foreach IEnumerable IEnumerator foreach (Foo element in source)\n{\n // Body\n}\n source IEnumerable<Foo> using (IEnumerator<Foo> iterator = source.GetEnumerator())\n{\n Foo element;\n while (iterator.MoveNext())\n {\n element = iterator.Current;\n // Body\n }\n}\n IEnumerator<Foo> IEnumerable<T> IEnumerator<T> public IEnumerable<int> EvenNumbers0To10()\n{\n for (int i=0; i <= 10; i += 2)\n {\n yield return i;\n }\n}\n\n// Later\nforeach (int x in EvenNumbers0To10())\n{\n Console.WriteLine(x); // 0, 2, 4, 6, 8, 10\n}\n IEnumerable<T> public class Foo : IEnumerable<string>\n{\n public IEnumerator<string> GetEnumerator()\n {\n yield return \"x\";\n yield return \"y\";\n }\n\n // Explicit interface implementation for nongeneric interface\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator(); // Just return the generic version\n }\n}\n"
},
{
"answer_id": 348983,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 3,
"selected": false,
"text": "List<MyObject> myObjects = // something\nforeach(MyObject myObject in myObjects)\n{\n // Do something nifty here\n}\n class MyContainer : IEnumerable<int>\n{\n private int max = 0;\n public MyContainer(int max)\n {\n this.max = max;\n }\n\n public IEnumerator<int> GetEnumerator()\n {\n for(int i = 0; i < max; ++i)\n yield return i;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n MyContainer myContainer = new MyContainer(10);\nforeach(int i in myContainer)\n Console.WriteLine(i);\n"
},
{
"answer_id": 61156378,
"author": "Brackets",
"author_id": 6544091,
"author_profile": "https://Stackoverflow.com/users/6544091",
"pm_score": 1,
"selected": false,
"text": "IEnumerable GetEnumerator GetEnumerator MoveNext foreach IEnumerable class Item\n{\n public Item Current { get; set; }\n public bool MoveNext()\n {\n return false;\n }\n}\n\nclass Foreachable\n{\n Item[] items;\n int index;\n public Item GetEnumerator()\n {\n return items[index];\n }\n}\n\nForeachable foreachable = new Foreachable();\nforeach (Item item in foreachable)\n{\n\n}\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42070/"
] |
348,966 | <p>I'm working with asp.net (I'm a designer) and at some point during debugging it'll throw me and I'll get to an Exception objErr in the code - and when I hover it says "file not found". I assume it's an image but I've been searching and can't find anyway to pinpoint which file is missing. I hope this is enough information - if anyone could give me a direction I'll really appreciate it!</p>
<p>AB</p>
| [
{
"answer_id": 349054,
"author": "Germstorm",
"author_id": 18631,
"author_profile": "https://Stackoverflow.com/users/18631",
"pm_score": 0,
"selected": false,
"text": "<asp:HyperLink ID=\"lnkExample\" runat=\"server\" NavigateUrl=\"~/Pages/Example.aspx\"> Example</asp:HyperLink>\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,985 | <p>I user sun jdk 1.5 ThreadPoolExecutor( 24, 24,60,TimeUnit.SECONDS, new LinkedBlockingQueue()). soemtime I use jdb tool to find the status of all threads in thread pool are " waiting in a monitor", the code is : </p>
<pre><code> String key = getKey(dt.getPrefix(), id);
synchronized (key.intern()) { ----->
</code></pre>
<p>Is there a problem in "synchronized (key.intern()) " ?</p>
<hr>
<p>I get following informatnio using jdb tool, the status of 24 threads is "waiting in a monitor", it means 24 threads are deadlock at "key.intern()".</p>
<p>(java.lang.Thread)0x28 pool-3-thread-2 waiting in a monitor</p>
<p>(java.lang.Thread)0x27 pool-3-thread-3 waiting in a monitor</p>
<p>(java.lang.Thread)0x1b pool-3-thread-4 waiting in a monitor</p>
<p>(java.lang.Thread)0x1a pool-3-thread-5 waiting in a monitor</p>
<p>(java.lang.Thread)0x19 pool-3-thread-6 waiting in a monitor</p>
<p>(java.lang.Thread)0x18 pool-3-thread-7 waiting in a monitor</p>
<p>(java.lang.Thread)0x17 pool-3-thread-8 waiting in a monitor
...</p>
<p>so the result is : in multi-threads environment, Sting intern() method may be deadlock, ok ?</p>
| [
{
"answer_id": 348994,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 2,
"selected": false,
"text": "key"
},
{
"answer_id": 358513,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 1,
"selected": false,
"text": "intern() String s1 = new String(new char[] { 'c', 'o', 'm', 'm', 'o', 'n' }).intern();\n String s2 = new String(\"commo\" + (s1.charAt(s1.length() - 1)).intern();\n String s3 = \"common\";\n if ((s1 == s2) && (s1 == s3))\n System.out.println(\"There's only one object here.\");\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44230/"
] |
348,991 | <p>I have a string, lets say "123|ABC|test|12345|FF" and I want to xor the ascii value of each character and print the result in hex.</p>
<p>What is the simplest way?</p>
| [
{
"answer_id": 348994,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 2,
"selected": false,
"text": "key"
},
{
"answer_id": 358513,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 1,
"selected": false,
"text": "intern() String s1 = new String(new char[] { 'c', 'o', 'm', 'm', 'o', 'n' }).intern();\n String s2 = new String(\"commo\" + (s1.charAt(s1.length() - 1)).intern();\n String s3 = \"common\";\n if ((s1 == s2) && (s1 == s3))\n System.out.println(\"There's only one object here.\");\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
348,999 | <p>On my Centos server Python's mimetypes.guess_type("mobile.3gp") returns (None, None), instead of ('video/3gpp', None).</p>
<p>Where does Python get the list of mimetypes from, and is it possible to add a missing type to the list?</p>
| [
{
"answer_id": 349020,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "knownfiles init()"
},
{
"answer_id": 43311856,
"author": "JinSnow",
"author_id": 1486850,
"author_profile": "https://Stackoverflow.com/users/1486850",
"pm_score": 0,
"selected": false,
"text": "C:\\Users\\Me\\AppData\\Local\\Programs\\Python\\Python36\\Lib\\mimetypes.py mp3"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/348999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21716/"
] |
349,004 | <p>I have written a game that uses GLUT, OpenGL and FMOD. The problem is that the binary won't run, unless Visual Studio 2008 is installed on the computer.</p>
<p>Why is this?</p>
| [
{
"answer_id": 349017,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 3,
"selected": false,
"text": "cout << \"Hello, World\" << endl;\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40002/"
] |
349,022 | <p>I have an app that run on many computers and connect to sql server
I want to log the machine names of that computers in a table every time they connect how can I do that</p>
<p>I want to know if there is a command like that</p>
<p>"Select @@MachineName"</p>
| [
{
"answer_id": 349028,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 0,
"selected": false,
"text": " [ , [ @datasrc= ] 'data_source' ] \n [ , [ @location= ] 'location' ] \n [ , [ @provstr= ] 'provider_string' ] \n [ , [ @catalog= ] 'catalog' ] \n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
349,023 | <p>The code below is the code i am using. It works fine in thunderbird but not in mac mail client (and i assume anything made by microsoft. I currently do not have access to this to test it in). Much as i am aware of the idiosyncrasies of the various mail clients, I am flummoxed by this! It's fairly self explanatory but i am trying to send plain text and html emails to increase the readership. Any help would be much appreciated.</p>
<p>EDIT</p>
<p>I should have clarified that the contents get sent regardless but in thunderbird it displays the message correctly, but in mac mail client you get the entire thing from the first PHP-alt to the last PHP</p>
<pre><code><?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
</code></pre>
| [
{
"answer_id": 349039,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 0,
"selected": false,
"text": "$message =ob_get_contents();\nob_end_clean();\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] |
349,025 | <p>Is a string literal in C++ created in static memory and destroyed only when the program exits?</p>
| [
{
"answer_id": 349030,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 7,
"selected": true,
"text": "char *x = \"hello\"; hello x x hello +-> plus:0 1 2 3 4 5 6 7 8 9 A B C D E\n| +---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+\n0x1000 | i | n | v | a | l | i | d | | o | p | t | i | o | n | \\0 |\n +---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+\n main()"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
349,040 | <p>I don't want a "close window" menu item in the task bar context menu for my WPF window. My intention is to annoy the user.</p>
<p>Thank you!</p>
| [
{
"answer_id": 349966,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 3,
"selected": false,
"text": "<Window ShowInTaskbar=\"False\" ... />\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22038/"
] |
349,050 | <p>I'm in the midst of writing a 3d engine and I've come across the LookAt algorithm described in the DirectX documentation:</p>
<pre><code>zaxis = normal(At - Eye)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)
xaxis.x yaxis.x zaxis.x 0
xaxis.y yaxis.y zaxis.y 0
xaxis.z yaxis.z zaxis.z 0
-dot(xaxis, eye) -dot(yaxis, eye) -dot(zaxis, eye) 1
</code></pre>
<p>Now I get how it works on the rotation side, but what I don't quite get is why it puts the translation component of the matrix to be those dot products. Examining it a bit it seems that it's adjusting the camera position by a small amount based on a projection of the new basis vectors onto the position of the eye/camera.</p>
<p>The question is why does it need to do this? What does it accomplish?</p>
| [
{
"answer_id": 353612,
"author": "TM.",
"author_id": 12983,
"author_profile": "https://Stackoverflow.com/users/12983",
"pm_score": 2,
"selected": false,
"text": "gluLookAt"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3719/"
] |
349,055 | <p>T have used checkbox column in gridview. On click of a linkbutton, it should be checked that checkboxes in gridview are checked or not. If none check box is checked then it should display alert("Check at leat one check box"). </p>
| [
{
"answer_id": 349168,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 0,
"selected": false,
"text": "var grid = document.getElementById(\"gridId\"); //Retrieve the grid \n var inputs = grid.getElementsByTagName(\"input\"); //Retrieve all the input elements from the grid\n var isValid = false;\n for (var i=0; i < inputs.length; i += 1) { //Iterate over every input element retrieved\n if (inputs[i].type === \"checkbox\") { //If the current element's type is checkbox, then it is wat we need\n if(inputs[i].checked === true) { //If the current checkbox is true, then atleast one checkbox is ticked, so break the loop\n isValid = true;\n break;\n }\n }\n }\n if(!isValid) {\n alert('Check at least one checkbox');\n }\n"
},
{
"answer_id": 349782,
"author": "Dave R.",
"author_id": 42841,
"author_profile": "https://Stackoverflow.com/users/42841",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\">\n function ClientCheck() {\n var valid = false;\n var gv = document.getElementById(\"GridView1\");\n\n for (var i = 0; i < gv.all.length; i++) {\n var node = gv.all[i];\n if (node != null && node.type == \"checkbox\" && node.checked) {\n valid = true;\n break;\n }\n }\n if (!valid) {\n alert(\"Invalid. Please select a checkbox to continue.\");\n }\n\n return valid;\n }\n</script>\n GridView for checkbox checked valid valid GridView TemplateField LinkButton <asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"False\" DataSourceID=\"ObjectDataSource1\">\n <Columns>\n <asp:TemplateField HeaderText=\"Button Field\" ShowHeader=\"False\">\n <ItemTemplate>\n <span onclick=\"return ClientCheck();\">\n <asp:LinkButton ID=\"LinkButton1\" runat=\"server\" CommandName=\"IDClick\" Text='<%# Eval(\"YourDataSourceItem\") %>'></asp:LinkButton>\n </span>\n </ItemTemplate>\n </asp:TemplateField>\n // ...your remaining columns...\n TemplateField span onclick ClientCheck CustomValidator"
},
{
"answer_id": 352166,
"author": "Devashri B.",
"author_id": 43886,
"author_profile": "https://Stackoverflow.com/users/43886",
"pm_score": 2,
"selected": true,
"text": " var frm=document.forms['aspnetForm'];\n var flag=false;\n for(var i=0;i<document.forms[0].length;i++)\n {\n if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)\n {\n if(document.forms[0].elements[i].checked)\n {\n flag=true\n } \n }\n } \n if (flag==true)\n {\n return true\n }else\n {\n alert('Please select at least one Event.')\n return false\n }\n\n}\n <asp:BoundField ItemStyle-Width =\"100px\" DataField =\"EventStartDate\" DataFormatString =\"{0:g}\" HeaderText =\"<%$ Resources:stringsRes, ctl_EventList_StartDate %>\" SortExpression =\"EventStartDate\" HtmlEncode =\"true\" ItemStyle-Wrap =\"false\" />\n <asp:BoundField ItemStyle-Width=\"100px\" DataField=\"EventDate\" DataFormatString=\"{0:g}\" HeaderText=\"<%$ Resources:stringsRes, ctl_EventList_Date %>\" SortExpression=\"EventDate\" HtmlEncode=\"true\" ItemStyle-Wrap=\"false\" />\n <asp:ButtonField ItemStyle-Width=\"150px\" ButtonType=\"Link\" DataTextField=\"EventName\" HeaderText=\"<%$ Resources:stringsRes, ctl_EventList_Event %>\" SortExpression=\"EventName\" CommandName=\"show_details\" CausesValidation=\"false\" />\n <asp:BoundField DataField=\"EventLocation\" HeaderText=\"<%$ Resources:stringsRes, ctl_EventList_Location %>\" SortExpression=\"EventLocation\" />\n <asp:TemplateField HeaderText =\"Select\">\n <ItemTemplate >\n <asp:CheckBox ID=\"chkDownloadSelectedEvent\" runat =\"server\" AutoPostBack =\"false\" Onclick=\"eachCheck();\"/> \n\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n <RowStyle Height=\"25px\" />\n <HeaderStyle Height=\"30px\"/>\n </asp:GridView>\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43886/"
] |
349,060 | <p>Now I know about the "normal" CSS list styles (roman, latin, etc) and certainly in years past they were somewhat inflexible in not allowing things like:</p>
<p>(a)</p>
<p>or </p>
<p>a)</p>
<p>only</p>
<p>a.</p>
<p>Now I believe that you can get an effect like the above with the :before and :after pseudo-elements. Is that correct? And whats the browser compatibility like if you can?</p>
<p>My main question however is that I want to have report style numbering:</p>
<ol>
<li>Introduction
1.1 Objectives
1.2 Assumptions
1.3 Limitations
1.3.1 ...</li>
<li>New Section
...</li>
</ol>
<p>and so on.</p>
<p>Can CSS do this and, if so, whats the browser compatibility like?</p>
| [
{
"answer_id": 349089,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 4,
"selected": true,
"text": "H1:before {\n content: \"Chapter \" counter(chapter) \". \";\n counter-increment: chapter; /* Add 1 to chapter */\n counter-reset: section; /* Set section to 0 */\n}\nH2:before {\n content: counter(chapter) \".\" counter(section) \" \";\n counter-increment: section;\n}\n"
},
{
"answer_id": 349102,
"author": "Ozh",
"author_id": 36850,
"author_profile": "https://Stackoverflow.com/users/36850",
"pm_score": 0,
"selected": false,
"text": "<ol>\n <li>level one</li>\n <ol start=\"10\"> \n <li>level two</li>\n <li>level two</li>\n <ol start=\"110\">\n <li>level three</li>\n </ol> \n <li>level two\n </ol> \n <li>level one</li>\n</ol>\n 1. level one\n 10. level two\n 11. level two\n 110. level three\n 12. level two \n 2. level one \n"
},
{
"answer_id": 23089781,
"author": "Kağan Kayal",
"author_id": 939280,
"author_profile": "https://Stackoverflow.com/users/939280",
"pm_score": 1,
"selected": false,
"text": "body {\n counter-reset:level1Header;\n}\nh1 {\n counter-reset:level2Header;\n}\nh2 {\n counter-reset:level3Header;\n}\nh3 {\n counter-reset:level4Header;\n}\nh4 {\n counter-reset:level5Header;\n}\nh5 {\n counter-reset:level6Header;\n}\n\nh1:before {\n counter-increment:level1Header;\n content:counter(level1Header) \". \";\n}\n\nh2:before {\n counter-increment:level2Header;\n content:counter(level1Header) \".\" counter(level2Header) \" \";\n}\n\nh3:before {\n counter-increment:level3Header;\n content:counter(level1Header) \".\" counter(level2Header) \".\" counter(level3Header) \" \";\n}\n\nh4:before {\n counter-increment:level4Header;\n content:counter(level1Header) \".\" counter(level2Header) \".\" counter(level3Header) \".\" counter(level4Header) \" \";\n}\n\nh5:before {\n counter-increment:level5Header;\n content:counter(level1Header) \".\" counter(level2Header) \".\" counter(level3Header) \".\" counter(level4Header) \".\" counter(level5Header) \" \";\n}\n\nh6:before {\n counter-increment:level6Header;\n content:counter(level1Header) \".\" counter(level2Header) \".\" counter(level3Header) \".\" counter(level4Header) \".\" counter(level5Header) \".\" counter(level6Header) \" \";\n}\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18393/"
] |
349,062 | <p>Is it possible to overload the null-coalescing operator for a class in C#? </p>
<p>Say for example I want to return a default value if an instance is null and return the instance if it's not. The code would look like something like this:</p>
<pre><code> return instance ?? new MyClass("Default");
</code></pre>
<p>But what if I would like to use the null-coalescing operator to also check if the MyClass.MyValue is set?</p>
| [
{
"answer_id": 349096,
"author": "Simon",
"author_id": 15371,
"author_profile": "https://Stackoverflow.com/users/15371",
"pm_score": 6,
"selected": true,
"text": "public class TestClass\n{\n public static TestClass operator ??(TestClass test1, TestClass test2)\n {\n return test1;\n }\n}\n"
},
{
"answer_id": 1763397,
"author": "soniiic",
"author_id": 104435,
"author_profile": "https://Stackoverflow.com/users/104435",
"pm_score": -1,
"selected": false,
"text": "return instance.MyValue != null ? instance : new MyClass(\"Default\");\n"
},
{
"answer_id": 21051751,
"author": "Robert Levy",
"author_id": 518955,
"author_profile": "https://Stackoverflow.com/users/518955",
"pm_score": 2,
"selected": false,
"text": "if (points != null) {\n var next = points.FirstOrDefault();\n if (next != null && next.X != null) return next.X;\n} \nreturn -1;\n var bestValue = points?.FirstOrDefault()?.X ?? -1;\n"
},
{
"answer_id": 60977574,
"author": "xr280xr",
"author_id": 263832,
"author_profile": "https://Stackoverflow.com/users/263832",
"pm_score": 0,
"selected": false,
"text": "Nullable<T> Nullable<T> Nullable<Guid> id1 = null;\nGuid id2 = id1 ?? Guid.NewGuid();\n id1 Nullable<Guid> Guid Nullable<T> explicit T Nullable<T> ?? public struct MyType<T>\n{\n private bool _hasValue;\n internal T _value;\n\n public MyType(T value)\n {\n this._value = value;\n this._hasValue = true;\n }\n\n public T Or(T altValue)\n {\n if (this._hasValue)\n return this._value;\n else\n return altValue;\n }\n}\n MyType<Guid> id1 = null;\nGuid id2 = id1.Or(Guid.Empty);\n id1 public class MyClass\n{\n public MyClass(string myValue)\n {\n MyValue = myValue;\n }\n\n public string MyValue { get; set; }\n}\n\npublic static class MyClassExtensions\n{ \n public static string Or(this MyClass myClass, string altVal)\n {\n if (myClass != null && myClass.MyValue != null)\n return myClass.MyValue;\n else\n return altVal;\n }\n}\n MyClass mc1 = new MyClass(null);\nstring requiredVal = mc1.Or(\"default\"); //Instead of mc1 ?? \"default\";\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936/"
] |
349,067 | <p>There's this Excel file I want users to be able to download from my server. There must be an easy way to initiate the download of the file after a click on the "Download" button... but I have no clue how to make that happen.</p>
<p>I have this so far: (VBscript and ASP)</p>
<pre><code><head>
<script type="text/javascript" src="overzicht.js"></script>
</head>
Set fs=Server.CreateObject("Scripting.FileSystemObject")
if (fs.FileExists("c:\file.xls"))=true then 'fake filename D:
response.write("<input type='button' value='Download Masterfile' class='button' onclick='exportmasterfile();' /><br />")
else
response.write("Masterfile not found. <br />")
end if
set fs=nothing
</code></pre>
<p>The javascript function is empty.</p>
| [
{
"answer_id": 349077,
"author": "Kablam",
"author_id": 42389,
"author_profile": "https://Stackoverflow.com/users/42389",
"pm_score": 5,
"selected": true,
"text": "function exportmasterfile()\n{ var url='../documenten/Master-File.xls'; \n window.open(url,'Download'); \n}\n"
},
{
"answer_id": 349078,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": 3,
"selected": false,
"text": "window.location = your_url\n"
},
{
"answer_id": 349118,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 4,
"selected": false,
"text": "location.href = your_url;\n location window"
},
{
"answer_id": 8981500,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 1,
"selected": false,
"text": "Function SaveUrlToFile(url, path)\n Dim xmlhttp, stream, fso\n\n ' Request the file from the internet.\n Set xmlhttp = CreateObject(\"MSXML2.XMLHTTP\")\n xmlhttp.open \"GET\", url, false\n xmlhttp.send\n If xmlhttp.status <> 200 Then\n SaveUrlToFile = false\n Exit Function\n End If\n\n ' Download the file into memory.\n Set stream = CreateObject(\"ADODB.Stream\")\n stream.Open\n stream.Type = 1 ' adTypeBinary\n stream.Write xmlhttp.responseBody\n stream.Position = 0 ' rewind stream\n\n ' Save from memory to physical file.\n Set fso = Createobject(\"Scripting.FileSystemObject\")\n If fso.Fileexists(path) Then\n fso.DeleteFile path\n End If\n stream.SaveToFile path\n\n SaveUrlToFile = true\nEnd Function\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42389/"
] |
349,075 | <p>Hey. I have a problem with the highlighter in ComboBox. Recently I had to gray out certain items in a ComboBox and I did that by manually (programitically) drawing strings in the <strong>ComboBox</strong>. In a .NET combobox under the <strong>DrawMode.NORMAL</strong>, the lighlighter will automatically come when you click the arrow and the backcolor of the highlighter will be kinna blue by default. The problem is when we move the mouse over a item the forecolor of the hovered item changes to white, but when we draw the items manually (<strong>DrawMode.OwnerDrawVariable</strong>) it dosen't work. Can you help me with this ??</p>
<p>This is how I grayed out items,</p>
<pre><code>private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
int index = e.Index;
CombinationEntry aFunction = comboBox1.Items[index] as CombinationEntry; //CombinationEntry is a custom object to hold the gray info. Gray if not available and black if available
if (aFunction.myIsAvailable)
{
e.Graphics.DrawString(aFunction.ToString(), new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, new Point(e.Bounds.X, e.Bounds.Y));
}
else
{
e.Graphics.DrawString(aFunction.ToString(), new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Gray, new Point(e.Bounds.X, e.Bounds.Y));
}
}
</code></pre>
| [
{
"answer_id": 350006,
"author": "Eric Rosenberger",
"author_id": 41624,
"author_profile": "https://Stackoverflow.com/users/41624",
"pm_score": 3,
"selected": false,
"text": "SystemColors.WindowText\n SystemColors.HighlightText\n e.State == DrawItemState.Selected ?\n SystemBrushes.HighlightText : SystemBrushes.WindowText\n SystemBrushes.GrayText\n comboBox1.Font\n"
},
{
"answer_id": 351681,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "if (e.State == ((DrawItemState.NoAccelerator | DrawItemState.NoFocusRect) | \n (DrawItemState.Selected | \n DrawItemState.NoAccelerator | \n DrawItemState.NoFocusRect)))\n{\n e.Graphics.DrawString(aFunction.ToString(), \n new Font(\"Arial\", 10, FontStyle.Regular,\n GraphicsUnit.Pixel), \n SystemBrushes.HighlightText, \n new Point(e.Bounds.X, e.Bounds.Y));\n}\n"
},
{
"answer_id": 5979859,
"author": "alex gil",
"author_id": 722038,
"author_profile": "https://Stackoverflow.com/users/722038",
"pm_score": 0,
"selected": false,
"text": "if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) e.State == DrawItemState.Selected"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
349,087 | <p>I have used checkbox column in gridview. I want to check status of that checkboxes. On click of a button it should be checked that if any checkbox is checked or not. If none checkbox is checked then it should display alert message that check checkbox first.</p>
| [
{
"answer_id": 349100,
"author": "I.devries",
"author_id": 6388,
"author_profile": "https://Stackoverflow.com/users/6388",
"pm_score": 2,
"selected": false,
"text": "if(document.getElementById('checkBoxId').checked) {\n //checked\n} else {\n //not checked\n}\n var inputs = document.getElementById('formId').getElementsByTagName('input');\nvar isChecked = false\nfor( var i = 0; i < inputs.length; i++) {\n if(inputs[i].type == 'checkbox' && inputs[i].checked) {\n isChecked = true;\n }\n}\n\nif(isChecked) {\n //at least one checkbox checked\n}\n"
},
{
"answer_id": 349130,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 2,
"selected": false,
"text": " flag = true;\n"
},
{
"answer_id": 349575,
"author": "Devashri B.",
"author_id": 43886,
"author_profile": "https://Stackoverflow.com/users/43886",
"pm_score": 3,
"selected": true,
"text": "function checkBoxselectedornot()\n{\n\n var frm=document.forms['aspnetForm'];\n var flag=false;\n for(var i=0;i<document.forms[0].length;i++)\n {\n if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)\n {\n if(document.forms[0].elements[i].checked)\n {\n flag=true\n } \n }\n } \n if (flag==true)\n {\n return true\n }else\n {\n alert('Please select at least one Event.')\n return false\n }\n\n}\n"
},
{
"answer_id": 350113,
"author": "Dave R.",
"author_id": 42841,
"author_profile": "https://Stackoverflow.com/users/42841",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\">\n function ClientCheck() {\n var valid = false;\n var gv = document.getElementById(\"GridView1\");\n\n for (var i = 0; i < gv.all.length; i++) {\n var node = gv.all[i];\n if (node != null && node.type == \"checkbox\" && node.checked) {\n valid = true;\n break;\n }\n }\n if (!valid) {\n alert(\"Invalid. Please select a checkbox to continue.\");\n }\n\n return valid;\n }\n</script>\n GridView for checkbox checked valid valid GridView TemplateField LinkButton <asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"False\" DataSourceID=\"ObjectDataSource1\">\n <Columns>\n <asp:TemplateField HeaderText=\"Button Field\" ShowHeader=\"False\">\n <ItemTemplate>\n <span onclick=\"return ClientCheck();\">\n <asp:LinkButton ID=\"LinkButton1\" runat=\"server\" CommandName=\"IDClick\" Text='<%# Eval(\"YourDataSourceItem\") %>'></asp:LinkButton>\n </span>\n </ItemTemplate>\n </asp:TemplateField>\n // ...your remaining columns...\n TemplateField span onclick ClientCheck CustomValidator"
},
{
"answer_id": 3210113,
"author": "Amit",
"author_id": 387412,
"author_profile": "https://Stackoverflow.com/users/387412",
"pm_score": 0,
"selected": false,
"text": " <script type=\"text/javascript\" language=\"javascript\">\n function CheckboxSelect() {\n\n var LIntCtr;\n var LIntSelectedCheckBoxes = 0;\n\n for (LIntCtr = 0; LIntCtr < document.forms[0].elements.length; LIntCtr++) {\n if ((document.forms[0].elements[LIntCtr].type == 'checkbox') && (document.forms[0].elements[LIntCtr].name.indexOf('chkID') > -1)) {\n if (document.forms[0].elements[LIntCtr].checked == true) {\n LIntSelectedCheckBoxes = parseInt(LIntSelectedCheckBoxes) + 1;\n }\n }\n }\n if (parseInt(LIntSelectedCheckBoxes) == 0) {\n alert('User(s) Must Be Selected For operation !');\n return false;\n }\n }\n </script>\n"
},
{
"answer_id": 12525909,
"author": "Ronak",
"author_id": 1688062,
"author_profile": "https://Stackoverflow.com/users/1688062",
"pm_score": 2,
"selected": false,
"text": " protected void OnCheckedChanged(object sender, EventArgs e)\n {\n bool flag = false;\n\n foreach (GridViewRow row in Grid_InvoiceGarden.Rows)\n {\n CheckBox chkItem = (CheckBox)row.FindControl(\"chkSelect\");\n if (chkItem.Checked)\n flag = true;\n }\n if (flag == true)\n {\n btnUpdate.Visible = true;\n }\n else\n {\n btnUpdate.Visible = false;\n } \n }\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43886/"
] |
349,092 | <p>I need to have one column as the primary key and another to auto increment an order number field. Is this possible?</p>
<p>EDIT: I think I'll just use a composite number as the order number. Thanks anyways.</p>
| [
{
"answer_id": 349137,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 6,
"selected": true,
"text": "CREATE TABLE [dbo].[Foo](\n [FooId] [int] IDENTITY(1,1) NOT NULL,\n [BarId] [int] IDENTITY(1,1) NOT NULL\n)\n Msg 2744, Level 16, State 2, Line 1\nMultiple identity columns specified for table 'Foo'. Only one identity column per table is allowed.\n"
},
{
"answer_id": 12099074,
"author": "Ali Karaca",
"author_id": 1417214,
"author_profile": "https://Stackoverflow.com/users/1417214",
"pm_score": 2,
"selected": false,
"text": "create table #tblStudent\n(\n ID int primary key identity(1,1),\n Number UNIQUEIDENTIFIER DEFAULT NEWID(),\n Name nvarchar(50)\n)\n insert into #tblStudent(Name) values('Ali')\n\nselect * from #tblStudent\n"
},
{
"answer_id": 21754022,
"author": "NiL",
"author_id": 564603,
"author_profile": "https://Stackoverflow.com/users/564603",
"pm_score": 0,
"selected": false,
"text": "create trigger UpdateSecondTableIdentity\nOn TableName For INSERT\nas\nupdate TableName\nset SecondIdentityColumn = 1000000+@@IDENTITY\nwhere ForstId = @@IDENTITY;\n"
},
{
"answer_id": 22814247,
"author": "benkevich",
"author_id": 1160745,
"author_profile": "https://Stackoverflow.com/users/1160745",
"pm_score": 5,
"selected": false,
"text": "--Create the Test schema\nCREATE SCHEMA Test ;\nGO\n\n-- Create a sequence\nCREATE SEQUENCE Test.SORT_ID_seq\n START WITH 1\n INCREMENT BY 1 ;\nGO\n\n-- Create a table\nCREATE TABLE Test.Foo\n (PK_ID int IDENTITY (1,1) PRIMARY KEY,\n SORT_ID int not null DEFAULT (NEXT VALUE FOR Test.SORT_ID_seq));\nGO\n\nINSERT INTO Test.Foo VALUES ( DEFAULT )\nINSERT INTO Test.Foo VALUES ( DEFAULT )\nINSERT INTO Test.Foo VALUES ( DEFAULT )\n\nSELECT * FROM Test.Foo \n\n-- Cleanup\n--DROP TABLE Test.Foo\n--DROP SEQUENCE Test.SORT_ID_seq\n--DROP SCHEMA Test\n"
},
{
"answer_id": 25899018,
"author": "Neha Verma",
"author_id": 3746019,
"author_profile": "https://Stackoverflow.com/users/3746019",
"pm_score": -1,
"selected": false,
"text": " create trigger [applicationstatus_insert] on [ApplicationStatus] after insert as \n update [Applicationstatus] \n set [Applicationstatus].applicationnumber =(applicationstatusid+ 4000000) \n from [Applicationstatus] \n inner join inserted on [applicationstatus].applicationstatusid = inserted.applicationstatusid\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23230/"
] |
349,094 | <p>I've been having an agruement with a friend that Mason (Perl) is not a framework, but a templating language. I feel Mason for Perl does what JSP does for Java (as an analogy, not pure technical comparison). From what I know, JSP is not a framework and I feel neither is Mason. When I looked up wikipedia <a href="http://en.wikipedia.org/wiki/Mason_%28Perl%29" rel="noreferrer">Mason (Perl)</a>, I see that the main site says it is a web application framework written in Perl while the discussion page contests it.</p>
<p>Any pointers on why it is/ it is not a framework?</p>
<p>Update based on comments from ysth:
For a framework, I feel it should at least make db access easy, manage sessions, basic security that a webapp would need, templating and code reuse (or libraries that make basic tasks easy).</p>
| [
{
"answer_id": 349124,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 2,
"selected": false,
"text": "HTML::Template Mason %ARGS %INIT mod_perl CGI Class::DBI DBIx::Perlish"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11541/"
] |
349,108 | <p>What is the correct way of retrieving maximum values of all columns in a table with a single query? Thanks.</p>
<p>Clarification: the same query should work on any table, i.e. the column names are not to be hard-coded into it.</p>
| [
{
"answer_id": 349115,
"author": "gnud",
"author_id": 27204,
"author_profile": "https://Stackoverflow.com/users/27204",
"pm_score": 3,
"selected": false,
"text": "SELECT max(col1) as max_col1, max(col2) as max_col2 FROM `table`;\n"
},
{
"answer_id": 349163,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "select max(c1),max(c2),max(c3),max(c4),max(c5)\nfrom (\n select 1 c1, 1 c2, 1 c3, 1 c4, 1 c5 from dual where 0\n union all\n select * from arbitrary5columntable\n) foo;\n"
},
{
"answer_id": 349191,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 1,
"selected": true,
"text": "$table = \"aTableName\";\n$columnsResult = mysql_query(\"SHOW COLUMNS FROM $table\");\n\n$maxValsSelect = \"\";\nwhile ($aColumn = mysql_fetch_assoc($columnsResult)) {\n if (strlen($maxValsSelect) > 0) {\n //Seperator\n $maxValsSelect .= \", \";\n } \n\n $maxValsSelect .= \"MAX(\" . $aColumn['Field'] . \") AS '\" . $aColumn['Field'] . \"'\";\n} \n\n//Complete the query\n$maxValsQuery = \"SELECT $maxValsSelect FROM $table\";\n$maxValsResult = mysql_query($maxValsQuery);\n\n//process the results....\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27122/"
] |
349,119 | <p>I have implemented tracing based on System.Diagnostics. </p>
<p>I am also using a System.Diagnostics.TextWriterTraceListener, and hooked the whole trace up to a MOSS 2007 Web Application. </p>
<p>The trace for some reason is trying to (a) create the log file, and/or (b) write to the log file using <strong>the user that is currently browsing the SharePoint site</strong> , is there any way to configure the logging to use a particular user account instead?</p>
| [
{
"answer_id": 349801,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "var wic = WindowsIdentity.Impersonate(IntPtr.Zero); // \"revert to self\"\n/* LOG GOES HERE K */\nwic.Undo(); // return to impersonation\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41291/"
] |
349,126 | <p>I'm running an upgrade script against a database hosted in Microsoft SQL Server. It's taking a while. Some of the queries are not worth optimising any further, for various reasons.</p>
<p>I'm the only person using this database: Is there a way that I can tell SQL Server to not bother with transactions/locking?</p>
<p>For instance, on a DELETE ... WHERE, does SQL need to get exclusive locks on the rows it's about to delete? If so, can I tell it not to bother, since this is the only running query?</p>
| [
{
"answer_id": 349193,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": true,
"text": "WITH (TABLOCKX)"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
349,127 | <p>My university refused to allow us to access out mail via POP or IMAP etc so I want to write a GTK based C app that sits in my notifcation area and does the job of a mail client notifier. Because I can't use anything like POP or IMAP, what would be a good way to do it? I guess I could scrape the HTML and look for a tag that is only present in unread mail or something?</p>
<p>Any Ideas?</p>
| [
{
"answer_id": 349177,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 0,
"selected": false,
"text": "WWW::Mechanize WWW::Mechanize"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
349,142 | <p>I am developing a multi-threaded application in Cocoa. The main thread takes values from the user, and when a button is clicked I invoke a secondary thread in which a long calculation takes place. Now from this thread I have to return the output of every step of the calculation to the main thread. I want to periodically send data from one thread to the other. I can't find any simple example that does this. Any ideas?</p>
| [
{
"answer_id": 350196,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 1,
"selected": false,
"text": "performSelectorOnMainThread:withObject:waitUntilDone:"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
349,155 | <p>For example, if you type something in upper-right google/yahoo search box in firefox there will be some kind 'suggested auto complete' sort of thing. </p>
<p>Another example is in youtube search box and Stackoverflow tags edit box just below this question preview. How do they work? What technology behind 'em?</p>
| [
{
"answer_id": 71302803,
"author": "Grogu",
"author_id": 12687061,
"author_profile": "https://Stackoverflow.com/users/12687061",
"pm_score": 0,
"selected": false,
"text": "$(function () {\nvar availableTags = [\n\"ActionScript\",\n\"AppleScript\",\n\"Asp\",\n\"BASIC\",\n\"C\",\n\"C++\",\n\"Clojure\",\n\"COBOL\",\n\"ColdFusion\",\n\"Erlang\",\n\"Fortran\",\n\"Groovy\",\n\"Haskell\",\n\"Java\",\n\"JavaScript\",\n\"Lisp\",\n\"Perl\",\n\"PHP\",\n\"Python\",\n\"Ruby\",\n\"Scala\",\n\"Scheme\"\n];\n$(\".sbx-custom__input\").autocomplete({\nsource: availableTags\n});\n}); <!--jqueryui-->\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/ui/1.13.1/jquery-ui.js\"></script>\n\n<!--autocompletejs-->\n<script src=\"https://cdn.jsdelivr.net/npm/@tarekraafat/autocomplete.js@10.2.6/dist/autoComplete.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@tarekraafat/autocomplete.js@10.2.6/dist/css/autoComplete.min.css\">\n\n\n<!--input-->\n<input class=\"sbx-custom__input\" autocomplete=\"on\" required=\"required\" placeholder=\"autocomplete...\">"
},
{
"answer_id": 73080810,
"author": "ahmetsokmen",
"author_id": 19166238,
"author_profile": "https://Stackoverflow.com/users/19166238",
"pm_score": 0,
"selected": false,
"text": " $(\"#Name\").autocomplete({\n source: function (request, response) {\n var prefix = { Name: request.term};\n $.ajax({\n url: '@Url.Action(\"FilterMastersByName\", \"JsonResult\")',\n data: JSON.stringify(prefix),\n dataType: \"json\",\n type: \"POST\",\n contentType: \"application/json; charset=utf-8\",\n success: function (data) {\n response($.map(data, function (item) {\n return item;\n }))\n },\n error: function (response) {\n alert(response.responseText);\n },\n failure: function (response) {\n alert(response.responseText);\n }\n });\n },\n select: function (e, i) {\n var abc=i.item.val;\n let a = document.createElement('a');\n a.href = `/Home/GetMasterById?masterId=${abc}`;\n a.click();\n\n },\n minLength: 1\n });\n });\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38515/"
] |
349,156 | <p>What's the regex to match a square bracket? I'm using <code>\\]</code> in a pattern in <code>eregi_replace</code>, but it doesn't seem to be able to find a <code>]</code>...</p>
| [
{
"answer_id": 349178,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 3,
"selected": false,
"text": "<?php\n $hay = \"ab]cd\";\n echo eregi_replace(\"\\]\", \"e\", $hay);\n?>\n abecd\n"
},
{
"answer_id": 349180,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 6,
"selected": true,
"text": "\\] \\ \\\\["
},
{
"answer_id": 349249,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": " '\\['\n \"\\[\" <\\s*(?:br|p)\\s*\\/?\\s*\\>\\s*\\[\n [ <br> <p>"
},
{
"answer_id": 349281,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 1,
"selected": false,
"text": "@\"\\[\"\n \"\\\\[\"\n"
},
{
"answer_id": 349865,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "/ [\\]] /x;\n\n/ \\] /x;\n / (\\w*) ( [\\d\\]] ) /x;\n\n/ (\\w*) ( \\d | \\] ) /x;\n \"[\\\\]]\" \"\\\\]\""
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44257/"
] |
349,172 | <p>I'm thinking about SEDA. We design at the moment an application (which is running on a server as a service) which must be multithreaded and message / event based.</p>
<p>The SEDA idea is very intresting and should match. But I cannot find articles etc. writing about experiences made with it. </p>
<p>My question(s) now is(are): </p>
<ul>
<li><p>Do you use ActiveMQ, MSMQ to implement the queues or do you have a self written class which acts as queue? We have written once a thread-safe FIFO Queue class which is very helpful in a multithreaded environment.</p></li>
<li><p>Fit's the threadpool class of .NET for this or did you implement an own Threadpool / sheduler ?</p></li>
</ul>
<p>Are there any traps / good practices?</p>
| [
{
"answer_id": 349178,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 3,
"selected": false,
"text": "<?php\n $hay = \"ab]cd\";\n echo eregi_replace(\"\\]\", \"e\", $hay);\n?>\n abecd\n"
},
{
"answer_id": 349180,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 6,
"selected": true,
"text": "\\] \\ \\\\["
},
{
"answer_id": 349249,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": " '\\['\n \"\\[\" <\\s*(?:br|p)\\s*\\/?\\s*\\>\\s*\\[\n [ <br> <p>"
},
{
"answer_id": 349281,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 1,
"selected": false,
"text": "@\"\\[\"\n \"\\\\[\"\n"
},
{
"answer_id": 349865,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "/ [\\]] /x;\n\n/ \\] /x;\n / (\\w*) ( [\\d\\]] ) /x;\n\n/ (\\w*) ( \\d | \\] ) /x;\n \"[\\\\]]\" \"\\\\]\""
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43532/"
] |
349,175 | <p>I need to convert a list (or a dict) into a comma-separated list for passing to another language.</p>
<p>Is there a nicer way of doing this than:</p>
<pre><code> result = ''
args = ['a', 'b', 'c', 'd']
i = 0
for arg in args:
if i != 0: result += arg
else: result += arg + ', '
i += 1
result = 'function (' + result + ')
</code></pre>
<p>Thanks,
Dan</p>
| [
{
"answer_id": 349182,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "', '.join(args)"
},
{
"answer_id": 349197,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 5,
"selected": true,
"text": "'function(%s)' % ', '.join(args)\n 'function(a, b, c, d)'\n"
},
{
"answer_id": 351629,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "result = 'function (%s)' % ', '.join(map(str,args))\n Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: sequence item 0: expected string, int found\n >>> d = {'d':5, 'f':6.0, 'r':\"BOB\"}\n>>> ','.join(d)\n'r,d,f'\n >>> d = {'d':5, 'f':6.0, 'r':\"BOB\"}\n>>> result = 'function (%s)' % ', '.join(map(str, d.values()))\n>>> result\n'function (BOB, 5, 6.0)'\n >>> l = list()\n>>> for val in d.values():\n... try:\n... v = float(val) #half-decent way of checking if something is an int, float, boolean\n... l.append(val) #if it was, then append the original type to the list\n... except:\n... #wasn't a number, assume it's a string and surround with quotes\n... l.append(\"\\\"\" + val + \"\\\"\")\n...\n>>> result = 'function (%s)' % ', '.join(map(str, l))\n>>> result\n'function (\"BOB\", 5, 6.0)'\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] |
349,192 | <p>In a multi-threaded program running on a multi-cpu machine do I need to access shared state ( _data in the example code below) using volatile read/writes to ensure correctness.</p>
<p>In other words, can heap objects be cached on the cpu?</p>
<p>Using the example below and assuming multi-threads will access the GetValue and Add methods, I need ThreadA to be able to add data (using the Add Method) and ThreadB to be able to see/get that added data immediately (using the GetValue method). So do I need to add volatile reads/writes to _data to ensure this? Basically I don’t want to added data to be cached on ThreadA’s cpu.</p>
<p>/ I am not Locking (enforcing exclusive thread access) as the code needs to be ultra-fast and I am not removing any data from _data so I don’t need to lock _data.</p>
<p>Thanks.</p>
<p>**** Update ****************************</p>
<p>Obviously you guys think going lock-free using this example is bad idea. But what side effects or exceptions could I face here?</p>
<p>Could the Dictionary type throw an exception if 1 thread is iterating the values for read and another thread is iterating the values for update? Or would I just experience “dirty reads” (which would be fine in my case)?</p>
<p>**** End Update ****************************</p>
<pre><code>public sealed class Data
{
private volatile readonly Dictionary<string, double> _data = new Dictionary<string, double>();
public double GetVaule(string key)
{
double value;
if (!_data.TryGetValue(key, out value))
{
throw new ArgumentException(string.Format("Key {0} does not exist.", key));
}
return value;
}
public void Add(string key, double value)
{
_data.Add(key, value);
}
public void Clear()
{
_data.Clear();
}
}
</code></pre>
<hr>
<p>Thanks for the replies. Regarding the locks, the methods are pretty much constantly called by mulitple threads so my problem is with contested locks not the actual lock operation.</p>
<p>So my question is about cpu caching, can heap objects (the _data instance field) be cached on a cpu? Do i need the access the _data field using volatile reads/writes?</p>
<p>/Also, I am stuck with .Net 2.0.</p>
<p>Thanks for your help.</p>
| [
{
"answer_id": 349239,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "ReaderWriterLockSlim"
},
{
"answer_id": 349245,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "Dictionary<TKey, TValue> ReaderWriterLockSlim"
},
{
"answer_id": 349374,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 2,
"selected": false,
"text": "public void Add(string key, double value)\n{\n _data.Add(key, value);\n}\n"
},
{
"answer_id": 936130,
"author": "Adam Robinson",
"author_id": 82187,
"author_profile": "https://Stackoverflow.com/users/82187",
"pm_score": 3,
"selected": false,
"text": "volatile volatile bool volatile readonly Dictionary<>"
},
{
"answer_id": 3792594,
"author": "tia",
"author_id": 397807,
"author_profile": "https://Stackoverflow.com/users/397807",
"pm_score": 1,
"selected": false,
"text": "volatile volatile volatile lock"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
349,204 | <p>I've written a simple control which basically displays a few words with an image next to it.</p>
<p>I want the containing items to strech when the parent form is resized and as you can see from my commented out code, I don't want to use a loop as it flickers.</p>
<p>Any idea on how to get the items to grow and shrink with the form in a nice way?</p>
<pre><code> public class IconListBox : FlowLayoutPanel {
private const int ITEM_PADDING = 2;
private const int MAX_IMAGE_SIZE = 64;
List<FlowLayoutPanel> _listItems;
public IconListBox() {
this.SizeChanged += new EventHandler(IconListBox_SizeChanged);
this.AutoScroll = true;
this.HorizontalScroll.Enabled = false;
this.HorizontalScroll.Visible = false;
this.VerticalScroll.Enabled = true;
this.VerticalScroll.Visible = true;
_listItems = new List<FlowLayoutPanel>();
}
void IconListBox_SizeChanged(object sender, EventArgs e) {
//foreach (FlowLayoutPanel item in _listItems) {
// item.Width = this.Width - 10;
//}
}
public void AddItem(string itemText) {
PictureBox pic = new PictureBox();
pic.Image = MyWave.Properties.Resources.mywave_icon;
pic.Width = pic.Height = MAX_IMAGE_SIZE;
pic.SizeMode = PictureBoxSizeMode.Normal;
pic.Enabled = false;
FlowLayoutPanel p = new FlowLayoutPanel();
p.Width = this.Width;
p.Height = pic.Image.Height + (ITEM_PADDING * 4);
p.BackColor = Color.White;
p.Padding = new Padding(ITEM_PADDING);
p.Margin = new Padding(0);
Label l = new Label();
l.Margin = new Padding(10, 5, 0, 0);
l.Width = this.Width - ITEM_PADDING - MAX_IMAGE_SIZE;
l.Height = p.Height - (ITEM_PADDING * 2);
l.Text = itemText;
l.Enabled = false;
//l.BorderStyle = BorderStyle.FixedSingle;
p.Controls.Add(pic);
p.Controls.Add(l);
p.MouseEnter += new EventHandler(p_MouseEnter);
p.MouseLeave += new EventHandler(p_MouseLeave);
p.MouseClick += new MouseEventHandler(p_MouseClick);
this.Controls.Add(p);
_listItems.Add(p);
p.Anchor = AnchorStyles.Right;
}
void p_MouseClick(object sender, MouseEventArgs e) {
//throw new NotImplementedException();
}
void p_MouseLeave(object sender, EventArgs e) {
((Panel)sender).BackColor = Color.White;
}
void p_MouseEnter(object sender, EventArgs e) {
((Panel)sender).BackColor = Color.LightBlue;
}
public void AddItem(string itemText, Image icon) {
}
}
</code></pre>
| [
{
"answer_id": 349244,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 3,
"selected": true,
"text": "foreach SuspendLayout() ResumeLayout() this.SuspendLayout();\n\nforeach (FlowLayoutPanel item in _listItems) \n{\n item.Width = this.Width - 10;\n}\n\nthis.ResumeLayout();\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
349,206 | <p>I'm trying to find the actual class of a django-model object, when using model-inheritance.</p>
<p>Some code to describe the problem:</p>
<pre><code>class Base(models.model):
def basemethod(self):
...
class Child_1(Base):
pass
class Child_2(Base):
pass
</code></pre>
<p>If I create various objects of the two Child classes and the create a queryset containing them all:</p>
<pre><code>Child_1().save()
Child_2().save()
(o1, o2) = Base.objects.all()
</code></pre>
<p>I want to determine if the object is of type Child_1 or Child_2 in basemethod, I can get to the child object via o1.child_1 and o2.child_2 but that reconquers knowledge about the childclasses in the baseclass.</p>
<p>I have come up with the following code:</p>
<pre><code>def concrete_instance(self):
instance = None
for subclass in self._meta.get_all_related_objects():
acc_name = subclass.get_accessor_name()
try:
instance = self.__getattribute__(acc_name)
return instance
except Exception, e:
pass
</code></pre>
<p>But it feels brittle and I'm not sure of what happens when if I inherit in more levels.</p>
| [
{
"answer_id": 349235,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": -1,
"selected": false,
"text": "aMethod() class Base(models.model):\n def aMethod(self):\n # base class implementation.\n\nclass Child_1(Base):\n def aMethod(self):\n # Child_1 override of base class behavior.\n\nclass Child_2(Base):\n def aMethod(self):\n supert( Child_2, self ).aMethod() # Invoke the base class version\n # Child_2 extension to base class behavior.\n"
},
{
"answer_id": 349494,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 5,
"selected": true,
"text": "Base.object.all() from django.contrib.contenttypes.models import ContentType\n\nclass Base(models.Model):\n content_type = models.ForeignKey(ContentType,editable=False,null=True)\n\n def save(self):\n if(not self.content_type):\n self.content_type = ContentType.objects.get_for_model(self.__class__)\n self.save_base()\n\n def as_leaf_class(self):\n content_type = self.content_type\n model = content_type.model_class()\n if(model == Base):\n return self\n return model.objects.get(id=self.id)\n if Base.content_type.model_class()"
},
{
"answer_id": 2936296,
"author": "Dhiana Deva",
"author_id": 353728,
"author_profile": "https://Stackoverflow.com/users/353728",
"pm_score": 0,
"selected": false,
"text": "class Cache(models.Model):\n valor = models.DecimalField(max_digits=9, decimal_places=2, blank= True, null= True)\n evento=models.ForeignKey(Evento)\n def __unicode__(self):\n return u'%s: %s' % (self.evento, self.valor)\n class Meta:\n verbose_name='Cachê'\n verbose_name_plural='Cachês'\n def is_cb(self):\n try:\n self.cache_bilheteria\n return True\n except self.DoesNotExist:\n return False\n def is_co(self):\n try:\n self.cache_outro\n return True\n except self.DoesNotExist:\n return False\n"
},
{
"answer_id": 8478666,
"author": "Jan Pöschko",
"author_id": 643091,
"author_profile": "https://Stackoverflow.com/users/643091",
"pm_score": 3,
"selected": false,
"text": "from model_utils.managers import InheritanceManager\n\nclass Base(models.Model):\n objects = InheritanceManager()\n\n# ...\n\nBase.objects.all().select_subclasses() # returns instances of child classes\n"
},
{
"answer_id": 17443716,
"author": "alexpirine",
"author_id": 1042635,
"author_profile": "https://Stackoverflow.com/users/1042635",
"pm_score": 0,
"selected": false,
"text": "from django.contrib.contenttypes.models import ContentType\nfrom django.db import models\n\ndef ParentClass(models.Model):\n superclass = models.CharField(max_length = 255, blank = True)\n\n def save(self, *args, **kwargs):\n if not self.superclass:\n self.superclass = ContentType.objects.get_for_model(self.__class__)\n\n super(ParentClass, self).save(*args, **kwargs)\n\n def getChild(self):\n s = getattr(self, self.superclass)\n if hasattr(s, 'pk'):\n return s\n else:\n return None\n\nclass Child1(ParentClass):\n pass\n\nclass Child2(ParentClass):\n pass\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6093/"
] |
349,238 | <p>I had a realtivley simple ajax application, which I have broken up to be more modular. The code is at the link below, and what I have mainly done is add the GetRecordSet function and allowed fetchcompelte to take a variable for which layer to put data in. It should work fine in thery. When I put alert()s in, the code seems to execute, except for inside either of the if clauses in fetchcomplete.</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22558" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22558</a></p>
<p>This is the code for get_records.php, which again seems like it should be fine</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22559" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22559</a></p>
<p>and this is the original index php file</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22560" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22560</a></p>
| [
{
"answer_id": 349235,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": -1,
"selected": false,
"text": "aMethod() class Base(models.model):\n def aMethod(self):\n # base class implementation.\n\nclass Child_1(Base):\n def aMethod(self):\n # Child_1 override of base class behavior.\n\nclass Child_2(Base):\n def aMethod(self):\n supert( Child_2, self ).aMethod() # Invoke the base class version\n # Child_2 extension to base class behavior.\n"
},
{
"answer_id": 349494,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 5,
"selected": true,
"text": "Base.object.all() from django.contrib.contenttypes.models import ContentType\n\nclass Base(models.Model):\n content_type = models.ForeignKey(ContentType,editable=False,null=True)\n\n def save(self):\n if(not self.content_type):\n self.content_type = ContentType.objects.get_for_model(self.__class__)\n self.save_base()\n\n def as_leaf_class(self):\n content_type = self.content_type\n model = content_type.model_class()\n if(model == Base):\n return self\n return model.objects.get(id=self.id)\n if Base.content_type.model_class()"
},
{
"answer_id": 2936296,
"author": "Dhiana Deva",
"author_id": 353728,
"author_profile": "https://Stackoverflow.com/users/353728",
"pm_score": 0,
"selected": false,
"text": "class Cache(models.Model):\n valor = models.DecimalField(max_digits=9, decimal_places=2, blank= True, null= True)\n evento=models.ForeignKey(Evento)\n def __unicode__(self):\n return u'%s: %s' % (self.evento, self.valor)\n class Meta:\n verbose_name='Cachê'\n verbose_name_plural='Cachês'\n def is_cb(self):\n try:\n self.cache_bilheteria\n return True\n except self.DoesNotExist:\n return False\n def is_co(self):\n try:\n self.cache_outro\n return True\n except self.DoesNotExist:\n return False\n"
},
{
"answer_id": 8478666,
"author": "Jan Pöschko",
"author_id": 643091,
"author_profile": "https://Stackoverflow.com/users/643091",
"pm_score": 3,
"selected": false,
"text": "from model_utils.managers import InheritanceManager\n\nclass Base(models.Model):\n objects = InheritanceManager()\n\n# ...\n\nBase.objects.all().select_subclasses() # returns instances of child classes\n"
},
{
"answer_id": 17443716,
"author": "alexpirine",
"author_id": 1042635,
"author_profile": "https://Stackoverflow.com/users/1042635",
"pm_score": 0,
"selected": false,
"text": "from django.contrib.contenttypes.models import ContentType\nfrom django.db import models\n\ndef ParentClass(models.Model):\n superclass = models.CharField(max_length = 255, blank = True)\n\n def save(self, *args, **kwargs):\n if not self.superclass:\n self.superclass = ContentType.objects.get_for_model(self.__class__)\n\n super(ParentClass, self).save(*args, **kwargs)\n\n def getChild(self):\n s = getattr(self, self.superclass)\n if hasattr(s, 'pk'):\n return s\n else:\n return None\n\nclass Child1(ParentClass):\n pass\n\nclass Child2(ParentClass):\n pass\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
349,248 | <p>I am using <code>cvs -tag -b "abcdefg"</code> command to tag-branch in my CVS. My CSV repo has an empty directory "obj" in every folder. </p>
<p>Whenever I use the command <code>cvs co -r "abcdefg" REPO</code>, I get a complete repo minus the empty folders. I tried using <code>-f</code> option too but it did not work. What is the way to get out of this?</p>
| [
{
"answer_id": 349275,
"author": "Ulf Lindback",
"author_id": 30354,
"author_profile": "https://Stackoverflow.com/users/30354",
"pm_score": 0,
"selected": false,
"text": "co -P\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20958/"
] |
349,250 | <p>As the question says, it just escaped my memory how to display xml in javascript, I want to display some source xml within an div on a page, that sits next to the processed result of the xml in another div.</p>
<p>Can't remember if there was an equivalent to javascript's escape to convert entities on the client </p>
<p><strong>Note</strong>: the xml files are served as is from the server, so I need a client side solution</p>
<p><strong>Note</strong>: the main problem is XML doesn't render correctly in most browsers, all the brackets and attributes disappear, leaving you with text that doesn't look like xml</p>
| [
{
"answer_id": 349264,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 2,
"selected": false,
"text": "<iframe src=\"/myapp/Document1.xml\"><iframe src=\"/myapp/Document2.xml\">\n getElementById(\"myDiv\").innerText = ajax.response;\n"
},
{
"answer_id": 349295,
"author": "Daniel Silveira",
"author_id": 1100,
"author_profile": "https://Stackoverflow.com/users/1100",
"pm_score": 4,
"selected": true,
"text": "XML XML iframe frame DIV HTTP iframe Content-Type: text/xml XML XML XML2HTML HTML PRE XML < > XML The browser XML HTML"
},
{
"answer_id": 349298,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\">\n<!--\n function xml_to_string(xml_node)\n {\n if (xml_node.xml)\n return xml_node.xml;\n else if (XMLSerializer)\n {\n var xml_serializer = new XMLSerializer();\n return xml_serializer.serializeToString(xml_node);\n }\n else\n {\n alert(\"ERROR: Extremely old browser\");\n return \"\";\n }\n }\n\n // display in alert box\n alert(xml_to_string(my_xml));\n\n // display in an XHTML element\n document.getElementById(\"my-element\").innerHTML = xml_to_string(my_xml);\n-->\n</script>\n"
},
{
"answer_id": 349504,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "function insertLiteral(literalString, targetElement)\n{\n var textNode = document.createTextNode(literalString);\n targetElement.appendChild(textNode)\n return textNode;\n}\n\n// test it (for the example, I assume #targetDiv is there but empty)\nvar xmlString = \"<this><is_some><xml with='attributes' /></is_some></this>\";\nvar targetElement = document.getElementById(\"targetDiv\");\nvar xmlTextNode = insertLiteral(xmlString, targetElement);\n #targetDiv #targetDiv {\n font-family: fixed;\n white-space: pre;\n}\n"
},
{
"answer_id": 349669,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 4,
"selected": false,
"text": "textarea"
},
{
"answer_id": 24585829,
"author": "cat",
"author_id": 712124,
"author_profile": "https://Stackoverflow.com/users/712124",
"pm_score": 2,
"selected": false,
"text": "var xml = document.getElementById('svg_element').innerHTML;\ndocument.getElementById('svg_pre').innerText = xml; \n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
349,251 | <p>I need to get a count of the number of files in a directory. I could get the names of all the files in the directory using <code>System.IO.Directory.GetFiles()</code> and take the length of that array but that takes too long on large directories. Is there a way to get just the count without having to get the names?</p>
| [
{
"answer_id": 349412,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 3,
"selected": false,
"text": "LARGE_INTEGER i1, i2; \n\nQueryPerformanceCounter(&i1); \n\nint count = IO::Directory::GetFiles(L\"c:\\\\windows\\\\system32\")->Length;\n\nQueryPerformanceCounter(&i2);\n\n__int64 result = i2.QuadPart - i1.QuadPart;\n LARGE_INTEGER i1, i2;\n\nQueryPerformanceCounter(&i1);\n\nintcount = QDir(\"c:/windows/system32\").entryList(QDir::Files).count();\n\nQueryPerformanceCounter(&i2);\n\n__int64 result += i2.QuadPart - i1.QuadPart;\n"
},
{
"answer_id": 349415,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 2,
"selected": false,
"text": "FindFirstFile FindNextFile"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
349,256 | <p>When is a good idea to save information in a XML file and when in a own-format file?</p>
<p>For XML (or other standard) I see:</p>
<ul>
<li>(+) Standard format.</li>
<li>(-) It's tedious to hand modify.</li>
</ul>
<p>For own-format files I see:</p>
<ul>
<li>(-) We need to build a own-parser (non-standard).</li>
<li>(+) It can be easy to hand modify the files.</li>
</ul>
| [
{
"answer_id": 350555,
"author": "Rich",
"author_id": 28442,
"author_profile": "https://Stackoverflow.com/users/28442",
"pm_score": 0,
"selected": false,
"text": "<?xml-stylesheet type=\"text/xsl\" href=\"config-documentation.xsl\"?>\n"
},
{
"answer_id": 350700,
"author": "Adam Jaskiewicz",
"author_id": 35322,
"author_profile": "https://Stackoverflow.com/users/35322",
"pm_score": 0,
"selected": false,
"text": "key:value"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] |
349,257 | <p>Is there a way to detect the true border, padding and margin of elements from Javascript code? If you look at the following code:</p>
<pre><code><html>
<head>
<style>
<!--
.some_class {
padding-left: 2px;
border: 2px solid green;
}
-->
</style>
<script>
<!--
function showDetails()
{
var elem = document.getElementById("my_div");
alert("elem.className=" + elem.className);
alert("elem.style.padding=" + elem.style.padding);
alert("elem.style.paddingLeft=" + elem.style.paddingLeft);
alert("elem.style.margin=" + elem.style.margin);
alert("elem.style.marginLeft=" + elem.style.marginLeft);
alert("elem.style.border=" + elem.style.border);
alert("elem.style.borderLeft=" + elem.style.borderLeft);
}
-->
</script>
</head>
<body>
<div id="my_div" class="some_class" style="width: 300px; height: 300px; margin-left: 4px;">
some text here
</div>
<button onclick="showDetails();">show details</button>
</body>
</html>
</code></pre>
<p>you can see, if you click the button, that the padding is not reported right. Only the properties defined directly through "style" are reported back, those defined through a CSS class are not reported.</p>
<p>Is there a way to get back the final values of these properties? I mean the values obtained after all CSS settings are computed and applied by the browser.</p>
| [
{
"answer_id": 1280733,
"author": "vsync",
"author_id": 104380,
"author_profile": "https://Stackoverflow.com/users/104380",
"pm_score": 3,
"selected": false,
"text": "var $elm = $('.box');\nvar hPadding = $elm.outerWidth() - $elm.width();\nvar vPadding = $elm.outerHeight() - $elm.height();\nvar hBorder = $elm.outerWidth() - $elm.innerWidth();\nvar vBorder = $elm.outerHeight() - $elm.innerHeight();\n\nconsole.log(\"Horizontal padding & border: \", hPadding);\nconsole.log(\"Vertical padding & border: \", vPadding);\nconsole.log(\"Horizontal border: \", hBorder);\nconsole.log(\"Vertical border: \", vBorder); .box{ \n width: 50%;\n padding:10vw; \n border:10px solid red; \n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div class='box'></div> var elm = $('.box');\nconsole.log(\"padding left (PX): \", elm.css(\"paddingLeft\")); .box { \n padding:0 50px 0 5vw; \n border: 2px solid green; \n width: 300px; \n height: 300px; \n margin-left: 4px;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div class=\"box\">some text here</div>"
},
{
"answer_id": 15126616,
"author": "YuC",
"author_id": 1682256,
"author_profile": "https://Stackoverflow.com/users/1682256",
"pm_score": 4,
"selected": false,
"text": "style <div id=\"target\" style=\"color:#ddd;margin:10px\">test</div> <style/> var div = document.getElementById(\"target\");\nvar style = div.currentStyle || window.getComputedStyle(div);\ndisplay(\"Current marginTop: \" + style.marginTop);\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11384/"
] |
349,260 | <p>I used a query a few weeks ago in MySQL that described a table and suggested possible improvements to its structure. For example, if I have an int field but only the numbers 1-3 in that field, it will suggest set(1,2,3) as the type.</p>
<p>I think I was using phpMyAdmin but I've been through all the functions I can find - Analyze, Describe, Explain, Optimize, etc - to no avail. I can't for the life of me remember what the query was!</p>
| [
{
"answer_id": 349273,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "SELECT *\nFROM `table_name`\nPROCEDURE ANALYSE ( ) \n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37947/"
] |
349,286 | <p>I am using ASP.NET membership for the authentication of my web app. This worked great for me. I now have to implement password expiration.</p>
<p>If the password has expired the user should be redirected to <code>ChangePassword</code> screen and should not be allowed access to any other part of the application without changing the password.</p>
<p>There are many aspx pages. One solution could be to redirect to the <code>ChangePassword</code> screen <code>OnInit</code> of every aspx if the password has expired. Is there any other solutions or recommendations.</p>
<p>Thanks,
Jai</p>
| [
{
"answer_id": 1177869,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "LoggingIn LastPasswordChangedDate ChangePassword"
},
{
"answer_id": 6705094,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 5,
"selected": false,
"text": "global.asax void Application_PostAuthenticateRequest(object sender, EventArgs e)\n{\n if (this.User.Identity.IsAuthenticated)\n {\n // get user\n MembershipUser user = Membership.GetUser();\n\n // has their password expired?\n if (user != null\n && user.LastPasswordChangedDate.Date.AddDays(90) < DateTime.Now.Date\n && !Request.Path.EndsWith(\"/Account/ChangePassword.aspx\"))\n {\n Server.Transfer(\"~/ChangePassword.aspx\");\n }\n }\n}\n"
},
{
"answer_id": 9879682,
"author": "rethenhouser2",
"author_id": 605913,
"author_profile": "https://Stackoverflow.com/users/605913",
"pm_score": 3,
"selected": false,
"text": "void Application_PostAuthenticateRequest(object sender, EventArgs e)\n {\n if (this.User.Identity.IsAuthenticated)\n {\n // get user \n MembershipUser user = Membership.GetUser();\n\n // has their password expired? \n if (user != null\n && user.LastPasswordChangedDate.AddMinutes(30) < DateTime.Now\n && !Request.Path.EndsWith(\"/Account/ChangePassword.aspx\"))\n {\n Server.Transfer(\"~/Account/ChangePassword.aspx\");\n }\n }\n } \n"
},
{
"answer_id": 10727546,
"author": "Leniel Maccaferri",
"author_id": 114029,
"author_profile": "https://Stackoverflow.com/users/114029",
"pm_score": 2,
"selected": false,
"text": "AuthorizeAttribute OnAuthorization public class ExpiredPasswordAttribute : AuthorizeAttribute\n{\n public override void OnAuthorization(AuthorizationContext filterContext)\n {\n IPrincipal user = filterContext.HttpContext.User;\n\n if(user != null && user.Identity.IsAuthenticated)\n {\n MembershipUser membershipUser = Membership.GetUser();\n\n if (PasswordExpired) // Your logic to check if password is expired...\n {\n filterContext.HttpContext.Response.Redirect(\n string.Format(\"~/{0}/{1}?{2}\", MVC.SGAccount.Name, MVC.SGAccount.ActionNames.ChangePassword,\n \"reason=expired\"));\n\n }\n }\n\n base.OnAuthorization(filterContext);\n }\n}\n AccountController"
},
{
"answer_id": 35927716,
"author": "Tommy Snacks",
"author_id": 4141751,
"author_profile": "https://Stackoverflow.com/users/4141751",
"pm_score": 0,
"selected": false,
"text": "void Application_PostAuthenticateRequest(object sender, EventArgs e)\n {\n if (this.User.Identity.IsAuthenticated)\n {\n WisewomanDBContext db = new WisewomanDBContext();\n\n // get user\n var userId = User.Identity.GetUserId();\n ApplicationUser user = db.Users.Find(userId);\n\n // has their password expired?\n if (user != null && user.PasswordExpires <= DateTime.Now.Date\n && !Request.Path.EndsWith(\"/Manage/ChangePassword\"))\n {\n Response.Redirect(\"~/Manage/ChangePassword\");\n }\n\n db.Dispose();\n }\n }\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44272/"
] |
349,291 | <p>How do I convert a datetime field in Grails to just date, with out capturing the time? I need to do this for comparison with system date. </p>
<pre><code>class Trip
{
String name
String city
Date startDate
Date endDate
String purpose
String notes
static constraints = {
name(maxLength: 50, blank: false)
startDate(validator: {return (it >= new Date())}) // This won't work as it compares the time as well
city(maxLength: 30, blank: false)
}
}
</code></pre>
| [
{
"answer_id": 349421,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 1,
"selected": false,
"text": "* format (required) - The format to use for the date\n* date (required) - The date object to format\n"
},
{
"answer_id": 349445,
"author": "LenW",
"author_id": 41292,
"author_profile": "https://Stackoverflow.com/users/41292",
"pm_score": 0,
"selected": false,
"text": "startDate(validator: {d = new Date(); return (it..d) >= 0})\n"
},
{
"answer_id": 349601,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 4,
"selected": true,
"text": "Grails|Groovy|Java java.util.Date java.util.Calendar DateTimeUtil static Date class DateTimeUtil {\n\n // ...\n\n public static Date getToday() {\n return setMidnight(new Date())\n }\n\n public static Date getTomorrow() {\n return (getToday() + 1) as Date\n }\n\n public static Date setMidnight(Date theDate) {\n Calendar cal = Calendar.getInstance()\n cal.setTime(theDate)\n cal.set(Calendar.HOUR_OF_DAY, 0)\n cal.set(Calendar.MINUTE, 0)\n cal.set(Calendar.SECOND, 0)\n cal.set(Calendar.MILLISECOND, 0)\n cal.getTime()\n }\n\n //...\n\n}\n startDate(validator: {return (it.after(DateTimeUtil.today))}) //Groovy-ism - today implicitly invokes `getToday()` \n"
},
{
"answer_id": 352053,
"author": "Omnipotent",
"author_id": 11193,
"author_profile": "https://Stackoverflow.com/users/11193",
"pm_score": 2,
"selected": false,
"text": "<g:datePicker name=\"startDate\" value=\"${trip?.startDate}\" years=\"${years}\" precision=\"day\" />\n"
},
{
"answer_id": 12900273,
"author": "A.J. Brown",
"author_id": 264016,
"author_profile": "https://Stackoverflow.com/users/264016",
"pm_score": 2,
"selected": false,
"text": "startdate.clearTime() def setStartDate( Date date ) {\n date.clearTime()\n startDate = date\n}\n"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
] |
349,322 | <p>I've been handing a design for a webpage which I'm trying to implement correctly. This design contains navigation elements which are partially or entirely duplicated all over the page - in particular, links to the main 3 categories for navigation are present on the page no less than 4 times.</p>
<p>I'm no web design expert, but I don't like the idea of having the same content duplicated in the html. Can I use CSS so that my html contains a single list of navigation links in a sane format, but the standard browser view contains multiple partial duplicates?</p>
<p>(Also, assuming this is possible, is it a good idea? or would I be better just getting used to the idea that my html is going to contain the same links 4 times?)</p>
<p>EDIT: Actually generating the nav links is not an issue; I was looking to clean up the output html</p>
| [
{
"answer_id": 15838669,
"author": "ScottS",
"author_id": 369707,
"author_profile": "https://Stackoverflow.com/users/369707",
"pm_score": 5,
"selected": true,
"text": "<a></a> a a a[href='#oneUrl']:before {\n content: 'your anchor text';\n}\n position: fixed"
},
{
"answer_id": 15870759,
"author": "nexus_07",
"author_id": 1787585,
"author_profile": "https://Stackoverflow.com/users/1787585",
"pm_score": -1,
"selected": false,
"text": "<!--#include virtual=\"path to file/include-file.html\" -->"
},
{
"answer_id": 54200117,
"author": "Timo Huovinen",
"author_id": 175071,
"author_profile": "https://Stackoverflow.com/users/175071",
"pm_score": 4,
"selected": false,
"text": ".duplicate::before,\n.duplicate::after {\n content:attr(title);\n display:block;\n} <div class=\"duplicate\" title=\"text to duplicate\"></div>"
},
{
"answer_id": 62109254,
"author": "Nanoo",
"author_id": 13319571,
"author_profile": "https://Stackoverflow.com/users/13319571",
"pm_score": 0,
"selected": false,
"text": "::before ::after <script>"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12744/"
] |
349,348 | <p>I have the following JavaScript code:
<a href="http://www.nomorepasting.com/getpaste.php?pasteid=22561" rel="nofollow noreferrer">Link</a></p>
<p>In which the function makewindows does not seem to be working.</p>
<p>It does actual create a window, however the html either contains what is quotes, or if I change it to</p>
<pre><code>child1.document.write(json_encode($row2["ARTICLE_DESC"]));
</code></pre>
<p>to create a blank html page.</p>
<p>I moved this function to my main JavaScript file to include because I was getting errors before, but now no HTML is presented in the popupwindow. Is this because I am not retrieving article_Desc in thest3.php?</p>
<p>The other 2 files used are here:
<a href="http://www.nomorepasting.com/getpaste.php?pasteid=22562" rel="nofollow noreferrer">link</a>
and <a href="http://www.nomorepasting.com/getpaste.php?pasteid=22563" rel="nofollow noreferrer">test3.php</a></p>
| [
{
"answer_id": 349363,
"author": "Irmantas",
"author_id": 43182,
"author_profile": "https://Stackoverflow.com/users/43182",
"pm_score": 2,
"selected": false,
"text": "child1.document.write(<?php echo json_encode($row2[\"ARTICLE_DESC\"]); ?>);\n"
},
{
"answer_id": 349448,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": -1,
"selected": false,
"text": " ...\n <p><a href='#' onclick='makewindows('\"\n . json_encode($row2[\"ARTICLE_DESC\"])\n . \"'); return false;'>...\n\n\nfunction makewindows(html){\n child1 = window.open (\"about:blank\");\n child1.document.write(html);\n child1.document.close();\n}\n"
},
{
"answer_id": 349470,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 3,
"selected": true,
"text": "<?php ?> child1.document.write(<?php echo json_encode($row2[\"ARTICLE_DESC\"]); ?>);\n write"
}
] | 2008/12/08 | [
"https://Stackoverflow.com/questions/349348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.