qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
361,304 | <p>How do I get the sequence number of the row just inserted?</p>
| [
{
"answer_id": 361309,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 6,
"selected": true,
"text": "declare\n s2 number;\n begin\n insert into seqtest2(x) values ('aaa') returning seq into s2;\n dbms_output.put_line(s2);\n end;\n myseq=curs.var(cx_Oracle.NUMBER)\ncurs.prepare(\"insert into seqtest2(x) values('bbb') returning seq into :x\")\ncurs.execute(None, x=myseq)\nprint int(myseq.getvalue())\n"
},
{
"answer_id": 361383,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 3,
"selected": false,
"text": "PROCEDURE insert_name(new_name IN names.name%TYPE, \n new_name_id OUT names.id%TYPE)\nIS\n new_id names.id%TYPE;\nBEGIN\n SELECT names_sequence.nextVal INTO new_id FROM dual;\n INSERT INTO names(id, name) VALUES(new_id, new_name);\n new_name_id := new_id;\nEND;\n"
},
{
"answer_id": 9944655,
"author": "Alexey Honorio",
"author_id": 1303369,
"author_profile": "https://Stackoverflow.com/users/1303369",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Oracle.DataAccess.Client;\nusing System.Data;\n\nnamespace ConsoleApplication3\n{\nclass Program\n{\n\n public static void Main(string[] args)\n {\n\n OracleConnection cn = new OracleConnection(\"your connection string here\");\n\n\n string sql = \"INSERT INTO testtable(testname) VALUES('testing2') RETURNING id INTO :LASTID\";\n OracleParameter lastId = new OracleParameter(\":LASTID\", OracleDbType.Int32);\n\n lastId.Direction = ParameterDirection.Output;\n\n using (OracleCommand cmd = new OracleCommand(sql, cn))\n {\n cn.Open();\n cmd.Parameters.Add(lastId);\n cmd.ExecuteNonQuery();\n Console.WriteLine(\"Last ID: \" + lastId.Value.ToString());\n cn.Close();\n }\n Console.WriteLine();\n Console.ReadKey(false);\n\n\n }\n}\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
361,307 | <p>When using the 'as' keyword in C# to make a cast which fails, null gets returned. What's going on in the background? Is it simply suppressing an exception so I don't have to write handling code for a failure?</p>
<p>I'm interested in the performance characteristics of it compared to a typical cast wrapped in a try-catch.</p>
| [
{
"answer_id": 361318,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 7,
"selected": true,
"text": "isinst castclass null isinst castclass isinst class A\n{\n public int Foo;\n}\n\nclass B\n{\n public int Foo;\n\n public static explicit operator B(A a)\n {\n return new B { Foo = a.Foo };\n }\n}\n var a = new A { Foo = 3 };\nvar b = (B)a;\nConsole.WriteLine(b.Foo); // prints 3\n var a = new A { Foo = 3 };\nvar b = a as B;\n"
},
{
"answer_id": 361463,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": "COREINFO_CLASS_STRUCT COREINFO_CLASS_STRUCT COREINFO_CLASS_STRUCT COREINFO_CLASS_STRUCT System.Object isinst castclass COREINFO_CLASS_STRUCT"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10756/"
] |
361,312 | <p>I do have to say I'm fairly inexperienced when it comes to C++, don't be too harsh on me.</p>
<p>Recently stumbled unto the wonders of the win32 API and have chosen to practice using it (I'd rather not use MFC/wxWidgets/etc at this point, just for educational purposes).</p>
<p>Well, my real question is:
How do you properly code your win32 GUI stuff into classes. I mean, sure, you can make a class that saves individual window handles, allows for easier modification of window properties, has a more simplified version of CreateWindow(). But as I understand it you will need a messagepump and several callback functions for your created windows. How does that work when combining them with classes?</p>
<p>Could anyone point me in the right direction here? I don't mind reading (a lot of) example code as long as it is commented.</p>
<p>PS: I'm also having trouble finding good (read: easy) documentation on using 'resource files' for my window decorations. Bonuspoints for that! :)</p>
| [
{
"answer_id": 361576,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "#include <windowsx.h>"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,329 | <p>Let's say I have some code like this </p>
<pre><code>if(isset($_GET['foo']))
//do something
if(isset($_GET['bar']))
//do something else
</code></pre>
<p>If a user is at example.com/?foo=abc and clicks on a link to set bar=xyz, I want to easily take them to example.com/?foo=abc&bar=xyz, rather than example.com/?bar=xyz. </p>
<p>I can think of a few very messy ways to do this, but I'm sure there's something cleaner that I don't know about and haven't been able to track down via Google.</p>
| [
{
"answer_id": 361354,
"author": "Logan Serman",
"author_id": 29595,
"author_profile": "https://Stackoverflow.com/users/29595",
"pm_score": 0,
"selected": false,
"text": "$link = ($_GET['foo'] == 'abc') ? 'foo=abc&bar=xyz' : 'bar=xyz';\n?>\n<a href=\"whatever.php?<?= $link ?>\">Click Me</a>\n"
},
{
"answer_id": 361358,
"author": "Ryan Smith",
"author_id": 10420,
"author_profile": "https://Stackoverflow.com/users/10420",
"pm_score": 0,
"selected": false,
"text": "echo '<a href=\"myurl.php' . querystring . '&bar=foo';\n"
},
{
"answer_id": 361400,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 3,
"selected": true,
"text": "//get passed params\n//(you might do some sanitizing at this point)\n$params=$_GET;\n\n//morph the params with new values\n$params['bar']='xyz';\n\n//build new query string\n$query='';\n$sep='?';\nforeach($params as $name=>$value)\n{\n $query.=$sep.$name.'='.urlencode($value);\n $sep='&';\n}\n"
},
{
"answer_id": 361401,
"author": "Byron Whitlock",
"author_id": 42304,
"author_profile": "https://Stackoverflow.com/users/42304",
"pm_score": 1,
"selected": false,
"text": "$qs=\"a=1&b=2\";\n$href=\"$qs&b=4\";\n$href contains \"a=1&b=2&b=4\"\n function getUpdateQS($key,$value)\n {\n foreach ($_GET as $k => $v)\n {\n if ($k != $key)\n {\n $qs .= \"$k=\".urlencode($v).\"&\"\n }\n else\n {\n $qs .= \"$key=\".urlencode($value).\"&\";\n }\n }\n return $qs\n }\n\n <a href=\"reports.php?<?getupdateqs('name','byron');?\">View report</a>\n"
},
{
"answer_id": 361530,
"author": "Matt Kantor",
"author_id": 3625,
"author_profile": "https://Stackoverflow.com/users/3625",
"pm_score": 0,
"selected": false,
"text": "function to_query_string($array) {\n if(is_scalar($array)) $query = trim($array, '? \\t\\n\\r\\0\\x0B'); // I could split on \"&\" and \"=\" do some urlencode-ing here\n else $query = http_build_query($array);\n return '?'.$query;\n}\n $_GET['overriden_or_new'] = 'new_value';\necho '<a href=\"'.to_query_string($_GET).'\">Yeah!</a>';\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30098/"
] |
361,330 | <p>I need to use the popcnt instruction in a project that is compiled using Visual Stdio 2005<br>
The intrinsic <code>__popcnt()</code> only works with VS2008 and the compiler doesn't seem to recognize the instruction even when I write in a <code>__asm {}</code> block.</p>
<p>Is there any way to do this?</p>
| [
{
"answer_id": 361665,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 2,
"selected": false,
"text": ";SSE2 macros for MASM 6.14 by daydreamer aka Magnus Svensson\n\nADDPD MACRO M1,M2\n db 066h\n ADDPS M1,M2\nENDM\n\nADDSD MACRO M1,M2\n DB 0F2H\n ADDPS M1,M2\nENDM\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
] |
361,336 | <p>I'm trying to build my first generic list and have run into some problems. I understand the declaration looks like " <code>List<T></code> ", and I have <code>using System.Collections.Generic;</code> at the top of my page. However, Visual Studio doesn't recognize the <code>T</code> variable. </p>
<p>What am I missing?</p>
| [
{
"answer_id": 361352,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 3,
"selected": false,
"text": "int List<int> list = new List<int>();\n T"
},
{
"answer_id": 361353,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 4,
"selected": false,
"text": "T int string List<int> values = new List<int>();\n\nvalues.Add(1);\nvalues.Add(2);\n\nint secondNumber = values[1]; // Yay! No casting or boxing required!\n"
},
{
"answer_id": 361357,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 2,
"selected": false,
"text": "List<Foo> fooList;\n"
},
{
"answer_id": 361365,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 7,
"selected": true,
"text": "List<T> List<WhateverTypeYouWantItToBeAListOf> List<Employee> employeeList = new List<Employee>();\n Employee Employee emp1 = new Employee();\nEmployee emp2 = new Employee();\n\nemployeeList.Add(emp1);\nemployeeList.Add(emp2);\n employeeList emp1 emp2 Animal List<Employee> Animal"
},
{
"answer_id": 361380,
"author": "gius",
"author_id": 19712,
"author_profile": "https://Stackoverflow.com/users/19712",
"pm_score": 3,
"selected": false,
"text": "T List<string> List<int> List"
},
{
"answer_id": 363427,
"author": "John Dunagan",
"author_id": 28939,
"author_profile": "https://Stackoverflow.com/users/28939",
"pm_score": 2,
"selected": false,
"text": "List<Object>"
},
{
"answer_id": 363488,
"author": "lithander",
"author_id": 45434,
"author_profile": "https://Stackoverflow.com/users/45434",
"pm_score": 3,
"selected": false,
"text": "new <> List<Employee> employeeList = new List<Employee>();\n Employee employeeList Employee T"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42987/"
] |
361,350 | <p>Our app allows multiple files to be selected in a file selection dialog which is shown via the GetOpenFileName function (this question also applies to folks using CFileDialog, etc...)</p>
<p>There appears to be a limit to the number of characters that can be typed into the filename field (259 seems to be the magic number - not sure why).</p>
<p>We have tried changing the following members of the <a href="http://msdn.microsoft.com/en-us/library/ms646839(VS.85).aspx" rel="nofollow noreferrer">OPENFILENAME</a> structure:</p>
<p>lpstrFile - point to our own buffer, sized at 4K bytes
nMaxFile - set to the size of lpstrFile (we are compiling ANSI, so this is effectively 4000</p>
<p>But these values appear to not increase the input width of the filename field in the dialog.</p>
<p>I am going to experiment with sending a EM_SETLIMITTEXT message to the control, but wanted to know if anyone else has a solution.</p>
<p>EDIT - solved this myself: <a href="https://stackoverflow.com/questions/361350/increase-number-of-characters-in-filename-field-of-getopenfilename-file-selecti#394443">solution</a> I can't accept out my own answer, but here it is for posterity. If anyone else has a better solution, please post it - or feel free to mod up my solution so future searchers will find it at the top.</p>
| [
{
"answer_id": 361360,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "MAX_PATH MAX_PATH \"\\\\?\\\" \"\\\\?\\D:\\<very long path>\" < >"
},
{
"answer_id": 394443,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 3,
"selected": true,
"text": "EM_SETLIMITTEXT GetDlgCtrl OnInitDialog CComboBox* LimitText() CB_LIMITTEXT CFileDialog OPENFIILENAME.nMaxFile"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10973/"
] |
361,359 | <p>I have three DIVs, something like this:</p>
<pre><code><div id="header">
...
</div>
<div id="content">
<div id="popup">
...
</div>
</div>
</code></pre>
<p>DIV#header is "position: fixed" and used as a non-scrolling header at the top of the screen. DIV#content has some content in it and is "position: relative". DIV#popup is "position: absolute" and starts out hidden and is displayed on hover. </p>
<p>I want the popup to be at the highest level on the page, so that it is above even DIV#header if they overlap. This works fine in Firefox but in IE the popups are behind the header. I can fix this by setting the z-index of DIV#content to be higher than the header, but then of course DIV#content will also be displayed above DIV#header when they overlap, which I don't want.</p>
<p>It sounds like I might be affected by what is described on <a href="http://annevankesteren.nl/2005/06/z-index" rel="nofollow noreferrer">this page</a>. However, as I understand it, doing something like setting a default z-index on all elements, like so:</p>
<pre><code>* {
z-index: 1
}
</code></pre>
<p>should fix this (as now every element would have a z-index of 1 explicitly set), however rather than fixing this in IE it breaks it in Firefox (such that Firefox now behaves like IE).</p>
<p>What's the real deal with z-indexes in IE?</p>
| [
{
"answer_id": 361360,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "MAX_PATH MAX_PATH \"\\\\?\\\" \"\\\\?\\D:\\<very long path>\" < >"
},
{
"answer_id": 394443,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 3,
"selected": true,
"text": "EM_SETLIMITTEXT GetDlgCtrl OnInitDialog CComboBox* LimitText() CB_LIMITTEXT CFileDialog OPENFIILENAME.nMaxFile"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] |
361,363 | <p>Using only ANSI C, is there any way to measure time with milliseconds precision or more? I was browsing time.h but I only found second precision functions.</p>
| [
{
"answer_id": 361492,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 8,
"selected": true,
"text": "gettimeofday struct timeval tval_before, tval_after, tval_result;\n\ngettimeofday(&tval_before, NULL);\n\n// Some code you want to time, for example:\nsleep(1);\n\ngettimeofday(&tval_after, NULL);\n\ntimersub(&tval_after, &tval_before, &tval_result);\n\nprintf(\"Time elapsed: %ld.%06ld\\n\", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);\n Time elapsed: 1.000870"
},
{
"answer_id": 368843,
"author": "Nick Van Brunt",
"author_id": 30470,
"author_profile": "https://Stackoverflow.com/users/30470",
"pm_score": 6,
"selected": false,
"text": "#include <time.h>\nclock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);\n"
},
{
"answer_id": 380446,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "#include <stdio.h>\n#include <stdint.h>\n#include <time.h>\n\nint64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)\n{\n return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -\n ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);\n}\n\nint main(int argc, char **argv)\n{\n struct timespec start, end;\n clock_gettime(CLOCK_MONOTONIC, &start);\n\n // Some code I am interested in measuring \n\n clock_gettime(CLOCK_MONOTONIC, &end);\n\n uint64_t timeElapsed = timespecDiff(&end, &start);\n}\n"
},
{
"answer_id": 18733858,
"author": "Jichao",
"author_id": 193251,
"author_profile": "https://Stackoverflow.com/users/193251",
"pm_score": -1,
"selected": false,
"text": "SYSTEMTIME t;\nGetLocalTime(&t);\nswprintf_s(buff, L\"[%02d:%02d:%02d:%d]\\t\", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);\n"
},
{
"answer_id": 36095407,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "timespec_get clock_gettime printf #include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstatic long get_nanos(void) {\n struct timespec ts;\n timespec_get(&ts, TIME_UTC);\n return (long)ts.tv_sec * 1000000000L + ts.tv_nsec;\n}\n\nint main(void) {\n long nanos;\n long last_nanos;\n long start;\n nanos = get_nanos();\n last_nanos = nanos;\n start = nanos;\n while (1) {\n nanos = get_nanos();\n if (nanos - last_nanos > 100000000L) {\n printf(\"current nanos: %ld\\n\", nanos - start);\n last_nanos = nanos;\n }\n }\n return EXIT_SUCCESS;\n}\n std::chrono::high_resolution_clock sysdeps/posix/timespec_get.c int\ntimespec_get (struct timespec *ts, int base)\n{\n switch (base)\n {\n case TIME_UTC:\n if (__clock_gettime (CLOCK_REALTIME, ts) < 0)\n return 0;\n break;\n\n default:\n return 0;\n }\n\n return base;\n}\n TIME_UTC __clock_gettime (CLOCK_REALTIME, ts) clock_gettime man clock_gettime getrusage()"
},
{
"answer_id": 37920181,
"author": "Alexander Saprykin",
"author_id": 6459465,
"author_profile": "https://Stackoverflow.com/users/6459465",
"pm_score": 5,
"selected": false,
"text": "LARGE_INTEGER tcounter;\nLARGE_INTEGER freq; \n\nif (QueryPerformanceFrequency (&tcounter) != 0)\n freq = tcounter.QuadPart;\n LARGE_INTEGER tcounter;\nLARGE_INTEGER tick_value;\n\nif (QueryPerformanceCounter (&tcounter) != 0)\n tick_value = tcounter.QuadPart;\n LARGE_INTEGER usecs = (tick_value - prev_tick_value) / (freq / 1000000);\n GetTickCount #include <mach/mach_time.h>\n#include <stdint.h>\n\nstatic uint64_t freq_num = 0;\nstatic uint64_t freq_denom = 0;\n\nvoid init_clock_frequency ()\n{\n mach_timebase_info_data_t tb;\n\n if (mach_timebase_info (&tb) == KERN_SUCCESS && tb.denom != 0) {\n freq_num = (uint64_t) tb.numer;\n freq_denom = (uint64_t) tb.denom;\n }\n}\n mach_absolute_time uint64_t tick_value = mach_absolute_time ();\n uint64_t value_diff = tick_value - prev_tick_value;\n\n/* To prevent overflow */\nvalue_diff /= 1000;\n\nvalue_diff *= freq_num;\nvalue_diff /= freq_denom;\n 1000 clock_gettime CLOCK_MONOTONIC clock_gettime CLOCK_MONOTONIC _POSIX_MONOTONIC_CLOCK >= 0 CLOCK_MONOTONIC _POSIX_MONOTONIC_CLOCK 0 sysconf #include <unistd.h>\n\n#ifdef _SC_MONOTONIC_CLOCK\nif (sysconf (_SC_MONOTONIC_CLOCK) > 0) {\n /* A monotonic clock presents */\n}\n#endif\n clock_gettime #include <time.h>\n#include <sys/time.h>\n#include <stdint.h>\n\nuint64_t get_posix_clock_time ()\n{\n struct timespec ts;\n\n if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0)\n return (uint64_t) (ts.tv_sec * 1000000 + ts.tv_nsec / 1000);\n else\n return 0;\n}\n uint64_t prev_time_value, time_value;\nuint64_t time_diff;\n\n/* Initial time */\nprev_time_value = get_posix_clock_time ();\n\n/* Do some work here */\n\n/* Final time */\ntime_value = get_posix_clock_time ();\n\n/* Time difference */\ntime_diff = time_value - prev_time_value;\n gettimeofday clock_gettime #include <time.h>\n#include <sys/time.h>\n#include <stdint.h>\n\nuint64_t get_gtod_clock_time ()\n{\n struct timeval tv;\n\n if (gettimeofday (&tv, NULL) == 0)\n return (uint64_t) (tv.tv_sec * 1000000 + tv.tv_usec);\n else\n return 0;\n}\n clock_gettime CLOCK_MONOTONIC CLOCK_SGI_CYCLE CLOCK_MONOTONIC clock_gettime gethrtime clock_gettime gethrtime #include <sys/time.h>\n\nvoid time_measure_example ()\n{\n hrtime_t prev_time_value, time_value;\n hrtime_t time_diff;\n\n /* Initial time */\n prev_time_value = gethrtime ();\n\n /* Do some work here */\n\n /* Final time */\n time_value = gethrtime ();\n\n /* Time difference */\n time_diff = time_value - prev_time_value;\n}\n clock_gettime gethrtime system_time #include <kernel/OS.h>\n\nvoid time_measure_example ()\n{\n bigtime_t prev_time_value, time_value;\n bigtime_t time_diff;\n\n /* Initial time */\n prev_time_value = system_time ();\n\n /* Do some work here */\n\n /* Final time */\n time_value = system_time ();\n\n /* Time difference */\n time_diff = time_value - prev_time_value;\n}\n DosTmrQueryFreq #define INCL_DOSPROFILE\n#define INCL_DOSERRORS\n#include <os2.h>\n#include <stdint.h>\n\nULONG freq;\n\nDosTmrQueryFreq (&freq);\n DosTmrQueryTime QWORD tcounter;\nunit64_t time_low;\nunit64_t time_high;\nunit64_t timestamp;\n\nif (DosTmrQueryTime (&tcounter) == NO_ERROR) {\n time_low = (unit64_t) tcounter.ulLo;\n time_high = (unit64_t) tcounter.ulHi;\n\n timestamp = (time_high << 32) | time_low;\n}\n uint64_t usecs = (prev_timestamp - timestamp) / (freq / 1000000);\n"
},
{
"answer_id": 49508131,
"author": "LeeR",
"author_id": 7247458,
"author_profile": "https://Stackoverflow.com/users/7247458",
"pm_score": 2,
"selected": false,
"text": "gettimeofday tv_sec tv_usec long currentTimeMillis() {\n struct timeval time;\n gettimeofday(&time, NULL);\n\n return time.tv_sec * 1000 + time.tv_usec / 1000;\n}\n\nint main() {\n printf(\"%ld\\n\", currentTimeMillis());\n // wait 1 second\n sleep(1);\n printf(\"%ld\\n\", currentTimeMillis());\n return 0;\n }\n 1522139691342 1522139692342 ^ "
},
{
"answer_id": 72596512,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 0,
"selected": false,
"text": "timespec_get() #include <time.h>\n\n/// Convert seconds to milliseconds\n#define SEC_TO_MS(sec) ((sec)*1000)\n/// Convert seconds to microseconds\n#define SEC_TO_US(sec) ((sec)*1000000)\n/// Convert seconds to nanoseconds\n#define SEC_TO_NS(sec) ((sec)*1000000000)\n\n/// Convert nanoseconds to seconds\n#define NS_TO_SEC(ns) ((ns)/1000000000)\n/// Convert nanoseconds to milliseconds\n#define NS_TO_MS(ns) ((ns)/1000000)\n/// Convert nanoseconds to microseconds\n#define NS_TO_US(ns) ((ns)/1000)\n\n/// Get a time stamp in milliseconds.\nuint64_t millis()\n{\n struct timespec ts;\n timespec_get(&ts, TIME_UTC);\n uint64_t ms = SEC_TO_MS((uint64_t)ts.tv_sec) + NS_TO_MS((uint64_t)ts.tv_nsec);\n return ms;\n}\n\n/// Get a time stamp in microseconds.\nuint64_t micros()\n{\n struct timespec ts;\n timespec_get(&ts, TIME_UTC);\n uint64_t us = SEC_TO_US((uint64_t)ts.tv_sec) + NS_TO_US((uint64_t)ts.tv_nsec);\n return us;\n}\n\n/// Get a time stamp in nanoseconds.\nuint64_t nanos()\n{\n struct timespec ts;\n timespec_get(&ts, TIME_UTC);\n uint64_t ns = SEC_TO_NS((uint64_t)ts.tv_sec) + (uint64_t)ts.tv_nsec;\n return ns;\n}\n\n// NB: for all 3 timestamp functions above: gcc defines the type of the internal\n// `tv_sec` seconds value inside the `struct timespec`, which is used\n// internally in these functions, as a signed `long int`. For architectures\n// where `long int` is 64 bits, that means it will have undefined\n// (signed) overflow in 2^64 sec = 5.8455 x 10^11 years. For architectures\n// where this type is 32 bits, it will occur in 2^32 sec = 136 years. If the\n// implementation-defined epoch for the timespec is 1970, then your program\n// could have undefined behavior signed time rollover in as little as\n// 136 years - (year 2021 - year 1970) = 136 - 51 = 85 years. If the epoch\n// was 1900 then it could be as short as 136 - (2021 - 1900) = 136 - 121 =\n// 15 years. Hopefully your program won't need to run that long. :). To see,\n// by inspection, what your system's epoch is, simply print out a timestamp and\n// calculate how far back a timestamp of 0 would have occurred. Ex: convert\n// the timestamp to years and subtract that number of years from the present\n// year.\n timespec_get()"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44808/"
] |
361,371 | <p>This is quite a controversial topic, and before you say "no", is it really, really needed? </p>
<p>I have been programming for about 10 years, and I can't honestly say that I can recall a time where inheritance solved a problem that couldn't be solved another way. On the other hand I can recall many times when I used inheritance, because I felt like I had to or because I though I was clever and ended up paying for it.</p>
<p>I can't really see any circumstances where, from an implementation stand point, aggregation or another technique could not be used instead of inheritance. </p>
<p>My only caveat to this is that we would still allow inheritance of interfaces.</p>
<p>(Update)</p>
<p>Let's give an example of why it's needed instead of saying, "sometimes it's just needed." That really isn't helpful at all. Where is your proof?</p>
<p>(Update 2 Code Example)</p>
<p>Here's the classic shape example, more powerful, and more explicit IMO, without inheritance. It is almost never the case in the real world that something really "Is a" of something else. Almost always "Is Implemented in Terms of" is more accurate.</p>
<pre><code>public interface IShape
{
void Draw();
}
public class BasicShape : IShape
{
public void Draw()
{
// All shapes in this system have a dot in the middle except squares.
DrawDotInMiddle();
}
}
public class Circle : IShape
{
private BasicShape _basicShape;
public void Draw()
{
// Draw the circle part
DrawCircle();
_basicShape.Draw();
}
}
public class Square : IShape
{
private BasicShape _basicShape;
public void Draw()
{
// Draw the circle part
DrawSquare();
}
}
</code></pre>
| [
{
"answer_id": 361411,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": false,
"text": "Stream public virtual int Read(byte[] buffer, int index, int count)\n{\n}\n\npublic int ReadByte()\n{\n // note: this is only an approximation to the real implementation\n var buffer = new byte[1];\n if (this.Read(buffer, 0, 1) == 1)\n {\n return buffer[0];\n }\n\n return -1;\n}\n ReadByte StreamUtil DerivedStream public class DerivedStream : Stream\n{\n public override int Read(byte[] buffer, int index, int count)\n {\n // my read implementation\n }\n}\n StreamUtil public class DerivedStream : IStream\n{\n public int Read(byte[] buffer, int index, int count)\n {\n // my read implementation\n }\n\n public int ReadByte()\n {\n return StreamUtil.ReadByte(this);\n }\n}\n"
},
{
"answer_id": 361464,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "public interface IPerson { ... }\npublic interface IEmployee : IPerson { ... }\npublic class Employee : IEmployee\n{\n private Person _Person;\n ...\n\n public String FirstName\n {\n get { return _Person.FirstName; }\n set { _Person.FirstName = value; }\n }\n}\n public class Employee : IEmployee\n{\n private Person _Person implements IPerson;\n ...\n}\n"
},
{
"answer_id": 362075,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 2,
"selected": false,
"text": "// Alternative 1:\npublic class MyThread extends Thread {\n\n // Abstract method to implement from Thread\n // aka. \"template method\" (GoF design pattern)\n public void run() {\n // ...\n }\n}\n\n// Usage:\nMyThread t = new MyThread();\nt.start();\n // Alternative 2:\npublic class MyThread implements Runnable {\n // Method to implement from Runnable:\n public void run() {\n // ...\n }\n}\n\n// Usage:\nMyThread m = new MyThread();\nThread t = new Thread(m);\nt.start();\n// …or if you have a curious perversion towards one-liners\nThread t = new Thread(new MyThread());\nt.start();\n"
},
{
"answer_id": 362654,
"author": "Clint Miller",
"author_id": 38226,
"author_profile": "https://Stackoverflow.com/users/38226",
"pm_score": 3,
"selected": false,
"text": "public class C2 implements I {\n private I c1;\n\n public C2() {\n c1 = new C1();\n }\n\n public void m1() {\n // This is the method C2 is overriding.\n }\n\n public void m2() {\n c1.m2();\n }\n\n public void m3() {\n c1.m3();\n }\n\n ...\n\n public void m10() {\n c1.m10();\n }\n}\n public class C2 implements I(delegate to c1) {\n private I c1;\n\n public C2() {\n c1 = new C1();\n }\n\n public void m1() {\n // This is the method C2 is overriding.\n }\n}\n"
},
{
"answer_id": 362937,
"author": "Ed Marty",
"author_id": 36007,
"author_profile": "https://Stackoverflow.com/users/36007",
"pm_score": 1,
"selected": false,
"text": "Hashtable.hashcode(Object o)"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45365/"
] |
361,391 | <p>In a client-server system, is it considered good architecture for a server method to "ask the client" for more information? If so, what's the best way to design such a scenario? Is there a "pattern" for this?</p>
<p>For example, suppose the end user selects a set of records they want to delete in the client UI, then the client makes a "delete records" call to the server with the set of records as a parameter. Then the server finds a subset of those records which are "special" in some way and thus need to be confirmed by the user. Is it appropriate for the server to somehow "call back" to the client to a method called "confirm records" while still continuing the original call from the client to the server?</p>
<p>And what about more complex server calls that could require a long "dialog" between server and client?</p>
| [
{
"answer_id": 361419,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 1,
"selected": false,
"text": "I_RELLY_WANT_TO"
},
{
"answer_id": 361657,
"author": "rik.the.vik",
"author_id": 45570,
"author_profile": "https://Stackoverflow.com/users/45570",
"pm_score": 1,
"selected": true,
"text": "client code: \n special_records = server.deleteRecords(records)\n server.deleteSpecialRecords(special_records)\n\nserver code:\n def deleteRecords(records):\n special_records = detectSpecialRecords(records)\n reply(special_records)\n actuallyDeleteRecords(records - special_records)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16012/"
] |
361,443 | <p>I am trying to learn more about regular expressions I have one below that I believe finds cases where there is a missing close paren on a number up to 999 billion. The one below it I thought should do the same but I do not get similar results</p>
<pre><code> missingParenReg=re.compile(r"^\([$]*[0-9]{1,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[.]*[0-9]*[^)]$")
missingParenReg2=re.compile(r"^\([$]?([0-9]{1,3}[,]?)+[.]*[0-9]*[^)]$")
</code></pre>
<p>I think the second one says:
There must be an open paren to start<br>
There may or may not be as many as one dollar sign<br>
The next group must exist at least once but can exist an unlimited number of times<br>
The group should have at least one digit but may have as many as three<br>
The group may have as few as 0 and as many as 1 commas<br>
Following this group there may or may not be a decimal point<br>
If there is a decimal point it will be followed by as many as 0 but as many as uncounted occurences of digits<br>
At the end there should not be a closing paren.</p>
<p>I am trying to understand this magic stuff so I would appreciate a correction to my regex (if it can be corrected) in addition to a more elegant solution if you have it.</p>
| [
{
"answer_id": 361475,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "whether_paren_is_missing = (astring[0] == '(' and not astring[-1] == ')')\n import re\n\ncents = r\"(?:\\.\\d\\d)\" # cents \nre_dollar_amount = re.compile(r\"\"\"(?x)\n ^ # match at the very begining of the string\n \\$? # optional dollar sign\n (?: # followed by\n (?: # integer part \n 0 # zero\n | # or\n [1-9]\\d{,2} # 1 to 3 digits (no leading zero) \n (?: # followed by\n (?:,\\d{3})* # zero or more three-digits groups with commas \n | # or\n \\d* # zero or more digits without commas (no leading zero)\n )\n )\n (?:\\.|%(cents)s)? # optional f.p. part \n | # or\n %(cents)s # pure f.p. '$.01'\n )\n $ # match end of string\n \"\"\" % vars())\n"
},
{
"answer_id": 361485,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": -1,
"selected": false,
"text": "(123,,,\n"
},
{
"answer_id": 361512,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "(1,2,3,4 (12,34,56 (1234......5 (1234,.5 (123,456789,012 (01234 (123.4X [-+]?[$]?(0|[1-9]\\d*|[1-9]\\d{0,2}(,\\d{3})*)(\\.\\d+)? | (?!...) (?!\\([$\\d.,]+\\))"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30105/"
] |
361,455 | <p>I have a MySQL query structured as follows:</p>
<pre><code>SELECT time(c.start_time),
time(c.end_time),
time(c.end_time) - time(c.start_time) as 'opening_hours'
FROM my_shop c;
</code></pre>
<p>The data in start and end time is 1970-01-01 07:00:00 and 1970-01-01 19:00:00 respectively.</p>
<p>On my local machine this this query returns:</p>
<pre><code>| 07:00:00 | 19:00:00 | 12 |
</code></pre>
<p>However on a remote machine (production) it is returning</p>
<pre><code>| 07:00:00 | 19:00:00 | 120000 |
</code></pre>
<p>Any ideas as to why this might be happening and how to fix it? </p>
<p>Both sets of data are identical and too the best of my knowledge both MySQL installations are identical.</p>
<p>Any help is much appreciated.</p>
<p>Update: </p>
<p>It would seem that the versions of MySQL are slightly different: 5.0.27-community-nt versus 5.0.51b-community-nt. This is most probably the reason why.</p>
<p>djt has raised a good point in that Bill's solution does not take into account minutes. As well as this djt's solution is not quite what i need. </p>
<p>So i guess the question has morphed into how to subtract two times including minutes such that:</p>
<pre><code>1970-01-01 19:00:00 - 1970-01-01 07:00:00 = 12
1970-01-01 19:00:00 - 1970-01-01 07:30:00 = 11.5
1970-01-01 19:00:00 - 1970-01-01 07:45:00 = 11.25
</code></pre>
<p>etc.</p>
| [
{
"answer_id": 361582,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": true,
"text": "SELECT TIME(c.start_time),\n TIME(c.end_time),\n EXTRACT(HOUR FROM TIMEDIFF(TIME(c.end_time), TIME(c.start_time)))\n AS 'opening_hours' \nFROM my_shop c;\n"
},
{
"answer_id": 361586,
"author": "djt",
"author_id": 26677,
"author_profile": "https://Stackoverflow.com/users/26677",
"pm_score": 1,
"selected": false,
"text": "SELECT TIME(c.start_time),\n TIME(c.end_time),\n TIMEDIFF(TIME(c.end_time), TIME(c.start_time)) as 'opening_hours'\n\nFROM my_shop c;\n"
},
{
"answer_id": 361933,
"author": "abarax",
"author_id": 24390,
"author_profile": "https://Stackoverflow.com/users/24390",
"pm_score": 0,
"selected": false,
"text": "SELECT EXTRACT(HOUR FROM TIMEDIFF(TIME(c.end_time), TIME(c.start_time))) \n+ ((EXTRACT(MINUTE FROM TIMEDIFF(TIME(c.end_time), TIME(c.start_time))))/60)\nFROM my_shop c;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24390/"
] |
361,467 | <p>I am using jQuert .ajax function to call a page method. The site is using FormsAuthentication. So when an authentication ticket expires a call to the page method will obviously cause a redirect to the login page. </p>
<p>Now, the geniuses that wrote the System.Web.Handlers.ScriptModule decided that if for some reason a REST style call to a page method or a web service method, from JavaScript causes a 302 Redirect, they're going to just simply turn the response into a 401 Unauthorized. This causes a browser to popup a login UI that is totally misleading, as the user tries to type in their username and password, which means nothing, because FormsAuthentication is used. Finally, when the user clicks Cancel, the 401 comes through to the error handler. </p>
<p>So, the question is, how can one disable the browser's login UI prompt in any way? Some people on the web suggest to use a username and password in the XHR request, but it does not seem to work.</p>
| [
{
"answer_id": 361564,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 4,
"selected": true,
"text": " $.ajax({\n type: \"POST\",\n url: postUrl + \"/SomePageMethod\",\n data: \"{searchString:\\\"\" + escape(searchString) + \"\\\"}\",\n contentType: \"application/json; charset=utf-8\",\n beforeSend: function(xhr) {\n xhr.setRequestHeader(\"X-MicrosoftAjax\",\"Delta=true\");\n },\n dataType: \"json\",\n success: onSuccess,\n error: onError\n });\n\nfunction onError(xhr, e, textStatus) {\n var isAjaxRedirect = xhr.status == 200 && xhr.responseText.match(/pageRedirect/);\n if (isAjaxRedirect == \"pageRedirect\") {\n // forms authentication ticket expired\n location.href = \"a session timeout page, or a login page or whatever\";\n }\n}\n"
},
{
"answer_id": 23027735,
"author": "tomasofen",
"author_id": 1253788,
"author_profile": "https://Stackoverflow.com/users/1253788",
"pm_score": 1,
"selected": false,
"text": "$.ajax({\n type: \"POST\",\n url: postUrl + \"/SomePageMethod\",\n data: \"{searchString:\\\"\" + escape(searchString) + \"\\\"}\",\n contentType: \"application/json; charset=utf-8\",\n headers: { \"cache-control\": \"no-cache\", \"X-MicrosoftAjax\" : \"Delta=true\" },\n dataType: \"json\",\n success: onSuccess,\n error: onError\n });\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2788/"
] |
361,468 | <p>I'm looking for a way in .NET (2.0, C# in particular) for source code to trigger a debugging break as if a breakpoint was set at that point, without having to remember to set a specific breakpoint there in the debugger, and without interfering with production runtime.</p>
<p>Our code needs to swallow exceptions in production so we don't disrupt a client application that links to us, but I'm trying to set it up so that such errors will pop up to be analyzed if it happens to be running in a debugger, and otherwise will be safely ignored.</p>
<p>My attempt to use <code>Debug.Assert(false)</code> has been less than ideal, and I assume that <code>Debug.Fail()</code> would behave the same way. It should theoretically have no effect in production, and it does successfully stop when debugging, but by design there is (as far as I can tell) no way to continue execution if you want to ignore that error, like you could with an actual breakpoint, and like it would do in production where we swallow the error. It also apparently breaks evaluation of variable state because the debugger actually stops down in native system code and not in ours, so it's debugging help is limited. (Maybe I'm missing some way of getting back into things to look at the variables and so on where it happened. ???)</p>
<p>I was hoping for something like <code>Debug.Break()</code>, but it doesn't seem to exist (unless maybe in a later version of .NET?), and no other <code>Debug</code> methods seem applicable, either.</p>
<p><strong>Update:</strong> While ctacke's answer is the best match for what I was looking for, I have since also discovered a trick with Debug.Assert()--when running in the debugger--Pause the debugger, go to the code for the Debug.Assert call pending (highlighted in green because it is down in the framework code) and hit Step-Out (shift-F11), then hit Ignore in the assert dialog box. This will leave the debugger paused upon the return of the assert (and able to continue execution as if it hadn't occurred, because it was ignored). There may be other ways to do much the same thing (does hitting Retry do this more directly?), but this way was intuitive.</p>
| [
{
"answer_id": 361473,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 4,
"selected": false,
"text": "System.Diagnostics.Debugger.Break"
},
{
"answer_id": 361479,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 4,
"selected": false,
"text": "System.Diagnostics.Debugger.Break();\n System.Diagnostics.Debugger.Launch();\n"
},
{
"answer_id": 361483,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 8,
"selected": true,
"text": "if(System.Diagnostics.Debugger.IsAttached)\n System.Diagnostics.Debugger.Break();\n // Conditional(\"Debug\") means that calls to DebugBreak will only be\n // compiled when Debug is defined. DebugBreak will still be compiled\n // even in release mode, but the #if eliminates the code within it.\n // DebuggerHidden is so that, when the break happens, the call stack\n // is at the caller rather than inside of DebugBreak.\n [DebuggerHidden]\n [Conditional(\"DEBUG\")] \n void DebugBreak()\n {\n if(System.Diagnostics.Debugger.IsAttached)\n System.Diagnostics.Debugger.Break();\n }\n"
},
{
"answer_id": 8233678,
"author": "Aren Cambre",
"author_id": 425477,
"author_profile": "https://Stackoverflow.com/users/425477",
"pm_score": 1,
"selected": false,
"text": "Debug.Assert"
},
{
"answer_id": 44217909,
"author": "Serg",
"author_id": 1844247,
"author_profile": "https://Stackoverflow.com/users/1844247",
"pm_score": 3,
"selected": false,
"text": "#if DEBUG\n if (Debugger.IsAttached)\n Debugger.Break();\n#endif\n public static class DebugHelper\n{\n [DebuggerHidden]\n [Conditional(\"DEBUG\")]\n public static void Stop()\n {\n if (Debugger.IsAttached)\n Debugger.Break();\n }\n}\n DebugHelper.Stop();\n DebuggerHiddenAttribute Stop F11"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181460/"
] |
361,471 | <p>I have a web application with multiple web services. This web application has business and persistency layer. Is it possible to use separate log appender (log file) per web service?</p>
<p>This applies to web pages too. Essentially I want to separate my logs NOT based on the class or layer/namespace, but from point of entry, which can be web service or web page.</p>
| [
{
"answer_id": 361622,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 1,
"selected": false,
"text": "namespace log4net\n{\n public class LogManager\n {\n public static ILog GetLogger(string name);\n public static ILog GetLogger(Type type);\n }\n}\n public class MyApp \n{\n // Define a static logger variable so that it references the\n // Logger instance named \"MyApp\".\nprivate static readonly ILog log = LogManager.GetLogger(typeof(MyApp));\n\nstatic void Main(string[] args) \n{\n // Set up a simple configuration that logs on the console.\n BasicConfigurator.Configure();\n\n log.Info(\"Entering application.\");\n Bar bar = new Bar();\n bar.DoIt();\n log.Info(\"Exiting application.\");\n}\n}\n typeof"
},
{
"answer_id": 1195773,
"author": "Ali B",
"author_id": 16073,
"author_profile": "https://Stackoverflow.com/users/16073",
"pm_score": 1,
"selected": true,
"text": "<appender name=\"UiFileAppender\" type=\"log4net.Appender.RollingFileAppender\">\n <file value=\"Log1.log\" />\n <appendToFile value=\"true\" />\n <rollingStyle value=\"Size\" />\n <maxSizeRollBackups value=\"10\" />\n <maximumFileSize value=\"5MB\" />\n <staticLogFileName value=\"true\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date [%thread] %-5level %logger [%property{NDC}] - %message%newline\" />\n </layout>\n <filter type=\"log4net.Filter.PropertyFilter\">\n <Key value=\"channel\"/>\n <StringToMatch value=\"ui\" />\n <AcceptOnMatch value=\"true\" />\n </filter>\n <filter type=\"log4net.Filter.DenyAllFilter\" />\n</appender>\n<appender name=\"WsFileAppender\" type=\"log4net.Appender.RollingFileAppender\">\n <file value=\"Log1.log\" />\n <appendToFile value=\"true\" />\n <rollingStyle value=\"Size\" />\n <maxSizeRollBackups value=\"10\" />\n <maximumFileSize value=\"5MB\" />\n <staticLogFileName value=\"true\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date [%thread] %-5level %logger [%property{NDC}] - %message%newline\" />\n </layout>\n <filter type=\"log4net.Filter.PropertyFilter\">\n <Key value=\"channel\"/>\n <StringToMatch value=\"ws\" />\n <AcceptOnMatch value=\"true\" />\n </filter>\n <filter type=\"log4net.Filter.DenyAllFilter\" />\n</appender>\n log4net.GlobalContext.Properties[\"channel\"] = \"ui\";\n log4net.GlobalContext.Properties[\"channel\"] = \"ws\";\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16073/"
] |
361,477 | <p>Note: Using MySQL 4.0, which means no subqueries (at present).</p>
<p>I have 2 tables:</p>
<ul>
<li>A "user_details" table</li>
<li>A "skills" table, which has the user_id and a "skill_id", which maps to a predefined set of skills defined elsewhere.</li>
</ul>
<p>The current query allows an admin to search for users by selecting skills, and the query works in an OR fashion, eg:</p>
<pre><code>LEFT JOIN skills
ON (ud.user_id = skills.user_id)
WHERE skills.skill_id in (51, 52, 53, 54, 55)
GROUP BY ud.user_id
</code></pre>
<p>This returns too many records and thus I want this search field to work in an AND fashion, where a user must have ALL the selected skills to be returned in the search.</p>
<p>It may be possible to get MySQL upgraded if subqueries are the best option.</p>
<p>edit: Something to do with group by, count, having etc. Can you restrict a group by command with a requirement on how many matched rows you return? (eg 5 in this example).</p>
<p>edit2: Testing out:</p>
<pre><code>HAVING COUNT( * ) > 5
</code></pre>
| [
{
"answer_id": 361551,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "SELECT user_id\nFROM skills\nWHERE skill_id IN (51, 52, 53, 54, 55)\nGROUP BY user_id\nHAVING COUNT(*) = 5;\n"
},
{
"answer_id": 361667,
"author": "djt",
"author_id": 26677,
"author_profile": "https://Stackoverflow.com/users/26677",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM user_details \nJOIN skills USING (user_id) \nWHERE skill_id IN (51, 52, 53, 54, 55) \nGROUP BY user_id \nHAVING COUNT(*) = 5\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/361477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29854/"
] |
361,481 | <p>Modal dialogs are evil, but I keep reading "You should remove modal dialogs <i>when possible</i>"</p>
<p>When isn't it possible to remove modal dialogs? I mean, what are some truly modal tasks that force us to use evil modal dialogs?</p>
<p>The most common given example is the "Do you want to Save?" I think this is the problem of the concept of having the user hit Save instead of remembering that <b>user input is sacred</b>. If you just saved automatically with the ability to "undo" or have revisions, then you don't ever need ask the user if they want to save.</p>
<ul>
<li>"Are you sure you want to delete?" Undelete</li>
<li>"Are you sure you want to quit?" Why would you ask that? Are you that vain?</li>
</ul>
<p>Why do we ever need modal dialogs?</p>
<p><strong>EDIT</strong></p>
<p>Webs app don't count in my books, unless they write their own UI windowing system within the browser. Web apps don't have the same tools set as desktop apps.</p>
<p><strong>EDIT 2</strong></p>
<p>My question is slightly different than the one labeled as duplicate. I feel that there is no case that modal dialogs are the best solution. The referred question assumes there is such a case.</p>
<h3>Duplicate of: <a href="https://stackoverflow.com/questions/152938/when-is-modal-ui-acceptable">When Is Modal UI acceptable</a>?</h3>
| [
{
"answer_id": 361488,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 3,
"selected": false,
"text": "onbeforeunload"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21838/"
] |
361,487 | <p>What is the exact pixel size of one column when I used the columns attribute to determine a width of an ASP.NET textbox control?</p>
<pre><code><asp:TextBox id="MyTextBox" runat="server" columns="10" />
</code></pre>
| [
{
"answer_id": 361521,
"author": "Ryan Smith",
"author_id": 10420,
"author_profile": "https://Stackoverflow.com/users/10420",
"pm_score": 2,
"selected": true,
"text": "style=\"width: 250px;\"\n"
},
{
"answer_id": 361542,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": -1,
"selected": false,
"text": "style=\"width: 100%\"\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
361,490 | <p>I have a silverlight 2 app that has an ObservableCollection of a class from a separate assem/lib. When I set my ListBox.ItemsSource on that collection, and run it, I get the error code:</p>
<blockquote>
<p>4004 "System.ArgumentException: Value does not fall within the expected range."</p>
</blockquote>
<p>Here is part of the code:</p>
<pre><code>public partial class Page : UserControl
{
ObservableCollection<Some.Lib.Owner> ooc;
public Page()
{
ooc = new ObservableCollection<Some.Lib.Owner>();
Some.Lib.Owner o1 = new Some.Lib.Owner() { FirstName = "test1" };
Some.Lib.Owner o2 = new Some.Lib.Owner() { FirstName = "test2" };
Some.Lib.Owner o3 = new Some.Lib.Owner() { FirstName = "test3" };
ooc.Add(o1);
ooc.Add(o2);
ooc.Add(o3);
InitializeComponent();
lb1.ItemsSource = ooc;
}
}
</code></pre>
<p>But when I create the Owner class within this same project, everything works fine.
Is there some security things going on behind the scenes? Also, I'm using the generate a html page option and not the aspx option, when I created this Silverlight 2 app.</p>
| [
{
"answer_id": 65333400,
"author": "ΩmegaMan",
"author_id": 285795,
"author_profile": "https://Stackoverflow.com/users/285795",
"pm_score": 0,
"selected": false,
"text": "entity Add Existing Item... shift alt A Add Add as link"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33324/"
] |
361,500 | <p>I have a situation where I need to process large (many GB's) amounts of data as such:</p>
<ol>
<li>build a large string by appending many smaller (C char*) strings</li>
<li>trim the string</li>
<li>convert the string into a C++ const std::string for processing (read only)</li>
<li>repeat</li>
</ol>
<p>The data in each iteration are independent.</p>
<p>My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem.</p>
<p>Is there a way to convert a C string (char*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data?</p>
<p>Alternatively, could I use stringstreams or something similar to re-use a large buffer?</p>
<p><strong>Edit:</strong> Thanks for the answers, for clarity, I think a revised question would be:</p>
<p><em>How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.</em></p>
| [
{
"answer_id": 361597,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 5,
"selected": true,
"text": "string::reserve(size_t) reserve"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40175/"
] |
361,529 | <p>I'm using Spring, but this question applies to all JSP-controller type designs.</p>
<p>The JSP page references data (using tags) which is populated by the corresponding controller. My question is, where is the appropriate place to perform formatting, in JSP or the controller?</p>
<p>So far I've been preparing the data by formatting it in my controller.</p>
<pre><code>public class ViewPersonController extends org.springframework.web.servlet.mvc.AbstractController
{
private static final Format MY_DATE_FORMAT = new SimpleDateFormat(...);
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
{
Person person = get person from backing service layer or database
Map properties = new HashMap();
// No formatting required, name is a String
properties.put("name", person.getName());
// getBirthDate() returns Date and is formatted by a Format
properties.put("birthDate", MY_DATE_FORMAT.format(person.getBirthDate()));
// latitude and longitude are separate fields in Person, but in the UI it's one field
properties.put("location", person.getLatitude() + ", " + person.getLongitude());
return new ModelAndView("viewPerson", "person", properties);
}
}
</code></pre>
<p>The JSP file would look something like:</p>
<pre><code>Name = <c:out value="${person. name}" /><br>
Birth Date = <c:out value="${person. birthDate}" /><br>
Location = <c:out value="${person. location}" /><br>
</code></pre>
<p>I know that JSP does have some provisions for formatting,</p>
<pre><code><%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<fmt:formatDate type="date" value="${person. birthDate}" />
</code></pre>
<p>But this only works with Java's <code>java.util.Format</code>. What if I need more complex or computed values. In such a case putting the code in the JSP would be cumbersome (and ugly).</p>
<p>I'm curious if this is following the spirit Spring/JSP/MVC. In other words, is the controller part of the view? Where is the preferred place to perform view related formatting? Should my controller just be returning the object (Person) instead of a Map of formatted values?</p>
| [
{
"answer_id": 361831,
"author": "bpapa",
"author_id": 543,
"author_profile": "https://Stackoverflow.com/users/543",
"pm_score": 0,
"selected": false,
"text": "public class Person {\n public String getLocation() {\n return this.latitude.concat(\", \").concat(this.longitude);\n }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
361,583 | <p><b>Duplicate of: <a href="https://stackoverflow.com/questions/255214/when-should-i-use-the-visitor-design-pattern">When Should I Use The Visitor Design Pattern</a></b></p>
<p>Why would someone want to use the visitor pattern? I've read a couple of articles, but I'm not getting something.</p>
<p>If I need a function to bill a custom, I could use</p>
<pre><code>Custom.Accept(BillVisitor)
</code></pre>
<p>or something like</p>
<pre><code>Bill(Customer)
</code></pre>
<p>The second is less complex, and the Bill function is still separated from the Customer class. So why would I want to use the visitor pattern?</p>
| [
{
"answer_id": 362186,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 4,
"selected": false,
"text": "void accept(BillVisitor visitor) { visitor.bill(this); } // java syntax\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,592 | <p>Imagine I use the .NET graphic classes to draw a rectangle.</p>
<p>How could I then assign an event so that if the user clicks a certain point, or a certain point range, something happens (a click event handler)?</p>
<p>I was reading CLR via C# and the event section, and I thought of this scenario from what I had read.</p>
<p>A code example of this would really improve my understanding of events in C#/.NET.</p>
<p>Thanks</p>
| [
{
"answer_id": 361607,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "public partial class Form1 : Form\n{\n private Rectangle rect;\n private Pen pen = Pens.Black;\n\n public Form1()\n {\n InitializeComponent();\n rect = new Rectangle(10, 10, Width - 30, Height - 60);\n Click += Form1_Click;\n }\n\n protected override void OnPaint(PaintEventArgs e) \n {\n base.OnPaint(e);\n e.Graphics.DrawRectangle(pen, rect);\n }\n\n void Form1_Click(object sender, EventArgs e)\n {\n Point cursorPos = this.PointToClient(Cursor.Position);\n if (rect.Contains(cursorPos)) \n {\n pen = Pens.Red;\n }\n else\n {\n pen = Pens.Black;\n }\n Invalidate();\n }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
361,633 | <p>VStudio ASP.NET gives the following message: </p>
<pre><code>Attribute 'bgcolor' is considered outdated. A newer construct is recommended.
</code></pre>
<p>What is the recommended construct?</p>
<p><code>bgcolor</code> is within a <code><td></code> element.<br>
Another related message is : </p>
<pre><code>Attribute 'bordercolor' is not a valid attribute of element 'table'.
</code></pre>
<p>Does anyone know where I might find the newer replacements?</p>
| [
{
"answer_id": 361642,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": false,
"text": "background-color border-color <table style=\"border-color: #ffffff;\">\n\n<td style=\"background-color: #000000;\">\n"
},
{
"answer_id": 361643,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 6,
"selected": true,
"text": "BGColor body {\n background-color : #ffffff;\n}\n <table>\n\n<tr id=\"row1\">\n <th>Header 1</th> <td>Cell 1</td> <td>Cell 2</td>\n</tr>\n<tr id=\"row2\">\n <th>Header 2</th> <td>Cell 3</td> <td>Cell 4</td>\n</tr>\n<tr id=\"row3\">\n <th>Header 3</th> <td>Cell 5</td> <td>Cell 6</td>\n</tr>\n</table>\n th { text-align: center; font-weight: bold; vertical-align: baseline }\n\ntd { vertical-align: middle }\n\ntable { border-collapse: collapse; background-color: #ffffff }\ntr#row1 { border-top: 3px solid blue }\ntr#row2 { border-top: 1px solid black }\ntr#row3 { border-top: 1px solid black }\n <link rel=\"stylesheet\" href=\"style.css\" TYPE=\"text/css\" media=\"screen\">\n"
},
{
"answer_id": 361644,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 2,
"selected": false,
"text": ".MyTable {\n border: solid 2px #000;\n}\n\n.MySpecialCell {\n background-color: #F00;\n}\n <table class=\"MyTable\">\n <tr>\n <td class=\"MySpecialCell\">...</td>\n </tr>\n</table>\n"
},
{
"answer_id": 362031,
"author": "danieltalsky",
"author_id": 22452,
"author_profile": "https://Stackoverflow.com/users/22452",
"pm_score": 2,
"selected": false,
"text": "<body style=\"background-color: #ccc;\">\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1682/"
] |
361,635 | <p>I need to debug JavaScript in Internet Explorer 7.</p>
<p>Unfortunately, its default debugger doesn't provide me with much information. It tells me the page that the error showed up on (not the specific script) and gives me a line number. I don't know if that is related to my problem.</p>
<p>It'd be nice if it could narrow down the error to a line number on a specific script (like Firebug can).</p>
<p>Is there an addon to debug JavaScript in IE7 like Firebug does in Firefox?</p>
<p>Thank you!</p>
<h3>See also:</h3>
<p><a href="https://stackoverflow.com/questions/56615/does-ie7-have-a-developer-mode-or-plugin-like-firefoxchromesafari">Does IE7 have a “developer mode” or plugin like Firefox/Chrome/Safari?</a></p>
| [
{
"answer_id": 2139008,
"author": "Marc",
"author_id": 259168,
"author_profile": "https://Stackoverflow.com/users/259168",
"pm_score": 5,
"selected": false,
"text": "javascript:var firebug=document.createElement('script');firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js');document.body.appendChild(firebug);(function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug);\n"
},
{
"answer_id": 6750556,
"author": "Jose",
"author_id": 101689,
"author_profile": "https://Stackoverflow.com/users/101689",
"pm_score": 1,
"selected": false,
"text": "debugger;\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
361,648 | <p>My main experience is with C && C++, so I'd prefer to remain with them. I don't want to use anything like QT, GTK, or wxWidgets or any tool kits. I'd like to learn native programming and this sort of defeats the purpose. With that in mind I'd also like to avoid Java.</p>
<p>I understand gnome and xfce and KDE and such are all Desktop Environments for Linux, and the base installed typically is X (Xorg). When coding for Linux, do you code for X, or for the desktop environment? Is there a standard Linux header for this (like win32 has windows.h) for Linux? or is it different coding methods for every desktop environment?</p>
<p>any help is greatly appreciated.</p>
| [
{
"answer_id": 6971261,
"author": "luser droog",
"author_id": 733077,
"author_profile": "https://Stackoverflow.com/users/733077",
"pm_score": 2,
"selected": false,
"text": "XFlush()"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36457/"
] |
361,661 | <p>I have a database table (named Topics) which includes these fields :</p>
<ol>
<li>topicId </li>
<li>name</li>
<li>parentId</li>
</ol>
<p>and by using them I wanna populate a TreeView in c#. How can I do that ?</p>
<p>Thanks in advance...</p>
| [
{
"answer_id": 361678,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 5,
"selected": true,
"text": "//In Page load\nforeach (DataRow row in topics.Rows)\n{\n TreeNode node = new TreeNode(dr[\"name\"], dr[\"topicId\"])\n node.PopulateOnDemand = true;\n\n TreeView1.Nodes.Add(node);\n }\n ///\n protected void PopulateNode(Object sender, TreeNodeEventArgs e)\n {\n string topicId = e.Node.Value;\n //select from topic where parentId = topicId.\n foreach (DataRow row in topics.Rows)\n {\n TreeNode node = new TreeNode(dr[\"name\"], dr[\"topicId\"])\n node.PopulateOnDemand = true;\n\n e.Node.ChildNodes.Add(node);\n }\n\n }\n"
},
{
"answer_id": 361721,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 3,
"selected": false,
"text": "foreach (DataRow row in topicsWithOutParents.Rows)\n{\n TreeNode node = New TreeNode(... whatever);\n DataSet childNodes = GetRowsWhereParentIDEquals(row[\"topicId\"]);\n foreach (DataRow child in childNodes.Rows)\n { \n Treenode childNode = new TreeNode(..Whatever);\n node.Nodes.add(childNode);\n }\n Tree.Nodes.Add(node);\n}\n"
},
{
"answer_id": 4597708,
"author": "MAK",
"author_id": 520109,
"author_profile": "https://Stackoverflow.com/users/520109",
"pm_score": 3,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n DataSet ds = RunQuery(\"Select topicid,name from Topics where Parent_ID IS NULL\");\n for (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n { \n TreeNode root = new TreeNode(ds.Tables[0].Rows[i][1].ToString(),ds.Tables[0].Rows[i][0].ToString());\n root.SelectAction = TreeNodeSelectAction.Expand;\n CreateNode(root);\n TreeView1.Nodes.Add(root);\n }\n\n\n\n}\nvoid CreateNode(TreeNode node)\n{\n DataSet ds = RunQuery(\"Select topicid, name from Category where Parent_ID =\" + node.Value);\n if (ds.Tables[0].Rows.Count == 0)\n {\n return;\n }\n for (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n {\n TreeNode tnode = new TreeNode(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());\n tnode.SelectAction = TreeNodeSelectAction.Expand;\n node.ChildNodes.Add(tnode);\n CreateNode(tnode);\n }\n\n}\nDataSet RunQuery(String Query)\n{\n DataSet ds = new DataSet();\n String connStr = \"???\";//write your connection string here;\n using (SqlConnection conn = new SqlConnection(connStr))\n {\n SqlCommand objCommand = new SqlCommand(Query, conn);\n SqlDataAdapter da = new SqlDataAdapter(objCommand);\n da.Fill(ds);\n da.Dispose();\n }\n return ds;\n}\n"
},
{
"answer_id": 5621873,
"author": "duc14s",
"author_id": 375277,
"author_profile": "https://Stackoverflow.com/users/375277",
"pm_score": 3,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n if (!Page.IsPostBack)\n PopulateRootLevel();\n}\n\n\nprivate void PopulateRootLevel()\n{\n SqlConnection objConn = new SqlConnection(connStr);\n SqlCommand objCommand = new SqlCommand(@\"select FoodCategoryID,FoodCategoryName,(select count(*) FROM FoodCategories WHERE ParentID=c.FoodCategoryID) childnodecount FROM FoodCategories c where ParentID IS NULL\", objConn);\n SqlDataAdapter da = new SqlDataAdapter(objCommand);\n DataTable dt = new DataTable();\n da.Fill(dt);\n PopulateNodes(dt, TreeView2.Nodes);\n}\n\nprivate void PopulateSubLevel(int parentid, TreeNode parentNode)\n{\n SqlConnection objConn = new SqlConnection(connStr);\n SqlCommand objCommand = new SqlCommand(@\"select FoodCategoryID,FoodCategoryName,(select count(*) FROM FoodCategories WHERE ParentID=sc.FoodCategoryID) childnodecount FROM FoodCategories sc where ParentID=@parentID\", objConn);\n objCommand.Parameters.Add(\"@parentID\", SqlDbType.Int).Value = parentid;\n SqlDataAdapter da = new SqlDataAdapter(objCommand);\n DataTable dt = new DataTable();\n da.Fill(dt);\n PopulateNodes(dt, parentNode.ChildNodes);\n}\n\n\nprotected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)\n{\n PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);\n}\n\nprivate void PopulateNodes(DataTable dt, TreeNodeCollection nodes)\n{\n foreach (DataRow dr in dt.Rows)\n {\n TreeNode tn = new TreeNode();\n tn.Text = dr[\"FoodCategoryName\"].ToString();\n tn.Value = dr[\"FoodCategoryID\"].ToString();\n nodes.Add(tn);\n\n //If node has child nodes, then enable on-demand populating\n tn.PopulateOnDemand = ((int)(dr[\"childnodecount\"]) > 0);\n }\n}\n"
},
{
"answer_id": 51242676,
"author": "S.Mohamed",
"author_id": 9293068,
"author_profile": "https://Stackoverflow.com/users/9293068",
"pm_score": 1,
"selected": false,
"text": " //dtTree should be accessible in both page load and AddNodes()\n //DocsMenu is the treeview Id\n DataTable dtTree = new DataTable(); \n//declare your connection string\n protected void Page_Load(object sender, EventArgs e)\n {\n //DataTable dtTree = new DataTable();\n using (con)\n {\n con.Open();\n\n string sQuery = \"Select topicId,parentid,name from tbl_topicMaster\";\n SqlCommand cmd = new SqlCommand(sQuery, con);\n cmd.CommandType = CommandType.Text;\n SqlDataAdapter da = new SqlDataAdapter(cmd);\n da.Fill(dtTree);\n da.Dispose();\n con.Close();\n }\n\n AddNodes(-1, DocsMenu.Nodes);\n }\n\n\n\n\n void AddNodes(int id, TreeNodeCollection tn)\n {\n foreach (DataRow dr in dtTree.Select(\"parentid= \" + id))\n {\n TreeNode sub = new TreeNode(dr[\"name\"].ToString(), dr[\"topicId\"].ToString());\n tn.Add(sub);\n AddNodes(Convert.ToInt32(sub.Value), sub.ChildNodes);\n }\n }\n <asp:TreeView ID=\"DocsMenu\" runat=\"server\" ImageSet=\"BulletedList\" \n NodeIndent=\"15\" > \n <HoverNodeStyle Font-Underline=\"True\" ForeColor=\"#6666AA\" />\n <NodeStyle Font-Names=\"Tahoma\" Font-Size=\"8pt\" ForeColor=\"Black\" HorizontalPadding=\"2px\" \n NodeSpacing=\"0px\" VerticalPadding=\"2px\"></NodeStyle> \n <ParentNodeStyle Font-Bold=\"False\" /> \n <SelectedNodeStyle BackColor=\"#B5B5B5\" Font-Underline=\"False\" HorizontalPadding=\"0px\" \n VerticalPadding=\"0px\" />\n </asp:TreeView> \n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44852/"
] |
361,675 | <p>I'm trying to get started with unit testing in Python and I was wondering if someone could explain the advantages and disadvantages of doctest and unittest. </p>
<p>What conditions would you use each for?</p>
| [
{
"answer_id": 361683,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "doctest doctest unittest"
},
{
"answer_id": 361788,
"author": "davidavr",
"author_id": 8247,
"author_profile": "https://Stackoverflow.com/users/8247",
"pm_score": 3,
"selected": false,
"text": "doctest DoctTestSuite DocFileSuite"
},
{
"answer_id": 13722080,
"author": "rahmu",
"author_id": 403401,
"author_profile": "https://Stackoverflow.com/users/403401",
"pm_score": 3,
"selected": false,
"text": "unittest doctest unittest doctest"
},
{
"answer_id": 16078267,
"author": "Harsh",
"author_id": 1780891,
"author_profile": "https://Stackoverflow.com/users/1780891",
"pm_score": 2,
"selected": false,
"text": "Doctest def convert():\n \"\"\"\n >>> convert()\n '\\xe0\\xa4\\x95'\n \"\"\"\n a = '\\xe0\\xa4\\x95'\n return a\nimport doctest\ndoctest.testmod()\n **********************************************************************\nFile \"hindi.py\", line 3, in __main__.convert\nFailed example:\n convert()\nExpected:\n 'क'\nGot:\n '\\xe0\\xa4\\x95'\n**********************************************************************\n1 items had failures:\n 1 of 1 in __main__.convert\n***Test Failed*** 1 failures. \n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44133/"
] |
361,681 | <p>I need a reasonably smart algorithm to come up with "nice" grid lines for a graph (chart).</p>
<p>For example, assume a bar chart with values of 10, 30, 72 and 60. You know:</p>
<p>Min value: 10
Max value: 72
Range: 62</p>
<p>The first question is: what do you start from? In this case, 0 would be the intuitive value but this won't hold up on other data sets so I'm guessing:</p>
<p>Grid min value should be either 0 or a "nice" value lower than the min value of the data in range. Alternatively, it can be specified.</p>
<p>Grid max value should be a "nice" value above the max value in the range. Alternatively, it can be specified (eg you might want 0 to 100 if you're showing percentages, irrespective of the actual values).</p>
<p>The number of grid lines (ticks) in the range should be either specified or a number within a given range (eg 3-8) such that the values are "nice" (ie round numbers) and you maximise use of the chart area. In our example, 80 would be a sensible max as that would use 90% of the chart height (72/80) whereas 100 would create more wasted space.</p>
<p>Anyone know of a good algorithm for this? Language is irrelevant as I'll implement it in what I need to.</p>
| [
{
"answer_id": 361687,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 5,
"selected": false,
"text": "import math\n\ndef BestTick(largest, mostticks):\n minimum = largest / mostticks\n magnitude = 10 ** math.floor(math.log(minimum, 10))\n residual = minimum / magnitude\n if residual > 5:\n tick = 10 * magnitude\n elif residual > 2:\n tick = 5 * magnitude\n elif residual > 1:\n tick = 2 * magnitude\n else:\n tick = magnitude\n return tick\n import bisect\n\ndef BestTick2(largest, mostticks):\n minimum = largest / mostticks\n magnitude = 10 ** math.floor(math.log(minimum, 10))\n residual = minimum / magnitude\n # this table must begin with 1 and end with 10\n table = [1, 1.5, 2, 3, 5, 7, 10]\n tick = table[bisect.bisect_right(table, residual)] if residual < 10 else 10\n return tick * magnitude\n"
},
{
"answer_id": 361694,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 5,
"selected": false,
"text": "range = max - min; \nexponent = int(log(range)); // See comment below.\nmagnitude = pow(10, exponent);\n value_per_division = magnitude / subdivisions;\n int()"
},
{
"answer_id": 545960,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 4,
"selected": false,
"text": "public static class AxisUtil\n{\n public static float CalcStepSize(float range, float targetSteps)\n {\n // calculate an initial guess at step size\n var tempStep = range/targetSteps;\n\n // get the magnitude of the step size\n var mag = (float)Math.Floor(Math.Log10(tempStep));\n var magPow = (float)Math.Pow(10, mag);\n\n // calculate most significant digit of the new step size\n var magMsd = (int)(tempStep/magPow + 0.5);\n\n // promote the MSD to either 1, 2, or 5\n if (magMsd > 5)\n magMsd = 10;\n else if (magMsd > 2)\n magMsd = 5;\n else if (magMsd > 1)\n magMsd = 2;\n\n return magMsd*magPow;\n }\n}\n"
},
{
"answer_id": 15071978,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 3,
"selected": false,
"text": "var calcStepSize = function(range, targetSteps)\n{\n // calculate an initial guess at step size\n var tempStep = range / targetSteps;\n\n // get the magnitude of the step size\n var mag = Math.floor(Math.log(tempStep) / Math.LN10);\n var magPow = Math.pow(10, mag);\n\n // calculate most significant digit of the new step size\n var magMsd = Math.round(tempStep / magPow + 0.5);\n\n // promote the MSD to either 1, 2, or 5\n if (magMsd > 5.0)\n magMsd = 10.0;\n else if (magMsd > 2.0)\n magMsd = 5.0;\n else if (magMsd > 1.0)\n magMsd = 2.0;\n\n return magMsd * magPow;\n};\n"
},
{
"answer_id": 18049477,
"author": "Gleno",
"author_id": 427673,
"author_profile": "https://Stackoverflow.com/users/427673",
"pm_score": 1,
"selected": false,
"text": "ndex float findNiceDelta(float maxvalue, int count)\n{\n float step = maxvalue/count,\n order = powf(10, floorf(log10(step))),\n delta = (int)(step/order + 0.5);\n\n static float ndex[] = {1, 1.5, 2, 2.5, 5, 10};\n static int ndexLenght = sizeof(ndex)/sizeof(float);\n for(int i = ndexLenght - 2; i > 0; --i)\n if(delta > ndex[i]) return ndex[i + 1] * order;\n return delta*order;\n}\n"
},
{
"answer_id": 19181778,
"author": "Museful",
"author_id": 827280,
"author_profile": "https://Stackoverflow.com/users/827280",
"pm_score": 0,
"selected": false,
"text": "tickSize <- function(range,minCount){\n logMaxTick <- log10(range/minCount)\n exponent <- floor(logMaxTick)\n mantissa <- 10^(logMaxTick-exponent)\n af <- c(1,2,5) # allowed factors\n mantissa <- af[findInterval(mantissa,af)]\n return(mantissa*10^exponent)\n}\n"
},
{
"answer_id": 22848419,
"author": "JFS",
"author_id": 1867590,
"author_profile": "https://Stackoverflow.com/users/1867590",
"pm_score": 2,
"selected": false,
"text": "- (NSArray*)niceAxis:(double)minValue :(double)maxValue\n{\n double min_ = 0, max_ = 0, min = minValue, max = maxValue, power = 0, factor = 0, tickWidth, minAxisValue = 0, maxAxisValue = 0;\n NSArray *factorArray = [NSArray arrayWithObjects:@\"0.0f\",@\"1.2f\",@\"2.5f\",@\"5.0f\",@\"10.0f\",nil];\n NSArray *scalarArray = [NSArray arrayWithObjects:@\"0.2f\",@\"0.2f\",@\"0.5f\",@\"1.0f\",@\"2.0f\",nil];\n\n // calculate x-axis nice scale and ticks\n // 1. min_\n if (min == 0) {\n min_ = 0;\n }\n else if (min > 0) {\n min_ = MAX(0, min-(max-min)/100);\n }\n else {\n min_ = min-(max-min)/100;\n }\n\n // 2. max_\n if (max == 0) {\n if (min == 0) {\n max_ = 1;\n }\n else {\n max_ = 0;\n }\n }\n else if (max < 0) {\n max_ = MIN(0, max+(max-min)/100);\n }\n else {\n max_ = max+(max-min)/100;\n }\n\n // 3. power\n power = log(max_ - min_) / log(10);\n\n // 4. factor\n factor = pow(10, power - floor(power));\n\n // 5. nice ticks\n for (NSInteger i = 0; factor > [[factorArray objectAtIndex:i]doubleValue] ; i++) {\n tickWidth = [[scalarArray objectAtIndex:i]doubleValue] * pow(10, floor(power));\n }\n\n // 6. min-axisValues\n minAxisValue = tickWidth * floor(min_/tickWidth);\n\n // 7. min-axisValues\n maxAxisValue = tickWidth * floor((max_/tickWidth)+1);\n\n // 8. create NSArray to return\n NSArray *niceAxisValues = [NSArray arrayWithObjects:[NSNumber numberWithDouble:minAxisValue], [NSNumber numberWithDouble:maxAxisValue],[NSNumber numberWithDouble:tickWidth], nil];\n\n return niceAxisValues;\n}\n NSArray *niceYAxisValues = [self niceAxis:-maxy :maxy];\n double minYAxisValue = [[niceYAxisValues objectAtIndex:0]doubleValue];\ndouble maxYAxisValue = [[niceYAxisValues objectAtIndex:1]doubleValue];\ndouble ticksYAxis = [[niceYAxisValues objectAtIndex:2]doubleValue];\n NSInteger maxNumberOfTicks = 9;\nNSInteger numberOfTicks = valueXRange / ticksXAxis;\nNSInteger newNumberOfTicks = floor(numberOfTicks / (1 + floor(numberOfTicks/(maxNumberOfTicks+0.5))));\ndouble newTicksXAxis = ticksXAxis * (1 + floor(numberOfTicks/(maxNumberOfTicks+0.5)));\n"
},
{
"answer_id": 26146210,
"author": "Gregor",
"author_id": 1163563,
"author_profile": "https://Stackoverflow.com/users/1163563",
"pm_score": 2,
"selected": false,
"text": "public class AxisAssists\n{\n public double Tick { get; private set; }\n\n public AxisAssists(double aTick)\n {\n Tick = aTick;\n }\n public AxisAssists(double range, int mostticks)\n {\n var minimum = range / mostticks;\n var magnitude = Math.Pow(10.0, (Math.Floor(Math.Log(minimum) / Math.Log(10))));\n var residual = minimum / magnitude;\n if (residual > 5)\n {\n Tick = 10 * magnitude;\n }\n else if (residual > 2)\n {\n Tick = 5 * magnitude;\n }\n else if (residual > 1)\n {\n Tick = 2 * magnitude;\n }\n else\n {\n Tick = magnitude;\n }\n }\n\n public double GetClosestTickBelow(double v)\n {\n return Tick* Math.Floor(v / Tick);\n }\n public double GetClosestTickAbove(double v)\n {\n return Tick * Math.Ceiling(v / Tick);\n }\n}\n double tickX = new AxisAssists(aMaxX - aMinX, 8).Tick;\n"
},
{
"answer_id": 35254002,
"author": "grabantot",
"author_id": 2277240,
"author_profile": "https://Stackoverflow.com/users/2277240",
"pm_score": 0,
"selected": false,
"text": "(max-min)/gridLinesNumber var ceilAbs = function(num, to, bias) {\n if (to == undefined) to = [-2, -5, -10]\n if (bias == undefined) bias = 0\n var numAbs = Math.abs(num) - bias\n var exp = Math.floor( Math.log10(numAbs) )\n\n if (typeof to == 'number') {\n return Math.sign(num) * to * Math.ceil(numAbs/to) + bias\n }\n\n var mults = to.filter(function(value) {return value > 0})\n to = to.filter(function(value) {return value < 0}).map(Math.abs)\n var m = Math.abs(numAbs) * Math.pow(10, -exp)\n var mRounded = Infinity\n\n for (var i=0; i<mults.length; i++) {\n var candidate = mults[i] * Math.ceil(m / mults[i])\n if (candidate < mRounded)\n mRounded = candidate\n }\n for (var i=0; i<to.length; i++) {\n if (to[i] >= m && to[i] < mRounded)\n mRounded = to[i]\n }\n return Math.sign(num) * mRounded * Math.pow(10, exp) + bias\n}\n ceilAbs(number, [0.5]) 301573431.1193228 -> 350000000\n14127.786597236991 -> 15000\n-63105746.17236853 -> -65000000\n-718854.2201183736 -> -750000\n-700660.340487957 -> -750000\n0.055717507097870114 -> 0.06\n0.0008068701205775142 -> 0.00085\n-8.66660070605576 -> -9\n-400.09256079792976 -> -450\n0.0011740548815578223 -> 0.0015\n-5.3003294346854085e-8 -> -6e-8\n-0.00005815960629843176 -> -0.00006\n-742465964.5184875 -> -750000000\n-81289225.90985894 -> -85000000\n0.000901771713513881 -> 0.00095\n-652726598.5496342 -> -700000000\n-0.6498901364393532 -> -0.65\n0.9978325804695487 -> 1\n5409.4078950583935 -> 5500\n26906671.095639467 -> 30000000\n"
},
{
"answer_id": 48053010,
"author": "MichaelLo",
"author_id": 2471009,
"author_profile": "https://Stackoverflow.com/users/2471009",
"pm_score": 0,
"selected": false,
"text": "steps = [numpy.round(x) for x in np.linspace(min, max, num=num_of_steps)]\n"
},
{
"answer_id": 65253271,
"author": "SuperSecretAndNotSafeFromWork",
"author_id": 6129842,
"author_profile": "https://Stackoverflow.com/users/6129842",
"pm_score": 0,
"selected": false,
"text": "func getMaxMinIntervals(max float64, min float64, forcePlotZero bool) (maxRounded float64, minRounded float64, intervalCount float64, intervalSize float64) {\n\n//STEP 1: start off determining the maxRounded value for the axis\nprecision := 0.0\nprecisionDampener := 0.0 //adjusts to prevent 235 going to 300, instead dampens the scaling to get 240\nepsilon := 0.0000001\nif math.Abs(max) >= 0 && math.Abs(max) < 2 {\n precision = math.Floor(-math.Log10(epsilon + math.Abs(max) - math.Floor(math.Abs(max)))) //counting number of zeros between decimal point and rightward digits\n precisionDampener = 1\n precision = precision + precisionDampener\n} else if math.Abs(max) >= 2 && math.Abs(max) < 100 {\n precision = math.Ceil(math.Log10(math.Abs(max)+1)) * -1 //else count number of digits before decimal point\n precisionDampener = 1\n precision = precision + precisionDampener\n} else {\n precision = math.Ceil(math.Log10(math.Abs(max)+1)) * -1 //else count number of digits before decimal point\n precisionDampener = 2\n if forcePlotZero == true {\n precisionDampener = 1\n }\n precision = precision + precisionDampener\n}\n\nuseThisFactorForIntervalCalculation := 0.0 // this is needed because intervals are calculated from the max value with a zero origin, this uses range for min - max\nif max < 0 {\n maxRounded = (math.Floor(math.Abs(max)*(math.Pow10(int(precision)))) / math.Pow10(int(precision)) * -1)\n useThisFactorForIntervalCalculation = (math.Floor(math.Abs(max)*(math.Pow10(int(precision)))) / math.Pow10(int(precision))) + ((math.Ceil(math.Abs(min)*(math.Pow10(int(precision)))) / math.Pow10(int(precision))) * -1)\n} else {\n maxRounded = math.Ceil(max*(math.Pow10(int(precision)))) / math.Pow10(int(precision))\n useThisFactorForIntervalCalculation = maxRounded\n}\n\nminNumberOfIntervals := 2.0\nmaxNumberOfIntervals := 19.0\nintervalSize = 0.001\nintervalCount = minNumberOfIntervals\n\n//STEP 2: get interval size (the step size on the axis)\nfor {\n if math.Abs(useThisFactorForIntervalCalculation)/intervalSize < minNumberOfIntervals || math.Abs(useThisFactorForIntervalCalculation)/intervalSize > maxNumberOfIntervals {\n intervalSize = intervalSize * 10\n } else {\n break\n }\n}\n\n//STEP 3: check that intervals are not too large, safety for max and min values that are close together (240, 220 etc)\nfor {\n if max-min < intervalSize {\n intervalSize = intervalSize / 10\n } else {\n break\n }\n}\n\n//STEP 4: now we can get minRounded by adding the interval size to 0 till we get to the point where another increment would make cumulative increments > min, opposite for negative in\nminRounded = 0.0\n\nif min >= 0 {\n for {\n if minRounded < min {\n minRounded = minRounded + intervalSize\n } else {\n minRounded = minRounded - intervalSize\n break\n }\n }\n} else {\n minRounded = maxRounded //keep going down, decreasing by the interval size till minRounded < min\n for {\n if minRounded > min {\n minRounded = minRounded - intervalSize\n\n } else {\n break\n }\n }\n}\n\n//STEP 5: get number of intervals to draw\nintervalCount = (maxRounded - minRounded) / intervalSize\nintervalCount = math.Ceil(intervalCount) + 1 // include the origin as an interval\n\n//STEP 6: Check that the intervalCount isn't too high\nif intervalCount-1 >= (intervalSize * 2) && intervalCount > maxNumberOfIntervals {\n intervalCount = math.Ceil(intervalCount / 2)\n intervalSize *= 2\n}\n\nreturn}\n"
},
{
"answer_id": 67268259,
"author": "Fady Megally",
"author_id": 2082120,
"author_profile": "https://Stackoverflow.com/users/2082120",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\ndef create_ticks(lo,hi):\n s = 10**(np.floor(np.log10(hi - lo)))\n start = s * np.floor(lo / s)\n end = s * np.ceil(hi / s)\n ticks = [start]\n t = start\n while (t < end):\n ticks += [t]\n t = t + s\n \n return ticks\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18393/"
] |
361,686 | <p>Not a programming question per se, but interesting for people who do commercial web development.</p>
<p>How do you track all of your clients' hosting, domain registration, and SSL certificate expiry dates?</p>
<p>Do you just keep a spreadsheet or is there some useful piece of software for this?</p>
<p>I've searched extensively and can't find a usable piece of software and am tempted to write something. With 100+ customers to manage, and with hosting and domain names spread across several hosting companies and registrars, my ad hoc means are failing.</p>
| [
{
"answer_id": 361739,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 2,
"selected": false,
"text": "using System.Net;\nusing System.Diagnostics;\nusing System.Net.Mail;\nusing System.Threading;\n\nstatic void Main(string[] args)\n{\n // List of URL's to check\n string[] urls = new string[]{\n \"https://www.6bit.com/\",\n \"https://www.google.com/\"\n };\n\n HttpWebRequest req = null;\n\n // Certificate check callback\n ServicePointManager.ServerCertificateValidationCallback = (state, cert, certChain, sslerr) =>\n {\n DateTime expiration = DateTime.Parse(cert.GetExpirationDateString());\n if (expiration < DateTime.Now.AddMonths(3))\n {\n Debug.WriteLine(\"Cert expiring on \" + expiration.ToShortDateString());\n MailMessage msg = new MailMessage(\"SSLCheck@example.com\", \"josh@example.com\", \"SSL Certificate Expiring\", \"The ssl certificate for\" + req.RequestUri.ToString() + \" will expire on \" + expiration.ToShortDateString());\n SmtpClient sc = new SmtpClient();\n sc.Send(msg);\n }\n\n return true;\n };\n\n // Request each url once a day so that the validation callback runs for each\n Timer t = new Timer(s =>\n {\n Array.ForEach(urls, url =>\n {\n try\n {\n req = (HttpWebRequest)HttpWebRequest.Create(url);\n HttpWebResponse resp = (HttpWebResponse)req.GetResponse();\n resp.Close();\n }\n catch (Exception ex)\n {\n Debug.WriteLine(\"Error checking site: \" + ex.ToString());\n }\n });\n }, null, TimeSpan.FromSeconds(0), TimeSpan.FromDays(1)); // Run the timer now and schedule to run once a day\n}\n"
},
{
"answer_id": 39636330,
"author": "nbari",
"author_id": 1135424,
"author_profile": "https://Stackoverflow.com/users/1135424",
"pm_score": 0,
"selected": false,
"text": "services:\n google:\n url: https://www.google.com\n seconds: 60\n expect:\n status: 302\n ssl:\n hours: 72\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15531/"
] |
361,717 | <p>I have HTML code like this :</p>
<pre><code><div>
<a>Link A1</a>
<a>Link A2</a>
<a>Link A3</a>
</div>
<div>
<a>Link B1</a>
<a>Link B2</a>
<a>Link B3</a>
</div>
</code></pre>
<p>When user clicks a link from above HTML, I want to get the jQuery object of the corresponding <code><a></code> element, and then manipulate its sibling. I can't think of any way other than creating an ID for each <code><a></code> element, and passing that ID to an onclick event handler. I really don't want to use IDs. </p>
<p>Any suggestions?</p>
| [
{
"answer_id": 361724,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 7,
"selected": true,
"text": "$(\"div a\").click( function(event)\n{\n var clicked = $(this); // jQuery wrapper for clicked element\n // ... click-specific code goes here ...\n});\n <a> <div>"
},
{
"answer_id": 361728,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 3,
"selected": false,
"text": "$(this) var nextSibling = $(this).next();\n $(this).index() var $clicked = $(this);\nvar linkIndex = $clicked.index();\n$clicked.parent().next().children().eq(linkIndex);\n"
},
{
"answer_id": 363262,
"author": "Josh Delsman",
"author_id": 40644,
"author_profile": "https://Stackoverflow.com/users/40644",
"pm_score": 0,
"selected": false,
"text": "$(this).next();\n var clicked;\n\n$(\"div a\").click(function(){\n clicked = $(this).next();\n // Do what you need to do to the newly defined click here\n});\n\n// But you can also access the \"clicked\" element here\n"
},
{
"answer_id": 1438321,
"author": "Alex Barrett",
"author_id": 69713,
"author_profile": "https://Stackoverflow.com/users/69713",
"pm_score": 3,
"selected": false,
"text": "// assuming A1 is clicked\n$('div a').click(function(e) {\n $(this); // A1\n $(this).parent(); // the div containing A1\n $(this).siblings(); // A2 and A3\n});\n // assuming A1 is clicked\n$('div a').live('click', function(e) {\n $(this); // A1\n $(this).parent(); // the div containing A1\n $(this).siblings(); // A2 and A3\n});\n"
},
{
"answer_id": 3724783,
"author": "Ayman",
"author_id": 449241,
"author_profile": "https://Stackoverflow.com/users/449241",
"pm_score": 2,
"selected": false,
"text": "$(\"div li\").click(function() {\n$(this).children().css('background','red');\n});\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10629/"
] |
361,723 | <p>I am having difficulty with the following method. I can't figure out if my problem is, but I have narrowed it down to not populating the array list from the file. Any help is greatly appreciated.</p>
<pre><code>private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {
//create arraylists
ArrayList<String> model = new ArrayList<String>();
ArrayList<String> length = new ArrayList<String>();
ArrayList<String> width = new ArrayList<String>();
ArrayList<String> radius = new ArrayList<String>();
ArrayList<String> depth = new ArrayList<String>();
ArrayList<String> volume = new ArrayList<String>();
ArrayList<String> shape = new ArrayList<String>();
//fill arraylists from file
try {
String outputline = "";
BufferedReader fin = new BufferedReader(new FileReader("stock.dat"));
while((outputline = fin.readLine()) != null) {
// for(int i = 0; i < outputline.length(); i++) {
int i = 0;
//model
boolean flag = false;
String pass = "";
while(flag = false) {
if(outputline.charAt(i) != ',')
pass.concat(Character.toString(outputline.charAt(i)));
else
flag = true;
i++;
}
model.add(pass);
//length
flag = false;
pass = "";
while(flag = false) {
if(outputline.charAt(i) != ',')
pass.concat(Character.toString(outputline.charAt(i)));
else
flag = true;
}
length.add(pass);
//width
flag = false;
pass = "";
while(flag = false) {
if(outputline.charAt(i) != ',')
pass.concat(Character.toString(outputline.charAt(i)));
else
flag = true;
}
width.add(pass);
//radius
flag = false;
pass = "";
while(flag = false) {
if(outputline.charAt(i) != ',')
pass.concat(Character.toString(outputline.charAt(i)));
else
flag = true;
}
radius.add(pass);
//depth
flag = false;
pass = "";
while(flag = false) {
if(outputline.charAt(i) != ',')
pass.concat(Character.toString(outputline.charAt(i)));
else
flag = true;
}
depth.add(pass);
//volume
flag = false;
pass = "";
while(flag = false) {
if(outputline.charAt(i) != ',')
pass.concat(Character.toString(outputline.charAt(i)));
else
flag = true;
}
volume.add(pass);
//shape
pass = "";
for(int j = i; j < outputline.length(); j++)
pass.concat(Character.toString(outputline.charAt(i)));
shape.add(pass);
}
fin.close();
}
catch(IOException e) {
System.err.print("Unable to read from file");
System.exit(-1);
}
int at = -1;
for(int i = 0; i < model.size(); i++) {
if(model.get(i).equals(searchIn.getText())) {
at = i;
i = model.size();
}
}
Component frame = null;
if(at != -1) {
searchDepthOut.setText(depth.get(at));
searchLengthOut.setText(length.get(at));
searchRadiusOut.setText(radius.get(at));
searchVolumeOut.setText(volume.get(at));
searchWidthOut.setText(width.get(at));
}
else
JOptionPane.showMessageDialog(null, "Your search did not return any results", "ERORR", JOptionPane.ERROR_MESSAGE);
</code></pre>
<p>}</p>
| [
{
"answer_id": 361755,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 2,
"selected": false,
"text": "String pass = \"\";\nwhile(flag = false) {\nif(outputline.charAt(i) != ',')\n pass.concat(Character.toString(outputline.charAt(i)));\n pass = pass.concat(.....)\n"
},
{
"answer_id": 361761,
"author": "dotjoe",
"author_id": 40822,
"author_profile": "https://Stackoverflow.com/users/40822",
"pm_score": 2,
"selected": false,
"text": "while((outputline = fin.readLine()) != null) {\n\n String[] tokens = outputline.split(\",\");\n if(tokens.length == 7){\n SObj o = new SObj; //Some Object\n\n o.model = tokens[0];\n o.length = tokens[1];\n //and so on\n\n oList.add(o);\n }\n}\n"
},
{
"answer_id": 361762,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 2,
"selected": false,
"text": "while(flag = false) false while (!flag)"
},
{
"answer_id": 361772,
"author": "Steve B.",
"author_id": 19479,
"author_profile": "https://Stackoverflow.com/users/19479",
"pm_score": 0,
"selected": false,
"text": "/** Expect a line of the form model, length, ...,\n return a list of ... \n*/\nprivate String[] parse (String inputLine)\n{\n //check input line charachteristics-not null, length, ...\n String out= inputLine.split(\",\");\n if (out.length()!= ... \n //whatever sanity checking...\n\n}\n\nprivate List<String[]> extract(BufferedReader fin)\n{\n while((outputline = fin.readLine()) != null) \n {\n //do something with parse(outputline);\n }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,742 | <p>Sorry if this is a really basic question but I struggling with how I should attack this. I am trying to wrap up some commands for a OLE object, the basic spec looks like this:</p>
<pre><code>Set Window window_id
//Units is part of the position setter.
[ Position ( x, y ) [ Units paper_units ] ]
[ Width win_width [ Units paper_units ] ]
[ Height win_height [ Units paper_units ] ]
..... this goes on for about 20+ commands, all optional.
</code></pre>
<p>Where anyhting in between [] is optional.</p>
<p>So I need to create a class lets call it "<strong>CommandBuilder</strong>" that can will have set methods for all these optional setters, thats fine I can handle that, the main problem I'm having is the ToCommandString method that needs to ouput a string which would look somthing like:</p>
<pre><code>Set Window 1 Position (x,y) Units "m" Height 100 Units "m" + what ever else the user added
</code></pre>
<p>Just doing a few if's based on variables that get set and joining the string works fine when there is nothing complicated about the variables being set or there are only a few variables but when there are heaps of variables and/or nested values that are also optional, it can make the ToString method very long and complicated + hard to maintain if anything changes.</p>
<p>I was wondering if I could solve this by using polymorphism by doing something like this.</p>
<pre><code>interface ICommand
{
string ToCommandString();
}
class PositionCommand : ICommand
{
double X;
double Y;
string Units;
public PositionCommand(double x, double y)
{
this.X = x;
this.Y = y;
}
public PositionCommand(double x,double y, string units)
{
this.X = x;
this.Y = y;
this.Units = units;
}
public string ToCommandString()
{
//Add more stuff here to handle empty units.
return String.Format(" Postion ({0},{1})", X.ToString(), Y.ToString());
}
}
....more command classes.
</code></pre>
<p>Then all my set methods in "<strong>CommandBuilder</strong>" can just create the right command type add it to a list, then the main ToString in "<strong>CommandBuilder</strong>" method can loop through all the ones that have been set and call ToCommandString and no have to worry about doing any if statments or null checks. </p>
<p>Would this be the correct way to go about this? </p>
<p>P.S. If you need more info I would be glad to add, just didn't want to make it to long first go.</p>
| [
{
"answer_id": 361759,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 2,
"selected": false,
"text": "class CommandBuilder\n{\n private List<ICommand> _commands = new List<ICommand>();\n\n public CommandBuilder Position(double x, double y)\n {\n _commands.Add(new PositionCommand(x,y))\n return this;\n }\n\n ...\n}\n class CommandBuilder\n{\n public void AddCommand(ICommand cmd)\n { ... }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
361,747 | <p>I was browsing through the questions and noticed this:</p>
<pre><code>SELECT prodid, issue
FROM Sales
WHERE custid = @custid
AND datesold = SELECT MAX(datesold)
FROM Sales s
WHERE s.prodid = Sales.prodid
AND s.issue = Sales.issue
AND s.custid = @custid
</code></pre>
<p>I was wondering what the "@" does in front of custID? Is it just a way of referencing the custID from the table being selected?</p>
| [
{
"answer_id": 361758,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 2,
"selected": false,
"text": "@ ?"
},
{
"answer_id": 361962,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 2,
"selected": false,
"text": "eg:\nsqlcommand cmd = new sqlcommand(query,connection);\ncmd.parameters.add(\"@custid\",\"1\");\nsqldatareader dr = cmd.executequery();\n"
},
{
"answer_id": 11728337,
"author": "marc",
"author_id": 1563955,
"author_profile": "https://Stackoverflow.com/users/1563955",
"pm_score": 0,
"selected": false,
"text": "publish data where stoloc = 'AB143' \n|\n[select prtnum where stoloc = @stoloc]\n @"
},
{
"answer_id": 45319068,
"author": "ZeroPhase",
"author_id": 2028236,
"author_profile": "https://Stackoverflow.com/users/2028236",
"pm_score": 0,
"selected": false,
"text": "@"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27620/"
] |
361,752 | <p>I'm working on a Perl script. How can I pass command line parameters to it?</p>
<p>Example:</p>
<pre><code>script.pl "string1" "string2"
</code></pre>
| [
{
"answer_id": 361757,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 6,
"selected": false,
"text": "@ARGV my $numArgs = $#ARGV + 1;\nprint \"thanks, you gave me $numArgs command-line arguments.\\n\";\n\nforeach my $argnum (0 .. $#ARGV) {\n\n print \"$ARGV[$argnum]\\n\";\n\n}\n"
},
{
"answer_id": 361769,
"author": "nrich",
"author_id": 44153,
"author_profile": "https://Stackoverflow.com/users/44153",
"pm_score": 5,
"selected": false,
"text": "foreach my $arg (@ARGV) {\n print $arg, \"\\n\";\n}\n"
},
{
"answer_id": 361771,
"author": "user44511",
"author_id": 44511,
"author_profile": "https://Stackoverflow.com/users/44511",
"pm_score": 9,
"selected": true,
"text": "<> GetOpt::Std GetOpt::Long GetOpt::Std GetOpt::Long GetOpt::Long use Getopt::Long;\nmy $data = \"file.dat\";\nmy $length = 24;\nmy $verbose;\n$result = GetOptions (\"length=i\" => \\$length, # numeric\n \"file=s\" => \\$data, # string\n \"verbose\" => \\$verbose); # flag\n @ARGV $ARGV[0] \"string1\" $ARGV[1] @ARGV"
},
{
"answer_id": 362030,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 3,
"selected": false,
"text": "while (my $line = <>) {\n process_line($line);\n}\n shift while (my $arg = shift) {\n print \"Found argument $arg\\n\";\n}\n shift sub sub sub"
},
{
"answer_id": 9984149,
"author": "rastin71",
"author_id": 1309088,
"author_profile": "https://Stackoverflow.com/users/1309088",
"pm_score": 5,
"selected": false,
"text": "my ($src, $dest) = @ARGV;"
},
{
"answer_id": 10190878,
"author": "Joao Costa",
"author_id": 188174,
"author_profile": "https://Stackoverflow.com/users/188174",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/perl -s\n\nprint \"value of -x: $x\\n\";\nprint \"value of -name: $name\\n\";\n % ./myprog -x -name=Jeff\nvalue of -x: 1\nvalue of -name: Jeff\n"
},
{
"answer_id": 17168769,
"author": "pkm",
"author_id": 2490439,
"author_profile": "https://Stackoverflow.com/users/2490439",
"pm_score": 4,
"selected": false,
"text": "@ARGV ( $st, $prod, $ar, $file, $chart, $e, $max, $flag ,$id) = @ARGV;\n"
},
{
"answer_id": 21901618,
"author": "user3331697",
"author_id": 3331697,
"author_profile": "https://Stackoverflow.com/users/3331697",
"pm_score": 3,
"selected": false,
"text": "my $output_file;\n\nif((scalar (@ARGV) == 2) && ($ARGV[0] eq \"-i\"))\n\n{\n\n$output_file= chomp($ARGV[1]) ;\n\n\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
361,756 | <p>Is tight looping in a program bad?</p>
<p>I have an application that has two threads for a game-physics simulator. An updateGame thread and a render thread. The render thread is throttled by causing the thread to sleep for some milliseconds (to achieve the frame-rate I want) and the updateGame thread (that updates my in game objects positions based off some physics equations) was previously throttled by a 10 millisecond sleep.</p>
<p>However, I recently unthrottled the updateGame thread and the simulation of my objects movement seems to be significantly more realistic now that I have taken out that 10ms sleep. Is it bad to hot loop or have a tight loop?</p>
<pre><code>private class UpdateTask implements Runnable
{
private long previousTime = System.currentTimeMillis();
private long currentTime = previousTime;
private long elapsedTime;
public void run()
{
while(true)
{
currentTime = System.currentTimeMillis();
elapsedTime = (currentTime - previousTime); // elapsed time in seconds
updateGame(elapsedTime / 1000f);
try {
Thread.currentThread().sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
previousTime = currentTime;
}
}
}
</code></pre>
<p>In this example I'm just sleeping for 1ms (and from my understanding with how millisecond accuracy and the sleep function works this is probably more like 5-10ms. If I sleep for any more than this it starts to have impacts on the accuracy of my collision detection and physics model.</p>
<p>Is it a bad practice to have tight loops or loops with 1ms sleeps in them? Is there something else I should do instead?</p>
| [
{
"answer_id": 361785,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 2,
"selected": false,
"text": "Thread.sleep Thread.sleep Thread.sleep"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
] |
361,775 | <p>I have a div tag styled through CSS. I set the padding to 10px (padding:10px), it works just as I wanted in Firefox and IE7, but in IE6 it adds additional padding at the bottom (about 2-3px I think). Anyone has idea about what's happening here?</p>
<p>[update]</p>
<p>I just noticed this, the div tag I'm talking about has a background-image. When I removed the background-image, the extra padding on the bottom disappears. Any ideas?</p>
<p>[another update, code sample]</p>
<p>Here's the CSS applied to my div tag:</p>
<pre><code>.user-info{
margin-top: 20px;
margin-right: 20px;
padding: 10px;
background-image: url("../img/user_panel_bg.png");
float:right;
border: 1px #AAAAAA solid;
font-size:12px;
}
</code></pre>
| [
{
"answer_id": 361820,
"author": "Philip Arthur Moore",
"author_id": 37702,
"author_profile": "https://Stackoverflow.com/users/37702",
"pm_score": 2,
"selected": false,
"text": "DIV overflow:hidden; display: inline;"
},
{
"answer_id": 361825,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 5,
"selected": true,
"text": "<div>\n<img src=\"myimage.jpg\">\n</div>\n <div><img src=\"myimage.jpg\"></div>\n"
},
{
"answer_id": 528952,
"author": "Neil Monroe",
"author_id": 64240,
"author_profile": "https://Stackoverflow.com/users/64240",
"pm_score": 1,
"selected": false,
"text": "<div class=\"box\"> \n <h1>Heading</h1> \n <p>This is the main content.</p> \n <div class=\"bottom\"></div> \n</div>\n <style type=\"text/css\">\n .box {\n background: url(bg-middle.jpg) repeat-y;\n }\n .box h1 {\n background: url(bg-top.jpg) no-repeat;\n }\n .box .bottom {\n background: url(bg-image.jpg) no-repeat; /* bottom cap image */\n height: 10px; /* height of your bg image */\n font-size: 1px; /* for IE6 */\n }\n</style>\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40538/"
] |
361,799 | <p>I have been working for a while to create an iPhone app. Today when my battery was low, I was working and constantly saving my source files then the power went out...</p>
<p>Now when I plugged my computer back in and it is getting good power I try to open my project file and I get an error:</p>
<blockquote>
<p>Unable to Open Project</p>
<p>Project ... cannot be opened because the project file cannot be parsed.</p>
</blockquote>
<p>Is there a way that people know of that I can recover from this? I tried using an older project file and re inserting it and then compiling. It gives me a funky error which is probably because it isn't finding all the files it wants...</p>
<p>I really don't want to rebuild my project from scratch if possible.</p>
<hr />
<h3>EDIT</h3>
<p>Ok, I did a diff between this and a slightly older project file that worked and saw that there was some corruption in the file. After merging them (the good and newest parts) it is now working.</p>
<p>Great points about the SVN. I have one, but there has been some funkiness trying to sync XCode with it. I'll definitely spend more time with it now... ;-)</p>
<p><img src="https://i.stack.imgur.com/Up53v.png" alt="enter image description here" /></p>
| [
{
"answer_id": 11992949,
"author": "Usuf",
"author_id": 3199983,
"author_profile": "https://Stackoverflow.com/users/3199983",
"pm_score": 8,
"selected": false,
"text": "projectname.xcodeproj projectname projectname.pbxproj <<<<<<< .mine ======= >>>>>>> .r <<<<<<< .mine\n 9ADAAC6A15DCEF6A0019ACA8 .... in Resources */,\n=======\n 52FD7F3D15DCEAEF009E9322 ... in Resources */,\n>>>>>>> .r269\n <<<<<<< .mine ======= >>>>>>> .r 9ADAAC6A15DCEF6A0019ACA8 /* BuyPriceBtn.png in Resources */,\n\n 52FD7F3D15DCEAEF009E9322 /* discussionForm.zip in Resources */,\n"
},
{
"answer_id": 21628450,
"author": "Oleksiy Ivanov",
"author_id": 2546685,
"author_profile": "https://Stackoverflow.com/users/2546685",
"pm_score": 5,
"selected": false,
"text": "2/7/14 12:39:12.792 PM Xcode[9949]: CFPropertyListCreateFromXMLData(): Old-style plist parser: missing semicolon in dictionary on line 4426. Parsing will be abandoned. Break on _CFPropertyListMissingSemicolon to debug.\n"
},
{
"answer_id": 29291094,
"author": "SnoopyProtocol",
"author_id": 3870838,
"author_profile": "https://Stackoverflow.com/users/3870838",
"pm_score": 6,
"selected": false,
"text": " <<<<<<< HEAD\n id = {\n isa = PBXGroup;\n children = (\n id\n );\n name = \"Your Group Name\";\n =======\n id = {\n isa = PBXGroup;\n children = (\n id\n );\n name = \"Your Group Name\";\n >>>>>>> branch name\n sourceTree = \"<group>\";\n };\n id = {\n isa = PBXGroup;\n children = (\n id\n );\n name = \"Your Group Name\";\n id = {\n isa = PBXGroup;\n children = (\n id\n );\n name = \"Your Group Name\";\n sourceTree = \"<group>\";\n };\n id = {\n isa = PBXGroup;\n children = (\n id\n );\n name = \"Your Group Name\";\n sourceTree = \"<group>\";\n };\n\n id = {\n isa = PBXGroup;\n children = (\n id\n );\n name = \"Your Group Name\";\n sourceTree = \"<group>\";\n };\n"
},
{
"answer_id": 35627367,
"author": "Jayprakash Dubey",
"author_id": 1753005,
"author_profile": "https://Stackoverflow.com/users/1753005",
"pm_score": 5,
"selected": false,
"text": "projectName.xcodeproj Show Package Contents .pbxproj project.pbxproj Text Edit <<<<<< .mine ============ >>>>>>>>>> .r123"
},
{
"answer_id": 41807541,
"author": "Vojta",
"author_id": 3797599,
"author_profile": "https://Stackoverflow.com/users/3797599",
"pm_score": 2,
"selected": false,
"text": "find -d . -name 'project.pbxproj' echo *.xcodeproj"
},
{
"answer_id": 49429624,
"author": "Abhi",
"author_id": 2736360,
"author_profile": "https://Stackoverflow.com/users/2736360",
"pm_score": 2,
"selected": false,
"text": "xxxxxxxxxxxxx /* [CP] Check Pods Manifest.lock */ = {\n"
},
{
"answer_id": 50646188,
"author": "beseder",
"author_id": 2181333,
"author_profile": "https://Stackoverflow.com/users/2181333",
"pm_score": 3,
"selected": false,
"text": "plutil -lint project.pbxproj union .gitattributes"
},
{
"answer_id": 57376154,
"author": "Subramani",
"author_id": 6492703,
"author_profile": "https://Stackoverflow.com/users/6492703",
"pm_score": 0,
"selected": false,
"text": "git merge --abort"
},
{
"answer_id": 63624911,
"author": "tyoc213",
"author_id": 682603,
"author_profile": "https://Stackoverflow.com/users/682603",
"pm_score": 0,
"selected": false,
"text": "<<<<<\n....\n======\n>>>>>>\n kin project.pbxproj\n"
},
{
"answer_id": 70092283,
"author": "Mostafa ElShazly",
"author_id": 9675580,
"author_profile": "https://Stackoverflow.com/users/9675580",
"pm_score": 0,
"selected": false,
"text": "ERROR: line 1197:40 mismatched input '1' expecting NON_QUOTED_STRING"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,801 | <p>I'm a newbie with Subversion, so I don't now if this is a dumb question:</p>
<p>I've inherited a subversion repository with a flat structure with no /trunk /tags /branches top level).</p>
<p>I'd like re-structure it so that it follows the </p>
<pre><code>/trunk
/tags
/branches
</code></pre>
<p>layout.</p>
<p>Is this possible?</p>
| [
{
"answer_id": 363168,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 4,
"selected": false,
"text": "move move svn mkdir --quiet --message \"Restructuring\" http://svnhost/svnrepos/trunk\nsvn mkdir --quiet --message \"Restructuring\" http://svnhost/svnrepos/tags\nsvn mkdir --quiet --message \"Restructuring\" http://svnhost/svnrepos/branches\n move svn move --message \"Restructuring\" http://svnhost/svnrepos/dir01 http://svnhost/svnrepos/trunk/dir01\n /repos\n /projectA\n /branches\n /tags\n /trunk\n /projectB\n /branches\n /tags\n /trunk\n"
},
{
"answer_id": 9244069,
"author": "msangel",
"author_id": 449553,
"author_profile": "https://Stackoverflow.com/users/449553",
"pm_score": 2,
"selected": false,
"text": "/trunk /tags /branches TortoiseSVN > Repo-Browser /trunk /tags /branches /trunk Ok > Submit > Ok"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,832 | <p>I have a base class in which I want to specify the methods a child class must have, but not implement them itself. However, the methods in a child class may have a different number of paramaters to the definition in the base class.</p>
<p>Having tried this with an abstract method, php doesn't allow this. Is it possible?</p>
| [
{
"answer_id": 362046,
"author": "danieltalsky",
"author_id": 22452,
"author_profile": "https://Stackoverflow.com/users/22452",
"pm_score": 1,
"selected": false,
"text": "func_get_args()\n"
},
{
"answer_id": 362368,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 0,
"selected": false,
"text": "class a {\n protected $requiredMethodsInSubclass = array( 'method1', 'method2', 'method3' );\n\n public function __construct() {\n $reflObject = new ReflectionObject($this);\n\n $className = $reflObject->getName();\n\n if ($className == __CLASS__) {\n //this class is being instanciated directly , so don't worry about any subclasses\n return;\n }\n\n foreach ($this->requiredMethodsInSubclass as $methodName) {\n try {\n $reflMethod = $reflObject->getMethod($methodName);\n } catch (ReflectionException $e) { //method not anywhere\n trigger_error(\"Method $methodName is not declared in class \" . __CLASS__ . \" or subclass $className\", E_USER_ERROR);\n continue;\n }\n\n $declaringClass = $reflMethod->getDeclaringClass();\n\n if ($declaringClass->getName() == __CLASS__) {\n //method is declared in this class, not subclass\n trigger_error(\"Method $methodName is not declared in subclass $className\", E_USER_ERROR);\n }\n }\n }\n\n public function method1() {\n\n }\n\n public function method2($a) {\n\n }\n }\n\n\n\nclass b extends a {\n public function __construct() {\n parent::__construct();\n\n //some stuff\n }\n\n\n public function method2($a, $b, $c) {\n\n }\n\n}\n\n\n\n$b = new b();\n"
},
{
"answer_id": 362409,
"author": "Greg",
"author_id": 1916,
"author_profile": "https://Stackoverflow.com/users/1916",
"pm_score": 3,
"selected": false,
"text": "abstract class Foo {\n abstract function bar($a);\n}\n\nclass NewFoo extends Foo {\n\n function bar($a, $b = null) {\n //do something\n }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40017/"
] |
361,839 | <p>Sorry for asking an implement my feature question type question last time. I am new to Stackoverflow.com and also to php that's why.</p>
<p>What I was trying to ask is:</p>
<p>I have made a admin account. Members have registration page so a member will register. When user registers in the database table I will have a field for which 0 value will be initialised which means he is not approved. In admin account I have code to get the list of members. The code is given below:</p>
<pre><code><h2><?php echo "User list"; ?></h2>
<table border="0" cellpadding="0" cellspacing="0">
<tr bgcolor="#f87820">
<td><img src="img/blank.gif" alt="" width="10" height="25"></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo "first name"; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo "lastname name"; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo "member id"; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="50" height="6"><br><b><?php echo "delete"; ?></b></td>
<td><img src="img/blank.gif" alt="" width="10" height="25"></td>
</tr>
<?php
}
$result=mysql_query("SELECT member_id,firstname,lastname,login FROM members ORDER BY firstname");
$i = 0;
while($row = mysql_fetch_array($result)) {
if ($i > 0) {
echo "<tr valign='bottom'>";
echo "<td bgcolor='#ffffff' height='1' style='background-image:url(img/strichel.gif)' colspan='6'></td>";
echo "</tr>";
}
echo "<tr valign='middle'>";
echo "<td class='tabval'><img src='img/blank.gif' alt='' width='10' height='20'></td>";
echo "<td class='tabval'><b>".$row['lastname']."</b></td>";
echo "<td class='tabval'>".$row['firstname']." </td>";
echo "<td class='tabval'>".$row['member_id']." </td>";
echo "<td class='tabval'><a onclick=\"return </span></a></td>";
echo "<td class='tabval'></td>";
echo "</tr>";
$i++;
}
?>
</table>
in this i wanna add tho more things in the table 1 to delete a member and 2 to have approved or denied option for that i made two functiom
below code is to delete
if($_REQUEST['action']=="del")
{
$memberId = mysql_real_Escape_string($_REQUEST['member_id']);
mysql_query("DELETE FROM members WHERE member_id=$memberId");
}
</code></pre>
<p>below one for approving members</p>
<p>But my problem is I don't know how to include a button or radio button in the table which can pass value delete or approve to these functions.</p>
<p>Please tell me how the syntax is to add this button so that for approving I can change the value 0 that I gave in the database to 1 so that member get approved.</p>
| [
{
"answer_id": 361858,
"author": "Levi",
"author_id": 27620,
"author_profile": "https://Stackoverflow.com/users/27620",
"pm_score": 0,
"selected": false,
"text": "?> <form name=\"deleteUser\" id=\"deleteUser\" method=\"post\" action=\"\">\n<input type=\"hidden\" name=\"member_id\" id=\"member_id\" value=\"<?php echo $row['member_id'] ?>\n<input type=\"submit\" name=\"action\" id=\"action\" value=\"del\" />\n</form><?php\n <td> <td class='tabval'>INSERT HERE</td>\";\n"
},
{
"answer_id": 361874,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 1,
"selected": false,
"text": "echo '<td><a href=\"http://yourwebsite/yourscriptname.php?action=del&member_id='\n . htmlspecialchars($row['member_id']) . '\">Delete</a>';\nif ($row['approved'] == 0) {\n echo ' <a href=\"http://yourwebsite/yourscriptname.php?action=approve&member_id='\n . htmlspecialchars($row['member_id']) . '\">Approve</a>';\n}\necho '</td>';\n $member_id = 0;\nif (isset($_GET['member_id'])) $member_id = intval($_GET['member_id']);\n$action = '';\nif (isset($_GET['action'])) $action = $_GET['action'];\n\n$sql = '';\nswitch($action) {\ncase 'approve':\n $sql = \"UPDATE members SET approval = 1 WHERE member_id = $member_id\";\n break;\ncase 'delete':\n $sql = \"DELETE FROM member WHERE member_id = $member_id\";\n break;\n}\nif (!empty($sql) && !empty($member_id)) {\n // execute the sql.\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40975/"
] |
361,840 | <p>This afternoon, upon noticing a broken build and the fact that some files looked like very old versions (about 2 weeks old), I checked the svn log. Apparently just this afternoon, 1 of the developers did an "svn copy" of a directory from an older revision to the same directory. Thus it appears that the latest version "i.e. head" of all the files in that directory are really old, and all the history "i.e. log" is even older.</p>
<p>However, I think I can recover by using another "svn copy" (i.e. the disease is the cure). What I am considering doing is finding the revision where the bad "svn copy" was done (say rev 1234) , subtracting 1 (1233) and doing:</p>
<pre><code>svn copy -r 1233 file://path/to/messed/up/dir file://path/to/messed/up/dir
</code></pre>
<p>That <em>should</em> restore the latest version, as well as get back all my history. Am I right about this?</p>
| [
{
"answer_id": 361961,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 1,
"selected": false,
"text": "svn rm file:///path/to/messed/up/dir\n svn cp file:///path/to/messed/up/dir@1233 file:///path/to/messed/up\n"
},
{
"answer_id": 362209,
"author": "Palmin",
"author_id": 5949,
"author_profile": "https://Stackoverflow.com/users/5949",
"pm_score": 4,
"selected": true,
"text": "svn merge -c -1234\n -c -1234 -r 1234:1233"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16012/"
] |
361,852 | <p>Sorry - this may be an easy question, I'm new to iPhone development and still wrapping my head around Views vs ViewControllers.</p>
<p>I have a NavigationViewController and I can push Views using the following method in the RootViewController which is connected to a Bar Button Item:</p>
<pre><code>- (IBAction)switch:(id)sender {
NSLog(@"Swith...");
LibraryViewController *varLibraryViewController = [[LibraryViewController alloc] initWithNibName:@"LibraryViewController" bundle:nil];
[[self navigationController] pushViewController:varLibraryViewController animated:YES];
}
</code></pre>
<p>I want to call this same method from a button on the same view that is currently loaded. Basically I want to have the Bar Button at the top call the same method as a button on the view. I was wondering how to call a method in the ViewController from the view loaded from that viewController. Hopefully that makes sense.</p>
<p>Do I need to create an instance of the RootViewController? I would think that would already be instantiated. Thank you.</p>
| [
{
"answer_id": 361914,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 1,
"selected": false,
"text": " - (IBAction) myMethod: (id) sender;\n selector myMethod"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29941/"
] |
361,854 | <p>I'm trying to get udp multicast data using sockets and c++ (c). I have a server with 2 network cards so I need to bind socket to specific interface. Currently I'm testing on another server that has only one network card.</p>
<p>When I use INADDR_ANY I can see the udp data, when I bind to specific interface I don't see any data. Function inet_addr is not failing (I removed checking for return value for now).</p>
<p>Code is below.
On a server with one network card, my IP address is 10.81.128.44. I receive data when I run as:
./client 225.0.0.37 12346</p>
<p>This gives me no data:
./client 225.0.0.37 12346 10.81.128.44</p>
<p>Any suggestions? (Hope the code compiles, I removed comments ...)</p>
<pre><code> #include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
#define HELLO_PORT 12345
#define HELLO_GROUP "225.0.0.37"
#define MSGBUFSIZE 256
int main(int argc, char *argv[])
{
string source_iface;
string group(HELLO_GROUP);
int port(HELLO_PORT);
if (!(argc < 2)) group = argv[1];
if (!(argc < 3)) port = atoi(argv[2]);
if (!(argc < 4)) source_iface = argv[3];
cout << "group: " << group << " port: " << port << " source_iface: " << source_iface << endl;
int fd;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(1);
}
u_int yes = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0)
{
perror("Reusing ADDR failed");
exit(1);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = (source_iface.empty() ? htonl(INADDR_ANY) : inet_addr(source_iface.c_str()));
if (bind(fd,(struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
exit(1);
}
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr(group.c_str());
mreq.imr_interface.s_addr = (source_iface.empty() ? htonl(INADDR_ANY) : inet_addr(source_iface.c_str()));
if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
{
perror("setsockopt");
exit(1);
}
socklen_t addrlen;
int nbytes;
char msgbuf[MSGBUFSIZE];
while (1)
{
memset(&msgbuf, 0, MSGBUFSIZE);
addrlen = sizeof(addr);
if ((nbytes = recvfrom(fd, msgbuf, MSGBUFSIZE, 0, (struct sockaddr *)&addr, &addrlen)) < 0)
{
perror("recvfrom");
exit(1);
}
cout.write(msgbuf, nbytes);
cout.flush();
}
return 0;
}
</code></pre>
<p>Thanks in advance ...</p>
| [
{
"answer_id": 362485,
"author": "David Allan Finch",
"author_id": 27417,
"author_profile": "https://Stackoverflow.com/users/27417",
"pm_score": 2,
"selected": false,
"text": " struct ip_mreq multi;\n\n multi.imr_multiaddr.s_addr = inet_addr(group.c_str());\n multi.imr_interface.s_addr = (source_iface.empty() ?\n htonl(INADDR_ANY): inet_addr(source_iface.c_str()));\n\n status = setsockopt(me->ns_fd, IPPROTO_IP, IP_MULTICAST_IF,\n (char *)&multi.imr_interface.s_addr,\n sizeof(multi.imr_interface.s_addr));\n"
},
{
"answer_id": 370863,
"author": "stefanB",
"author_id": 45654,
"author_profile": "https://Stackoverflow.com/users/45654",
"pm_score": 3,
"selected": false,
"text": "INADDR_ANY addr.sin_family = AF_INET;\naddr.sin_port = htons(port);\naddr.sin_addr.s_addr = (source_iface.empty() ?\n htonl(INADDR_ANY) : \n inet_addr(source_iface.c_str()));\n addr.sin_family = AF_INET;\naddr.sin_port = htons(port);\naddr.sin_addr.s_addr = (group.empty() ?\n htonl(INADDR_ANY) :\n inet_addr(group.c_str()));\n IP_MULTICAST_IF"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,855 | <p>I'm running a django instance behind nginx connected using fcgi (by using the manage.py runfcgi command). Since the code is loaded into memory I can't reload new code without killing and restarting the django fcgi processes, thus interrupting the live website. The restarting itself is very fast. But by killing the fcgi processes first some users' actions will get interrupted which is not good.
I'm wondering how can I reload new code without ever causing any interruption. Advices will be highly appreciated!</p>
| [
{
"answer_id": 957050,
"author": "sheats",
"author_id": 4915,
"author_profile": "https://Stackoverflow.com/users/4915",
"pm_score": 4,
"selected": false,
"text": "pid_file=/path/to/pidfile\nport_file=/path/to/port_file\nold_pid=`cat $pid_file`\n\nif [[ -f $port_file ]]; then\n last_port=`cat $port_file`\n port_to_use=$(($last_port + 1))\nelse\n port_to_use=8000\nfi\n\n# Reset so me don't go up forever\nif [[ $port_to_use -gt 8999 ]]; then\n port_to_use=8000\nfi\n\nsed -i \"s/$old_port/$port_to_use/g\" /path/to/nginx.conf\n\npython manage.py runfcgi host=127.0.0.1 port=$port_to_use maxchildren=5 maxspare=5 minspare=2 method=prefork pidfile=$pid_file\n\necho $port_to_use > $port_file\n\nkill -HUP `cat /var/run/nginx.pid`\n\necho \"Sleeping for 5 seconds\"\nsleep 5s\n\necho \"Killing old processes on $last_port, pid $old_pid\"\nkill $old_pid\n"
},
{
"answer_id": 4991305,
"author": "Nick Craig-Wood",
"author_id": 164234,
"author_profile": "https://Stackoverflow.com/users/164234",
"pm_score": 2,
"selected": false,
"text": "2 KeyboardInterrupt"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31604/"
] |
361,856 | <p>I need some help with jQuery script again :-) Just trying to play with jQuery..I use script below for coloring options of select element. It works in pure html, but in my asp.net 2.0 (Master + Content pages) does not. Script is placed in Head section.</p>
<pre><code>function pageLoad(){
var allOddSelectOption = "select option:odd";
var evenStyle = "background-color:'#f4f4f4';color:'#555'";
$(allOddSelectOption).attr('style',evenStyle);
}
</code></pre>
<p>I tried also use <code>$(document).ready(function(){</code> but it didn't work too.</p>
<p>Any ideas, tips most welcome?</p>
| [
{
"answer_id": 361861,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": true,
"text": "$(document).ready(function(){\n $(\"select option:odd\").css({'background-color' : 'yellow', 'font-weight' : 'bolder'});\n});\n $(document).ready() <asp:ContentPlaceHolder id=\"head\" runat=\"server\">\n</asp:ContentPlaceHolder>\n <asp:Content ID=\"Content1\" ContentPlaceHolderID=\"head\" Runat=\"Server\">\n <script language=\"JavaScript>\n //Scripts here!\n </script>\n</asp:Content> \n"
},
{
"answer_id": 361865,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 0,
"selected": false,
"text": "$(\"[id$=originalIdFromAspxPage]\").attr...\n $="
},
{
"answer_id": 362265,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 1,
"selected": false,
"text": "e.g $('#someDiv').addClass('odd');\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24507/"
] |
361,869 | <p>I have read a lot of popular standards manuals for open source PHP projects.</p>
<p>A lot enforce underscores for variables spaces, and a lot enforce camelCase.</p>
<p>Should global functions and variables be named differently to class methods/properties?</p>
<p>I know the most important thing is consistency, but I'd like to hear some thoughts on this.</p>
<p>What would you recommend?</p>
| [
{
"answer_id": 361899,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 0,
"selected": false,
"text": "grep SomeField some_table"
},
{
"answer_id": 361901,
"author": "ieure",
"author_id": 45224,
"author_profile": "https://Stackoverflow.com/users/45224",
"pm_score": 5,
"selected": true,
"text": "Item Row DB Items $column $name DEBUG TYPE_FOO get perform do getThing() getThings()"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
361,904 | <pre><code>function holiday_hitlist($tablename, $hit_user){
global $host, $user, $pass, $dbname;
$link = mysql_connect($host, $user, $pass, $dbname);
print "<div class=\"hit_list\">
<h3>My Holiday Hitlist</h3>
<p>Five things I want the most, based on my desirability ratings.<br/>You can't go wrong with this stuff!</p>
<ol>";
$sql = "SELECT title, URL, price FROM $dbname.$tablename WHERE user='$hit_user' AND rank >= 3 ORDER BY date DESC LIMIT 5";
$result = mysql_query($sql) or die ("Couldn't retrieve holiday hit list for this user. " . mysql_error());
while($row = mysql_fetch_array($result)) {
$title = $row['title'];
$url = $row['URL'];
$price = "$" . $row['price'];
$output = print "<li><a href=\"$url\" target=\"_blank\">$title</a> $price</li>";
}
print "</ol></div>";
return $output;
}
</code></pre>
<p>On an HTML page, it puts the "1" immediately following the closing <code>div</code> tag. Why? </p>
| [
{
"answer_id": 361915,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 4,
"selected": true,
"text": "$output = print \"<li><a href=\\\"$url\\\" target=\\\"_blank\\\">$title</a> $price</li>\";\n"
},
{
"answer_id": 362017,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 2,
"selected": false,
"text": "function holiday_hitlist($tablename, $hit_user){\n /* connections etc\n\n */\n\n while($row = mysql_fetch_array($result)) {\n $title = $row['title'];\n $url = $row['URL'];\n $price = \"$\" . $row['price'];\n $output = print \"<li><a href=\\\"$url\\\" target=\\\"_blank\\\">$title</a>$price</li>\";\n }\n print \"</ol></div>\";\n return $output;\n}\n\nprint holiday_hitlist(\"mytab\",\"myuser\");\n $somevar = holiday_hitlist(\"mytab\",\"myuser\");\nprint $somevar;\n function holiday_hitlist($tablename, $hit_user){\n /* connections etc\n\n */\n\n while($row = mysql_fetch_array($result)) {\n $title = $row['title'];\n $url = $row['URL'];\n $price = \"$\" . $row['price'];\n $output .= \"<li><a href=\\\"$url\\\" target=\\\"_blank\\\">$title</a>$price</li>\";\n }\n return $output;\n}\n\n$somevar = holiday_hitlist(\"mytab\",\"myuser\");\n\nprint \"<div class=\\'hit_list\\'>\n<h3>My Holiday Hitlist</h3>\n<p>Five things I want the most, based on my desirability ratings.<br/>You can't go wrong with this stuff!</p>\n<ol>\n$somevar\n</ol></div>\";\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7853/"
] |
361,910 | <p>Say you have something like an ASP.NET ASP:DetailsView to show and edit a single record in a database.</p>
<p>It's simple to record the error cases... you add validation and a validation summary. When your update form fails validation it naturally makes noise: it shows the validation message and/or the validation summary. Not a single code behind is required.</p>
<p>But then, you pass validation, and it makes your update completely silently. There's no sense that anything happened, and there doesn't seem to be any default settings to make a success message without code-behinds.</p>
<p>But, even code-behinds are confusing. What event should show the success message? onItemUpdate, right? Fine, but then let's say you make another change and get a validation error? Your success message stays. I wasn't able to find an event that would reliably turn off an existing success message if there were a validation error. </p>
<p>This should be web development 101! Why is it so hard?</p>
<p><strong>EDIT:</strong></p>
<p>Someone suggested using the ItemCommand event... I tried this and many other events, but that success message just won't disappear. Here's some code.</p>
<p>My message in ASP.NET</p>
<pre><code><label id="successMessage" class="successMessage" runat="server"></label>
</code></pre>
<p>And my DataView tag (simplified):</p>
<pre><code> <asp:DetailsView
Id="EditClient"
DataKeyNames="LicenseID"
DataSourceID="MySource"
runat="server"
OnItemUpdated="SuccessfulClientUpdate"
OnItemCommand="ClearMessages">
</code></pre>
<p>And, my code-behind:</p>
<pre><code>protected void SuccessfulClientUpdate(object sender, DetailsViewUpdatedEventArgs e)
{
successMessage.InnerText = string.Format("Your changes were saved.");
successMessage.Visible = true;
}
protected void ClearMessages(object sender, DetailsViewCommandEventArgs e)
{
successMessage.InnerText = string.Empty;
successMessage.Visible = false;
}
</code></pre>
<p>Once I do a successful update, however, nothing seems to make that message disappear, not even failed validation.</p>
<p><strong>2nd EDIT:</strong></p>
<p>Just want to be clear that I did try putting the ClearMessages code in Page_Load. However, nothing seems to make that successMessage label disappear when I hit update a 2nd time WITH a validation error. Can anyone suggest any other troubleshooting tips?</p>
| [
{
"answer_id": 361952,
"author": "JoshBerke",
"author_id": 26160,
"author_profile": "https://Stackoverflow.com/users/26160",
"pm_score": 0,
"selected": false,
"text": "protected void ClearMessages(object sender, DetailsViewCommandEventArgs e)\n{\n successMessage.InnerText = string.Empty; \n successMessage.Visible = false;\n}\n protected void Page_Load(object sender, EventArgs e)\n{\n successMessage.InnerText = string.Empty; \n successMessage.Visible = false;\n\n}\n"
},
{
"answer_id": 362147,
"author": "Dan C.",
"author_id": 26391,
"author_profile": "https://Stackoverflow.com/users/26391",
"pm_score": 4,
"selected": true,
"text": "<div> <div> <form name=\"aspnetForm\" method=\"post\" action=\"MyPage.aspx\" onsubmit=\"javascript:return WebForm_OnSubmit();id=\"aspnetForm\"> function WebForm_OnSubmit() {\nif (typeof(ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false)\n return false;\nreturn true;\n}\n if (!Page.ClientScript.IsOnSubmitStatementRegistered(\"ClearMessage\"))\n{\n string script = @\"document.getElementById('\" + \n yourDivControl.ClientID + \"').style.display='none'\";\n Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), \"ClearMessage\", script);\n}\n function WebForm_OnSubmit() {\n document.getElementById('ctl00_yourDivControl').style.display='none';\n if (typeof(ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false)\n return false;\n return true;\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22452/"
] |
361,921 | <pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace ConsoleApplication1
{
public class Class1
{
static void Main(string[] args)
{
List<Car> mylist = new List<Car>();
Car car1;
Car car2;
Car car3;
car1 = new Car()
{
make = "Honda",
id = 1
};
car2 = new Car()
{
make = "toyota",
id = 2
};
car3 = new Car()
{
make = "Honda",
id = 3,
color = "red"
};
mylist.Add(car1);
mylist.Add(car2);
**////mylist.Where(p => p.id == 1).SingleOrDefault() = car3;**
}
}
public class Car
{
public int id { get; set; }
public string make { get; set; }
public string color { get; set; }
}
}
</code></pre>
<p>How can I update the list by replacing the honda car of Id 1 with honda car with Id 3 in the best way.</p>
| [
{
"answer_id": 361936,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 7,
"selected": true,
"text": "int index = mylist.FindIndex(p => p.id == 1);\nif(index<0) {\n mylist.Add(car3);\n} else {\n mylist[index] = car3;\n}\n List<T>"
},
{
"answer_id": 361950,
"author": "Joel Meador",
"author_id": 1976,
"author_profile": "https://Stackoverflow.com/users/1976",
"pm_score": 3,
"selected": false,
"text": "foreach (var f in mylist.FindAll(x => x.id == 1)) \n{ \n f.id = car3.id; \n f.color = car3.color; \n f.make = car3.make; \n} \n"
},
{
"answer_id": 361958,
"author": "Funky81",
"author_id": 37509,
"author_profile": "https://Stackoverflow.com/users/37509",
"pm_score": 3,
"selected": false,
"text": "(from car in mylist\nwhere car.id == 1\nselect car).Update(\ncar => car.id = 3);\n public static void Update<T>(this IEnumerable<T> source, params Action<T>[] updates)\n{\n if (source == null)\n throw new ArgumentNullException(\"source\");\n\n if (updates == null)\n throw new ArgumentNullException(\"updates\");\n\n foreach (T item in source)\n {\n foreach (Action<T> update in updates)\n {\n update(item);\n }\n }\n}\n"
},
{
"answer_id": 361991,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 2,
"selected": false,
"text": "mylist = new List<Car>(from car in mylist select car.id == 1? car3 : car)\n"
},
{
"answer_id": 2116101,
"author": "rockvista",
"author_id": 1996230,
"author_profile": "https://Stackoverflow.com/users/1996230",
"pm_score": 2,
"selected": false,
"text": "//Item class\nClass Item\n{\n public string Name { get; set; }\n}\n\nList < Item > myList = new List< Item >()\n\n//Add item to list\nItem item = new Item();\nitem.Name = \"Name\";\n\nmyList.Add(Item);\n\n//Find the item with the name prop\n\nItem item2 = myList.Find(x => x.Name == \"Name\");\n\nif(item2 != null)\n item.Name = \"Changed\";\n"
},
{
"answer_id": 4266614,
"author": "jose mauricio",
"author_id": 518725,
"author_profile": "https://Stackoverflow.com/users/518725",
"pm_score": 1,
"selected": false,
"text": "List<AvailabilityIssue> ai = new List<AvailabilityIssue>();\n\nai.AddRange(\n (from a in db.CrewLicences\n where\n a.ValidationDate <= ((UniversalTime)todayDate.AddDays(30)).Time &&\n a.ValidationDate >= ((UniversalTime)todayDate.AddDays(15)).Time\n select new AvailabilityIssue()\n {\n crewMemberId = a.CrewMemberId,\n expirationDays = 30,\n Name = a.LicenceType.Name,\n expirationDate = new UniversalTime(a.ValidationDate).ToString(\"yyyy-MM-dd\"),\n documentType = Controllers.rpmdataController.DocumentType.Licence\n }).ToList());\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42564/"
] |
361,922 | <p>I am trying to create 1 Parent Drop Down, that has 2 dependent child drop down lists using JAVASCRIPT.</p>
<p>My html page is at - <a href="http://www.larkgrove.com/entryform/entryform.html" rel="nofollow noreferrer">http://www.larkgrove.com/entryform/entryform.html</a></p>
<p>I am using the Dynamic Options Lists / Dependent Selects:
<a href="http://www.javascripttoolbox.com/lib/dynamicoptionlist/examples.php" rel="nofollow noreferrer">http://www.javascripttoolbox.com/lib/dynamicoptionlist/examples.php</a></p>
<p>If you check out my site, you can see that I can get the Child lists to change between nothing there and "NULL", but thats about all I can do.</p>
<p>THANKS!</p>
| [
{
"answer_id": 361987,
"author": "danieltalsky",
"author_id": 22452,
"author_profile": "https://Stackoverflow.com/users/22452",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\nvar TESTLIST = new DynamicOptionList(\"PARENT1\",\"CHILD1\",\"CHILD2\");\nTESTLIST.forValue(\"A\").forValue(\"A\").forValue(\"A\").addOptionsTextValue(\"C\",\"C\",\"D\",\"D\");\n</script>\n<select name=\"PARENT1\">\n <option value=\"A\">A</option>\n <option value=\"B\">B</option>\n</select>\n<br /><br />\n<select name=\"CHILD1\"><script type=\"text/javascript\">TESTLIST.printOptions(\"CHILD1\")</script></select>\n<br /><br />\n<select name=\"CHILD2\"><script type=\"text/javascript\">TESTLIST.printOptions(\"CHILD2\")</script></select>\n TESTLIST.forValue(\"A\").forValue(\"A\").forValue(\"A\").addOptionsTextValue(\"C\",\"C\",\"D\",\"D\");\n regionState.forValue(\"west\").addOptions(\"California\",\"Washington\",\"Oregon\");\n TESTLIST.forValue(\"A\").addOptionsTextValue(\"C\",\"D\");\nTESTLIST.forValue(\"B\").addOptionsTextValue(\"E\",\"F\");\n"
},
{
"answer_id": 362010,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 1,
"selected": false,
"text": "<select id=\"parentList\" onchange=\"parentList_OnChange(this)\">\n <option>Choose an option</option>\n <option value=\"A\">A</option>\n <option value=\"B\">B</option>\n <option value=\"C\">C</option>\n <option value=\"D\">D</option>\n</select>\n\n<select id=\"childList1\"></select>\n<select id=\"childList2\"></select>\n // Data for child list 1, this is a of the parent value to one or more options\nvar childList1Data = {\n \"A\": [\"ChildList1 - A1\", \"ChildList1 - A2\", \"ChildList1 - A3\"],\n \"B\": [\"ChildList1 - B1\"],\n \"C\": [\"ChildList1 - C1\", \"ChildList1 - C2\"],\n \"D\": [\"ChildList1 - D1\", \"ChildList1 - D2\"]\n};\n\n\n// Data for child list 2, this is a of the parent value to one or more options\nvar childList2Data = {\n \"A\": [\"ChildList2 - A1\", \"ChildList2 - A2\"],\n \"B\": [\"ChildList2 - B1\", \"ChildList2 - B2\", \"ChildList2 - B3\"],\n \"C\": [\"ChildList2 - C1\", \"ChildList2 - C2\"],\n \"D\": [\"ChildList2 - D1\"]\n};\n\n\n// onchange is called when the parent value is changed\nfunction parentList_OnChange(objParentList) {\n var child1 = document.getElementById(\"childList1\");\n var child2 = document.getElementById(\"childList2\");\n\n // Remove all options from both child lists\n removeOptions(child1);\n removeOptions(child2);\n\n // Lookup and get the array of values for child list 1, using the parents selected value\n var child1Data = childList1Data[objParentList.options[objParentList.selectedIndex].value];\n\n // Add the options to child list 1\n if (child1Data) {\n for (var i = 0; i < child1Data.length; i++) {\n child1.options[i] = new Option(child1Data[i], child1Data[i]);\n }\n }\n\n\n // Do the same for the second list\n var child2Data = childList2Data[objParentList.options[objParentList.selectedIndex].value];\n\n if (child2Data) {\n for (var i = 0; i < child2Data.length; i++) {\n child2.options[i] = new Option(child2Data[i], child2Data[i]);\n }\n }\n}\n\n\nfunction removeOptions(objSelect) {\n while (objSelect.options.length > 0)\n objSelect.options[0] = null;\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
361,930 | <p>Are all these types of sites just illegally scraping Google or another search engine?<br>
As far as I can tell ther is no 'legal' way to get this data for a commercial site.. The Yahoo! api ( <a href="http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html" rel="nofollow noreferrer">http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html</a> ) is only for noncommercial use, Yahoo! Boss does not allow automated queries etc.<br>
Any ideas?</p>
| [
{
"answer_id": 754901,
"author": "Shalom Craimer",
"author_id": 54491,
"author_profile": "https://Stackoverflow.com/users/54491",
"pm_score": 2,
"selected": false,
"text": "link:http://www.google.com\n link:URL\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45598/"
] |
361,943 | <p>I wanted to know why UDP is used in RTP rather than TCP ?. Major VoIP Tools used only UDP as i hacked some of the VoIP OSS.</p>
| [
{
"answer_id": 1910859,
"author": "rdegges",
"author_id": 194175,
"author_profile": "https://Stackoverflow.com/users/194175",
"pm_score": 0,
"selected": false,
"text": "rtpchecksums=yes ; or no if you prefer\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38038/"
] |
361,955 | <p>I'm trying to build about 600 projects some are .net 2.0, some are 3.5. I'm using Windows 2003 Enterprise Edition 32 bit with all the latest windows updates.</p>
<p>Builds fine when maxcpucount is 1. If I bump it up to try and improve performance it get reference errors. When I look at the project references from where the error occurred it appears they should have been built in order.</p>
<p>Below I've provided an example of the errors that are causing the build to be broken. Don't get hung up on the project names or the relative paths because I've changed this so I don't get in trouble with my employer.</p>
<p>It's like the relative project references can't be properly resolved when more then one core is building the solution.</p>
<pre><code>"C:\SVN\MyLibrary\MyLibrary.csproj" (default target) (15) ->
"C:\SVN\FileProcessor\FileProcessor.csproj" (default target) (17) ->
(ResolveProjectReferences target) ->
C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets : warning : The referenced project '..\..\Manager\Manager.csproj' does not exist.
"C:\SVN\MyLibrary\MyLibrary.csproj" (default target) (15) ->
"C:\SVN\FileProcessor\FileProcessor.csproj" (default target) (17) ->
(CoreCompile target) ->
FileProcessor.cs(18,39): error CS0234: The type or namespace name 'Manager' does not exist in the namespace 'TheNamespace' (are you missing an assembly reference?)
</code></pre>
<p>I'm not using msbuild on a solution file. I'm using wildcards to select all csproj files then feeding them to msbuild. For development we have multiple solutions we use for different components of the system. 95% are project reference, the only binary references are for core utility libs</p>
| [
{
"answer_id": 378668,
"author": "Gregg",
"author_id": 18266,
"author_profile": "https://Stackoverflow.com/users/18266",
"pm_score": 3,
"selected": false,
"text": "\n<ProjectReference Include=\"..\\..\\Manager\\Manager.csproj\">\n <Project>{C0F60D74-3EF9-4B49-9563-66E70D0DDF43}</Project>\n <Name>Manager</Name>\n</ProjectReference>\n \n<Reference Include=\"Manager.dll, Version=2.0.0.0, Culture=neutral, PublicKeyToken=e79aa50eb4f67b0c, processorArchitecture=MSIL\">\n <SpecificVersion>False</SpecificVersion>\n <HintPath>....\\Manager\\Manager.dll</HintPath>\n</Reference>\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45005/"
] |
361,966 | <p>I need to create a 3D model of a cube with a circular hole punched at the center of one face passing completely through the cube to the opposite side. I am able to generate the vertices for the faces and for the holes.</p>
<p>Four of the faces (untouched by the hole) can be modeled as a single triangle strip. The inside of the hole can also be modeled as a single triangle strip.</p>
<p>How do I generate the index buffer for the faces with the holes? Is there a standard algorithm(s) to do this?</p>
<p>I am using Direct3D but ideas from elsewhere are welcome.</p>
| [
{
"answer_id": 362130,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "(x/M,y/M) M max(abs(x),abs(y)) M (x,y) from math import sin, cos, pi\nfrom itertools import izip\n\ndef pairs(iterable):\n \"\"\"Yields the previous and the current item on each iteration.\n \"\"\"\n last = None\n for item in iterable:\n if last is not None:\n yield last, item\n last = item\n\ndef circle(radius, subdiv):\n \"\"\"Yields coordinates of a circle.\n \"\"\"\n for angle in xrange(0,subdiv+1):\n x = radius * cos(angle * 2 * pi / subdiv)\n y = radius * sin(angle * 2 * pi / subdiv)\n yield x, y\n\ndef line(x0,y0,x1,y1,subdiv):\n \"\"\"Yields coordinates of a line.\n \"\"\"\n for t in xrange(subdiv+1):\n x = (subdiv - t)*x0 + t*x1\n y = (subdiv - t)*y0 + t*y1\n yield x/subdiv, y/subdiv\n\ndef tesselate_square_with_hole((x,y),(w,h), radius=0.5, subdiv_circle=64, subdiv_ray=8):\n \"\"\"Yields quads of a tesselated square with a circluar hole.\n \"\"\"\n for (x0,y0),(x1,y1) in pairs(circle(radius,subdiv_circle)):\n M0 = max(abs(x0),abs(y0))\n xM0, yM0 = x0/M0, y0/M0\n\n M1 = max(abs(x1),abs(y1))\n xM1, yM1 = x1/M1, y1/M1\n\n L1 = line(x0,y0,xM0,yM0,subdiv_ray)\n L2 = line(x1,y1,xM1,yM1,subdiv_ray)\n for ((xa,ya),(xb,yb)),((xc,yc),(xd,yd)) in pairs(izip(L1,L2)):\n yield ((x+xa*w/2,y+ya*h/2),\n (x+xb*w/2,y+yb*h/2),\n (x+xc*w/2,y+yc*h/2),\n (x+xd*w/2,y+yd*h/2))\n\n\nimport pygame\ndef main():\n \"\"\"Simple pygame program that displays the tesselated figure.\n \"\"\"\n print('Calculating faces...')\n faces = list(tesselate_square_with_hole((150,150),(200,200),0.5,64,8))\n print('done')\n\n pygame.init()\n pygame.display.set_mode((300,300))\n surf = pygame.display.get_surface()\n running = True\n\n while running:\n need_repaint = False\n for event in pygame.event.get() or [pygame.event.wait()]:\n if event.type == pygame.QUIT:\n running = False\n elif event.type in (pygame.VIDEOEXPOSE, pygame.VIDEORESIZE):\n need_repaint = True\n if need_repaint:\n print('Repaint')\n surf.fill((255,255,255))\n for pa,pb,pc,pd in faces:\n # draw a single quad with corners (pa,pb,pd,pc)\n pygame.draw.aalines(surf,(0,0,0),True,(pa,pb,pd,pc),1)\n pygame.display.flip()\n\ntry:\n main()\nfinally:\n pygame.quit()\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
] |
361,973 | <p>I have written my program in c# .net. I want to convert it in to a powershell cmdlet. I was instructed to use pssnapin and getproc programs. Can anyone plz help me out..</p>
<p>Regards
Arun</p>
| [
{
"answer_id": 362191,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": 2,
"selected": false,
"text": "namespace System.Management.Automation\n{\n public abstract class PSCmdlet : Cmdlet\n {\n protected PSCmdlet();\n\n public PSHost Host { get; }\n public CommandInvocationIntrinsics InvokeCommand { get; }\n public ProviderIntrinsics InvokeProvider { get; }\n public InvocationInfo MyInvocation { get; }\n public string ParameterSetName { get; }\n public SessionState SessionState { get; }\n\n public PathInfo CurrentProviderLocation(string providerId);\n public Collection<string> GetResolvedProviderPathFromPSPath(string path, out ProviderInfo provider);\n public string GetUnresolvedProviderPathFromPSPath(string path);\n public object GetVariableValue(string name);\n public object GetVariableValue(string name, object defaultValue);\n }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201406/"
] |
361,975 | <p>How do I properly set the default character encoding used by the JVM (1.5.x) programmatically?</p>
<p>I have read that <code>-Dfile.encoding=whatever</code> used to be the way to go for older JVMs. I don't have that luxury for reasons I wont get into.</p>
<p>I have tried:</p>
<pre><code>System.setProperty("file.encoding", "UTF-8");
</code></pre>
<p>And the property gets set, but it doesn't seem to cause the final <code>getBytes</code> call below to use UTF8:</p>
<pre><code>System.setProperty("file.encoding", "UTF-8");
byte inbytes[] = new byte[1024];
FileInputStream fis = new FileInputStream("response.txt");
fis.read(inbytes);
FileOutputStream fos = new FileOutputStream("response-2.txt");
String in = new String(inbytes, "UTF8");
fos.write(in.getBytes());
</code></pre>
| [
{
"answer_id": 361984,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 5,
"selected": false,
"text": "String.getBytes(\"charsetName\") String.getBytes()"
},
{
"answer_id": 362006,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 9,
"selected": true,
"text": "file.encoding String.getBytes() InputStreamReader OutputStreamWriter JAVA_TOOL_OPTIONS java -Dfile.encoding=UTF-8 … com.x.Main\n Charset.defaultCharset() file.encoding file.encoding Charset.defaultCharset()"
},
{
"answer_id": 370421,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 1,
"selected": false,
"text": "DataOutputStream.writeUTF(String) byte inbytes[] = new byte[1024];\nFileInputStream fis = new FileInputStream(\"response.txt\");\nfis.read(inbytes);\nString in = new String(inbytes, \"UTF8\");\nDataOutputStream out = new DataOutputStream(new FileOutputStream(\"response-2.txt\"));\nout.writeUTF(in); // no getBytes() here\n"
},
{
"answer_id": 623036,
"author": "dwardu",
"author_id": 75183,
"author_profile": "https://Stackoverflow.com/users/75183",
"pm_score": 8,
"selected": false,
"text": "JAVA_TOOL_OPTIONS JAVA_TOOL_OPTIONS -Dfile.encoding=UTF8 System System.err Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8"
},
{
"answer_id": 8932021,
"author": "lizi",
"author_id": 312292,
"author_profile": "https://Stackoverflow.com/users/312292",
"pm_score": 0,
"selected": false,
"text": "file.encoding=UTF8\nclient.encoding.override=UTF-8\n"
},
{
"answer_id": 8945913,
"author": "Emmanuel.B",
"author_id": 1161197,
"author_profile": "https://Stackoverflow.com/users/1161197",
"pm_score": 4,
"selected": false,
"text": " new OutputStreamWriter( new FileOutputStream(\"Your_file_fullpath\" ),Charset.forName(\"UTF8\"))\n"
},
{
"answer_id": 14987992,
"author": "naskoos",
"author_id": 2092680,
"author_profile": "https://Stackoverflow.com/users/2092680",
"pm_score": 6,
"selected": false,
"text": "System.setProperty(\"file.encoding\",\"UTF-8\");\nField charset = Charset.class.getDeclaredField(\"defaultCharset\");\ncharset.setAccessible(true);\ncharset.set(null,null);\n"
},
{
"answer_id": 21009671,
"author": "D Bright",
"author_id": 3175616,
"author_profile": "https://Stackoverflow.com/users/3175616",
"pm_score": 3,
"selected": false,
"text": "-Dfile.encoding=UTF8 unicode/UTF-8 Java/Tomcat ~/.bashrc"
},
{
"answer_id": 24550034,
"author": "Lavixu",
"author_id": 1651085,
"author_profile": "https://Stackoverflow.com/users/1651085",
"pm_score": 3,
"selected": false,
"text": "String s = \"एक गाव में एक किसान\";\nString out = new String(s.getBytes(\"UTF-8\"), \"ISO-8859-1\");\n"
},
{
"answer_id": 46747257,
"author": "midmaestro",
"author_id": 8776712,
"author_profile": "https://Stackoverflow.com/users/8776712",
"pm_score": 0,
"selected": false,
"text": "-Dfile.encoding=MS950 -Duser.language=zh -Duser.country=TW -Dsun.jnu.encoding=MS950\n"
},
{
"answer_id": 48952844,
"author": "Michail Michailidis",
"author_id": 986160,
"author_profile": "https://Stackoverflow.com/users/986160",
"pm_score": 3,
"selected": false,
"text": "file.encoding mvn spring-boot:run -Drun.jvmArguments=\"-Dfile.encoding=UTF-8\"\n JTwig ANSI_X3.4-1968 System.out.println(System.getProperty(\"file.encoding\"));"
},
{
"answer_id": 49126338,
"author": "prabushi samarakoon",
"author_id": 9449998,
"author_profile": "https://Stackoverflow.com/users/9449998",
"pm_score": 1,
"selected": false,
"text": "mvn clean install -Dfile.encoding=UTF-8 -Dmaven.repo.local=/path-to-m2\n Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0\nError occurred during initialization of VM\njava.nio.charset.IllegalCharsetNameException: \"UTF-8\"\n at java.nio.charset.Charset.checkName(Charset.java:315)\n at java.nio.charset.Charset.lookup2(Charset.java:484)\n at java.nio.charset.Charset.lookup(Charset.java:464)\n at java.nio.charset.Charset.defaultCharset(Charset.java:609)\n at sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:56)\n at java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:111)\n at java.io.PrintStream.<init>(PrintStream.java:104)\n at java.io.PrintStream.<init>(PrintStream.java:151)\n at java.lang.System.newPrintStream(System.java:1148)\n at java.lang.System.initializeSystemClass(System.java:1192)\n"
},
{
"answer_id": 56870696,
"author": "JacobTheKnitter",
"author_id": 6807182,
"author_profile": "https://Stackoverflow.com/users/6807182",
"pm_score": 2,
"selected": false,
"text": " -Dfile.encoding=UTF-8 \n <jvmArguments>\n -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8001\n -Dfile.encoding=UTF-8\n </jvmArguments>\n"
},
{
"answer_id": 63303242,
"author": "Febix",
"author_id": 3785939,
"author_profile": "https://Stackoverflow.com/users/3785939",
"pm_score": 1,
"selected": false,
"text": "File->Settings...->Editor-> File Encodings System.setProperty(\"file.encoding\",\"UTF-8\"); System.out.println(\"My project encoding is : \"+ Charset.defaultCharset());"
},
{
"answer_id": 69849422,
"author": "theseventhsense",
"author_id": 11241086,
"author_profile": "https://Stackoverflow.com/users/11241086",
"pm_score": 1,
"selected": false,
"text": "java -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 file.encoding=UTF-8 sun.jnu.encoding=UTF-8"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/361975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
362,000 | <p>I have this input text:</p>
<pre><code><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body><table cellspacing="0" cellpadding="0" border="0" align="center" width="603"> <tbody><tr> <td><table cellspacing="0" cellpadding="0" border="0" width="603"> <tbody><tr> <td width="314"><img height="61" width="330" src="/Elearning_Platform/dp_templates/dp-template-images/awards-title.jpg" alt="" /></td> <td width="273"><img height="61" width="273" src="/Elearning_Platform/dp_templates/dp-template-images/awards.jpg" alt="" /></td> </tr> </tbody></table></td> </tr> <tr> <td><table cellspacing="0" cellpadding="0" border="0" align="center" width="603"> <tbody><tr> <td colspan="3"><img height="45" width="603" src="/Elearning_Platform/dp_templates/dp-template-images/top-bar.gif" alt="" /></td> </tr> <tr> <td background="/Elearning_Platform/dp_templates/dp-template-images/left-bar-bg.gif" width="12"><img height="1" width="12" src="/Elearning_Platform/dp_templates/dp-template-images/left-bar-bg.gif" alt="" /></td> <td width="580"><p>&nbsp;what y all heard?</p><p>i'm shark oysters.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p></td> <td background="/Elearning_Platform/dp_templates/dp-template-images/right-bar-bg.gif" width="11"><img height="1" width="11" src="/Elearning_Platform/dp_templates/dp-template-images/right-bar-bg.gif" alt="" /></td> </tr> <tr> <td colspan="3"><img height="31" width="603" src="/Elearning_Platform/dp_templates/dp-template-images/bottom-bar.gif" alt="" /></td> </tr> </tbody></table></td> </tr> </tbody></table> <p>&nbsp;</p></body></html>
</code></pre>
<p>As you can see, there's no newline in this chunk of HTML text, and I need to look for all image links inside, copy them out to a directory, and change the line inside the text to something like <code>./images/file_name</code>. </p>
<p>Currently, the Perl code that I'm using looks like this:</p>
<pre><code>my ($old_src,$new_src,$folder_name);
foreach my $record (@readfile) {
## so the if else case for the url replacement block below will be correct
$old_src = "";
$new_src = "";
if ($record =~ /\<img(.+)/){
if($1=~/src=\"((\w|_|\\|-|\/|\.|:)+)\"/){
$old_src = $1;
my @tmp = split(/\/Elearning/,$old_src);
$new_src = "/media/www/vprimary/Elearning".$tmp[-1];
push (@images, $new_src);
$folder_name = "images";
}## end if
}
elsif($record =~ /background=\"(.+\.jpg)/){
$old_src = $1;
my @tmp = split(/\/Elearning/,$old_src);
$new_src = "/media/www/vprimary/Elearning".$tmp[-1];
push (@images, $new_src);
$folder_name = "images";
}
elsif($record=~/\<iframe(.+)/){
if($1=~/src=\"((\w|_|\\|\?|=|-|\/|\.|:)+)\"/){
$old_src = $1;
my @tmp = split(/\/Elearning/,$old_src);
$new_src = "/media/www/vprimary/Elearning".$tmp[-1];
## remove the ?rand behind the html file name
if($new_src=~/\?rand/){
my ($fname,$rand) = split(/\?/,$new_src);
$new_src = $fname;
my ($fname,$rand) = split(/\?/,$old_src);
$old_src = $fname."\\?".$rand;
}
print "old_src::$old_src\n"; ##s7test
print "new_src::$new_src\n\n"; ##s7test
push (@iframes, $new_src);
$folder_name = "iframes";
}## end if
}## end if
my $new_record = $record;
if($old_src && $new_src){
$new_record =~ s/$old_src/$new_src/ ;
print "new_record:$new_record\n"; ##s7test
my @tmp = split(/\//,$new_src);
$new_record =~ s/$new_src/\.\\$folder_name\\$tmp[-1]/;
## print "new_record2:$new_record\n\n"; ##s7test
}## end if
print WRITEFILE $new_record;
} # foreach
</code></pre>
<p>This is only sufficient to handle HTML text with newlines in them.
I thought only looping the regex statement,
but then i would have to change the matching line to some other text.</p>
<p>Do you have any idea if there an elegant Perl way to do this?
Or maybe I'm just too dumb to see the obvious way of doing it, plus I know putting global option doesn't work.</p>
<p>thanks.
~steve</p>
| [
{
"answer_id": 362090,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "while ($string =~ m/(?:\\<\\s*(?:img|iframe)[^\\>]+src\\s*=\\s*\\\"((?:\\w|_|\\\\|-|\\/|\\.|:)+)\\\"|background\\s*=\\s*\\\"([^\\>]+\\.jpg)|\\<\\s*iframe)/g) {\n $old_src = $1;\n my @tmp = split(/\\/Elearning/,$old_src);\n $new_src = \"/media/www/vprimary/Elearning\".$tmp[-1];\n if($new_src=~/\\?rand/){\n // remove rand and push in @iframes\n else\n {\n // push into @images\n }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38124/"
] |
362,032 | <p>I want the Perl script to extract a data from a text file and save it as another text file. Each line of the text file contains an URL to a jpg like "<a href="http://pics1.riyaj.com/thumbs/000/082/104//small.jpg" rel="nofollow noreferrer">http://pics1.riyaj.com/thumbs/000/082/104//small.jpg</a>". I want the script to extract the last 6 numbers of each jpg URL, (i.e 082104) to a variable. I want the variable to be added to a different location on each line of the new text.</p>
<p>Input text:</p>
<pre><code>text http://pics1.riyaj.com/thumbs/000/082/104/small.jpg text
text http://pics1.riyaj.com/thumbs/000/569/315/small.jpg text
</code></pre>
<p>Output text:</p>
<pre><code>text php?id=82104 text
text php?id=569315 text
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 362128,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 2,
"selected": false,
"text": "-p perl -pi.old -e 's|http://.*/\\d+/(\\d+)/(\\d+).*?jpg|php?id=$1$2|' inputfile > outputfile\n"
},
{
"answer_id": 362139,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 1,
"selected": false,
"text": "use FileHandle;\n\nmy $jpeg_RE = qr{\n (.*?) # Anything, watching out for patterns ahead\n \\s+ # At least one space\n (?> http:// ) # Once we match \"http://\" we're onto the next section\n \\S*? # Any non-space, watching out for what follows\n ( (?: \\d+ / )* # At least one digit, followed by a slash, any number of times\n \\d+ # another group of digits\n ) # end group\n \\D*? # Any number of non-digits looking ahead\n \\.jpg # literal string '.jpg'\n \\s+ # At least one space\n (.*) # The rest of the line\n}x;\n\nmy $infile = FileHandle->new( \"<$file_in\" );\nmy $outfile = FileHandle->new( \">$file_out\" );\n\nwhile ( my $line = <$infile> ) { \n my ( $pre_text, $digits, $post_text ) = ( $line =~ m/$jpeg_RE/ );\n $digits =~ s/\\D//g;\n $outfile->printf( \"$pre_text php?id=%s $post_text\\n\", substr( $digits, -6 ));\n}\n$infile->close();\n use FileHandle;\nmy $jpeg_RE = qr{\n (?> \\Qhttp://pics1.riyaj.com/thumbs/\\E ) \n \\d{3}\n /\n ( \\d{3} )\n / \n ( \\d{3} )\n \\S*?\n \\.jpg\n}x;\n\nmy $infile = FileHandle->new( \"<$file_in\" );\nmy $outfile = FileHandle->new( \">$file_out\" );\n\nwhile ( my $line = <$infile> ) { \n $line =~ s/$jpeg_RE/php?id=$1$2/g;\n $outfile->print( $line );\n}\n$infile->close();\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45614/"
] |
362,038 | <p>I need to build a div with curved corner border, with out using any images in the corner. Is it possible?</p>
<p>I dont want to insert curved images in the corner, Please help me regarding this.</p>
| [
{
"answer_id": 362047,
"author": "alex",
"author_id": 31671,
"author_profile": "https://Stackoverflow.com/users/31671",
"pm_score": 3,
"selected": false,
"text": "border-radius: 10px;\n"
},
{
"answer_id": 362056,
"author": "jimg",
"author_id": 2621,
"author_profile": "https://Stackoverflow.com/users/2621",
"pm_score": 3,
"selected": false,
"text": ".radius {\n-moz-border-radius: 6px;\n-webkit-border-radius:6px;\nborder-radius: 6px;\n }\n"
},
{
"answer_id": 363623,
"author": "Sal",
"author_id": 32144,
"author_profile": "https://Stackoverflow.com/users/32144",
"pm_score": 0,
"selected": false,
"text": ".rounded {background-color:#f1f0f1}\n.rounded .inner {padding:8px 10px 8px 12px}\n.rounded .c1 {height:1px;line-height:1px;font-size:1px;border-width: 0px 4px 0px 4px;border-color:#FFFFFF;border-style:solid;padding:0px}\n.rounded .c2 {height:1px;line-height:1px;font-size:1px;display:block;border-width: 0px 2px 0px 2px;border-color:#FFFFFF;border-style:solid;padding:0px}\n.rounded .c3 {height:2px;line-height:1px;font-size:1px;display:block;border-width: 0px 1px 0px 1px;border-color:#FFFFFF;border-style:solid;padding:0px}\n\n\n <div class=\"rounded\" style=\"width:200px;height:100px\">\n <div class=\"c1\"></div><div class=\"c2\"></div><div class=\"c3\"></div>\n <div class=\"inner\">\n -- Content Here --\n </div>\n <div class=\"c3\"></div><div class=\"c2\"></div><div class=\"c1\"></div>\n </div>\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38172/"
] |
362,042 | <p>We have a client application that has reference to a webservice. We had set the timeout property on the webclientprotocol object to 50 (ms) and wanted to observe what goes on. We tied up a long running webmethod that returns a huge DataSet to the client. When the default value was there, the DataSet was returned properly to the client. When we changed this to 50(ms), we did not observe anything. Our assumption was that there would be some kind of exception that occurs on the client side since the timeout has occurred. Can anyone please explain what is going on here</p>
<p>Thanks
Raj</p>
| [
{
"answer_id": 5386072,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 0,
"selected": false,
"text": "WebException Message TimeoutException"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
362,044 | <p><strong>My requirement</strong></p>
<p>A table needs to maintain a <em>status</em> column.</p>
<p>This column represents one of 5 states.</p>
<p><br>
<strong>initial design</strong></p>
<p>I figured I can just make it an integer column and represent the states using a numeric value.</p>
<ul>
<li>0 = start</li>
<li>1 = running</li>
<li>2 = crashed</li>
<li>3 = paused</li>
<li>4 = stopped</li>
</ul>
<p>Since I don't want my app to maintain the mapping from the integers to their string description, I plan to place those in a separate state description table (relying on a FK relation).</p>
<p>Then I discovered that MySQL has an ENUM type which matches my requirement exactly.
Other than a direct dependency on MySQL, are there any pitfalls with using the ENUM type?</p>
| [
{
"answer_id": 362058,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 8,
"selected": true,
"text": "ALTER TABLE INFORMATION_SCHEMA SELECT DISTINCT status"
},
{
"answer_id": 362888,
"author": "MatthieuP",
"author_id": 41469,
"author_profile": "https://Stackoverflow.com/users/41469",
"pm_score": 3,
"selected": false,
"text": "<empty> NULL"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24457/"
] |
362,055 | <p>Is it possible to host a Maven repository that serves the artifacts (at least the jar files) from SourceForge's file release system (since they are already there and SF provides download statistics and such)? </p>
<p>All the repositories I have seen use the same directory layout, but is that a must?
Download URLs would have to look more like <em><a href="http://sf.net/something.cgi?file-id=1234567" rel="nofollow noreferrer">http://sf.net/something.cgi?file-id=1234567</a></em></p>
<p>There would only be a small number of files in the project, so that maintaining the download URL in some kind of repository metadata XML file semi-manually is still an option.</p>
<p><strong>Note:</strong> This is kind of the opposite question to <a href="https://stackoverflow.com/questions/16487/how-can-i-deploy-artifacts-from-a-maven-build-to-the-sourceforge-file-release-s">How can I deploy artifacts from a Maven build to the SourceForge File Release System?</a></p>
<p><strong>Clarification:</strong> I want to put the files in the File Release System (Project Downloads), not the project web space or the subversion repository.</p>
| [
{
"answer_id": 1896946,
"author": "Huluvu424242",
"author_id": 373498,
"author_profile": "https://Stackoverflow.com/users/373498",
"pm_score": 0,
"selected": false,
"text": "<plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-install-plugin</artifactId>\n <executions>\n <execution>\n <goals>\n <goal>install</goal>\n </goals>\n <configuration>\n <createChecksum>true</createChecksum>\n </configuration>\n </execution>\n </executions>\n</plugin>\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14955/"
] |
362,059 | <p>What is the Big-O time complexity of the following nested loops:</p>
<pre class="lang-cpp prettyprint-override"><code>for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
System.out.println("i = " + i + " j = " + j);
}
}
</code></pre>
<p>Would it be <em>O(N^2)</em> still?</p>
| [
{
"answer_id": 59340933,
"author": "Ashwin",
"author_id": 6662058,
"author_profile": "https://Stackoverflow.com/users/6662058",
"pm_score": 2,
"selected": false,
"text": "for (int i = 0; i < n; i++)\n for (int j = i; j < n; j++)\n println(...);\n i For i = 0: println will execute 3 times\nfor i = 1: println will execute 2 times\nfor i = 2: println will execute 1 times\n println"
},
{
"answer_id": 71537431,
"author": "Deepthi Tabitha Bennet",
"author_id": 17112163,
"author_profile": "https://Stackoverflow.com/users/17112163",
"pm_score": 3,
"selected": false,
"text": "for (int i = 0; i < N; i++) { // outer loop\n for (int j = i + 1; j < N; j++) { // inner loop\n System.out.println(\"i = \" + i + \" j = \" + j);\n }\n}\n N - 1 N - 2 N - 3 N - 2 2 N - 1 1 N 0 N - 1 N - 2 N - 3 2 1 0 0 1 2 N - 3 N - 2 N - 1 (N - 1)((N - 1) + 1) / 2 (N - 1)(N) / 2 ((N^2) - N) / 2 O(N^2) System.out.println O(1)"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
] |
362,104 | <p>I have a Template Column under which I have Placed a Dropdownlist. Now I would Like to get the selectedRow of the datagrid on selectedIndeChanged event of the dropdownlist that's inside the template Column</p>
| [
{
"answer_id": 362177,
"author": "Tom Jelen",
"author_id": 28399,
"author_profile": "https://Stackoverflow.com/users/28399",
"pm_score": 2,
"selected": true,
"text": " protected void DropDown_SelectedIndexChanged(object sender, object eventdata)\n {\n int gridRowIndex = ((DataGridItem)((DropDownList)sender).Parent.Parent).ItemIndex;\n }\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
362,105 | <p>I have a Hash like this</p>
<pre><code>{ 55 => {:value=>61, :rating=>-147},
89 => {:value=>72, :rating=>-175},
78 => {:value=>64, :rating=>-155},
84 => {:value=>90, :rating=>-220},
95 => {:value=>39, :rating=>-92},
46 => {:value=>97, :rating=>-237},
52 => {:value=>73, :rating=>-177},
64 => {:value=>69, :rating=>-167},
86 => {:value=>68, :rating=>-165},
53 => {:value=>20, :rating=>-45}
}
</code></pre>
<p>How can i sort it by <strong><em>:rating</em></strong>? Or maybe i should use some different structure?</p>
| [
{
"answer_id": 362133,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 3,
"selected": false,
"text": ">> { :a => 4, :b => 12, :c => 3, :d => 8 }.sort_by { |key, value| value }\n=> [[:c, 3], [:a, 4], [:d, 8], [:b, 12]]\n hsh.sort_by {|key, ratings| ratings[:rating] }\n"
},
{
"answer_id": 362137,
"author": "danieltalsky",
"author_id": 22452,
"author_profile": "https://Stackoverflow.com/users/22452",
"pm_score": 2,
"selected": false,
"text": "my_hash = { \n 55 => {:value=>61, :rating=>-147},\n 89 => {:value=>72, :rating=>-175},\n 78 => {:value=>64, :rating=>-155},\n 84 => {:value=>90, :rating=>-220},\n 95 => {:value=>39, :rating=>-92},\n 46 => {:value=>97, :rating=>-237},\n 52 => {:value=>73, :rating=>-177},\n 64 => {:value=>69, :rating=>-167},\n 86 => {:value=>68, :rating=>-165},\n 53 => {:value=>20, :rating=>-45}\n}\n\nputs \"MY HASH\"\nmy_hash.each do |local|\n puts local\nend\n\nsorted_hash = my_hash.sort { | leftval, rightval | rightval[1][:rating]<=>leftval[1][:rating] }\n\nputs \"SORTED HASH\"\nsorted_hash.each do |local|\n puts local\nend\n"
},
{
"answer_id": 365178,
"author": "Milan Novota",
"author_id": 26123,
"author_profile": "https://Stackoverflow.com/users/26123",
"pm_score": 4,
"selected": true,
"text": "my_array =\n[\n {:id => 78, :value=>64, :rating=>-155},\n {:id => 84, :value=>90, :rating=>-220},\n {:id => 95, :value=>39, :rating=>-92}\n]\n my_array.sort_by { |record| record[:rating] }\n def my_array.find_by_id(id) \n self.find { |hash| hash[:id] == id }\nend\n my_array.find_by_id(id)\n my_hash[id]\n"
},
{
"answer_id": 72181262,
"author": "Crazy Cat",
"author_id": 4456511,
"author_profile": "https://Stackoverflow.com/users/4456511",
"pm_score": 0,
"selected": false,
"text": "Hash[result_hash.sort_by {|key, value| value[:rating] }]\n result_hash"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45622/"
] |
362,112 | <p>Consider a simple table with an auto-increment column like this:</p>
<pre><code>CREATE TABLE foo
(
`fooid` bigint unsigned NOT NULL auto_increment,
....snipped.... other columns
PRIMARY KEY (`fooid`)
)
ENGINE=InnoDB AUTO_INCREMENT=10
</code></pre>
<p>How does one redesign this so that we don't hit the max of the bigint datatype ?
The unsigned range is 0 to 18446744073709551615.
I don't know how long it will take to reach 18446744073709551615, but like the Y2K problem, I want to be ready for it.</p>
| [
{
"answer_id": 362471,
"author": "flamingLogos",
"author_id": 8161,
"author_profile": "https://Stackoverflow.com/users/8161",
"pm_score": 4,
"selected": false,
"text": "AUTO_INCREMENT INSERT INSERT INSERT AUTO_INCREMENT SMALLINT MySQL said:\n\n#1062 - Duplicate entry '65535' for key 1\n BIGINT TINYINT SMALLINT INSERT"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24457/"
] |
362,120 | <p>Why the FontFamily param of the Font object is a string and not an enum?</p>
| [
{
"answer_id": 362145,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 3,
"selected": true,
"text": "public enum MyEnum\n{\n A = 1,\n B = 2\n}\n\npublic enum FooEnum\n{\n A,\n B\n}\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text;\n using System.Drawing.Text;\n using System.Drawing;\n\n namespace ConsoleApplication19\n {\n class Program\n {\n static void Main(string[] args)\n {\n InstalledFontCollection ifc = new InstalledFontCollection();\n\n foreach (FontFamily o in ifc.Families)\n {\n Console.WriteLine(o.Name);\n }\n Console.ReadLine();\n }\n }\n }\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45624/"
] |
362,121 | <p>I have the following table</p>
<pre>
custid ordid qty datesold
1 A2 12 2008-01-05
2 A5 5 2008-01-02
1 A1 5 2008-01-01
2 A7 3 2007-02-05
</pre>
<p>What't the best way of getting the previous order for every customer?</p>
<p>Thanks</p>
| [
{
"answer_id": 362143,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 1,
"selected": false,
"text": "SELECT custid, ordid, qty, datesold\nFROM (\n SELECT *, \n Row_Number() OVER (PARTITION BY custid ORDER BY datesold desc) as 'Rank'\n FROM tbl\n)\nWHERE Rank = 1\n SELECT custid, ordid, qty, datesold\nFROM tbl\nWHERE id = \n (SELECT TOP 1 id FROM tbl a WHERE custid = a.custID ORDER BY dateSold)\n SELECT custid, ordid, qty, datesold\nFROM tbl\nINNER JOIN (\n SELECT a.id FROM tbl a GROUP BY tbl.custId\n) s ON tbl.id = s.id\n"
},
{
"answer_id": 362148,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "SELECT TOP 1\n ordid\nFROM\n orders\nWHERE\n custid = @custid\n and datesold < (SELECT MAX(datesold) FROM orders i where i.custid = orders.custid)\nORDER BY\n datesold DESC\n datesold datesold"
},
{
"answer_id": 362149,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "\nSELECT TOP 1 *\nFROM Orders\nWHERE DateSold < (SELECT DateSold FROM Orders WHERE CustId = 2 and OrdID = A5)\nAND CustId = 2 \n"
},
{
"answer_id": 362647,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "SELECT\n T1.ordid\nFROM\n dbo.Sales T1\nINNER JOIN dbo.Sales T2 ON\n T2.custid = T1.custid AND\n T2.datesold > T1.datesold\nLEFT OUTER JOIN dbo.Sales T3 ON\n T3.custid = T1.custid AND\n T3.datesold > T1.datesold AND\n T3.datesold < T2.datesold\nWHERE\n T1.custid = @custid AND\n T3.custid IS NULL\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
362,124 | <p>any generic way to trace/log values of all local variables when an exception occurs in a method?
(in C# 3)</p>
| [
{
"answer_id": 373934,
"author": "usman shaheen",
"author_id": 7722,
"author_profile": "https://Stackoverflow.com/users/7722",
"pm_score": 4,
"selected": true,
"text": "private static void TraceMethodArguments(MethodExecutionEventArgs eventArgs)\n{\n object[] parameters = eventArgs.GetReadOnlyArgumentArray();\n\n if (parameters != null)\n {\n string paramValue = null;\n foreach (object p in parameters)\n {\n Type _type = p.GetType();\n if (_type == typeof(string) || _type == typeof(int) || _type == typeof(double) || _type == typeof(decimal))\n {\n paramValue = (string)p;\n }\n else if (_type == typeof(XmlDocument))\n {\n paramValue = ((XmlDocument)p).OuterXml;\n }\n else\n { //try to serialize\n try\n {\n XmlSerializer _serializer = new XmlSerializer(p.GetType());\n StringWriter _strWriter = new StringWriter();\n\n _serializer.Serialize(_strWriter, p);\n paramValue = _strWriter.ToString();\n }\n catch\n {\n paramValue = \"Unable to Serialize Parameter\";\n }\n }\n Trace.TraceInformation(\"[\" + Process.GetCurrentProcess().Id + \"-\" + Thread.CurrentThread.ManagedThreadId.ToString() + \"]\" + \" Parameter: \" + paramValue);\n }\n }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7722/"
] |
362,154 | <p>I'm just reading Code Complete by Steve McConell and I'm thinking of an Example he gives in a section about loose coupling. It's about the interface of a method that calculates the number of holidays for an employee, which is calculated from the entry date of the employee and her sales. The author suggests a to have entry date and sales as the parameters of the method instead of an instance of the employee:</p>
<pre><code>int holidays(Date entryDate, Number sales)
</code></pre>
<p>instead of </p>
<pre><code>int holidays(Employee emp)
</code></pre>
<p>The argument is that this decouples the client of the method because it does not need to know anything about the Employee class.</p>
<p>Two things came to my mind:</p>
<ol>
<li><p>Providing all the parameters that are needed for the calculation breaks encapsulation. It shows the internals of the method on how it computes the result.</p></li>
<li><p>It's harder to change, e.g. when someone decides that also the age of the employee should be included in the calculation. One would have to change the signature.</p></li>
</ol>
<p>What's your opinion?</p>
| [
{
"answer_id": 362180,
"author": "Brian Rasmussen",
"author_id": 38206,
"author_profile": "https://Stackoverflow.com/users/38206",
"pm_score": 0,
"selected": false,
"text": "Sum(int a, int b)"
},
{
"answer_id": 362181,
"author": "Chuck Conway",
"author_id": 17360,
"author_profile": "https://Stackoverflow.com/users/17360",
"pm_score": 1,
"selected": false,
"text": "int holidays(Employee emp)\n"
},
{
"answer_id": 362299,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 3,
"selected": false,
"text": "Employee Employee IHolidayable"
},
{
"answer_id": 2075009,
"author": "dsimcha",
"author_id": 23903,
"author_profile": "https://Stackoverflow.com/users/23903",
"pm_score": 2,
"selected": false,
"text": "int holidays(Date entryDate, Number sales)\n int holidays(Employee emp)"
},
{
"answer_id": 2962537,
"author": "Veritte",
"author_id": 356992,
"author_profile": "https://Stackoverflow.com/users/356992",
"pm_score": 0,
"selected": false,
"text": "int holidays (IHolidayInfo obj)\n IHolidayInfo"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
] |
362,202 | <p>I am looking for a reference database that can be used to test for possible name typos in a contact database. This is for a batch process, so performance isn't a real issue. Ideally I'd like a comprehensive database, but even something like "top 5000" would go a long way. </p>
<p>Thanks!</p>
| [
{
"answer_id": 362303,
"author": "Mapad",
"author_id": 28165,
"author_profile": "https://Stackoverflow.com/users/28165",
"pm_score": 4,
"selected": false,
"text": "Phil, Phile, Philip, Philipp, Phillip, Felipe, Philippe"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
362,215 | <p>I want to build a threaded forum for an elearning site (opensource asp.net mvc ofcourse, though this doesn't matter for this question). </p>
<p>What should be the DB structure which will help retrieve the forum postings with optimum performance? I am not putting a no. to it as it may vary with the amount of rows being retrieved.</p>
<p>Besides I should be able to link a particular thread with another threads. For eg. show "Related Forum Links".</p>
<p>I am using SQL Server 2005.</p>
<p>The following is the structure that I have in mind (shamelessly took it from )
<a href="http://weblogs.asp.net/stephenwalther/archive/2008/09/05/asp-net-mvc-application-building-forums-3-post-messages.aspx" rel="nofollow noreferrer">Stephen Walther Excellent blog post</a></p>
<p>Table : Forum</p>
<pre><code>· Id
· ParentId (null if this is the first message)
· ParentThreadId (Identify message in the same thread)
· Author
· Subject
· Body
· PostedDate
</code></pre>
<p>Table: RelatedForum</p>
<pre><code>· ForumId
· RelatedForumId
</code></pre>
<p>Ideas/suggestions welcome.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 362230,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "WHERE ParentId = @SomeId ThreadId ForumId SELECT COUNT(*) FROM Postings WHERE ThreadId = @SomeId"
},
{
"answer_id": 362246,
"author": "Supernovah",
"author_id": 36076,
"author_profile": "https://Stackoverflow.com/users/36076",
"pm_score": 1,
"selected": false,
"text": "· ThreadId\n· UUID\n· Author\n· Subject\n· Body\n· PostedDate \n ·ThreadID\n·Forum\n·UUID\n·Author\n·Subject\n·Body\n·PostedDate\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34644/"
] |
362,222 | <p>I am actually rendering an excel file in the browser. I use the Response.Writefile(filePath) to dod this. It is working perfectly fine in few of the machines. I am getting a pop up with "Open","Save" and "Cancel" option. </p>
<p>But incase of few machines after i do a save click on the popup a plain empty page remains open. This happens only in few of the machines. This window just flickers in the other machine and closes by itself. Please let me know of what can be done to avoid this plain empty page to be closed by itself after the file is opened or saved.</p>
| [
{
"answer_id": 362712,
"author": "HectorMac",
"author_id": 1400,
"author_profile": "https://Stackoverflow.com/users/1400",
"pm_score": 3,
"selected": true,
"text": "Response.ContentType = \"application/x-excel\";\n Response.AddHeader(\"content-disposition\", \"inline; filename=\\\"\" + YourSuggestedFileName + \"\\\"\");\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
] |
362,231 | <p>I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string. </p>
<p>What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:</p>
<pre><code>matches = [s for s in allfiles if s.startswith(input)]
</code></pre>
<p>I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?</p>
| [
{
"answer_id": 362285,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "set_completer()"
},
{
"answer_id": 362433,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 4,
"selected": true,
"text": " a--t\n / \\ \nc r\n \\\n o--w\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
362,260 | <p>How does <code>const</code> (pointers, references and member functions) help with thread safety in C++?</p>
| [
{
"answer_id": 362362,
"author": "Evgeny Lazin",
"author_id": 42371,
"author_profile": "https://Stackoverflow.com/users/42371",
"pm_score": 3,
"selected": false,
"text": "class Foo\n{\n size_t size_;\npublic:\n ...\n size_t get_size() const\n {\n return size_\n }\n};\n\nclass Bar\n{\n boost::shared_ptr<Foo> foo_;\npublic:\n //accessor\n size_t get_size() const\n {\n size_t size = 0;\n if (foo_)\n size = foo_->size();\n return size;\n }\n //modifiers\n void init()\n {\n foo_ = new Foo;\n }\n\n void clear()\n {\n foo_ = boost::shared_ptr<Foo>();\n }\n};\n class Bar\n{\n boost::shared_ptr<Foo> foo_;\n mutable tbb::spin_rw_mutex lock_;\npublic:\n //accessor\n size_t get_size() const\n {\n size_t size = 0;\n //lock modifiers\n rw_mutex_type::scoped_lock lock(mutex, false);\n if (foo_)\n size = foo_->size();\n return size;\n }\n //modifiers\n void init()\n {\n //lock accessor and modifiers\n rw_mutex_type::scoped_lock lock(mutex, true);\n foo_ = new Foo;\n }\n\n void clear()\n {\n //lock accessor and modifiers\n rw_mutex_type::scoped_lock lock(mutex, true);\n foo_ = boost::shared_ptr<Foo>();\n }\n};\n"
},
{
"answer_id": 448353,
"author": "dsimcha",
"author_id": 23903,
"author_profile": "https://Stackoverflow.com/users/23903",
"pm_score": 2,
"selected": false,
"text": "Foo myVar;\nconst Foo* ptr1;\nFoo* ptr2;\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11828/"
] |
362,269 | <p>I am having a very strange problem. I have a very large regular expression searching for certain words in some text (RegEx looks something like this: <code>(?i)\b(a|b|c|d...)\b;</code> and so on where a, b, c, d, represent words). Anyway, I put it in a pre compiled assembly to speed things up a bit, however the problem is that pre compiled regex does not work the same way as a non compiled version of the same regex... o_0</p>
<p>For example if the regex is: <code>(?i)\b(he|desk)\b</code> and I pass "helpdesk" through it the pre compiled version returns "lp" so the words he and desk gets striped out as if the boundary condition is not working at all, however if I do use exactly the same regular expression a non pre compiled version it works just fine...
Does anyone know if I may be missing anything?</p>
<p>Thanks</p>
<p>(Sorry using VB.Net and C#)</p>
| [
{
"answer_id": 362370,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "\\w+"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45645/"
] |
362,278 | <p>I'm begginer in java I'm reading data from serial port and I have stored the data in string array data is 24 byte length.</p>
<p>Data I'm getting as output: 12120814330006050.0 </p>
<p>data also contains hexadecimal character in the string I want to read first character of the string. I have done:</p>
<pre><code>String str=dispArray[i].substring(1,2);
int i= Integer.parseInt(str,16);
System.out.println("Decimal:="+ i);
</code></pre>
<p>But I'm getting NumberFormatException.plz help me to read hexadecimal character.</p>
<p>Thanks for reply</p>
| [
{
"answer_id": 362289,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 2,
"selected": false,
"text": "str.getChar(0);\n Integer.parseInt(str,16);\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
362,300 | <p>I plan to use a distributed cache in my load-balanced webapp.
So I'm going to try to abstract out the common functions between apache ehcache and memcached.</p>
<p>My goal is to be able to make a simple configuration switch to select the caching solution to use. Should I go the SPI route e.g. like how XML parsers are wired in ?</p>
| [
{
"answer_id": 362289,
"author": "Markus Lausberg",
"author_id": 39062,
"author_profile": "https://Stackoverflow.com/users/39062",
"pm_score": 2,
"selected": false,
"text": "str.getChar(0);\n Integer.parseInt(str,16);\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24457/"
] |
362,326 | <p>I have 6 classes, which are all document types. All the document types have the same 8 fields. There is one class which consists of only these 8 fields. The rest of the classes have more fields. Some of these classes have the same fields (beside the 8 fields).</p>
<p>Example:</p>
<p>class Document: fields 1 to 8</p>
<p>class Form: fields 1 to 8 and field 9 and 10</p>
<p>class WorkInstruction: fields 1 to 8 and field 9 and 10</p>
<p>class Procedure: fields 1 to 10 and field 11</p>
<p>Hopefully this will make clear my point.</p>
<p>My question is, what is the best way to implement this? Should i make one or more interfaces, or should i use abstract classes?</p>
<p>Thnx</p>
| [
{
"answer_id": 362332,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "class Form : Document { ... }\n\n// Later on\nControls.Add(new DocumentDisplay(form));\n class Form\n{\n private Document Document { get; set; }\n // Other stuff\n}\n\n// Later on\nControls.Add (new DocumentDisplay(form.Document));\n"
},
{
"answer_id": 362487,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "class Document\n{\n List<Field> m_Fields;\n public void AddField(Field f) {... }\n public void AddFields(Field[] f) {... }\n}\n\nclass DocumentFactory()\n{\n public static Document GetDocument()\n {\n Document d = new Document();\n d.AddFields(GetDocumentFields()); // private helper .. returns fields 1-8\n return d; \n }\n public static Document GetForm()\n {\n Document d = new Document();\n AddDocumentFields(d);\n d.AddField(FIELD_9);\n d.AddField(FIELD_10);\n }\n // and so on..\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] |
362,328 | <p>I'm trying to run PHPDocumentor on my WAMPServer setup. It runs fine, but I'd like to exclude certain directories, such as \sqlbuddy\ which don't contain my own code. Ironically, PHPDocumentor appears to be ignoring my --ignore switch. I've tried several ways of expressing the same thing, but with the same result. Below is the command I'm running it with:</p>
<pre><code>php.exe "C:\Users\username\Documents\PhpDocumentor\phpdoc" -t "C:\Program Files\wamp\www\docs" -o HTML:default:default -d "C:\Program Files\wamp\www" --ignore sqlbuddy\ --ignore docs\
</code></pre>
<p>Many thanks.</p>
| [
{
"answer_id": 4105306,
"author": "Sonata",
"author_id": 498238,
"author_profile": "https://Stackoverflow.com/users/498238",
"pm_score": 3,
"selected": false,
"text": "--ignore sqlbuddy/,docs/"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742/"
] |
362,360 | <p>I am developing a Web Album using Grails and for image processing, I am using grails-image-tools plugin. I need a functionality to resize the images if the uploaded images size is too big (for eg: more than 600 * 840 ) . In this case I need to resize this image to 600 * 840). What is the most efficient way to do this? Thanks a lot.</p>
| [
{
"answer_id": 362411,
"author": "Warrior",
"author_id": 40933,
"author_profile": "https://Stackoverflow.com/users/40933",
"pm_score": 4,
"selected": true,
"text": "import java.awt.Image as AWTImage \nimport java.awt.image.BufferedImage \nimport javax.swing.ImageIcon \nimport javax.imageio.ImageIO as IIO \nimport java.awt.Graphics2D\n\n\nstatic resize = { bytes, out, maxW, maxH -> \n AWTImage ai = new ImageIcon(bytes).image \n int width = ai.getWidth( null ) \n int height = ai.getHeight( null )\n\n def limits = 300..2000 \n assert limits.contains( width ) && limits.contains( height ) : 'Picture is either too small or too big!'\n\n float aspectRatio = width / height float requiredAspectRatio = maxW / maxH\n\n int dstW = 0 \n int dstH = 0 \n if (requiredAspectRatio < aspectRatio) { \n dstW = maxW dstH = Math.round( maxW / aspectRatio) \n } else { \n dstH = maxH dstW = Math.round(maxH * aspectRatio) \n }\n\n BufferedImage bi = new BufferedImage(dstW, dstH, BufferedImage.TYPE_INT_RGB) \n Graphics2D g2d = bi.createGraphics() g2d.drawImage(ai, 0, 0, dstW, dstH, null, null) \n\n IIO.write( bi, 'JPEG', out )\n} \n"
},
{
"answer_id": 12204680,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 4,
"selected": false,
"text": "BuildConfig.groovy dependencies {\n compile 'org.imgscalr:imgscalr-lib:4.1' \n}\n BufferedImage thumbnail = Scalr.resize(image, 150);\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
] |
362,367 | <p>So in C#, I can treat a <code>string[]</code> as an <code>IEnumerable<string></code>.</p>
<p>Is there a Java equivalent?</p>
| [
{
"answer_id": 362387,
"author": "Learning",
"author_id": 18275,
"author_profile": "https://Stackoverflow.com/users/18275",
"pm_score": 3,
"selected": false,
"text": "Iterable <T>"
},
{
"answer_id": 362396,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 3,
"selected": false,
"text": "Iterable<String> Iterable<T> <=> IEnumerable<T>\nIterator<T> <=> IEnumerator<T>\n"
},
{
"answer_id": 362416,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 2,
"selected": false,
"text": "Iterable<String> String[] String[] strings = new String[]{\"this\", \"that\"};\nfor (String s : strings) {\n // do something\n}\n Iterable<String> String[] strings = new String[]{\"this\", \"that\"};\nIterable<String> stringIterable = Arrays.asList(strings);\n"
},
{
"answer_id": 366689,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 7,
"selected": true,
"text": "Iterable<String> IEnumerable<string> Iterable String[] Object[] Iterable<String> Iterable<Object> String[] Iterable String[] Iterable Iterable<String> strs = java.util.Arrays.asList(strArray);\n"
},
{
"answer_id": 35197992,
"author": "slavpetroff",
"author_id": 5510473,
"author_profile": "https://Stackoverflow.com/users/5510473",
"pm_score": 0,
"selected": false,
"text": "Iterable<T> stream() StreamSupport()"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35086/"
] |
362,384 | <p>I ask because I am sending a byte stream from a C process to Java. On the C side the 32 bit integer has the LSB is the first byte and MSB is the 4th byte.</p>
<p>So my question is: On the Java side when we read the byte as it was sent from the C process, what is <a href="https://en.wikipedia.org/wiki/Endianness" rel="noreferrer">endian</a> on the Java side?</p>
<p>A follow-up question: If the endian on the Java side is not the same as the one sent, how can I convert between them?</p>
| [
{
"answer_id": 362390,
"author": "Jonas Elfström",
"author_id": 44620,
"author_profile": "https://Stackoverflow.com/users/44620",
"pm_score": 4,
"selected": false,
"text": "int i = (int) b & 0xFF;\n long l = (long)b[0] & 0xFF;\nl += ((long)b[1] & 0xFF) << 8;\nl += ((long)b[2] & 0xFF) << 16;\nl += ((long)b[3] & 0xFF) << 24;\n"
},
{
"answer_id": 8432010,
"author": "WB Greene",
"author_id": 1087865,
"author_profile": "https://Stackoverflow.com/users/1087865",
"pm_score": 6,
"selected": false,
"text": "2**7 2**0 table[0x01]=0x80"
},
{
"answer_id": 54742400,
"author": "Donald W. Smith",
"author_id": 3127865,
"author_profile": "https://Stackoverflow.com/users/3127865",
"pm_score": 2,
"selected": false,
"text": " // Declare an array of 4 shorts to hold the four unsigned bytes\n short[] tempShort = new short[4];\n for (int b = 0; b < 4; b++) {\n tempShort[b] = (short)dIStream.readUnsignedByte(); \n }\n int curVal = convToInt(tempShort);\n\n // Pass an array of four shorts which convert from LSB first \n public int convToInt(short[] sb)\n {\n int answer = sb[0];\n answer += sb[1] << 8;\n answer += sb[2] << 16;\n answer += sb[3] << 24;\n return answer; \n }\n"
},
{
"answer_id": 70622171,
"author": "Javaddict",
"author_id": 5920099,
"author_profile": "https://Stackoverflow.com/users/5920099",
"pm_score": 2,
"selected": false,
"text": "int i=0xAABBCCDD\n byte[] b={0xAA,0xBB,0xCC,0xDD}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42303/"
] |
362,386 | <pre><code>dev%40bionic%2Dcomms%2Eco%2Euk
</code></pre>
<p>I want to turn the above back in to readable text. Can anyone tell me how? Thanks</p>
<p>EDIT
Forgive my oversight, PHP is the language of choice!</p>
| [
{
"answer_id": 362403,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 2,
"selected": false,
"text": "decodeURIComponent(\"dev%40bionic%2Dcomms%2Eco%2Euk\")"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] |
362,402 | <p>I have found <a href="http://www.jamesholmes.com/struts/console/help.html" rel="nofollow noreferrer">Struts Console Tool</a> but its development stopped in 2004, so it works with Netbeans 3.2.</p>
<p>Is there a way to install it under Netbeans 6.5?</p>
<p>Are there any options to edit struts-config.xml above the XML level?</p>
| [
{
"answer_id": 365162,
"author": "asalamon74",
"author_id": 21348,
"author_profile": "https://Stackoverflow.com/users/21348",
"pm_score": 2,
"selected": true,
"text": "struts-config.xml New/Struts Action struts-config.xml <action> struts-config.xml"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21047/"
] |
362,419 | <p>I'd like to periodically run an arbitrary .NET exe under a specified user account from a Windows Service. </p>
<p>So far I've got my windows service running with logic to decide what the target process is, and when to run it.
The target process is started in the following manner:</p>
<ol>
<li>The Windows Service is started using "administrator" credentials.</li>
<li>When the time comes, an intermediate .NET process is executed with arguments detailing which process should be started (filename, username, domain, password).</li>
<li>This process creates a new System.Diagnostics.Process, associates a ProcessStartInfo object filled with the arguments passed to it, and then calls Start() on the process object.</li>
</ol>
<p>The <strong>first time</strong> this happens, <strong>the target process executes fine and then closes normally</strong>. Every subsequent time however, as soon as the target process is started it throws the error "Application failed to initalize properly (0xc0000142)". Restarting the Windows Service will allow the process to run successfully once again (for the first execution).</p>
<p>Naturally, the goal is to have target process execute successfully every time.</p>
<p>Regarding step 2 above: To run a process as a different user .NET calls the win32 function CreateProcessWithLogonW. This function requires a window handle to log the specified user in. Since the Windows Service isn't running in Interactive Mode it has no window handle. This intermediate process solves the issue, as it has a window handle which can be passed to the target process.</p>
<p>Please, no suggestions of using psexec or the windows task planner. I've accepted my lot in life, and that includes solving the problem in the manner stated above.</p>
| [
{
"answer_id": 564429,
"author": "Matt Jacobsen",
"author_id": 15608,
"author_profile": "https://Stackoverflow.com/users/15608",
"pm_score": 6,
"selected": true,
"text": "Process proc = null;\nSystem.Diagnostics.ProcessStartInfo info;\nstring domain = string.IsNullOrEmpty(row.Domain) ? \".\" : row.Domain;\ninfo = new ProcessStartInfo(\"Starter.exe\");\ninfo.Arguments = cmd + \" \" + domain + \" \" + username + \" \" + password + \" \" + args;\ninfo.WorkingDirectory = Path.GetDirectoryName(cmd);\ninfo.UseShellExecute = false;\ninfo.RedirectStandardError = true;\ninfo.RedirectStandardOutput = true;\nproc = System.Diagnostics.Process.Start(info);\n class Program\n{\n #region Interop\n\n [StructLayout(LayoutKind.Sequential)]\n public struct LUID\n {\n public UInt32 LowPart;\n public Int32 HighPart;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n public struct LUID_AND_ATTRIBUTES\n {\n public LUID Luid;\n public UInt32 Attributes;\n }\n\n public struct TOKEN_PRIVILEGES\n {\n public UInt32 PrivilegeCount;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]\n public LUID_AND_ATTRIBUTES[] Privileges;\n }\n\n enum TOKEN_INFORMATION_CLASS\n {\n TokenUser = 1,\n TokenGroups,\n TokenPrivileges,\n TokenOwner,\n TokenPrimaryGroup,\n TokenDefaultDacl,\n TokenSource,\n TokenType,\n TokenImpersonationLevel,\n TokenStatistics,\n TokenRestrictedSids,\n TokenSessionId,\n TokenGroupsAndPrivileges,\n TokenSessionReference,\n TokenSandBoxInert,\n TokenAuditPolicy,\n TokenOrigin,\n TokenElevationType,\n TokenLinkedToken,\n TokenElevation,\n TokenHasRestrictions,\n TokenAccessInformation,\n TokenVirtualizationAllowed,\n TokenVirtualizationEnabled,\n TokenIntegrityLevel,\n TokenUIAccess,\n TokenMandatoryPolicy,\n TokenLogonSid,\n MaxTokenInfoClass\n }\n\n [Flags]\n enum CreationFlags : uint\n {\n CREATE_BREAKAWAY_FROM_JOB = 0x01000000,\n CREATE_DEFAULT_ERROR_MODE = 0x04000000,\n CREATE_NEW_CONSOLE = 0x00000010,\n CREATE_NEW_PROCESS_GROUP = 0x00000200,\n CREATE_NO_WINDOW = 0x08000000,\n CREATE_PROTECTED_PROCESS = 0x00040000,\n CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,\n CREATE_SEPARATE_WOW_VDM = 0x00001000,\n CREATE_SUSPENDED = 0x00000004,\n CREATE_UNICODE_ENVIRONMENT = 0x00000400,\n DEBUG_ONLY_THIS_PROCESS = 0x00000002,\n DEBUG_PROCESS = 0x00000001,\n DETACHED_PROCESS = 0x00000008,\n EXTENDED_STARTUPINFO_PRESENT = 0x00080000\n }\n\n public enum TOKEN_TYPE\n {\n TokenPrimary = 1,\n TokenImpersonation\n }\n\n public enum SECURITY_IMPERSONATION_LEVEL\n {\n SecurityAnonymous,\n SecurityIdentification,\n SecurityImpersonation,\n SecurityDelegation\n }\n\n [Flags]\n enum LogonFlags\n {\n LOGON_NETCREDENTIALS_ONLY = 2,\n LOGON_WITH_PROFILE = 1\n }\n\n enum LOGON_TYPE\n {\n LOGON32_LOGON_INTERACTIVE = 2,\n LOGON32_LOGON_NETWORK,\n LOGON32_LOGON_BATCH,\n LOGON32_LOGON_SERVICE,\n LOGON32_LOGON_UNLOCK = 7,\n LOGON32_LOGON_NETWORK_CLEARTEXT,\n LOGON32_LOGON_NEW_CREDENTIALS\n }\n\n enum LOGON_PROVIDER\n {\n LOGON32_PROVIDER_DEFAULT,\n LOGON32_PROVIDER_WINNT35,\n LOGON32_PROVIDER_WINNT40,\n LOGON32_PROVIDER_WINNT50\n }\n\n #region _SECURITY_ATTRIBUTES\n //typedef struct _SECURITY_ATTRIBUTES { \n // DWORD nLength; \n // LPVOID lpSecurityDescriptor; \n // BOOL bInheritHandle;\n //} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;\n #endregion\n struct SECURITY_ATTRIBUTES\n {\n public uint Length;\n public IntPtr SecurityDescriptor;\n public bool InheritHandle;\n }\n\n [Flags] enum SECURITY_INFORMATION : uint\n {\n OWNER_SECURITY_INFORMATION = 0x00000001,\n GROUP_SECURITY_INFORMATION = 0x00000002,\n DACL_SECURITY_INFORMATION = 0x00000004,\n SACL_SECURITY_INFORMATION = 0x00000008,\n UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000,\n UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000,\n PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000,\n PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000\n }\n\n #region _SECURITY_DESCRIPTOR\n //typedef struct _SECURITY_DESCRIPTOR {\n // UCHAR Revision;\n // UCHAR Sbz1;\n // SECURITY_DESCRIPTOR_CONTROL Control;\n // PSID Owner;\n // PSID Group;\n // PACL Sacl;\n // PACL Dacl;\n //} SECURITY_DESCRIPTOR, *PISECURITY_DESCRIPTOR;\n #endregion\n [StructLayoutAttribute(LayoutKind.Sequential)]\n struct SECURITY_DESCRIPTOR\n {\n public byte revision;\n public byte size;\n public short control; // public SECURITY_DESCRIPTOR_CONTROL control;\n public IntPtr owner;\n public IntPtr group;\n public IntPtr sacl;\n public IntPtr dacl;\n }\n\n #region _STARTUPINFO\n //typedef struct _STARTUPINFO { \n // DWORD cb; \n // LPTSTR lpReserved; \n // LPTSTR lpDesktop; \n // LPTSTR lpTitle; \n // DWORD dwX; \n // DWORD dwY; \n // DWORD dwXSize; \n // DWORD dwYSize; \n // DWORD dwXCountChars; \n // DWORD dwYCountChars; \n // DWORD dwFillAttribute; \n // DWORD dwFlags; \n // WORD wShowWindow; \n // WORD cbReserved2; \n // LPBYTE lpReserved2; \n // HANDLE hStdInput; \n // HANDLE hStdOutput; \n // HANDLE hStdError; \n //} STARTUPINFO, *LPSTARTUPINFO;\n #endregion\n struct STARTUPINFO\n {\n public uint cb;\n [MarshalAs(UnmanagedType.LPTStr)]\n public string Reserved;\n [MarshalAs(UnmanagedType.LPTStr)]\n public string Desktop;\n [MarshalAs(UnmanagedType.LPTStr)]\n public string Title;\n public uint X;\n public uint Y;\n public uint XSize;\n public uint YSize;\n public uint XCountChars;\n public uint YCountChars;\n public uint FillAttribute;\n public uint Flags;\n public ushort ShowWindow;\n public ushort Reserverd2;\n public byte bReserverd2;\n public IntPtr StdInput;\n public IntPtr StdOutput;\n public IntPtr StdError;\n }\n\n #region _PROCESS_INFORMATION\n //typedef struct _PROCESS_INFORMATION { \n // HANDLE hProcess; \n // HANDLE hThread; \n // DWORD dwProcessId; \n // DWORD dwThreadId; } \n // PROCESS_INFORMATION, *LPPROCESS_INFORMATION;\n #endregion\n [StructLayout(LayoutKind.Sequential)]\n struct PROCESS_INFORMATION\n {\n public IntPtr Process;\n public IntPtr Thread;\n public uint ProcessId;\n public uint ThreadId;\n }\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool InitializeSecurityDescriptor(IntPtr pSecurityDescriptor, uint dwRevision);\n const uint SECURITY_DESCRIPTOR_REVISION = 1;\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool SetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR sd, bool daclPresent, IntPtr dacl, bool daclDefaulted);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n extern static bool DuplicateTokenEx(\n IntPtr hExistingToken,\n uint dwDesiredAccess,\n ref SECURITY_ATTRIBUTES lpTokenAttributes,\n SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,\n TOKEN_TYPE TokenType,\n out IntPtr phNewToken);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n public static extern bool LogonUser(\n string lpszUsername,\n string lpszDomain,\n string lpszPassword,\n int dwLogonType,\n int dwLogonProvider,\n out IntPtr phToken\n );\n\n #region GetTokenInformation\n //BOOL WINAPI GetTokenInformation(\n // __in HANDLE TokenHandle,\n // __in TOKEN_INFORMATION_CLASS TokenInformationClass,\n // __out_opt LPVOID TokenInformation,\n // __in DWORD TokenInformationLength,\n // __out PDWORD ReturnLength\n //);\n #endregion\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool GetTokenInformation(\n IntPtr TokenHandle,\n TOKEN_INFORMATION_CLASS TokenInformationClass,\n IntPtr TokenInformation,\n int TokenInformationLength,\n out int ReturnLength\n );\n\n\n #region CreateProcessAsUser\n // BOOL WINAPI CreateProcessAsUser(\n // __in_opt HANDLE hToken,\n // __in_opt LPCTSTR lpApplicationName,\n // __inout_opt LPTSTR lpCommandLine,\n // __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,\n // __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,\n // __in BOOL bInheritHandles,\n // __in DWORD dwCreationFlags,\n // __in_opt LPVOID lpEnvironment,\n // __in_opt LPCTSTR lpCurrentDirectory,\n // __in LPSTARTUPINFO lpStartupInfo,\n // __out LPPROCESS_INFORMATION lpProcessInformation);\n #endregion\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n static extern bool CreateProcessAsUser(\n IntPtr Token, \n [MarshalAs(UnmanagedType.LPTStr)] string ApplicationName,\n [MarshalAs(UnmanagedType.LPTStr)] string CommandLine,\n ref SECURITY_ATTRIBUTES ProcessAttributes, \n ref SECURITY_ATTRIBUTES ThreadAttributes, \n bool InheritHandles,\n uint CreationFlags, \n IntPtr Environment, \n [MarshalAs(UnmanagedType.LPTStr)] string CurrentDirectory, \n ref STARTUPINFO StartupInfo, \n out PROCESS_INFORMATION ProcessInformation);\n\n #region CloseHandle\n //BOOL WINAPI CloseHandle(\n // __in HANDLE hObject\n // );\n #endregion\n [DllImport(\"Kernel32.dll\")]\n extern static int CloseHandle(IntPtr handle);\n\n [DllImport(\"advapi32.dll\", ExactSpelling = true, SetLastError = true)]\n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);\n\n [StructLayout(LayoutKind.Sequential, Pack = 1)]\n internal struct TokPriv1Luid\n {\n public int Count;\n public long Luid;\n public int Attr;\n }\n\n //static internal const int TOKEN_QUERY = 0x00000008;\n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;\n //static internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;\n\n internal const int TOKEN_QUERY = 0x00000008;\n internal const int TOKEN_DUPLICATE = 0x0002;\n internal const int TOKEN_ASSIGN_PRIMARY = 0x0001;\n\n #endregion\n\n [STAThread]\n static void Main(string[] args)\n {\n string username, domain, password, applicationName;\n username = args[2];\n domain = args[1];\n password = args[3];\n applicationName = @args[0];\n\n IntPtr token = IntPtr.Zero;\n IntPtr primaryToken = IntPtr.Zero;\n try\n {\n bool result = false;\n\n result = LogonUser(username, domain, password, (int)LOGON_TYPE.LOGON32_LOGON_NETWORK, (int)LOGON_PROVIDER.LOGON32_PROVIDER_DEFAULT, out token);\n if (!result)\n {\n int winError = Marshal.GetLastWin32Error();\n }\n\n string commandLine = null;\n\n #region security attributes\n SECURITY_ATTRIBUTES processAttributes = new SECURITY_ATTRIBUTES();\n\n SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR();\n IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(sd));\n Marshal.StructureToPtr(sd, ptr, false);\n InitializeSecurityDescriptor(ptr, SECURITY_DESCRIPTOR_REVISION);\n sd = (SECURITY_DESCRIPTOR)Marshal.PtrToStructure(ptr, typeof(SECURITY_DESCRIPTOR));\n\n result = SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false);\n if (!result)\n {\n int winError = Marshal.GetLastWin32Error();\n }\n\n primaryToken = new IntPtr();\n result = DuplicateTokenEx(token, 0, ref processAttributes, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out primaryToken);\n if (!result)\n {\n int winError = Marshal.GetLastWin32Error();\n }\n processAttributes.SecurityDescriptor = ptr;\n processAttributes.Length = (uint)Marshal.SizeOf(sd);\n processAttributes.InheritHandle = true;\n #endregion\n\n SECURITY_ATTRIBUTES threadAttributes = new SECURITY_ATTRIBUTES();\n threadAttributes.SecurityDescriptor = IntPtr.Zero;\n threadAttributes.Length = 0;\n threadAttributes.InheritHandle = false;\n\n bool inheritHandles = true;\n //CreationFlags creationFlags = CreationFlags.CREATE_DEFAULT_ERROR_MODE;\n IntPtr environment = IntPtr.Zero;\n string currentDirectory = currdir;\n\n STARTUPINFO startupInfo = new STARTUPINFO();\n startupInfo.Desktop = \"\";\n\n PROCESS_INFORMATION processInformation;\n\n result = CreateProcessAsUser(primaryToken, applicationName, commandLine, ref processAttributes, ref threadAttributes, inheritHandles, 16, environment, currentDirectory, ref startupInfo, out processInformation);\n if (!result)\n {\n int winError = Marshal.GetLastWin32Error();\n File.AppendAllText(logfile, DateTime.Now.ToLongTimeString() + \" \" + winError + Environment.NewLine);\n }\n }\n catch\n {\n int winError = Marshal.GetLastWin32Error();\n File.AppendAllText(logfile, DateTime.Now.ToLongTimeString() + \" \" + winError + Environment.NewLine);\n }\n finally\n {\n if (token != IntPtr.Zero)\n {\n int x = CloseHandle(token);\n if (x == 0)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n x = CloseHandle(primaryToken);\n if (x == 0)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n }\n"
},
{
"answer_id": 43679922,
"author": "Harry Berry",
"author_id": 809177,
"author_profile": "https://Stackoverflow.com/users/809177",
"pm_score": 0,
"selected": false,
"text": "var processStartInfo = new ProcessStartInfo()\n{\n FileName = $@\"{assemblyFolder}\\PhantomJS\\phantomjs.exe\",\n Arguments = $\"--webdriver={port}\",\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n RedirectStandardInput = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n ErrorDialog = false,\n WindowStyle = ProcessWindowStyle.Hidden\n};\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15608/"
] |
362,424 | <p>Lets say I have a concrete class Class1 and I am creating an anonymous class out of it.</p>
<pre><code>Object a = new Class1(){
void someNewMethod(){
}
};
</code></pre>
<p>Now is there any way I could overload the constructor of this anonymous class. Like shown below</p>
<pre><code>Object a = new Class1(){
void someNewMethod(){
}
public XXXXXXXX(int a){
super();
System.out.println(a);
}
};
</code></pre>
<p>With something at xxxxxxxx to name the constructor?</p>
| [
{
"answer_id": 362443,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "public class Test {\n public static void main(String[] args) throws Exception {\n final int fakeConstructorArg = 10;\n\n Object a = new Object() {\n {\n System.out.println(\"arg = \" + fakeConstructorArg);\n }\n };\n }\n}\n"
},
{
"answer_id": 362463,
"author": "Arne Burmeister",
"author_id": 12890,
"author_profile": "https://Stackoverflow.com/users/12890",
"pm_score": 7,
"selected": false,
"text": "final int anInt = ...;\nObject a = new Class1()\n{\n {\n System.out.println(anInt);\n }\n\n void someNewMethod() {\n }\n};\n"
},
{
"answer_id": 2026058,
"author": "Joel Shemtov",
"author_id": 206771,
"author_profile": "https://Stackoverflow.com/users/206771",
"pm_score": 6,
"selected": false,
"text": "public class Test{\n\n public static final void main(String...args){\n\n new Thread(){\n\n private String message = null;\n\n Thread initialise(String message){\n\n this.message = message;\n return this;\n }\n\n public void run(){\n System.out.println(message);\n }\n }.initialise(args[0]).start();\n }\n}\n"
},
{
"answer_id": 10465155,
"author": "arnaldocan",
"author_id": 1377250,
"author_profile": "https://Stackoverflow.com/users/1377250",
"pm_score": 1,
"selected": false,
"text": "Object a = getClass1(x);\n\npublic Class1 getClass1(int x) {\n class Class2 implements Class1 {\n void someNewMethod(){\n }\n public Class2(int a){\n super();\n System.out.println(a);\n }\n }\n Class1 c = new Class2(x);\n return c;\n}\n"
},
{
"answer_id": 11697472,
"author": "Whimusical",
"author_id": 1352530,
"author_profile": "https://Stackoverflow.com/users/1352530",
"pm_score": 2,
"selected": false,
"text": "Boolean var= new anonymousClass(){\n private String myVar; //String for example\n\n @Overriden public Boolean method(int i){\n //use myVar and i\n }\n public String setVar(String var){myVar=var; return this;} //Returns self instane\n}.setVar(\"Hello\").method(3);\n"
},
{
"answer_id": 14625945,
"author": "Peter Verhas",
"author_id": 1573682,
"author_profile": "https://Stackoverflow.com/users/1573682",
"pm_score": 2,
"selected": false,
"text": "static abstract class Q{\n int z;\n Q(int z){ this.z=z;}\n void h(){\n Q me = new Q(1) {\n };\n }\n}\n"
},
{
"answer_id": 26912508,
"author": "Diogo Quintela",
"author_id": 4248833,
"author_profile": "https://Stackoverflow.com/users/4248833",
"pm_score": 2,
"selected": false,
"text": "public class ResultsBuilder {\n Set<Result> errors;\n Set<Result> warnings;\n\n...\n\n public Results<E> build() {\n return new Results<E>() {\n private Result[] errorsView;\n private Result[] warningsView;\n {\n errorsView = ResultsBuilder.this.getErrors();\n warningsView = ResultsBuilder.this.getWarnings();\n }\n\n public Result[] getErrors() {\n return errorsView;\n }\n\n public Result[] getWarnings() {\n return warningsView;\n }\n };\n }\n\n public Result[] getErrors() {\n return !isEmpty(this.errors) ? errors.toArray(new Result[0]) : null;\n }\n\n public Result[] getWarnings() {\n return !isEmpty(this.warnings) ? warnings.toArray(new Result[0]) : null;\n }\n}\n"
},
{
"answer_id": 32715815,
"author": "Thirumalai Parthasarathi",
"author_id": 2416313,
"author_profile": "https://Stackoverflow.com/users/2416313",
"pm_score": 4,
"selected": false,
"text": "StoredProcedure sp = new StoredProcedure(datasource, spName) {\n {// init code if there are any}\n};\n StoredProcedure DataSource String"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27784/"
] |
362,426 | <p>What is the "cleanest" way to implement an command-line UI, similar to git's, for example:</p>
<pre><code>git push origin/master
git remote add origin git://example.com master
</code></pre>
<p>Ideally also allowing the more flexible parsing, for example,</p>
<pre><code>jump_to_folder app theappname v2
jump_to_folder app theappname source
jump_to_folder app theappname source v2
jump_to_folder app theappname build v1
jump_to_folder app theappname build 1
jump_to_folder app theappname v2 build
</code></pre>
<p><code>jump_to_folder</code> is the scripts name, <code>app</code> is the command, <code>theappname</code> is a "fixed-location" parameter, "build" and "v2" etc are arguments (For example, possible arguments would be any number/any number prefixed with a v, or build/source/tmp/config)</p>
<p>I could just manually parse the arguments with a series of <code>if</code>/<code>else</code>/<code>elifs</code>, but there must be a more elegant way to do this?</p>
<p>As an entirely theoretically example, I could describe the UI schema..</p>
<pre><code>app:
fixed: application_name
optional params:
arg subsection:
"build"
"source"
"tmp"
"config"
arg version:
integer
"v" + integer
</code></pre>
<p>Then parse the supplied arguments though the above schema, and get a dictionary:</p>
<pre><code>>>> print schema.parse(["app", "theappname", "v1", "source"])
{
"application_name": "theappname",
"params":{
"subsection": "source",
"version":"v1"
}
}
</code></pre>
<p>Does such a system exist? If not, how would I go about implementing something along these lines?</p>
| [
{
"answer_id": 362475,
"author": "klozovin",
"author_id": 33841,
"author_profile": "https://Stackoverflow.com/users/33841",
"pm_score": 2,
"selected": false,
"text": "import sys\n\ndef prog1_func1_act1(): print \"pfa1\"\ndef prog2_func2_act2(): print \"pfa2\"\n\ncommands = {\n \"prog1 func1 act1\": prog1_func1_act1,\n \"prog2 func2 act2\": prog2_func2_act2\n}\n\ntry:\n commands[\" \".join(sys.argv[1:])]()\nexcept KeyError:\n print \"Usage: \", commands.keys()\n"
},
{
"answer_id": 362700,
"author": "davidavr",
"author_id": 8247,
"author_profile": "https://Stackoverflow.com/users/8247",
"pm_score": 3,
"selected": false,
"text": "cmd import cmd\n\nclass Calc(cmd.Cmd):\n def do_add(self, arg):\n print sum(map(int, arg.split()))\n\nif __name__ == '__main__':\n Calc().cmdloop()\n $python calc.py\n(Cmd) add 4 5\n9\n(Cmd) help\n\nUndocumented commands:\n======================\nadd help\n\n(Cmd)\n"
},
{
"answer_id": 362936,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "jump_to_folder -n theappname -v2 cmd \njump_to_folder -n theappname cmd source \njump_to_folder -n theappname -v2 cmd source \njump_to_folder -n theappname -v1 cmd build \njump_to_folder -n theappname -1 cmd build \njump_to_folder -n theappname -v2 cmd build\n"
},
{
"answer_id": 10913734,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 5,
"selected": true,
"text": "import argparse\n\n\ndef main():\n arger = argparse.ArgumentParser()\n\n # Arguments for top-level, e.g \"subcmds.py -v\"\n arger.add_argument(\"-v\", \"--verbose\", action=\"count\", default=0)\n\n subparsers = arger.add_subparsers(dest=\"command\")\n\n # Make parser for \"subcmds.py info ...\"\n info_parser = subparsers.add_parser(\"info\")\n info_parser.add_argument(\"-m\", \"--moo\", dest=\"moo\")\n\n # Make parser for \"subcmds.py create ...\"\n create_parser = subparsers.add_parser(\"create\")\n create_parser.add_argument(\"name\")\n create_parser.add_argument(\"additional\", nargs=\"*\")\n\n # Parse\n opts = arger.parse_args()\n\n # Print option object for debug\n print opts\n\n if opts.command == \"info\":\n print \"Info command\"\n print \"--moo was %s\" % opts.moo\n\n elif opts.command == \"create\":\n print \"Creating %s\" % opts.name\n print \"Additional: %s\" % opts.additional\n\n else:\n # argparse will error on unexpected commands, but\n # in case we mistype one of the elif statements...\n raise ValueError(\"Unhandled command %s\" % opts.command)\n\n\nif __name__ == '__main__':\n main()\n $ python subcmds.py create myapp v1 blah\nNamespace(additional=['v1', 'blah'], command='create', name='myapp', verbose=0)\nCreating myapp\nAdditional: ['v1', 'blah']\n$ python subcmds.py info --moo\nusage: subcmds.py info [-h] [-m MOO]\nsubcmds.py info: error: argument -m/--moo: expected one argument\n$ python subcmds.py info --moo 1\nNamespace(command='info', moo='1', verbose=0)\nInfo command\n--moo was 1\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
362,428 | <p>This is a two part question. A dumb technical query and a broader query about my possibly faulty approach to learning to do some things in a language I'm new to.</p>
<p>I'm just playing around with a few Python GUI libraries (mostly wxPython and IronPython) for some work I'm thinking of doing on an open source app, just to improve my skills and so forth.</p>
<p>By day I am a pretty standard c# bod working with a pretty normal set of MS based tools and I am looking at Python to give me a new perspective. Thus using Ironpython Studio is probably cheating a bit (alright, a lot). This seems not to matter because however much it attempts to look like a Visual Studio project etc. There's one simple behaviour I'm probably being too dumb to implement.</p>
<p>I.E. How do I keep my forms in nice separate code files, like the c# monkey I have always been ,and yet invoke them from one another? I've tried importing the form to be invoked to the main form but I just can't seem to get the form to be recognized as anything other than an object. The new form appears to be a form object in its own code file, I am importing the clr. I am trying to invoke a form's 'Show' method. Is this not right?</p>
<p>I've tried a few (to my mind more unlikely) ways around this but the problem seems intractable. Is this something I'm just not seeing or would it in fact be more appropriate for me to change the way I think about my GUI scripting to fit round Python (in which case I may switch back to wxPython which seemed more approachable from a Pythonic point of view) rather than try to look at Python from the security of the Visual Studio shell?</p>
| [
{
"answer_id": 362868,
"author": "babbageclunk",
"author_id": 38851,
"author_profile": "https://Stackoverflow.com/users/38851",
"pm_score": 1,
"selected": false,
"text": "System.Windows.Forms.Form # in form.py\nfrom System.Windows.Forms import Form, Button, MessageBox\nclass TrivialForm(Form):\n def __init__(self):\n button = Button(Parent=self, Text='Click!')\n button.Click += self.show_message\n\n def show_message(self, sender, args):\n MessageBox.Show('Stop that!')\n\n# in main.py\nimport clr\nclr.AddReference('System.Windows.Forms')\nfrom System.Windows.Forms import Application\nfrom form import TrivialForm\nif __name__ == '__main__':\n f = TrivialForm()\n Application.Run(f)\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
362,429 | <p>I've created a utf8 encoded RSS feed which presents news data drawn from a database. I've set all aspects of my database to utf8 and also saved the text which i have put into the database as utf8 by pasting it into notepad and saving as utf8. So everything should be encoded in utf8 when the RSS feed is presented to the browser, however I am still getting the weird question mark characters for pound signs :( </p>
<p>Here is my RSS feed code (CFML):</p>
<pre><code><cfsilent>
<!--- Get News --->
<cfinvoke component="com.news" method="getAll" dsn="#Request.App.dsn#" returnvariable="news" />
</cfsilent>
<!--- If we have news items --->
cfif news.RecordCount GT 0>
<!--- Serve RSS content-type --->
<cfcontent type="application/rss+xml">
<!--- Output feed --->
<cfcontent reset="true"><?xml version="1.0" encoding="utf-8"?>
<cfoutput>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>News RSS Feed</title>
<link>#Application.siteRoot#</link>
<description>Welcome to the News RSS Feed</description>
<lastBuildDate>Wed, 19 Nov 2008 09:05:00 GMT</lastBuildDate>
<language>en-uk</language>
<atom:link href="#Application.siteRoot#news/rss/index.cfm" rel="self" type="application/rss+xml" />
<cfloop query="news">
<!--- Make data xml compliant --->
<cfscript>
news.headline = replace(news.headline, "<", "&lt;", "ALL");
news.body = replace(news.body, "<", "&lt;", "ALL");
news.date = dateformat(news.date, "ddd, dd mmm yyyy");
news.time = timeformat(news.time, "HH:mm:ss") & " GMT";
</cfscript>
<item>
<title>#news.headline#</title>
<link>#Application.siteRoot#news/index.cfm?id=#news.id#</link>
<guid>#Application.siteRoot#news/index.cfm?id=#news.id#</guid>
<pubDate>#news.date# #news.time#</pubDate>
<description>#news.body#</description>
</item>
</cfloop>
</channel>
</rss>
</cfoutput>
<cfelse>
<!--- If we have no news items, relocate to news page --->
<cflocation url="../news/index.cfm" addtoken="no">
</cfif>
</code></pre>
<p>Has anyone any suggestions? I've done loads of research but can't find any answers :(</p>
<p>Thanks in advance,</p>
<p>Chromis</p>
| [
{
"answer_id": 362649,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "& & £"
},
{
"answer_id": 363788,
"author": "rip747",
"author_id": 31278,
"author_profile": "https://Stackoverflow.com/users/31278",
"pm_score": 3,
"selected": false,
"text": "<item>\n <title>#XMLFormat(news.headline)#</title>\n <link>#Application.siteRoot#news/index.cfm?id=#XMLFormat(news.id)#</link>\n <guid>#Application.siteRoot#news/index.cfm?id=#XMLFormat(news.id)#</guid>\n <pubDate>#XMLFormat(news.date)# #XMLFormat(news.time)#</pubDate>\n <description>#XMLFormat(news.body)#</description>\n</item>\n"
},
{
"answer_id": 11550564,
"author": "Troy",
"author_id": 1536174,
"author_profile": "https://Stackoverflow.com/users/1536174",
"pm_score": 1,
"selected": false,
"text": "<cfcontent type=\"text/xml; charset=utf-8\" reset=\"yes\" />"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45427/"
] |
362,434 | <p>I dropped a database from SQL Server, however it turns out that <strong>my login</strong> was set to use the dropped database as its default. I can connect to SQL Server Management Studio by using the 'options' button in the connection dialog and selecting 'master' as the database to connect to. However, whenever I try to do anything in object explorer, it tries to connect using my default database and fails.</p>
<p>Does anyone know how to set my default database <strong>without using object explorer</strong>?</p>
| [
{
"answer_id": 362435,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 8,
"selected": false,
"text": "Exec sp_defaultdb @loginame='login', @defdb='master' \n"
},
{
"answer_id": 363496,
"author": "Greg B",
"author_id": 1741868,
"author_profile": "https://Stackoverflow.com/users/1741868",
"pm_score": 4,
"selected": false,
"text": "USE [SomeOtherDb]\nSELECT 'I am now using a different DB'\n"
},
{
"answer_id": 40423812,
"author": "gmesorio",
"author_id": 2246100,
"author_profile": "https://Stackoverflow.com/users/2246100",
"pm_score": 2,
"selected": false,
"text": "sqlcmd –E -S InstanceName –d master\n"
},
{
"answer_id": 47414134,
"author": "Marek",
"author_id": 168747,
"author_profile": "https://Stackoverflow.com/users/168747",
"pm_score": 7,
"selected": true,
"text": "ALTER LOGIN ALTER LOGIN [my_user_name] WITH DEFAULT_DATABASE = [new_default_database]\n sp_defaultdb domain\\username ALTER LOGIN me WITH DEFAULT_DATABASE = my_database\n ALTER LOGIN [EVILCORP\\j.smith28] WITH DEFAULT_DATABASE = [prod\\v-45]\n"
},
{
"answer_id": 51830521,
"author": "vapcguy",
"author_id": 1181535,
"author_profile": "https://Stackoverflow.com/users/1181535",
"pm_score": 1,
"selected": false,
"text": "master ALTER LOGIN [DOMAIN\\useracct] WITH DEFAULT_DATABASE=[master]\nGO\n"
},
{
"answer_id": 54842303,
"author": "Mubashar",
"author_id": 806076,
"author_profile": "https://Stackoverflow.com/users/806076",
"pm_score": 2,
"selected": false,
"text": "ALTER LOGIN"
},
{
"answer_id": 73736722,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "USE testdb\nGO\n SELECT DB_NAME()\nGO\n SELECT name FROM master.sys.databases\nGO\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553/"
] |
362,441 | <p>I am sure this is a very simple problem, but I am new to VB.NET, so I am having an issue with it.</p>
<p>I have a <code>Decimal</code> variable, and I need to split it into two separate variables, one containing the integer part, and one containing the fractional part. </p>
<p>For example, for x = 12.34 you would end up with a y = 12 and a z = 0.34.</p>
<p>Is there a nice built-in functions to do this or do I have to try and work it out manually?</p>
| [
{
"answer_id": 362453,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "Sub SplitDecimal(ByVal number As Decimal, ByRef wholePart As Decimal, _\n ByRef fractionalPart As Decimal)\n wholePart = Math.Truncate(number)\n fractionalPart = number - wholePart\nEnd Sub\n"
},
{
"answer_id": 362454,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 3,
"selected": false,
"text": " Sub SlipDecimal(ByVal Number As Decimal, ByRef IntegerPart As Integer, _\n ByRef DecimalPart As Decimal)\n IntegerPart = Int(Number)\n DecimalPart = Number - IntegerPart\n End Sub\n"
},
{
"answer_id": 36124036,
"author": "Ram",
"author_id": 193061,
"author_profile": "https://Stackoverflow.com/users/193061",
"pm_score": 2,
"selected": false,
"text": "DecimalNumber - Int(DecimalNumber)\n"
},
{
"answer_id": 67858509,
"author": "Meisam Rasouli",
"author_id": 8963814,
"author_profile": "https://Stackoverflow.com/users/8963814",
"pm_score": 0,
"selected": false,
"text": "Dim dbl as double = 13.067\nDim int1 As Integer = 0\nDim fraction As Double = 0\nIf dbl >= 0 Then\n int1 = Math.Floor(dbl)\nElseIf dbl < 0 Then\n int1 = Math.Ceiling(dbl)\nEnd If\nfraction = dbl - int1\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30297/"
] |
362,444 | <p>I would like to write a macro for Notepad++ which should replace char1, char2, char3 with char4, char5, char6, respectively.</p>
| [
{
"answer_id": 362869,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 7,
"selected": true,
"text": "<Macro name=\"Trim Trailing and save\" Ctrl=\"no\" Alt=\"yes\" Shift=\"yes\" Key=\"83\">\n <Action type=\"1\" message=\"2170\" wParam=\"0\" lParam=\"0\" sParam=\" \" />\n <Action type=\"1\" message=\"2170\" wParam=\"0\" lParam=\"0\" sParam=\" \" />\n <Action type=\"1\" message=\"2170\" wParam=\"0\" lParam=\"0\" sParam=\" \" />\n <Action type=\"0\" message=\"2327\" wParam=\"0\" lParam=\"0\" sParam=\"\" />\n <Action type=\"0\" message=\"2327\" wParam=\"0\" lParam=\"0\" sParam=\"\" />\n <Action type=\"2\" message=\"0\" wParam=\"42024\" lParam=\"0\" sParam=\"\" />\n <Action type=\"2\" message=\"0\" wParam=\"41006\" lParam=\"0\" sParam=\"\" />\n</Macro>\n"
},
{
"answer_id": 60457111,
"author": "Nøk",
"author_id": 8885117,
"author_profile": "https://Stackoverflow.com/users/8885117",
"pm_score": 3,
"selected": false,
"text": "<Macro name=\"REPLACE_IN_FILES_REGEX_DOT_FINDS_CR_AND_LF\" Ctrl=\"no\" Alt=\"no\" Shift=\"no\" Key=\"0\">\n <Action type=\"3\" message=\"1700\" wParam=\"0\" lParam=\"0\" sParam=\"\" />\n <Action type=\"3\" message=\"1601\" wParam=\"0\" lParam=\"0\" sParam=\"SEARCHTEXT\" />\n <Action type=\"3\" message=\"1625\" wParam=\"0\" lParam=\"2\" sParam=\"\" />\n <Action type=\"3\" message=\"1602\" wParam=\"0\" lParam=\"0\" sParam=\"REPLACETEXT\" />\n <Action type=\"3\" message=\"1653\" wParam=\"0\" lParam=\"0\" sParam=\"PATH\" />\n <Action type=\"3\" message=\"1652\" wParam=\"0\" lParam=\"0\" sParam=\"GLOBFILEFILTER\" />\n <Action type=\"3\" message=\"1702\" wParam=\"0\" lParam=\"1024\" sParam=\"\" /> \n <!-- #COMMENT: \"1024\" seems to be the flag \". finds /n and /r\". This is not in the documentation. -->\n <Action type=\"3\" message=\"1701\" wParam=\"0\" lParam=\"1660\" sParam=\"\" />\n</Macro>\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4235/"
] |
362,445 | <p>I'm assuming this is an easy question, but I'll be darned if I can find the answer.</p>
<p>I have a website in Visual Studio 2008. The paths to the stylesheets (and images) are in the following format /css/stylesheetname.css</p>
<p>At the root of the web project in Visual studio the folder exists as does the stylesheet. These paths work fine when running it in IIS.</p>
<p>If I use the inbuilt webserver in Visual Studio the paths fail because it puts the projectname in the path i.e. <a href="http://localhost:2020/projectname/default.aspx" rel="noreferrer">http://localhost:2020/projectname/default.aspx</a></p>
<p>In this case the / takes the path right back to <a href="http://localhost:2020" rel="noreferrer">http://localhost:2020</a></p>
<p>This is further compounded by the fact that if you click "design" the styles that import background images all fail although the stylesheet is imported correctly (becuase all other aspects of the stylesheet work i.e. <code>.class{font-family:arial;}</code> works but <code>.class{background: url(/images/image.jpg)}</code> does not).</p>
<p>I guess it's all to do with how Visual studio calculates its root path for the website, however I can't find a setting to change this.</p>
<p>Any ideas??
<strong>Update:</strong> as per Egil Hansen's answer I converted the paths in the CSS file to relative paths. However the background images still do not display in Design mode. I'll take a look at using Themes to get round this in due course.</p>
| [
{
"answer_id": 362502,
"author": "Egil Hansen",
"author_id": 32809,
"author_profile": "https://Stackoverflow.com/users/32809",
"pm_score": 3,
"selected": false,
"text": "/App_Themes/YourTheme/Images/ /App_Themes/YourTheme/ url(Images/img.gif) <pages styleSheetTheme=\"Default\">"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1970/"
] |
362,446 | <p>Are there some practical programming situations for someone to declare a class abstract when all the methods in it are concrete?</p>
| [
{
"answer_id": 362469,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 0,
"selected": false,
"text": "abstract"
},
{
"answer_id": 363748,
"author": "Markus",
"author_id": 45064,
"author_profile": "https://Stackoverflow.com/users/45064",
"pm_score": 2,
"selected": false,
"text": "public interface Foo {\n public void bar();\n}\npublic abstract class FooDecorator implements Foo {\n private final Foo wrapped;\n public FooDecorator(Foo wrapped) { this.wrapped = wrapped; }\n public void bar() { wrapped.bar(); }\n}\npublic class TracingFoo extends FooDecorator {\n //Omitting constructor code...\n public void bar() {\n log(\"Entering bar()\");\n super.bar();\n log(\"Exiting bar()\");\n }\n}\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27784/"
] |
362,461 | <p>I am trying to build a working encrypted signature for the Amazon S3 web service, writing a connection library using Objective C. </p>
<p>I have run into HMAC SHA-1 digest problems with the ObjC code, so I'm putting that to the side and looking at existing, working Perl code, to try to troubleshoot digest creation.</p>
<p>I am testing HMAC SHA-1 digest output from the <code>s3ls</code> command of the <code>Net::Amazon::S3</code> package and comparing that against the <code>_encode</code> subroutine that I pulled out and put into its own perl script:</p>
<pre><code>#!/usr/bin/perl -w
use MIME::Base64 qw(encode_base64);
use Digest::HMAC_SHA1;
use String::Escape qw( printable unprintable );
sub _ascii_to_hex {
(my $str = shift) =~ s/(.|\n)/sprintf("%02lx", ord $1)/eg;
return $str;
}
sub _encode {
my ( $aws_secret_access_key, $str ) = @_;
print "secret key hex: "._ascii_to_hex($aws_secret_access_key)."\n";
my $hmac = Digest::HMAC_SHA1->new($aws_secret_access_key);
$hmac->add($str);
my $digest = $hmac->digest;
print "cleartext hex: "._ascii_to_hex($str)."\n";
print "digest hex: "._ascii_to_hex($digest)."\n";
my $b64 = encode_base64( $digest, '' );
print "encoded: ".$b64."\n";
}
my $secret = "abcd1234";
my $cleartext = "GET\n\n\nFri, 12 Dec 2008 10:08:51 GMT+00:00\n/";
_encode($secret, $cleartext);
</code></pre>
<p>Here is sample output from this script:</p>
<pre><code>$ ./testhmac.pl
secret key hex: 6162636431323334
cleartext hex: 4745540a0a0a4672692c2031322044656320323030382031303a30383a353120474d542b30303a30300a2f
digest hex: 63308f9b8a198440d6d8685a3f3f70d0aab02f68
encoded: YzCPm4oZhEDW2GhaPz9w0KqwL2g=
</code></pre>
<p>What I am testing is that, if I input the same secret key and cleartext into the same <code>_encode</code> function of the <code>Net::Amazon::S3</code> package, I should see the very same secret key, cleartext, and digest bytes.</p>
<p>Indeed, I get the same bytes for the secret key and cleartext.</p>
<p>But I get something different for the digest (and of course the base64 encoding), e.g.:</p>
<pre><code>$ s3ls --access-key=foobar --secret-key=abcd1234
...
secret key hex: 6162636431323334
cleartext hex: 4745540a0a0a4672692c2031322044656320323030382031303a30383a353120474d542b30303a30300a2f
digest hex: c0da50050c451847de7ed055c5286de584527a22
encoded: wNpQBQxFGEfeftBVxSht5YRSeiI=
</code></pre>
<p>I have verified that the secret key and clear text are the same input to both scripts. The encoding subroutine is virtually identical in both scripts (except for an unused argument passed to the subroutine, which I remove from my custom version).</p>
<p>What would cause the HMAC SHA-1 digest to be computed differently in both cases, if the input bytes and <code>_encode</code> subroutine are the same?</p>
<p>(I have also verified the two scripts against the test cases at <a href="http://www.faqs.org/rfcs/rfc2202.html" rel="nofollow noreferrer">RFC 2201</a>.)</p>
| [
{
"answer_id": 362501,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 1,
"selected": false,
"text": "secret key hex: abcd...1234\n _ascii_to_hex(\"blahblahblah\")\n"
},
{
"answer_id": 362594,
"author": "brofield",
"author_id": 31423,
"author_profile": "https://Stackoverflow.com/users/31423",
"pm_score": 3,
"selected": true,
"text": "use Digest::SHA qw(hmac_sha1_hex);\nmy $hash = hmac_sha1_hex($data, $key);\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19410/"
] |
362,468 | <p>I'm new to log4net, so hopefully this is a really easy question for someone?!</p>
<p>I've got log4net working with the RollingLogFileAppender for my web application. I'm using logging to try and find where some performance issues are coming from. In order to do this, it'd be useful to include the ASP.NET SessionID in the log output so that I can make sure I'm looking at log entries for a specific user.</p>
<p>Is there any way I can do this through the <code>conversionPattern</code> setting for the appender? Is there a <code>%property{??}</code> setting I can use?</p>
<p><strong>UPDATE: This question still hasn't been answered - does anybody have any ideas?</strong></p>
| [
{
"answer_id": 362526,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 1,
"selected": false,
"text": "<conversionPattern\n value=\"%date %-5level %logger ${COMPUTERNAME} [%property{SessionID}] - %message%newline\" />\n protected void Session_Start(object sender, EventArgs e)\n{\n log4net.ThreadContext.Properties[\"SessionID\"] = Session.SessionID;\n log4net.Config.XmlConfigurator.Configure();\n}\n"
},
{
"answer_id": 873500,
"author": "Alexander K.",
"author_id": 108096,
"author_profile": "https://Stackoverflow.com/users/108096",
"pm_score": 4,
"selected": false,
"text": "%aspnet-request{ASP.NET_SessionId} protected void Application_PostAcquireRequestState(object sender, EventArgs e)\n{\n log4net.ThreadContext.Properties[\"SessionID\"] = Session.SessionID;\n}\n"
},
{
"answer_id": 1180535,
"author": "kimsk",
"author_id": 58905,
"author_profile": "https://Stackoverflow.com/users/58905",
"pm_score": 3,
"selected": false,
"text": " private void AcquireRequestState(Object source, EventArgs e)\n {\n HttpApplication application = (HttpApplication)source;\n HttpContext context = application.Context;\n log4net.ThreadContext.Properties[\"SessionId\"] = context.Session.SessionID;\n }\n <appender name=\"rollingFile\"\n type=\"log4net.Appender.RollingFileAppender,log4net\" >\n <param name=\"AppendToFile\" value=\"false\" />\n <param name=\"RollingStyle\" value=\"Date\" />\n <param name=\"DatePattern\" value=\"yyyy.MM.dd\" />\n <param name=\"StaticLogFileName\" value=\"true\" />\n\n <param name=\"File\" value=\"log.txt\" />\n <layout type=\"log4net.Layout.PatternLayout,log4net\">\n <param name=\"ConversionPattern\"\n value=\"%property{SessionId} %d [%t] %-5p %c - %m%n\" />\n </layout>\n</appender>\n"
},
{
"answer_id": 5321301,
"author": "Dan Turner",
"author_id": 464604,
"author_profile": "https://Stackoverflow.com/users/464604",
"pm_score": 4,
"selected": false,
"text": "PostAcquireRequestState HttpException protected void Application_PostAcquireRequestState(object sender, EventArgs e)\n{\n if (Context.Handler is IRequiresSessionState)\n {\n log4net.ThreadContext.Properties[\"SessionId\"] = Session.SessionID;\n }\n}\n"
},
{
"answer_id": 10975686,
"author": "Kappas",
"author_id": 1448327,
"author_profile": "https://Stackoverflow.com/users/1448327",
"pm_score": 3,
"selected": false,
"text": "%aspnet-request{ASP.NET_SessionId}"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475/"
] |
362,483 | <p>Is is possible to put a constant where clause to a Linq to SQl mapping.</p>
<p>I really don't want to do this at the query level or in my Data Access Object as these are currently completely generic and would like to keep it that way to make life for the other developers and save me repeating myself constantly.</p>
<p>Colin G</p>
| [
{
"answer_id": 362534,
"author": "Paul Nearney",
"author_id": 24071,
"author_profile": "https://Stackoverflow.com/users/24071",
"pm_score": 3,
"selected": true,
"text": "public static IQueryable<Horse> GetHorses(this DataContext db)\n{\n return from h in db.Horses\n where !h.Inactive\n select h;\n}\n var deadHorses = from h in db.Horses\n where !h.inactive && !h.Alive\n select h;\n var deadHorses = from h in db.GetHorses()\n where !h.Alive\n select h;\n"
}
] | 2008/12/12 | [
"https://Stackoverflow.com/questions/362483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213936/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.