qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
221,267
|
<p>What is the simplest way of copying symbolic links on the Mac?</p>
<p>A python or perl solution would be preferred, but any solution would be a help.</p>
<p>I am copying frameworks for an installation package, and need the links to be maintained</p>
|
[
{
"answer_id": 221305,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": false,
"text": "import os, stat\nif stat.S_ISLNK(os.lstat('foo').st_mode):\n src = os.readlink('source')\n os.symlink(src, 'destination')\n cp -R source destination\n from subprocess import call\ncall(['cp', '-R', 'source', 'destination'])\n"
},
{
"answer_id": 221316,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 7,
"selected": true,
"text": "cp -R source destination\n"
},
{
"answer_id": 42466294,
"author": "n1000",
"author_id": 2075003,
"author_profile": "https://Stackoverflow.com/users/2075003",
"pm_score": 4,
"selected": false,
"text": "cp -a\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259/"
] |
221,273
|
<p>I've been given a prototype/mockup of a grid written in html and javascript (via ExtJS) that I now need to implement within an ASP.net web application. Does anyone have any pointers as to how to pass data to the grid (to a GroupingStore, specifically). </p>
<p>I'd rather not have a proliferation of web services or helper pages returning XML/JSON so if there's a way to use Client callbacks or Page Methods (Can't you tell I'm not particularly familiar with either - buzzword bingo!) or somesuch, that would be preferred.</p>
<p>Please, no recommendations that I use jQuery, the built-in ASP.net grid, or any other UI framework. The use of the ExtJS grid has been mandated by the powers that be, so that's the grid I'm using, for better or worse :)</p>
|
[
{
"answer_id": 221360,
"author": "tobinharris",
"author_id": 1136215,
"author_profile": "https://Stackoverflow.com/users/1136215",
"pm_score": 2,
"selected": true,
"text": "http://mysite.com/query.aspx?sql=select * from orders where status = 'open'\n void Page_Load(object sender, EventArgs e)\n{\n Response.ContentType=\"text/json\"; \n DataTable contents = ExecuteDataTable(Request[\"sql\"]);\n Response.Write( JRockSerialize( contents ) );\n Response.End();\n}\n DataTable url:"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7872/"
] |
221,277
|
<p>I'm trying to do XHTML DOM parsing with JTidy, and it seems to be rather counterintuitive task. In particular, there's a method to parse HTML:</p>
<pre><code>Node Tidy.parse(Reader, Writer)
</code></pre>
<p>And to get the <body /> of that Node, I assume, I should use</p>
<pre><code>Node Node.findBody(TagTable)
</code></pre>
<p>Where should I get an instance of that TagTable? (Constructor is protected, and I haven't found a factory to produce it.)</p>
<p>I use JTidy 8.0-SNAPSHOT.</p>
|
[
{
"answer_id": 221327,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": false,
"text": "parseDOM org.w3c.dom.Document Document document = Tidy.parseDOM(reader, writer);\nNode body = document.getElementsByTagName(\"body\").item(0);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764/"
] |
221,283
|
<p>I like to keep my shell sessions named with useful titles as I work, this helps me keep track of what I'm using each of the many tabs for.</p>
<p>Currently to rename a session I double click its name on the tabbed part of the console - is there any command that I can use to do this from within the shell? It would save me a bit of time.</p>
<p>thanks in advance</p>
<p>edit :-
I am using KDE's Konsole shell.</p>
|
[
{
"answer_id": 221293,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "echo -n \"\\033]0;New Window Title\\007\"\n"
},
{
"answer_id": 222216,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": true,
"text": "dcop $KONSOLE_DCOP_SESSION renameSession \"I am renamed!\"\n"
},
{
"answer_id": 10402391,
"author": "cyber-monk",
"author_id": 468304,
"author_profile": "https://Stackoverflow.com/users/468304",
"pm_score": 1,
"selected": false,
"text": "$> sudo apt-get install xtitle\n ...\n$> xtitle --title wow it worked!\n or simply\n$> xtitle this is great\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22061/"
] |
221,287
|
<p>I've noticed that when you create a web service object (inheriting from SoapHttpClientProtocol) and you use the Async method, it makes the callback on the Windows GUI thread.</p>
<ol>
<li>Does anyone know how this works?</li>
<li>How can I achieve the same thing.</li>
</ol>
<p>I figure this will save me having to check for InvokeRequired in my GUI forms if I am sure the callback is always occurring on the gui thread.</p>
|
[
{
"answer_id": 221506,
"author": "Richard Nienaber",
"author_id": 9539,
"author_profile": "https://Stackoverflow.com/users/9539",
"pm_score": 2,
"selected": false,
"text": " public partial class AsyncTest : Form\n {\n static void Main()\n {\n Application.Run(new AsyncTest());\n }\n\n AsyncOperation _operation;\n SynchronizationContext _context;\n TextBox _textBox;\n public AsyncTest()\n {\n _operation = AsyncOperationManager.CreateOperation(null);\n _context = WindowsFormsSynchronizationContext.Current;\n _textBox = new TextBox();\n this.Controls.Add(_textBox);\n new Thread(AsyncThread).Start();\n }\n\n void AsyncThread()\n {\n _operation.Post(GuiThread, null);\n _context.Post(GuiThread, null);\n }\n\n void GuiThread(object state)\n {\n _textBox.Text = _textBox.InvokeRequired ? \"Didn't work\" : \"It Worked\";\n }\n }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9539/"
] |
221,292
|
<p>I have a problem with Crystal Reports 8. When exporting a report from my application, Crystal Reports <strong>sometimes</strong> freezes. The progress windows just stays, saying X of X records exported.</p>
<ol>
<li>Smaller reports with less data are more likley to freeze.</li>
<li>Faster workstations (P4, Core2) tend to freeze much more often, sometimes every second try. On older workstations (< P2) no freezing happens at all, or at least once every one or two days.</li>
<li>The export format (rtf, pdf, html, rpt) does not influence the freezing behavior.</li>
<li>The same report can be successfully exported multiple times with excactly the same data, but eventually it will freeze.</li>
<li>No freezing happens on Windows Vista (!)</li>
</ol>
<p>Is there a way to stop this or at least a way to predict a freeze?</p>
|
[
{
"answer_id": 1321068,
"author": "Daniel Rikowski",
"author_id": 23368,
"author_profile": "https://Stackoverflow.com/users/23368",
"pm_score": 3,
"selected": true,
"text": "WaitForSingleObject(?, INFINITE) WaitForSingleObject"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
221,294
|
<p>I want a single number that represents the current date and time, like a <a href="https://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">Unix timestamp</a>.</p>
|
[
{
"answer_id": 221297,
"author": "daveb",
"author_id": 11858,
"author_profile": "https://Stackoverflow.com/users/11858",
"pm_score": 13,
"selected": true,
"text": "Date.now Date.now()\n + Date.prototype.valueOf + new Date()\n valueOf new Date().valueOf()\n Date.now if (!Date.now) {\n Date.now = function() { return new Date().getTime(); }\n}\n getTime new Date().getTime()\n Math.floor(Date.now() / 1000)\n Date.now() / 1000 | 0\n performance.now var isPerformanceSupported = (\n window.performance &&\n window.performance.now &&\n window.performance.timing &&\n window.performance.timing.navigationStart\n);\n\nvar timeStampInMs = (\n isPerformanceSupported ?\n window.performance.now() +\n window.performance.timing.navigationStart :\n Date.now()\n);\n\nconsole.log(timeStampInMs, Date.now());"
},
{
"answer_id": 221357,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 7,
"selected": false,
"text": "var time = Date.now || function() {\n return +new Date;\n};\n\ntime();\n"
},
{
"answer_id": 221771,
"author": "aemkei",
"author_id": 28150,
"author_profile": "https://Stackoverflow.com/users/28150",
"pm_score": 7,
"selected": false,
"text": "var timestamp = Number(new Date()); // current time as number\n"
},
{
"answer_id": 807980,
"author": "Tom Viner",
"author_id": 15890,
"author_profile": "https://Stackoverflow.com/users/15890",
"pm_score": 6,
"selected": false,
"text": "console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch"
},
{
"answer_id": 1714649,
"author": "Kiragaz",
"author_id": 208609,
"author_profile": "https://Stackoverflow.com/users/208609",
"pm_score": -1,
"selected": false,
"text": "time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);\n"
},
{
"answer_id": 5036460,
"author": "xer0x",
"author_id": 47604,
"author_profile": "https://Stackoverflow.com/users/47604",
"pm_score": 9,
"selected": false,
"text": "+new Date\n Date.now()\n"
},
{
"answer_id": 5971324,
"author": "Daithí",
"author_id": 288644,
"author_profile": "https://Stackoverflow.com/users/288644",
"pm_score": 8,
"selected": false,
"text": "var unix = Math.round(+new Date()/1000);\n var milliseconds = new Date().getTime();\n"
},
{
"answer_id": 10428184,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 5,
"selected": false,
"text": "Date.getTime() floor (new Date).getTime() / 1000\n Date.valueOf() Date.getTime()"
},
{
"answer_id": 11446757,
"author": "GottZ",
"author_id": 1519836,
"author_profile": "https://Stackoverflow.com/users/1519836",
"pm_score": 7,
"selected": false,
"text": "Date.now() /1000 |0\n |0 Math.floor() Math.floor() Math.floor(Date.now() /1000);\n new Date/1e3|0\n Date.now() if (!Date.now) {\n Date.now = function now() {\n return new Date().getTime();\n };\n}\n Math.floor(Date.now() / 1000)\n const relativeTime = (() => {\n const start = Date.now();\n return () => Date.now() - start;\n})();\n $.now() $.now() (new Date).getTime() |0 | Date.now() / 1000 Math.floor() Date.now Date.now()"
},
{
"answer_id": 12536800,
"author": "live-love",
"author_id": 436341,
"author_profile": "https://Stackoverflow.com/users/436341",
"pm_score": 6,
"selected": false,
"text": "function displayTime() {\n var str = \"\";\n\n var currentTime = new Date()\n var hours = currentTime.getHours()\n var minutes = currentTime.getMinutes()\n var seconds = currentTime.getSeconds()\n\n if (minutes < 10) {\n minutes = \"0\" + minutes\n }\n if (seconds < 10) {\n seconds = \"0\" + seconds\n }\n str += hours + \":\" + minutes + \":\" + seconds + \" \";\n if(hours > 11){\n str += \"PM\"\n } else {\n str += \"AM\"\n }\n return str;\n}\n"
},
{
"answer_id": 15434736,
"author": "VisioN",
"author_id": 1249581,
"author_profile": "https://Stackoverflow.com/users/1249581",
"pm_score": 6,
"selected": false,
"text": "var timestamp = $.now();\n (new Date).getTime()"
},
{
"answer_id": 16456126,
"author": "SBotirov",
"author_id": 1942750,
"author_profile": "https://Stackoverflow.com/users/1942750",
"pm_score": 4,
"selected": false,
"text": "currentTime = Date.now() || +new Date()\n"
},
{
"answer_id": 16666424,
"author": "deepakssn",
"author_id": 1411589,
"author_profile": "https://Stackoverflow.com/users/1411589",
"pm_score": 5,
"selected": false,
"text": "function getTimeStamp() {\n var now = new Date();\n return ((now.getMonth() + 1) + '/' +\n (now.getDate()) + '/' +\n now.getFullYear() + \" \" +\n now.getHours() + ':' +\n ((now.getMinutes() < 10)\n ? (\"0\" + now.getMinutes())\n : (now.getMinutes())) + ':' +\n ((now.getSeconds() < 10)\n ? (\"0\" + now.getSeconds())\n : (now.getSeconds())));\n}\n"
},
{
"answer_id": 17398791,
"author": "Anoop P S",
"author_id": 1338683,
"author_profile": "https://Stackoverflow.com/users/1338683",
"pm_score": 4,
"selected": false,
"text": "var a = new Date(UNIX_timestamp*1000);\nvar hour = a.getUTCHours();\nvar min = a.getUTCMinutes();\nvar sec = a.getUTCSeconds();\n"
},
{
"answer_id": 19602603,
"author": "Vicky Gonsalves",
"author_id": 1548301,
"author_profile": "https://Stackoverflow.com/users/1548301",
"pm_score": 3,
"selected": false,
"text": "var timeStamp=event.timestamp || new Date().getTime();\n"
},
{
"answer_id": 22756677,
"author": "Belldandu",
"author_id": 3271268,
"author_profile": "https://Stackoverflow.com/users/3271268",
"pm_score": 5,
"selected": false,
"text": "Math.floor(Date.now() / 1000); // current time in seconds\n var _ = require('lodash'); // from here https://lodash.com/docs#now\n_.now();\n"
},
{
"answer_id": 23261705,
"author": "DevC",
"author_id": 973699,
"author_profile": "https://Stackoverflow.com/users/973699",
"pm_score": 3,
"selected": false,
"text": "timestamp : parseInt(new Date().getTime()/1000, 10)\n"
},
{
"answer_id": 23816968,
"author": "Saucier",
"author_id": 2174320,
"author_profile": "https://Stackoverflow.com/users/2174320",
"pm_score": 1,
"selected": false,
"text": "var pad = function(int) { return int < 10 ? 0 + int : int; };\nvar timestamp = new Date();\n\n timestamp.day = [\n pad(timestamp.getDate()),\n pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.\n timestamp.getFullYear()\n ];\n\n timestamp.time = [\n pad(timestamp.getHours()),\n pad(timestamp.getMinutes()),\n pad(timestamp.getSeconds())\n ];\n\ntimestamp.now = parseInt(timestamp.day.join(\"\") + timestamp.time.join(\"\"));\nalert(timestamp.now);\n"
},
{
"answer_id": 28890441,
"author": "Rimian",
"author_id": 63810,
"author_profile": "https://Stackoverflow.com/users/63810",
"pm_score": 4,
"selected": false,
"text": "moment().unix();\n"
},
{
"answer_id": 28983302,
"author": "georgez",
"author_id": 2113279,
"author_profile": "https://Stackoverflow.com/users/2113279",
"pm_score": 4,
"selected": false,
"text": "var date = new Date();\nvar timestamp = +date;\n"
},
{
"answer_id": 29287521,
"author": "Eugene",
"author_id": 1062764,
"author_profile": "https://Stackoverflow.com/users/1062764",
"pm_score": 2,
"selected": false,
"text": "var my_timestamp = ~~(Date.now()/1000);"
},
{
"answer_id": 29299909,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Number(new Date()) 1000"
},
{
"answer_id": 29341730,
"author": "Muhammad Reda",
"author_id": 863380,
"author_profile": "https://Stackoverflow.com/users/863380",
"pm_score": 4,
"selected": false,
"text": "_.now var timestamp = _.now(); // in milliseconds\n"
},
{
"answer_id": 29600955,
"author": "jameslouiz",
"author_id": 3562401,
"author_profile": "https://Stackoverflow.com/users/3562401",
"pm_score": 3,
"selected": false,
"text": "var d = new Date();\nconsole.log(d.valueOf()); \n"
},
{
"answer_id": 30531157,
"author": "Kevinleary.net",
"author_id": 172870,
"author_profile": "https://Stackoverflow.com/users/172870",
"pm_score": 4,
"selected": false,
"text": "var time = process.hrtime();\nvar timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );\n /dist/css/global.css?v=245521377 245521377 hrtime()"
},
{
"answer_id": 31236206,
"author": "iter",
"author_id": 5046452,
"author_profile": "https://Stackoverflow.com/users/5046452",
"pm_score": 5,
"selected": false,
"text": "performance.now function time() { \n return performance.now() + performance.timing.navigationStart;\n}\n 1436140826653.139 Date.now 1436140826653"
},
{
"answer_id": 31401583,
"author": "FullStack",
"author_id": 3694557,
"author_profile": "https://Stackoverflow.com/users/3694557",
"pm_score": 5,
"selected": false,
"text": "moment.js moment().valueOf()\n moment().unix()\n moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()\n moment.js <script src=\"moment.js\"></script>\n<script>\n moment().valueOf();\n</script>\n"
},
{
"answer_id": 32845874,
"author": "blueberry0xff",
"author_id": 3059453,
"author_profile": "https://Stackoverflow.com/users/3059453",
"pm_score": 4,
"selected": false,
"text": "// The Current Unix Timestamp\n// 1443534720 seconds since Jan 01 1970. (UTC)\n\n// seconds\nconsole.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720\nconsole.log(Math.floor(Date.now() / 1000)); // 1443534720\nconsole.log(Math.floor(new Date().getTime() / 1000)); // 1443534720\n\n// milliseconds\nconsole.log(Math.floor(new Date().valueOf())); // 1443534720087\nconsole.log(Math.floor(Date.now())); // 1443534720087\nconsole.log(Math.floor(new Date().getTime())); // 1443534720087\n\n// jQuery\n// seconds\nconsole.log(Math.floor($.now() / 1000)); // 1443534720\n// milliseconds\nconsole.log($.now()); // 1443534720087 <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>"
},
{
"answer_id": 33028757,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": 4,
"selected": false,
"text": "console.log(clock.now);\n// returns 1444356078076\n\nconsole.log(clock.format(clock.now));\n//returns 10/8/2015 21:02:16\n\nconsole.log(clock.format(clock.now + clock.add(10, 'minutes'))); \n//returns 10/8/2015 21:08:18\n\nvar clock = {\n now:Date.now(),\n add:function (qty, units) {\n switch(units.toLowerCase()) {\n case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;\n case 'days' : val = qty * 1000 * 60 * 60 * 24; break;\n case 'hours' : val = qty * 1000 * 60 * 60; break;\n case 'minutes' : val = qty * 1000 * 60; break;\n case 'seconds' : val = qty * 1000; break;\n default : val = undefined; break;\n }\n return val;\n },\n format:function (timestamp){\n var date = new Date(timestamp);\n var year = date.getFullYear();\n var month = date.getMonth() + 1;\n var day = date.getDate();\n var hours = date.getHours();\n var minutes = \"0\" + date.getMinutes();\n var seconds = \"0\" + date.getSeconds();\n // Will display time in xx/xx/xxxx 00:00:00 format\n return formattedTime = month + '/' + \n day + '/' + \n year + ' ' + \n hours + ':' + \n minutes.substr(-2) + \n ':' + seconds.substr(-2);\n }\n};\n"
},
{
"answer_id": 33131028,
"author": "Valentin Podkamennyi",
"author_id": 5438323,
"author_profile": "https://Stackoverflow.com/users/5438323",
"pm_score": 5,
"selected": false,
"text": "Math.floor(new Date().getTime() / 1000) new Date / 1E3 | 0 getTime() | 0 Math.floor() 1E3 1000 1E3 var ts = new Date / 1E3 | 0;\n\nconsole.log(ts);"
},
{
"answer_id": 35087703,
"author": "Joaquinglezsantos",
"author_id": 5325015,
"author_profile": "https://Stackoverflow.com/users/5325015",
"pm_score": 6,
"selected": false,
"text": "console.log(new Date().toISOString());"
},
{
"answer_id": 36027644,
"author": "Jitendra Pawar",
"author_id": 4305683,
"author_profile": "https://Stackoverflow.com/users/4305683",
"pm_score": 5,
"selected": false,
"text": " var timestamp = new Date().getTime();\n console.log(timestamp);"
},
{
"answer_id": 44082035,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 6,
"selected": false,
"text": "Date.now(); //return 1495255666921\n Date.now(); new Date().getTime();\n"
},
{
"answer_id": 47810722,
"author": "Olemak",
"author_id": 3278654,
"author_profile": "https://Stackoverflow.com/users/3278654",
"pm_score": 4,
"selected": false,
"text": "Date.now()\n const currentTimestamp = (!Date.now ? +new Date() : Date.now());\n"
},
{
"answer_id": 49526664,
"author": "unknown123",
"author_id": 8590807,
"author_profile": "https://Stackoverflow.com/users/8590807",
"pm_score": 2,
"selected": false,
"text": "function getTimeStamp() {\n var now = new Date();\n return ((now.getMonth() + 1) + '/' +\n (now.getDate()) + '/' +\n now.getFullYear() + \" \" +\n now.getHours() + ':' +\n ((now.getMinutes() < 10)\n ? (\"0\" + now.getMinutes())\n : (now.getMinutes())) + ':' +\n ((now.getSeconds() < 10)\n ? (\"0\" + now.getSeconds())\n : (now.getSeconds())));\n}\n"
},
{
"answer_id": 51067600,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 6,
"selected": false,
"text": "Date.now() performance.now() function A() {\n return new Date().getTime();\n}\n\nfunction B() {\n return new Date().valueOf();\n}\n\nfunction C() {\n return +new Date();\n}\n\nfunction D() {\n return new Date()*1;\n}\n\nfunction E() {\n return Date.now();\n}\n\nfunction F() {\n return Number(new Date());\n}\n\nfunction G() {\n // this solution returns time counted from loading the page.\n // (and on Chrome it gives better precission)\n return performance.now(); \n}\n\n\n\n// TEST\n\nlog = (n,f) => console.log(`${n} : ${f()}`);\n\nlog('A',A);\nlog('B',B);\nlog('C',C);\nlog('D',D);\nlog('E',E);\nlog('F',F);\nlog('G',G); This snippet only presents code used in external benchmark"
},
{
"answer_id": 56202700,
"author": "cenkarioz",
"author_id": 6846195,
"author_profile": "https://Stackoverflow.com/users/6846195",
"pm_score": 4,
"selected": false,
"text": "new Date().toISOString()"
},
{
"answer_id": 59043796,
"author": "Ashish",
"author_id": 10943108,
"author_profile": "https://Stackoverflow.com/users/10943108",
"pm_score": 3,
"selected": false,
"text": "new Date().getTime(); + new Date(); and Date.now();\n new Date(\"11/01/2018\").getTime()\n"
},
{
"answer_id": 60489900,
"author": "Ganesh",
"author_id": 4060431,
"author_profile": "https://Stackoverflow.com/users/4060431",
"pm_score": 1,
"selected": false,
"text": "var currentTime = new Date();\nvar month = currentTime.getMonth() + 1;\nvar day = currentTime.getDate();\nvar year = currentTime.getFullYear();\n"
},
{
"answer_id": 65848448,
"author": "Flash Noob",
"author_id": 12106367,
"author_profile": "https://Stackoverflow.com/users/12106367",
"pm_score": 2,
"selected": false,
"text": " Date.now() \n new Date().getTime() \n new Date().valueOf()\n Math.floor(Date.now() / 1000)\n"
},
{
"answer_id": 70266631,
"author": "dazzafact",
"author_id": 1163485,
"author_profile": "https://Stackoverflow.com/users/1163485",
"pm_score": 3,
"selected": false,
"text": "//if you need 10 digits\n alert('timestamp '+ts());\nfunction ts() {\n return parseInt(Date.now()/1000);\n\n}"
},
{
"answer_id": 74412005,
"author": "RyadPasha",
"author_id": 9937620,
"author_profile": "https://Stackoverflow.com/users/9937620",
"pm_score": 0,
"selected": false,
"text": "/**\n * Equivalent to PHP's time(), which returns\n * current Unix timestamp.\n *\n * @param {string} unit - Unit of time to return.\n * - Use 's' for seconds and 'ms' for milliseconds.\n * @return {number}\n */\ntime(unit = 's') {\n return unit == 's' ? Math.floor(Date.now() / 1000) : Date.now()\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
221,307
|
<p>I've been scanning through all the popular js libraries, but I can't find one that has a width function for a DOM element that actually accounts for quirks mode in Internet Explorer. The issue is that padding and borders don't get counted in the the width when quirks mode is engaged. As far as I can tell this happens when the doctype is left out or the doctype is set to html 3.2.</p>
<p>Obviously I could just set the doctype to something standards compliant, but this script can be embedded anywhere so I don't have control over the doctype.</p>
<p>To break the problem down into smaller parts:</p>
<p>1) How do you detect quirks mode?
2) What's the best way to extract the border and padding from an element to compensate?</p>
<p>Example with prototype:</p>
<pre><code><html>
<head>
</head>
<body>
<div id="mydiv" style="width: 250px; pading-left: 1px; border: 2px black solid">hello</div>
<script>
alert($('mydiv').getWidth())
</script>
</body>
</html>
</code></pre>
<p>result:</p>
<p>253 (ff)
250 (ie)</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 221405,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 1,
"selected": false,
"text": "<div id=\"mydiv\" style=\"width: 100px; border-left: 100px black solid;\"> </div>\n $(document).ready(function() {\n alert(\"width=\" + $('#mydiv').width() \n + \" outerWidth=\" + $('#mydiv').outerWidth() \n + \" borderLeftWidth=\" + $('#mydiv').css(\"borderLeftWidth\"))\n});\n"
},
{
"answer_id": 221703,
"author": "Jeremy B.",
"author_id": 28567,
"author_profile": "https://Stackoverflow.com/users/28567",
"pm_score": 1,
"selected": false,
"text": "javascript:(function(){\n var mode=document.compatmode,m;if(mode){\n if(mode=='BackCompat')m='quirks';\n else if(mode=='CSS1Compat')m='Standard';\n else m='Almost Standard';\n alert('The page is rendering in '+m+' mode.');\n }\n})();\n"
},
{
"answer_id": 221895,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 3,
"selected": true,
"text": "document.compatMode\n <div id=\"mydiv\" style=\"width: 250px; padding-left: 1px; border: 2px black solid\">hello</div>\n\ndocument.getElementById('mydiv').offsetWidth\n//255 (standards) 250 (quirks)\n function compensateWidth( el, targetWidth ){\n\n var removeUnit = function( str ){\n if( str.indexOf('px') ){\n return str.replace('px','') * 1;\n }\n else { //because won't work for other units... one may wish to implement \n return 0;\n }\n }\n if(document.compatMode && document.compatMode==\"BackCompat\"){\n if(targetWidth && el.offsetWidth < targetWidth){\n el.style.width = targetWidth;\n }\n else if (el.currentStyle){\n var borders = removeUnit(el.currentStyle['borderLeftWidth']) + removeUnit(el.currentStyle['borderRightWidth']);\n var paddings = removeUnit(el.currentStyle['paddingLeft']) + removeUnit(el.currentStyle['paddingRight']);\n el.style.width = el.offsetWidth + borders + paddings +'px';\n }\n }\n\n}\n var div = document.getElementById('mydiv')\n// will try to calculate target width, but won't be able to work with units other than px\ncompensateWidth( div );\n\n//if you know what the width should be in standards mode\ncompensateWidth( div, 254 );\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29899/"
] |
221,311
|
<p>I have a sea of weighted nodes with edges linking clusters of nodes together. This graph follows the typical small world layout.</p>
<p>I wish to find a path finding algorithm, which isn't costly on processor power, to find a path along the best possible path where the nodes are the most favorably weighted, the fastest route is not the most important factor.
This algorithm, also takes into consideration load bearing, and traffic rerouting.</p>
<p>(sidenote: could neural networks be used here?)</p>
<p>Thanks</p>
<hr>
<p>I'm looking at <a href="http://www.scholarpedia.org/article/Ant_colony_optimization" rel="noreferrer"><strong>ACO</strong></a>. Is there anything better than ACO for this kind of problem?</p>
<hr>
<p>Right the <a href="http://en.wikipedia.org/wiki/A%2A" rel="noreferrer"><strong>A*</strong></a> algorithm finds the least cost or fastest route, without load balancing.</p>
<p>Lets say that the fastest or shortest route is not the most important route, what is more important is following a path where the weighted nodes have a certain value. no1.</p>
<p>no2. If using A* the traffic on that route gets overloaded then suddenly that path is redundant. So as cool as A* is, it doesnt have certain features that ACO ie inherent load balancing.</p>
<p>-- unless im mistaken and misunderstood A*</p>
<p>Then what beats ACO?</p>
<hr>
<p>It really looks like a show down between ACO and A* , there has been so much positive talk about A* , I will certainly look deeper into it.</p>
<p>Firstly in response to David; I can run ACO simulation in the back ground and come up with the best path, so yes there is an initial startup cost but the startup luckily isnt essential. So i can afford to run a simulation multiple times. The one real trouble is finding connected source and destination nodes. Whereas it seems A* will be able to do this quite easily. Now what happens when this network get dreadfully large like in millions of nodes. Will A* be able to scale easily?</p>
<p>I will research A* further. But I leave you with a last question!</p>
<p>Will A* be able to scale as well as Antnet (ACO)?</p>
|
[
{
"answer_id": 221454,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 3,
"selected": false,
"text": "A---1---B---1---C\n| |\n\\-------1-------/\n A---r---B---r---C\n| |\n\\-------r-------/\n r(NM) = k(NM) + users(NM) / 10\n r(NM) is the cost for a connection between N and M,\nk(NM) is the constant cost for a connection between N and M,\nusers(NM) is the number of objects using the connection\n"
},
{
"answer_id": 50149961,
"author": "Alexandr Zhytenko",
"author_id": 7831384,
"author_profile": "https://Stackoverflow.com/users/7831384",
"pm_score": 0,
"selected": false,
"text": "graph = {}\n\ngraph[\"start\"] = {}\ngraph[\"start\"][\"a\"] = 6\ngraph[\"start\"][\"b\"] = 2\ngraph[\"a\"] = {}\ngraph[\"a\"][\"finish\"] = 1\ngraph[\"b\"] = {}\ngraph[\"b\"][\"a\"] = 3\ngraph[\"b\"][\"finish\"] = 5\ngraph[\"finish\"] = {}\n\ninfinity = float(\"inf\")\ncosts = {}\ncosts[\"a\"] = 6\ncosts[\"b\"] = 2\ncosts[\"finish\"] = infinity\nprint \"The weight of each node is: \", costs\n\nparents = {}\nparents[\"a\"] = \"start\"\nparents[\"b\"] = \"start\"\nparents[\"finish\"] = None\n\nprocessed = []\n\ndef find_lowest_cost_node(costs):\n lowest_cost = float(\"inf\")\n lowest_cost_node = None\n for node in costs:\n cost = costs[node]\n if cost < lowest_cost and node not in processed:\n lowest_cost = cost\n lowest_cost_node = node\n return lowest_cost_node\n\nnode = find_lowest_cost_node(costs)\nprint \"Start: the lowest cost node is\", node, \"with weight\",\\\n graph[\"start\"][\"{}\".format(node)]\n\nwhile node is not None:\n cost = costs[node]\n print \"Continue execution ...\"\n print \"The weight of node {} is\".format(node), cost\n neighbors = graph[node]\n if neighbors != {}:\n print \"The node {} has neighbors:\".format(node), neighbors\n else:\n print \"It is finish, we have the answer: {}\".format(cost)\n for neighbor in neighbors.keys():\n new_cost = cost + neighbors[neighbor]\n if costs[neighbor] > new_cost:\n costs[neighbor] = new_cost\n parents[neighbor] = node\n processed.append(node)\n print \"This nodes we researched:\", processed\n node = find_lowest_cost_node(costs)\n if node is not None:\n print \"Look at the neighbor:\", node\n\n# to draw graph\nimport networkx\nG = networkx.Graph()\nG.add_nodes_from(graph)\nG.add_edge(\"start\", \"a\", weight=6)\nG.add_edge(\"b\", \"a\", weight=3)\nG.add_edge(\"start\", \"b\", weight=2)\nG.add_edge(\"a\", \"finish\", weight=1)\nG.add_edge(\"b\", \"finish\", weight=5)\n\nimport matplotlib.pyplot as plt\nnetworkx.draw(G, with_labels=True)\nplt.show()\n\nprint \"But the shortest path is:\", networkx.shortest_path(G, \"start\", \"finish\")\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
221,317
|
<p>I've created a custom search page with some defined options in my search scope.</p>
<p>I have a metadata mapped <code>jobtitle</code>, and added the search option to my custom search.</p>
<pre><code><Property name="JobTitle"
ManagedName="title"
ProfileURI="urn:schemas-microsoft-com:sharepoint:portal:profile:Title"/>
</code></pre>
<p>I want to change my managed name to <code>jobtitle</code>, because title doesn't hit the dutch word for jobtitle. I changed the managed name to <code>jobtitle</code>, after applying the changes it wouldn't change the label.</p>
<p>Anyone have an idea?</p>
|
[
{
"answer_id": 227583,
"author": "RedDeckWins",
"author_id": 1646,
"author_profile": "https://Stackoverflow.com/users/1646",
"pm_score": 1,
"selected": false,
"text": "xsl/xml"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28139/"
] |
221,320
|
<p>For a file containing the given class, SomeCoolClass, what would be the proper or standard filename?</p>
<pre>
1. somecoolclass.rb
2. some_cool_class.rb
3. some-cool-class.rb
4. SomeCoolClass.rb
</pre>
<p>or some other variation?</p>
<p>I noticed in the Ruby stdlib, versions 1, 2 and 3 are used.</p>
|
[
{
"answer_id": 221391,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 7,
"selected": true,
"text": "lowercase_and_underscore.rb lowercasenounderscore.rb"
},
{
"answer_id": 222178,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 3,
"selected": false,
"text": "# gem install my_cool_lib\nrequire 'my-cool-lib'\n\n# gem install MyCoolLib\nrequire 'my_cool_lib'\n # gem install my_cool_lib\nrequire 'my_cool_lib'\n\n# gem install my-cool-lib\nrequire 'my-cool-lib'\n"
},
{
"answer_id": 15222302,
"author": "Mike",
"author_id": 57481,
"author_profile": "https://Stackoverflow.com/users/57481",
"pm_score": 3,
"selected": false,
"text": "my-proj\n├── README\n├── lib\n│ └── some_cool_class.rb\n└── test\n └── some_cool_class_test.rb\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
221,345
|
<p>I am currently writing a system that stores meta data for around 140,000 ish images stored within a legacy image library that are being moved to cloud storage. I am using the following to get the jpg data...</p>
<pre><code>System.Drawing.Image image = System.Drawing.Image.FromFile("filePath");
</code></pre>
<p>Im quite new to image manipulation but this is fine for getting simple values like width, height, aspect ratio etc but what I cannot work out is how to retrieve the physical file size of the jpg expressed in bytes. Any help would be much appreciated.</p>
<p>Thanks</p>
<p>Final solution including an MD5 hash of the image for later comparison</p>
<pre><code>System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
if (image != null)
{
int width = image.Width;
int height = image.Height;
decimal aspectRatio = width > height ? decimal.divide(width, height) : decimal.divide(height, width);
int fileSize = (int)new System.IO.FileInfo(filePath).Length;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(fileSize))
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
Byte[] imageBytes = stream.GetBuffer();
System.Security.Cryptography.MD5CryptoServiceProvider provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
Byte[] hash = provider.ComputeHash(imageBytes);
System.Text.StringBuilder hashBuilder = new System.Text.StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
hashBuilder.Append(hash[i].ToString("X2"));
}
string md5 = hashBuilder.ToString();
}
image.Dispose();
}
</code></pre>
|
[
{
"answer_id": 221348,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 7,
"selected": true,
"text": " var fileLength = new FileInfo(filePath).Length; \n long jpegByteSize;\nusing (var ms = new MemoryStream(estimatedLength)) // estimatedLength can be original fileLength\n{\n image.Save(ms, ImageFormat.Jpeg); // save image to stream in Jpeg format\n jpegByteSize = ms.Length;\n }\n"
},
{
"answer_id": 221353,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 1,
"selected": false,
"text": "System.Drawing.Image int len = (new System.IO.FileInfo(sFullPath)).Length;\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12918/"
] |
221,346
|
<p>What is the arrow operator (<code>-></code>) a synonym for?</p>
|
[
{
"answer_id": 221351,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": true,
"text": "a->b\n\n(*a).b\n"
},
{
"answer_id": 221354,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "a->b (*a).b * . *a.b . *(a.b) -> *"
},
{
"answer_id": 221359,
"author": "Tetha",
"author_id": 17663,
"author_profile": "https://Stackoverflow.com/users/17663",
"pm_score": 4,
"selected": false,
"text": "foo->bar->baz = qux->croak\n"
},
{
"answer_id": 221367,
"author": "P-A",
"author_id": 4975,
"author_profile": "https://Stackoverflow.com/users/4975",
"pm_score": 6,
"selected": false,
"text": "-> . anObject aPointer SomeClass anObject = new SomeClass();\nSomeClass *aPointer = &anObject;\n (*aPointer).method();\n aPointer->method();\n *(aPointer.method()); // Not our intention!\n"
},
{
"answer_id": 4113619,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "auto f() -> int; // \"->\" means \"returns ...\"\n"
},
{
"answer_id": 55063340,
"author": "Tryb Ghost",
"author_id": 11056439,
"author_profile": "https://Stackoverflow.com/users/11056439",
"pm_score": 2,
"selected": false,
"text": "-> int* prt = &intVar;\n (*ptr).foo();\n *(ptr.foo()) ptr->foo();\n -> foo() -> myClass* ptr = &myClassMember;\nptr->myClassVar = 2; \n"
},
{
"answer_id": 56032844,
"author": "Zhang",
"author_id": 9250490,
"author_profile": "https://Stackoverflow.com/users/9250490",
"pm_score": 0,
"selected": false,
"text": "auto fun() -> int\n{\nreturn 100;\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4975/"
] |
221,365
|
<p>If I have a folder structure set up like this:</p>
<pre><code>~/Projects
emacs
package1
package1-helpers
package2
package2-helpers
package2-more-helpers
package3
package3-helpers
</code></pre>
<p>How do I add these folders:</p>
<ul>
<li>~/Projects/emacs</li>
<li>~/Projects/emacs/package1</li>
<li>~/Projects/emacs/package2</li>
<li>~/Projects/emacs/package3</li>
</ul>
<p>...to the <code>load-path</code> from my .emacs file?</p>
<p>I basically need a short automated version of this code:</p>
<pre><code>(add-to-list 'load-path "~/Projects/emacs")
(add-to-list 'load-path "~/Projects/emacs/package1")
(add-to-list 'load-path "~/Projects/emacs/package2")
(add-to-list 'load-path "~/Projects/emacs/package3")
</code></pre>
|
[
{
"answer_id": 221449,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 5,
"selected": true,
"text": "(let ((base \"~/Projects/emacs\"))\n (add-to-list 'load-path base)\n (dolist (f (directory-files base))\n (let ((name (concat base \"/\" f)))\n (when (and (file-directory-p name) \n (not (equal f \"..\"))\n (not (equal f \".\")))\n (add-to-list 'load-path name)))))\n"
},
{
"answer_id": 702280,
"author": "Nicholas Riley",
"author_id": 6372,
"author_profile": "https://Stackoverflow.com/users/6372",
"pm_score": 3,
"selected": false,
"text": "(let* ((my-lisp-dir \"~/.elisp/\")\n (default-directory my-lisp-dir)\n (orig-load-path load-path))\n (setq load-path (cons my-lisp-dir nil))\n (normal-top-level-add-subdirs-to-load-path)\n (nconc load-path orig-load-path))\n"
},
{
"answer_id": 1515968,
"author": "Sujoy",
"author_id": 67373,
"author_profile": "https://Stackoverflow.com/users/67373",
"pm_score": 2,
"selected": false,
"text": "(defun add-to-list-with-subdirs (base exclude-list include-list)\n (dolist (f (directory-files base))\n (let ((name (concat base \"/\" f)))\n (when (and (file-directory-p name)\n (not (member f exclude-list)))\n (add-to-list 'load-path name)\n (when (member f include-list)\n (add-to-list-with-subdirs name exclude-list include-list)))))\n (add-to-list 'load-path base))\n (add-to-list-with-subdirs \"~/.emacs.d\" '(\".\" \"..\" \"backup\") '(\"vendor\" \"my-lisp\"))\n"
},
{
"answer_id": 26030360,
"author": "El Queso Grande",
"author_id": 4077571,
"author_profile": "https://Stackoverflow.com/users/4077571",
"pm_score": 1,
"selected": false,
"text": "(defun add-subdirs-to-load-path (base-path)\n \"Adds first level subfolders to LOAD-PATH.\nBASE-PATH must not end with a '/'\"\n (mapc (lambda (attr)\n (let ((name (car attr))\n (folder-p (cadr attr)))\n (unless (or (not folder-p)\n (equal name \".\")\n (equal name \"..\"))\n (add-to-list 'load-path (concat base-path \"/\" name)))))\n (directory-files-and-attributes base-path)))\n"
},
{
"answer_id": 28685837,
"author": "Mirzhan Irkegulov",
"author_id": 596361,
"author_profile": "https://Stackoverflow.com/users/596361",
"pm_score": 1,
"selected": false,
"text": "dash f f-directories (f-directories \"~/YOURDIR\") ; return only immediate directories\n(f-directories \"~/YOURDIR\" nil t) ; all directories recursively\n --each load-path load-path (add-to-list 'load-path \"~/YOURDIR\") ; your parent folder itself\n(--each (f-directories \"~/YOURDIR\") (add-to-list 'load-path it))\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/712/"
] |
221,370
|
<p>Is there an easy way with LINQ to flatten an XML file?</p>
<p>I can see a number of ways with XSLT but wondered what the best option with LINQ would be?</p>
<p>I cant put the xml structure up exactly as stackoverflow seems to filter chevron chars. But its something like this </p>
<p>nodeA </p>
<p>--nodeA1 </p>
<p>--nodeA2 </p>
<p>NodeB </p>
<p>I want to end up with </p>
<p>nodeA </p>
<p>nodeA1</p>
<p>nodeA2 </p>
<p>NodeB</p>
|
[
{
"answer_id": 221377,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "string xml = @\"<xml><nodeA><nodeA1/><nodeA2/></nodeA><NodeB/></xml>\";\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(xml);\n\nXmlDocument clone = new XmlDocument();\nXmlElement root = (XmlElement) clone.AppendChild(clone.CreateElement(\"xml\"));\nforeach(XmlElement el in doc.SelectNodes(\"//*\")) {\n root.AppendChild(clone.ImportNode(el, false));\n}\nConsole.WriteLine(clone.OuterXml);\n <xml><xml /><nodeA /><nodeA1 /><nodeA2 /><NodeB /></xml>\n"
},
{
"answer_id": 265959,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 0,
"selected": false,
"text": "string xml = @\"<xml><nodeA><nodeA1><inner1/><inner2/></nodeA1><nodeA2/></nodeA><NodeB/></xml>\";\n\nXDocument doc = XDocument.Parse(xml);\n\ndoc.Dump();\ndoc.Root.Descendants().Dump();\ndoc.Descendants().Dump();\ndoc.Root.Descendants().Count().Dump();\ndoc.Descendants().Count().Dump();\n"
},
{
"answer_id": 7185227,
"author": "ehosca",
"author_id": 199771,
"author_profile": "https://Stackoverflow.com/users/199771",
"pm_score": 1,
"selected": false,
"text": "public static class XElementExtensions\n{\n public static string Path(this XElement xElement)\n {\n return PathInternal(xElement);\n }\n\n private static string PathInternal(XElement xElement)\n {\n if (xElement.Parent != null)\n return string.Concat(PathInternal(xElement.Parent), \".\", xElement.Name.LocalName);\n\n return xElement.Name.LocalName;\n }\n}\n private static void Main()\n{\n string sb =@\"<xml>\n <nodeA>\n <nodeA1>\n <inner1/><inner2/>\n </nodeA1>\n <nodeA2/>\n </nodeA>\n <NodeB/>\n </xml>\";\n\n XDocument xDoc = XDocument.Parse(sb);\n\n var result = xDoc.Root.Descendants()\n .Select(r => new {Path = r.Path()});\n\n foreach (var p in result)\n Console.WriteLine(p.Path);\n}\n xml.nodeA\nxml.nodeA.nodeA1\nxml.nodeA.nodeA1.inner1\nxml.nodeA.nodeA1.inner2\nxml.nodeA.nodeA2\nxml.NodeB\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
221,373
|
<p>Sometimes, when we're doing small changes to our web apps, e.g. bug fixes, we don't build a whole new WAR-file each time, but merely replace just the affected class files in the exploded web app directory under <code>WEB-INF/classes</code> and restart the app.</p>
<p>Is that okay?</p>
|
[
{
"answer_id": 221811,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 2,
"selected": false,
"text": "svn update\nmvn clean compile war:exploded tomcat:inplace -P deployment\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
] |
221,376
|
<p>I need to include a copyright statement at the top of every Python source file I produce:</p>
<pre><code># Copyright: © 2008 etc.
</code></pre>
<p>However, when I then run such a file I get this message:</p>
<p>SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see <a href="http://www.python.org/peps/pep-0263.html" rel="noreferrer">http://www.python.org/peps/pep-0263.html</a> for details.</p>
<p>Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:</p>
<pre><code># -*- coding: iso-8859-1 -*-
</code></pre>
<p>to tell Python I'm using Latin encoding, or I can change the copyright statement to: </p>
<pre><code># Copyright: \xa9 2008 etc.
</code></pre>
<p>which just possibly doesn't have the same legal standing.</p>
<p>Is there a more elegant solution?</p>
|
[
{
"answer_id": 221380,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": true,
"text": "(c) Copyright"
},
{
"answer_id": 19210542,
"author": "sergio",
"author_id": 2852044,
"author_profile": "https://Stackoverflow.com/users/2852044",
"pm_score": 3,
"selected": false,
"text": "# -*- coding: utf-8 -*-\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11677/"
] |
221,378
|
<p>I appreciate that there are now many mechanisms in dotnet to deal with XML in a myriad of ways... </p>
<p>Suppose I have a string containing the XML....</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<root>
<Element1>
<Element1_1>
SomeData
</Element1_1>
</Element1>
<Element2>
Some More Data
</Element2>
</root>
</code></pre>
<p><strong>What is the simplest (most readable) way of removing Element1_1?</strong></p>
<p>Update... I can use any .Net API available in .Net 3.5 :D </p>
|
[
{
"answer_id": 221383,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "XElement element = doc.XPathSelectElement(\"/root/Element1/Element1_1\");\nelement.Remove();\n XElement element = doc.Descendants(\"Element1_1\").Single().Remove();\n"
},
{
"answer_id": 221403,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "XmlDocument x = new XmlDocument();\nx.LoadXml(SomeXmlString);\n\nforeach (XmlNode xn in x.SelectNodes(\"//Element1_1\"))\n xn.ParentNode.RemoveChild(xn);\n foreach (XmlNode xn in x.SelectNodes(\"/root/Element1/Element1_1\"))\n xn.ParentNode.RemoveChild(xn);\n XmlNode xn = x.SelectSingleNode(\"/root/Element1/Element1_1\");\nxn.ParentNode.RemoveChild(xn);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] |
221,379
|
<p>Is it okay to run Hibernate applications configured with <code>hbm2ddl.auto=update</code> to update the database schema in a production environment?</p>
|
[
{
"answer_id": 336101,
"author": "cliff.meyers",
"author_id": 41754,
"author_profile": "https://Stackoverflow.com/users/41754",
"pm_score": 5,
"selected": false,
"text": "String with @Column(length=50) ==> varchar(50)\nchanged to\nString with @Column(length=100) ==> still varchar(50), not changed to varchar(100)\n\n@Temporal(TemporalType.TIMESTAMP,TIME,DATE) will not update the DB columns if changed\n"
},
{
"answer_id": 1141531,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "DDL hbm2ddl.auto=update"
},
{
"answer_id": 18180192,
"author": "user1027272",
"author_id": 1027272,
"author_profile": "https://Stackoverflow.com/users/1027272",
"pm_score": 3,
"selected": false,
"text": "hibernate.hbm2ddl.auto=update hibernate.hbm2ddl.auto=create_tables add_columns"
},
{
"answer_id": 44362261,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 5,
"selected": false,
"text": "hbm2ddl.auto hbm2ddl"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
] |
221,385
|
<p>Has anyone gotten the jquery plugin <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">jeditable</a> to run properly in a Rails applications. If so, could you share some hints on how to set it up? I'm having some trouble with creating the "submit-url".</p>
<hr>
<p>IIRC, you cannot simply call ruby code from within javascript (please let me be wrong:-). Do you mean RJS??? Isn't that limited to Prototype? I'm using jQuery.</p>
<hr>
<p><strong>UPDATE:</strong><br>
uh.....asked this a while back and in the meantime switched to a different solution. But IIRC my main issue was the following:</p>
<p>I'm using the RESTful resources. So let's say I have to model a blog and thus have the resource "posts". If I want to edit a post (e.g. the post with the ID 8), my update is sent via HTTP to the URL <a href="http://my.url.com/posts/8" rel="nofollow noreferrer">http://my.url.com/posts/8</a> with the HTTP verb POST. This URL however is constructed in my Rails code. So how would I get my submit-url into my jQuery code? Since this is RESTful code, my update URL will change with every post.</p>
|
[
{
"answer_id": 259187,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 0,
"selected": false,
"text": "<%= url_for(@post) %>\n"
},
{
"answer_id": 259755,
"author": "Sebastian",
"author_id": 29909,
"author_profile": "https://Stackoverflow.com/users/29909",
"pm_score": 4,
"selected": true,
"text": "jQuery(document).ready(function($) {\n\n$(\".edit_textfield\").each( function(i) {\n $(this).editable(\"update\", {\n type : 'textarea',\n rows : 8,\n name : $(this).attr('name'),\n cancel : 'Cancel',\n submit : 'OK',\n indicator : \"<img src='../images/spinner.gif' />\",\n tooltip : 'Double-click to edit...'\n })\n });\n});\n"
},
{
"answer_id": 551392,
"author": "Josh Rickard",
"author_id": 66675,
"author_profile": "https://Stackoverflow.com/users/66675",
"pm_score": 3,
"selected": false,
"text": "<div id=\"email_name\"><%= h( @email.name ) %></div>\n\n$('#email_name').editable( <%= email_path(@email).to_json %>, {\n name: 'email[name]',\n method: 'PUT',\n submitdata: {\n authenticity_token: <%= form_authenticity_token.to_json %>,\n wants: 'name'\n }\n});\n def update\n @email = Email.find( params[:id] )\n @email.update_attributes!( params[:email )\n respond_to do |format|\n format.js\n end\nend\n <%=\n case params[:wants]\n when 'name' then h( @email.name )\n # add other attributes if you have more inline forms for this model\n else ''\n end\n%>\n"
},
{
"answer_id": 880976,
"author": "catalpa",
"author_id": 52211,
"author_profile": "https://Stackoverflow.com/users/52211",
"pm_score": 0,
"selected": false,
"text": "<span id=\"my_edit\"><%= foo.bar %></span>\n\n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#my_edit\").editable('<%= url_for(:action => \"update_bar\", \n :id => foo) %>',\n {\n method: 'PUT',\n cancel : 'Cancel',\n submit : 'OK',\n indicator : \"<img src='../images/spinner.gif' />\",\n tooltip : 'Double-click to edit...',\n submitdata: {\n authenticity_token: <%= form_authenticity_token.to_json %>,\n }\n }\n });\n</script>\n def update_bar\n foo = Foo.find(params[:id])\n bar= params[:value]\n // insert justifiable code here\n foo.save\n render :text=>params[:value]\nend\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29909/"
] |
221,386
|
<p>I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?</p>
|
[
{
"answer_id": 221696,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 0,
"selected": false,
"text": "subprocess fgrep -o -b <search string> file seek read write"
},
{
"answer_id": 221851,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": true,
"text": "open(\"big.file\").read() f = open(\"big.file\", \"rb\") f.read(500) target_seq = \"567\"\ninput_file = \"1234567890\"\n\ntarget_seq.read(5) # reads 12345, doesn't contain 567\ntarget_seq.read(5) # reads 67890, doesn't contain 567\n len(target_seq) while cur_data != \"\":\n seek_start = 0\n chunk_size = len(target_seq)\n\n input_file.seek(offset = seek_start, whence = 1) #whence=1 means seek from start of file (0 + offset)\n cur_data = input_file.read(chunk_size) # reads 123\n if target_seq == cur_data:\n # Found it!\n out_file.write(\"replacement_string\")\n else:\n # not it, shove it in the new file\n out_file.write(cur_data)\n seek_start += 1\n"
},
{
"answer_id": 1008370,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "def ReplaceSequence(inFilename, outFilename, oldSeq, newSeq):\n inputFile = open(inFilename, \"rb\")\n outputFile = open(outFilename, \"wb\")\n\n data = \"\"\n chunk = 1024\n\n while 1:\n data = inputFile.read(chunk)\n data = data.replace(oldSeq, newSeq)\n outputFile.write(data)\n\n inputFile.seek(-len(oldSequence), 1)\n outputFile.seek(-len(oldSequence), 1)\n\n if len(data) < chunk:\n break\n\n inputFile.close()\n outputFile.close()\n"
},
{
"answer_id": 1008461,
"author": "Kenan Banks",
"author_id": 43089,
"author_profile": "https://Stackoverflow.com/users/43089",
"pm_score": 0,
"selected": false,
"text": "import StringIO\n\ndef gen_chars(stream):\n while True:\n ch = stream.read(1)\n if ch: \n yield ch\n else:\n break\n\ndef gen_unique_chars(stream):\n lastchar = ''\n for char in gen_chars(stream):\n if char != lastchar:\n yield char\n lastchar=char\n\ndef remove_seq(infile, outfile):\n for ch in gen_unique_chars(infile):\n outfile.write(ch)\n\n# Represents a file open for reading\ninfile = StringIO.StringIO(\"1122233333444555\")\n\n# Represents a file open for writing\noutfile = StringIO.StringIO()\n\n# Will print \"12345\"\nremove_seq(infile, outfile)\noutfile.seek(0)\nprint outfile.read()\n"
},
{
"answer_id": 13611980,
"author": "edasx",
"author_id": 1086202,
"author_profile": "https://Stackoverflow.com/users/1086202",
"pm_score": 1,
"selected": false,
"text": "def ReplaceSequence(inFilename, outFilename, oldSeq, newSeq):\n inputFile = open(inFilename, \"rb\")\n outputFile = open(outFilename, \"wb\")\n\ndata = \"\"\nchunk = 1024\n\noldSeqLen = len(oldSeq)\n\nwhile 1:\n data = inputFile.read(chunk)\n\n dataSize = len(data)\n seekLen= dataSize - data.rfind(oldSeq) - oldSeqLen\n if seekLen > oldSeqLen:\n seekLen = oldSeqLen\n\n data = data.replace(oldSeq, newSeq)\n outputFile.write(data)\n inputFile.seek(-seekLen, 1) \n outputFile.seek(-seekLen, 1)\n\n if dataSize < chunk:\n break\n\ninputFile.close()\noutputFile.close()\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29908/"
] |
221,387
|
<p>I need a way to check for Wi-Fi routers/access points on my DS homebrew. I'm using PAlib.</p>
|
[
{
"answer_id": 825415,
"author": "PypeBros",
"author_id": 15304,
"author_profile": "https://Stackoverflow.com/users/15304",
"pm_score": 2,
"selected": false,
"text": "Wifi_ScanMode() Wifi_GetNumAP() Wifi_GetAPData(i,&data); nbitems=Wifi_GetNumAP();\nWifi_AccessPoint ap;\n\nfor (int i=0;i<nbitems; i++) {\n if(Wifi_GetAPData(i+scrolltop,&ap)==WIFI_RETURN_OK)\n do_whatever_with(&ap);\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
] |
221,396
|
<p>Is it possible to call a function from PHP using <code>onsubmit</code> from JavaScript? If so could someone give me an example of how it would be done?</p>
<pre><code>function addOrder(){
$con = mysql_connect("localhost", "146687", "password");
if(!$con){
die('Could not connect: ' . mysql_error())
}
$sql = "INSERT INTO orders ((user, 1st row, 2nd row, 3rd row, 4th row)
VALUES ($session->username,1st variable, 2nd variable, 3rd variable, 4th variable))";
mysql_query($sql,$con)
if(mysql_query($sql,$con)){
echo "Your order has been added";
}else{
echo "There was an error adding your order to the databse: " . mysql_error();
}
}
</code></pre>
<p>That's the function I am wanting to call. Its an ordering system, you type in how much of each item you want, hit submit and it <em>should</em> add the order to the table.</p>
|
[
{
"answer_id": 221658,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 5,
"selected": true,
"text": "$.ajax({\n type: \"POST\", // the request type. You most likely going to use POST\n url: \"your_php_script.php\", // the script path on the server side\n data: \"name=John&location=Boston\", // here you put you http param you want to be able to retrieve in $_POST \n success: function(msg) {\n alert( \"Data Saved: \" + msg ); // what you do once the request is completed\n }\n"
},
{
"answer_id": 221983,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 2,
"selected": false,
"text": "<form action=\"add_order.php\" method=\"POST\" id=\"add_order_form\">\n<!-- all of your form fields -->\n<input type='submit' value='Add Order'>\n</form>\n\n<script type=\"text/javascript\">\n$(\"#add_order_form\").submit(function() {\n var action = $(\"#add_order_form\").attr(\"action\");\n var data = $(\"#add_order_form\").serialize();\n $.post(action, data, function(json, status) {\n if(status == 'success') {\n alert(json.message);\n } else {\n alert('Something went wrong.');\n }\n }, \"json\"); \n return false;\n});\n</script>\n add_order.php $success = 0;\n$con = mysql_connect(\"localhost\", \"146687\", \"password\");\nif(!$con) {\n $message = 'Could not connect to the database.';\n} else {\n // SANITIZE DATA BEFORE INSERTING INTO DATABASE\n // LOOK INTO MYSQL_REAL_ESCAPE_STRING AT LEAST,\n // PREFERABLY INTO PREPARED STATEMENTS\n $query_ok = mysql_query(\"INSERT INTO `orders` ....\");\n if($query_ok) {\n $success = 1;\n $message = \"Order added.\";\n } else {\n $message = \"Unable to save information\";\n }\n}\n\nprint json_encode(array('success' => $success, 'message' => $message));\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29912/"
] |
221,399
|
<p>I am using <strong>mysql (5.0.32-Debian_7etch6-log)</strong> and i've got a nightly running bulk load <strong>php (5.2.6)</strong> script <strong>(using Zend_DB (1.5.1)</strong> via PDO) which does the following:</p>
<ol>
<li>truncating a set of 4 'import' tables</li>
<li>bulk inserting data into these 4 'import' tables (re-using ids that have previously been in the tables as well, but i truncated the whole table, so that shouldn't be an issue, right?)</li>
<li>if everything goes well, rename the 'live' tables to 'temp', the 'import' tables to 'live' and then the 'temp' (old 'live') tables to 'import'</li>
</ol>
<p>This worked great for weeks. Now I am occassionally getting this, somewhere in the middle of the whole bulk loading process:</p>
<p><code>SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '911' for key 1</code></p>
<p>Mind you that, this is not the first id that has been in the table before the truncation already. When I just start the script manually again, it works like a charm.</p>
<p>Any ideas? leftover indexes, something to do with the renaming maybe?</p>
<p>In addition, when I check the table for an entry with the id 911 afterwards, it is not even in there.</p>
|
[
{
"answer_id": 222904,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "DELETE FROM TRUNCATE RENAME TABLE ALTER TABLE xxx RENAME TO zzz"
},
{
"answer_id": 224223,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "> repair table mytablename;\n > truncate table temptable;\n> truncate table importtable;\n\n> #bulk insert new data\n> insert into importtable(col1,col2,col3) \n> values(1,2,3),(4,5,6),(7,8,9);\n\n> #now archive the live data\n> insert into temptable(col1,col2,col3)\n> select col1,col2,col3 from livetable;\n\n> #finally copy the new data to live\n> truncate table livetable;\n> insert into livetable(col1,col2,col3)\n> select col1,col2,col3 from importtable;\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
221,410
|
<p>I need to be able to logoff any user from his windows session from a program. </p>
<p>I know I could log in as an admin and force a remote logoff. Is there any other way to force a logoff without logging in? </p>
<p>The tool will run as admin so that's not a problem, being able to remote logoff without logging in is.</p>
<p>Tool is in .NET, but any other way is welcome (JScript, command line tool to run from PInvoke, etc.)</p>
|
[
{
"answer_id": 222192,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "' Logoff.vbs, Version 1.00\n' Logoff current user on any WMI enabled computer on the network\n'\n' Adapted from posts by Alex Angelopoulos on www.developersdex.com\n' and Michael Harris on microsoft.public.scripting.vbscript\n'\n' Written by Rob van der Woude\n' http://www.robvanderwoude.com\n\n' Check command line parameters\nSelect Case WScript.Arguments.Count\n Case 0\n ' Default is local computer if none specified\n strComputer = \".\"\n Case 1\n Select Case WScript.Arguments(0)\n ' \"?\", \"-?\" or \"/?\" invoke online help\n Case \"?\"\n Syntax\n Case \"-?\"\n Syntax\n Case \"/?\"\n Syntax\n Case Else\n strComputer = WScript.Arguments(0)\n End Select\n Case Else\n ' More than 1 argument is not allowed\n Syntax\nEnd Select\n\n' Define some constants that can be used in this script;\n' logoff = 0 (no forced close of applications) or 5 (forced);\n' 5 works OK in Windows 2000, but may result in power off in XP\nConst EWX_LOGOFF = 0\nConst EWX_SHUTDOWN = 1\nConst EWX_REBOOT = 2\nConst EWX_FORCE = 4\nConst EWX_POWEROFF = 8\n\n' Connect to computer\nSet OpSysSet = GetObject(\"winmgmts:{(Shutdown)}//\" & strComputer & \"/root/cimv2\").ExecQuery(\"select * from Win32_OperatingSystem where Primary=true\")\n\n' Actual logoff\nfor each OpSys in OpSysSet\n OpSys.Win32Shutdown EWX_LOGOFF\nnext\n\n' Done\nWScript.Quit(0)\n\n\nSub Syntax\nmsg = vbCrLf & \"Logoff.vbs, Version 1.00\" & vbCrLf & _\n \"Logoff the current user of any WMI enabled computer on the network.\" & _\n vbCrLf & vbCrLf & \"Usage: CSCRIPT LOGOFF.VBS [ computer_name ]\" & _\n vbCrLf & vbCrLf & _\n \"Where: \" & Chr(34) & \"computer_name\" & Chr(34) & _\n \" is the name of the computer to be logged off\" & vbCrLf & _\n \" (without leading backslashes); default is \" & _\n Chr(34) & \".\" & Chr(34) & vbCrLf & _\n \" (the local computer).\" & vbCrLf & vbCrLf & _\n \"Written by Rob van der Woude\" & vbCrLf & _\n \"http://www.robvanderwoude.com\" & vbCrLf & vbCrLf & _\n \"Based on posts by Alex Angelopoulos on www.developersdex.com\" & _\n vbCrLf & _\n \"and Michael Harris on microsoft.public.scripting.vbscript\" & vbCrLf\nWscript.Echo(msg)\nWscript.Quit(1)\nEnd Sub\n"
},
{
"answer_id": 49085000,
"author": "Manas Dash",
"author_id": 9260316,
"author_profile": "https://Stackoverflow.com/users/9260316",
"pm_score": 0,
"selected": false,
"text": "C:\\>psexec \\\\remotepc shutdown /f /l\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
221,411
|
<p>I'm creating window using pure Win32 API (RegisterClass and CreateWindow functions). How can I specify a font for the window instead of system defined one?</p>
|
[
{
"answer_id": 221419,
"author": "vividos",
"author_id": 23740,
"author_profile": "https://Stackoverflow.com/users/23740",
"pm_score": 3,
"selected": false,
"text": "CreateFont CreateFontIndirect WM_SETFONT SetFont DeleteObject CreateFont CreateFontIndirect WM_SETFONT WM_GETFONT"
},
{
"answer_id": 224457,
"author": "Bob Jones",
"author_id": 2067,
"author_profile": "https://Stackoverflow.com/users/2067",
"pm_score": 4,
"selected": false,
"text": "HFONT hFont = CreateFont (13, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET, \n OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \n DEFAULT_PITCH | FF_DONTCARE, TEXT(\"Tahoma\"));\n SendMessage(window, WM_SETFONT, hFont, TRUE);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
221,432
|
<p>I'm opening a new browser window from my site for some of the members. However, some may later close it, or it might have initially failed to open.</p>
<p>Is there a snippet of fairly plain Javascript that can be run on each page to confirm if another browser window is open, and if not, to provide a link to re-open it?</p>
<p><strong>[clarification:]</strong> The code to check is a window is open would be run on other pages - not just in the same window and URL that opened it. Imagine a user logging in, the window (tries to) open, and then they surf around in the same tab/window (or others) for some time before they close the 2nd window (or it never opened) - I want to be able to notice the window has been closed some time after the initial attempt at opening/after it's closed, so I'm not sure that checking the javascript's return from window.open() (with popup_window_handle.closed) is easily used, or indeed possible.</p>
|
[
{
"answer_id": 221439,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "var myWin = window.open(...);\n\nif (myWin.closed)\n{\n myWin = window.open(...);\n}\n"
},
{
"answer_id": 221461,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": true,
"text": "<script language=\"JavaScript\"><!--\nfunction open_main(page) {\n window_handle = window.open(page,'main');\n return false;\n}\n//--></script>\n\n<script language=\"JavaScript1.1\"><!--\nfunction open_main(page) {\n if (opener && !opener.closed) {\n opener.location.href = page;\n }\n else {\n window_handle = window.open(page,'main');\n }\n return false;\n}\n//--></script>\n\n<a href=\"example.htm\" onClick=\"return open_main('example.htm')\">example.htm</a>\n window_handle = window.open(page,'myPopupName');\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6216/"
] |
221,434
|
<p>I'm trying to serve dynamically generated xml pages from a web server, and provide a custom, static, xslt from the same web server, that will offload the processing into the client web browser.</p>
<p>Until recently, I had this working fine in Firefox 2, 3, IE5, 6 and Chrome. Recently, though, something has changed, and Firefox 3 now displays just the text elements in the source.</p>
<p>The page source starts like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!-- Firefox 2.0 and Internet Explorer 7 use simplistic feed sniffing to override desired presentation behavior for this feed, and thus we are obliged to insert this comment, a bit of a waste of bandwidth, unfortunately. This should ensure that the following stylesheet processing instruction is honored by these new browser versions. For some more background you might want to visit the following bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=338621 -->
<?xml-stylesheet type="text/xsl" href="/WebObjects/SantaPreview.woa/Contents/WebServerResources/Root.xsl"?>
<wrapper xmlns="http://www.bbc.co.uk/ContentInterface/Content" xmlns:cont="http://www.bbc.co.uk/ContentInterface/Content" sceneId="T2a_INDEX" serviceName="DSat_T2">
....
</code></pre>
<p>Firebug shows that the Root.xsl file is being loaded, and the response headers for it include the line</p>
<pre><code>Content-Type text/xml
</code></pre>
<p><em>I've also tried it with application/xml as the content type, but it makes no difference :-(</em></p>
<p>The Web Developer Extension shows the correct generated source too, and if you save this and load the page in Firefox, it displays correctly.</p>
<p>The version of Firefox displaying the problem is 3.0.3</p>
<p>Any ideas what I might be doing wrong?</p>
|
[
{
"answer_id": 3925500,
"author": "Prof. Falken",
"author_id": 193892,
"author_profile": "https://Stackoverflow.com/users/193892",
"pm_score": 2,
"selected": false,
"text": "_ my_super_nice_xslt_which_loads_in_opera_and_ie.xsl my-super-nice-xslt-which-loads-in-opera-and-ie.xsl"
},
{
"answer_id": 16191491,
"author": "Thomas Leonard",
"author_id": 50926,
"author_profile": "https://Stackoverflow.com/users/50926",
"pm_score": 2,
"selected": false,
"text": "Allow <site>"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7938/"
] |
221,442
|
<p>With JSR 311 and its implementations we have a powerful standard for exposing Java objects via REST. However on the client side there seems to be something missing that is comparable to Apache Axis for SOAP - something that hides the web service and marshals the data transparently back to Java objects.</p>
<p>How do you create Java RESTful clients? Using HTTPConnection and manual parsing of the result? Or specialized clients for e.g. Jersey or Apache CXR?</p>
|
[
{
"answer_id": 221763,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 6,
"selected": false,
"text": " clientConfig = new DefaultClientConfig();\n client = Client.create(clientConfig);\n\n resource = client.resource(\"http://localhost:8080\");\n // lets get the XML as a String\n String text = resource(\"foo\").accept(\"application/xml\").get(String.class); \n"
},
{
"answer_id": 3533714,
"author": "bdoughan",
"author_id": 383861,
"author_profile": "https://Stackoverflow.com/users/383861",
"pm_score": 6,
"selected": false,
"text": "private void updateCustomer(Customer customer) { \n try { \n URL url = new URL(\"http://www.example.com/customers\"); \n HttpURLConnection connection = (HttpURLConnection) url.openConnection(); \n connection.setDoOutput(true); \n connection.setInstanceFollowRedirects(false); \n connection.setRequestMethod(\"PUT\"); \n connection.setRequestProperty(\"Content-Type\", \"application/xml\"); \n\n OutputStream os = connection.getOutputStream(); \n jaxbContext.createMarshaller().marshal(customer, os); \n os.flush(); \n\n connection.getResponseCode(); \n connection.disconnect(); \n } catch(Exception e) { \n throw new RuntimeException(e); \n } \n} \n WebResource resource = client.resource(\"http://www.example.com/customers\"); \nClientResponse response = resource.type(\"application/xml\");).put(ClientResponse.class, \"<customer>...</customer.\"); \nSystem.out.println(response); \n"
},
{
"answer_id": 5110268,
"author": "Johan",
"author_id": 398441,
"author_profile": "https://Stackoverflow.com/users/398441",
"pm_score": 4,
"selected": false,
"text": "// Make a GET request to \"/lotto\"\nString json = get(\"/lotto\").asString()\n// Parse the JSON response\nList<String> winnderIds = with(json).get(\"lotto.winners.winnerId\");\n\n// Make a POST request to \"/shopping\"\nString xml = post(\"/shopping\").andReturn().body().asString()\n// Parse the XML\nNode category = with(xml).get(\"shopping.category[0]\");\n"
},
{
"answer_id": 10372027,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 3,
"selected": false,
"text": "JdkRequest String body = new JdkRequest(\"http://www.google.com\")\n .header(\"User-Agent\", \"it's me\")\n .fetch()\n .body()\n"
},
{
"answer_id": 22856154,
"author": "George Georgovassilis",
"author_id": 3194801,
"author_profile": "https://Stackoverflow.com/users/3194801",
"pm_score": 1,
"selected": false,
"text": "public interface BookService {\n @RequestMapping(\"/volumes\")\n QueryResult findBooksByTitle(@RequestParam(\"q\") String q);\n\n @RequestMapping(\"/volumes/{id}\")\n Item findBookById(@PathVariable(\"id\") String id);\n}\n"
},
{
"answer_id": 24846525,
"author": "g00dnatur3",
"author_id": 1500191,
"author_profile": "https://Stackoverflow.com/users/1500191",
"pm_score": 0,
"selected": false,
"text": "RestClient client = RestClient.builder().build();\nString geocoderUrl = \"http://maps.googleapis.com/maps/api/geocode/json\"\nMap<String, String> params = Maps.newHashMap();\nparams.put(\"address\", \"beverly hills 90210\");\nparams.put(\"sensor\", \"false\");\nJsonNode node = client.get(geocoderUrl, params, JsonNode.class);\n RestClient client = RestClient.builder().build();\nString url = ...\nPerson person = ...\nHeader header = client.create(url, person);\nif (header != null) System.out.println(\"Location header is:\" + header.value());\n RestClient client = RestClient.builder().build();\nString url = ...\nPerson person = client.get(url, null, Person.class); //no queryParams\n"
},
{
"answer_id": 25993066,
"author": "abhishek ringsia",
"author_id": 3589749,
"author_profile": "https://Stackoverflow.com/users/3589749",
"pm_score": 1,
"selected": false,
"text": " <!-- jersey -->\n <dependency>\n <groupId>com.sun.jersey</groupId>\n <artifactId>jersey-json</artifactId>\n <version>1.8</version>\n </dependency>\n <dependency>\n <groupId>com.sun.jersey</groupId>\n <artifactId>jersey-server</artifactId>\n <version>1.8</version>\n </dependency>\n\n<dependency>\n <groupId>com.sun.jersey</groupId>\n <artifactId>jersey-client</artifactId>\n <version>1.8</version>\n</dependency>\n\n <dependency>\n <groupId>org.json</groupId>\n <artifactId>json</artifactId>\n <version>20090211</version>\n</dependency>\n Client client = Client.create();\n WebResource webResource1 = client\n .resource(\"http://localhost:10102/NewsTickerServices/AddGroup/\"\n + userN + \"/\" + groupName);\n\n ClientResponse response1 = webResource1.get(ClientResponse.class);\n System.out.println(\"responser is\" + response1);\n Client client = Client.create();\n\n WebResource webResource1 = client\n .resource(\"http://localhost:10102/NewsTickerServices/GetAssignedUser/\"+grpName); \n //value changed\n String response1 = webResource1.type(MediaType.APPLICATION_JSON).get(String.class);\n\n List <String > Assignedlist =new ArrayList<String>();\n JSONArray jsonArr2 =new JSONArray(response1);\n for (int i =0;i<jsonArr2.length();i++){\n\n Assignedlist.add(jsonArr2.getString(i)); \n }\n Client client = Client.create();\n WebResource webResource = client\n .resource(\"http://localhost:10102/NewsTickerServices/CreateJUser\");\n // value added\n\n ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,mapper.writeValueAsString(user));\n\n if (response.getStatus() == 500) {\n\n context.addMessage(null, new FacesMessage(\"User already exist \"));\n }\n"
},
{
"answer_id": 33737547,
"author": "Sam Edwards",
"author_id": 509081,
"author_profile": "https://Stackoverflow.com/users/509081",
"pm_score": 3,
"selected": false,
"text": "public static final MediaType JSON\n = MediaType.parse(\"application/json; charset=utf-8\");\n\nOkHttpClient client = new OkHttpClient();\n\nString post(String url, String json) throws IOException {\n RequestBody body = RequestBody.create(JSON, json);\n Request request = new Request.Builder()\n .url(url)\n .post(body)\n .build();\n Response response = client.newCall(request).execute();\n return response.body().string();\n}\n public interface GitHubService {\n @GET(\"/users/{user}/repos\")\n Call<List<Repo>> listRepos(@Path(\"user\") String user);\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7524/"
] |
221,444
|
<p>How can I put up a "File Open" dialog from some VBA running in Excel? </p>
<p>I'm using Excel 2003. </p>
|
[
{
"answer_id": 221456,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 2,
"selected": false,
"text": "Sub PromptForFile()\nDim d As New MSComDlg.CommonDialog\n\nd.Filter = \"xls\"\nd.Filename = \"*.xls\"\nd.ShowOpen\n\nExcel.Workbooks.Open d.Filename\n\nSet d = Nothing\nEnd Sub \n"
},
{
"answer_id": 221457,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": true,
"text": "Application.GetOpenFilename"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
] |
221,452
|
<pre><code>Control.TabIndex
</code></pre>
<p>Only allows me to overide the Tab order of controls in a given container. </p>
<p>Is there a way to specify this across all the controls in, for example a UserControl, regardless of the contains used to arrange the controls.</p>
<p>Cheers,</p>
<p>Jan</p>
|
[
{
"answer_id": 234133,
"author": "James Osborn",
"author_id": 6686,
"author_profile": "https://Stackoverflow.com/users/6686",
"pm_score": 1,
"selected": false,
"text": "KeyboardNavigation.TabNavigation TabIndex TabNavigation"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460845/"
] |
221,455
|
<p>My stomach churns when I see this kind of output.</p>
<p><a href="http://www.freeimagehosting.net/uploads/e1097a5a10.jpg" rel="nofollow noreferrer">http://www.freeimagehosting.net/uploads/e1097a5a10.jpg</a></p>
<p>and this was my command
as suggested by <a href="https://stackoverflow.com/questions/75500/best-way-to-convert-pdf-files-to-tiff-files#221341">Best way to convert pdf files to tiff files</a></p>
<pre><code>gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif a.pdf -c quit
</code></pre>
<p>What am I doing wrong?</p>
<p>(commercial products will not be considered)</p>
|
[
{
"answer_id": 221588,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "nconvert -page 1 -out tiff -dpi 200 -c 2 -o c.tif FMD.pdf\n"
},
{
"answer_id": 224517,
"author": "Setori",
"author_id": 21537,
"author_profile": "https://Stackoverflow.com/users/21537",
"pm_score": 1,
"selected": false,
"text": " os.popen(' '.join([\n self._ghostscriptPath + 'gswin32c.exe', \n '-q',\n '-dNOPAUSE',\n '-dBATCH',\n '-r800',\n '-sDEVICE=tiffg4',\n '-sPAPERSIZE=a4',\n '-sOutputFile=%s %s' % (tifDest, pdfSource),\n ]))\n"
},
{
"answer_id": 2981522,
"author": "Kurt Pfeifle",
"author_id": 359307,
"author_profile": "https://Stackoverflow.com/users/359307",
"pm_score": 1,
"selected": false,
"text": "-r600 gswin32c.exe ^\n -o output.tiff ^\n -sDEVICE=tiffg4 ^\n -r600 ^\n input.pdf\n -dDITHERPPI=<lpi> -r600 -dDITHERPPI=30 dDITHERPPI=120"
},
{
"answer_id": 4427418,
"author": "Amil Waduwawara",
"author_id": 540323,
"author_profile": "https://Stackoverflow.com/users/540323",
"pm_score": 4,
"selected": false,
"text": "convert convert -define quantum:polarity=min-is-white \\\n -endian MSB \\\n -units PixelsPerInch \\\n -density 204x196 \\\n -monochrome \\\n -compress Fax \\\n -sample 1728 \\\n \"input.pdf\" \"output.tif\"\n"
},
{
"answer_id": 7466753,
"author": "Stephen Quan",
"author_id": 705252,
"author_profile": "https://Stackoverflow.com/users/705252",
"pm_score": 2,
"selected": false,
"text": "gswin32c.exe -q -dNOPAUSE -r600 -sDEVICE=tiff24nc -sOutputFile=a.tif a.pdf -c quit\n"
},
{
"answer_id": 10403444,
"author": "Gene Garber",
"author_id": 1303375,
"author_profile": "https://Stackoverflow.com/users/1303375",
"pm_score": 0,
"selected": false,
"text": "$Imagick->blackThresholdImage('grey');\n convert a.pdf -threshold 60% a.tif\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
221,467
|
<p>I'm trying to complete a practice question from a book on generics but the question doesn't make sense to me. Here it goes.</p>
<p>Create two classes with identical functionality. Use generics for the first class, and cast the second class to Object types. Create a for loop that uses class and the Object based class to determine which performs better.</p>
<p>I'm not sure what it means by casting to Object types. Here is my code so far</p>
<pre><code> //Generic
class Person<T> {
T var1;
public Person(T yer) {
var1 = yer;
}
public T Value { get { return var1; } }
}
//Normal class
class Human {
int var1;
public Human(int yer) {
var1 = yer;
}
public int Value { get { return var1; } }
}
</code></pre>
<p>My main program running the loops</p>
<pre><code>for (int i = 0; i < 1000000; i++) {
Person<int> me = new Person<int>(1);
int hey = me.Value;
}
for (int i = 0; i < 1000000; i++) {
Human per = new Human(1);
object her = (object)per.Value;
}
</code></pre>
<p>I don't know if Im doing this right. Help please :-)</p>
|
[
{
"answer_id": 221470,
"author": "endian",
"author_id": 25462,
"author_profile": "https://Stackoverflow.com/users/25462",
"pm_score": 4,
"selected": true,
"text": "List<Human> myList = new List<Human>();\nHuman h = new Human();\nmyList.Add(h);\n ArrayList myObjectList = new ArrayList();\nHuman h = new Human();\nmyObjectList.Add((object)h));\n"
},
{
"answer_id": 221480,
"author": "Chris Conway",
"author_id": 2849,
"author_profile": "https://Stackoverflow.com/users/2849",
"pm_score": 0,
"selected": false,
"text": "object her = (object)per.Value;\n int her = per.Value;\n"
},
{
"answer_id": 221488,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 1,
"selected": false,
"text": "List<Person> pList = new List<Person>();\nfor(int i = 0; i<1000; ++i)\n pList.Add(new Person(30));\n\nStopWatch sw = new StopWatch();\nsw.start();\nint sum = 0;\nforeach(Person p in pList)\n sum += p.Value;\nsw.Stop();\n ArrayList hList = new ArrayList;\nfor(int i = 0; i<1000; ++i)\n hList.Add(new Human(30));\n\nStopWatch sw = new StopWatch();\nsw.start();\nint sum = 0;\nforeach(Object h in hList)\n sum += ((Human)h).Value;\nsw.Stop();\n"
},
{
"answer_id": 221518,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "class Human \n{ \n object var1;\n public Human(int yer) \n { \n var1 = (object) yer; \n }\n public int Value \n { \n get { return (int) var1; }\n } \n}\n"
},
{
"answer_id": 9680520,
"author": "Ian",
"author_id": 1265974,
"author_profile": "https://Stackoverflow.com/users/1265974",
"pm_score": 0,
"selected": false,
"text": "DateTime.Now.Ticks DateTime t = DateTime.Now;\n for (int i = 0; i < 1000000; i++)\n {\n Person<int> me = new Person<int>(1);\n int hey = me.Value;\n }\n long a = DateTime.Now.Ticks - t.Ticks;\n TimeSpan A = new TimeSpan(a);\n\n\n for (int i = 0; i < 1000000; i++)\n {\n Human per = new Human(1);\n object her = (object)per.Value;\n }\n\n long b = DateTime.Now.Ticks - t.Ticks;\n TimeSpan B = new TimeSpan(b);\n\n Console.WriteLine(A.ToString());\n Console.WriteLine(B.ToString());\n Console.ReadLine();\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
221,474
|
<p>When you create a link to an executable file intended for download (like say update.exe), on a web page, IE7 gives the user the option to "Run" or "Save". I don't want users to be running the update file they should be downloading.</p>
<p>Is it possible to disable the "Save" option on the dialog the IE displays, or even force the download automatically.</p>
|
[
{
"answer_id": 221493,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 3,
"selected": true,
"text": "HttpContext.Current.Response.Buffer = false;\nHttpContext.Current.Response.ClearContent();\nHttpContext.Current.Response.ClearHeaders();\nHttpContext.Current.Response.AddHeader(\"Content-disposition\", \"attachment; filename=filename.exe\");\nHttpContext.Current.Response.AddHeader(\"Content-length\", contentLength);\nHttpContext.Current.Response.AddHeader(\"Content-Transfer-Encoding\", \"binary\");\nHttpContext.Current.Response.ContentType = \"application/octet-stream\";\nHttpContext.Current.Response.TransmitFile(filePath);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
] |
221,475
|
<p>In LinqToSql, it is lovely easy to load a row, change a column, and submit the changes to the database:</p>
<pre><code>using (MyDataContext wdc = new MyDataContext())
{
Article article = wdc.Article.First(p => p.ID == id);
article.ItemsInStock = itemsinstock;
wdc.SubmitChanges();
}
</code></pre>
<p>The only drawback: Article is huge. <strong>To load the entire article, just to update one column is way overkill</strong> and slows down my app significantly.</p>
<p>Is there a way to update a single column using LINQ, without having to load the entire row?</p>
<p>Right now I revert to using ExecuteCommand where speed is of essence, but this is ugly and error prone:</p>
<pre><code>wdc.ExecuteCommand("UPDATE Article SET ItemsInStock = @1 WHERE ID = @2", itemsinstock,id);
</code></pre>
|
[
{
"answer_id": 221547,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 3,
"selected": false,
"text": "UPDATE ... SET ... WHERE ID = @2\n UPDATE ... SET ... WHERE ID = @2 AND ItemsInStock = @1 AND SomeOtherColumn = @3 AND...\n context.Articles.Attach(article /* article with updated values */, new Article { ID = articleID, ItemsInStock = -1 } /* pretend that this is the original article */);\ncontext.SubmitChanges();\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
] |
221,476
|
<p>After update, old Eclipse plugins remain in "plugins" folder (there are also leftovers in "features" folder).</p>
<p>Is there a way to remove those automatically?</p>
|
[
{
"answer_id": 221985,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "\\[eclipse\\]/dropins/eclemma1.3.1/eclipse/(plugins|features)\n"
},
{
"answer_id": 10878310,
"author": "LiuYan 刘研",
"author_id": 404192,
"author_profile": "https://Stackoverflow.com/users/404192",
"pm_score": 3,
"selected": false,
"text": "guess-old-eclipse-plugins.sh remove-old-eclipse-plugins.txt PluginsDir=plugins\nFeaturesDir=features\nPluginIDSeparator=_\nRemovingScriptFileName=remove-old-eclipse-plugins.txt\nrm -rf $RemovingScriptFileName\n\n#for dir in $PluginsDir $FeaturesDir\nfor dir in $PluginsDir # $FeaturesDir: most file names in features dir contains more than 1 _ character\ndo\n echo \"Processing [$dir] directory...\"\n # split PluginID from filename\n # (not reliable, but general working. (ex: will get one junit PluginID because there're move than 1 _ characters in file name))\n file_list=$(ls $dir);\n echo \"$file_list\" | cut -f1 -d $PluginIDSeparator > $dir-all.txt\n echo \"$file_list\" | cut -f1 -d $PluginIDSeparator | uniq > $dir-uniq.txt\n\n # get the PluginList which VERY POSSIBLY has old versions\n diff_result=$(diff -U 0 $dir-uniq.txt $dir-all.txt)\n plugins_which_has_old_versions=$(echo \"$diff_result\" | grep -e \"^+[^+]\" | cut -f 2 -d +)\n\n #\n for p in $(echo \"$plugins_which_has_old_versions\")\n do\n echo \"$p\"\n i=0\n for f in $(ls -d -t $dir/$p$PluginIDSeparator*) # use 'ls' command, can sort result by file time, but can not handle file name contains special characters (white space) when using wildcard\n #for f in $(find $dir -name \"$p$PluginIDSeparator*\") # use 'find' command\n do\n if [ -d $f ]\n then\n # should use rm -rf\n echo -n \"[D]\"\n else\n echo -n \" \"\n fi\n echo -n \"$f\"\n\n ((i++))\n if [ $i -eq 1 ]\n then\n echo \"\"\n continue # first file, the newest version\n fi\n echo \" [old]\"\n echo \"rm -rf $f\" >> $RemovingScriptFileName\n done\n\n echo\n done\ndone\n remove-old-eclipse-plugins.txt _ org.junit_ org.junit\n[D]plugins/org.junit_3.8.2.v3_8_2_v20100427-1100\n[D]plugins/org.junit_4.8.2.v4_8_2_v20110321-1705 [old] <-- wrong\n $ ./guess-old-eclipse-plugins.sh\nProcessing [plugins] directory...\norg.eclipse.gef\n plugins/org.eclipse.gef_3.7.2.v20111106-2020.jar\n plugins/org.eclipse.gef_3.6.2.v20110110-2020.jar [old]\n\norg.eclipse.help.base\n plugins/org.eclipse.help.base_3.6.2.v201202080800.jar\n plugins/org.eclipse.help.base_3.5.3.v201102101200.jar [old]\n\norg.eclipse.help.ui\n plugins/org.eclipse.help.ui_3.5.101.r37_20110819.jar\n plugins/org.eclipse.help.ui_3.5.3.r36_20101116.jar [old]\n...\n rm -rf plugins/org.eclipse.gef_3.6.2.v20110110-2020.jar\nrm -rf plugins/org.eclipse.help.base_3.5.3.v201102101200.jar\nrm -rf plugins/org.eclipse.help.ui_3.5.3.r36_20101116.jar\nrm -rf plugins/org.eclipse.help.webapp_3.5.3.r36_20101130.jar\nrm -rf plugins/org.eclipse.jdt.apt.core_3.3.402.R36_v20110120-1000.jar\nrm -rf plugins/org.eclipse.jdt.debug.ui_3.5.2.v20100928a_r362.jar\n"
},
{
"answer_id": 17677038,
"author": "FKorning",
"author_id": 1288623,
"author_profile": "https://Stackoverflow.com/users/1288623",
"pm_score": 2,
"selected": false,
"text": "# scan_old_plugins.sh\n\n# script to scan for duplicate old eclipse features, plugins and dropins\n# generates a \"clean-old-plugins.sh\" script to clean old versions.\n# warning: DANGEROUS! review clean-old-plugins script before running it.\n\nDropinsDir=dropins\nFeaturesDir=features\nPluginsDir=plugins\n\nCanonicalPluginsFile=sed_canonical_plugins.sh\nCleanPluginScriptFile=clean_old_plugins.sh\n\necho \"\" > $CanonicalPluginsFile\necho \"\" > $CleanPluginScriptFile\n\n#for dir in $PluginsDir\nfor dir in $FeaturesDir $PluginsDir $DropinsDir\ndo\n echo \"Processing [$dir] directory...\"\n # \n file_list=$(\\ls -1 $dir | sort -r);\n echo \"$file_list\" > $dir-all.txt\n\n #\n for p in $(echo \"$file_list\")\n do\n v=$(echo $p | sed -e 's/_[0-9\\._\\-]*/_.*/g' | sed -e 's/[0-9][0-9]*/.*/g')\n g=$(grep -l \"$v\" $CanonicalPluginsFile | head -1 | awk '{print $1}')\n if [ \"$g\" = \"\" ]; then\n echo \"$p=keep\";\n echo \"$v=$p\" >> $CanonicalPluginsFile\n else\n echo \"$p=stale\";\n echo \"rm -rf $p\" >> $CleanPluginScriptFile\n fi\n \n done\ndone\n"
},
{
"answer_id": 22167100,
"author": "Andrej",
"author_id": 1838770,
"author_profile": "https://Stackoverflow.com/users/1838770",
"pm_score": 3,
"selected": false,
"text": "dropins/eclipse dropins"
},
{
"answer_id": 30361073,
"author": "Bender270",
"author_id": 2641499,
"author_profile": "https://Stackoverflow.com/users/2641499",
"pm_score": 1,
"selected": false,
"text": "# -*- coding: utf-8 -*-\nimport os\nimport re\nfrom datetime import datetime\n\ndirectory=\"C:\\\\eclipse64\\\\plugins\"\ndirBackup=\"C:\\\\eclipse64\\\\PluginsBackup\" #This folder is a kind of recycle bin for save deleted plugins. In case you have problems running eclipse after remove them you can restore them. If you don't detect any problem you can erase this folder to save disk space\nmanual=False #Verifying deletion of each plugin manually (True) or automatic (False) \n\ndef globRegEx(directory,pat,absolutePath=True,type_=0):\n '''Function that given a directory and a regular pattern returns a list of files that meets the pattern\n\n :param str directory: Base path where we search for files that meet the pattern\n :param str pat: Regular expression that selected files must match \n :param bool absolutePath: Optional parameter that indicates if the returned list contains absolute (True) or relative paths (False)\n :param int type_: Type of selection 0: selects files and directories 1: only selects files 2: only selects directories\n :return: a list with the paths that meet the regular pattern\n '''\n names=os.listdir(directory)\n pat=re.compile(pat)\n res=[]\n\n for name in names:\n if pat.match(name):\n path=directory+os.sep+name\n\n if type_==1 and os.path.isfile(path):\n res.append(path if absolutePath else name)\n elif type_==2 and os.path.isdir(path):\n res.append(path if absolutePath else name)\n elif type_==0:\n res.append(path if absolutePath else name)\n\n return(res)\n\ndef processRepeated(repList):\n ''' this function is responsible for leaving only the newer version of the plugin\n '''\n\n if repList and len(repList)>1: #If the plugin is repeated\n repList.sort(reverse=True)\n print(\"Repeated plugins found:\")\n min=len(repList[0]) # If strings haven't got the same length indicates a change in the numeration version system\n max=min\n newer=datetime.fromtimestamp(0)\n sel=0\n\n for i,path in enumerate(repList):\n lr=len(path)\n modifDate=datetime.fromtimestamp((os.path.getctime(path)))\n if modifDate>newer: #Keep the last creation date and its index\n newer=modifDate\n sel=i+1\n\n if lr<min: \n min=lr\n elif lr>max: \n max=lr\n\n print(str(i+1) + \" \" + modifDate.strftime(\"%Y-%m-%d\") + \": \" + path)\n print(\" \")\n\n if manual or min!=max: #If manual mode is enabled or if there is a string length diference between different version of plugins\n selec=raw_input(\"Which version do you want to keep?: [\"+str(sel)+\"] \")\n if selec:\n selec=int(selec)\n else: \n selec=sel #Newer is the Default value\n else:\n selec=1\n\n\n del(repList[selec-1]) #Delete selected plugin from the list\n\n for path in repList: #Move the rest of the list to the backup folder\n print(\"Deleting: \"+ path)\n os.renames(path,os.path.join(dirBackup,os.path.basename(path)))\n\n print(\"-------------------------------------\\n\\n\")\n\ndef main():\n\n filePlugins=globRegEx(directory,\"^.*$\",False,1) #Creates a list with all the files only\n dirPlugins=globRegEx(directory,\"^.*$\",False,2) #Creates a list with all the folders only\n\n\n #Process files first\n\n for plugin in filePlugins:\n m=re.match(r\"(.*_)\\d.*?\\.jar$\",plugin) #Creates the glob pattern\n if m:\n patAux=m.groups()[0]+\".*?\\.jar$\"\n find=globRegEx(directory,patAux,True,1)\n processRepeated(find)\n\n #Now Directories \n\n for plugin in dirPlugins:\n m=re.match(r\"(.*_)\\d.*$\",plugin) #Creates the glob pattern\n if m:\n patAux=m.groups()[0]+\".*$\"\n find=globRegEx(directory,patAux,True,2)\n processRepeated(find)\n\nif __name__==\"__main__\":\n main()\n"
},
{
"answer_id": 33818480,
"author": "Ogmios",
"author_id": 1924321,
"author_profile": "https://Stackoverflow.com/users/1924321",
"pm_score": 3,
"selected": false,
"text": "bundles.info eclipse/configuration/org.eclipse.equinox.simpleconfigurator/bundles.info .*plugins/([^,]*),.* $1 eclipse/plugin/"
},
{
"answer_id": 52577085,
"author": "Konstantin Kolinko",
"author_id": 4116988,
"author_profile": "https://Stackoverflow.com/users/4116988",
"pm_score": 3,
"selected": false,
"text": "eclipse -application org.eclipse.equinox.p2.garbagecollector.application -profile epp.package.jee\n -profile epp.package.jee configuration/config.ini eclipse.p2.profile=epp.package.jee\n"
},
{
"answer_id": 60378274,
"author": "Gionata",
"author_id": 11643143,
"author_profile": "https://Stackoverflow.com/users/11643143",
"pm_score": 2,
"selected": false,
"text": "eclipse -application org.eclipse.equinox.p2.garbagecollector.application -profile SDKProfile\n epp.package.jee"
},
{
"answer_id": 63545967,
"author": "Marcel",
"author_id": 1586832,
"author_profile": "https://Stackoverflow.com/users/1586832",
"pm_score": 0,
"selected": false,
"text": "\"C:\\ST\\STM32CubeIDE_1.3.0\\STM32CubeIDE\\eclipsec\" -application org.eclipse.equinox.p2.garbagecollector.application -profile STM32CubeIDE\n"
},
{
"answer_id": 68071564,
"author": "Mike Pawlowski",
"author_id": 5795299,
"author_profile": "https://Stackoverflow.com/users/5795299",
"pm_score": 0,
"selected": false,
"text": "eclipse-java-2021-06-R-win32-x86_64.zip eclipse eclipse"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5817/"
] |
221,502
|
<p>I'm comparing the results produced when i use the 'Make .exe' compared to when i run the exact same process using the exact same variables though the IDE vb 6 debugger.</p>
<p>I've tried an array of different compiler options but to no avail.</p>
<p>So my question is why would i get a difference between the debugger and the 'Make .exe'?
have you ever come arross something similar and if so did you find a fix?</p>
<p><em>the program takes a large file of counts of cars in a timeperiod and averages them into 15 minute timeperiods for the day over a month for each route.
It elminates certain records depending on if there outside the standard deviation and other statistical algorithms To eliminate values.
its a bit to much code to post unfortunately...</em></p>
|
[
{
"answer_id": 221622,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 2,
"selected": false,
"text": "Debug.Assert Debug.Print Debug.Assert( DoSomeThingImportend() )\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5186/"
] |
221,503
|
<p>I wish we have "Usable" pattern in C#, when code block of using construct would be passed to a function as delegate:</p>
<pre><code>class Usable : IUsable
{
public void Use(Action action) // implements IUsable
{
// acquire resources
action();
// release resources
}
}
</code></pre>
<p>and in user code:</p>
<pre><code>using (new Usable())
{
// this code block is converted to delegate and passed to Use method above
}
</code></pre>
<p>Pros:</p>
<ul>
<li>Controlled execution, exceptions </li>
<li>The fact of using "Usable" is visible in call stack</li>
</ul>
<p>Cons:</p>
<ul>
<li>Cost of delegate</li>
</ul>
<p>Do you think it is feasible and useful, and if it doesn't have any problems from the language point of view? Are there any pitfalls you can see?</p>
<p>EDIT: David Schmitt <a href="https://stackoverflow.com/questions/221503/iusable-controlling-resources-in-a-better-way-than-idisposable#221522">proposed</a> the following </p>
<pre><code>using(new Usable(delegate() {
// actions here
}) {}
</code></pre>
<p>It can work in the sample scenario like that, but usually you have resource already allocated and want it to look like this:</p>
<pre><code>using (Repository.GlobalResource)
{
// actions here
}
</code></pre>
<p>Where GlobalResource (yes, I know global resources are bad) implements IUsable.
You can rewrite is as short as</p>
<pre><code>Repository.GlobalResource.Use(() =>
{
// actions here
});
</code></pre>
<p>But it looks a little bit weird (and more weird if you implement interface explicitly), and this is so often case in various flavours, that I thought it deserve to be new syntactic sugar in a language. </p>
|
[
{
"answer_id": 221522,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 1,
"selected": false,
"text": "using(new Usable(delegate() {\n // actions here\n}) {}\n"
},
{
"answer_id": 221923,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 2,
"selected": false,
"text": "class Usable<T> where T : ICriticalResource, new()\n{\n static void Do(Action<T> action) {\n ICriticalResource resource = new T();\n resource.Acquire();\n action(resource);\n resource.Relese();\n }\n}\n Usable<SomeResource>.Do(resource => resource.SomeMethod());\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18575/"
] |
221,514
|
<p>Suppose, objects of type <i>A</i> are stored in DB. Here's the way I load specific one from DB using hibernate:</p>
<pre><code>org.hibernate.Session session = ...;
long id = 1;
A obj = session.load(A.class, id);
</code></pre>
<p>If object with id=1 doesn't exist I will get <i>ObjectNotFoundException</i>. But is there a way to check if such object exists without having to catch the exception? What I would like to have is smth like:</p>
<pre><code>org.hibernate.Session session = ...;
long id = 1;
boolean exists = session.exists(A.class, id);
if(exists){
// do smth.....
}
</code></pre>
<p>Couldn't find it hibernate docs...</p>
|
[
{
"answer_id": 221526,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 6,
"selected": true,
"text": "session.get public Object get(Class clazz,\n Serializable id)\n throws HibernateException\n"
},
{
"answer_id": 6796237,
"author": "ArBR",
"author_id": 476200,
"author_profile": "https://Stackoverflow.com/users/476200",
"pm_score": 6,
"selected": false,
"text": "public Boolean exists (DTOAny instance) {\n Query query = getSession(). \n createQuery(\"select 1 from DTOAny t where t.key = :key\");\n query.setString(\"key\", instance.getKey() );\n return (query.uniqueResult() != null);\n}\n"
},
{
"answer_id": 30598238,
"author": "Journeycorner",
"author_id": 3698894,
"author_profile": "https://Stackoverflow.com/users/3698894",
"pm_score": 4,
"selected": false,
"text": "public boolean exists(Class clazz, String idKey, Object idValue) {\n return getSession().createCriteria(clazz)\n .add(Restrictions.eq(idKey, idValue))\n .setProjection(Projections.property(idKey))\n .uniqueResult() != null;\n}\n public boolean exists(Class clazz, Object key) {\n try {\n return entitymanager.getReference(Entity.class, key) != null;\n } catch (EntityNotFoundException.class) {\n return false;\n }\n}\n"
},
{
"answer_id": 42404799,
"author": "v.ladynev",
"author_id": 3405171,
"author_profile": "https://Stackoverflow.com/users/3405171",
"pm_score": 3,
"selected": false,
"text": "public boolean exists(Class<?> clazz, Object idValue) {\n return getSession().createCriteria(clazz)\n .add(Restrictions.idEq(idValue))\n .setProjection(Projections.id())\n .uniqueResult() != null;\n}\n Restrictions.idEq() public static boolean uniqueExists(Criteria uniqueCriteria) {\n uniqueCriteria.setProjection(Projections.id());\n return uniqueCriteria.uniqueResult() != null;\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
221,519
|
<p>The following Code does not compile</p>
<pre><code>Dim BasicGroups As String() = New String() {"Node1", "Node2"}
Dim NodesToRemove = From Element In SchemaDoc.Root.<Group> _
Where Element.@Name not in BasicGroups
For Each XNode In NodesToRemove
XNode.Remove()
Next
</code></pre>
<p>It is supposed to Remove any Immediate child of the rootnode which has an attribute called name whose value is <strong>Not</strong> listed in the BasicGroups StringArray.</p>
<p><strong>What is the correct syntax for this task?</strong></p>
|
[
{
"answer_id": 221605,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 3,
"selected": true,
"text": "where (not (list.Contains(foo))\n"
},
{
"answer_id": 221613,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 1,
"selected": false,
"text": "Dim SchemaDoc As New XDocument(<Root><Group Name=\"Foo\"/><Group Name=\"Node1\"/>\n <Group Name=\"Node2\"/><Group name=\"Bar\"/></Root>)\nDim NodesToRemove = From Element In SchemaDoc.<Root>.<Group> Where _\n Element.@Name Like \"NotNode?\"\nFor Each XNode In NodesToRemove.ToArray()\n XNode.Remove()\nNext\n Dim NodesToRemove As New Collections.ObjectModel.Collection(Of XNode)\nFor Each Element In SchemaDoc.<Root>.<Group>\n If Not BasicGroups.Contains(Element.@Name) Then\n NodesToRemove.Add(Element)\n End If\nNext\n"
},
{
"answer_id": 1203412,
"author": "Joe Chung",
"author_id": 86483,
"author_profile": "https://Stackoverflow.com/users/86483",
"pm_score": 0,
"selected": false,
"text": "Dim NodesToRemove = From Element In SchemaDoc.Root.<Group> _\n Where Not BasicGroups.Contains(Element.@Name)\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] |
221,520
|
<p>I don't understand, why does the following regular expression:</p>
<pre><code>^*$
</code></pre>
<p>Match the string "127.0.0.1"? Using <code>Regex.IsMatch("127.0.0.1", "^*$");</code></p>
<p>Using Expresso, it does not match, which is also what I would expect. Using the expression <code>^.*$</code> does match the string, which I would also expect.</p>
<p>Technically, <code>^*$</code> should match the beginning of a string/line any number of times, followed by the ending of the string/line. It seems * is implicitly treated as a <code>.*</code></p>
<p>What am I missing?</p>
<p>EDIT:
Run the following to see an example of the problem.</p>
<pre><code>using System;
using System.Text.RegularExpressions;
namespace RegexFubar
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Regex.IsMatch("127.0.0.1", "^*$"));
Console.Read();
}
}
}
</code></pre>
<p>I do not wish to have ^*$ match my string, I am wondering why it <strong>does</strong> match it. I would think that the expression should result in an exception being thrown, or at least a non-match.</p>
<p>EDIT2:
To clear up any confusion. I did not write this regex with the intention of having it match "127.0.0.1". A user of our application entered the expression and wondered why it matched the string when it should not. After looking at it, I could not come up with an explanation for why it matched - especially not since Expresso and .NET seems to handle it differently.</p>
<p>I guess the question is answered by it being due to the .NET implementation avoiding throwing an exception, even thought it's technically an incorrect expression. But is this really what we want?</p>
|
[
{
"answer_id": 221537,
"author": "Richard Nienaber",
"author_id": 9539,
"author_profile": "https://Stackoverflow.com/users/9539",
"pm_score": -1,
"selected": false,
"text": "^+$\n"
},
{
"answer_id": 221545,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 6,
"selected": true,
"text": "# echo -n 127.0.0.1 | perl -n -e 'print (($_ =~ m/(^.*$)/)[0]),\"\\n\";'\n-> 127.0.0.1\n# echo -n 127.0.0.1 | perl -n -e 'print (($_ =~ m/(^*$)/)[0]),\"\\n\";'\n->\n"
},
{
"answer_id": 221559,
"author": "ptor",
"author_id": 28176,
"author_profile": "https://Stackoverflow.com/users/28176",
"pm_score": 0,
"selected": false,
"text": "^*$ ^ $ * /^.**$/"
},
{
"answer_id": 221649,
"author": "Lucas",
"author_id": 24231,
"author_profile": "https://Stackoverflow.com/users/24231",
"pm_score": 2,
"selected": false,
"text": "Regex.Match(\"127.0.0.1\", \"^*1$\")\n"
},
{
"answer_id": 221903,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 0,
"selected": false,
"text": "^ $ * ^"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12469/"
] |
221,523
|
<p>I would like to hide the UISearchBar most of the time and only call it to appear when user wants it. </p>
<p>I've put a UISearchBar in Interface Builder and hide it behind a view, when user click a button, it calls the following code, which I hoped it would bring the search bar to the front and slide the keyboard to view. But it doesn't....</p>
<pre><code>- (IBAction)search:(id)sender
{
[mySearchBar performSelector:@selector(searchBarTextDidBeginEditing:)];
}
</code></pre>
<p>Anyone have any idea how to activate UISearchBar by code?</p>
<p>Thanks. </p>
<p>Thanks for your replies. I just post the complete code in case someone's interested</p>
<pre><code>- (IBAction)search:(id)sender
{
mySearchBar.hidden = NO;
[mySearchBar becomeFirstResponder];
}
#pragma mark UISearchBarDelegate delegate methods
// called when keyboard search button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
mySearchBar.hidden = YES;
[mySearchBar resignFirstResponder];
// Do something with the mySearchBar.text
}
// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
mySearchBar.hidden = YES;
[mySearchBar resignFirstResponder];
}
</code></pre>
|
[
{
"answer_id": 221581,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 2,
"selected": false,
"text": "mySearchBar.hidden = NO;\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9774/"
] |
221,525
|
<p>Please don't say EHCache or OSCache, etc. Assume for purposes of this question that I want to implement my own using just the SDK (learning by doing). Given that the cache will be used in a multithreaded environment, which datastructures would you use? I've already implemented one using <a href="http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html" rel="noreferrer">LinkedHashMap</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map)" rel="noreferrer">Collections#synchronizedMap</a>, but I'm curious if any of the new concurrent collections would be better candidates.</p>
<p>UPDATE: I was just reading through <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html" rel="noreferrer">Yegge's latest</a> when I found this nugget:</p>
<blockquote>
<p>If you need constant-time access and want to maintain the insertion order, you can't do better than a LinkedHashMap, a truly wonderful data structure. The only way it could possibly be more wonderful is if there were a concurrent version. But alas.</p>
</blockquote>
<p>I was thinking almost exactly the same thing before I went with the <code>LinkedHashMap</code> + <code>Collections#synchronizedMap</code> implementation I mentioned above. Nice to know I hadn't just overlooked something.</p>
<p>Based on the answers so far, it sounds like my best bet for a highly concurrent LRU would be to extend <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer">ConcurrentHashMap</a> using some of the same logic that <code>LinkedHashMap</code> uses.</p>
|
[
{
"answer_id": 221546,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 3,
"selected": false,
"text": "class CacheElement {\n private final Object obj;\n private int numberOfUsers = 0;\n\n CacheElement(Object obj) {\n this.obj = obj;\n }\n\n ... etc.\n}\n"
},
{
"answer_id": 224256,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 2,
"selected": false,
"text": "import java.util.HashMap;\nimport java.util.Map;\npublic class LRUCache<K, V>\n{\n int maxSize;\n int currentSize = 0;\n\n Map<K, ValueHolder<K, V>> map;\n LinkedList<K> queue;\n\n public LRUCache(int maxSize)\n {\n this.maxSize = maxSize;\n map = new HashMap<K, ValueHolder<K, V>>();\n queue = new LinkedList<K>();\n }\n\n private void freeSpace()\n {\n K k = queue.remove();\n map.remove(k);\n currentSize--;\n }\n\n public void put(K key, V val)\n {\n while(currentSize >= maxSize)\n {\n freeSpace();\n }\n if(map.containsKey(key))\n {//just heat up that item\n get(key);\n return;\n }\n ListNode<K> ln = queue.add(key);\n ValueHolder<K, V> rv = new ValueHolder<K, V>(val, ln);\n map.put(key, rv); \n currentSize++;\n }\n\n public V get(K key)\n {\n ValueHolder<K, V> rv = map.get(key);\n if(rv == null) return null;\n queue.remove(rv.queueLocation);\n rv.queueLocation = queue.add(key);//this ensures that each item has only one copy of the key in the queue\n return rv.value;\n }\n}\n\nclass ListNode<K>\n{\n ListNode<K> prev;\n ListNode<K> next;\n K value;\n public ListNode(K v)\n {\n value = v;\n prev = null;\n next = null;\n }\n}\n\nclass ValueHolder<K,V>\n{\n V value;\n ListNode<K> queueLocation;\n public ValueHolder(V value, ListNode<K> ql)\n {\n this.value = value;\n this.queueLocation = ql;\n }\n}\n\nclass LinkedList<K>\n{\n ListNode<K> head = null;\n ListNode<K> tail = null;\n\n public ListNode<K> add(K v)\n {\n if(head == null)\n {\n assert(tail == null);\n head = tail = new ListNode<K>(v);\n }\n else\n {\n tail.next = new ListNode<K>(v);\n tail.next.prev = tail;\n tail = tail.next;\n if(tail.prev == null)\n {\n tail.prev = head;\n head.next = tail;\n }\n }\n return tail;\n }\n\n public K remove()\n {\n if(head == null)\n return null;\n K val = head.value;\n if(head.next == null)\n {\n head = null;\n tail = null;\n }\n else\n {\n head = head.next;\n head.prev = null;\n }\n return val;\n }\n\n public void remove(ListNode<K> ln)\n {\n ListNode<K> prev = ln.prev;\n ListNode<K> next = ln.next;\n if(prev == null)\n {\n head = next;\n }\n else\n {\n prev.next = next;\n }\n if(next == null)\n {\n tail = prev;\n }\n else\n {\n next.prev = prev;\n } \n }\n}\n"
},
{
"answer_id": 613495,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "LinkedHashMap LinkedHashMap LinkedHashMap[4], index 0, 1, 2, 3 key%4 binary OR [key, 3] ConcurrentHashMap LinkedHashMap put putIfAbsent ConcurrentHashMap ConcurrentHashMap HashMap"
},
{
"answer_id": 1953516,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 7,
"selected": false,
"text": "LinkedHashMap Collections.synchronizedMap ConcurrentHashMap LinkedHashMap HashMap private class LruCache<A, B> extends LinkedHashMap<A, B> {\n private final int maxEntries;\n\n public LruCache(final int maxEntries) {\n super(maxEntries + 1, 1.0f, true);\n this.maxEntries = maxEntries;\n }\n\n /**\n * Returns <tt>true</tt> if this <code>LruCache</code> has more entries than the maximum specified when it was\n * created.\n *\n * <p>\n * This method <em>does not</em> modify the underlying <code>Map</code>; it relies on the implementation of\n * <code>LinkedHashMap</code> to do that, but that behavior is documented in the JavaDoc for\n * <code>LinkedHashMap</code>.\n * </p>\n *\n * @param eldest\n * the <code>Entry</code> in question; this implementation doesn't care what it is, since the\n * implementation is only dependent on the size of the cache\n * @return <tt>true</tt> if the oldest\n * @see java.util.LinkedHashMap#removeEldestEntry(Map.Entry)\n */\n @Override\n protected boolean removeEldestEntry(final Map.Entry<A, B> eldest) {\n return super.size() > maxEntries;\n }\n}\n\nMap<String, String> example = Collections.synchronizedMap(new LruCache<String, String>(CACHE_SIZE));\n"
},
{
"answer_id": 3444210,
"author": "Raj Pandian",
"author_id": 415550,
"author_profile": "https://Stackoverflow.com/users/415550",
"pm_score": 0,
"selected": false,
"text": "LinkedHashMap Collections#synchronizedMap LRUMap implements Map ArrayIndexOutofBoundException private void moveToFront(int index) {\n if (listHead != index) {\n int thisNext = nextElement[index];\n int thisPrev = prevElement[index];\n nextElement[thisPrev] = thisNext;\n if (thisNext >= 0) {\n prevElement[thisNext] = thisPrev;\n } else {\n listTail = thisPrev;\n }\n //old listHead and new listHead say new is 1 and old was 0 then prev[1]= 1 is the head now so no previ so -1\n // prev[0 old head] = new head right ; next[new head] = old head\n prevElement[index] = -1;\n nextElement[index] = listHead;\n prevElement[listHead] = index;\n listHead = index;\n }\n }\n get(Object key) put(Object key, Object value) moveToFront"
},
{
"answer_id": 6125609,
"author": "Zoltan Boda",
"author_id": 769703,
"author_profile": "https://Stackoverflow.com/users/769703",
"pm_score": 1,
"selected": false,
"text": "package util.collection;\n\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\n\n/**\n * Limited size concurrent cache map implementation.<br/>\n * LRU: Least Recently Used.<br/>\n * If you add a new key-value pair to this cache after the maximum size has been exceeded,\n * the oldest key-value pair will be removed before adding.\n */\n\npublic class ConcurrentLRUCache<Key, Value> {\n\nprivate final int maxSize;\nprivate int currentSize = 0;\n\nprivate ConcurrentHashMap<Key, Value> map;\nprivate ConcurrentLinkedQueue<Key> queue;\n\npublic ConcurrentLRUCache(final int maxSize) {\n this.maxSize = maxSize;\n map = new ConcurrentHashMap<Key, Value>(maxSize);\n queue = new ConcurrentLinkedQueue<Key>();\n}\n\nprivate synchronized void freeSpace() {\n Key key = queue.poll();\n if (null != key) {\n map.remove(key);\n currentSize = map.size();\n }\n}\n\npublic void put(Key key, Value val) {\n if (map.containsKey(key)) {// just heat up that item\n put(key, val);\n return;\n }\n while (currentSize >= maxSize) {\n freeSpace();\n }\n synchronized(this) {\n queue.add(key);\n map.put(key, val);\n currentSize++;\n }\n}\n\npublic Value get(Key key) {\n return map.get(key);\n}\n}\n"
},
{
"answer_id": 6137948,
"author": "Zoltan Boda",
"author_id": 771233,
"author_profile": "https://Stackoverflow.com/users/771233",
"pm_score": 2,
"selected": false,
"text": "public class ConcurrentLRUCache<Key, Value> {\n\nprivate final int maxSize;\n\nprivate ConcurrentHashMap<Key, Value> map;\nprivate ConcurrentLinkedQueue<Key> queue;\n\npublic ConcurrentLRUCache(final int maxSize) {\n this.maxSize = maxSize;\n map = new ConcurrentHashMap<Key, Value>(maxSize);\n queue = new ConcurrentLinkedQueue<Key>();\n}\n\n/**\n * @param key - may not be null!\n * @param value - may not be null!\n */\npublic void put(final Key key, final Value value) {\n if (map.containsKey(key)) {\n queue.remove(key); // remove the key from the FIFO queue\n }\n\n while (queue.size() >= maxSize) {\n Key oldestKey = queue.poll();\n if (null != oldestKey) {\n map.remove(oldestKey);\n }\n }\n queue.add(key);\n map.put(key, value);\n}\n\n/**\n * @param key - may not be null!\n * @return the value associated to the given key or null\n */\npublic Value get(final Key key) {\n return map.get(key);\n}\n"
},
{
"answer_id": 11858494,
"author": "Abhishek Gayakwad",
"author_id": 741882,
"author_profile": "https://Stackoverflow.com/users/741882",
"pm_score": 0,
"selected": false,
"text": " /**\n * This method is invoked by the superclass whenever the value\n * of a pre-existing entry is read by Map.get or modified by Map.set.\n * If the enclosing Map is access-ordered, it moves the entry\n * to the end of the list; otherwise, it does nothing.\n */\n void recordAccess(HashMap<K,V> m) {\n LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;\n if (lm.accessOrder) {\n lm.modCount++;\n remove();\n addBefore(lm.header);\n }\n }\n"
},
{
"answer_id": 13851929,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 5,
"selected": true,
"text": "CacheBuilder"
},
{
"answer_id": 15008085,
"author": "broc.seib",
"author_id": 516910,
"author_profile": "https://Stackoverflow.com/users/516910",
"pm_score": 2,
"selected": false,
"text": "CacheBuilder import java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\n\npublic class MaxIdleLRUCache<KK, VV> {\n\n final static private int IDEAL_MAX_CACHE_ENTRIES = 128;\n\n public interface DeadElementCallback<KK, VV> {\n public void notify(KK key, VV element);\n }\n\n private Object lock = new Object();\n private long minAge;\n private HashMap<KK, Item<VV>> cache;\n\n\n public MaxIdleLRUCache(long minAgeMilliseconds) {\n this(minAgeMilliseconds, IDEAL_MAX_CACHE_ENTRIES);\n }\n\n public MaxIdleLRUCache(long minAgeMilliseconds, int idealMaxCacheEntries) {\n this(minAgeMilliseconds, idealMaxCacheEntries, null);\n }\n\n public MaxIdleLRUCache(long minAgeMilliseconds, int idealMaxCacheEntries, final DeadElementCallback<KK, VV> callback) {\n this.minAge = minAgeMilliseconds;\n this.cache = new LinkedHashMap<KK, Item<VV>>(IDEAL_MAX_CACHE_ENTRIES + 1, .75F, true) {\n private static final long serialVersionUID = 1L;\n\n // This method is called just after a new entry has been added\n public boolean removeEldestEntry(Map.Entry<KK, Item<VV>> eldest) {\n // let's see if the oldest entry is old enough to be deleted. We don't actually care about the cache size.\n long age = System.currentTimeMillis() - eldest.getValue().birth;\n if (age > MaxIdleLRUCache.this.minAge) {\n if ( callback != null ) {\n callback.notify(eldest.getKey(), eldest.getValue().payload);\n }\n return true; // remove it\n }\n return false; // don't remove this element\n }\n };\n\n }\n\n public void put(KK key, VV value) {\n synchronized ( lock ) {\n// System.out.println(\"put->\"+key+\",\"+value);\n cache.put(key, new Item<VV>(value));\n }\n }\n\n public VV get(KK key) {\n synchronized ( lock ) {\n// System.out.println(\"get->\"+key);\n Item<VV> item = getItem(key);\n return item == null ? null : item.payload;\n }\n }\n\n public VV remove(String key) {\n synchronized ( lock ) {\n// System.out.println(\"remove->\"+key);\n Item<VV> item = cache.remove(key);\n if ( item != null ) {\n return item.payload;\n } else {\n return null;\n }\n }\n }\n\n public int size() {\n synchronized ( lock ) {\n return cache.size();\n }\n }\n\n private Item<VV> getItem(KK key) {\n Item<VV> item = cache.get(key);\n if (item == null) {\n return null;\n }\n item.touch(); // idle the item to reset the timeout threshold\n return item;\n }\n\n private static class Item<T> {\n long birth;\n T payload;\n\n Item(T payload) {\n this.birth = System.currentTimeMillis();\n this.payload = payload;\n }\n\n public void touch() {\n this.birth = System.currentTimeMillis();\n }\n }\n\n}\n"
},
{
"answer_id": 16001454,
"author": "Deepak Singhvi",
"author_id": 2279035,
"author_profile": "https://Stackoverflow.com/users/2279035",
"pm_score": 2,
"selected": false,
"text": "import java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.PriorityQueue;\n\n\npublic class LRUForCache {\n private PriorityQueue<LRUPage> priorityQueue = new PriorityQueue<LRUPage>(3, new LRUPageComparator());\n public static void main(String[] args) throws InterruptedException {\n\n System.out.println(\" Pages for consideration : 2, 1, 0, 2, 8, 2, 4\");\n System.out.println(\"----------------------------------------------\\n\");\n\n LRUForCache cache = new LRUForCache();\n cache.addPageToQueue(new LRUPage(\"2\"));\n Thread.sleep(100);\n cache.addPageToQueue(new LRUPage(\"1\"));\n Thread.sleep(100);\n cache.addPageToQueue(new LRUPage(\"0\"));\n Thread.sleep(100);\n cache.addPageToQueue(new LRUPage(\"2\"));\n Thread.sleep(100);\n cache.addPageToQueue(new LRUPage(\"8\"));\n Thread.sleep(100);\n cache.addPageToQueue(new LRUPage(\"2\"));\n Thread.sleep(100);\n cache.addPageToQueue(new LRUPage(\"4\"));\n Thread.sleep(100);\n\n System.out.println(\"\\nLRUCache Pages\");\n System.out.println(\"-------------\");\n cache.displayPriorityQueue();\n }\n\n\n public synchronized void addPageToQueue(LRUPage page){\n boolean pageExists = false;\n if(priorityQueue.size() == 3){\n Iterator<LRUPage> iterator = priorityQueue.iterator();\n\n while(iterator.hasNext()){\n LRUPage next = iterator.next();\n if(next.getPageName().equals(page.getPageName())){\n /* wanted to just change the time, so that no need to poll and add again.\n but elements ordering does not happen, it happens only at the time of adding\n to the queue\n\n In case somebody finds it, plz let me know.\n */\n //next.setPageCreationTime(page.getPageCreationTime()); \n\n priorityQueue.remove(next);\n System.out.println(\"Page: \" + page.getPageName() + \" already exisit in cache. Last accessed time updated\");\n pageExists = true;\n break;\n }\n }\n if(!pageExists){\n // enable it for printing the queue elemnts\n //System.out.println(priorityQueue);\n LRUPage poll = priorityQueue.poll();\n System.out.println(\"Page Fault, PAGE: \" + poll.getPageName()+\", Replaced with PAGE: \"+page.getPageName());\n\n }\n }\n if(!pageExists){\n System.out.println(\"Page added into cache is : \" + page.getPageName());\n }\n priorityQueue.add(page);\n\n }\n\n public void displayPriorityQueue(){\n Iterator<LRUPage> iterator = priorityQueue.iterator();\n while(iterator.hasNext()){\n LRUPage next = iterator.next();\n System.out.println(next);\n }\n }\n}\n\nclass LRUPage{\n private String pageName;\n private long pageCreationTime;\n public LRUPage(String pagename){\n this.pageName = pagename;\n this.pageCreationTime = System.currentTimeMillis();\n }\n\n public String getPageName() {\n return pageName;\n }\n\n public long getPageCreationTime() {\n return pageCreationTime;\n }\n\n public void setPageCreationTime(long pageCreationTime) {\n this.pageCreationTime = pageCreationTime;\n }\n\n @Override\n public boolean equals(Object obj) {\n LRUPage page = (LRUPage)obj; \n if(pageCreationTime == page.pageCreationTime){\n return true;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return (int) (31 * pageCreationTime);\n }\n\n @Override\n public String toString() {\n return \"PageName: \" + pageName +\", PageCreationTime: \"+pageCreationTime;\n }\n}\n\n\nclass LRUPageComparator implements Comparator<LRUPage>{\n\n @Override\n public int compare(LRUPage o1, LRUPage o2) {\n if(o1.getPageCreationTime() > o2.getPageCreationTime()){\n return 1;\n }\n if(o1.getPageCreationTime() < o2.getPageCreationTime()){\n return -1;\n }\n return 0;\n }\n}\n"
},
{
"answer_id": 16215471,
"author": "Deepak Singhvi",
"author_id": 2279035,
"author_profile": "https://Stackoverflow.com/users/2279035",
"pm_score": 0,
"selected": false,
"text": "import java.util.LinkedHashMap;\nimport java.util.Map;\n\n/**\n * @author Deepak Singhvi\n *\n */\npublic class LRUCacheUsingLinkedHashMap {\n\n\n private static int CACHE_SIZE = 3;\n public static void main(String[] args) {\n System.out.println(\" Pages for consideration : 2, 1, 0, 2, 8, 2, 4,99\");\n System.out.println(\"----------------------------------------------\\n\");\n\n\n// accessOrder is true, so whenever any page gets changed or accessed, // its order will change in the map, \n LinkedHashMap<Integer,String> lruCache = new \n LinkedHashMap<Integer,String>(CACHE_SIZE, .75F, true) {\n\n private static final long serialVersionUID = 1L;\n\n protected boolean removeEldestEntry(Map.Entry<Integer,String> \n\n eldest) {\n return size() > CACHE_SIZE;\n }\n\n };\n\n lruCache.put(2, \"2\");\n lruCache.put(1, \"1\");\n lruCache.put(0, \"0\");\n System.out.println(lruCache + \" , After first 3 pages in cache\");\n lruCache.put(2, \"2\");\n System.out.println(lruCache + \" , Page 2 became the latest page in the cache\");\n lruCache.put(8, \"8\");\n System.out.println(lruCache + \" , Adding page 8, which removes eldest element 2 \");\n lruCache.put(2, \"2\");\n System.out.println(lruCache+ \" , Page 2 became the latest page in the cache\");\n lruCache.put(4, \"4\");\n System.out.println(lruCache+ \" , Adding page 4, which removes eldest element 1 \");\n lruCache.put(99, \"99\");\n System.out.println(lruCache + \" , Adding page 99, which removes eldest element 8 \");\n\n }\n\n}\n Pages for consideration : 2, 1, 0, 2, 8, 2, 4,99\n--------------------------------------------------\n {2=2, 1=1, 0=0} , After first 3 pages in cache\n {2=2, 1=1, 0=0} , Page 2 became the latest page in the cache\n {1=1, 0=0, 8=8} , Adding page 8, which removes eldest element 2 \n {0=0, 8=8, 2=2} , Page 2 became the latest page in the cache\n {8=8, 2=2, 4=4} , Adding page 4, which removes eldest element 1 \n {2=2, 4=4, 99=99} , Adding page 99, which removes eldest element 8 \n"
},
{
"answer_id": 20644976,
"author": "RickHigh",
"author_id": 2876739,
"author_profile": "https://Stackoverflow.com/users/2876739",
"pm_score": 3,
"selected": false,
"text": "import java.util.LinkedHashMap;\nimport java.util.Map;\n\npublic class LruSimpleCache<K, V> implements LruCache <K, V>{\n\n Map<K, V> map = new LinkedHashMap ( );\n\n\n public LruSimpleCache (final int limit) {\n map = new LinkedHashMap <K, V> (16, 0.75f, true) {\n @Override\n protected boolean removeEldestEntry(final Map.Entry<K, V> eldest) {\n return super.size() > limit;\n }\n };\n }\n @Override\n public void put ( K key, V value ) {\n map.put ( key, value );\n }\n\n @Override\n public V get ( K key ) {\n return map.get(key);\n }\n\n //For testing only\n @Override\n public V getSilent ( K key ) {\n V value = map.get ( key );\n if (value!=null) {\n map.remove ( key );\n map.put(key, value);\n }\n return value;\n }\n\n @Override\n public void remove ( K key ) {\n map.remove ( key );\n }\n\n @Override\n public int size () {\n return map.size ();\n }\n\n public String toString() {\n return map.toString ();\n }\n\n\n}\n public class LruSimpleTest {\n\n @Test\n public void test () {\n LruCache <Integer, Integer> cache = new LruSimpleCache<> ( 4 );\n\n\n cache.put ( 0, 0 );\n cache.put ( 1, 1 );\n\n cache.put ( 2, 2 );\n cache.put ( 3, 3 );\n\n\n boolean ok = cache.size () == 4 || die ( \"size\" + cache.size () );\n\n\n cache.put ( 4, 4 );\n cache.put ( 5, 5 );\n ok |= cache.size () == 4 || die ( \"size\" + cache.size () );\n ok |= cache.getSilent ( 2 ) == 2 || die ();\n ok |= cache.getSilent ( 3 ) == 3 || die ();\n ok |= cache.getSilent ( 4 ) == 4 || die ();\n ok |= cache.getSilent ( 5 ) == 5 || die ();\n\n\n cache.get ( 2 );\n cache.get ( 3 );\n cache.put ( 6, 6 );\n cache.put ( 7, 7 );\n ok |= cache.size () == 4 || die ( \"size\" + cache.size () );\n ok |= cache.getSilent ( 2 ) == 2 || die ();\n ok |= cache.getSilent ( 3 ) == 3 || die ();\n ok |= cache.getSilent ( 4 ) == null || die ();\n ok |= cache.getSilent ( 5 ) == null || die ();\n\n\n if ( !ok ) die ();\n\n }\n import java.util.LinkedHashMap;\nimport java.util.Map;\nimport java.util.concurrent.locks.ReadWriteLock;\nimport java.util.concurrent.locks.ReentrantReadWriteLock;\n\npublic class LruSimpleConcurrentCache<K, V> implements LruCache<K, V> {\n\n final CacheMap<K, V>[] cacheRegions;\n\n\n private static class CacheMap<K, V> extends LinkedHashMap<K, V> {\n private final ReadWriteLock readWriteLock;\n private final int limit;\n\n CacheMap ( final int limit, boolean fair ) {\n super ( 16, 0.75f, true );\n this.limit = limit;\n readWriteLock = new ReentrantReadWriteLock ( fair );\n\n }\n\n protected boolean removeEldestEntry ( final Map.Entry<K, V> eldest ) {\n return super.size () > limit;\n }\n\n\n @Override\n public V put ( K key, V value ) {\n readWriteLock.writeLock ().lock ();\n\n V old;\n try {\n\n old = super.put ( key, value );\n } finally {\n readWriteLock.writeLock ().unlock ();\n }\n return old;\n\n }\n\n\n @Override\n public V get ( Object key ) {\n readWriteLock.writeLock ().lock ();\n V value;\n\n try {\n\n value = super.get ( key );\n } finally {\n readWriteLock.writeLock ().unlock ();\n }\n return value;\n }\n\n @Override\n public V remove ( Object key ) {\n\n readWriteLock.writeLock ().lock ();\n V value;\n\n try {\n\n value = super.remove ( key );\n } finally {\n readWriteLock.writeLock ().unlock ();\n }\n return value;\n\n }\n\n public V getSilent ( K key ) {\n readWriteLock.writeLock ().lock ();\n\n V value;\n\n try {\n\n value = this.get ( key );\n if ( value != null ) {\n this.remove ( key );\n this.put ( key, value );\n }\n } finally {\n readWriteLock.writeLock ().unlock ();\n }\n return value;\n\n }\n\n public int size () {\n readWriteLock.readLock ().lock ();\n int size = -1;\n try {\n size = super.size ();\n } finally {\n readWriteLock.readLock ().unlock ();\n }\n return size;\n }\n\n public String toString () {\n readWriteLock.readLock ().lock ();\n String str;\n try {\n str = super.toString ();\n } finally {\n readWriteLock.readLock ().unlock ();\n }\n return str;\n }\n\n\n }\n\n public LruSimpleConcurrentCache ( final int limit, boolean fair ) {\n int cores = Runtime.getRuntime ().availableProcessors ();\n int stripeSize = cores < 2 ? 4 : cores * 2;\n cacheRegions = new CacheMap[ stripeSize ];\n for ( int index = 0; index < cacheRegions.length; index++ ) {\n cacheRegions[ index ] = new CacheMap<> ( limit / cacheRegions.length, fair );\n }\n }\n\n public LruSimpleConcurrentCache ( final int concurrency, final int limit, boolean fair ) {\n\n cacheRegions = new CacheMap[ concurrency ];\n for ( int index = 0; index < cacheRegions.length; index++ ) {\n cacheRegions[ index ] = new CacheMap<> ( limit / cacheRegions.length, fair );\n }\n }\n\n private int stripeIndex ( K key ) {\n int hashCode = key.hashCode () * 31;\n return hashCode % ( cacheRegions.length );\n }\n\n private CacheMap<K, V> map ( K key ) {\n return cacheRegions[ stripeIndex ( key ) ];\n }\n\n @Override\n public void put ( K key, V value ) {\n\n map ( key ).put ( key, value );\n }\n\n @Override\n public V get ( K key ) {\n return map ( key ).get ( key );\n }\n\n //For testing only\n @Override\n public V getSilent ( K key ) {\n return map ( key ).getSilent ( key );\n\n }\n\n @Override\n public void remove ( K key ) {\n map ( key ).remove ( key );\n }\n\n @Override\n public int size () {\n int size = 0;\n for ( CacheMap<K, V> cache : cacheRegions ) {\n size += cache.size ();\n }\n return size;\n }\n\n public String toString () {\n\n StringBuilder builder = new StringBuilder ();\n for ( CacheMap<K, V> cache : cacheRegions ) {\n builder.append ( cache.toString () ).append ( '\\n' );\n }\n\n return builder.toString ();\n }\n\n\n}\n public class SimpleConcurrentLRUCache {\n\n\n @Test\n public void test () {\n LruCache <Integer, Integer> cache = new LruSimpleConcurrentCache<> ( 1, 4, false );\n\n\n cache.put ( 0, 0 );\n cache.put ( 1, 1 );\n\n cache.put ( 2, 2 );\n cache.put ( 3, 3 );\n\n\n boolean ok = cache.size () == 4 || die ( \"size\" + cache.size () );\n\n\n cache.put ( 4, 4 );\n cache.put ( 5, 5 );\n\n puts (cache);\n ok |= cache.size () == 4 || die ( \"size\" + cache.size () );\n ok |= cache.getSilent ( 2 ) == 2 || die ();\n ok |= cache.getSilent ( 3 ) == 3 || die ();\n ok |= cache.getSilent ( 4 ) == 4 || die ();\n ok |= cache.getSilent ( 5 ) == 5 || die ();\n\n\n cache.get ( 2 );\n cache.get ( 3 );\n cache.put ( 6, 6 );\n cache.put ( 7, 7 );\n ok |= cache.size () == 4 || die ( \"size\" + cache.size () );\n ok |= cache.getSilent ( 2 ) == 2 || die ();\n ok |= cache.getSilent ( 3 ) == 3 || die ();\n\n cache.put ( 8, 8 );\n cache.put ( 9, 9 );\n\n ok |= cache.getSilent ( 4 ) == null || die ();\n ok |= cache.getSilent ( 5 ) == null || die ();\n\n\n puts (cache);\n\n\n if ( !ok ) die ();\n\n }\n\n\n @Test\n public void test2 () {\n LruCache <Integer, Integer> cache = new LruSimpleConcurrentCache<> ( 400, false );\n\n\n cache.put ( 0, 0 );\n cache.put ( 1, 1 );\n\n cache.put ( 2, 2 );\n cache.put ( 3, 3 );\n\n\n for (int index =0 ; index < 5_000; index++) {\n cache.get(0);\n cache.get ( 1 );\n cache.put ( 2, index );\n cache.put ( 3, index );\n cache.put(index, index);\n }\n\n boolean ok = cache.getSilent ( 0 ) == 0 || die ();\n ok |= cache.getSilent ( 1 ) == 1 || die ();\n ok |= cache.getSilent ( 2 ) != null || die ();\n ok |= cache.getSilent ( 3 ) != null || die ();\n\n ok |= cache.size () < 600 || die();\n if ( !ok ) die ();\n\n\n\n }\n\n}\n public interface LruCache<KEY, VALUE> {\n void put ( KEY key, VALUE value );\n\n VALUE get ( KEY key );\n\n VALUE getSilent ( KEY key );\n\n void remove ( KEY key );\n\n int size ();\n}\n import java.util.Deque;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.Map;\n\npublic class LruCacheNormal<KEY, VALUE> implements LruCache<KEY,VALUE> {\n\n Map<KEY, VALUE> map = new HashMap<> ();\n Deque<KEY> queue = new LinkedList<> ();\n final int limit;\n\n\n public LruCacheNormal ( int limit ) {\n this.limit = limit;\n }\n\n public void put ( KEY key, VALUE value ) {\n VALUE oldValue = map.put ( key, value );\n\n /*If there was already an object under this key,\n then remove it before adding to queue\n Frequently used keys will be at the top so the search could be fast.\n */\n if ( oldValue != null ) {\n queue.removeFirstOccurrence ( key );\n }\n queue.addFirst ( key );\n\n if ( map.size () > limit ) {\n final KEY removedKey = queue.removeLast ();\n map.remove ( removedKey );\n }\n\n }\n\n\n public VALUE get ( KEY key ) {\n\n /* Frequently used keys will be at the top so the search could be fast.*/\n queue.removeFirstOccurrence ( key );\n queue.addFirst ( key );\n return map.get ( key );\n }\n\n\n public VALUE getSilent ( KEY key ) {\n\n return map.get ( key );\n }\n\n public void remove ( KEY key ) {\n\n /* Frequently used keys will be at the top so the search could be fast.*/\n queue.removeFirstOccurrence ( key );\n map.remove ( key );\n }\n\n public int size () {\n return map.size ();\n }\n\n public String toString() {\n return map.toString ();\n }\n}\n public class LruCacheTest {\n\n @Test\n public void test () {\n LruCache<Integer, Integer> cache = new LruCacheNormal<> ( 4 );\n\n\n cache.put ( 0, 0 );\n cache.put ( 1, 1 );\n\n cache.put ( 2, 2 );\n cache.put ( 3, 3 );\n\n\n boolean ok = cache.size () == 4 || die ( \"size\" + cache.size () );\n ok |= cache.getSilent ( 0 ) == 0 || die ();\n ok |= cache.getSilent ( 3 ) == 3 || die ();\n\n\n cache.put ( 4, 4 );\n cache.put ( 5, 5 );\n ok |= cache.size () == 4 || die ( \"size\" + cache.size () );\n ok |= cache.getSilent ( 0 ) == null || die ();\n ok |= cache.getSilent ( 1 ) == null || die ();\n ok |= cache.getSilent ( 2 ) == 2 || die ();\n ok |= cache.getSilent ( 3 ) == 3 || die ();\n ok |= cache.getSilent ( 4 ) == 4 || die ();\n ok |= cache.getSilent ( 5 ) == 5 || die ();\n\n if ( !ok ) die ();\n\n }\n}\n import java.util.Deque;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.locks.ReentrantLock;\n\npublic class ConcurrentLruCache<KEY, VALUE> implements LruCache<KEY,VALUE> {\n\n private final ReentrantLock lock = new ReentrantLock ();\n\n\n private final Map<KEY, VALUE> map = new ConcurrentHashMap<> ();\n private final Deque<KEY> queue = new LinkedList<> ();\n private final int limit;\n\n\n public ConcurrentLruCache ( int limit ) {\n this.limit = limit;\n }\n\n @Override\n public void put ( KEY key, VALUE value ) {\n VALUE oldValue = map.put ( key, value );\n if ( oldValue != null ) {\n removeThenAddKey ( key );\n } else {\n addKey ( key );\n }\n if (map.size () > limit) {\n map.remove ( removeLast() );\n }\n }\n\n\n @Override\n public VALUE get ( KEY key ) {\n removeThenAddKey ( key );\n return map.get ( key );\n }\n\n\n private void addKey(KEY key) {\n lock.lock ();\n try {\n queue.addFirst ( key );\n } finally {\n lock.unlock ();\n }\n\n\n }\n\n private KEY removeLast( ) {\n lock.lock ();\n try {\n final KEY removedKey = queue.removeLast ();\n return removedKey;\n } finally {\n lock.unlock ();\n }\n }\n\n private void removeThenAddKey(KEY key) {\n lock.lock ();\n try {\n queue.removeFirstOccurrence ( key );\n queue.addFirst ( key );\n } finally {\n lock.unlock ();\n }\n\n }\n\n private void removeFirstOccurrence(KEY key) {\n lock.lock ();\n try {\n queue.removeFirstOccurrence ( key );\n } finally {\n lock.unlock ();\n }\n\n }\n\n\n @Override\n public VALUE getSilent ( KEY key ) {\n return map.get ( key );\n }\n\n @Override\n public void remove ( KEY key ) {\n removeFirstOccurrence ( key );\n map.remove ( key );\n }\n\n @Override\n public int size () {\n return map.size ();\n }\n\n public String toString () {\n return map.toString ();\n }\n}\n Map<KEY, VALUE> map = new LinkedHashMap<KEY, VALUE> () {\n\n @Override\n protected boolean removeEldestEntry ( Map.Entry<KEY, VALUE> eldest ) {\n return this.size () > limit;\n }\n };\n cache.get ( 2 );\n cache.get ( 3 );\n cache.put ( 6, 6 );\n cache.put ( 7, 7 );\n ok |= cache.size () == 4 || die ( \"size\" + cache.size () );\n ok |= cache.getSilent ( 2 ) == 2 || die ();\n ok |= cache.getSilent ( 3 ) == 3 || die ();\n ok |= cache.getSilent ( 4 ) == null || die ();\n ok |= cache.getSilent ( 5 ) == null || die ();\n import java.util.*;\n\npublic class FifoCache<KEY, VALUE> implements LruCache<KEY,VALUE> {\n\n final int limit;\n\n Map<KEY, VALUE> map = new LinkedHashMap<KEY, VALUE> () {\n\n @Override\n protected boolean removeEldestEntry ( Map.Entry<KEY, VALUE> eldest ) {\n return this.size () > limit;\n }\n };\n\n\n public LruCacheNormal ( int limit ) {\n this.limit = limit;\n }\n\n public void put ( KEY key, VALUE value ) {\n map.put ( key, value );\n\n\n }\n\n\n public VALUE get ( KEY key ) {\n\n return map.get ( key );\n }\n\n\n public VALUE getSilent ( KEY key ) {\n\n return map.get ( key );\n }\n\n public void remove ( KEY key ) {\n map.remove ( key );\n }\n\n public int size () {\n return map.size ();\n }\n\n public String toString() {\n return map.toString ();\n }\n}\n"
},
{
"answer_id": 22891780,
"author": "sanjanab",
"author_id": 3503127,
"author_profile": "https://Stackoverflow.com/users/3503127",
"pm_score": 3,
"selected": false,
"text": "import java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\n\npublic class LRUCache<K,V> {\n private ConcurrentHashMap<K,V> map;\n private ConcurrentLinkedQueue<K> queue;\n private final int size; \n\n public LRUCache(int size) {\n this.size = size;\n map = new ConcurrentHashMap<K,V>(size);\n queue = new ConcurrentLinkedQueue<K>();\n }\n\n public V get(K key) {\n //Recently accessed, hence move it to the tail\n queue.remove(key);\n queue.add(key);\n return map.get(key);\n }\n\n public void put(K key, V value) {\n //ConcurrentHashMap doesn't allow null key or values\n if(key == null || value == null) throw new NullPointerException();\n if(map.containsKey(key) {\n queue.remove(key);\n }\n if(queue.size() >= size) {\n K lruKey = queue.poll();\n if(lruKey != null) {\n map.remove(lruKey);\n }\n }\n queue.add(key);\n map.put(key,value);\n }\n\n}\n"
},
{
"answer_id": 26601181,
"author": "murasing",
"author_id": 1973026,
"author_profile": "https://Stackoverflow.com/users/1973026",
"pm_score": 3,
"selected": false,
"text": "import java.util.*;\npublic class Lru {\n\npublic static <K,V> Map<K,V> lruCache(final int maxSize) {\n return new LinkedHashMap<K, V>(maxSize*4/3, 0.75f, true) {\n\n private static final long serialVersionUID = -3588047435434569014L;\n\n @Override\n protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {\n return size() > maxSize;\n }\n };\n }\n public static void main(String[] args ) {\n Map<Object, Object> lru = Lru.lruCache(2); \n lru.put(\"1\", \"1\");\n lru.put(\"2\", \"2\");\n lru.put(\"3\", \"3\");\n System.out.println(lru);\n}\n}\n"
},
{
"answer_id": 54446613,
"author": "Aleksander Lech",
"author_id": 2440071,
"author_profile": "https://Stackoverflow.com/users/2440071",
"pm_score": 0,
"selected": false,
"text": "public class LRUCache<K, V> {\n\n private ConcurrentHashMap<K, V> map;\n private final Consumer<V> onRemove;\n private ConcurrentLinkedQueue<K> queue;\n private final int size;\n\n public LRUCache(int size, Consumer<V> onRemove) {\n this.size = size;\n this.onRemove = onRemove;\n this.map = new ConcurrentHashMap<>(size);\n this.queue = new ConcurrentLinkedQueue<>();\n }\n\n public V get(K key) {\n //Recently accessed, hence move it to the tail\n if (queue.remove(key)) {\n queue.add(key);\n return map.get(key);\n }\n return null;\n }\n\n public void put(K key, V value) {\n //ConcurrentHashMap doesn't allow null key or values\n if (key == null || value == null) throw new IllegalArgumentException(\"key and value cannot be null!\");\n\n V existing = map.get(key);\n if (existing != null) {\n queue.remove(key);\n onRemove.accept(existing);\n }\n\n if (map.size() >= size) {\n K lruKey = queue.poll();\n if (lruKey != null) {\n V removed = map.remove(lruKey);\n onRemove.accept(removed);\n }\n }\n queue.add(key);\n map.put(key, value);\n }\n}\n"
},
{
"answer_id": 61573269,
"author": "Dhirendra Gautam",
"author_id": 9332102,
"author_profile": "https://Stackoverflow.com/users/9332102",
"pm_score": 2,
"selected": false,
"text": "public class Solution {\n\nMap<Integer,Integer> cache;\nint capacity;\npublic Solution(int capacity) {\n this.cache = new LinkedHashMap<Integer,Integer>(capacity); \n this.capacity = capacity;\n\n}\n\n// This function returns false if key is not \n// present in cache. Else it moves the key to \n// front by first removing it and then adding \n// it, and returns true. \n\npublic int get(int key) {\nif (!cache.containsKey(key)) \n return -1; \n int value = cache.get(key);\n cache.remove(key); \n cache.put(key,value); \n return cache.get(key); \n\n}\n\npublic void set(int key, int value) {\n\n // If already present, then \n // remove it first we are going to add later \n if(cache.containsKey(key)){\n cache.remove(key);\n }\n // If cache size is full, remove the least \n // recently used. \n else if (cache.size() == capacity) { \n Iterator<Integer> iterator = cache.keySet().iterator();\n cache.remove(iterator.next()); \n }\n cache.put(key,value);\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4203/"
] |
221,534
|
<p>What are the <strong>differences</strong> in considerations in respect to designing or developing an <strong>Intranet and an Internet application</strong> ?</p>
|
[
{
"answer_id": 221632,
"author": "Jon Schneider",
"author_id": 12484,
"author_profile": "https://Stackoverflow.com/users/12484",
"pm_score": 3,
"selected": false,
"text": "\\\\corporateserver\\devteam\\ArchitectureDiagram.vsd"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11614/"
] |
221,539
|
<p>I've seen this in a few <a href="https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript#221357">places</a></p>
<pre><code>function fn() {
return +new Date;
}
</code></pre>
<p>And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing.</p>
<p>Can anyone explain?</p>
|
[
{
"answer_id": 221560,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 6,
"selected": false,
"text": ">>> +new Date()\n1224589625406\n>>> +\"3\"\n3\n>>> +true\n1\n>>> 3 == \"3\"\ntrue\n"
},
{
"answer_id": 221565,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 9,
"selected": true,
"text": "+ function(){ return Number(new Date); }\n"
},
{
"answer_id": 32494974,
"author": "Dev",
"author_id": 1302592,
"author_profile": "https://Stackoverflow.com/users/1302592",
"pm_score": 3,
"selected": false,
"text": "var date = +new Date(); //same as 'var date =number(new Date());'\n"
},
{
"answer_id": 39555703,
"author": "Raghavendra",
"author_id": 1177295,
"author_profile": "https://Stackoverflow.com/users/1177295",
"pm_score": 2,
"selected": false,
"text": "+new Date() valueOf() toString() new Date().valueOf() == (+new Date) // true\n"
},
{
"answer_id": 52835113,
"author": "S.Serpooshan",
"author_id": 2803565,
"author_profile": "https://Stackoverflow.com/users/2803565",
"pm_score": 2,
"selected": false,
"text": "var d1 = new Date(\"2000/01/01 00:00:00\"); \nvar d2 = new Date(\"2000/01/01 00:00:01\"); //one second later\n\nvar t = d2 - d1; //will be 1000 (msec) = 1 sec\n\ntypeof t; // \"number\"\n t = new Date() - 0; //numeric value of Date: number of msec's since 1 Jan 1970.\ntypeof t; // \"number\"\n + typeof (+new Date()) //\"number\"\n 0 + new Date() 0 + new Date() // \"0Tue Oct 16 05:03:24 PDT 2018\"\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
221,568
|
<p>Is there a way in SWT to get a monospaced font simply, that works across various operating systems?</p>
<p>For example. this works on Linux, but not Windows:</p>
<pre>
<code>
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
</code>
</pre>
<p>or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.</p>
<p>I tried getting the system font from Display, but that wasn't monospaced.</p>
|
[
{
"answer_id": 222885,
"author": "fhe",
"author_id": 4445,
"author_profile": "https://Stackoverflow.com/users/4445",
"pm_score": 5,
"selected": true,
"text": "Font mono = new Font(parent.getDisplay(), \"Monospaced\", 10, SWT.NONE);"
},
{
"answer_id": 226404,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 2,
"selected": false,
"text": "private static Font loadMonospacedFont(Display display) {\n String jreHome = System.getProperty(\"java.home\");\n File file = new File(jreHome, \"/lib/fonts/LucidaTypewriterRegular.ttf\");\n if (!file.exists()) {\n throw new IllegalStateException(file.toString());\n }\n if (!display.loadFont(file.toString())) {\n throw new IllegalStateException(file.toString());\n }\n final Font font = new Font(display, \"Lucida Sans Typewriter\", 10,\n SWT.NORMAL);\n display.addListener(SWT.Dispose, new Listener() {\n public void handleEvent(Event event) {\n font.dispose();\n }\n });\n return font;\n}\n public class Monotest {\n\n private static boolean isMonospace(GC gc) {\n final String wide = \"wgh8\";\n final String narrow = \"1l;.\";\n assert wide.length() == narrow.length();\n return gc.textExtent(wide).x == gc.textExtent(narrow).x;\n }\n\n private static void testFont(Display display, Font font) {\n Image image = new Image(display, 100, 100);\n try {\n GC gc = new GC(image);\n try {\n gc.setFont(font);\n System.out.println(isMonospace(gc) + \"\\t\"\n + font.getFontData()[0].getName());\n } finally {\n gc.dispose();\n }\n } finally {\n image.dispose();\n }\n }\n\n private static void walkFonts(Display display) {\n final boolean scalable = true;\n for (FontData fontData : display.getFontList(null, scalable)) {\n Font font = new Font(display, fontData);\n try {\n testFont(display, font);\n } finally {\n font.dispose();\n }\n }\n }\n\n public static void main(String[] args) {\n Display display = new Display();\n try {\n walkFonts(display);\n } finally {\n display.dispose();\n }\n }\n\n}\n"
},
{
"answer_id": 359064,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "new Font(display, \"Courier\", 10, SWT.NORMAL)"
},
{
"answer_id": 9467122,
"author": "Bartleby",
"author_id": 1235845,
"author_profile": "https://Stackoverflow.com/users/1235845",
"pm_score": 5,
"selected": false,
"text": "Font terminalFont = JFaceResources.getFont(JFaceResources.TEXT_FONT);\n Font font = JFaceResources.getTextFont();\n"
},
{
"answer_id": 15269870,
"author": "freesniper",
"author_id": 1300475,
"author_profile": "https://Stackoverflow.com/users/1300475",
"pm_score": 2,
"selected": false,
"text": "public Font loadDigitalFont(int policeSize) {\n URL fontFile = YouClassName.class\n .getResource(\"/fonts/DS-DIGI.TTF\");\n boolean isLoaded = Display.getCurrent().loadFont(fontFile.getPath());\n if (isLoaded) {\n FontData[] fd = Display.getCurrent().getFontList(null, true);\n FontData fontdata = null;\n for (int i = 0; i < fd.length; i++) {\n if (fd[i].getName().equals(\"DS-Digital\")) {\n fontdata = fd[i];\n break;\n }}\n if (fontdata != null) {\n fontdata.setHeight(policeSize);\n fontdata.setStyle(SWT.BOLD);return new Font(getDisplay(), fontdata));}\n }return null; }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17832/"
] |
221,570
|
<p>I'd like them to be easy to bundle, with few dependencies and easy to use.</p>
|
[
{
"answer_id": 33449865,
"author": "stack questions",
"author_id": 5395968,
"author_profile": "https://Stackoverflow.com/users/5395968",
"pm_score": 1,
"selected": false,
"text": " RSyntaxTextArea textArea = new RSyntaxTextArea();\n textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);\n textArea.setCodeFoldingEnabled(true);\n RTextScrollPane rs = new RTextScrollPane(textArea);\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28968/"
] |
221,578
|
<p>I'm trying to make a script that sleeps my wireless card in linux. For that I'm using the <code>deepsleep</code> command of <code>iwpriv</code>:</p>
<pre><code>iwpriv wlan0 deepsleep 1
</code></pre>
<p>The problem is that this command only works if the wireless card is disconnected and disassociated. When it's connected there is no problem because if I disconnect, it disassociates automatically. But if it's disconnected, sometimes it associates (but not connects) automatically to unencrypted networks, so I cannot run the <code>iwpriv</code> command. The only fix I have found is to change the mode first to Ad-Hoc and then to Managed before sleep the card:</p>
<pre><code>iwconfig wlan0 mode ad-hoc
iwconfig wlan0 mode managed
iwpriv wlan0 deepsleep 1
</code></pre>
<p>But I think it's a bit tricky.</p>
<p>Does exist a more direct way to disassociate a wireless card in linux?</p>
|
[
{
"answer_id": 327211,
"author": "ctuffli",
"author_id": 26683,
"author_profile": "https://Stackoverflow.com/users/26683",
"pm_score": 1,
"selected": false,
"text": "iwconfig wlan0 ap 00:00:00:00:00:00\nsleep 1\niwpriv wlan0 deepsleep 1\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28855/"
] |
221,582
|
<p>This question comes up occasionally, but I haven't seen a satisfactory answer.</p>
<p>A typical pattern is (row is a <strong>DataRow</strong>):</p>
<pre><code> if (row["value"] != DBNull.Value)
{
someObject.Member = row["value"];
}
</code></pre>
<p>My first question is which is more efficient (I've flipped the condition):</p>
<pre><code> row["value"] == DBNull.Value; // Or
row["value"] is DBNull; // Or
row["value"].GetType() == typeof(DBNull) // Or... any suggestions?
</code></pre>
<p><a href="https://stackoverflow.com/questions/184681/is-vs-typeof">This</a> indicates that .GetType() should be faster, but maybe the compiler knows a few tricks I don't?</p>
<p>Second question, is it worth caching the value of row["value"] or does the compiler optimize the indexer away anyway?</p>
<p>For example:</p>
<pre><code> object valueHolder;
if (DBNull.Value == (valueHolder = row["value"])) {}
</code></pre>
<p>Notes:</p>
<ol>
<li>row["value"] exists.</li>
<li>I don't know the column index of the column (hence the column name lookup).</li>
<li>I'm asking specifically about checking for DBNull and then assignment (not about premature optimization, etc.).</li>
</ol>
<p>I benchmarked a few scenarios (time in seconds, 10,000,000 trials):</p>
<pre><code>row["value"] == DBNull.Value: 00:00:01.5478995
row["value"] is DBNull: 00:00:01.6306578
row["value"].GetType() == typeof(DBNull): 00:00:02.0138757
</code></pre>
<p>Object.ReferenceEquals has the same performance as "=="</p>
<p>The most interesting result? If you mismatch the name of the column by case (for example, "Value" instead of "value", it takes roughly ten times longer (for a string):</p>
<pre><code>row["Value"] == DBNull.Value: 00:00:12.2792374
</code></pre>
<p>The moral of the story seems to be that if you can't look up a column by its index, then ensure that the column name you feed to the indexer matches the DataColumn's name exactly.</p>
<p>Caching the value also appears to be nearly <strong>twice</strong> as fast:</p>
<pre><code>No Caching: 00:00:03.0996622
With Caching: 00:00:01.5659920
</code></pre>
<p>So the most efficient method <em>seems</em> to be:</p>
<pre><code> object temp;
string variable;
if (DBNull.Value != (temp = row["value"]))
{
variable = temp.ToString();
}
</code></pre>
|
[
{
"answer_id": 221590,
"author": "Jon Grant",
"author_id": 18774,
"author_profile": "https://Stackoverflow.com/users/18774",
"pm_score": 5,
"selected": false,
"text": "Convert.IsDBNull()\n int? myValue = (Convert.IsDBNull(row[\"column\"]) ? null : (int?) Convert.ToInt32(row[\"column\"]));\n"
},
{
"answer_id": 221599,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "object value = row[\"value\"];\n DBNull.Value"
},
{
"answer_id": 221600,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "if (row[\"value\"] != DBNull.Value)\n someObject.Member = row[\"value\"];\n"
},
{
"answer_id": 221612,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 3,
"selected": false,
"text": "IDataRecord int columnIndex = row.GetOrdinal(\"Foo\");\nstring foo; // the variable we're assigning based on the column value.\nif (row.IsDBNull(columnIndex)) {\n foo = String.Empty; // or whatever\n} else { \n foo = row.GetString(columnIndex);\n}\n int bar = -1 row[\"Bar\"] int i; // can be reused for every field.\nstring foo = (row.IsDBNull(i = row.GetOrdinal(\"Foo\")) ? null : row.GetString(i));\nint bar = (row.IsDbNull(i = row.GetOrdinal(\"Bar\")) ? -1 : row.GetInt32(i));\n"
},
{
"answer_id": 221905,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 3,
"selected": false,
"text": "public static IsDBNull<T>(this object value, T default)\n{\n return (value == DBNull.Value)\n ? default\n : (T)value;\n}\n\npublic static IsDBNull<T>(this object value)\n{\n return value.IsDBNull(default(T));\n}\n IDataRecord record; // Comes from somewhere\n\nentity.StringProperty = record[\"StringProperty\"].IsDBNull<string>(null);\nentity.Int32Property = record[\"Int32Property\"].IsDBNull<int>(50);\n\nentity.NoDefaultString = record[\"NoDefaultString\"].IsDBNull<string>();\nentity.NoDefaultInt = record[\"NoDefaultInt\"].IsDBNull<int>();\n"
},
{
"answer_id": 318678,
"author": "Chris Marisic",
"author_id": 37055,
"author_profile": "https://Stackoverflow.com/users/37055",
"pm_score": 2,
"selected": false,
"text": "///<summary>\n/// Handles operations for Enumerations\n///</summary>\npublic static class DataRowUserExtensions\n{\n /// <summary>\n /// Gets the specified data row.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"dataRow\">The data row.</param>\n /// <param name=\"key\">The key.</param>\n /// <returns></returns>\n public static T Get<T>(this DataRow dataRow, string key)\n {\n return (T) ChangeTypeTo<T>(dataRow[key]);\n }\n\n private static object ChangeTypeTo<T>(this object value)\n {\n Type underlyingType = typeof (T);\n if (underlyingType == null)\n throw new ArgumentNullException(\"value\");\n\n if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))\n {\n if (value == null)\n return null;\n var converter = new NullableConverter(underlyingType);\n underlyingType = converter.UnderlyingType;\n }\n\n // Try changing to Guid \n if (underlyingType == typeof (Guid))\n {\n try\n {\n return new Guid(value.ToString());\n }\n catch\n\n {\n return null;\n }\n }\n return Convert.ChangeType(value, underlyingType);\n }\n}\n if (dbRow.Get<int>(\"Type\") == 1)\n{\n newNode = new TreeViewNode\n {\n ToolTip = dbRow.Get<string>(\"Name\"),\n Text = (dbRow.Get<string>(\"Name\").Length > 25 ? dbRow.Get<string>(\"Name\").Substring(0, 25) + \"...\" : dbRow.Get<string>(\"Name\")),\n ImageUrl = \"file.gif\",\n ID = dbRow.Get<string>(\"ReportPath\"),\n Value = dbRow.Get<string>(\"ReportDescription\").Replace(\"'\", \"\\'\"),\n NavigateUrl = (\"?ReportType=\" + dbRow.Get<string>(\"ReportPath\"))\n };\n}\n"
},
{
"answer_id": 319473,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "public static class DataExtensions\n{\n /// <summary>\n /// Gets the value.\n /// </summary>\n /// <typeparam name=\"T\">The type of the data stored in the record</typeparam>\n /// <param name=\"record\">The record.</param>\n /// <param name=\"columnName\">Name of the column.</param>\n /// <returns></returns>\n public static T GetColumnValue<T>(this IDataRecord record, string columnName)\n {\n return GetColumnValue<T>(record, columnName, default(T));\n }\n\n /// <summary>\n /// Gets the value.\n /// </summary>\n /// <typeparam name=\"T\">The type of the data stored in the record</typeparam>\n /// <param name=\"record\">The record.</param>\n /// <param name=\"columnName\">Name of the column.</param>\n /// <param name=\"defaultValue\">The value to return if the column contains a <value>DBNull.Value</value> value.</param>\n /// <returns></returns>\n public static T GetColumnValue<T>(this IDataRecord record, string columnName, T defaultValue)\n {\n object value = record[columnName];\n if (value == null || value == DBNull.Value)\n {\n return defaultValue;\n }\n else\n {\n return (T)value;\n }\n }\n}\n int number = record.GetColumnValue<int>(\"Number\",0)\n"
},
{
"answer_id": 470548,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 3,
"selected": false,
"text": "null int? as int? string.Empty null .ToString() string.Empty"
},
{
"answer_id": 749234,
"author": "stevehipwell",
"author_id": 89075,
"author_profile": "https://Stackoverflow.com/users/89075",
"pm_score": 3,
"selected": false,
"text": "oSomeObject.IntMemeber = oRow[\"Value\"] as int? ?? iDefault;\noSomeObject.StringMember = oRow[\"Name\"] as string ?? sDefault;\n"
},
{
"answer_id": 2871680,
"author": "Mastahh",
"author_id": 345818,
"author_profile": "https://Stackoverflow.com/users/345818",
"pm_score": 2,
"selected": false,
"text": "public String TryGetString(SqlDataReader sqlReader, int row)\n{\n String res = \"\";\n try\n {\n res = sqlReader.GetString(row);\n }\n catch (Exception)\n { \n }\n return res;\n}\n"
},
{
"answer_id": 3050671,
"author": "Saleh Najar",
"author_id": 367881,
"author_profile": "https://Stackoverflow.com/users/367881",
"pm_score": 3,
"selected": false,
"text": " static void Main(string[] args)\n {\n object number = DBNull.Value;\n\n int newNumber = number.SafeDBNull<int>();\n\n Console.WriteLine(newNumber);\n }\n\n\n\n public static T SafeDBNull<T>(this object value, T defaultValue) \n {\n if (value == null)\n return default(T);\n\n if (value is string)\n return (T) Convert.ChangeType(value, typeof(T));\n\n return (value == DBNull.Value) ? defaultValue : (T)value;\n } \n\n public static T SafeDBNull<T>(this object value) \n { \n return value.SafeDBNull(default(T)); \n } \n"
},
{
"answer_id": 3050744,
"author": "Dan Tao",
"author_id": 105570,
"author_profile": "https://Stackoverflow.com/users/105570",
"pm_score": 6,
"selected": false,
"text": "DBNull DataRow.IsNull public static T? GetValue<T>(this DataRow row, string columnName) where T : struct\n{\n if (row.IsNull(columnName))\n return null;\n\n return row[columnName] as T?;\n}\n\npublic static string GetText(this DataRow row, string columnName)\n{\n if (row.IsNull(columnName))\n return string.Empty;\n\n return row[columnName] as string ?? string.Empty;\n}\n int? id = row.GetValue<int>(\"Id\");\nstring name = row.GetText(\"Name\");\ndouble? price = row.GetValue<double>(\"Price\");\n Nullable<T> GetValue<T> default(T) oSomeObject.IntMember = If(TryConvert(Of Integer)(oRow(\"Value\")), iDefault)\noSomeObject.StringMember = If(TryCast(oRow(\"Name\"), String), sDefault)\n\nFunction TryConvert(Of T As Structure)(ByVal obj As Object) As T?\n If TypeOf obj Is T Then\n Return New T?(DirectCast(obj, T))\n Else\n Return Nothing\n End If\nEnd Function\n"
},
{
"answer_id": 5898888,
"author": "Neil",
"author_id": 566823,
"author_profile": "https://Stackoverflow.com/users/566823",
"pm_score": 2,
"selected": false,
"text": "public static class DBH\n{\n /// <summary>\n /// Return default(T) if supplied with DBNull.Value\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"value\"></param>\n /// <returns></returns>\n public static T Get<T>(object value)\n { \n return value == DBNull.Value ? default(T) : (T)value;\n }\n}\n DBH.Get<String>(itemRow[\"MyField\"])\n"
},
{
"answer_id": 14725065,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 3,
"selected": false,
"text": "record[X] IsDBNull record[X] record[X] == DBNull.Value Convert IDataRecord IDataReader record.GetColumnValue<int?>(\"field\");\n record.GetColumnValue<int>(\"field\");\n 0 DBNull default(MyEnum) record.GetColumnValue<MyEnum?>(\"Field\") DataRow DataRow IDataReader public static T Get<T>(this DataRow dr, int index, T defaultValue = default(T))\n{\n return dr[index].Get<T>(defaultValue);\n}\n\nstatic T Get<T>(this object obj, T defaultValue) //Private method on object.. just to use internally.\n{\n if (obj.IsNull())\n return defaultValue;\n\n return (T)obj;\n}\n\npublic static bool IsNull<T>(this T obj) where T : class \n{\n return (object)obj == null || obj == DBNull.Value;\n} \n\npublic static T Get<T>(this IDataReader dr, int index, T defaultValue = default(T))\n{\n return dr[index].Get<T>(defaultValue);\n}\n record.Get<int>(1); //if DBNull should be treated as 0\nrecord.Get<int?>(1); //if DBNull should be treated as null\nrecord.Get<int>(1, -1); //if DBNull should be treated as a custom value, say -1\n record.GetInt32 record.GetString GetInt GetEnum GetGuid DBNull Guid static T Get<T>(this object obj, T defaultValue, Func<object, T> converter)\n{\n if (obj.IsNull())\n return defaultValue;\n\n return converter == null ? (T)obj : converter(obj);\n}\n"
},
{
"answer_id": 35620842,
"author": "Stefan",
"author_id": 5978889,
"author_profile": "https://Stackoverflow.com/users/5978889",
"pm_score": 2,
"selected": false,
"text": "decimal result = rw[\"fieldname\"] as decimal? ?? 0;\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
221,584
|
<p>I have some products that belongs to the some category.</p>
<p>Each category can have different properties.</p>
<p>For example, </p>
<ul>
<li>category <em>cars</em> has properties <em>color</em>,
power, ... </li>
<li>category <em>pets</em> have properties <em>weight</em>, <em>age</em>, ...</li>
</ul>
<p>Number of categories is about 10-15.
Number of properties in each category is 3-15.
Number of products is very big.</p>
<p>Main requirement for this app is very good search. We will select category, and enter criteria for each property in this category.</p>
<p>Have to design database for this scenario. (SQL Server 2005)</p>
|
[
{
"answer_id": 221614,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": false,
"text": "tProduct \n productID\n <other product details>\n\ntCategory\n categoryID\n <other category details>\n\ntProperty\n propertyID\n <other property details>\n\ntProductXCategory\n productyID\n categoryID\n\ntCategoryXProperty\n categoryID\n propertyID\n"
},
{
"answer_id": 221638,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "Product\n ProductId*\n CategoryId: FK to Category.CategroyId\n Name\n\nCategory\n CategoryId*\n Name\n\nProperty\n PropertyId*\n Name\n Type\n\nCategoryProperty\n CategoryId*: FK to Category.CategoryId\n PropertyId*: FK to Property.PropertyId\n\nProductProperty\n ProductId*: FK to Product.ProductId\n PropertyId*: FK to Property.PropertyId\n ValueAsString\n SELECT\n Product.ProductId,\n Product.Name AS ProductName,\n Category.CategoryId,\n Category.Name AS CategoryName,\n Property.PropertyId,\n Property.Name AS PropertyName,\n Property.Type AS PropertyType,\n ProductProperty.ValueAsString\nFROM\n Product \n INNER JOIN Category ON Category.CategoryId = Product.CategoryId\n INENR JOIN CategoryProperty ON CategoryProperty.CategoryId = Category.CategoryId\n INNER JOIN Property ON Property.PropertyId = CategoryProperty.PropertyId\n INNER JOIN ProductProperty ON ProductProperty.PropertyId = Property.PropertyId\n AND ProductProperty.ProductId = Product.ProductId\nWHERE\n Product.ProductId = 1\n"
},
{
"answer_id": 221790,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 1,
"selected": false,
"text": "Products(ProductID, CategoryID, <any other common properties>) Categories(CategoryID, Name, Description, ..) Cars(CarID, ProductID, ..) Pets(PetID, ProductID, ..) SELECT <fields> FROM Cars INNER JOIN Products ON Cars.ProductID = Products.ProductID CategoryProperty (CPID, Name, Type) PropertyAssociation (CPID, PropertyID) Properties(CategoryID, PropertyID, Name, Type) PropertyValueInt(ProductID, CPID, PropertyID, Value) PropertyValueString(ProductID, CPID, PropertyID, Value) PropertyValueMoney(ProductID, CPID, PropertyID, Value)"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
221,592
|
<p>Does anyone know whether the iPhone supports or will soon support the <a href="http://dev.w3.org/geo/api/spec-source.html" rel="noreferrer">W3C Geolocation specification</a>?</p>
<p>I'm looking to build an app for mobile users, but rather than spend the time developing apps for every different platform (iPhone, Android, etc...), I'd much prefer to create a web app that makes use of the W3C Standard.</p>
|
[
{
"answer_id": 1134136,
"author": "SavoryBytes",
"author_id": 131944,
"author_profile": "https://Stackoverflow.com/users/131944",
"pm_score": 7,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.0//EN\" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>Geolocation API Demo</title>\n<meta content=\"width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\" name=\"viewport\"/>\n<script>\nfunction successHandler(location) {\n var message = document.getElementById(\"message\"), html = [];\n html.push(\"<img width='256' height='256' src='http://maps.google.com/maps/api/staticmap?center=\", location.coords.latitude, \",\", location.coords.longitude, \"&markers=size:small|color:blue|\", location.coords.latitude, \",\", location.coords.longitude, \"&zoom=14&size=256x256&sensor=false' />\");\n html.push(\"<p>Longitude: \", location.coords.longitude, \"</p>\");\n html.push(\"<p>Latitude: \", location.coords.latitude, \"</p>\");\n html.push(\"<p>Accuracy: \", location.coords.accuracy, \" meters</p>\");\n message.innerHTML = html.join(\"\");\n}\nfunction errorHandler(error) {\n alert('Attempt to get location failed: ' + error.message);\n}\nnavigator.geolocation.getCurrentPosition(successHandler, errorHandler);\n</script>\n</head>\n<body>\n<div id=\"message\">Location unknown</div>\n</body>\n</html>\n"
},
{
"answer_id": 5355812,
"author": "Niraj D",
"author_id": 397159,
"author_profile": "https://Stackoverflow.com/users/397159",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.0//EN\" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>iPhone 4.0 geolocation demo</title>\n<meta content=\"width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\" name=\"viewport\"/>\n<script>\nfunction handler(location) {\nvar message = document.getElementById(\"message\");\nmessage.innerHTML =\"<img src='http://maps.google.com/maps/api/staticmap?center=\" + location.coords.latitude + \",\" + location.coords.longitude + \"&zoom=14&size=256x256&maptype=roadmap&sensor=false&markers=color:blue%7Clabel:ABC%7C\" + location.coords.latitude + \",\" + location.coords.longitude + \"' />\";\n\n\n\nmessage.innerHTML+=\"<p>Longitude: \" + location.coords.longitude + \"</p>\";\nmessage.innerHTML+=\"<p>Accuracy: \" + location.coords.accuracy + \"</p>\";\nmessage.innerHTML+=\"<p>Latitude: \" + location.coords.latitude + \"</p>\";\n\n\n\n}\nnavigator.geolocation.getCurrentPosition(handler);\n</script>\n</head>\n<body>\n<div id=\"message\">Location unknown</div>\n</body>\n</html>\n"
},
{
"answer_id": 8952351,
"author": "Artur Bodera",
"author_id": 181664,
"author_profile": "https://Stackoverflow.com/users/181664",
"pm_score": -1,
"selected": false,
"text": "//determine if the handset has client side geo location capabilities\nif(geo_position_js.init()){\n geo_position_js.getCurrentPosition(success_callback,error_callback);\n}else{\n alert(\"Functionality not available\");\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12037/"
] |
221,593
|
<p>I am building an ObjectQuery like this:</p>
<pre><code> string query = "select value obj from Entities.Class as obj " +
"where obj.Property = @Value";
ObjectQuery<Class> oQuery = new ObjectQuery<Class>(query, EntityContext.Instance);
oQuery.Parameters.Add(new ObjectParameter("Value", someVariable));
</code></pre>
<p>I can now assign this object as a DataSource for a control, or iterate with a foreach loop or even force a materialization to a List, however, I can I count the number of objects that will be returned, without forcing a materialization?</p>
<p>Do I need to create a companion query that will execute a count() or is there a function that will do that for me somewhere?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 221630,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "ObjectQuery<T> IQueryable<T> int count = oQuery.Count();\n"
},
{
"answer_id": 221633,
"author": "Jon Grant",
"author_id": 18774,
"author_profile": "https://Stackoverflow.com/users/18774",
"pm_score": 1,
"selected": false,
"text": "int count = oQuery.Count();\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3610/"
] |
221,595
|
<p>I have a button inside an update panel that I would like to update the whole page. I have set <code>ChildrenAsTriggers="false"</code> and <code>UpdateMode="Conditional"</code>.</p>
<p>I have some sample code here that demonstrates my problem.</p>
<pre><code><asp:UpdatePanel ID="myFirstPanel" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button runat="server" ID="myFirstButton" Text="My First Button" onclick="myFirstButton_Click" />
<asp:Button runat="server" ID="mySecondButton" Text="My Second Button" onclick="mySecondButton_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="mySecondPanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="myFirstLabel" Text="My First Label"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myFirstButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Label runat="server" ID="mySecondLabel" Text="My Second Label"></asp:Label>
</code></pre>
<p>And the code behind:</p>
<pre><code>protected void myFirstButton_Click(object sender, EventArgs e)
{
myFirstLabel.Text = "Inside Panel " + DateTime.Now.ToString("mm:ss");
}
protected void mySecondButton_Click(object sender, EventArgs e)
{
mySecondLabel.Text = "Outside Panel " + DateTime.Now.ToString("mm:ss");
}
</code></pre>
<p>I want to update the label that is not inside an update panel when the second button is clicked.
The second button needs to be in an update panel. I don't want to put the lable into an update panel.</p>
|
[
{
"answer_id": 221718,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 1,
"selected": false,
"text": "<Triggers>\n <asp:PostBackTrigger ControlID=\"mySecondButton\" />\n</Triggers>\n"
},
{
"answer_id": 12943127,
"author": "Mark Meuer",
"author_id": 9117,
"author_profile": "https://Stackoverflow.com/users/9117",
"pm_score": 0,
"selected": false,
"text": " protected void Page_Load(object sender, EventArgs e)\n {\n // If the chart is within an update panel then we need to tell the script manager\n // to not do an asynch postback on chartdownload. If we don't, the download\n // doesn't work.\n var scriptManager = ScriptManager.GetCurrent(Page);\n if (scriptManager != null)\n {\n scriptManager.RegisterPostBackControl(ChartSaveButton);\n }\n // Rest of Page_Load followed here...\n ChartSaveButton private Control ChartSaveButton\n {\n get { return FindControl(\"btnDownloadChart\"); }\n }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
221,611
|
<p>For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated. How would you design this?</p>
<ul>
<li><p>What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?</p></li>
<li><p>What data types would you use in Java (<code>Date</code>, <code>Calendar</code>, <code>long</code>, ...)?</p></li>
<li><p>Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?</p></li>
<li><p>What annotations would you use for the mapping (e.g. <code>@Temporal</code>)?</p></li>
</ul>
<p>I'm not only looking for a working solution, but for a safe and well-designed solution.</p>
|
[
{
"answer_id": 221782,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 2,
"selected": false,
"text": "java.util.Calender java.util.Date"
},
{
"answer_id": 221827,
"author": "Guðmundur Bjarni",
"author_id": 27349,
"author_profile": "https://Stackoverflow.com/users/27349",
"pm_score": 8,
"selected": false,
"text": "@PrePersist @PreUpdate @Entity\n@Table(name = \"entities\") \npublic class Entity {\n ...\n\n private Date created;\n private Date updated;\n\n @PrePersist\n protected void onCreate() {\n created = new Date();\n }\n\n @PreUpdate\n protected void onUpdate() {\n updated = new Date();\n }\n}\n @EntityListener"
},
{
"answer_id": 229927,
"author": "ngn",
"author_id": 23109,
"author_profile": "https://Stackoverflow.com/users/23109",
"pm_score": 4,
"selected": false,
"text": "decimal(20) DEFAULT CURRENT_TIMESTAMP long long < + long java.lang.Long java.util.Date foo.getLastUpdate().setTime(System.currentTimeMillis()) @Temporal @Version @PrePersist @PreUpdate"
},
{
"answer_id": 4038363,
"author": "Olivier Refalo",
"author_id": 258689,
"author_profile": "https://Stackoverflow.com/users/258689",
"pm_score": 7,
"selected": false,
"text": "import java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.PrePersist;\nimport javax.persistence.PreUpdate;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n@MappedSuperclass\npublic abstract class AbstractTimestampEntity {\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"created\", nullable = false)\n private Date created;\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"updated\", nullable = false)\n private Date updated;\n\n @PrePersist\n protected void onCreate() {\n updated = created = new Date();\n }\n\n @PreUpdate\n protected void onUpdate() {\n updated = new Date();\n }\n}\n @Entity\n@Table(name = \"campaign\")\npublic class Campaign extends AbstractTimestampEntity implements Serializable {\n...\n}\n"
},
{
"answer_id": 7844107,
"author": "Kieren Dixon",
"author_id": 746819,
"author_profile": "https://Stackoverflow.com/users/746819",
"pm_score": 4,
"selected": false,
"text": "public interface TimeStamped {\n public Date getCreatedDate();\n public void setCreatedDate(Date createdDate);\n public Date getLastUpdated();\n public void setLastUpdated(Date lastUpdatedDate);\n}\n public class TimeStampInterceptor extends EmptyInterceptor {\n\n public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, \n Object[] previousState, String[] propertyNames, Type[] types) {\n if (entity instanceof TimeStamped) {\n int indexOf = ArrayUtils.indexOf(propertyNames, \"lastUpdated\");\n currentState[indexOf] = new Date();\n return true;\n }\n return false;\n }\n\n public boolean onSave(Object entity, Serializable id, Object[] state, \n String[] propertyNames, Type[] types) {\n if (entity instanceof TimeStamped) {\n int indexOf = ArrayUtils.indexOf(propertyNames, \"createdDate\");\n state[indexOf] = new Date();\n return true;\n }\n return false;\n }\n}\n"
},
{
"answer_id": 23284778,
"author": "endriju",
"author_id": 1038593,
"author_profile": "https://Stackoverflow.com/users/1038593",
"pm_score": 4,
"selected": false,
"text": "@Temporal(TemporalType.TIMESTAMP)\n@Column(name = \"created\", nullable = false, updatable=false)\nprivate Date created;\n"
},
{
"answer_id": 33130639,
"author": "vicch",
"author_id": 1620248,
"author_profile": "https://Stackoverflow.com/users/1620248",
"pm_score": 3,
"selected": false,
"text": "@MappedSuperclass\npublic abstract class AbstractTimestampEntity {\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"created\")\n private Date created=new Date();\n\n @Temporal(TemporalType.TIMESTAMP)\n @Column(name = \"updated\")\n @Version\n private Date updated;\n\n public Date getCreated() {\n return created;\n }\n\n public void setCreated(Date created) {\n this.created = created;\n }\n\n public Date getUpdated() {\n return updated;\n }\n\n public void setUpdated(Date updated) {\n this.updated = updated;\n }\n}\n"
},
{
"answer_id": 39427923,
"author": "idmitriev",
"author_id": 2625691,
"author_profile": "https://Stackoverflow.com/users/2625691",
"pm_score": 8,
"selected": false,
"text": "@CreationTimestamp @UpdateTimestamp @CreationTimestamp\n@Temporal(TemporalType.TIMESTAMP)\n@Column(name = \"create_date\")\nprivate Date createDate;\n\n@UpdateTimestamp\n@Temporal(TemporalType.TIMESTAMP)\n@Column(name = \"modify_date\")\nprivate Date modifyDate;\n"
},
{
"answer_id": 44734067,
"author": "amdg",
"author_id": 4060708,
"author_profile": "https://Stackoverflow.com/users/4060708",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE my_table (\n ...\n updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP\n );\n"
},
{
"answer_id": 55546553,
"author": "prranay",
"author_id": 1589549,
"author_profile": "https://Stackoverflow.com/users/1589549",
"pm_score": 2,
"selected": false,
"text": "package com.my.backend.models;\n\nimport java.util.Date;\n\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\n\nimport org.hibernate.annotations.ColumnDefault;\nimport org.hibernate.annotations.CreationTimestamp;\nimport org.hibernate.annotations.UpdateTimestamp;\n\nimport lombok.Getter;\nimport lombok.Setter;\n\n@MappedSuperclass\n@Getter @Setter\npublic class BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n protected Integer id;\n\n @CreationTimestamp\n @ColumnDefault(\"CURRENT_TIMESTAMP\")\n protected Date createdAt;\n\n @UpdateTimestamp\n @ColumnDefault(\"CURRENT_TIMESTAMP\")\n protected Date updatedAt;\n}\n"
},
{
"answer_id": 60360233,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 7,
"selected": false,
"text": "TIMESTAMP 2038-01-19 03:14:07.999999 DATETIME DATETIME hibernate.jdbc.time_zone LocalDateTime Date @Temporal LocalDateTime java.sql.Timestamp @Temporal java.util.Date @Temporal @Temporal(TemporalType.TIMESTAMP)\n@Column(name = \"created_on\")\nprivate Date createdOn;\n @Column(name = \"created_on\")\nprivate LocalDateTime createdOn;\n create_on DEFAULT ALTER TABLE post \nADD CONSTRAINT created_on_default \nDEFAULT CURRENT_TIMESTAMP() FOR created_on;\n updated_on CURRENT_TIMESTAMP() created_by created_on updated_by updated_on @CreationTimestamp @UpdateTimestamp @CreationTimestamp @UpdateTimestamp created_on updated_on @MappedSuperclass @MappedSuperclass\npublic class BaseEntity {\n \n @Id\n @GeneratedValue\n private Long id;\n \n @Column(name = \"created_on\")\n @CreationTimestamp\n private LocalDateTime createdOn;\n \n @Column(name = \"created_by\")\n private String createdBy;\n \n @Column(name = \"updated_on\")\n @UpdateTimestamp\n private LocalDateTime updatedOn;\n \n @Column(name = \"updated_by\")\n private String updatedBy;\n \n //Getters and setters omitted for brevity\n}\n BaseEntity @Entity(name = \"Post\")\n@Table(name = \"post\")\npublic class Post extend BaseEntity {\n \n private String title;\n \n @OneToMany(\n mappedBy = \"post\",\n cascade = CascadeType.ALL,\n orphanRemoval = true\n )\n private List<PostComment> comments = new ArrayList<>();\n \n @OneToOne(\n mappedBy = \"post\",\n cascade = CascadeType.ALL,\n orphanRemoval = true,\n fetch = FetchType.LAZY\n )\n private PostDetails details;\n \n @ManyToMany\n @JoinTable(\n name = \"post_tag\",\n joinColumns = @JoinColumn(\n name = \"post_id\"\n ),\n inverseJoinColumns = @JoinColumn(\n name = \"tag_id\"\n )\n )\n private List<Tag> tags = new ArrayList<>();\n \n //Getters and setters omitted for brevity\n}\n createdOn updateOn @CreationTimestamp @UpdateTimestamp createdBy updatedBy @EntityListeners @Embeddable\npublic class Audit {\n \n @Column(name = \"created_on\")\n private LocalDateTime createdOn;\n \n @Column(name = \"created_by\")\n private String createdBy;\n \n @Column(name = \"updated_on\")\n private LocalDateTime updatedOn;\n \n @Column(name = \"updated_by\")\n private String updatedBy;\n \n //Getters and setters omitted for brevity\n}\n AuditListener public class AuditListener {\n \n @PrePersist\n public void setCreatedOn(Auditable auditable) {\n Audit audit = auditable.getAudit();\n \n if(audit == null) {\n audit = new Audit();\n auditable.setAudit(audit);\n }\n \n audit.setCreatedOn(LocalDateTime.now());\n audit.setCreatedBy(LoggedUser.get());\n }\n \n @PreUpdate\n public void setUpdatedOn(Auditable auditable) {\n Audit audit = auditable.getAudit();\n \n audit.setUpdatedOn(LocalDateTime.now());\n audit.setUpdatedBy(LoggedUser.get());\n }\n}\n AuditListener @EntityListeners @Entity(name = \"Post\")\n@Table(name = \"post\")\n@EntityListeners(AuditListener.class)\npublic class Post implements Auditable {\n \n @Id\n private Long id;\n \n @Embedded\n private Audit audit;\n \n private String title;\n \n @OneToMany(\n mappedBy = \"post\",\n cascade = CascadeType.ALL,\n orphanRemoval = true\n )\n private List<PostComment> comments = new ArrayList<>();\n \n @OneToOne(\n mappedBy = \"post\",\n cascade = CascadeType.ALL,\n orphanRemoval = true,\n fetch = FetchType.LAZY\n )\n private PostDetails details;\n \n @ManyToMany\n @JoinTable(\n name = \"post_tag\",\n joinColumns = @JoinColumn(\n name = \"post_id\"\n ),\n inverseJoinColumns = @JoinColumn(\n name = \"tag_id\"\n )\n )\n private List<Tag> tags = new ArrayList<>();\n \n //Getters and setters omitted for brevity\n}\n"
},
{
"answer_id": 65250994,
"author": "Mohammed Javad",
"author_id": 10532966,
"author_profile": "https://Stackoverflow.com/users/10532966",
"pm_score": 3,
"selected": false,
"text": "@CreatedDate @LastModifiedDate @CreatedBy @LastModifiedBy @MappedSuperclass @EntityListeners(AuditingEntityListener.class) @MappedSuperclass\n@EntityListeners(AuditingEntityListener.class)\npublic class BaseDomain implements Serializable {\n\n @CreatedDate\n private Date createdOn;\n\n @LastModifiedDate\n private Date modifiedOn;\n\n @CreatedBy\n private String createdBy;\n\n @LastModifiedBy\n private String modifiedBy;\n\n}\n AuditingEntityListener getCurrentAuditor() getCurrentAuditor() public class AuditorAwareImpl implements AuditorAware<String> {\n @Override\n public Optional<String> getCurrentAuditor() {\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n return authentication == null ? Optional.empty() : Optional.ofNullable(authentication.getName());\n }\n}\n Optional Optional String @Configuration\n@EnableJpaAuditing(auditorAwareRef = \"auditorAware\")\npublic class JpaConfig {\n @Bean\n public AuditorAware<String> auditorAware() {\n return new AuditorAwareImpl();\n }\n}\n BaseDomain"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23109/"
] |
221,674
|
<p>Are there ways except CAPTCHAs for web apps like <a href="http://pastie.org" rel="nofollow noreferrer">pastie.org</a> or <a href="http://p.ramaze.net" rel="nofollow noreferrer">p.ramaze.net</a>? CAPTCHAs take too long for a small paste for my taste.</p>
|
[
{
"answer_id": 221721,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 1,
"selected": false,
"text": "* Current software is unable to solve accurately.\n* Most humans can solve.\n* Does not rely on the type of CAPTCHA being new to the attacker.\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28968/"
] |
221,687
|
<p>I want to make a generic class that accepts only serializable classes, can it be done with the where constraint?</p>
<p>The concept I'm looking for is this:</p>
<pre><code>public class MyClass<T> where T : //[is serializable/has the serializable attribute]
</code></pre>
|
[
{
"answer_id": 221695,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "where T : class where T : struct where T : SomeClass where T : ISomeInterface where T : new()"
},
{
"answer_id": 221727,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 3,
"selected": false,
"text": "public void Initialize<T>(T obj)\n{\n object[] attributes = obj.GetType().GetCustomAttributes(typeof(SerializableAttribute));\n if(attributes == null || attributes.Length == 0)\n throw new InvalidOperationException(\"The provided object is not serializable\");\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
221,691
|
<p>This might be a old question: Why does <code>IEnumerable<T></code> inherit from <code>IEnumerable</code>?</p>
<p>This is how .NET do, but it brings a little trouble. Every time I write a class implements <code>IEumerable<T></code>, I have to write two <code>GetEnumerator()</code> functions, one for <code>IEnumerable<T></code> and the other for <code>IEnumerable</code>.</p>
<p>And, <code>IList<T></code> doesn't inherit from IList. </p>
<p>I don't know why <code>IEnumerable<T></code> is designed in other way.</p>
|
[
{
"answer_id": 221722,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "IEnumerable IEnumerable IEnumerator.Current object IEnumerator<T>.Current T object IList<T> IList Add(object) IList IList<T> IList<object>"
},
{
"answer_id": 221724,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 7,
"selected": true,
"text": "ICollection<T> IList<T> IList<T> IList IEnumerable<T> IEnumerable<T> IEnumerable<T> ICollection<T> IList<T> IEnumerable<T> IEnumerable"
},
{
"answer_id": 221726,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": " private IEnumerator<string> Enumerator() {\n // ...\n }\n\n public IEnumerator<string> GetEnumerator() {\n return Enumerator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {\n return Enumerator();\n }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
221,693
|
<p>I have a function that automatically exports a table into a CSV file, then I try to attach that same file into a function that will email it. I have sent attachments using html mime mail before, but I was wondering if that created CSV file needs to be stored on the server first before attaching it to the email?</p>
|
[
{
"answer_id": 221720,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 0,
"selected": false,
"text": "uuencode"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
221,730
|
<p>I want to create a .bat file so I can just click on it so it can run:</p>
<pre><code>svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
</code></pre>
<p>Can someone help me with the structure of the .bat file?</p>
|
[
{
"answer_id": 221815,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 3,
"selected": false,
"text": "@echo off\nsvcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service\n"
},
{
"answer_id": 221845,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 3,
"selected": false,
"text": "echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service >CreateService.cmd\n CreateService.cmd .cmd .bat"
},
{
"answer_id": 6167028,
"author": "shinukb",
"author_id": 775022,
"author_profile": "https://Stackoverflow.com/users/775022",
"pm_score": 6,
"selected": false,
"text": "start \"c:\\windows\\system32\" notepad.exe \n"
},
{
"answer_id": 6602119,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 8,
"selected": false,
"text": "start /d \"path\" file.exe\n"
},
{
"answer_id": 15954974,
"author": "user2075928",
"author_id": 2075928,
"author_profile": "https://Stackoverflow.com/users/2075928",
"pm_score": 6,
"selected": false,
"text": "start \"windowTitle\" fullPath/file.exe\n start \"\" fullPath/file.exe\n"
},
{
"answer_id": 16581128,
"author": "Gipphe",
"author_id": 1848885,
"author_profile": "https://Stackoverflow.com/users/1848885",
"pm_score": 2,
"selected": false,
"text": "Start start \"svcutil\" \"svcutil.exe\" \"language:cs\" \"out:generatedProxy.cs\" \"config:app.config\" \"http://localhost:8000/ServiceModelSamples/service\"\n \"svcutil\" start start \"svcutil.exe\""
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
221,732
|
<p>I've been searching a lot but couldn't find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?</p>
|
[
{
"answer_id": 221740,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 10,
"selected": true,
"text": "DateTime.MinValue DateTime? MyNullableDate;\n Nullable<DateTime> MyNullableDate;\n null DateTime.MinValue default(DateTime)\n default\n"
},
{
"answer_id": 221741,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 4,
"selected": false,
"text": "DateTime? myDate DateTime myDate"
},
{
"answer_id": 221743,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 7,
"selected": false,
"text": "DateTime? dt = null;\n Nullable<DateTime> dt = null;\n dt = new DateTime();\n if (dt.HasValue)\n{\n // Do something with dt.Value\n}\n DateTime dt2 = dt ?? DateTime.MinValue;\n"
},
{
"answer_id": 221750,
"author": "Aaron Smith",
"author_id": 12969,
"author_profile": "https://Stackoverflow.com/users/12969",
"pm_score": 3,
"selected": false,
"text": "DateTime? date = new DateTime?();\n"
},
{
"answer_id": 221753,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 3,
"selected": false,
"text": "Nullable<DateTime> myDateTime;\n DateTime? myDateTime;\n"
},
{
"answer_id": 221756,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": false,
"text": "DateTime.MinValue"
},
{
"answer_id": 221877,
"author": "user29958",
"author_id": 29958,
"author_profile": "https://Stackoverflow.com/users/29958",
"pm_score": 3,
"selected": false,
"text": "DateTime? nullDate = null;\n DateTime? nullDate;\n"
},
{
"answer_id": 2731193,
"author": "Iman",
"author_id": 184572,
"author_profile": "https://Stackoverflow.com/users/184572",
"pm_score": 5,
"selected": false,
"text": "MyDateTime = (dr[\"f1\"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr[\"f1\"]);\n"
},
{
"answer_id": 16542967,
"author": "DarkoM",
"author_id": 2102684,
"author_profile": "https://Stackoverflow.com/users/2102684",
"pm_score": 1,
"selected": false,
"text": "var orderResults = Repository.GetOrders(id, (DateTime?)model.DateFrom, (DateTime?)model.DateTo)\n public Orders[] GetOrders(string id, DateTime? dateFrom, DateTime? dateTo){...}\n"
},
{
"answer_id": 23398756,
"author": "uncoder",
"author_id": 3438832,
"author_profile": "https://Stackoverflow.com/users/3438832",
"pm_score": 3,
"selected": false,
"text": "DateTime null null DateTime date;\n...\nif(date == null) // <-- will never be 'true'\n ...\n"
},
{
"answer_id": 35055189,
"author": "Gabe",
"author_id": 5697616,
"author_profile": "https://Stackoverflow.com/users/5697616",
"pm_score": 2,
"selected": false,
"text": "DateTime date = myNullableObject.Value.ToUniversalTime(); //Works DateTime date = myNullableObject.ToUniversalTime(); //Not a datetime object, fails DateTime date = Convert.ToDateTime(myNullableObject).ToUniversalTime(); //works but why..."
},
{
"answer_id": 38435535,
"author": "No Holidays",
"author_id": 5018454,
"author_profile": "https://Stackoverflow.com/users/5018454",
"pm_score": 2,
"selected": false,
"text": "DateTime? dt = null;\nDateTime dte = Convert.ToDateTime(dt);\n"
},
{
"answer_id": 38586385,
"author": "Brendan Vogt",
"author_id": 225799,
"author_profile": "https://Stackoverflow.com/users/225799",
"pm_score": 0,
"selected": false,
"text": "null nullable min max nullable null DateTime DateTime BlogPost DatePublished DateModified public class BlogPost : Entity\n{\n public DateTime DateModified { get; set; }\n\n public DateTime DatePublished { get; set; }\n}\n ADO.NET DateTime.MinValue BlogPost blogPost = new BlogPost();\nblogPost.DateModified = sqlDataReader.IsDBNull(0) ? DateTime.MinValue : sqlDataReader.GetFieldValue<DateTime>(0);\nblogPost.DatePublished = sqlDataReader.GetFieldValue<DateTime>(1);\n DateModified nullable null public DateTime? DateModified { get; set; }\n ADO.NET null DateTime.MinValue BlogPost blogPost = new BlogPost();\nblogPost.DateModified = sqlDataReader.IsDBNull(0) ? (DateTime?)null : sqlDataReader.GetFieldValue<DateTime>(0);\nblogPost.DatePublished = sqlDataReader.GetFieldValue<DateTime>(1);\n"
},
{
"answer_id": 42061453,
"author": "Aleksei",
"author_id": 2767565,
"author_profile": "https://Stackoverflow.com/users/2767565",
"pm_score": 5,
"selected": false,
"text": "myClass.PublishDate = toPublish ? DateTime.Now : (DateTime?)null;\n"
},
{
"answer_id": 42308712,
"author": "Kiril Dobrev",
"author_id": 7547275,
"author_profile": "https://Stackoverflow.com/users/7547275",
"pm_score": 1,
"selected": false,
"text": "Assert.Throws<ArgumentNullException>(()=>sut.StartingDate = DateTime.Parse(null));\n"
},
{
"answer_id": 71654440,
"author": "esenkaya",
"author_id": 4004831,
"author_profile": "https://Stackoverflow.com/users/4004831",
"pm_score": 0,
"selected": false,
"text": " DateNotified = DBNull.Value.Equals(reader[\"DateNotified\"])? Convert.ToDateTime(reader[\"DateNotified\"]): DateTime.MaxValue\n columns.Add(col => col.DateNotified).Css(\"text-right\").Titled(\"Date Notified\").RenderValueAs(c => c.DateNotified.ToString(\"MM/dd/yyyy\").Equals(DateTime.MaxValue) ? \"\":c.DateNotified.ToString(\"MM/dd/yyyy\"));\n @Model.DateNotified.ToString(\"MM/dd/yyyy\").Equals(DateTime.MaxValue) ? \"\":Model.DateNotified.ToString(\"MM/dd/yyyy\")\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
] |
221,745
|
<p>I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks</p>
|
[
{
"answer_id": 221832,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 4,
"selected": true,
"text": "from twisted.internet import task\nfrom twisted.internet import reactor\n\ndatagramRecieved = False\ntimeout = 1.0 # One second\n\n# UDP code here\n\ndef testTimeout():\n global datagramRecieved\n if not datagramRecieved:\n reactor.stop()\n datagramRecieved = False\n\n\nl = task.LoopingCall(testTimeout)\nl.start(timeout) # call every second\n\n# l.stop() will stop the looping calls\nreactor.run()\n"
},
{
"answer_id": 251302,
"author": "daf",
"author_id": 32082,
"author_profile": "https://Stackoverflow.com/users/32082",
"pm_score": 4,
"selected": false,
"text": "reactor.callLater LoopingCall class Protocol(DatagramProtocol):\n def __init__(self, timeout):\n self.timeout = timeout\n\n def datagramReceived(self, datagram):\n self.timeout.cancel()\n # ...\n\ntimeout = reactor.callLater(5, timedOut)\nreactor.listenUDP(Protocol(timeout))\n"
},
{
"answer_id": 11810177,
"author": "Mychot sad",
"author_id": 1126139,
"author_profile": "https://Stackoverflow.com/users/1126139",
"pm_score": 2,
"selected": false,
"text": "# -*- coding: utf-8 -*-\n\nfrom twisted.internet.protocol import Factory\nfrom twisted.protocols.basic import LineReceiver\nfrom twisted.internet import reactor, defer\n\n_timeout = 27\n\n\nclass ServiceProtocol(LineReceiver):\n\n def __init__(self, users):\n self.users = users\n\n\n def connectionLost(self, reason):\n if self.users.has_key(self.name):\n del self.users[self.name]\n\n def timeOut(self):\n if self.users.has_key(self.name):\n del self.users[self.name]\n self.sendLine(\"\\nOUT: 9 - Disconnected, reason: %s\" % 'Connection Timed out')\n print \"%s - Client disconnected: %s. Reason: %s\" % (datetime.now(), self.client_ip, 'Connection Timed out' )\n self.transport.loseConnection()\n\n def connectionMade(self):\n self.timeout = reactor.callLater(_timeout, self.timeOut)\n\n self.sendLine(\"\\nOUT: 7 - Welcome to CAED\")\n\n def lineReceived(self, line):\n # a simple timeout procrastination\n self.timeout.reset(_timeout)\n\nclass ServFactory(Factory):\n\n def __init__(self):\n self.users = {} # maps user names to Chat instances\n\n def buildProtocol(self, addr):\n return ServiceProtocol(self.users)\n\nport = 8123\nreactor.listenTCP(port, ServFactory())\nprint \"Started service at port %d\\n\" % port\nreactor.run()\n"
},
{
"answer_id": 24895751,
"author": "Tim Tisdall",
"author_id": 918558,
"author_profile": "https://Stackoverflow.com/users/918558",
"pm_score": 0,
"selected": false,
"text": "twisted.protocols.policies.TimeoutMixin callLater Mixin"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20572/"
] |
221,774
|
<p>I have a MySQL database of keywords that are presently mixed-case. However, I want to convert them all to lowercase. Is there an easy command to do this, either using MySQL or MySQL and PHP?</p>
|
[
{
"answer_id": 221780,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": false,
"text": "SELECT LOWER(foo) AS foo FROM bar"
},
{
"answer_id": 221787,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 9,
"selected": true,
"text": "UPDATE table SET colname=LOWER(colname);\n"
},
{
"answer_id": 221788,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 3,
"selected": false,
"text": "mysql> SELECT LOWER('QUADRATICALLY');\n -> 'quadratically'\n"
},
{
"answer_id": 221789,
"author": "Jon Grant",
"author_id": 18774,
"author_profile": "https://Stackoverflow.com/users/18774",
"pm_score": 5,
"selected": false,
"text": "select LOWER(keyword) from my_table\n"
},
{
"answer_id": 221801,
"author": "Rodent43",
"author_id": 28869,
"author_profile": "https://Stackoverflow.com/users/28869",
"pm_score": -1,
"selected": false,
"text": "strtolower() \n"
},
{
"answer_id": 221807,
"author": "dmanxiii",
"author_id": 4316,
"author_profile": "https://Stackoverflow.com/users/4316",
"pm_score": 3,
"selected": false,
"text": "SELECT LOWER(column_name) FROM table a;\n SELECT column_name FROM table a where column = LOWER('STRING')\n"
},
{
"answer_id": 22611328,
"author": "uma",
"author_id": 1845837,
"author_profile": "https://Stackoverflow.com/users/1845837",
"pm_score": -1,
"selected": false,
"text": "LOWER select LOWER(username) from users;\n select * from users where LOWER(username) = 'vrishbh';\n"
},
{
"answer_id": 48167700,
"author": "Vi8L",
"author_id": 7889523,
"author_profile": "https://Stackoverflow.com/users/7889523",
"pm_score": 3,
"selected": false,
"text": "UPDATE `tablename` SET `colnameone`=LOWER(`colnameone`); \n UPDATE `tablename` SET `colnameone`=LCASE(`colnameone`);\n"
},
{
"answer_id": 52409055,
"author": "HD FrenchFeast",
"author_id": 10348469,
"author_profile": "https://Stackoverflow.com/users/10348469",
"pm_score": 0,
"selected": false,
"text": "function ColBuilder ($field_name) {\n…\nWhile ($result = DB_fetch_array($PricesResult)) {\n$result[$field_name]\n}\n…\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
221,781
|
<p>We are migrating a web applicatin from vs05 to vs08. This application is using Telerik web controls. After I converted the project, and run, I get the exception: "A control is already associated with the element". I traced it down to a use control that has Telerik RadCombo box on it. However, I don't see anything out of place. Researching it, hasn't gotten me any results. I would appreciate any pointers.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 6444157,
"author": "Greg Woods",
"author_id": 810857,
"author_profile": "https://Stackoverflow.com/users/810857",
"pm_score": 1,
"selected": false,
"text": "child.control.dispose();\nchild.control = undefined;\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29726/"
] |
221,783
|
<p>Consider the following code:</p>
<pre><code>client.Send(data, data.Length, endpoint);
byte[] response = client.Receive(ref endpoint);
</code></pre>
<p>While, according to WireShark (network sniffer), the remote host does reply with data,
the application here just waits for data forever... it does not receive the answer from the remote host for some reason.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 4849573,
"author": "Mostafa",
"author_id": 596652,
"author_profile": "https://Stackoverflow.com/users/596652",
"pm_score": 1,
"selected": false,
"text": "client.Client.ReceiveTimeout = 5000; \n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28149/"
] |
221,800
|
<p>I want to learn MSBuild, was wondering if someone could get me started with a simple build script to filter out my vs.net 2008 project of all files with the .cs extension.</p>
<ol>
<li>how do I run the build?</li>
<li>where do you usually store the build also?</li>
</ol>
|
[
{
"answer_id": 221854,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "C:\\projects\\_Play\\SimpleIpService>type \\\\sysrdswbld1\\public\\bin\\mrb-vs2008.cmd\n@echo off\n\ncall \"c:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\"\n\necho %0 %*\necho %0 %* >> %MrB-LOG%\ncd\nif not \"\"==\"%~dp1\" pushd %~dp1\ncd\nif exist %~nx1 (\n echo VS2008 build of '%~nx1'.\n echo VS2008 build of '%~nx1'. >> %MrB-LOG%\n set MrB-BUILDLOG=%MrB-BASE%\\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log\n msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release > %MrB-BUILDLOG%\n findstr /r /c:\"[1-9][0-9]* Error(s)\" %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build errors in '%~nx1'.\n echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-LOG%\n call mrb-email \"Mr Build isn't happy about build errors in '%~nx1'\" %MrB-BUILDLOG%\n ) else (\n findstr /r /c:\"[1-9][0-9]* Warning(s)\" %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build warnings in '%~nx1'.\n echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-LOG%\n call mrb-email \"Mr Build isn't happy about build warnings in '%~nx1'\" %MrB-BUILDLOG%\n ) else (\n echo Successful build of '%~nx1'.\n echo Successful build of '%~nx1'. >> %MrB-LOG%\n )\n )\n) else (\n echo ERROR '%1' doesn't exist.\n echo ERROR '%1' doesn't exist. >> %MrB-LOG%\n)\npopd\n"
},
{
"answer_id": 222068,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "MSBuild <scriptfilename> /t:targetname\n <Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n <Import Project=\"Project.csproj\" Condition=\"Exists(Project.csproj')\"/>\n\n <Target Name=\"Test\">\n <Message Text=\"@(Compile)\"/>\n </Target>\n</Project>\n <Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n <Import Project=\"Project.csproj\" Condition=\"Exists(Project.csproj')\"/>\n\n <Target Name=\"Test\">\n <Message Text=\"%(Compile.FullPath)\"/>\n </Target>\n</Project>\n <Project ...> <Import ...> <Message Text=\"@(Compile)\"/>"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
221,804
|
<p>I need to find the min and max value in an array. The <code>.max</code> function works but <code>.min</code> keeps showing zero.</p>
<pre><code>Public Class Program_2_Grade
Dim max As Integer
Dim min As Integer
Dim average As Integer
Dim average1 As Integer
Dim grade As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = Nothing Or TextBox1.Text > 100 Then
MsgBox("Doesn't Meet Grade Requirements", MsgBoxStyle.Exclamation, "Error")
TextBox1.Clear()
TextBox1.Focus()
counter = 0
Else
grade_enter(counter) = TextBox1.Text
TextBox1.Clear()
TextBox1.Focus()
counter = counter + 1
If counter = grade_amount Then
max = grade_enter.Max()
min = grade_enter.Min()
For i As Integer = 0 To counter
average = average + grade_enter(i) / counter
average1 = average1 + grade_enter(i) - grade_enter.Min / counter
Next
Select Case average
Case 30 To 49
grade = "C"
Case 50 To 69
grade = "B"
Case 70 To 100
grade = "A"
Case Else
grade = "Fail"
End Select
If (Program_2.CheckBox1.Checked = True) Then
Program_2.TextBox4.Text = _
("Name:" & " " & (Program_2.TextBox1.Text) & vbNewLine & _
"Class: " & (Program_2.TextBox2.Text) & vbNewLine & _
"Number Of Grades:" & " " & (Program_2.TextBox3.Text) & vbNewLine & _
"Max:" & " " & max & vbNewLine & _
"Min:" & " " & min & vbNewLine & _
"Average:" & " " & average1 & vbNewLine) & _
"Grade:" & " " & grade & vbNewLine & _
"Dropped Lowest Grade"
Else
Program_2.TextBox4.Text = _
("Name:" & " " & (Program_2.TextBox1.Text) & vbNewLine & _
"Class: " & (Program_2.TextBox2.Text) & vbNewLine & _
"Number Of Grades:" & " " & (Program_2.TextBox3.Text) & vbNewLine & _
"Max:" & " " & max & vbNewLine & _
"Min:" & " " & min & vbNewLine & _
"Average:" & " " & average & vbNewLine) & _
"Grade:" & " " & grade & vbNewLine
End If
Me.Close()
average = 0
average1 = 0
counter = 0
End If
End If
End Sub
</code></pre>
<p>My arrays are set at global scope.</p>
|
[
{
"answer_id": 221834,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "max = grade_enter.Take(counter).Max()\nmin = grade_enter.Take(counter).Min()\n List(Of Integer)"
},
{
"answer_id": 221836,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "List(Of Integer)"
},
{
"answer_id": 221907,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": false,
"text": "Min() Public grade_enter(20) As Integer\n List(Of Integer) List Min() Max() ToArray() Min() Max()"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
221,806
|
<p>I have two questions :</p>
<ol>
<li><p>While doing source level debugging (using any debugger) does any debugger save state of some iteration/for-loop/any code executed and allow the user to go back to that previously executed code/data state at a later point of time during debugging?
The need for this is some variable/pointer is corrupted somewhere earlier in time during execution but is accessed after some time / later in the execution of code and thats when it crashes/hangs the code, so i would like to go back and see which function/at what time the variable was corrupted/wrong value computed and written to it ? Is it possible in any debugger (gcc, MSVC6.0 ...) </p></li>
<li><p>Does any debugger/IDE have provision that when a memory address/variable is marked for "analysis", it should display which function in which file, and which code changed that memory(write), every time it is changed/written?</p></li>
</ol>
<p>-AD </p>
|
[
{
"answer_id": 221849,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 1,
"selected": false,
"text": "for (i = 0; i < list.size(); i++) {\n foo = list[i];\n}\n i == 17 foo == null"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] |
221,822
|
<p>I'm familiar with Sybase / SQL server, where I can create a temp. table like this: </p>
<pre><code>SELECT *
INTO #temp
FROM tab1 ,
tab2
WHERE tab1.key = tab2.fkey
SELECT *
FROM #temp
WHERE field1 = 'value'
</code></pre>
<p>#temp only exists for the duration of this session, and can only be seen by me. </p>
<p>I would like to do a similar thing in Oracle, but I'm reading about "global temporary tables", which don't sound like the same thing. </p>
<p>How can I do the same thing in Oracle as I'm doing in Sybase? </p>
<p>Thanks :)</p>
|
[
{
"answer_id": 221880,
"author": "carson",
"author_id": 25343,
"author_profile": "https://Stackoverflow.com/users/25343",
"pm_score": 1,
"selected": false,
"text": "CREATE GLOBAL TEMPORARY TABLE my_temp_table ON COMMIT DELETE ROWS select * from other table;\n"
},
{
"answer_id": 225726,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 3,
"selected": true,
"text": "SELECT * \nFROM \n(\nSELECT * \nFROM tab1 , \n tab2 \nWHERE tab1.key = tab2.fkey\n)\nWHERE field1 = 'value';\n with #temp as\n(\nSELECT /*+ materialize */ \n * \nFROM tab1 , \n tab2 \nWHERE tab1.key = tab2.fkey\n)\nSELECT * \nFROM temp#\nWHERE field1 = 'value';\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
] |
221,824
|
<p>Basically I'm converting local dates stored in the database into UTC. But I've read somewhere that daylight saving rules have changed in 2007. So does the Date.ToUniversalTime() function still work correctly. Basically the dates before 2007(when the new rules came into effect) would be converted correctly but the dates after that would be not. Am I right here? Or would .Net take care of the conversion internally i.e. depending upon the different daylight saving rules?</p>
<p>EDIT: Dates are stored in DB as local times. I am converting it into UTC. So a date such as '9 March 2005' should be converted using day light rules of 2005 instead of today's rules. The rules changed in the US in 2007. So the date is coming out wrong by one hour.</p>
|
[
{
"answer_id": 221850,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "ToUniversalTime()"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] |
221,830
|
<p>I have two BufferedImages I loaded in from pngs. The first contains an image, the second an alpha mask for the image.</p>
<p>I want to create a combined image from the two, by applying the alpha mask. My google-fu fails me.</p>
<p>I know how to load/save the images, I just need the bit where I go from two BufferedImages to one BufferedImage with the right alpha channel.</p>
|
[
{
"answer_id": 221869,
"author": "Zarkonnen",
"author_id": 15255,
"author_profile": "https://Stackoverflow.com/users/15255",
"pm_score": 0,
"selected": false,
"text": "for (int y = 0; y < image.getHeight(); y++) {\n for (int x = 0; x < image.getWidth(); x++) {\n Color c = new Color(image.getRGB(x, y));\n Color maskC = new Color(mask.getRGB(x, y));\n Color maskedColor = new Color(c.getRed(), c.getGreen(), c.getBlue(),\n maskC.getRed());\n resultImg.setRGB(x, y, maskedColor.getRGB());\n }\n}\n"
},
{
"answer_id": 221982,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": false,
"text": "TestMask() throws IOException\n{\n m_images = new BufferedImage[3];\n m_images[0] = ImageIO.read(new File(\"E:/Documents/images/map.png\"));\n m_images[1] = ImageIO.read(new File(\"E:/Documents/images/mapMask3.png\"));\n Image transpImg = TransformGrayToTransparency(m_images[1]);\n m_images[2] = ApplyTransparency(m_images[0], transpImg);\n}\n\nprivate Image TransformGrayToTransparency(BufferedImage image)\n{\n ImageFilter filter = new RGBImageFilter()\n {\n public final int filterRGB(int x, int y, int rgb)\n {\n return (rgb << 8) & 0xFF000000;\n }\n };\n\n ImageProducer ip = new FilteredImageSource(image.getSource(), filter);\n return Toolkit.getDefaultToolkit().createImage(ip);\n}\n\nprivate BufferedImage ApplyTransparency(BufferedImage image, Image mask)\n{\n BufferedImage dest = new BufferedImage(\n image.getWidth(), image.getHeight(),\n BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = dest.createGraphics();\n g2.drawImage(image, 0, 0, null);\n AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0F);\n g2.setComposite(ac);\n g2.drawImage(mask, 0, 0, null);\n g2.dispose();\n return dest;\n}\n"
},
{
"answer_id": 221990,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 4,
"selected": true,
"text": "final int width = image.getWidth();\nint[] imgData = new int[width];\nint[] maskData = new int[width];\n\nfor (int y = 0; y < image.getHeight(); y++) {\n // fetch a line of data from each image\n image.getRGB(0, y, width, 1, imgData, 0, 1);\n mask.getRGB(0, y, width, 1, maskData, 0, 1);\n // apply the mask\n for (int x = 0; x < width; x++) {\n int color = imgData[x] & 0x00FFFFFF; // mask away any alpha present\n int maskColor = (maskData[x] & 0x00FF0000) << 8; // shift red into alpha bits\n color |= maskColor;\n imgData[x] = color;\n }\n // replace the data\n image.setRGB(0, y, width, 1, imgData, 0, 1);\n}\n"
},
{
"answer_id": 8058442,
"author": "Meyer",
"author_id": 859499,
"author_profile": "https://Stackoverflow.com/users/859499",
"pm_score": 5,
"selected": false,
"text": "public void applyGrayscaleMaskToAlpha(BufferedImage image, BufferedImage mask)\n{\n int width = image.getWidth();\n int height = image.getHeight();\n\n int[] imagePixels = image.getRGB(0, 0, width, height, null, 0, width);\n int[] maskPixels = mask.getRGB(0, 0, width, height, null, 0, width);\n\n for (int i = 0; i < imagePixels.length; i++)\n {\n int color = imagePixels[i] & 0x00ffffff; // Mask preexisting alpha\n int alpha = maskPixels[i] << 24; // Shift blue to alpha\n imagePixels[i] = color | alpha;\n }\n\n image.setRGB(0, 0, width, height, imagePixels, 0, width);\n}\n"
},
{
"answer_id": 46474971,
"author": "Thiago Medeiros dos Santos",
"author_id": 8691156,
"author_profile": "https://Stackoverflow.com/users/8691156",
"pm_score": 1,
"selected": false,
"text": " val width = this.width\n val imgData = IntArray(width)\n val maskData = IntArray(width)\n\n for(y in 0..(this.height - 1)) {\n\n this.getRGB(0, y, width, 1, imgData, 0, 1)\n mask.getRGB(0, y, width, 1, maskData, 0, 1)\n\n for (x in 0..(this.width - 1)) {\n\n val maskAlpha = (maskData[x] and 0x000000FF)/ 255f\n val imageAlpha = ((imgData[x] shr 24) and 0x000000FF) / 255f\n val rgb = imgData[x] and 0x00FFFFFF\n val alpha = ((maskAlpha * imageAlpha) * 255).toInt() shl 24\n imgData[x] = rgb or alpha\n }\n this.setRGB(0, y, width, 1, imgData, 0, 1)\n }\n int width = image.getWidth();\n int[] imgData = new int[width];\n int[] maskData = new int[width];\n\n for (int y = 0; y < image.getHeight(); y ++) {\n\n image.getRGB(0, y, width, 1, imgData, 0, 1);\n mask.getRGB(0, y, width, 1, maskData, 0, 1);\n\n for (int x = 0; x < image.getWidth(); x ++) {\n\n //Normalize (0 - 1)\n float maskAlpha = (maskData[x] & 0x000000FF)/ 255f;\n float imageAlpha = ((imgData[x] >> 24) & 0x000000FF) / 255f;\n\n //Image without alpha channel\n int rgb = imgData[x] & 0x00FFFFFF;\n\n //Multiplied alpha\n int alpha = ((int) ((maskAlpha * imageAlpha) * 255)) << 24;\n\n //Add alpha to image\n imgData[x] = rgb | alpha;\n }\n image.setRGB(0, y, width, 1, imgData, 0, 1);\n }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15255/"
] |
221,892
|
<p>Is there a way to write an enumeration that can be extended. I have several methods that I would like to always have available for my enumerations. For example I use an enumeration for my database fields. I include the actual field name in the database. </p>
<pre><code>public enum ORDERFIELDS
{
OrderID("Order_ID");
private String FieldName;
private ORDERFIELDS(String fname)
{
this.FieldName = fname;
}
public String getFieldName()
{
return FieldName;
}
}
</code></pre>
|
[
{
"answer_id": 221902,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 4,
"selected": false,
"text": "java.lang.Enum"
},
{
"answer_id": 221916,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 4,
"selected": true,
"text": "public abstract class DatabaseField {\n private String fieldName;\n\n private DatabaseField(String fieldName) {\n this.fieldName = fieldName;\n }\n\n public String getFieldName() {\n return fieldName;\n }\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17712/"
] |
221,894
|
<p>We are currently using the <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;118623" rel="noreferrer">NetBios method</a>, and it works ok under XP. Preliminary tests under Vista show that it also works, but there are caveats - NetBIOS has to be present, for instance, and from what I've been reading, the order of the adapters is bound to change. Our alternative method - with <a href="http://msdn.microsoft.com/en-us/library/aa378021(VS.85).aspx" rel="noreferrer">SNMPExtensionQuery</a> - seems to be broken under Vista.</p>
<p>The question is: do you know of a reliable way to get a list of the local MAC addresses on a Vista machine? Backwards compatibility with XP is a plus (I'd rather have one single method than lots of ugly #ifdef's). Thanks!</p>
|
[
{
"answer_id": 221992,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "void getdMacAddresses(std::vector<std::string> &vMacAddresses;)\n{\n vMacAddresses.clear();\n IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs\n DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer\n DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo\n AdapterInfo, // [out] buffer to receive data\n &dwBufLen); // [in] size of receive data buffer\n\n //No network card? Other error?\n if(dwStatus != ERROR_SUCCESS)\n return;\n\n PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;\n char szBuffer[512];\n while(pAdapterInfo)\n {\n if(pAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)\n {\n sprintf_s(szBuffer, sizeof(szBuffer), \"%.2x-%.2x-%.2x-%.2x-%.2x-%.2x\"\n , pAdapterInfo->Address[0]\n , pAdapterInfo->Address[1]\n , pAdapterInfo->Address[2]\n , pAdapterInfo->Address[3]\n , pAdapterInfo->Address[4]\n , pAdapterInfo->Address[5]\n );\n vMacAddresses.push_back(szBuffer);\n }\n pAdapterInfo = pAdapterInfo->Next;\n\n }\n}\n"
},
{
"answer_id": 34074424,
"author": "fadi abassi",
"author_id": 5636586,
"author_profile": "https://Stackoverflow.com/users/5636586",
"pm_score": 0,
"selected": false,
"text": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <Windows.h>\n#include <Iphlpapi.h>\n#include <Assert.h>\n#include <string>\n#pragma comment(lib, \"iphlpapi.lib\")\n\n\nchar* getdMacAddresses()\n{\n\n IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs\n DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer\n DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo\n AdapterInfo, // [out] buffer to receive data\n &dwBufLen); // [in] size of receive data buffer\n\n //Exit When Error \n if (dwStatus != ERROR_SUCCESS)\n return \"ERROR\";\n\n PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;\n char szBuffer[512];\n while (pAdapterInfo)\n {\n if (pAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)\n {\n\n sprintf_s(szBuffer, sizeof(szBuffer), \"%.2x-%.2x-%.2x-%.2x-%.2x-%.2x\"\n , pAdapterInfo->Address[0]\n , pAdapterInfo->Address[1]\n , pAdapterInfo->Address[2]\n , pAdapterInfo->Address[3]\n , pAdapterInfo->Address[4]\n , pAdapterInfo->Address[5]\n );\n\n return szBuffer; \n\n }\n\n\n pAdapterInfo = pAdapterInfo->Next;\n\n }\n\n return \"ERROR\";\n}\n"
},
{
"answer_id": 52086224,
"author": "Jesse Chisholm",
"author_id": 1456887,
"author_profile": "https://Stackoverflow.com/users/1456887",
"pm_score": 1,
"selected": false,
"text": "ToString convertToUtf8 convertFromUtf8 class WmiAccessor\n{\npublic:\n WmiAccessor()\n : _pWbemLocator(NULL)\n , _pWbemServices(NULL)\n , _com_initialized(false)\n , _com_need_uninitialize(false)\n , _svc_initialized(false)\n , _loc_initialized(false)\n , _all_initialized(false)\n , _errors(\"\")\n , m_mutex()\n {\n HRESULT hr;\n hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);\n switch (hr)\n {\n case S_OK:\n // The COM library was initialized successfully on this thread.\n _com_initialized = true;\n _com_need_uninitialize = true;\n break;\n case S_FALSE:\n // The COM library is already initialized on this thread.\n _com_initialized = true;\n _com_need_uninitialize = true;\n break;\n case RPC_E_CHANGED_MODE:\n // A previous call to CoInitializeEx specified the concurrency model\n // for this thread as multithread apartment (MTA).\n // This could also indicate that a change from neutral-threaded apartment to\n // single-threaded apartment has occurred.\n _com_initialized = true;\n _com_need_uninitialize = false;\n break;\n default:\n _com_initialized = false;\n _com_need_uninitialize = false;\n _errors += \"Failed to initialize COM.\\r\\n\";\n return;\n }\n\n hr = ::CoInitializeSecurity(NULL, -1, NULL, NULL,\n 0 /*RPC_C_AUTHN_LEVEL_DEFAULT*/,\n 3 /*RPC_C_IMP_LEVEL_IMPERSONATE*/,\n NULL, EOAC_NONE, NULL);\n // RPC_E_TOO_LATE == Security must be initialized before!\n // It cannot be changed once initialized. I don't care!\n if (FAILED(hr) && (hr != RPC_E_TOO_LATE))\n {\n _errors += \"Failed to initialize COM Security.\\r\\n\";\n if (_com_need_uninitialize)\n {\n ::CoUninitialize();\n _com_need_uninitialize = false;\n }\n return;\n }\n\n hr = _pWbemLocator.CoCreateInstance(CLSID_WbemLocator);\n if (FAILED(hr) || (_pWbemLocator == nullptr))\n {\n _errors += \"Failed to initialize WBEM Locator.\\r\\n\";\n return;\n }\n _loc_initialized = true;\n\n hr = _pWbemLocator->ConnectServer(\n CComBSTR(L\"root\\\\cimv2\"), NULL, NULL, 0, NULL, 0, NULL, &_pWbemServices);\n if (FAILED(hr) || (_pWbemServices == nullptr))\n {\n _errors += \"Failed to connect WBEM Locator.\\r\\n\";\n _pWbemLocator.Release();\n _loc_initialized = false;\n return;\n }\n else\n {\n _svc_initialized = true;\n\n // Set security Levels on the proxy\n hr = CoSetProxyBlanket(_pWbemServices,\n RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx\n RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx\n NULL, // Server principal name\n RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx\n RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx\n NULL, // client identity\n EOAC_NONE // proxy capabilities\n );\n if (FAILED(hr))\n {\n _errors += \"Failed to set proxy blanket.\\r\\n\";\n return;\n }\n }\n\n _all_initialized = true;\n }\n\n ~WmiAccessor()\n {\n std::unique_lock<std::mutex> slock(m_mutex);\n\n if (_svc_initialized)\n {\n if (_pWbemServices)\n _pWbemServices.Release();\n _svc_initialized = false;\n }\n if (_loc_initialized)\n {\n if (_pWbemLocator)\n _pWbemLocator.Release();\n _loc_initialized = false;\n }\n if (_com_initialized)\n {\n if (_com_need_uninitialize)\n {\n ::CoUninitialize();\n }\n _com_initialized = false;\n _com_need_uninitialize = false;\n }\n _all_initialized = false;\n }\n\n // public: must lock\n std::string get_and_clear_errors()\n {\n std::string result = \"\";\n std::unique_lock<std::mutex> slock(m_mutex);\n std::swap(result, _errors);\n return result;\n }\n\n // public: must lock\n std::string get_string(const std::string& name, const std::string& dflt /*= \"\"*/)\n {\n std::unique_lock<std::mutex> slock(m_mutex);\n return _all_initialized ? _string(name) : dflt;\n }\n\n // public: must lock\n uint32_t get_uint32(const std::string& name, uint32_t dflt /*= 0*/)\n {\n std::unique_lock<std::mutex> slock(m_mutex);\n return _all_initialized ? _uint32(name) : dflt;\n }\n\n\n // similarly for other public accessors of basic types.\n\n\nprivate:\n CComPtr<IWbemLocator> _pWbemLocator;\n CComPtr<IWbemServices> _pWbemServices;\n volatile bool _com_initialized;\n volatile bool _com_need_uninitialize;\n volatile bool _svc_initialized;\n volatile bool _loc_initialized;\n volatile bool _all_initialized;\n std::string _errors;\n CComVariant _variant(const std::wstring& name);\n std::string _string(const std::string& name);\n uint32_t _uint32(const std::string& name);\n uint16_t _uint16(const std::string& name);\n uint8_t _uint8(const std::string& name);\n std::vector<std::string> _macAddresses(bool forceReCalculate = false);\n // to protect internal objects, public methods need to protect the internals.\n //\n mutable std::mutex m_mutex;\n std::vector<std::string> _macs; // unlikely to change, so save them once found.\n\n // internal: assumes inside a lock\n CComVariant _variant(const std::wstring& name)\n {\n if (!_all_initialized)\n return CComVariant();\n\n CComPtr<IEnumWbemClassObject> pEnum;\n CComBSTR cbsQuery = std::wstring(L\"Select \" + name + L\" from Win32_OperatingSystem\").c_str();\n HRESULT hr = _pWbemServices->ExecQuery(\n CComBSTR(L\"WQL\"), cbsQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);\n CComVariant cvtValue;\n if (FAILED(hr) || !pEnum)\n {\n std::wstring wquery(cbsQuery, SysStringLen(cbsQuery));\n _errors += \"Failed to exec WMI query: '\" + convertToUtf8(wquery) + \"'\\r\\n\";\n return cvtValue;\n }\n ULONG uObjectCount = 0;\n CComPtr<IWbemClassObject> pWmiObject;\n hr = pEnum->Next(WBEM_INFINITE, 1, &pWmiObject, &uObjectCount);\n if (FAILED(hr) || !pWmiObject)\n {\n _errors\n += \"Failed to get WMI Next result for: '\" + convertToUtf8(name) + \"'\\r\\n\";\n return cvtValue;\n }\n hr = pWmiObject->Get(name.c_str(), 0, &cvtValue, 0, 0);\n if (FAILED(hr))\n {\n _errors\n += \"Failed to get WMI result value for: '\" + convertToUtf8(name) + \"'\\r\\n\";\n }\n return cvtValue;\n }\n\n // internal: assumes inside a lock\n std::string _string(const std::string& name)\n {\n if (!_all_initialized)\n return \"\";\n\n CComVariant cvtValue = _variant(convertFromUtf8(name).c_str());\n std::wstring wValue(cvtValue.bstrVal, SysStringLen(cvtValue.bstrVal));\n std::string sValue = convertToUtf8(wValue);\n return sValue;\n }\n\n // internal: assumes inside a lock\n uint32_t _uint32(const std::string& name)\n {\n if (!_all_initialized)\n return 0;\n\n CComVariant cvtValue = _variant(convertFromUtf8(name).c_str());\n uint32_t uValue = static_cast<uint32_t>(cvtValue.lVal);\n return uValue;\n }\n\n // similarly for other internal access of basic types.\n\n // internal: assumes inside a lock\n std::vector<std::string> _macAddresses(bool forceReCalculate /*= false*/)\n {\n if (!_all_initialized)\n {\n return _macs; // it will still be empty at this point.\n }\n if (forceReCalculate)\n {\n _macs.clear();\n }\n if (_macs.empty())\n {\n // hr == 0x80041010 == WBEM_E_INVALID_CLASS\n // hr == 0x80041017 == WBEM_E_INVALID_QUERY\n // hr == 0x80041018 == WBEM_E_INVALID_QUERY_TYPE\n CComBSTR cbsQuery = std::wstring(L\"Select * from Win32_NetworkAdapter\").c_str();\n CComPtr<IEnumWbemClassObject> pEnum;\n HRESULT hr = _pWbemServices->ExecQuery(\n CComBSTR(L\"WQL\"), cbsQuery, WBEM_RETURN_IMMEDIATELY, NULL, &pEnum);\n if (FAILED(hr))\n {\n _errors += \"error: MacAddresses: ExecQuery('\"\n + convertToUtf8((LPWSTR)cbsQuery) + \"') returned \"\n + ToString(hr) + \"\\r\\n\";\n }\n if (SUCCEEDED(hr))\n {\n ULONG fetched;\n VARIANT var;\n IWbemClassObject* pclsObj = NULL;\n while (pEnum)\n {\n hr = pEnum->Next(WBEM_INFINITE, 1, &pclsObj, &fetched);\n if (0 == fetched)\n break;\n\n std::string theMac = \"\";\n VariantInit(&var);\n hr = pclsObj->Get(L\"MACAddress\", 0, &var, 0, 0);\n if (SUCCEEDED(hr))\n {\n switch (var.vt)\n {\n case VT_NULL: break;\n case VT_BSTR:\n theMac = (var.bstrVal == NULL)\n ? \"\"\n : convertToUtf8(var.bstrVal);\n break;\n case VT_LPSTR:\n theMac = (var.bstrVal == NULL)\n ? \"\"\n : (const char*)var.bstrVal;\n break;\n case VT_LPWSTR:\n theMac = (var.bstrVal == NULL)\n ? \"\"\n : convertToUtf8((LPWSTR)var.bstrVal);\n break;\n // _could_ be array of BSTR, LPSTR, LPWSTR; unlikely, but ....\n case VT_ARRAY | VT_BSTR:\n case VT_ARRAY | VT_LPSTR:\n case VT_ARRAY | VT_LPWSTR:\n _errors += \"warning: MacAddresses: unexpected array of addresses\";\n _errors += \"\\r\\n\";\n\n // yet another exercise for the reader :)\n break;\n default:\n _errors += \"error: MacAddresses: unexpected VARIANT.vt = \"\n + ToString(var.vt) + \"\\r\\n\";\n break;\n }\n // local loopback has an empty address?\n if (!theMac.empty())\n {\n _macs.push_back(theMac);\n }\n }\n VariantClear(&var);\n pclsObj->Release();\n }\n }\n }\n return _macs;\n }\n\n...\n\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7134/"
] |
221,901
|
<p>Do the clients need something else than a proper jdk and javafx compliant browser to visit javafx applets?</p>
|
[
{
"answer_id": 221992,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "void getdMacAddresses(std::vector<std::string> &vMacAddresses;)\n{\n vMacAddresses.clear();\n IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs\n DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer\n DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo\n AdapterInfo, // [out] buffer to receive data\n &dwBufLen); // [in] size of receive data buffer\n\n //No network card? Other error?\n if(dwStatus != ERROR_SUCCESS)\n return;\n\n PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;\n char szBuffer[512];\n while(pAdapterInfo)\n {\n if(pAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)\n {\n sprintf_s(szBuffer, sizeof(szBuffer), \"%.2x-%.2x-%.2x-%.2x-%.2x-%.2x\"\n , pAdapterInfo->Address[0]\n , pAdapterInfo->Address[1]\n , pAdapterInfo->Address[2]\n , pAdapterInfo->Address[3]\n , pAdapterInfo->Address[4]\n , pAdapterInfo->Address[5]\n );\n vMacAddresses.push_back(szBuffer);\n }\n pAdapterInfo = pAdapterInfo->Next;\n\n }\n}\n"
},
{
"answer_id": 34074424,
"author": "fadi abassi",
"author_id": 5636586,
"author_profile": "https://Stackoverflow.com/users/5636586",
"pm_score": 0,
"selected": false,
"text": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <Windows.h>\n#include <Iphlpapi.h>\n#include <Assert.h>\n#include <string>\n#pragma comment(lib, \"iphlpapi.lib\")\n\n\nchar* getdMacAddresses()\n{\n\n IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs\n DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer\n DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo\n AdapterInfo, // [out] buffer to receive data\n &dwBufLen); // [in] size of receive data buffer\n\n //Exit When Error \n if (dwStatus != ERROR_SUCCESS)\n return \"ERROR\";\n\n PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;\n char szBuffer[512];\n while (pAdapterInfo)\n {\n if (pAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)\n {\n\n sprintf_s(szBuffer, sizeof(szBuffer), \"%.2x-%.2x-%.2x-%.2x-%.2x-%.2x\"\n , pAdapterInfo->Address[0]\n , pAdapterInfo->Address[1]\n , pAdapterInfo->Address[2]\n , pAdapterInfo->Address[3]\n , pAdapterInfo->Address[4]\n , pAdapterInfo->Address[5]\n );\n\n return szBuffer; \n\n }\n\n\n pAdapterInfo = pAdapterInfo->Next;\n\n }\n\n return \"ERROR\";\n}\n"
},
{
"answer_id": 52086224,
"author": "Jesse Chisholm",
"author_id": 1456887,
"author_profile": "https://Stackoverflow.com/users/1456887",
"pm_score": 1,
"selected": false,
"text": "ToString convertToUtf8 convertFromUtf8 class WmiAccessor\n{\npublic:\n WmiAccessor()\n : _pWbemLocator(NULL)\n , _pWbemServices(NULL)\n , _com_initialized(false)\n , _com_need_uninitialize(false)\n , _svc_initialized(false)\n , _loc_initialized(false)\n , _all_initialized(false)\n , _errors(\"\")\n , m_mutex()\n {\n HRESULT hr;\n hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);\n switch (hr)\n {\n case S_OK:\n // The COM library was initialized successfully on this thread.\n _com_initialized = true;\n _com_need_uninitialize = true;\n break;\n case S_FALSE:\n // The COM library is already initialized on this thread.\n _com_initialized = true;\n _com_need_uninitialize = true;\n break;\n case RPC_E_CHANGED_MODE:\n // A previous call to CoInitializeEx specified the concurrency model\n // for this thread as multithread apartment (MTA).\n // This could also indicate that a change from neutral-threaded apartment to\n // single-threaded apartment has occurred.\n _com_initialized = true;\n _com_need_uninitialize = false;\n break;\n default:\n _com_initialized = false;\n _com_need_uninitialize = false;\n _errors += \"Failed to initialize COM.\\r\\n\";\n return;\n }\n\n hr = ::CoInitializeSecurity(NULL, -1, NULL, NULL,\n 0 /*RPC_C_AUTHN_LEVEL_DEFAULT*/,\n 3 /*RPC_C_IMP_LEVEL_IMPERSONATE*/,\n NULL, EOAC_NONE, NULL);\n // RPC_E_TOO_LATE == Security must be initialized before!\n // It cannot be changed once initialized. I don't care!\n if (FAILED(hr) && (hr != RPC_E_TOO_LATE))\n {\n _errors += \"Failed to initialize COM Security.\\r\\n\";\n if (_com_need_uninitialize)\n {\n ::CoUninitialize();\n _com_need_uninitialize = false;\n }\n return;\n }\n\n hr = _pWbemLocator.CoCreateInstance(CLSID_WbemLocator);\n if (FAILED(hr) || (_pWbemLocator == nullptr))\n {\n _errors += \"Failed to initialize WBEM Locator.\\r\\n\";\n return;\n }\n _loc_initialized = true;\n\n hr = _pWbemLocator->ConnectServer(\n CComBSTR(L\"root\\\\cimv2\"), NULL, NULL, 0, NULL, 0, NULL, &_pWbemServices);\n if (FAILED(hr) || (_pWbemServices == nullptr))\n {\n _errors += \"Failed to connect WBEM Locator.\\r\\n\";\n _pWbemLocator.Release();\n _loc_initialized = false;\n return;\n }\n else\n {\n _svc_initialized = true;\n\n // Set security Levels on the proxy\n hr = CoSetProxyBlanket(_pWbemServices,\n RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx\n RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx\n NULL, // Server principal name\n RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx\n RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx\n NULL, // client identity\n EOAC_NONE // proxy capabilities\n );\n if (FAILED(hr))\n {\n _errors += \"Failed to set proxy blanket.\\r\\n\";\n return;\n }\n }\n\n _all_initialized = true;\n }\n\n ~WmiAccessor()\n {\n std::unique_lock<std::mutex> slock(m_mutex);\n\n if (_svc_initialized)\n {\n if (_pWbemServices)\n _pWbemServices.Release();\n _svc_initialized = false;\n }\n if (_loc_initialized)\n {\n if (_pWbemLocator)\n _pWbemLocator.Release();\n _loc_initialized = false;\n }\n if (_com_initialized)\n {\n if (_com_need_uninitialize)\n {\n ::CoUninitialize();\n }\n _com_initialized = false;\n _com_need_uninitialize = false;\n }\n _all_initialized = false;\n }\n\n // public: must lock\n std::string get_and_clear_errors()\n {\n std::string result = \"\";\n std::unique_lock<std::mutex> slock(m_mutex);\n std::swap(result, _errors);\n return result;\n }\n\n // public: must lock\n std::string get_string(const std::string& name, const std::string& dflt /*= \"\"*/)\n {\n std::unique_lock<std::mutex> slock(m_mutex);\n return _all_initialized ? _string(name) : dflt;\n }\n\n // public: must lock\n uint32_t get_uint32(const std::string& name, uint32_t dflt /*= 0*/)\n {\n std::unique_lock<std::mutex> slock(m_mutex);\n return _all_initialized ? _uint32(name) : dflt;\n }\n\n\n // similarly for other public accessors of basic types.\n\n\nprivate:\n CComPtr<IWbemLocator> _pWbemLocator;\n CComPtr<IWbemServices> _pWbemServices;\n volatile bool _com_initialized;\n volatile bool _com_need_uninitialize;\n volatile bool _svc_initialized;\n volatile bool _loc_initialized;\n volatile bool _all_initialized;\n std::string _errors;\n CComVariant _variant(const std::wstring& name);\n std::string _string(const std::string& name);\n uint32_t _uint32(const std::string& name);\n uint16_t _uint16(const std::string& name);\n uint8_t _uint8(const std::string& name);\n std::vector<std::string> _macAddresses(bool forceReCalculate = false);\n // to protect internal objects, public methods need to protect the internals.\n //\n mutable std::mutex m_mutex;\n std::vector<std::string> _macs; // unlikely to change, so save them once found.\n\n // internal: assumes inside a lock\n CComVariant _variant(const std::wstring& name)\n {\n if (!_all_initialized)\n return CComVariant();\n\n CComPtr<IEnumWbemClassObject> pEnum;\n CComBSTR cbsQuery = std::wstring(L\"Select \" + name + L\" from Win32_OperatingSystem\").c_str();\n HRESULT hr = _pWbemServices->ExecQuery(\n CComBSTR(L\"WQL\"), cbsQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);\n CComVariant cvtValue;\n if (FAILED(hr) || !pEnum)\n {\n std::wstring wquery(cbsQuery, SysStringLen(cbsQuery));\n _errors += \"Failed to exec WMI query: '\" + convertToUtf8(wquery) + \"'\\r\\n\";\n return cvtValue;\n }\n ULONG uObjectCount = 0;\n CComPtr<IWbemClassObject> pWmiObject;\n hr = pEnum->Next(WBEM_INFINITE, 1, &pWmiObject, &uObjectCount);\n if (FAILED(hr) || !pWmiObject)\n {\n _errors\n += \"Failed to get WMI Next result for: '\" + convertToUtf8(name) + \"'\\r\\n\";\n return cvtValue;\n }\n hr = pWmiObject->Get(name.c_str(), 0, &cvtValue, 0, 0);\n if (FAILED(hr))\n {\n _errors\n += \"Failed to get WMI result value for: '\" + convertToUtf8(name) + \"'\\r\\n\";\n }\n return cvtValue;\n }\n\n // internal: assumes inside a lock\n std::string _string(const std::string& name)\n {\n if (!_all_initialized)\n return \"\";\n\n CComVariant cvtValue = _variant(convertFromUtf8(name).c_str());\n std::wstring wValue(cvtValue.bstrVal, SysStringLen(cvtValue.bstrVal));\n std::string sValue = convertToUtf8(wValue);\n return sValue;\n }\n\n // internal: assumes inside a lock\n uint32_t _uint32(const std::string& name)\n {\n if (!_all_initialized)\n return 0;\n\n CComVariant cvtValue = _variant(convertFromUtf8(name).c_str());\n uint32_t uValue = static_cast<uint32_t>(cvtValue.lVal);\n return uValue;\n }\n\n // similarly for other internal access of basic types.\n\n // internal: assumes inside a lock\n std::vector<std::string> _macAddresses(bool forceReCalculate /*= false*/)\n {\n if (!_all_initialized)\n {\n return _macs; // it will still be empty at this point.\n }\n if (forceReCalculate)\n {\n _macs.clear();\n }\n if (_macs.empty())\n {\n // hr == 0x80041010 == WBEM_E_INVALID_CLASS\n // hr == 0x80041017 == WBEM_E_INVALID_QUERY\n // hr == 0x80041018 == WBEM_E_INVALID_QUERY_TYPE\n CComBSTR cbsQuery = std::wstring(L\"Select * from Win32_NetworkAdapter\").c_str();\n CComPtr<IEnumWbemClassObject> pEnum;\n HRESULT hr = _pWbemServices->ExecQuery(\n CComBSTR(L\"WQL\"), cbsQuery, WBEM_RETURN_IMMEDIATELY, NULL, &pEnum);\n if (FAILED(hr))\n {\n _errors += \"error: MacAddresses: ExecQuery('\"\n + convertToUtf8((LPWSTR)cbsQuery) + \"') returned \"\n + ToString(hr) + \"\\r\\n\";\n }\n if (SUCCEEDED(hr))\n {\n ULONG fetched;\n VARIANT var;\n IWbemClassObject* pclsObj = NULL;\n while (pEnum)\n {\n hr = pEnum->Next(WBEM_INFINITE, 1, &pclsObj, &fetched);\n if (0 == fetched)\n break;\n\n std::string theMac = \"\";\n VariantInit(&var);\n hr = pclsObj->Get(L\"MACAddress\", 0, &var, 0, 0);\n if (SUCCEEDED(hr))\n {\n switch (var.vt)\n {\n case VT_NULL: break;\n case VT_BSTR:\n theMac = (var.bstrVal == NULL)\n ? \"\"\n : convertToUtf8(var.bstrVal);\n break;\n case VT_LPSTR:\n theMac = (var.bstrVal == NULL)\n ? \"\"\n : (const char*)var.bstrVal;\n break;\n case VT_LPWSTR:\n theMac = (var.bstrVal == NULL)\n ? \"\"\n : convertToUtf8((LPWSTR)var.bstrVal);\n break;\n // _could_ be array of BSTR, LPSTR, LPWSTR; unlikely, but ....\n case VT_ARRAY | VT_BSTR:\n case VT_ARRAY | VT_LPSTR:\n case VT_ARRAY | VT_LPWSTR:\n _errors += \"warning: MacAddresses: unexpected array of addresses\";\n _errors += \"\\r\\n\";\n\n // yet another exercise for the reader :)\n break;\n default:\n _errors += \"error: MacAddresses: unexpected VARIANT.vt = \"\n + ToString(var.vt) + \"\\r\\n\";\n break;\n }\n // local loopback has an empty address?\n if (!theMac.empty())\n {\n _macs.push_back(theMac);\n }\n }\n VariantClear(&var);\n pclsObj->Release();\n }\n }\n }\n return _macs;\n }\n\n...\n\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148909/"
] |
221,909
|
<p>I'm writing a stored procedure that needs to have a lot of conditioning in it. With the general knowledge from C#.NET coding that exceptions can hurt performance, I've always avoided using them in PL/SQL as well. My conditioning in this stored proc mostly revolves around whether or not a record exists, which I could do one of two ways:</p>
<pre><code>SELECT COUNT(*) INTO var WHERE condition;
IF var > 0 THEN
SELECT NEEDED_FIELD INTO otherVar WHERE condition;
....
</code></pre>
<p><b>-or-</b></p>
<pre><code>SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND
....
</code></pre>
<p>The second case seems a bit more elegant to me, because then I can use NEEDED_FIELD, which I would have had to select in the first statement after the condition in the first case. Less code. But if the stored procedure will run faster using the COUNT(*), then I don't mind typing a little more to make up processing speed.</p>
<p>Any hints? Am I missing another possibility?</p>
<p><b>EDIT</b>
I should have mentioned that this is all already nested in a FOR LOOP. Not sure if this makes a difference with using a cursor, since I don't think I can DECLARE the cursor as a select in the FOR LOOP.</p>
|
[
{
"answer_id": 221960,
"author": "Steve Bosman",
"author_id": 4389,
"author_profile": "https://Stackoverflow.com/users/4389",
"pm_score": 1,
"selected": false,
"text": "DECLARE\n CURSOR foo_cur IS \n SELECT NEEDED_FIELD WHERE condition ;\nBEGIN\n OPEN foo_cur;\n FETCH foo_cur INTO foo_rec;\n IF foo_cur%FOUND THEN\n ...\n END IF;\n CLOSE foo_cur;\nEXCEPTION\n WHEN OTHERS THEN\n CLOSE foo_cur;\n RAISE;\nEND ;\n"
},
{
"answer_id": 222332,
"author": "DCookie",
"author_id": 8670,
"author_profile": "https://Stackoverflow.com/users/8670",
"pm_score": 3,
"selected": false,
"text": "DECLARE\n CURSOR foo_cur IS \n SELECT NEEDED_FIELD WHERE condition ;\nBEGIN\n FOR foo_rec IN foo_cur LOOP\n ...\n END LOOP;\nEXCEPTION\n WHEN OTHERS THEN\n RAISE;\nEND ;\n DECLARE\nBEGIN\n FOR foo_rec IN (SELECT NEEDED_FIELD WHERE condition) LOOP\n ...\n END LOOP;\nEXCEPTION\n WHEN OTHERS THEN\n RAISE;\nEND ;\n"
},
{
"answer_id": 222347,
"author": "RussellH",
"author_id": 30000,
"author_profile": "https://Stackoverflow.com/users/30000",
"pm_score": 6,
"selected": true,
"text": "count(*) count(*) select ... into count(*) SQL>create table t (NEEDED_FIELD number, COND number);\n SQL>insert into t (NEEDED_FIELD, cond) values (1, 0);\n declare\n otherVar number;\n cnt number;\nbegin\n for i in 1 .. 50000 loop\n select count(*) into cnt from t where cond = 1;\n\n if (cnt = 1) then\n select NEEDED_FIELD INTO otherVar from t where cond = 1;\n else\n otherVar := 0;\n end if;\n end loop;\nend;\n/\n declare\n otherVar number;\nbegin\n for i in 1 .. 50000 loop\n begin\n select NEEDED_FIELD INTO otherVar from t where cond = 1;\n exception\n when no_data_found then\n otherVar := 0;\n end;\n end loop;\nend;\n/\n"
},
{
"answer_id": 222378,
"author": "RussellH",
"author_id": 30000,
"author_profile": "https://Stackoverflow.com/users/30000",
"pm_score": 2,
"selected": false,
"text": "EXCEPTION \n WHEN OTHERS THEN \n RAISE;\n"
},
{
"answer_id": 222460,
"author": "RussellH",
"author_id": 30000,
"author_profile": "https://Stackoverflow.com/users/30000",
"pm_score": 2,
"selected": false,
"text": "begin \n for i in 2 .. 10000 loop\n insert into t (NEEDED_FIELD, cond) values (i, 10);\n end loop;\nend;\n declare\n otherVar number;\n cnt number;\nbegin\n for i in 1 .. 5000 loop\n select count(*) into cnt from t where cond = 0;\n\n if (cnt = 1) then\n select NEEDED_FIELD INTO otherVar from t where cond = 0;\n else\n otherVar := 0;\n end if;\n end loop;\nend;\n/\n\nPL/SQL procedure successfully completed.\n\nElapsed: 00:00:04.34\n\ndeclare\n otherVar number;\nbegin\n for i in 1 .. 5000 loop\n begin\n select NEEDED_FIELD INTO otherVar from t where cond = 0;\n exception\n when no_data_found then\n otherVar := 0;\n end;\n end loop;\nend;\n/\n\nPL/SQL procedure successfully completed.\n\nElapsed: 00:00:02.10\n SELECT NEEDED_FIELD INTO var WHERE condition;\nEXCEPTION\nWHEN NO_DATA_FOUND....\n"
},
{
"answer_id": 222492,
"author": "RussellH",
"author_id": 30000,
"author_profile": "https://Stackoverflow.com/users/30000",
"pm_score": 0,
"selected": false,
"text": "declare\n otherVar number;\nbegin\n for i in 1 .. 5000 loop\n begin\n for foo_rec in (select NEEDED_FIELD from t where cond = 0) loop\n otherVar := foo_rec.NEEDED_FIELD;\n end loop;\n otherVar := 0;\n end;\n end loop;\nend;\n"
},
{
"answer_id": 223128,
"author": "Noah Yetter",
"author_id": 30080,
"author_profile": "https://Stackoverflow.com/users/30080",
"pm_score": 3,
"selected": false,
"text": "SELECT MAX(column)\n INTO var\n FROM table\n WHERE conditions;\n\nIF var IS NOT NULL\nTHEN ...\n"
},
{
"answer_id": 229227,
"author": "pablo",
"author_id": 16112,
"author_profile": "https://Stackoverflow.com/users/16112",
"pm_score": 1,
"selected": false,
"text": "BEGIN\n FOR rec IN (SELECT a.needed_field,b.other_field\n FROM table1 a\n LEFT OUTER JOIN table2 b\n ON a.needed_field = b.condition_field\n WHERE a.column = ???)\n LOOP\n IF rec.other_field IS NOT NULL THEN\n -- whatever processing needs to be done to other_field\n END IF;\n END LOOP;\nEND;\n"
},
{
"answer_id": 377096,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "declare\ncursor cur_name is select * from emp;\nbegin\nfor cur_rec in cur_name Loop\n dbms_output.put_line(cur_rec.ename);\nend loop;\nEnd ;\n declare\ncursor cur_name is select * from emp;\ncur_rec emp%rowtype;\nbegin\nOpen cur_name;\nLoop\nFetch cur_name into Cur_rec;\n Exit when cur_name%notfound;\n dbms_output.put_line(cur_rec.ename);\nend loop;\nClose cur_name;\nEnd ;\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27457/"
] |
221,913
|
<p>I am getting a warning when trying to include the .net 3.5 sp1 prerequisite for my setup project. The warning states Prerequisite could not found for bootstrapping.</p>
<p>Any suggestions?</p>
<p>Thanks</p>
|
[
{
"answer_id": 5556080,
"author": "Michael Eakins",
"author_id": 437301,
"author_profile": "https://Stackoverflow.com/users/437301",
"pm_score": 1,
"selected": false,
"text": "<PackageFile Name=\"TOOLS\\clwireg.exe\"/>\n<PackageFile Name=\"TOOLS\\clwireg_x64.exe\"/>\n<PackageFile Name=\"TOOLS\\clwireg_ia64.exe\"/> \n < PackageFile Name=\"dotNetFX30\\XPSEPSC-x86-en-US.exe\" 3082010A0282010100A2DB0A8DCFC2C1499BCDAA3A34AD23596BDB6CBE2122B794C8EAAEBFC6D526C232118BBCDA5D2CFB36561E152BAE8F0DDD14A36E284C7F163F41AC8D40B146880DD98194AD9706D05744765CEAF1FC0EE27F74A333CB74E5EFE361A17E03B745FFD53E12D5B0CA5E0DD07BF2B7130DFC606A2885758CB7ADBC85E817B490BEF516B6625DED11DF3AEE215B8BAF8073C345E3958977609BE7AD77C1378D33142F13DB62C9AE1AA94F9867ADD420393071E08D6746E2C61CF40D5074412FE805246A216B49B092C4B239C742A56D5C184AAB8FD78E833E780A47D8A4B28423C3E2F27B66B14A74BD26414B9C6114604E30C882F3D00B707CEE554D77D2085576810203010001"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29961/"
] |
221,919
|
<p>Is there a difference between the two examples below for beginning a Perl script? If so, when would I use one over the other?</p>
<p>example 1:</p>
<pre><code>#!/usr/bin/perl
use warnings;
</code></pre>
<p>example 2:</p>
<pre><code>#!/usr/bin/perl -w
</code></pre>
|
[
{
"answer_id": 222071,
"author": "friedo",
"author_id": 20745,
"author_profile": "https://Stackoverflow.com/users/20745",
"pm_score": 4,
"selected": false,
"text": "-w use warnings no warnings -w"
},
{
"answer_id": 227553,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "use strict;\nuse warnings FATAL => 'all', NONFATAL => 'exec';\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6406/"
] |
221,921
|
<p>I'm looking for the string <code>foo=</code> in text files in a directory tree. It's on a common Linux machine, I have bash shell:</p>
<pre><code>grep -ircl "foo=" *
</code></pre>
<p>In the directories are also many binary files which match <code>"foo="</code>. As these results are not relevant and slow down the search, I want grep to skip searching these files (mostly JPEG and PNG images). How would I do that?</p>
<p>I know there are the <code>--exclude=PATTERN</code> and <code>--include=PATTERN</code> options, but what is the pattern format? The man page of grep says:</p>
<pre><code>--include=PATTERN Recurse in directories only searching file matching PATTERN.
--exclude=PATTERN Recurse in directories skip file matching PATTERN.
</code></pre>
<p>Searching on <em>grep include</em>, <em>grep include exclude</em>, <em>grep exclude</em> and variants did not find anything relevant</p>
<p>If there's a better way of grepping only in certain files, I'm all for it; moving the offending files is not an option. I can't search only certain directories (the directory structure is a big mess, with everything everywhere). Also, I can't install anything, so I have to do with common tools (like <em>grep</em> or the suggested <em>find</em>).</p>
|
[
{
"answer_id": 221929,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 11,
"selected": true,
"text": "grep pattern -r --include=\\*.cpp --include=\\*.h rootdir\n --exclude --include=\"*.cpp\" grep pattern -r --include=foo.cpp --include=bar.cpp rootdir foo.cpp bar.cpp grep pattern -r --include=\\*.{cpp,h} rootdir\n .cpp .h rootdir"
},
{
"answer_id": 221936,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 3,
"selected": false,
"text": "grep -rn \"foo=\" . | grep -v \"Binary file\"\n"
},
{
"answer_id": 221940,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 2,
"selected": false,
"text": "find . -not -name '*.png' -o -type f -print | xargs grep -icl \"foo=\"\n find . -not -name '*.png' -o -type f -print | xargs wc -l\n find . -not -name '*.png' -o -type f -print | xargs rm\n -print0 xargs -0"
},
{
"answer_id": 222021,
"author": "rmeador",
"author_id": 10861,
"author_profile": "https://Stackoverflow.com/users/10861",
"pm_score": 8,
"selected": false,
"text": "-I grep -rI --exclude-dir=\"\\.svn\" \"pattern\" *\n"
},
{
"answer_id": 222044,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 6,
"selected": false,
"text": "grep -ircl --exclude=*.{png,jpg} \"foo=\" *\n ack -icl \"foo=\"\n ack -icl --cpp \"foo=\"\n"
},
{
"answer_id": 264611,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "du -ha | grep -i -o \"\\./.*\" | grep -v \"\\.svn\\|another_file\\|another_folder\" | xargs grep -i -n \"$1\"\n"
},
{
"answer_id": 375629,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "grep -Ir --exclude=\"*\\.svn*\" \"pattern\" *\n"
},
{
"answer_id": 512703,
"author": "Corey",
"author_id": 62548,
"author_profile": "https://Stackoverflow.com/users/62548",
"pm_score": 5,
"selected": false,
"text": "--exclude-dir grep -rI --exclude-dir=\\.svn PATTERN .\n GREP_OPTIONS=\"--exclude-dir=\\.svn\""
},
{
"answer_id": 721012,
"author": "mjs",
"author_id": 11543,
"author_profile": "https://Stackoverflow.com/users/11543",
"pm_score": 1,
"selected": false,
"text": "--binary-files=without-match grep -I grep"
},
{
"answer_id": 2559609,
"author": "deric",
"author_id": 284349,
"author_profile": "https://Stackoverflow.com/users/284349",
"pm_score": 4,
"selected": false,
"text": "export GREP_OPTIONS=\"--exclude=\\*.svn\\*\"\n"
},
{
"answer_id": 3729661,
"author": "lathomas64",
"author_id": 387191,
"author_profile": "https://Stackoverflow.com/users/387191",
"pm_score": -1,
"selected": false,
"text": "grep -Ri \"pattern\" * | awk '{if($1 != \"Binary\") print $0}'\n"
},
{
"answer_id": 4141430,
"author": "suhas tawade",
"author_id": 502774,
"author_profile": "https://Stackoverflow.com/users/502774",
"pm_score": 2,
"selected": false,
"text": "grep --exclude=\"*\\.svn*\" -rn \"foo=\" * | grep -v Binary | grep -v tags\n"
},
{
"answer_id": 4150217,
"author": "P Stack",
"author_id": 503912,
"author_profile": "https://Stackoverflow.com/users/503912",
"pm_score": -1,
"selected": false,
"text": "--F --F double-minus-F #> grep -i --exclude-dir=\"\\-\\-F\" \"pattern\" *"
},
{
"answer_id": 8127815,
"author": "OnlineCop",
"author_id": 801098,
"author_profile": "https://Stackoverflow.com/users/801098",
"pm_score": 3,
"selected": false,
"text": "find -prune find [directory] \\\n -name \"pattern_to_exclude\" -prune \\\n -o -name \"another_pattern_to_exclude\" -prune \\\n -o -name \"pattern_to_INCLUDE\" -print0 \\\n| xargs -0 -I FILENAME grep -IR \"pattern\" FILENAME\n . \"*.png\" \"*.gif\" \"*.jpg\" -o -name \"...\" -prune -o find -print -print0 *.gif *.png -o -print0 xargs FILENAME grep -IR \"pattern\" FILENAME xargs find find . \\\n -name \"*.png\" -prune \\\n -o -name \"*.gif\" -prune \\\n -o -name \"*.svn\" -prune \\\n -o -print0 | xargs -0 -I FILES grep -IR \"foo=\" FILES\n"
},
{
"answer_id": 9980986,
"author": "Keith Knauber",
"author_id": 1001801,
"author_profile": "https://Stackoverflow.com/users/1001801",
"pm_score": 1,
"selected": false,
"text": "alias gisrc 'grep -I -r -i --exclude=\"*\\.svn*\" --include=\"*\\.\"{mm,m,h,cc,c} \\!* *'\n"
},
{
"answer_id": 13965553,
"author": "Rushabh Mehta",
"author_id": 407404,
"author_profile": "https://Stackoverflow.com/users/407404",
"pm_score": 5,
"selected": false,
"text": "grep \"z-index\" . --include=*.js --exclude=*js/lib/* --exclude=*.min.js\n"
},
{
"answer_id": 26807953,
"author": "aesede",
"author_id": 591257,
"author_profile": "https://Stackoverflow.com/users/591257",
"pm_score": 3,
"selected": false,
"text": "grep \"term\" -Hnir --include \\*.php --exclude-dir \"*excluded_dir*\"\n --include --exclude include-dir --exclude-dir"
},
{
"answer_id": 39070634,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 2,
"selected": false,
"text": "grep \"foo\" *.{html,txt}\n grep \"foo\" */*.{html,txt}\n grep \"foo\" */*/*.{html,txt}\n"
},
{
"answer_id": 49837768,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 2,
"selected": false,
"text": "ripgrep rg \"some_pattern\"\n .gitignore -g --glob .gitignore man rg brew install ripgrep"
},
{
"answer_id": 49837791,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 3,
"selected": false,
"text": "git grep git grep .gitignore --no-index git grep --no-index \"some_pattern\"\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19746/"
] |
221,925
|
<p>What is the prefered method for creating a byte array from an input stream? </p>
<p>Here is my current solution with .NET 3.5. </p>
<pre><code>Stream s;
byte[] b;
using (BinaryReader br = new BinaryReader(s))
{
b = br.ReadBytes((int)s.Length);
}
</code></pre>
<p>Is it still a better idea to read and write chunks of the stream?</p>
|
[
{
"answer_id": 221941,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 11,
"selected": true,
"text": "s.Length public static byte[] ReadFully(Stream input)\n{\n byte[] buffer = new byte[16*1024];\n using (MemoryStream ms = new MemoryStream())\n {\n int read;\n while ((read = input.Read(buffer, 0, buffer.Length)) > 0)\n {\n ms.Write(buffer, 0, read);\n }\n return ms.ToArray();\n }\n}\n Stream.CopyTo MemoryStream stream.CopyTo(ms) ms.ToArray() Stream.Read BinaryReader.Read MemoryStream MemoryStream MemoryStream MemoryStream.GetBuffer"
},
{
"answer_id": 2630539,
"author": "Fernando Neira",
"author_id": 315601,
"author_profile": "https://Stackoverflow.com/users/315601",
"pm_score": 7,
"selected": false,
"text": "memorystream.ToArray() MemoryStream public static byte[] StreamToByteArray(Stream stream)\n{\n if (stream is MemoryStream)\n {\n return ((MemoryStream)stream).ToArray(); \n }\n else\n {\n // Jon Skeet's accepted answer \n return ReadFully(stream);\n }\n}\n"
},
{
"answer_id": 4978315,
"author": "Sandip Patel",
"author_id": 614236,
"author_profile": "https://Stackoverflow.com/users/614236",
"pm_score": 6,
"selected": false,
"text": "MemoryStream ms = new MemoryStream();\nfile.PostedFile.InputStream.CopyTo(ms);\nvar byts = ms.ToArray();\nms.Dispose();\n"
},
{
"answer_id": 6181941,
"author": "Brian Hinchey",
"author_id": 62278,
"author_profile": "https://Stackoverflow.com/users/62278",
"pm_score": 3,
"selected": false,
"text": "Stream s;\nbyte[] b;\n\nif (s.Length > int.MaxValue) {\n throw new Exception(\"This stream is larger than the conversion algorithm can currently handle.\");\n}\n\nusing (var br = new BinaryReader(s)) {\n b = br.ReadBytes((int)s.Length);\n}\n"
},
{
"answer_id": 6586039,
"author": "Nathan Phillips",
"author_id": 740378,
"author_profile": "https://Stackoverflow.com/users/740378",
"pm_score": 10,
"selected": false,
"text": "CopyTo CopyTo MemoryStream public static byte[] ReadFully(Stream input)\n{\n using (MemoryStream ms = new MemoryStream())\n {\n input.CopyTo(ms);\n return ms.ToArray();\n }\n}\n"
},
{
"answer_id": 11546618,
"author": "Michal T",
"author_id": 1535583,
"author_profile": "https://Stackoverflow.com/users/1535583",
"pm_score": 4,
"selected": false,
"text": "namespace Foo\n{\n public static class Extensions\n {\n public static byte[] ToByteArray(this Stream stream)\n {\n using (stream)\n {\n using (MemoryStream memStream = new MemoryStream())\n {\n stream.CopyTo(memStream);\n return memStream.ToArray();\n }\n }\n }\n }\n}\n byte[] arr = someStream.ToByteArray()\n"
},
{
"answer_id": 11730556,
"author": "NothinRandom",
"author_id": 1449633,
"author_profile": "https://Stackoverflow.com/users/1449633",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.IO;\n\n private static byte[] ReadFully(string input)\n {\n FileStream sourceFile = new FileStream(input, FileMode.Open); //Open streamer\n BinaryReader binReader = new BinaryReader(sourceFile);\n byte[] output = new byte[sourceFile.Length]; //create byte array of size file\n for (long i = 0; i < sourceFile.Length; i++)\n output[i] = binReader.ReadByte(); //read until done\n sourceFile.Close(); //dispose streamer\n binReader.Close(); //dispose reader\n return output;\n }'\n"
},
{
"answer_id": 14940312,
"author": "Mr. Pumpkin",
"author_id": 524605,
"author_profile": "https://Stackoverflow.com/users/524605",
"pm_score": 6,
"selected": false,
"text": "public static class StreamHelpers\n{\n public static byte[] ReadFully(this Stream input)\n {\n using (MemoryStream ms = new MemoryStream())\n {\n input.CopyTo(ms);\n return ms.ToArray();\n }\n }\n}\n"
},
{
"answer_id": 42652943,
"author": "Abba",
"author_id": 4904299,
"author_profile": "https://Stackoverflow.com/users/4904299",
"pm_score": -1,
"selected": false,
"text": "byte [] byteArr= ((MemoryStream)localStream).ToArray();\n"
},
{
"answer_id": 44026626,
"author": "önder çalbay",
"author_id": 4748913,
"author_profile": "https://Stackoverflow.com/users/4748913",
"pm_score": 2,
"selected": false,
"text": "public static byte[] ToByteArray(this Stream stream)\n{\n if (stream is MemoryStream)\n return ((MemoryStream)stream).ToArray();\n else\n {\n using MemoryStream ms = new();\n stream.CopyTo(ms);\n return ms.ToArray();\n } \n}\n"
},
{
"answer_id": 45343277,
"author": "Egemen Çiftci",
"author_id": 3480261,
"author_profile": "https://Stackoverflow.com/users/3480261",
"pm_score": 2,
"selected": false,
"text": "public static class StreamExtensions\n{\n public static byte[] ToByteArray(this Stream stream)\n {\n var bytes = new List<byte>();\n\n int b;\n\n // -1 is a special value that mark the end of the stream\n while ((b = stream.ReadByte()) != -1)\n bytes.Add((byte)b);\n\n return bytes.ToArray();\n }\n}\n"
},
{
"answer_id": 51292831,
"author": "Nilesh Kumar",
"author_id": 9927177,
"author_profile": "https://Stackoverflow.com/users/9927177",
"pm_score": 4,
"selected": false,
"text": "MemoryStream ms = (MemoryStream)dataInStream;\nbyte[] imageBytes = ms.ToArray();\n"
},
{
"answer_id": 52426274,
"author": "Kalyn Padayachee",
"author_id": 8990343,
"author_profile": "https://Stackoverflow.com/users/8990343",
"pm_score": 2,
"selected": false,
"text": "public static class StreamHelpers\n{\n public static byte[] ReadFully(this Stream input)\n {\n using (MemoryStream ms = new MemoryStream())\n {\n input.CopyTo(ms);\n return ms.ToArray();\n }\n }\n}\n"
},
{
"answer_id": 52864715,
"author": "SensorSmith",
"author_id": 3610458,
"author_profile": "https://Stackoverflow.com/users/3610458",
"pm_score": 3,
"selected": false,
"text": "public static class StreamHelpers\n{\n public static byte[] ReadFully(this Stream input)\n {\n var ms = new MemoryStream();\n input.CopyTo(ms);\n return ms.ToArray();\n }\n}\n"
},
{
"answer_id": 54121303,
"author": "Fred.S",
"author_id": 1495119,
"author_profile": "https://Stackoverflow.com/users/1495119",
"pm_score": 2,
"selected": false,
"text": " public static byte[] StreamToByteArray(Stream input)\n {\n if (input == null)\n return null;\n byte[] buffer = new byte[16 * 1024];\n input.Position = 0;\n using (MemoryStream ms = new MemoryStream())\n {\n int read;\n while ((read = input.Read(buffer, 0, buffer.Length)) > 0)\n {\n ms.Write(buffer, 0, read);\n }\n byte[] temp = ms.ToArray();\n\n return temp;\n }\n }\n"
},
{
"answer_id": 54184278,
"author": "Wieslaw Olborski",
"author_id": 3098913,
"author_profile": "https://Stackoverflow.com/users/3098913",
"pm_score": 2,
"selected": false,
"text": "using RestSharp.Extensions;\nvar byteArray = inputStream.ReadAsBytes();\n"
},
{
"answer_id": 69299328,
"author": "adsamcik",
"author_id": 2422905,
"author_profile": "https://Stackoverflow.com/users/2422905",
"pm_score": 2,
"selected": false,
"text": "MemoryStream.ToArray NotSupportedException public static async Task<byte[]> ToArrayAsync(this Stream stream)\n{\n var array = new byte[stream.Length];\n await stream.ReadAsync(array, 0, (int)stream.Length);\n return array;\n}\n /// <summary>\n/// Converts stream to byte array.\n/// </summary>\n/// <param name=\"stream\">Stream</param>\n/// <returns>Binary data from stream in an array</returns>\npublic static async Task<byte[]> ToArrayAsync(this Stream stream)\n{\n if (!stream.CanRead)\n {\n throw new AccessViolationException(\"Stream cannot be read\");\n }\n\n if (stream.CanSeek)\n {\n return await ToArrayAsyncDirect(stream);\n }\n else\n {\n return await ToArrayAsyncGeneral(stream);\n }\n}\n\nprivate static async Task<byte[]> ToArrayAsyncGeneral(Stream stream)\n{\n using (var memoryStream = new MemoryStream())\n {\n await stream.CopyToAsync(memoryStream);\n return memoryStream.ToArray();\n }\n}\n\nprivate static async Task<byte[]> ToArrayAsyncDirect(Stream stream)\n{\n var array = new byte[stream.Length];\n await stream.ReadAsync(array, 0, (int)stream.Length);\n return array;\n}\n"
},
{
"answer_id": 71655362,
"author": "Kirk Woll",
"author_id": 189950,
"author_profile": "https://Stackoverflow.com/users/189950",
"pm_score": 2,
"selected": false,
"text": "public static async Task<byte[]> ReadAsByteArrayAsync(this Stream source)\n{\n // Optimization\n if (source is MemoryStream memorySource)\n return memorySource.ToArray();\n\n using var memoryStream = new MemoryStream();\n await source.CopyToAsync(memoryStream);\n return memoryStream.ToArray();\n}\n ToArray"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45/"
] |
221,930
|
<p>I have a master page that contains an ASP.NET server side Menu control (System.Web.UI.WebControls.Menu)</p>
<p>I <em>am</em> using the CSSFriendly adapters from here</p>
<p><a href="http://www.asp.net/CSSAdapters/Menu.aspx" rel="noreferrer">http://www.asp.net/CSSAdapters/Menu.aspx</a></p>
<p>and they do make the rendered HTML much cleaner however I am still getting inline styles output into the HEAD element in the HTML like this</p>
<pre><code><style type="text/css">
.ctl00_SiteHeader1_TabBar1_Menu1_0 { background-color:white;visibility:hidden;display:none;position:absolute;left:0px;top:0px; }
.ctl00_SiteHeader1_TabBar1_Menu1_1 { text-decoration:none; }
.ctl00_SiteHeader1_TabBar1_Menu1_2 { }
.ctl00_LeftColumnContent_LeftHandNavigator1_Menu1_0 { text-decoration:none; }
</style>
</head>
<body>
</code></pre>
<p>I thik these styles are being generated by ASP.NET, I don't think I need them as I am using the CSSAdapters so is there any way of stopping them from being generated?</p>
<p>Derek</p>
|
[
{
"answer_id": 9429489,
"author": "Ignacio Calvo",
"author_id": 429487,
"author_profile": "https://Stackoverflow.com/users/429487",
"pm_score": 2,
"selected": false,
"text": "IncludeStyleBlock <style> style=\"float:left\" float: none !important"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28584/"
] |
221,938
|
<p>I want to provide silverlight app to my customer while hosting the app at my own site for streamlined maintenance.</p>
<ul>
<li>my Silverlight .xap is hosted in, let say, domain <em>me-supplier.com</em></li>
<li>i want to embed it in, let say, domain <em>my-customer.com</em></li>
</ul>
<p>It works perfectly for <em><a href="http://my-customer.com" rel="nofollow noreferrer">http://my-customer.com</a></em>, not for <strong><em>https</strong>://my-customer.com</em> </p>
<ul>
<li>i have added the (<em>me-supplier.com</em> hosted) cross domain silverlight policy file to allow <em>my-customer.com</em></li>
<li>i have configured the mime types for .xap</li>
<li>the silverlight app needs html dom access so the iframe approach is not viable i believe.</li>
</ul>
<p>this works for javascript code, so why not for silverlight ? any idea, workaround ?</p>
|
[
{
"answer_id": 9429489,
"author": "Ignacio Calvo",
"author_id": 429487,
"author_profile": "https://Stackoverflow.com/users/429487",
"pm_score": 2,
"selected": false,
"text": "IncludeStyleBlock <style> style=\"float:left\" float: none !important"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29952/"
] |
221,950
|
<p>This <a href="http://themechanicalbride.blogspot.com/2008/04/using-operators-with-generics.html" rel="nofollow noreferrer">article</a> describes a way, in C#, to allow the addition of arbitrary value types which have a + operator defined for them. In essence it allows the following code:</p>
<pre><code>public T Add(T val1, T val2)
{
return val1 + val2;
}
</code></pre>
<p>This code does not compile as there is no guarantee that the T type has a definition for the '+' operator, but the effect is achieved with code like this:</p>
<pre><code>public T Add(T val1, T val2)
{
//Num<T> defines a '+' operation which returns a value of type T
return (new Num<T>(val1) + new Num<T>(val2));
}
</code></pre>
<p>Follow the link to see how the Num class achieves this. Anyways, on to the question. Is there any way to achieve the same effect in C or C++? For the curious, the problem I'm trying to solve is to allow a CUDA kernel to be more flexible/general by allowing it to operate on more types.</p>
<p><strong>Update:</strong> For .NET, Marc Gravell has made a <a href="http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html" rel="nofollow noreferrer">utility library</a> which solves the operator problem very elegantly.</p>
|
[
{
"answer_id": 221961,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 5,
"selected": true,
"text": "template < class T >\nT add(T const & val1, T const & val2)\n{\n return val1 + val2;\n}\n"
},
{
"answer_id": 221962,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "\ntemplate <typename T>\nT Add(T val1, T val2)\n{\n return val1 + val2;\n}"
},
{
"answer_id": 221965,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 0,
"selected": false,
"text": "template<typename T> \nT add(T x, T y)\n{ \n return x + y;\n}\n"
},
{
"answer_id": 222000,
"author": "lefticus",
"author_id": 29975,
"author_profile": "https://Stackoverflow.com/users/29975",
"pm_score": 1,
"selected": false,
"text": "#define ADD(A,B) (A+B)\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
221,976
|
<p>I am creating an application in java which will be the part of an external application. My application contains a viewport which shows some polygons and stuff like that. The external application needs to get the image of the viewport in gif format. For that it calls a method in an interface (implemented by my application) and my application returns the image. The external application needs to store the image in database (or something related to it which I dont need to worry about).</p>
<p>My question is:- What should be the data container type of the image when my application send it to the external application? I mean what should be the return type of the method?
Currently my gif encoder class returns a byte array. Is there any other 'better' option?</p>
|
[
{
"answer_id": 222010,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": true,
"text": "OutputStream ByteArrayOutputStream"
},
{
"answer_id": 417778,
"author": "asalamon74",
"author_id": 21348,
"author_profile": "https://Stackoverflow.com/users/21348",
"pm_score": 0,
"selected": false,
"text": "java.awt.Image java.awt.Image OutputStream"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22550/"
] |
221,984
|
<p>I'm writing an Excel Addin using COM Interop from .net. I have a command that pops up a dialog, and from the dialog I do some work like collecting data from the used range of several sheets. The problem is that if a cell is in edit mode, some of the calls that I need to make will throw exceptions. I would like a way of determining before-hand that Excel is in edit mode, so that I can warn the user to finish editing the cell first.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 25057820,
"author": "SZL",
"author_id": 2278037,
"author_profile": "https://Stackoverflow.com/users/2278037",
"pm_score": 3,
"selected": false,
"text": " Function IsInEditMode(ByRef exapp As Excel.Application) As Boolean\n If exapp.Interactive = False Then\n Return False\n Else\n Try\n exapp.Interactive = False\n exapp.Interactive = True\n\n Return False\n Catch\n Return True\n End Try\n End If\n End Function\n"
},
{
"answer_id": 45492503,
"author": "TheAtomicOption",
"author_id": 3626160,
"author_profile": "https://Stackoverflow.com/users/3626160",
"pm_score": 2,
"selected": false,
"text": " bool IsInEditMode(ref Microsoft.Office.Interop.Excel.Application exapp)\n {\n if (exapp.Interactive == false)\n {\n return false;\n }\n else\n {\n try\n {\n exapp.Interactive = false;\n exapp.Interactive = true;\n return false;\n }\n\n catch\n {\n return true;\n }\n }\n\n }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/221984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1727/"
] |
222,017
|
<p>I'm looking for (simple) examples of problems for which JMS is a good solution, and also reasons why JMS is a good solution in these cases. In the past I've simply used the database as a means of passing messages from A to B when the message cannot necessarily be processed by B immediately.</p>
<p>A hypothetical example of such a system is where all newly registered users should be sent a welcome e-mail within 24 hours of registration. For the sake of argument, assume the DB does not record the time when each user registered, but instead a reference (foreign key) to each new user is stored in the pending_email table. The e-mail sender job runs once every 24 hours, sends an e-mail to all the users in this table, then deletes all the pending_email records.</p>
<p>This seems like the kind of problem for which JMS should be used, but it's not clear to me what benefit JMS would have over the approach I've described. One advantage of the DB approach is that the messages are persistent. I understand that JMS message queues can also be persisted, but in that case there seems to be little difference between JMS and the "database as message queue" approach I've described?</p>
<p>What am I missing?
- Don</p>
|
[
{
"answer_id": 19044855,
"author": "Aniket Thakur",
"author_id": 2396539,
"author_profile": "https://Stackoverflow.com/users/2396539",
"pm_score": 2,
"selected": false,
"text": "what is JMS good for?"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
222,018
|
<p>How to format numbers in JavaScript?</p>
<hr>
<ul>
<li><a href="https://stackoverflow.com/questions/51564/javascript-culture-sensitive-currency-formatting">JavaScript culture sensitive currency formatting</a></li>
</ul>
|
[
{
"answer_id": 222038,
"author": "SaaS Developer",
"author_id": 7215,
"author_profile": "https://Stackoverflow.com/users/7215",
"pm_score": 5,
"selected": true,
"text": "var num = 10;\nvar result = num.toFixed(2); // result will equal 10.00\n\nnum = 930.9805;\nresult = num.toFixed(3); // result will equal 930.981\n\nnum = 500.2349;\nresult = num.toPrecision(4); // result will equal 500.2\n\nnum = 5000.2349;\nresult = num.toPrecision(4); // result will equal 5000\n\nnum = 555.55;\nresult = num.toPrecision(2); // result will equal 5.6e+2\n"
},
{
"answer_id": 8462816,
"author": "Rodrigo",
"author_id": 1086511,
"author_profile": "https://Stackoverflow.com/users/1086511",
"pm_score": 1,
"selected": false,
"text": "function formatFloat(num,casasDec,sepDecimal,sepMilhar) {\n if (num < 0)\n {\n num = -num;\n sinal = -1;\n } else\n sinal = 1;\n var resposta = \"\";\n var part = \"\";\n if (num != Math.floor(num)) // decimal values present\n {\n part = Math.round((num-Math.floor(num))*Math.pow(10,casasDec)).toString(); // transforms decimal part into integer (rounded)\n while (part.length < casasDec)\n part = '0'+part;\n if (casasDec > 0)\n {\n resposta = sepDecimal+part;\n num = Math.floor(num);\n } else\n num = Math.round(num);\n } // end of decimal part\n while (num > 0) // integer part\n {\n part = (num - Math.floor(num/1000)*1000).toString(); // part = three less significant digits\n num = Math.floor(num/1000);\n if (num > 0)\n while (part.length < 3) // 123.023.123 if sepMilhar = '.'\n part = '0'+part; // 023\n resposta = part+resposta;\n if (num > 0)\n resposta = sepMilhar+resposta;\n }\n if (sinal < 0)\n resposta = '-'+resposta;\n return resposta;\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
222,019
|
<p>How do i take advantage of MySQL's ability to cache prepared statements?
One reason to use prepared statements is that there is no need to send the prepared statement itself multiple times if the same prepared statement is to be used again. </p>
<pre><code>Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb" +
"?cachePrepStmts=true", "user", "pass");
for (int i = 0; i < 5; i++) {
PreparedStatement ps = conn.prepareStatement("select * from MYTABLE where id=?");
ps.setInt(1, 1);
ps.execute();
}
conn.close()
</code></pre>
<p>When running the above Java example I see 5 pairs of Prepare and Execute commands in the mysqld log file. Moving the ps assignment outside of the loop results in a single Prepare and 5 Execute commands of course. The connection parameter "cachePrepStmts=true" doesn't seem to make any difference here.<br>
When running a similar program using Spring and Hibernate the number of Prepare commands sent (1 or 5) depends on whether the cachePrepStmts connection parameter is enabled. How does Hibernate execute prepared statements to take advantage of the cachePrepStmts setting? Is it possible to mimic this using pure JDBC?<br>
I was running this on MySQL Server 4.1.22 and mysql-connector-java-5.0.4.jar</p>
|
[
{
"answer_id": 374372,
"author": "kosoant",
"author_id": 15114,
"author_profile": "https://Stackoverflow.com/users/15114",
"pm_score": 2,
"selected": false,
"text": "Connection conn = DatabaseUtil.getConnection();\nPreparedStatement stmtUpdate = conn.prepareStatement(\"UPDATE foo SET bar=? WHERE id = ?\");\nfor(int id=0; id<10; id++){\n stmtUpdate.setString(1, \"baz\");\n stmtUpdate.setInt(2, id);\n int rows = stmtUpdate.executeUpdate();\n // Clear parameters for reusing the preparedStatement\n stmtUpdate.clearParameters();\n}\nconn.close();\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11411/"
] |
222,028
|
<p>Lots of frameworks let me expose an ejb as a webservice. </p>
<p>But then 2 months after publishing the initial service I need to change the ejb or any part of its interface. I still have clients that need to access the old interface, so I obviously need to have 2 webservices with different signatures.</p>
<p>Anyone have any suggestions on how I can do this, preferably letting the framework do the grunt work of creating wrappers and copying logic (unless there's an even smarter way).</p>
<p>I can choose webservice framework on basis of this, so suggestions are welcome.</p>
<p>Edit: I know my change is going to break compatibility,and I am fully aware that I will need two services with different namespaces at the same time. But how can I do it in a simple manner ?</p>
|
[
{
"answer_id": 265013,
"author": "Kariem",
"author_id": 12039,
"author_profile": "https://Stackoverflow.com/users/12039",
"pm_score": 4,
"selected": true,
"text": "@WebService\n@SOAPBinding(style = Style.RPC)\npublic interface ILegacyService extends IOtherLegacyService {\n // the interface methods\n ...\n}\n\n@Stateless\n@Local(ILegacyService.class)\n@WebService(endpointInterface = \"...ILegacyService\", ...)\npublic class LegacyServiceImpl implements ILegacyService {\n // implementation of ILegacyService\n}\n ILegacyService LegacyServiceImpl"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
222,029
|
<p>the WPF Popup control is nice, but somewhat limited in my opinion. is there a way to "drag" a popup around when it is opened (like with the DragMove() method of windows)?</p>
<p>can this be done without big problems or do i have to write a substitute for the popup class myself?
thanks</p>
|
[
{
"answer_id": 222219,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 4,
"selected": false,
"text": "<Popup x:Name=\"pop\" IsOpen=\"True\" Height=\"200\" Placement=\"AbsolutePoint\" Width=\"200\">\n <Rectangle Stretch=\"Fill\" Fill=\"Red\"/> \n</Popup>\n pop.MouseMove += new MouseEventHandler(pop_MouseMove);\n\n void pop_MouseMove(object sender, MouseEventArgs e)\n {\n if (e.LeftButton == MouseButtonState.Pressed)\n {\n pop.PlacementRectangle = new Rect(new Point(e.GetPosition(this).X,\n e.GetPosition(this).Y),new Point(200,200));\n\n }\n }\n"
},
{
"answer_id": 5843788,
"author": "Jonatas",
"author_id": 722886,
"author_profile": "https://Stackoverflow.com/users/722886",
"pm_score": 0,
"selected": false,
"text": "Private Point startPoint;\n\n private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n\n startPoint = e.GetPosition(null);\n }\nprivate void Window_MouseMove(object sender, MouseEventArgs e)\n {\n if (e.LeftButton == MouseButtonState.Pressed)\n {\n Point relative = e.GetPosition(null);\n Point AbsolutePos = new Point(relative.X + this.Left, relative.Y + this.Top);\n this.Top = AbsolutePos.Y - startPoint.Y;\n this.Left = AbsolutePos.X - startPoint.X;\n }\n }\n"
},
{
"answer_id": 8170666,
"author": "jacob",
"author_id": 1052229,
"author_profile": "https://Stackoverflow.com/users/1052229",
"pm_score": 5,
"selected": true,
"text": "<Popup x:Class=\"PopupTest.DraggablePopup\" ...>\n <Canvas x:Name=\"ContentCanvas\">\n\n </Canvas>\n</Popup>\n public partial class DraggablePopup : Popup \n{\n public DraggablePopup()\n {\n var thumb = new Thumb\n {\n Width = 0,\n Height = 0,\n };\n ContentCanvas.Children.Add(thumb);\n\n MouseDown += (sender, e) =>\n {\n thumb.RaiseEvent(e);\n };\n\n thumb.DragDelta += (sender, e) =>\n {\n HorizontalOffset += e.HorizontalChange;\n VerticalOffset += e.VerticalChange;\n };\n }\n}\n"
},
{
"answer_id": 8450024,
"author": "Leon",
"author_id": 446725,
"author_profile": "https://Stackoverflow.com/users/446725",
"pm_score": 2,
"selected": false,
"text": "Popup.CaptureMouse() Popup.Child.CaptureMouse() Popup.Child Popup.Child.MouseMove Popup.Child.LostCapture"
},
{
"answer_id": 54677782,
"author": "Gregory A. Owen",
"author_id": 4484284,
"author_profile": "https://Stackoverflow.com/users/4484284",
"pm_score": 2,
"selected": false,
"text": " [ContentProperty(\"Child\")]\n [DefaultEvent(\"Opened\")]\n [DefaultProperty(\"Child\")]\n [Localizability(LocalizationCategory.None)]\n public class DraggablePopup : Popup\n {\n public DraggablePopup()\n {\n MouseDown += (sender, e) =>\n {\n Thumb.RaiseEvent(e);\n };\n\n Thumb.DragDelta += (sender, e) =>\n {\n HorizontalOffset += e.HorizontalChange;\n VerticalOffset += e.VerticalChange;\n };\n }\n\n /// <summary>\n /// The original child added via Xaml\n /// </summary>\n public UIElement TrueChild { get; private set; }\n\n public Thumb Thumb { get; private set; } = new Thumb\n {\n Width = 0,\n Height = 0,\n };\n\n protected override void OnInitialized(EventArgs e)\n {\n base.OnInitialized(e);\n\n TrueChild = Child;\n\n var surrogateChild = new StackPanel();\n\n RemoveLogicalChild(TrueChild);\n\n surrogateChild.Children.Add(Thumb);\n surrogateChild.Children.Add(TrueChild);\n\n AddLogicalChild(surrogateChild);\n Child = surrogateChild;\n }\n }\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20227/"
] |
222,030
|
<p>How can I create 7-Zip archives from my C# console application? I need to be able to extract the archives using the regular, widely available <a href="http://www.7-zip.org/" rel="noreferrer">7-Zip</a> program.</p>
<hr>
<h2>Here are my results with the examples provided as answers to this question</h2>
<ul>
<li>"Shelling out" to 7z.exe - this is the simplest and most effective approach, and I can confirm that <strong>it works nicely</strong>. As <a href="https://stackoverflow.com/questions/222030/how-do-i-create-7-zip-archives-with-net#222047">workmad3 mentions</a>, I just need to guarantee that 7z.exe is installed on all target machines, which is something I can guarantee.</li>
<li><a href="http://www.eggheadcafe.com/tutorials/aspnet/064b41e4-60bc-4d35-9136-368603bcc27a/7zip-lzma-inmemory-com.aspx" rel="noreferrer">7Zip in memory compression</a> - this refers to compressing cookies "in-memory" before sending to the client; this method seems somewhat promising. The wrapper methods (wrapping the <a href="http://www.7-zip.org/sdk.html" rel="noreferrer">LZMA SDK</a>) return type <code>byte[]</code>. When I write the <code>byte[]</code> array to a file, I can't extract it using 7-Zip (<code>File.7z is not supported archive</code>).</li>
<li><a href="http://www.codeplex.com/7zsharp" rel="noreferrer">7zSharp</a> Wrapper (found on CodePlex) - this wraps the 7z exe/<a href="http://www.7-zip.org/sdk.html" rel="noreferrer">LZMA SDK</a>. I referenced the project from my app, and it successfully created some archive files, but I was unable to extract the files using the regular 7-Zip program (<code>File.7z is not supported archive</code>).</li>
<li><a href="http://www.7-zip.org/sdk.html" rel="noreferrer">7Zip SDK aka LZMA SDK</a> - I guess I'm not smart enough to figure out how to use this (which is why I posted here)... Any working code examples that demonstrate creating a 7zip archive that is able to be extracted by the regular 7zip program?</li>
<li><a href="http://www.codeproject.com/KB/DLL/cs_interface_7zip.aspx" rel="noreferrer">CodeProject C# (.NET) Interface for 7-Zip Archive DLLs</a> - only supports extracting from 7zip archives... I need to create them!</li>
<li><a href="http://sharpdevelop.net/OpenSource/SharpZipLib/Default.aspx" rel="noreferrer">SharpZipLib</a> - According to their <a href="http://wiki.sharpdevelop.net/SharpZipLib_FAQ.ashx" rel="noreferrer">FAQ</a>, SharpZipLib doesn't support 7zip.</li>
</ul>
|
[
{
"answer_id": 367502,
"author": "WOPR",
"author_id": 46255,
"author_profile": "https://Stackoverflow.com/users/46255",
"pm_score": 3,
"selected": false,
"text": "using SevenZip.Compression.LZMA;\nprivate static void CompressFileLZMA(string inFile, string outFile)\n{\n SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();\n\n using (FileStream input = new FileStream(inFile, FileMode.Open))\n {\n using (FileStream output = new FileStream(outFile, FileMode.Create))\n {\n coder.Code(input, output, -1, -1, null);\n output.Flush();\n }\n }\n}\n"
},
{
"answer_id": 8775927,
"author": "Orwellophile",
"author_id": 912236,
"author_profile": "https://Stackoverflow.com/users/912236",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing SevenZip.Compression.LZMA;\nusing System.IO;\nusing SevenZip;\n\nnamespace VHD_Director\n{\n class My7Zip\n {\n public static void CompressFileLZMA(string inFile, string outFile)\n {\n Int32 dictionary = 1 << 23;\n Int32 posStateBits = 2;\n Int32 litContextBits = 3; // for normal files\n // UInt32 litContextBits = 0; // for 32-bit data\n Int32 litPosBits = 0;\n // UInt32 litPosBits = 2; // for 32-bit data\n Int32 algorithm = 2;\n Int32 numFastBytes = 128;\n\n string mf = \"bt4\";\n bool eos = true;\n bool stdInMode = false;\n\n\n CoderPropID[] propIDs = {\n CoderPropID.DictionarySize,\n CoderPropID.PosStateBits,\n CoderPropID.LitContextBits,\n CoderPropID.LitPosBits,\n CoderPropID.Algorithm,\n CoderPropID.NumFastBytes,\n CoderPropID.MatchFinder,\n CoderPropID.EndMarker\n };\n\n object[] properties = {\n (Int32)(dictionary),\n (Int32)(posStateBits),\n (Int32)(litContextBits),\n (Int32)(litPosBits),\n (Int32)(algorithm),\n (Int32)(numFastBytes),\n mf,\n eos\n };\n\n using (FileStream inStream = new FileStream(inFile, FileMode.Open))\n {\n using (FileStream outStream = new FileStream(outFile, FileMode.Create))\n {\n SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder();\n encoder.SetCoderProperties(propIDs, properties);\n encoder.WriteCoderProperties(outStream);\n Int64 fileSize;\n if (eos || stdInMode)\n fileSize = -1;\n else\n fileSize = inStream.Length;\n for (int i = 0; i < 8; i++)\n outStream.WriteByte((Byte)(fileSize >> (8 * i)));\n encoder.Code(inStream, outStream, -1, -1, null);\n }\n }\n\n }\n\n public static void DecompressFileLZMA(string inFile, string outFile)\n {\n using (FileStream input = new FileStream(inFile, FileMode.Open))\n {\n using (FileStream output = new FileStream(outFile, FileMode.Create))\n {\n SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder();\n\n byte[] properties = new byte[5];\n if (input.Read(properties, 0, 5) != 5)\n throw (new Exception(\"input .lzma is too short\"));\n decoder.SetDecoderProperties(properties);\n\n long outSize = 0;\n for (int i = 0; i < 8; i++)\n {\n int v = input.ReadByte();\n if (v < 0)\n throw (new Exception(\"Can't Read 1\"));\n outSize |= ((long)(byte)v) << (8 * i);\n }\n long compressedSize = input.Length - input.Position;\n\n decoder.Code(input, output, compressedSize, outSize, null);\n }\n }\n }\n\n public static void Test()\n {\n CompressFileLZMA(\"DiscUtils.pdb\", \"DiscUtils.pdb.7z\");\n DecompressFileLZMA(\"DiscUtils.pdb.7z\", \"DiscUtils.pdb2\");\n }\n }\n}\n"
},
{
"answer_id": 24816635,
"author": "lifestylebyatom",
"author_id": 3169585,
"author_profile": "https://Stackoverflow.com/users/3169585",
"pm_score": 1,
"selected": false,
"text": " string PZipPath = @\"C:\\Program Files\\7-Zip\\7z.exe\";\n string sourceCompressDir = @\"C:\\Test\";\n string targetCompressName = @\"C:\\Test\\abc.zip\";\n string CompressName = targetCompressName.Split('\\\\').Last();\n string[] fileCompressList = Directory.GetFiles(sourceCompressDir, \"*.*\");\n\n if (fileCompressList.Length == 0)\n {\n MessageBox.Show(\"No file in directory\", \"Important Message\");\n return;\n }\n string filetozip = null;\n foreach (string filename in fileCompressList)\n {\n filetozip = filetozip + \"\\\"\" + filename + \" \";\n }\n\n ProcessStartInfo pCompress = new ProcessStartInfo();\n pCompress.FileName = PZipPath;\n if (chkRequestPWD.Checked == true)\n {\n pCompress.Arguments = \"a -tzip \\\"\" + targetCompressName + \"\\\" \" + filetozip + \" -mx=9\" + \" -p\" + tbPassword.Text;\n }\n else\n {\n pCompress.Arguments = \"a -tzip \\\"\" + targetCompressName + \"\\\" \\\"\" + filetozip + \"\\\" -mx=9\";\n }\n pCompress.WindowStyle = ProcessWindowStyle.Hidden;\n Process x = Process.Start(pCompress);\n x.WaitForExit();\n"
},
{
"answer_id": 27997144,
"author": "Vishal Sen",
"author_id": 3555828,
"author_profile": "https://Stackoverflow.com/users/3555828",
"pm_score": 2,
"selected": false,
"text": " string zipfile = @\"E:\\Folderx\\NPPES.zip\";\n string folder = @\"E:\\TargetFolderx\";\n\n ExtractFile(zipfile,folder);\npublic void ExtractFile(string source, string destination)\n {\n // If the directory doesn't exist, create it.\n if (!Directory.Exists(destination))\n Directory.CreateDirectory(destination);\n\n //string zPath = ConfigurationManager.AppSettings[\"FileExtactorEXE\"];\n // string zPath = Properties.Settings.Default.FileExtactorEXE; ;\n\n string zPath=@\"C:\\Program Files\\7-Zip\\7zG.exe\";\n\n try\n {\n ProcessStartInfo pro = new ProcessStartInfo();\n pro.WindowStyle = ProcessWindowStyle.Hidden;\n pro.FileName = zPath;\n pro.Arguments = \"x \\\"\" + source + \"\\\" -o\" + destination;\n Process x = Process.Start(pro);\n x.WaitForExit();\n }\n catch (System.Exception Ex) { }\n }\n"
},
{
"answer_id": 28368184,
"author": "Brent",
"author_id": 589577,
"author_profile": "https://Stackoverflow.com/users/589577",
"pm_score": 0,
"selected": false,
"text": "Private Function CompressFile(filename As String) As Boolean\nUsing zip As New ZipFile()\n zip.AddFile(filename & \".txt\", \"\")\n zip.Save(filename & \".zip\")\nEnd Using\n\nReturn File.Exists(filename & \".zip\")\nEnd Function\n"
},
{
"answer_id": 53896663,
"author": "Fidel",
"author_id": 171846,
"author_profile": "https://Stackoverflow.com/users/171846",
"pm_score": 1,
"selected": false,
"text": "SevenZipSharp.Interop SevenZipBase.SetLibraryPath(@\".\\x86\\7z.dll\");\nvar compressor = new SevenZip.SevenZipCompressor();\nvar filesToCompress = Directory.GetFiles(@\"D:\\data\\\");\ncompressor.CompressFiles(@\"C:\\archive\\abc.7z\", filesToCompress);\n"
},
{
"answer_id": 57251011,
"author": "MrCalvin",
"author_id": 3175384,
"author_profile": "https://Stackoverflow.com/users/3175384",
"pm_score": 2,
"selected": false,
"text": "CoderPropID[] propIDs = {\n //CoderPropID.DictionarySize,\n //CoderPropID.PosStateBits,\n //CoderPropID.LitContextBits,\n //CoderPropID.LitPosBits,\n //CoderPropID.Algorithm,\n //CoderPropID.NumFastBytes,\n //CoderPropID.MatchFinder,\n CoderPropID.EndMarker\n};\nobject[] properties = {\n //(Int32)(dictionary),\n //(Int32)(posStateBits),\n //(Int32)(litContextBits),\n //(Int32)(litPosBits),\n //(Int32)(algorithm),\n //(Int32)(numFastBytes),\n //mf,\n eos\n};\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
222,043
|
<p>I have a variable that contains a 4 byte, network-order IPv4 address (this was created using pack and the integer representation). I have another variable, also a 4 byte network-order, subnet. I'm trying to add them together and add one to get the first IP in the subnet.</p>
<p>To get the ASCII representation, I can do <code>inet_ntoa($ip&$netmask)</code> to get the base address, but it's an error to do <code>inet_ntoa((($ip&$netmask)+1)</code>; I get a message like:</p>
<pre><code> Argument "\n\r&\0" isn't numeric in addition (+) at test.pm line 95.
</code></pre>
<p>So what's happening, the best as I can tell, is it's looking at the 4 bytes, and seeing that the 4 bytes don't represent a numeric string, and then refusing to add 1.</p>
<p>Another way of putting it: What I want it to do is add 1 to the least significant byte, which I know is the 4th byte? That is, I want to take the string <code>\n\r&\0</code> and end up with the string <code>\n\r&\1</code>. What's the simplest way of doing that? </p>
<p>Is there a way to do this without having to unpack and re-pack the variable?</p>
|
[
{
"answer_id": 222096,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 5,
"selected": true,
"text": "$ip&$netmask inet_ntoa pack(\"N\", unpack(\"N\", $ip&$netmask) + 1)\n"
},
{
"answer_id": 222169,
"author": "Liudvikas Bukys",
"author_id": 5845,
"author_profile": "https://Stackoverflow.com/users/5845",
"pm_score": 3,
"selected": false,
"text": "use Socket;\n\n$ip = pack(\"C4\", 192,168,250,66); # why not inet_aton(\"192.168.250.66\")\n$netmask = pack(\"C4\", 255,255,255,0);\n\n$ipi = unpack(\"N\", $ip);\n$netmaski = unpack(\"N\", $netmask);\n\n$ip1 = pack(\"N\", ($ipi&$netmaski)+1);\nprint inet_ntoa($ip1), \"\\n\";\n 192.168.250.1\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7548/"
] |
222,052
|
<p>I have a ControlTemplate that is made up of a ToolBarTray and a ToolBar. In my ToolBar, I have several buttons and then a label. I want to be able to update the label in my toolbar with something like "1 of 10" </p>
<p>My first thought is to programatically find the label and set it, but I'm reading that this should be done with Triggers. I am having a hard time understanding how to accomplish this. Any ideas?</p>
<pre><code> <Style x:Key="DocViewerToolBarStyle" TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<ToolBarTray... />
<ToolBar.../>
<Button../>
<Button..>
<Label x:Name="myStatusLabel" .. />
</code></pre>
|
[
{
"answer_id": 222106,
"author": "Bryan Anderson",
"author_id": 21186,
"author_profile": "https://Stackoverflow.com/users/21186",
"pm_score": 1,
"selected": false,
"text": "<Label x:Name=\"myStatusLabel\" Content=\"{TemplateBinding Content}\"/>\n"
},
{
"answer_id": 222129,
"author": "EFrank",
"author_id": 28572,
"author_profile": "https://Stackoverflow.com/users/28572",
"pm_score": 2,
"selected": true,
"text": "<Label x:Name=\"myStatusLabel\" Content={TemplateBinding MyStatusLabelProperty} ../>\n"
},
{
"answer_id": 248048,
"author": "pousi",
"author_id": 19982,
"author_profile": "https://Stackoverflow.com/users/19982",
"pm_score": 0,
"selected": false,
"text": "<DataTemplate DataType={x:Type viewmodel:MyToolBarViewModel}>\n <Label Content={Binding CurrentPage} />\n <Label Content={Binding TotalPages} ContentStringFormat=\"{}of {0}\" />\n</DataTemplate>\n\n<ToolBar>\n <ContentPresenter Content={Binding <PathtoViewModel>} />\n</ToolBar>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
222,053
|
<p>this is my first question here so I hope I can articulate it well and hopefully it won't be too mind-numbingly easy.</p>
<p>I have the following class <em>SubSim</em> which extends <em>Sim</em>, which is extending <em>MainSim</em>. In a completely separate class (and library as well) I need to check if an object being passed through is a type of <em>MainSim</em>. So the following is done to check;</p>
<pre>
Type t = GetType(sim);
//in this case, sim = SubSim
if (t != null)
{
return t.BaseType == typeof(MainSim);
}
</pre>
<p>Obviously <em>t.BaseType</em> is going to return <em>Sim</em> since <em>Type.BaseType</em> gets the type from which the current Type directly inherits. </p>
<p>Short of having to do <em>t.BaseType.BaseType</em> to get <em>MainSub</em>, is there any other way to get the proper type using .NET libraries? Or are there overrides that can be redefined to return the main class? </p>
<p>Thank you in advance</p>
|
[
{
"answer_id": 222059,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "if (sim is MainSim)\n"
},
{
"answer_id": 222062,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "sim is MainSim;\n(sim as MainSim) != null;\nsim.GetType().IsSubclassOf(typeof(MainSim));\ntypeof(MainSim).IsAssignableFrom(sim.GetType());\n bool IsMainSimType(Type t)\n { if (t == typeof(MainSim)) return true; \n if (t == typeof(object) ) return false;\n return IsMainSimType(t.BaseType);\n }\n"
},
{
"answer_id": 222063,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "is return t is MainSim;\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13064/"
] |
222,065
|
<p>When creating an index over a column that is going to be UNIQUE (but not the primary key of the table), SQL server let's me choose a few options:</p>
<p>1) I can choose for it to be a Constraint or an Index.<br>
I'm guessing this means that if I set it as constraint, it won't use it when querying, only when writing. However, the only efficient way I can think of for SQL Server to enforce that constraint is by actually building an index. What is the use for this option?</p>
<p>2) Also, if I set it as "index", it let's me specify that it should ignore duplicate keys.
This is the most puzzling for me...<br>
I again guess it means the opposite of constraint. It probably means "use it when querying, but don't even check when writing".<br>
But then why would I set it as UNIQUE?<br>
I'm guessing there are some optimizations SQL Server can do, but i'd like to understand it better.</p>
<p>Does anyone know what exactly SQL Server does with these options?<br>
What's the use case for setting an index to be Unique, but ignore duplicate keys?</p>
<p>NOTE: This is for SQL Server 2000</p>
<hr />
<p><strong>EDIT:</strong> According to what you said, however... If I create a Constraint, will it be used to speed up queries that filter using the fields in the constraint?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 222284,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 4,
"selected": true,
"text": "UNIQUE UNIQUE UNIQUE"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
222,089
|
<p>With the following file reading code:</p>
<pre><code>using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
using (TextReader tr = new StreamReader(fileStream))
{
string fileContents = tr.ReadToEnd();
}
}
</code></pre>
<p>And the following file write code:</p>
<pre><code>using (TextWriter tw = new StreamWriter(fileName))
{
tw.Write(fileContents);
tw.Close();
}
</code></pre>
<p>The following exception details are seen:</p>
<blockquote>
<p>The process cannot access the file
'c:\temp\myfile.txt' because it is
being used by another process.</p>
</blockquote>
<p>What is the best way of avoiding this? Does the reader need to retry upon receipt of the exception or is there some better way?</p>
<p>Note that the reader process is using a <em>FileSystemWatcher</em> to know when the file has changed.</p>
<p>Also note that, in this instance, I'm <strong>not</strong> looking for alternatives ways of sharing strings between the 2 processes.</p>
|
[
{
"answer_id": 222100,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "Mutex"
},
{
"answer_id": 222111,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 6,
"selected": true,
"text": "using (FileStream stream = new FileStream(@\"C:\\Myfile.txt\", FileMode.Open, FileAccess.ReadWrite, FileShare.Read))\n{\n // Do your writing here.\n}\n using (FileStream stream = new FileStream(@\"C:\\Myfile.txt\", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n{\n // Does reading here.\n}\n"
},
{
"answer_id": 222205,
"author": "Iain",
"author_id": 5993,
"author_profile": "https://Stackoverflow.com/users/5993",
"pm_score": 2,
"selected": false,
"text": "using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))\n{\n using (TextReader tr = new StreamReader(fileStream))\n {\n string fileContents = tr.ReadToEnd();\n }\n}\n FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);\nusing (TextWriter tw = new StreamWriter(fileStream))\n{\n tw.Write(fileContents);\n tw.Close();\n}\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5993/"
] |
222,108
|
<p>On my busiest production installation, on occasion I get a single thread that seems to get stuck in an infinite loop. I've not managed to figure out who is the culprit, after much research and debugging, but it seems like it should be possible. Here are the gory details:</p>
<p><strong><em>Current debugging notes:</em></strong></p>
<p>1) <strong>ps -eL 18975</strong> shows me the the Linux pid the problem child thread, 19269</p>
<pre><code>$ps -eL | grep 18975
...
PID LWP TTY TIME CMD
18975 18994 ? 00:00:05 java
18975 19268 ? 00:00:00 java
18975 19269 ? 05:16:49 java
18975 19271 ? 00:01:22 java
18975 19273 ? 00:00:00 java
...
</code></pre>
<p>2) <strong>jstack -l 18975</strong> says there are no deadlocks, <strong>jstack -m 18975</strong> does not work </p>
<p>3) <strong>jstack -l 18975</strong> does give me the stack trace for all my threads (~400). Example thread stack (<em>and not the problem</em>):</p>
<pre>"http-342.877.573.944-8080-360" daemon prio=10 tid=0x0000002adaba9c00 nid=0x754c in Object.wait() [0x00000000595bc000..0x00000000595bccb0]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on (a org.apache.tomcat.util.net.JIoEndpoint$Worker)
at java.lang.Object.wait(Object.java:485)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.await(JIoEndpoint.java:416)
- locked (a org.apache.tomcat.util.net.JIoEndpoint$Worker)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:442)
at java.lang.Thread.run(Thread.java:619)
</pre>
<p>4) The ps -eL output's thread ID does not match the output from jstack, or at least I cannot see it. (jstack documentation is a bit sparse.) </p>
<p>5) There are no heavy IO, memory usage or other corresponding activity clues to work with.</p>
<p><strong><em>Platform:</em></strong></p>
<ul>
<li>Java 6</li>
<li>Tomcat 6</li>
<li>RHEL 4 (64-bit)</li>
</ul>
<p>Does anybody know how I can make that connection from the linux ps output to my problem child java thread? So close, yet so far...</p>
|
[
{
"answer_id": 1199127,
"author": "ubiyubix",
"author_id": 19701,
"author_profile": "https://Stackoverflow.com/users/19701",
"pm_score": 5,
"selected": true,
"text": "\"http-342.877.573.944-8080-360\" daemon prio=10 tid=0x0000002adaba9c00 nid=0x754c in Object.wait() [0x00000000595bc000..0x00000000595bccb0]\n #!/usr/bin/perl -w\nwhile (<>) {\n if (/nid=(0x[[:xdigit:]]+)/) {\n $lwp = hex($1);\n s/nid=/lwp=$lwp nid=/;\n }\n print;\n}\n"
},
{
"answer_id": 1798043,
"author": "yes",
"author_id": 218758,
"author_profile": "https://Stackoverflow.com/users/218758",
"pm_score": 0,
"selected": false,
"text": "prstat -L prstat -L -v -u weblogic\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2961/"
] |
222,117
|
<p><a href="https://stackoverflow.com/questions/106597/why-are-fixnums-in-emacs-only-29-bits">The fixnum question</a> brought my mind to an other question I've wondered for a long time.</p>
<p>Many online material about garbage collection does not tell about how runtime type information can be implemented. Therefore I know lots about all sorts of garbage collectors, but not really about how I can implement them.</p>
<p>The fixnum solution is actually quite nice, it's very clear which value is a pointer and which isn't. What other commonly used solutions for storing type information there is?</p>
<p>Also, I wonder about fixnum -thing. Doesn't that mean that you are being limited to fixnums on every array index? Or is there some sort of workaround for getting full 64-bit integers?</p>
|
[
{
"answer_id": 711687,
"author": "Damien Pollet",
"author_id": 63112,
"author_profile": "https://Stackoverflow.com/users/63112",
"pm_score": 0,
"selected": false,
"text": "SmallInteger LargePositiveInteger SmallInteger maxVal LargePositiveInteger SmallInteger"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] |
222,119
|
<p>I have encapsulated a backup database command in a Try/Catch and it appears that the error message is being lost somewhere. For example:</p>
<pre><code>BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak'
</code></pre>
<p>..gives error:<br>
<strong><em>Could not locate entry in sysdatabases for database 'NonExistantDB'. No entry found with that name. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally.</em></strong></p>
<p>Whereas:</p>
<pre><code>BEGIN TRY
BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak'
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
END CATCH
</code></pre>
<p>... only gives error: <strong><em>BACKUP DATABASE is terminating abnormally.</em></strong></p>
<p>Is there a way to get the full error message or is this a limitation of try/catch?</p>
|
[
{
"answer_id": 222277,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 3,
"selected": true,
"text": " BACKUP DATABASE NonExistantDB TO DISK = 'C:\\TEMP\\NonExistantDB.bak'\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989/"
] |
222,133
|
<p>I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output.</p>
<p>Pulling the class dynamically from the global namespace works:</p>
<pre><code>result = globals()[classname](param).html
</code></pre>
<p>And it's certainly more succinct than:</p>
<pre><code>if classname == 'Foo':
result = Foo(param).html
elif classname == 'Bar':
...
</code></pre>
<p>What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?</p>
|
[
{
"answer_id": 222307,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 2,
"selected": false,
"text": "dispatch = {'Foo': Foo, 'Bar': Bar, 'Bizbaz': Bizbaz}\n globals() classname classname dispatch globals()[variable] variable"
},
{
"answer_id": 222334,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 4,
"selected": true,
"text": " class_lookup = {'Class1' : Class1, ... }\n ...\n result = class_lookup[className](param).html\n class Namespace(object):\n class Class1(object):\n ...\n class Class2(object):\n ...\n...\nresult = getattr(Namespace, className)(param).html\n def register_subclasses(base):\n d={}\n for cls in base.__subclasses__():\n d[cls.__name__] = cls\n d.update(register_subclasses(cls))\n return d\n\nclass_lookup = register_subclasses(MyBaseClass)\n"
},
{
"answer_id": 224641,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 0,
"selected": false,
"text": "class Foo:\n lookup = True\n def __init__(self, params):\n # and so on\n class_lookup = zip([(c, globals()[c]) for c in dir() if hasattr(globals()[c], \"lookup\")])\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7341/"
] |
222,139
|
<p>I'm building a new site for my company, and I'm at the stage where I've created the html mockup of the first page. I'm going to use this as a basis for the rest of the site. I'm thinking of organising my stylesheet better now I've got the design looking consistent cross-browser, but I'm wondering how far to go when I'm breaking it up.</p>
<p>One idea is to have the following:</p>
<ul>
<li>reset.css</li>
<li>typography.css</li>
<li>layout.css</li>
<li>colors.css</li>
</ul>
<p>but where do I draw the line? theoretically I could go on and break them down into classes, ids etc, but I think thats going overboard.</p>
<p>Does this seem a reasonable method?</p>
|
[
{
"answer_id": 222158,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "base.css reset.css page.css microsite_skin.css"
},
{
"answer_id": 222867,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 2,
"selected": false,
"text": "<body>\n<!--[if IE 7]><div class=\"IE IE7\"><![endif]-->\n<!--[if IE 6]><div class=\"IE IE6\"><![endif]-->\n\n... rest of markup ...\n\n<!--[if IE]></div><![endif]-->\n</body>\n"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
222,148
|
<p>The default value for the first item in a drop down list is the name of the database field. I need to change it to a more user friendly name. How do I change the value?</p>
|
[
{
"answer_id": 222852,
"author": "Joshua",
"author_id": 6013,
"author_profile": "https://Stackoverflow.com/users/6013",
"pm_score": 4,
"selected": true,
"text": "<script> document.formWarpRequest._oLstChoicesMyList[0].text = '--SELECT A CITY--'; </script>"
}
] |
2008/10/21
|
[
"https://Stackoverflow.com/questions/222148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.