qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
216,865
|
<p>I'm wondering about the practical use of #undef in C. I'm working through K&R, and am up to the preprocessor. Most of this was material I (more or less) understood, but something on page 90 (second edition) stuck out at me:</p>
<blockquote>
<p>Names may be undefined with <code>#undef</code>,
usually to ensure that a routine is
really a function, not a macro:</p>
<p><code>#undef getchar</code></p>
<p><code>int getchar(void) { ... }</code></p>
</blockquote>
<p>Is this a common practice to defend against someone <code>#define</code>-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting <code>getchar()</code>, so it shouldn't come up.) With your own function names, do you feel the need to do this? Does that change if you're developing a library for others to use?</p>
|
[
{
"answer_id": 216874,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 2,
"selected": false,
"text": "#included #undef"
},
{
"answer_id": 216891,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "#undef #undef #define bool int"
},
{
"answer_id": 216895,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "#define OpenFile <windows.h> OpenFile OpenFileA OpenFileW UNICODE #undef OpenFile"
},
{
"answer_id": 216922,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "#undef assert assert #undef NDEBUG assert extern /* globals.h */\n/* ------------------------------------------------------ */\n#undef GLOBAL\n#ifdef DEFINE_GLOBALS\n#define GLOBAL\n#else\n#define GLOBAL extern\n#endif\n\nGLOBAL int g_x;\nGLOBAL char* g_name;\n/* ------------------------------------------------------ */\n\n\n\n/* globals.c */\n/* ------------------------------------------------------ */\n#include \"some_master_header_that_happens_to_include_globals.h\"\n\n/* define the globals here (and only here) using globals.h */\n#define DEFINE_GLOBALS\n#include \"globals.h\"\n\n/* ------------------------------------------------------ */\n"
},
{
"answer_id": 216925,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "#undef #define MYLIB_MAKE_PC_PROVIDER(name) \\\n struct PcApi##name { \\\n many members …\n };\n\nMYLIB_MAKE_PC_PROVIDER(SA)\nMYLIB_MAKE_PC_PROVIDER(SSA)\nMYLIB_MAKE_PC_PROVIDER(AF)\n\n#undef MYLIB_MAKE_PC_PROVIDER\n"
},
{
"answer_id": 217221,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "<stdio.h> getchar() getc() getc() getchar() getc() #include <stdio.h>\n#undef getchar\n\nextern int some_function(int (*)(void));\n\nint core_function(void)\n{\n int c = some_function(getchar);\n return(c);\n}\n core_function() isxxxx() <ctype.h> #undef int c = (getchar)();\n getchar ( #undef /* function.h */\n…\nextern int function(int c);\nextern int other_function(int c, FILE *fp);\n#define function(c) other_function(c, stdout);\n…\n /* function.c */\n\n…\n\n/* Provide function despite macro override */\nint (function)(int c)\n{\n return function(c, stdout);\n}\n function ( return"
},
{
"answer_id": 217239,
"author": "Dustin Getz",
"author_id": 20003,
"author_profile": "https://Stackoverflow.com/users/20003",
"pm_score": 0,
"selected": false,
"text": "#pragma push_macro( \"new\" )\n#undef new\n#include <vector>\n#pragma pop_macro( \"new\" )\n"
},
{
"answer_id": 217986,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 2,
"selected": false,
"text": "\nint foo(int x, int y)\n{\n#define OUT_OF_RANGE(v, vlower, vupper) \\\n if (v < vlower) {v = vlower; goto EXIT;} \\\n else if (v > vupper) {v = vupper; goto EXIT;}\n\n /* do some calcs */\n x += (x + y)/2;\n OUT_OF_RANGE(x, 0, 100);\n y += (x - y)/2;\n OUT_OF_RANGE(y, -10, 50);\n\n /* do some more calcs and range checks*/\n ...\n\nEXIT:\n /* undefine OUT_OF_RANGE, because we don't need it anymore */\n#undef OUT_OF_RANGE\n ...\n return x;\n}\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14048/"
] |
216,870
|
<p>I'm using the following regex to capture a fixed width "description" field that is always 50 characters long:</p>
<pre><code>(?.{50})
</code></pre>
<p>My problem is that the descriptions sometimes contain a <em>lot</em> of whitespace, e.g.</p>
<pre><code>"FLUID COMPRESSOR "
</code></pre>
<p>Can somebody provide a regex that:</p>
<ol>
<li>Trims all whitespace off the end</li>
<li>Collapses any whitespace in between words to a <strong>single space</strong></li>
</ol>
|
[
{
"answer_id": 216877,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 1,
"selected": false,
"text": " s/[ \\t]+/ /g\n s/[ \\t]+$/$/\n sed"
},
{
"answer_id": 216885,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 5,
"selected": true,
"text": "s/ +/ /g\n s/\\s\\s+/ /g\n s/\\s{2,}/ /g\n"
},
{
"answer_id": 217399,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 3,
"selected": false,
"text": "str = Regex.Replace(str, \" +( |$)\", \"$1\");\n"
},
{
"answer_id": 1250923,
"author": "Casey Rodarmor",
"author_id": 66450,
"author_profile": "https://Stackoverflow.com/users/66450",
"pm_score": 1,
"selected": false,
"text": "re.replace(\"s/\\s+/ /g\", str.strip())\n"
},
{
"answer_id": 5920170,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 2,
"selected": false,
"text": " string x = Regex.Replace(x, @\"\\s+\", \" \").Trim();\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2773/"
] |
216,875
|
<p>As mentioned in many of my previous questions, I'm working through K&R, and am currently into the preprocessor. One of the more interesting things — something I never knew before from any of my prior attempts to learn C — is the <code>##</code> preprocessor operator. According to K&R:</p>
<blockquote>
<p>The preprocessor operator <code>##</code>
provides a way to concatenate actual
arguments during macro expansion. If a
parameter in the replacement text is
adjacent to a <code>##</code>, the parameter is
replaced by the actual argument, the
<code>##</code> and surrounding white space are
removed, and the result is re-scanned.
For example, the macro <code>paste</code>
concatenates its two arguments:</p>
<p><code>#define paste(front, back) front ## back</code></p>
<p>so <code>paste(name, 1)</code> creates the token
<code>name1</code>.</p>
</blockquote>
<p>How and why would someone use this in the real world? What are practical examples of its use, and are there gotchas to consider? </p>
|
[
{
"answer_id": 216888,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 7,
"selected": true,
"text": "#define WIDEN2(x) L ## x\n#define WIDEN(x) WIDEN2(x)\n//Note you need a WIDEN2 so that __DATE__ will evaluate first.\n std::wstring BuildDate = std::wstring(WIDEN(__DATE__)) + L\" \" + WIDEN(__TIME__);\n L __ DATE __ #ifdef _UNICODE\n #define _T(x) L ## x\n#else\n #define _T(x) x\n#endif\n _T #define MYLIB_ACCESSOR(name) (Get##name)\n#define MYLIB_MODIFIER(name) (Set##name)\n #define CREATE_3_VARS(name) name##1, name##2, name##3\nint CREATE_3_VARS(myInts);\nmyInts1 = 13;\nmyInts2 = 19;\nmyInts3 = 77;\n"
},
{
"answer_id": 216893,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "UNITTEST(test_name)\n void __testframework_test_name ()\n"
},
{
"answer_id": 216903,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 2,
"selected": false,
"text": "#define LINKED_LIST(A) struct list##_##A {\\\nA value; \\\nstruct list##_##A *next; \\\n};\n struct list_int {\nint value;\nstruct list_int *next;\n};\n"
},
{
"answer_id": 216904,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 3,
"selected": false,
"text": "fn_foo #define LOAD_IMGLIB_FN(lib,func) { \\\n fn_##func = (void *) GetProcAddress (lib, #func); \\\n if (!fn_##func) return 0; \\\n }\n LOAD_IMGLIB_FN (library, XpmFreeAttributes);\nLOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);\nLOAD_IMGLIB_FN (library, XpmReadFileToImage);\nLOAD_IMGLIB_FN (library, XImageFree);\n fn_XpmFreeAttributes \"XpmFreeAttributes\""
},
{
"answer_id": 216911,
"author": "mcherm",
"author_id": 14570,
"author_profile": "https://Stackoverflow.com/users/14570",
"pm_score": 2,
"selected": false,
"text": "#define LIFECYCLE(name, func) (struct name x = name##_create(); name##_activate(x); func(x); name##_release())\n"
},
{
"answer_id": 216912,
"author": "Tall Jeff",
"author_id": 1553,
"author_profile": "https://Stackoverflow.com/users/1553",
"pm_score": 2,
"selected": false,
"text": "SCREEN_HANDLER( activeCall )\n STATUS activeCall_constructor( HANDLE *pInst )\nSTATUS activeCall_eventHandler( HANDLE *pInst, TOKEN *pEvent );\nSTATUS activeCall_destructor( HANDLE *pInst );\n SCREEN_HANDLER( activeCall )\nSCREEN_HANDLER( ringingCall )\nSCREEN_HANDLER( heldCall )\n"
},
{
"answer_id": 216927,
"author": "ya23",
"author_id": 29430,
"author_profile": "https://Stackoverflow.com/users/29430",
"pm_score": 0,
"selected": false,
"text": "#define LOG(msg) log_msg(__function__, ## msg)\n #define LOG(msg) log_msg(__file__, __line__, ## msg)\n"
},
{
"answer_id": 216975,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 4,
"selected": false,
"text": "## #define STRINGIFY(x) #x\n#define PLUS(a, b) STRINGIFY(a##+##b)\n#define NS(a, b) STRINGIFY(a##::##b)\nprintf(\"%s %s\\n\", PLUS(1,2), NS(std,vector));\n 1+2 std::vector\n 1 + 2 std :: vector\n foo.cpp:16:1: pasting \"1\" and \"+\" does not give a valid preprocessing token\nfoo.cpp:16:1: pasting \"+\" and \"2\" does not give a valid preprocessing token\nfoo.cpp:16:1: pasting \"std\" and \"::\" does not give a valid preprocessing token\nfoo.cpp:16:1: pasting \"::\" and \"vector\" does not give a valid preprocessing token\n #define STRINGIFY(x) #x\n#define PLUS(a, b) STRINGIFY(a+b)\n#define NS(a, b) STRINGIFY(a::b)\nprintf(\"%s %s\\n\", PLUS(1,2), NS(std,vector));\n"
},
{
"answer_id": 216977,
"author": "c0m4",
"author_id": 2079,
"author_profile": "https://Stackoverflow.com/users/2079",
"pm_score": 2,
"selected": false,
"text": "\n\n#define ASSERT(exp) if(!(exp)){ \\\n print_to_rs232(\"Assert failed: \" ## #exp );\\\n while(1){} //Let the watchdog kill us \n\n"
},
{
"answer_id": 217086,
"author": "Bill Forster",
"author_id": 3955,
"author_profile": "https://Stackoverflow.com/users/3955",
"pm_score": 2,
"selected": false,
"text": "ENUM_BEGIN( Color )\n ENUM(RED),\n ENUM(GREEN),\n ENUM(BLUE)\nENUM_END( Color )\n const char *ColorStringTable[] =\n{\n \"RED\",\n \"GREEN\",\n \"BLUE\"\n};\n"
},
{
"answer_id": 217181,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": false,
"text": "## # #include <stdio.h>\n\n#define STRINGIFY2( x) #x\n#define STRINGIFY(x) STRINGIFY2(x)\n#define PASTE2( a, b) a##b\n#define PASTE( a, b) PASTE2( a, b)\n\n#define BAD_PASTE(x,y) x##y\n#define BAD_STRINGIFY(x) #x\n\n#define SOME_MACRO function_name\n\nint main() \n{\n printf( \"buggy results:\\n\");\n printf( \"%s\\n\", STRINGIFY( BAD_PASTE( SOME_MACRO, __LINE__)));\n printf( \"%s\\n\", BAD_STRINGIFY( BAD_PASTE( SOME_MACRO, __LINE__)));\n printf( \"%s\\n\", BAD_STRINGIFY( PASTE( SOME_MACRO, __LINE__)));\n\n printf( \"\\n\" \"desired result:\\n\");\n printf( \"%s\\n\", STRINGIFY( PASTE( SOME_MACRO, __LINE__)));\n}\n buggy results:\nSOME_MACRO__LINE__\nBAD_PASTE( SOME_MACRO, __LINE__)\nPASTE( SOME_MACRO, __LINE__)\n\ndesired result:\nfunction_name21\n"
},
{
"answer_id": 16648750,
"author": "Keshava GN",
"author_id": 2006333,
"author_profile": "https://Stackoverflow.com/users/2006333",
"pm_score": 1,
"selected": false,
"text": "#define BITFMASK(bit_position) (((1U << (bit_position ## _WIDTH)) - 1) << (bit_position ## _LEFTSHIFT))\n #define ADDR_LEFTSHIFT 0\n\n#define ADDR_WIDTH 7\n BITFMASK(ADDR)\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14048/"
] |
216,890
|
<p>One of our providers are sometimes sending XML feeds that are tagged as UTF-8 encoded documents but includes characters that are not included in the UTF-8 charset. This causes the parser to throw an exception and stop building the DOM object when these characters are encountered:</p>
<pre><code>DocumentBuilder.parse(ByteArrayInputStream bais)
</code></pre>
<p>throws the following exception:</p>
<pre><code>org.xml.sax.SAXParseException: Invalid byte 2 of 2-byte UTF-8 sequence.
</code></pre>
<p>Is there a way to "capture" these problems early and avoid the exception (i.e. finding and removing those characters from the stream)? What I'm looking for is a "best effort" type of fallback for wrongly encoded documents. The correct solution would obviously be to attack the problem at the source and make sure that only correct documents are delivered, but what is a good approach when that is not possible?</p>
|
[
{
"answer_id": 217165,
"author": "james",
"author_id": 17156,
"author_profile": "https://Stackoverflow.com/users/17156",
"pm_score": 3,
"selected": true,
"text": "DocumentBuilder.parse(new InpputSource(new InputStreamReader(inputStream, \"<real encoding>\")));\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29042/"
] |
216,894
|
<p>What's the best way to pipe the output from an java.io.OutputStream to a String in Java?</p>
<p>Say I have the method:</p>
<pre><code> writeToStream(Object o, OutputStream out)
</code></pre>
<p>Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.</p>
<p>I'm considering writing a class like this (untested):</p>
<pre><code>class StringOutputStream extends OutputStream {
StringBuilder mBuf;
public void write(int byte) throws IOException {
mBuf.append((char) byte);
}
public String getString() {
return mBuf.toString();
}
}
</code></pre>
<p>But is there a better way? I only want to run a test!</p>
|
[
{
"answer_id": 216913,
"author": "Horcrux7",
"author_id": 12631,
"author_profile": "https://Stackoverflow.com/users/12631",
"pm_score": 10,
"selected": true,
"text": "ByteArrayOutputStream new String( baos.toByteArray(), codepage );\n baos.toString( codepage );\n String codepage String toString() String codepage"
},
{
"answer_id": 216921,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 6,
"selected": false,
"text": "toString(String enc) toByteArray()"
},
{
"answer_id": 259952,
"author": "Adrian Mouat",
"author_id": 4332,
"author_profile": "https://Stackoverflow.com/users/4332",
"pm_score": 4,
"selected": false,
"text": "Obj.writeToStream(toWrite, os);\ntry {\n String out = new String(os.toByteArray(), \"UTF-8\");\n assertTrue(out.contains(\"testString\"));\n} catch (UnsupportedEncondingException e) {\n fail(\"Caught exception: \" + e.getMessage());\n}\n ByteArrayOutputStream"
},
{
"answer_id": 1022434,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "OutputStream output = new OutputStream() {\n private StringBuilder string = new StringBuilder();\n\n @Override\n public void write(int b) throws IOException {\n this.string.append((char) b );\n }\n\n //Netbeans IDE automatically overrides this toString()\n public String toString() {\n return this.string.toString();\n }\n};\n marshaller.marshal( (Object) toWrite , (OutputStream) output); System.out.println(output); marshaller.marshal(Object,Outputstream)"
},
{
"answer_id": 61884063,
"author": "jschnasse",
"author_id": 1485527,
"author_profile": "https://Stackoverflow.com/users/1485527",
"pm_score": 3,
"selected": false,
"text": "baos.toString(StandardCharsets.UTF_8);\n"
},
{
"answer_id": 73619210,
"author": "Jurgen Rutten",
"author_id": 14313338,
"author_profile": "https://Stackoverflow.com/users/14313338",
"pm_score": -1,
"selected": false,
"text": " //create lock for multithreading\n synchronized (System.err){\n //create new error stream\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n PrintStream errorOut = new PrintStream(byteArrayOutputStream);\n\n //save standard err out\n PrintStream standardErrOut = System.err;\n\n try{\n //set new error stream\n System.setErr(errorOut);\n\n exceptionList.forEach(exception -> {\n exception.printStackTrace();\n System.err.println(\"<---------->\");\n });\n\n\n } finally {\n //reset everything back to normal\n System.setErr(standardErrOut);\n\n //Log all the exceptions\n exceptionLogger.warning(byteArrayOutputStream.toString());\n\n //throw final generic exception\n throw new Exception();\n }\n }}\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4332/"
] |
216,959
|
<p>I have a web application with users and their documents. Each user can have many documents:</p>
<p>user.rb: </p>
<pre><code>has_many :documents
</code></pre>
<p>document.rb:</p>
<pre><code>belongs_to :user
</code></pre>
<p>document_controller.rb:</p>
<pre><code>def index
@documents = Document.find(:all)
end
</code></pre>
<p>I am using the restful_authentication plugin. Here is my question: How do I get the controller to only show documents that belongs to each user? Right now it shows all the documents for all the users.</p>
<p>I am using the latest version of Rails.</p>
|
[
{
"answer_id": 217011,
"author": "sock",
"author_id": 4028,
"author_profile": "https://Stackoverflow.com/users/4028",
"pm_score": 3,
"selected": false,
"text": "def index\n @documents = @current_user.documents\nend\n"
},
{
"answer_id": 217698,
"author": "JasonOng",
"author_id": 6048,
"author_profile": "https://Stackoverflow.com/users/6048",
"pm_score": 2,
"selected": false,
"text": "def index\n @documents = Document.find(:all, :conditions => {:user_id => session[:user_id]})\nend\n"
},
{
"answer_id": 15600694,
"author": "Lacloake",
"author_id": 2204371,
"author_profile": "https://Stackoverflow.com/users/2204371",
"pm_score": 2,
"selected": false,
"text": "def index\n @documents = Document.where(:user_id => current_user.id)\nend\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29441/"
] |
216,963
|
<p>Say you have a large PHP project and suddenly, when attempting to run it, you just end up with a blank page. The script terminates and you want to find exactly where that is with as little effort as possible.</p>
<p>Is there a tool/program/command/IDE that can, on PHP script termination, tell you the location of a script exit?</p>
<p>Note: I can't mark my own post as "accepted answer" so look at the bottom to see my solution. If you come up with a better solution I will mark your post as the answer.</p>
|
[
{
"answer_id": 216966,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 0,
"selected": false,
"text": "grep -n die filename\n"
},
{
"answer_id": 216979,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "function shutdown()\n{\n print_r(debug_backtrace());\n}\n\n\nregister_shutdown_function('shutdown');\n"
},
{
"answer_id": 217022,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 0,
"selected": false,
"text": "exit|die"
},
{
"answer_id": 217223,
"author": "Hannes Landeholm",
"author_id": 29442,
"author_profile": "https://Stackoverflow.com/users/29442",
"pm_score": 3,
"selected": true,
"text": "function shutdown() {\n global $dbg_stack_a;\n print_r($dbg_stack_a);\n}\nregister_shutdown_function('shutdown');\n eval('\nglobal $dbg_stack_a, $dbg_stack_b, $dbg_stack_c;\n$dbg_stack_a = $dbg_stack_b;\n$dbg_stack_b = $dbg_stack_c;\n$dbg_stack_c = debug_backtrace();\nreturn false;\n')\n"
},
{
"answer_id": 217255,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 0,
"selected": false,
"text": "memory_limit"
},
{
"answer_id": 5120640,
"author": "cweiske",
"author_id": 282601,
"author_profile": "https://Stackoverflow.com/users/282601",
"pm_score": 4,
"selected": false,
"text": "function shutdown_find_exit()\n{\n var_dump($GLOBALS['dbg_stack']);\n}\nregister_shutdown_function('shutdown_find_exit');\nfunction write_dbg_stack()\n{\n $GLOBALS['dbg_stack'] = debug_backtrace();\n}\nregister_tick_function('write_dbg_stack');\ndeclare(ticks=1);\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29442/"
] |
216,972
|
<p>Which types of objects fall into the domain of "subscriptable"?</p>
|
[
{
"answer_id": 216980,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 10,
"selected": true,
"text": "__getitem__()"
},
{
"answer_id": 217049,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": false,
"text": "__getitem__"
},
{
"answer_id": 217081,
"author": "Dan",
"author_id": 444,
"author_profile": "https://Stackoverflow.com/users/444",
"pm_score": 7,
"selected": false,
"text": "string: \"foobar\"[3] == \"b\"\ntuple: (1,2,3,4)[3] == 4\nlist: [1,2,3,4][3] == 4\ndict: {\"a\":1, \"b\":2, \"c\":3}[\"c\"] == 3\n __getitem__"
},
{
"answer_id": 40765305,
"author": "user2194711",
"author_id": 2194711,
"author_profile": "https://Stackoverflow.com/users/2194711",
"pm_score": 4,
"selected": false,
"text": "arr = []\narr.append[\"HI\"]\n [ arr.append(\"HI\")"
},
{
"answer_id": 49588151,
"author": "Vicrobot",
"author_id": 9134528,
"author_profile": "https://Stackoverflow.com/users/9134528",
"pm_score": 4,
"selected": false,
"text": "() >>> var = \"myString\"\n>>> def foo(): return 0\n... \n>>> var[3]\n't'\n>>> foo[3]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'function' object is not subscriptable\n function [] __getitem__() arr.append[\"HI\"]\n"
},
{
"answer_id": 57070158,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 3,
"selected": false,
"text": "def gimme_things():\n if something_happens():\n return ['all', 'the', 'things']\n something_happens() True if gimme_things return return None things = gimme_things()\nprint(\"My first thing is {0}\".format(things[0]))\n NoneType things None None[0] things things = gimme_things()\nif things:\n print(\"My first thing is {0}\".format(things[0]))\nelse:\n print(\"No things\") # or raise an error, or do nothing, or ...\n TypeError things = gimme_things()\ntry:\n print(\"My first thing is {0}\".format(things[0]))\nexcept TypeError:\n print(\"No things\") # or raise an error, or do nothing, or ...\n gimme_things def gimme_things():\n if something_happens():\n return ['all', 'the', 'things']\n else: # make sure we always return a list, no matter what!\n logging.info(\"Something didn't happen; return empty list\")\n return []\n else: something_happens() None things[0] IndexError things try except (TypeError, IndexError)"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11324/"
] |
216,973
|
<p>I'm doing a custom 404 page for a large website that's undergoing a redesign. There are about 40 high-use pages that customers may have bookmarked, and our new site structure will break these bookmarks. </p>
<p>On my custom 404 page, I want to alert them to the new URL if they attempt to navigate to one of these high-use pages via its old URL. So I have a couple of dynamic controls on the 404 page, one for a "did-you-want-this?" type of dialog, and another for a "if-so-go-here (and update your bookmark)" type of dialog. That's the easy part.</p>
<p>To suggest a new URL, I'm looking at the requested URL. If it has key words in it, I'm going to suggest the new URL based on that, and them I'm firing off the appropriate did-you-want..., and if-so... suggestions on the 404 page as mentioned above. </p>
<p>So I want to store these 40-ish key/value pairs (<em>keyword/new-URL pairs</em>) in a data structure, and I'm not sure what would be best. Dictionary? IDictionary? What's the difference and which is more appropriate?</p>
<p>Or am I totally on the wrong track?</p>
<p>Thanks for your time.</p>
|
[
{
"answer_id": 217002,
"author": "milot",
"author_id": 22637,
"author_profile": "https://Stackoverflow.com/users/22637",
"pm_score": 1,
"selected": false,
"text": "public class KeyValuesClass\n{\n private string a_key;\n private string a_value;\n\n public KeyValuesClass(string a_key, string a_value)\n {\n this.a_key = a_key;\n this.a_value = a_value;\n }\n\n public string Key\n {\n get{ return a_key; }\n set { a_key = value; }\n }\n\n public string Value\n {\n get{ return a_value; }\n set { a_value = value; }\n }\n\n}\n List<KeyValuesClass> my_key_value_list = new List<KeyValuesClass>();\nmy_key_value_list.Add(new KeyValuesClass(\"key\", \"value\");\n"
},
{
"answer_id": 217160,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "class UriSuggester {\n private List<SuggestedUri> Uris { get; set; }\n\n Uri[] GetSuggestions(Uri originalUri) {\n var suggestionHits = new Dictionary<SuggestedUri, int>();\n foreach (var keyword in KeyWords.Parse(originalUri)) {\n // find suggestions matching that keyword\n foreach (var suggestedUri in Uris.Where(u => u.Keywords.Contains(keyword)) {\n // add a hit for keyword match\n suggestionHits[suggestedUri] += 1;\n }\n }\n // order by weight * hits\n return suggestionHits.Keys\n .OrderBy(s => s.Weight * suggestionHits[s])\n .Select(s => s.Uri)\n .ToArray();\n }\n}\n\nclass SuggestedUri {\n public Uri Suggested { get; set; }\n public int Weight { get; set; }\n public Keyword[] Keywords;\n}\n\nclass Keyword {\n public string Value { get; set; }\n public static Keyword[] Parse(Uri uri);\n override Equals;\n override GetHashCode;\n}\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856/"
] |
216,995
|
<p>Say I want to copy the contents of a directory excluding files and folders whose names contain the word 'Music'.</p>
<pre><code>cp [exclude-matches] *Music* /target_directory
</code></pre>
<p>What should go in place of [exclude-matches] to accomplish this?</p>
|
[
{
"answer_id": 217004,
"author": "Daniel Bungert",
"author_id": 21093,
"author_profile": "https://Stackoverflow.com/users/21093",
"pm_score": 2,
"selected": false,
"text": "$ mkdir foo bar\n$ touch foo/a.txt foo/Music.txt\n$ find foo -type f ! -name '*Music*' -exec cp {} bar \\;\n$ ls bar\na.txt\n"
},
{
"answer_id": 217006,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 5,
"selected": false,
"text": "cp `ls | grep -v Music` /target_directory\n"
},
{
"answer_id": 217016,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 3,
"selected": false,
"text": "for for f in `find . -not -name \"*Music*\"`\ndo\n cp $f /target/dir\ndone\n"
},
{
"answer_id": 217017,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 10,
"selected": true,
"text": "extglob ls cp ~/foobar> shopt extglob\nextglob off\n~/foobar> ls\nabar afoo bbar bfoo\n~/foobar> ls !(b*)\n-bash: !: event not found\n~/foobar> shopt -s extglob # Enables extglob\n~/foobar> ls !(b*)\nabar afoo\n~/foobar> ls !(a*)\nbbar bfoo\n~/foobar> ls !(*foo)\nabar bbar\n shopt -u extglob\n"
},
{
"answer_id": 217026,
"author": "Steve",
"author_id": 27893,
"author_profile": "https://Stackoverflow.com/users/27893",
"pm_score": 4,
"selected": false,
"text": "find foo -type f ! -name '*Music*' -exec cp {} bar \\; # new proc for each exec\n\n\n\nfind . -maxdepth 1 -name '*Music*' -prune -o -print0 | xargs -0 -i cp {} dest/\n"
},
{
"answer_id": 217208,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 8,
"selected": false,
"text": "extglob shopt -s extglob shopt -u extglob $ shopt -s extglob\n$ cp !(*Music*) /target_directory\n man bash .c .h $ ls -d !(*@(.c|.h))\n $ ls -d !(*.[ch])\n"
},
{
"answer_id": 4979686,
"author": "gabreal",
"author_id": 614426,
"author_profile": "https://Stackoverflow.com/users/614426",
"pm_score": 1,
"selected": false,
"text": "cp -a ^'Music' /target\n cp -a ^\\*?'complete' /target\ncp -a ^'complete'?\\* /target\n"
},
{
"answer_id": 5039641,
"author": "Abid H. Mujtaba",
"author_id": 622877,
"author_profile": "https://Stackoverflow.com/users/622877",
"pm_score": 2,
"selected": false,
"text": "ls | grep -v \"Music\" | while read filename\ndo\necho $filename\ndone\n ls | grep -v \"Music\" | while read filename\ndo\ncp \"$filename\" /target_directory\ndone\n"
},
{
"answer_id": 5140113,
"author": "zrajm",
"author_id": 351162,
"author_profile": "https://Stackoverflow.com/users/351162",
"pm_score": 2,
"selected": false,
"text": "*.txt bash dash zsh for FILE in /some/dir/*.txt; do # for each *.txt file\n case \"${FILE##*/}\" in # if file basename...\n [0-9]*) continue ;; # starts with digit: skip\n esac\n ## otherwise, do stuff with $FILE here\ndone\n /some/dir/*.txt for /some/dir .txt ${FILE##*/} /some/dir/ $FILE case [0-9]* continue for [!a-z]* [0-9]*|*.bak .bak"
},
{
"answer_id": 33974971,
"author": "mivk",
"author_id": 111036,
"author_profile": "https://Stackoverflow.com/users/111036",
"pm_score": 3,
"selected": false,
"text": "shopt -s extglob GLOBIGNORE GLOBIGNORE=\"*techno*\"; cp *Music* /only_good_music/\n unset GLOBIGNORE rm *techno*"
},
{
"answer_id": 42770388,
"author": "James M. Lay",
"author_id": 1461154,
"author_profile": "https://Stackoverflow.com/users/1461154",
"pm_score": 3,
"selected": false,
"text": "extglob find grep comm comm -23 <(ls) <(ls *Music*)\n comm diff ls ls *Music* ls find sort comm -23 <(find . | sort) <(find . | grep -i '.jpg' | sort)\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/216995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4812/"
] |
217,065
|
<p>I'm working on a sparse matrix class that <strong>needs</strong> to use an array of <code>LinkedList</code> to store the values of a matrix. Each element of the array (i.e. each <code>LinkedList</code>) represents a row of the matrix. And, each element in the <code>LinkedList</code> array represents a column and the stored value.</p>
<p>In my class, I have a declaration of the array as:</p>
<pre><code>private LinkedList<IntegerNode>[] myMatrix;
</code></pre>
<p>And, in my constructor for the <code>SparseMatrix</code>, I try to define:</p>
<pre><code>myMatrix = new LinkedList<IntegerNode>[numRows];
</code></pre>
<p>The error I end up getting is</p>
<blockquote>
<p>Cannot create a generic array of <code>LinkedList<IntegerNode></code>.</p>
</blockquote>
<p>So, I have two issues with this:</p>
<ol>
<li>What am I doing wrong, and</li>
<li>Why is the type acceptable in the declaration for the array if it can't be created?</li>
</ol>
<p><code>IntegerNode</code> is a class that I have created. And, all of my class files are packaged together.</p>
|
[
{
"answer_id": 217093,
"author": "Fredrik",
"author_id": 9191,
"author_profile": "https://Stackoverflow.com/users/9191",
"pm_score": 7,
"selected": false,
"text": "myMatrix = (LinkedList<IntegerNode>[]) new LinkedList<?>[numRows];\n"
},
{
"answer_id": 217110,
"author": "Sergey",
"author_id": 29363,
"author_profile": "https://Stackoverflow.com/users/29363",
"pm_score": 7,
"selected": true,
"text": "List< List<IntegerNode>> nodeLists = new LinkedList< List< IntegerNode >>();\n class IntegerNodeList {\n private final List< IntegerNode > nodes;\n}\n"
},
{
"answer_id": 217145,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 3,
"selected": false,
"text": "ArrayList LinkedList O(n) O(1) ArrayList private Map<Integer, Map<Integer, IntegerNode>> myMatrix = new HashMap<Integer, Map<Integer, IntegerNode>>();\n\n// access a matrix cell:\nint rowIdx = 100;\nint colIdx = 30;\nMap<Integer, IntegerNode> row = myMatrix.get(rowIdx); // if null, create and add to matrix\nIntegerNode node = row.get(colIdx); // possibly null\n TreeMap HashMap TreeMap"
},
{
"answer_id": 2559239,
"author": "user306708",
"author_id": 306708,
"author_profile": "https://Stackoverflow.com/users/306708",
"pm_score": 2,
"selected": false,
"text": "myMatrix = (LinkedList<IntegerNode>[]) new LinkedList[numRows]; class IntegerNodeList { private final List< IntegerNode > nodes; } public interface IntegerNodeList extends List<IntegerNode> {}\n List<IntegerNode>[] myMatrix = new IntegerNodeList[numRows];\n"
},
{
"answer_id": 5477207,
"author": "Bob",
"author_id": 682652,
"author_profile": "https://Stackoverflow.com/users/682652",
"pm_score": 2,
"selected": false,
"text": "class IntegerNodeList extends LinkedList<IntegerNode> {}\n\nIntegerNodeList[] myMatrix = new IntegerNodeList[numRows]; \n"
},
{
"answer_id": 5843737,
"author": "Andrii",
"author_id": 732640,
"author_profile": "https://Stackoverflow.com/users/732640",
"pm_score": 2,
"selected": false,
"text": "List<String>[] lst = new List[2];\nlst[0] = new LinkedList<String>();\nlst[1] = new LinkedList<String>();\n"
},
{
"answer_id": 12733948,
"author": "Ryan",
"author_id": 399887,
"author_profile": "https://Stackoverflow.com/users/399887",
"pm_score": 0,
"selected": false,
"text": "LinkedList<Node>[] matrix = new LinkedList<Node>[5];\n LinkedList<Node>[] matrix = new LinkedList[5];\n for(int i=0; i < matrix.length; i++){\n\n matrix[i] = new LinkedList<>();\n}\n"
},
{
"answer_id": 14797460,
"author": "Yiling",
"author_id": 1212682,
"author_profile": "https://Stackoverflow.com/users/1212682",
"pm_score": 0,
"selected": false,
"text": "private IntegerNode[] node_array = new IntegerNode[sizeOfYourChoice];\n node_array[i] ArrayList<IntegerNode> LinkedList<IntegerNode> list.get(index)"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22371/"
] |
217,067
|
<p>I have a button on an ASP.Net page that will call Response.Redirect back to the same page after performing some processing in order to re-display the results of a query. However, for some reason, the page comes up blank. It seems that IsPostBack is returning true after the redirect. Anybody know why this would happen?</p>
<p>The page is a custom page in Community Server. Here is the basic code:</p>
<pre><code>void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr);
DataTable tbl = new DataTable();
da.Fill(tbl);
da.Dispose();
rptNonResidents.DataSource = tbl;
rptNonResidents.DataBind();
}
}
void btnApprove_Command(object sender, CommandEventArgs e)
{
// Code removed for testing.
Response.Clear();
Response.Redirect("ApproveResidents.aspx", true);
Response.End();
}
</code></pre>
|
[
{
"answer_id": 217260,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "protected void Page_Load( object sender, EventArgs e )\n{\n if (!IsPosBack) {\n BuildData();\n }\n}\n\nvoid btnApprove_Command(object sender, CommandEventArgs e)\n{\n // do your stuff and clear any some controls, maybe\n\n BuildData();\n}\n\nprivate void BuildData()\n{\n string connStr = ConfigurationManager.ConnectionStrings[\"SiteSqlServer\"].ConnectionString;\n SqlDataAdapter da = new SqlDataAdapter(\"SELECT * FROM ge_vw_NonResidents\", connStr);\n DataTable tbl = new DataTable();\n da.Fill(tbl);\n da.Dispose();\n rptNonResidents.DataSource = tbl;\n rptNonResidents.DataBind();\n}\n"
},
{
"answer_id": 73907810,
"author": "Vishakha Suthar",
"author_id": 19782028,
"author_profile": "https://Stackoverflow.com/users/19782028",
"pm_score": 1,
"selected": false,
"text": "Response.Redirect(url,true); \n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320/"
] |
217,070
|
<p>Using Apache's commons-httpclient for Java, what's the best way to add query parameters to a GetMethod instance? If I'm using PostMethod, it's very straightforward:</p>
<pre><code>PostMethod method = new PostMethod();
method.addParameter("key", "value");
</code></pre>
<p>GetMethod doesn't have an "addParameter" method, though. I've discovered that this works:</p>
<pre><code>GetMethod method = new GetMethod("http://www.example.com/page");
method.setQueryString(new NameValuePair[] {
new NameValuePair("key", "value")
});
</code></pre>
<p>However, most of the examples I've seen either hard-code the parameters directly into the URL, e.g.:</p>
<pre><code>GetMethod method = new GetMethod("http://www.example.com/page?key=value");
</code></pre>
<p>or hard-code the query string, e.g.:</p>
<pre><code>GetMethod method = new GetMethod("http://www.example.com/page");
method.setQueryString("?key=value");
</code></pre>
<p>Is one of these patterns to be preferred? And why the API discrepancy between PostMethod and GetMethod? And what are all those other HttpMethodParams methods intended to be used for?</p>
|
[
{
"answer_id": 217102,
"author": "Ryan Guest",
"author_id": 1811,
"author_profile": "https://Stackoverflow.com/users/1811",
"pm_score": 6,
"selected": true,
"text": "String url = \"http://www.example.com/page?key=value\";\nGetMethod method = new GetMethod(url);\n GetMethod method = new GetMethod(\"example.com/page\"); \nmethod.setQueryString(new NameValuePair[] { \n new NameValuePair(\"key\", \"value\") \n}); \n"
},
{
"answer_id": 3443335,
"author": "Steve Jones",
"author_id": 165085,
"author_profile": "https://Stackoverflow.com/users/165085",
"pm_score": 4,
"selected": false,
"text": "setQueryString(String) setQueryString(NameValuePair[])"
},
{
"answer_id": 13033597,
"author": "Randal Harleigh",
"author_id": 1768747,
"author_profile": "https://Stackoverflow.com/users/1768747",
"pm_score": 3,
"selected": false,
"text": " URIBuilder builder = new URIBuilder(\"https://graph.facebook.com/oauth/access_token\")\n .addParameter(\"client_id\", application.getKey())\n .addParameter(\"client_secret\", application.getSecret())\n .addParameter(\"redirect_uri\", callbackURL)\n .addParameter(\"code\", code);\n\n HttpPost method = new HttpPost(builder.build());\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29173/"
] |
217,074
|
<p>I've been having a lot of problems trying to figure out how to use <code>scanf()</code>. It seems to work fine with integers, being fairly straight forward <code>scanf("%d", &i)</code>.</p>
<p>Where I am running into issues is using <code>scanf()</code> in loops trying to read input. For example:</p>
<pre><code>do {
printf("counter: %d: ", counter);
scanf("%c %c%d", &command, &prefix, &input);
} while (command != 'q');
</code></pre>
<ol>
<li><p>When I enter in a validly structured input like <code>c P101</code>, it seems to loop again before prompting me. This seems to happen even with a single:</p>
<pre><code>scanf("%c", &c)
</code></pre>
<p>in a while loop. It'll do the loop twice before prompting me again. What is making it loop twice, and how do I stop it?</p></li>
<li><p>When I enter in less amount of input that programmatically wouldn't have another character or number such as <code>q</code>, pressing enter seems to prompt me to enter more. How do I get <code>scanf()</code> to process both single and double character entries? </p></li>
</ol>
|
[
{
"answer_id": 217085,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 1,
"selected": false,
"text": "printf() printf stdout scanf() scanf() fgets() sscanf()"
},
{
"answer_id": 217122,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 5,
"selected": true,
"text": "c P101 c P101\\n %c \\n command c prefix P P101\\n P 1 1 01 \\n q q\\n q \\n q"
},
{
"answer_id": 217126,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n\nint main(void)\n{\n int counter = 1;\n char command, prefix;\n int input;\n\n do \n {\n printf(\"counter: %d: \", counter);\n scanf(\"%c %c%d\", &command, &prefix, &input);\n printf(\"---%c %c%d---\\n\", command, prefix, input);\n counter++;\n } while (command != 'q');\n}\n counter: 1: a b1\n---a b1---\ncounter: 2: c d2\n---\n c1---\ncounter: 3: e f3\n---d 21---\ncounter: 4: ---e f3---\ncounter: 5: g h4\n---\n g3---\n"
},
{
"answer_id": 13471778,
"author": "jap3r",
"author_id": 1838532,
"author_profile": "https://Stackoverflow.com/users/1838532",
"pm_score": 0,
"selected": false,
"text": " while(command != 'q')\n {\n //statements\n }\n scanf() gets() fgets() getline() gets() string fgets() getline() string[strcspn(string, \"\\n\")] = '\\0';"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
] |
217,089
|
<p>I am looking for a (simple) text editor that can handle text in different encodings in the same document.</p>
<p>I need to develop some sites with mixed Japanese and English text and the editors I have now (on an English Windows system) are unable to display the Japanese text.
Jedit files don't display the Japanese text I have inputted but when I look at the file in a browser it shows up correctly.
Gvim shows all Japanese text in the editor as question marks and also in the browser.
In Gvim inputting the kanji works (you input the pronounciation and then press space bar to get the kanji) but when you confirm the kanji you want it replaces that kanji with question marks. (1 question mark for every kanji).</p>
<p>Can someone recommend me a text editor to edit html and php files that is able to display utf-8 encoded text and also save as an utf-8 file ?</p>
<p>thank you.</p>
<p>After reading about emacs I installed it. see below.</p>
<p>Thanks everybody for the hints.
if you don't have a unicode font yet you have to find one online or buy one.
here are the instructions to install the font on a windows system <a href="http://support.microsoft.com/kb/314960" rel="nofollow noreferrer">http://support.microsoft.com/kb/314960</a></p>
<p>jEdit
I changed my font in Jedit to a UTF font and now the Japanese shows up normally.
inputting the Japanese is still problematic as you don't see what you are typing.
(to change your font to edit files go to Utilities -> Global Options -> text area
select a Unicode font and you'll be able to see the Japanese characters.</p>
<p>gVim
I am still trying to figure out how to add a font in gvim. Once I know how to do that I ll update this.</p>
<p>Emacs
Emacs does not show the kanji correctly, they are displayed as ??? but at least I can see what I type in Japanese and select the right word.</p>
<p>so at this point I have to say that in jEdit I can see Japanese text but I can't input Japanese text. Gvim I can input Japanese text but inside the text area it is displayed as ??? and the same goes for Emacs.
adding a font in emacs and gvim is sadly enough not a trivial task.
At the moment I use notepad with the Arial unicode MS font and saving as UTF-8 file as my Japanese editor. Not ideal but at least it works.</p>
|
[
{
"answer_id": 3756762,
"author": "David Johnstone",
"author_id": 120410,
"author_profile": "https://Stackoverflow.com/users/120410",
"pm_score": 3,
"selected": false,
"text": "set guifont=Consolas\n .vimrc set encoding=utf8\n set encoding?\n"
},
{
"answer_id": 3756826,
"author": "Rachel",
"author_id": 164299,
"author_profile": "https://Stackoverflow.com/users/164299",
"pm_score": 1,
"selected": false,
"text": "UTF-8"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18383/"
] |
217,111
|
<p>I'm working my way into MVC at the moment, but on my "To learn at some point" list, I also have WCF.</p>
<p>I just wonder if WCF is something that should/could be used in an MVC Application or not? The Background is that I want a Desktop Application (.NET 3.5, WPF) interact with my MVC Web Site, and I wonder what the best way to transfer data between the two is. Should I just use special Views/have the controllers return JSON or XML (using the ContentResult)?</p>
<p>And maybe even more important, for the other way round, could I just call special controllers? Not sure how Authorization would work in such a context. I can either use Windows Authentication or (if the Site is running forms authentication) have the user store his/her credentials in the application, but I would then essentially create a HTTP Client in my Application. So while MVC => Application seems really easy, Application => MVC does seem to be somewhat tricky and a possible use for WCF?</p>
<p>I'm not trying to brute-force WCF in this, but I just wonder if there is indeed a good use case for WCF in an MVC application.</p>
|
[
{
"answer_id": 1139220,
"author": "user139669",
"author_id": 139669,
"author_profile": "https://Stackoverflow.com/users/139669",
"pm_score": 3,
"selected": false,
"text": "public class JsonOrXml : ActionFilterAttribute\n{\n private static UTF8Encoding UTF8 = new UTF8Encoding(false);\n\n public override void OnActionExecuted(ActionExecutedContext filterContext)\n {\n // setup the request, view and data\n HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;\n ViewResult view = (ViewResult)(filterContext.Result);\n var data = view.ViewData.Model;\n\n String contentType = request.ContentType ?? string.Empty;\n\n // JSON\n if (contentType.Contains(\"application/json\") || (string)view.ViewData[\"FORMAT\"] == \"json\")\n {\n filterContext.Result = new JsonResult\n {\n Data = data\n };\n }\n\n // POX\n else if (contentType.Contains(\"text/xml\") || (string)view.ViewData[\"FORMAT\"] == \"xml\")\n {\n // MemoryStream to encapsulate as UTF-8 (default UTF-16)\n // http://stackoverflow.com/questions/427725/\n //\n // MemoryStream also used for atomicity but not here\n // http://stackoverflow.com/questions/486843/\n //using (MemoryStream stream = new MemoryStream(500))\n //{\n // using (var xmlWriter =\n // XmlTextWriter.Create(stream,\n // new XmlWriterSettings()\n // {\n // OmitXmlDeclaration = false,\n // Encoding = UTF8,\n // Indent = true\n // }))\n // {\n // new XmlSerializer(data.GetType()).Serialize(xmlWriter, data);\n // }\n\n // filterContext.Result = new ContentResult\n // {\n // ContentType = \"text/xml\",\n // Content = UTF8.GetString(stream.ToArray()),\n // ContentEncoding = UTF8\n // };\n //}\n\n XmlDeclaration xmlDecl = new XmlDocument().CreateXmlDeclaration(\"1.0\", \"UTF-8\", \"yes\");\n\n filterContext.Result = new ContentResult\n { \n ContentType = \"text/xml\",\n Content = xmlDecl.OuterXml + data.ToString(),\n ContentEncoding = UTF8\n };\n }\n }\n}\n public class ContentFile : Entity\n{\n public ContentBook BelongsToBook { get; set; }\n public string FileName { get; set; }\n public XElement FileXml { get; set; }\n public Binary FileData { get; set; }\n public List<ContentFile> Versions { get; set; }\n public List<ContentNode> ContentNodes { get; set; }\n\n public override string ToString()\n {\n return this.ToString(SaveOptions.DisableFormatting);\n }\n\n public string ToString(SaveOptions options)\n {\n XElement xml = XElement.Parse(\"<contentFile id=\\\"\" + Id.ToString() + \"\" + \"\\\" />\");\n xml.Add(new XElement(\"fileName\", FileName));\n xml.Add(new XElement(\"fileStructure\", FileXml));\n xml.Add(base.ToString(options));\n return xml.ToString(options);\n }\n}\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
217,113
|
<p>Long time ago, I saved a sentence from a Java reference book: <em>"Java has no mechanism to handle deadlock. it won't even know deadlock occurred." (Head First Java 2nd Edition, p.516)</em></p>
<p>So, what is about it? Is there a way to catch deadlock case in Java? I mean, is there a way that our code understands a deadlock case occurred?</p>
|
[
{
"answer_id": 217558,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "Thread.stop"
},
{
"answer_id": 217693,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 2,
"selected": false,
"text": "findMonitorDeadlockedThreads() java.lang.management.ManagementFactory.getThreadMXBean() findDeadlockedThreads() ReentrandLock ReentrantReadWriteLock"
},
{
"answer_id": 217701,
"author": "staffan",
"author_id": 988,
"author_profile": "https://Stackoverflow.com/users/988",
"pm_score": 6,
"selected": false,
"text": "java.lang.management findMonitorDeadlockedThreads() findDeadlockedThreads() ThreadMXBean ThreadMXBean tmx = ManagementFactory.getThreadMXBean();\n long[] ids = tmx.findDeadlockedThreads();\n if (ids != null) {\n ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);\n System.out.println(\"The following threads are deadlocked:\");\n for (ThreadInfo ti : infos) {\n System.out.println(ti);\n }\n }\n"
},
{
"answer_id": 1661294,
"author": "Dave Griffiths",
"author_id": 15379,
"author_profile": "https://Stackoverflow.com/users/15379",
"pm_score": 4,
"selected": false,
"text": "import java.util.concurrent.locks.*;\nimport java.lang.management.*;\n\npublic class LockTest {\n\n static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();\n\n public static void main(String[] args) throws Exception {\n Reader reader = new Reader();\n Writer writer = new Writer();\n sleep(10);\n System.out.println(\"finding deadlocked threads\");\n ThreadMXBean tmx = ManagementFactory.getThreadMXBean();\n long[] ids = tmx.findDeadlockedThreads();\n if (ids != null) {\n ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);\n System.out.println(\"the following threads are deadlocked:\");\n for (ThreadInfo ti : infos) {\n System.out.println(ti);\n }\n }\n System.out.println(\"finished finding deadlocked threads\");\n }\n\n static void sleep(int seconds) {\n try {\n Thread.currentThread().sleep(seconds*1000);\n } catch (InterruptedException e) {}\n }\n\n static class Reader implements Runnable {\n Reader() {\n new Thread(this).start();\n }\n public void run() {\n sleep(2);\n System.out.println(\"reader thread getting lock\");\n lock.readLock().lock();\n System.out.println(\"reader thread got lock\");\n synchronized (lock) {\n System.out.println(\"reader thread inside monitor!\");\n lock.readLock().unlock();\n }\n }\n }\n\n static class Writer implements Runnable {\n Writer() {\n new Thread(this).start();\n }\n public void run() {\n synchronized (lock) {\n sleep(4);\n System.out.println(\"writer thread getting lock\");\n lock.writeLock().lock();\n System.out.println(\"writer thread got lock!\");\n }\n }\n }\n}\n"
},
{
"answer_id": 2897687,
"author": "Saurabh M. Chande",
"author_id": 349035,
"author_profile": "https://Stackoverflow.com/users/349035",
"pm_score": -1,
"selected": false,
"text": "Class A\n{\n synchronized void methodA(B b)\n {\n b.last();\n }\n\n synchronized void last()\n {\n SOP(“ Inside A.last()”);\n }\n}\n\nClass B\n{\n synchronized void methodB(A a)\n {\n a.last();\n }\n\n synchronized void last()\n {\n SOP(“ Inside B.last()”);\n }\n}\n\n\nClass Deadlock implements Runnable \n{\n A a = new A(); \n B b = new B();\n\n // Constructor\n Deadlock()\n {\n Thread t = new Thread(); \n t.start();\n a.methodA(b);\n }\n\n public void run()\n {\n b.methodB(a);\n }\n\n public static void main(String args[] )\n {\n new Deadlock();\n }\n}\n"
},
{
"answer_id": 8437590,
"author": "Jeach",
"author_id": 88252,
"author_profile": "https://Stackoverflow.com/users/88252",
"pm_score": 3,
"selected": false,
"text": "kill -3 PID # where 'PID' is the Linux process ID\n Found one Java-level deadlock:\n=============================\n\"Thread-0\":\n waiting to lock monitor 0x08081670 (object 0x7f61ddb8, a Deadlock$A),\n which is held by \"main\"\n\"main\":\n waiting to lock monitor 0x080809f0 (object 0x7f61f3b0, a Deadlock$B),\n which is held by \"Thread-0\"\n"
},
{
"answer_id": 62519467,
"author": "Manas",
"author_id": 6812618,
"author_profile": "https://Stackoverflow.com/users/6812618",
"pm_score": 2,
"selected": false,
"text": "jcmd jcmd jcmd <PID> Thread.print jcmd jcmd <PID> help"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26379/"
] |
217,116
|
<p>Is it possible to see the return value of a method after the line has been run and before the instruction pointer returns to the calling function?</p>
<p>I am debugging code I can't modify <em>(read: don't want to re-compile a third party library)</em>, and sometimes it jumps to code I don't have source to or the return expression has side effects that stop me being able to just run the expression in the <em>Display</em> tab.</p>
<p>Often the return value is used in a compound statement, and so the <em>Variables</em> view will never show me the value (hence wanting to see the result before control returns to the calling function).</p>
<p><strong>UPDATE:</strong> I can't use the expression viewer as there are side-effects in the statement.</p>
|
[
{
"answer_id": 217152,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "return varname; return(some * expression || other);"
},
{
"answer_id": 302443,
"author": "zvikico",
"author_id": 2823,
"author_profile": "https://Stackoverflow.com/users/2823",
"pm_score": 3,
"selected": false,
"text": "MyReturnedType foo() {\n MyReturnedType result = null;\n\n // do your stuff, modify the result or not\n\n return result;\n}\n"
},
{
"answer_id": 461387,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "return"
},
{
"answer_id": 21398654,
"author": "Satish",
"author_id": 3243336,
"author_profile": "https://Stackoverflow.com/users/3243336",
"pm_score": 5,
"selected": false,
"text": "Ctrl + Shift + D\n"
},
{
"answer_id": 74233246,
"author": "drac_o",
"author_id": 9728769,
"author_profile": "https://Stackoverflow.com/users/9728769",
"pm_score": 0,
"selected": false,
"text": "Windows> Preferences> Java> Debug> Show method result......"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943/"
] |
217,132
|
<p>So I have an Access application, and I'd like some forms to be maximised when they are opened, and others to be medium-sized when they are opened. However, if I try something like this:</p>
<pre><code>Private Sub Form_Activate()
DoCmd.Maximize
End Sub
</code></pre>
<p>or</p>
<pre><code>Private Sub Form_Activate()
DoCmd.Restore
End Sub
</code></pre>
<p>it has the effect of maximizing or restoring every open window, which isn't what I'm looking for.</p>
<p>Is there any way around this?</p>
<p>I'm using Access 2003.</p>
|
[
{
"answer_id": 217137,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "Application hwndAccessApp struct Rect Type Rect… const SW_SHOWNORMAL = 1 GetParent GetClientRect IsZoomed ShowWindow MoveWindow IsZoomed(frm.hWnd) = True ShowWindow frm.hWnd, SW_SHOWNORMAL GetClientRect GetParent(frm.hWnd, rect) MoveWindow frm.hWnd, 0, 0, rect.x2-rect.x1, rect.y2-rect.y1"
},
{
"answer_id": 217144,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "DoCmd.MoveSize 100,100\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,149
|
<p>In programming we face various situations where we are required to make use of intermediate STL containers as the following example depicts:</p>
<pre><code>while(true)
{
set < int > tempSet;
for (int i = 0; i < n; i ++)
{
if (m.size() == min && m.size() <= max)
{
tempSet.insert(i);
}
}
//Some condition testing code
}
</code></pre>
<p>Or</p>
<pre><code>set < int > tempSet;
while(true)
{
for (int i = 0; i < n; i ++)
{
if (m.size() == min && m.size() <= max)
{
tempSet.insert(i);
}
}
tempSet.clear();
//Some condition testing code
}
</code></pre>
<p>Which approach is better in terms of time and space complexity considering the present state of C++ compliers?</p>
|
[
{
"answer_id": 217156,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 2,
"selected": false,
"text": "set/map/list vector/hash_set/hash_map/string vector struct/class"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6561/"
] |
217,157
|
<p>I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen.</p>
<p>I'd like to do this purely from (Py)GTK+, but I am amenable to calling platform-specific functions. Ideally I'd like to call functions which have already been wrapped from Python, but if that's not possible, I'm not above a little bit of C or <code>ctypes</code> code, as long as I know what I'm actually looking for.</p>
<p>On Windows I think the function I want is <a href="http://msdn.microsoft.com/en-us/library/ms646302.aspx" rel="noreferrer"><code>GetLastInputInfo</code></a>, but that doesn't seem to be wrapped by pywin32; I hope I'm missing something.</p>
|
[
{
"answer_id": 1145688,
"author": "drdaeman",
"author_id": 116546,
"author_profile": "https://Stackoverflow.com/users/116546",
"pm_score": 5,
"selected": true,
"text": "GetTickCount ctypes XScreenSaverQueryInfo HIDIdleTime"
},
{
"answer_id": 16777652,
"author": "Johan Dahlin",
"author_id": 14337,
"author_profile": "https://Stackoverflow.com/users/14337",
"pm_score": 3,
"selected": false,
"text": "import ctypes\nimport ctypes.util\nimport platform\n\nclass XScreenSaverInfo(ctypes.Structure):\n _fields_ = [('window', ctypes.c_long),\n ('state', ctypes.c_int),\n ('kind', ctypes.c_int),\n ('til_or_since', ctypes.c_ulong),\n ('idle', ctypes.c_ulong),\n ('eventMask', ctypes.c_ulong)]\n\nclass IdleXScreenSaver(object):\n def __init__(self):\n self.xss = self._get_library('Xss')\n self.gdk = self._get_library('gdk-x11-2.0')\n\n self.gdk.gdk_display_get_default.restype = ctypes.c_void_p\n # GDK_DISPLAY_XDISPLAY expands to gdk_x11_display_get_xdisplay\n self.gdk.gdk_x11_display_get_xdisplay.restype = ctypes.c_void_p\n self.gdk.gdk_x11_display_get_xdisplay.argtypes = [ctypes.c_void_p]\n # GDK_ROOT_WINDOW expands to gdk_x11_get_default_root_xwindow\n self.gdk.gdk_x11_get_default_root_xwindow.restype = ctypes.c_void_p\n\n self.xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo)\n self.xss.XScreenSaverQueryExtension.restype = ctypes.c_int\n self.xss.XScreenSaverQueryExtension.argtypes = [ctypes.c_void_p,\n ctypes.POINTER(ctypes.c_int),\n ctypes.POINTER(ctypes.c_int)]\n self.xss.XScreenSaverQueryInfo.restype = ctypes.c_int\n self.xss.XScreenSaverQueryInfo.argtypes = [ctypes.c_void_p,\n ctypes.c_void_p,\n ctypes.POINTER(XScreenSaverInfo)]\n\n # gtk_init() must have been called for this to work\n import gtk\n gtk # pyflakes\n\n # has_extension = XScreenSaverQueryExtension(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),\n # &event_base, &error_base);\n event_base = ctypes.c_int()\n error_base = ctypes.c_int()\n gtk_display = self.gdk.gdk_display_get_default()\n self.dpy = self.gdk.gdk_x11_display_get_xdisplay(gtk_display)\n available = self.xss.XScreenSaverQueryExtension(self.dpy,\n ctypes.byref(event_base),\n ctypes.byref(error_base))\n if available == 1:\n self.xss_info = self.xss.XScreenSaverAllocInfo()\n else:\n self.xss_info = None\n\n def _get_library(self, libname):\n path = ctypes.util.find_library(libname)\n if not path:\n raise ImportError('Could not find library \"%s\"' % (libname, ))\n lib = ctypes.cdll.LoadLibrary(path)\n assert lib\n return lib\n\n def get_idle(self):\n if not self.xss_info:\n return 0\n\n # XScreenSaverQueryInfo(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),\n # GDK_ROOT_WINDOW(), mit_info);\n drawable = self.gdk.gdk_x11_get_default_root_xwindow()\n self.xss.XScreenSaverQueryInfo(self.dpy, drawable, self.xss_info)\n # return (mit_info->idle) / 1000;\n return self.xss_info.contents.idle / 1000\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13564/"
] |
217,177
|
<p>Problem : I have multiple projects checked out in my depot. I also have multiple pending numbered change lists, each change list containing checked out files specific to its project. When I check out a new file, it appears in the default change list instead of in the change list that is relevant to its project and I need to manually move it to the relevant change list. This gets real tedious real quick. </p>
<p>Is there any way to automate this process? Sure, a shell script with regular expressions could work, but I want to know if there is any Perforce feature that does this. For example, is there a way to link my project folder to a numbered change list so that a newly checked out file automatically appears in the relevant change list?</p>
|
[
{
"answer_id": 1028439,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 3,
"selected": true,
"text": "p4 edit -c 1234 foo.txt\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13760/"
] |
217,187
|
<p>I am new to the world of ASP.NET and SQL server, so please pardon my ignorance ...</p>
<p>If I have a data structure in C# (for e.g. let's just say, a vector that stores some strings), is it possible to store the contents of the vector as is in SQL table? I want to do this so that it fast to convert that data back into vector form as fast as possible without having to construct it element by element. Almost like writing binary data to a file and then reading it and copying it to an allocated structure in C.</p>
<p>I've created a table on SQL Server 2008 for which a field is defined as VARBINARY(MAX). I thought I'd start with that.</p>
<p>Could someone show me an example of how I would go about storing and retrieving a vector of, say, 10 strings, into and from that field? Is this even possible (I can't think of why not)?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 217202,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "[Serializable] ISerializable BinaryFormatter"
},
{
"answer_id": 217207,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 6,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.Serialization;\nusing System.IO;\n\nnamespace SerializeThingy\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<string> myList = new List<string>();\n myList.Add(\"One\");\n myList.Add(\"Two\");\n myList.Add(\"Three\");\n NetDataContractSerializer serializer = new NetDataContractSerializer();\n MemoryStream stream = new MemoryStream();\n serializer.Serialize(stream, myList);\n stream.Position = 0;\n Console.WriteLine(ASCIIEncoding.ASCII.GetString(stream.ToArray()));\n List<string> myList2 = (List<string>)serializer.Deserialize(stream);\n Console.WriteLine(myList2[0]);\n Console.ReadKey();\n }\n }\n}\n"
},
{
"answer_id": 217211,
"author": "Vyrotek",
"author_id": 10941,
"author_profile": "https://Stackoverflow.com/users/10941",
"pm_score": 3,
"selected": false,
"text": "[Serializable]\npublic struct Vector3\n{\n public double x, y, z;\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Vector3 vector = new Vector3();\n vector.x = 1;\n vector.y = 2;\n vector.z = 3;\n\n MemoryStream memoryStream = new MemoryStream();\n BinaryFormatter binaryFormatter = new BinaryFormatter();\n binaryFormatter.Serialize(memoryStream, vector);\n string str = System.Convert.ToBase64String(memoryStream.ToArray());\n\n //Store str into the database\n }\n}\n"
},
{
"answer_id": 217224,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 2,
"selected": false,
"text": "using System.Runtime.Serialization.Formatters.Binary;\nusing System.IO;\nusing System.Data.SqlClient;\nusing System.Runtime.Serialization;\n\npublic byte[] SerializeList<T>(List<T> list)\n{\n\n MemoryStream ms = new MemoryStream();\n\n BinaryFormatter bf = new BinaryFormatter();\n\n bf.Serialize(ms, list);\n\n ms.Position = 0;\n\n byte[] serializedList = new byte[ms.Length];\n\n ms.Read(serializedList, 0, (int)ms.Length);\n\n ms.Close();\n\n return serializedList; \n\n} \n\npublic List<T> DeserializeList<T>(byte[] data)\n{\n try\n {\n MemoryStream ms = new MemoryStream();\n\n ms.Write(data, 0, data.Length);\n\n ms.Position = 0;\n\n BinaryFormatter bf = new BinaryFormatter();\n\n List<T> list = bf.Deserialize(ms) as List<T>;\n\n return list;\n }\n catch (SerializationException ex)\n {\n // Handle deserialization problems here.\n Debug.WriteLine(ex.ToString());\n\n return null;\n }\n\n}\n List<string> stringList = new List<string>() { \"January\", \"February\", \"March\" };\n\nbyte[] data = SerializeList<string>(stringList);\n SqlParameter param = new SqlParameter(\"columnName\", SqlDbType.Binary, data.Length);\nparam.Value = data; \n\netc...\n"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25205/"
] |
217,190
|
<p>I have a revision that has been committed to SVN trunk which I would like to roll back. However, I would like to retain the changes in some fashion such as a branch or even a patch file. Any suggestions?</p>
|
[
{
"answer_id": 217200,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 1,
"selected": false,
"text": "svn diff"
}
] |
2008/10/19
|
[
"https://Stackoverflow.com/questions/217190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2043539/"
] |
217,213
|
<p>Is there a way to make <strong>awk</strong> (gawk) ignore or skip missing files? That is, files passed on the command line that no longer exist in the file system (e.g. rapidly appearing/disappearing files under /proc/[1-9]*).</p>
<p>By default, a missing file is a fatal error :-(</p>
<p>I would like to be able to do the equivalent of something like this:</p>
<pre><code>BEGIN { MISSING_FILES_ARE_FATAL = 0 } # <- Wishful thinking!
{ count++ }
END { print count }
</code></pre>
<p>A wrapper script cannot check that files exist befor awk is run as they may disappear between the time they are checked and awk then tries to open them, i.e., it is a race condition. (It is also a race condition to check-and-then-open within awk, although the timing is tighter)</p>
|
[
{
"answer_id": 217267,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/perl -w\n\nfor my $file (@ARGV) {\n open my $fh, $file or next;\n while(<$fh>) {\n ...do your thing here...\n }\n}\n"
},
{
"answer_id": 217897,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 1,
"selected": false,
"text": "[ -r \"$filename\" ] && awk -f ... $filename\n"
},
{
"answer_id": 217927,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 1,
"selected": false,
"text": "ARGV getline if (system(\"test -r \" ARGV[1]) == 0)\n while ( (getline aline < ARGV[1]) >0 )\n # process ARGV[1] via `aline` instead of $0\n"
},
{
"answer_id": 223724,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 0,
"selected": false,
"text": "cat /proc/[1-9]* 2>/dev/null | awk ....\n"
},
{
"answer_id": 420244,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "* io.c (nextfile): Users Strong In The Ways Of The Source can use\nnon-existant files on the command line without it being a fatal error.\n"
},
{
"answer_id": 12350657,
"author": "Dennis Williamson",
"author_id": 26428,
"author_profile": "https://Stackoverflow.com/users/26428",
"pm_score": 2,
"selected": false,
"text": "BEGINFILE ERRNO nextfile ERRNO"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,219
|
<p>I am using the Entity Framework and Linq to Entities. I have created a small database pattern & framework to implement versioning as well as localization. Every entity now consists of two or three tables, (ie Product, ProductBase & ProductLocal). </p>
<p>My linq always includes the following boilerplate code:</p>
<pre><code>from o in DB.Product
from b in o.Base
from l in o.Local
WHERE o.VersionStatus == (int)VersionStatus.Active
&& b.VersionStatus == (int)VersionStatus.Active
&& l.VersionStatus == (int)VersionStatus.Active
&& l.VersionLanguage == Context.CurrentLanguage
select new ProductInstance { Instance = o, Base = b, Local = l }
</code></pre>
<p>What I would like to accomplish is to turn the above into:</p>
<pre><code>(from o in DB.Product
from b in o.Base
from l in o.Local
select new ProductInstance { Instance = o, Base = b, Local = l }).IsActive()
</code></pre>
<p>Or at worst, something like:</p>
<pre><code>from o in DB.Product.Active()
from b in o.Base.Active()
from l in o.Local.Active()
select new ProductInstance { Instance = o, Base = b, Local = l }
</code></pre>
<p>I have extended the base classes the EDM generates to implement some interfaces that enforce the properties ( IVersionStatus and/or IVersionLanguage ). Is there some way I can walk the expression tree, check if the type in the expression implements that interface, then set the VersionStatus accordingly?</p>
<p>I woud love it to be as simple as the first option, just less to write and/or forget. I have seen examples that do it after the fact, after its IEnumerable, but I would rather not pull more from the database than I need to. </p>
<p>Thanks for any tips! </p>
|
[
{
"answer_id": 217293,
"author": "Ryan M",
"author_id": 29466,
"author_profile": "https://Stackoverflow.com/users/29466",
"pm_score": 0,
"selected": false,
"text": "DataLoadOptions"
},
{
"answer_id": 217299,
"author": "Scott Wisniewski",
"author_id": 1737192,
"author_profile": "https://Stackoverflow.com/users/1737192",
"pm_score": 2,
"selected": false,
"text": "DB.Product.SelectMany(o=>o.base, (o, b)=>new{o.b}).SelectMany(item=>o.local, (item, local)=>new {item.o, item.b, item.local}).Select(item=>new ProductInstance { Instance = item.o, Base = item.b, Local=item.Local});\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29466/"
] |
217,233
|
<p>I have multiple layers in an application and i find myself having to bubble up events to the GUI layer for doing status bar changes, etc . . I find myself having to write repeated coded where each layer simply subscribes to events from the lower layer and then in the call back simply raise an event up the chain. Is there a more efficient way of doing this?</p>
|
[
{
"answer_id": 217366,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "public event EventHandler SaveButtonClick\n{\n add { this.SaveButton.Click += value; }\n remove { this.SaveButton.Click -= value; }\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
217,253
|
<p>Here are the requirements:</p>
<p>Must be alphanumeric, 8-10 characters so that it is user friendly. These will be stored as unique keys in database. I am using Guids as primary keys so an option to use GUids to generate these unique Ids would be preferable.</p>
<p>I am thinking on the lines of a base-n converter that takes a Guid and converts to an 8 character unique string.</p>
<p>Short, light-weight algorithm preferred as it would be called quite often.</p>
|
[
{
"answer_id": 217284,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 2,
"selected": false,
"text": "words = [s.strip().lower() for s in open('/usr/share/dict/canadian-english') if \"'\" not in s]\nmod = len(words)\n\ndef main(script, guid):\n guid = hash(guid)\n\n print \"+\".join(words[(guid ** e) % mod] for e in (53, 61, 71))\n\nif __name__ == \"__main__\":\n import sys\n main(*sys.argv)\n oranjestad+compressing+wellspring\npadlock+discommoded+blazons\npt+olenek+renews\n"
},
{
"answer_id": 220006,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 3,
"selected": false,
"text": "8 characters - perfectly random - 36^8 = 2,821,109,907,456 combinations\n10 characters - perfectly random - 36^10 = 3,656,158,440,062,976 combinations\nGUID's - statistically unique* - 2^128 = 340,000,000,000,000,000,000,000,000,000,000,000,000 combinations\n Wholesaler, product name, product version, sku\nAmazon, IPod Nano, 2.2, AMIPDNN22\nBestBuy, Vaio, 3.2, BEVAIO32\n key -- what the key table may look like\nCREATE TABLE Keys(Name VARCHAR(10) primary key, NextID INT)\nINSERT INTO Keys Values('sku',1)\n\n// some elements of the class\npublic static SkuKeyGenerator \n{\n private static syncObject = new object();\n private static int nextID = 0;\n private static int maxID = 0;\n private const int amountToReserve = 100;\n\n public static int NextKey()\n {\n lock( syncObject )\n {\n if( nextID == maxID )\n {\n ReserveIds();\n }\n return nextID++;\n }\n }\n private static void ReserveIds()\n {\n // pseudocode - in reality I'd do this with a stored procedure inside a transaction,\n // We reserve some predefined number of keys from Keys where Name = 'sku'\n // need to run the select and update in the same transaction because this isn't the only\n // method that can use this table.\n using( Transaction trans = new Transaction() ) // pseudocode.\n {\n int currentTableValue = db.Execute(trans, \"SELECT NextID FROM Keys WHERE Name = 'sku'\");\n int newMaxID = currentTableValue + amountToReserve;\n db.Execute(trans, \"UPDATE Keys SET NextID = @1 WHERE Name = 'sku'\", newMaxID);\n\n trans.Commit();\n\n nextID = currentTableValue;\n maxID = newMaxID;\n }\n } \n key table"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23217/"
] |
217,257
|
<p>I want to sort members by name in the source code. Is there any easy way to do it? </p>
<p>I'm using NetBeans, but if there is another editor that can do that, just tell me the name of it.</p>
|
[
{
"answer_id": 27170560,
"author": "Johnny Baloney",
"author_id": 779449,
"author_profile": "https://Stackoverflow.com/users/779449",
"pm_score": 6,
"selected": true,
"text": "Tools -> Options -> Editor -> Formatting -> Category: Ordering\n Source -> Organize Members\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418/"
] |
217,258
|
<p>Let's say that you have overridden an object's equals() and hashCode() methods, so that they use the object's fields.</p>
<p>How you do you check if two references are to the same object, ala the stock equals() method?</p>
|
[
{
"answer_id": 217275,
"author": "joel.neely",
"author_id": 3525,
"author_profile": "https://Stackoverflow.com/users/3525",
"pm_score": 6,
"selected": true,
"text": "== equals() equals()"
},
{
"answer_id": 54128003,
"author": "Molten Ice",
"author_id": 679285,
"author_profile": "https://Stackoverflow.com/users/679285",
"pm_score": 1,
"selected": false,
"text": "Assert.assertSame()"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27708/"
] |
217,259
|
<p>Often, programmers write code that generates other code.</p>
<p>(The technical term is <a href="http://en.wikipedia.org/wiki/Metaprogramming" rel="nofollow noreferrer" title="Wikipedia article on metaprogramming">metaprogramming</a>, but it is more common than merely cross-compilers; think about every PHP web-page that generates HTML or every XSLT file.)</p>
<p>One area I find challenging is coming up with techniques to ensure that <em>both</em> the hand-written source file, and the computer-generated object file are clearly indented to aid debugging. The two goals often seem to be competing.</p>
<p>I find this particularly challenging in the PHP/HTML combination. I think that is because:</p>
<ul>
<li>there is sometimes more of the HTML code in the source file than the generating PHP</li>
<li>HTML files tend to be longer than, say, SQL statements, and need better indenting</li>
<li>HTML has space-sensitive features (e.g. between tags)</li>
<li>the result is more publicly visible HTML than SQL statements, so there is more pressure to do a reasonable job.</li>
</ul>
<p>What techniques do you use to address this?</p>
<p><hr/>
Edit: I accept that there are at least three arguments to not bothering to generate pretty HTML code:</p>
<ul>
<li>Complexity of generating code is increased.</li>
<li>Makes no difference to rendering by browser; developers can use Firebug or similar to view it nicely.</li>
<li>Minor performance hit - increased download time for whitespace characters.</li>
</ul>
<p>I have certainly sometimes generated code without thought to the indenting (especially SQL).</p>
<p>However, there are a few arguments pushing the other way:</p>
<ul>
<li>I find, in practice, that I <em>do</em> frequently read generated code - having extra steps to access it is inconvenient.</li>
<li>HTML has some space-sensitivity issues that bite occasionally. </li>
</ul>
<p>For example, consider the code:</p>
<pre><code><div class="foo">
<?php
$fooHeader();
$fooBody();
$fooFooter();
?>
</div>
</code></pre>
<p>It is clearer than the following code:</p>
<pre><code><div class="foo"><?php
$fooHeader();
$fooBody();
$fooFooter();
?></div>
</code></pre>
<p>However, it is also has different rendering because of the whitespace included in the HTML.</p>
|
[
{
"answer_id": 217264,
"author": "Oddthinking",
"author_id": 8014,
"author_profile": "https://Stackoverflow.com/users/8014",
"pm_score": 2,
"selected": false,
"text": "def generateWhileLoop(condition, block, indentPrefix = \"\"):\n print indentPrefix + \"while \" + condition + \":\"\n generateBlock(block, indentPrefix + \" \")\n def generateWhileLoop(condition, block, indentLevel = 0):\n print \" \" * (indentLevel * spacesPerIndent) + \"while \" + condition + \":\"\n generateBlock(block, indentLevel + 1)\n condition block"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8014/"
] |
217,266
|
<p>If the C++ runtime msvcr80.dll is missing from a compiled library, is there any way to determine which version was used to create the library or to get it to run on a later version of msvcr80.dll?</p>
|
[
{
"answer_id": 217369,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 5,
"selected": true,
"text": "%SystemRoot%\\WinSxS %ProgramFiles%\\Microsoft Visual Studio 8\\VC\\redist mt.exe -inputresource:mydll.dll;#1 -out:mydll.dll.manifest\n <assemblyIdentity type=\"win32\" name=\"Microsoft.VC90.CRT\" version=\"9.0.21022.8\" processorArchitecture=\"x86\" publicKeyToken=\"1fc8b3b9a1e18e3b\">\n</assemblyIdentity>\n WinSxS D:>dir c:\\windows\\WinSxS\\*VC90.CRT*\n12/14/2007 02:16 AM <DIR> amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_750b37ff97f4f68b\n12/14/2007 02:00 AM <DIR> x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4670/"
] |
217,287
|
<p>I'm a c++ programmer and I'm playing around with java after finding JPA which for a few of my current applications is a god send. I haven't touched java since university and I'm having a problem running out of heap space. I'm using the code below as the main part of a not-very-serious test of jdbc/jpa/lucene but I keep on getting random OutOfMemory exceptions.</p>
<pre><code> EntityManager em = emf.createEntityManager();
Query q = em.createQuery("select p from Product p" +
" where p.productid = :productid");
Connection con = DriverManager.getConnection("connection string");
Statement st = con.createStatement();
IndexWriter writer = new IndexWriter("c:\\temp\\lucene", new StandardAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
ResultSet rs = st.executeQuery("select productid from product order by productid");
while (rs.next()) {
int productid = rs.getInt("PRODUCTID");
q.setParameter("productid", productid);
Product p = (Product)q.getSingleResult();
writer.addDocument(createDocument(p));
}
writer.commit();
writer.optimize();
writer.close();
st.close();
con.close();
</code></pre>
<p>I won't post all of createDocument but all it does is instantiate a new org.apache.lucene.document.Document and adds fields via add(new Field...) etc. There are about 50 fields in total and most are short strings (<32 characters) in length.</p>
<p>In my newby-ness is there something completely stupid I'm doing (or not) that would cause things not to be GC'd?</p>
<p>Are there best practices regarding java memory management and tickling the GC?</p>
|
[
{
"answer_id": 217294,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "-Xmx n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,301
|
<p>I've run across this sort of thing on multiple websites and was wondering what it was called, does anyone know? <a href="http://twitpic.com/h77i/full" rel="nofollow noreferrer" title="twitpic.com">Here's a screenshot.</a></p>
|
[
{
"answer_id": 217294,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "-Xmx n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26948/"
] |
217,316
|
<p>I am using pseudo-code here, but this is in JavaScript. With the most efficient algorithm possible I am trying to find the high and low given an array of positive whole numbers. This is what I came up with, but I don't think it is probably best, and was just wondering if anyone has any other suggestions.</p>
<pre><code>var low = 1;
var high = 1;
for ( loop numbers ) {
if ( number > high ) {
high = number;
}
if ( low == 1 ) {
low = high;
}
if ( number < low ) {
low = number;
}
}
</code></pre>
|
[
{
"answer_id": 217320,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": -1,
"selected": false,
"text": ">>> seq = [1, 2, 3, 4, 5, 6, 7]\n>>> max(seq)\n7\n>>> min(seq)\n1\n"
},
{
"answer_id": 217322,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 3,
"selected": false,
"text": "O(n) n O(n*log(n)) O(n)"
},
{
"answer_id": 217324,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 0,
"selected": false,
"text": "low = +INFINITY\nhigh = -INFINITY\nfor each n in numbers:\n if n < low:\n low = n\n if n > high:\n high = n\n"
},
{
"answer_id": 217326,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": true,
"text": "var myArray = [...],\n low = myArray[0],\n high = myArray[0]\n;\n// start looping at index 1\nfor (var i = 1, l = myArray.length; i < l; ++i) {\n if (myArray[i] > high) {\n high = myArray[i];\n } else if (myArray[i] < low) {\n low = myArray[i];\n }\n}\n for (var i = 1, val; (val = myArray[i]) !== undefined; ++i) {\n if (val > high) {\n high = val;\n } else if (val < low) {\n low = val;\n }\n}\n"
},
{
"answer_id": 217327,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "var low = numbers[0]; // first number in array\nvar high = numbers[0]; // first number in array\nfor ( loop numbers ) {\n if ( number > high ) {\n high = number;\n }\n if ( number < low ) {\n low = number;\n }\n}\n"
},
{
"answer_id": 217330,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 3,
"selected": false,
"text": "# Initialize max & min\nmy $max = $list[0];\nmy $min = $list[0];\nfor my $num (@list) {\n $max = $num if $num > $max;\n $min = $num if $num < $min;\n}\n"
},
{
"answer_id": 217508,
"author": "Drew Hall",
"author_id": 23934,
"author_profile": "https://Stackoverflow.com/users/23934",
"pm_score": 2,
"selected": false,
"text": "std::pair<int, int> minmax(int* a, int n)\n{\n int low = std::numeric_limits<int>::max();\n int high = std::numeric_limits<int>::min();\n\n for (int i = 0; i < n-1; i += 2) {\n if (a[i] < a[i+i]) {\n if (a[i] < low) {\n low = a[i];\n }\n if (a[i+1] > high) {\n high = a[i+1];\n }\n }\n else {\n if (a[i] > high) {\n high = a[i];\n }\n if (a[i+1] < low) {\n low = a[i+1];\n }\n }\n }\n\n // Handle last element if we've got an odd array size\n if (a[n-1] < low) {\n low = a[n-1];\n }\n if (a[n-1] > high) {\n high = a[n-1];\n }\n\n return std::make_pair(low, high);\n} \n"
},
{
"answer_id": 218116,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 2,
"selected": false,
"text": "var numbers = [1,2,5,9,16,4,6];\n\nvar maxNumber = Math.max.apply(null, numbers);\nvar minNumber = Math.min.apply(null, numbers);\n"
},
{
"answer_id": 237158,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 2,
"selected": false,
"text": "var A = [ /* 100,000 random integers */];\n\nfunction minmax() {\n var low = A[A.length-1];\n var high = A[A.length-1];\n var i, x, y;\n for (i = A.length - 3; 0 <= i; i -= 2) {\n y = A[i+1];\n x = A[i];\n if (x < y) {\n if (x < low) {\n low = x;\n }\n if (high < y) {\n high = y;\n }\n } else {\n if (y < low) {\n low = y;\n }\n if (high < x) {\n high = x;\n }\n }\n }\n if (i === -1) {\n x = A[0];\n if (high < x) {\n high = x;\n } else if (x < low) {\n low = x;\n }\n }\n return [low, high];\n}\n\nfor (var i = 0; i < 1000; ++i) { minmax(); }\n"
},
{
"answer_id": 832791,
"author": "fearphage",
"author_id": 2733,
"author_profile": "https://Stackoverflow.com/users/2733",
"pm_score": 2,
"selected": false,
"text": "var sorted = arrayOfNumbers.sort(function(a, b) { return a - b; }),\n ,min = sorted[0], max = sorted[sorted.length -1];\n // standard sort function\nfunction sorter(a, b) {\n if (/* some check */)\n return -1; // a should be left of b\n if (/*some other check*/)\n return 1; // a should be to the right of b\n return 0; // a is equal to b (no movement)\n}\n var numbers = [5,8,123,1,7,77,3.14,-5];\n\n// default lexicographical sort\nnumbers.sort() // -5,1,123,3.14,5,7,77,8\n\n// numerical sort\nnumbers.sort(function(a, b) { return a - b; }) // -5,1,123,3.14,5,7,77,8\n"
},
{
"answer_id": 1717166,
"author": "NeO",
"author_id": 208878,
"author_profile": "https://Stackoverflow.com/users/208878",
"pm_score": 0,
"selected": false,
"text": "enter code here\nint l=0,h=1,index,i=3;\n if(a[l]>a[h])\n swap(&a[l],&a[h]);\n for(i=2;i<9;i++)\n {\n if(a[i]<a[l])\n {\n swap(&a[i],&a[l]); \n }\n if(a[i]>a[h])\n {\n swap(&a[i],&a[h]);\n }\n }\n printf(\"Low: %d High: %d\",a[0],a[1]);\n"
},
{
"answer_id": 45689679,
"author": "a_rahmanshah",
"author_id": 861712,
"author_profile": "https://Stackoverflow.com/users/861712",
"pm_score": 1,
"selected": false,
"text": "var arrNums = [1, 2, 3, 4, 5];\nMath.max(...arrNums) // 5\nMath.min(...arrNums) // 1\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,350
|
<p>I'm building an ASP.Net MVC website. Rather than have everything in one project, I've decided to separate the Web, Model and Controller out into different projects in the same solution, that reference each-other.</p>
<p>The referencing goes like this:</p>
<blockquote>
<p>Web ---[references]---> Controller ---[references]---> Model</p>
</blockquote>
<p>Now I wanted to add 2 custom methods to the HtmlHelper class - they're called "IncludeScript" and "IncludeStyle". They each take a single string parameter, and generate a script or link tag respectively.</p>
<p>I've created an extender class, according to documentation on the web, and written the two methods and compiled the application.</p>
<p>Now, when I go into the Public.Master page (which is my main master-page, and one of the places where I intend to use these methods), I can enter code such as below:</p>
<p><code><%= Html.IncludeScript("\js\jquery.js") %></code></p>
<p>The IntelliSense picks up and IncludeScript method and shows me the syntax just fine. So I'd expect that everything should work.</p>
<p>But it doesn't.</p>
<p>Everything compiles, but as soon as I run the application, I get the following run-time error from line 14 of Default.aspx.cs:</p>
<p><code>c:\\Projects\\PhoneReel\\PhoneReel.Web\\Views\\Shared\\Public.Master(11): error CS0117: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'IncludeScript'</code></p>
<p>Here's the line of code that the error happens on:</p>
<p><code>httpHandler.ProcessRequest(HttpContext.Current);</code></p>
<p>Any ideas what could be going wrong here?</p>
|
[
{
"answer_id": 220162,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 5,
"selected": true,
"text": "<%@ Import Namespace=\"MyRootNamespace.NamespaceForMyHtmlHelperExtensions\"%>\n <add namespace=\"MyRootNamespace.NamespaceForMyHtmlHelperExtensions\"/>\n"
},
{
"answer_id": 1980592,
"author": "Ben Lesh",
"author_id": 135786,
"author_profile": "https://Stackoverflow.com/users/135786",
"pm_score": 3,
"selected": false,
"text": "HtmlHelper<object> HtmlHelper<T> public static string IncludeScript<T>(this HtmlHelper<T> html, string url) {\n return \"<script type=\\\"text/javascript\\\" src=\\\"\" + url + \"\\\"></script>\";\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23341/"
] |
217,353
|
<p>I've been trying to figure out how to retrieve the text selected by the user in my webbrowser control and have had no luck after digging through msdn and other resources, So I was wondering if there is a way to actually do this. Maybe I simply missed something.</p>
<p>I appreciate any help or resources regarding this.</p>
<p>Thanks</p>
|
[
{
"answer_id": 217509,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 6,
"selected": true,
"text": "using mshtml;\n\n...\n\n IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;\n\n IHTMLSelectionObject currentSelection= htmlDocument.selection;\n\n if (currentSelection!=null) \n {\n IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange;\n\n if (range != null)\n {\n MessageBox.Show(range.text);\n }\n }\n"
},
{
"answer_id": 20808916,
"author": "Hermano",
"author_id": 3140793,
"author_profile": "https://Stackoverflow.com/users/3140793",
"pm_score": 0,
"selected": false,
"text": " Clipboard.Clear();\n SendKeys.SendWait(\"^(c)\");\n string strClip = Clipboard.GetText().Trim();\n Clipboard.Clear();\n"
},
{
"answer_id": 41764428,
"author": "username",
"author_id": 479248,
"author_profile": "https://Stackoverflow.com/users/479248",
"pm_score": 3,
"selected": false,
"text": "private string GetSelectedText()\n{\n dynamic document = webBrowser.Document.DomDocument;\n dynamic selection = document.selection;\n dynamic text = selection.createRange().text;\n return (string)text;\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29477/"
] |
217,356
|
<p>What kind of collection I should use to convert NameValue collection to be bindable to GridView?
When doing directly it didn't work.</p>
<p><strong>Code in aspx.cs</strong></p>
<pre><code> private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = list;
resultGV.DataBind();
}
</code></pre>
<p><strong>Code in aspx</strong></p>
<pre><code><asp:GridView ID="resultGV" runat="server" AutoGenerateColumns="False" Width="100%">
<Columns>
<asp:BoundField DataField="Key" HeaderText="Key" />
<asp:BoundField DataField="Value" HeaderText="Value" />
</Columns>
</asp:GridView>
</code></pre>
<p>Any tip most welcome. Thanks. X.</p>
|
[
{
"answer_id": 217361,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "resultGV.DataSource = from item in nvpDictionary\n select new { Key = item.Key, Value = item.Value };\nresultGV.DataBind();\n resultGV.DataSource = nvpDictionary;\nresultGV.DataBind();\n private void BindList(NameValueCollection nvpList)\n{\n Dictionary<string,string> temp = new Dictionary<string,string>();\n foreach (string key in nvpList)\n {\n temp.Add(key,nvpList[key]);\n }\n\n resultGV.DataSource = temp;\n resultGV.DataBind();\n}\n public static class NameValueCollectionExtensions\n{\n public static Dictionary<string,string> ToDictionary( this NameValueCollection collection )\n {\n Dictionary<string,string> temp = new Dictionary<string,string>();\n foreach (string key in collection)\n {\n temp.Add(key,collection[key]);\n }\n return temp;\n }\n}\n\nprivate void BindList(NameValueCollection nvpList)\n{\n resultGV.DataSource = nvpList.ToDictionary();\n resultGV.DataBind();\n}\n"
},
{
"answer_id": 221681,
"author": "Jaroslav Urban",
"author_id": 24507,
"author_profile": "https://Stackoverflow.com/users/24507",
"pm_score": 2,
"selected": false,
"text": " private void BindList(NvpList nvpList)\n {\n IDictionary dict = new Dictionary<string, string>();\n\n foreach (String s in nvpList.AllKeys)\n dict.Add(s, nvpList[s]);\n\n resultGV.DataSource = dict;\n resultGV.DataBind();\n }\n"
},
{
"answer_id": 221797,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": false,
"text": "<asp:GridView id=\"gv\" runat=\"server\" AutoGenerateColumns=\"false\">\n <Columns>\n <asp:TemplateField HeaderText=\"Key\">\n <ItemTemplate><%# Container.DataItem %></ItemTemplate>\n </asp:TemplateField>\n <asp:TemplateField HeaderText=\"Value\">\n <ItemTemplate>\n <%# ((NameValueCollection)gv.DataSource)[(string)Container.DataItem] %>\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n</asp:GridView>\n"
},
{
"answer_id": 2548768,
"author": "Adam Nofsinger",
"author_id": 18524,
"author_profile": "https://Stackoverflow.com/users/18524",
"pm_score": 1,
"selected": false,
"text": "Repeater GridView <asp:Repeater ID=\"rpt\" runat=\"server\">\n<ItemTemplate>\n <li>\n <%# Container.DataItem %>:\n <%# ((NameValueCollection)((Repeater)Container.Parent).DataSource)[(string)Container.DataItem] %>\n </li> \n</ItemTemplate>\n</asp:Repeater>\n"
},
{
"answer_id": 7050031,
"author": "fredsmith",
"author_id": 892980,
"author_profile": "https://Stackoverflow.com/users/892980",
"pm_score": 1,
"selected": false,
"text": "Dim sDict as New StringDictionary\nsDict.Add(\"1\",\"data1\")\nsDict.Add(\"2\",\"data2\")\nsDict.Add(\"3\",\"data3\")\n...\n\nCheckBoxList1.DataSource = sDict\nCheckBoxList1.DataValueField = \"key\"\nCheckBoxList1.DataTextField = \"value\"\nCheckBoxList1.DataBind()\n"
},
{
"answer_id": 9930261,
"author": "PCasagrande",
"author_id": 624089,
"author_profile": "https://Stackoverflow.com/users/624089",
"pm_score": 0,
"selected": false,
"text": "<asp:GridView ID=\"gv\" runat=\"server\" AutoGenerateColumns=\"False\">\n <Columns>\n <asp:TemplateField HeaderText=\"Attribute\">\n <ItemTemplate>\n <%# ((KeyValuePair<string,string>)Container.DataItem).Key %>\n </ItemTemplate>\n </asp:TemplateField>\n <asp:TemplateField HeaderText=\"Value\">\n <ItemTemplate>\n <%# ((KeyValuePair<string,string>)Container.DataItem).Value %>\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n</asp:GridView>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24507/"
] |
217,377
|
<p>How do you use the LEFT function (or an equivalent) on a SQL Server NTEXT column?</p>
<p>Basically I'm building a GridView and I just want to return the first 100 or so characters from the Description column which is NTEXT. </p>
|
[
{
"answer_id": 13456806,
"author": "Dane B",
"author_id": 4480,
"author_profile": "https://Stackoverflow.com/users/4480",
"pm_score": 3,
"selected": false,
"text": "SUBSTRING ( value_expression , start_expression , length_expression )\n Description SELECT SUBSTRING(Description, 1, 100) as truncatedDescription FROM MyTable;\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
217,389
|
<p>I'm working on a C# program, and right now I have one <code>Form</code> and a couple of classes. I would like to be able to access some of the <code>Form</code> controls (such as a <code>TextBox</code>) from my class. When I try to change the text in the <code>TextBox</code> from my class I get the following error:</p>
<blockquote>
<p>An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog' </p>
</blockquote>
<p>How can I access methods and controls that are in <code>Form1.cs</code> from one of my classes?</p>
|
[
{
"answer_id": 217394,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 2,
"selected": false,
"text": "Form1.txtLog.Text = \"blah\"\n Form1 blah = new Form1();\nblah.txtLog.Text = \"hello\"\n"
},
{
"answer_id": 217397,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 6,
"selected": true,
"text": "public void DoSomethingWithText(string formText)\n{\n // do something text in here\n}\n string SomeProperty\n{\n get \n {\n return textBox1.Text;\n }\n set\n {\n textBox1.Text = value;\n }\n}\n"
},
{
"answer_id": 217425,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 4,
"selected": false,
"text": "public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n TestClass test = new TestClass();\n test.ModifyText(textBox1);\n }\n}\n\npublic class TestClass\n{\n public void ModifyText(TextBox textBox)\n {\n textBox.Text = \"New text\";\n }\n}\n"
},
{
"answer_id": 2256501,
"author": "Ojhnny777",
"author_id": 272270,
"author_profile": "https://Stackoverflow.com/users/272270",
"pm_score": 2,
"selected": false,
"text": "public partial class Form1 : Form\n{\n public ListView Lv\n {\n get { return lvProcesses; }\n }\n\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n Utilities ut = new Utilities(this);\n }\n}\n class Utilities\n{\n private Form1 _mainForm;\n public Utilities(Form1 mainForm)\n {\n _mainForm = mainForm;\n _mainForm.Lv.Items.Clear();\n }\n}\n"
},
{
"answer_id": 4401749,
"author": "Jim",
"author_id": 536876,
"author_profile": "https://Stackoverflow.com/users/536876",
"pm_score": 1,
"selected": false,
"text": " //Add a new form called frmEditData to project.\n //Draw a textbox on it named txtTest; set the text to\n //something in design as a test.\n Form frmED = new frmEditData();\n MessageBox.Show(frmED.Controls[\"txtTest\"].Text);\n"
},
{
"answer_id": 20883920,
"author": "Toprak",
"author_id": 2476266,
"author_profile": "https://Stackoverflow.com/users/2476266",
"pm_score": 0,
"selected": false,
"text": "Class1 excell = new Class1 (); //you must declare this in form as you want to control\n\nexcel.get_data_from_excel(this); // And create instance for class and sen this form to another class\n class Class1\n{\n public void get_data_from_excel (Form1 form) //you getting the form here and you can control as you want\n {\n form.ComboBox1.text = \"try it\"; //you can chance Form1 UI elements inside the class now\n }\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13504/"
] |
217,414
|
<p>I am a big fan of the Lightbox2 library, and have used it in the past just not on an MVC project. In the past I remember that Lightbox2 was picky about the paths it scripts, css, and images resided in. I remember specifically have to put everything in subdirectories of the page's path, else it wouldn't work.</p>
<p>In a non-MVC application that approach was fine, but now I find myself working on an MVC application and a page's URL may have nothing to do with the directory structure. So linking to Lightbox2 per the instructions of:</p>
<pre><code><script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
</code></pre>
<p>obviously does not work.</p>
<p>I tried putting the absolute path to the JavaScript which gave me the effects, just without the images. I am suspecting that the JavaScript "knows" where its images are, and cannot find them.</p>
<p>Has anyone had success with Lightbox2 in an MVC environment? Perhaps just success deploying Lightbox2 to a non-subdirectory?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 217456,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": -1,
"selected": false,
"text": "\n<script type=\"text/javascript\" src=\"/js/prototype.js\">\n"
},
{
"answer_id": 217459,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 3,
"selected": true,
"text": "fileLoadingImage: 'images/loading.gif', \nfileBottomNavCloseImage: 'images/closelabel.gif',\n #prevLink:hover, #prevLink:visited:hover { background: url(../images/prevlabel.gif) left 15% no-repeat; }\n#nextLink:hover, #nextLink:visited:hover { background: url(../images/nextlabel.gif) right 15% no-repeat; }\n"
},
{
"answer_id": 28580994,
"author": "Kush Bhardwaj",
"author_id": 4268585,
"author_profile": "https://Stackoverflow.com/users/4268585",
"pm_score": 0,
"selected": false,
"text": "<script src=\"~/LightBox/js/jquery.js\"></script>\n\n<script src=\"~/LightBox/js/jquery.lightbox-0.5.min.js\"></script>\n\n<a title=\"Title here\" class=\"lightbox\" href=\"~/LightBox/images/lightbox-btn-close.gif\">click</a>\n\n\n\n<script type=\"text/javascript\">\n $(function () {\n $('a.lightbox').lightBox();//.lightBox(); // Select all links with lightbox class\n });\n</script>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27860/"
] |
217,424
|
<p>I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.</p>
<p>I have the e-mailing of the link, MySQL query, etc. covered.</p>
<p>How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL? </p>
<p>I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.</p>
|
[
{
"answer_id": 217432,
"author": "Gavin M. Roy",
"author_id": 13203,
"author_profile": "https://Stackoverflow.com/users/13203",
"pm_score": 1,
"selected": false,
"text": "header('Content-type: text/csv');\nheader('Content-disposition: attachment; filename=\"myfile.csv\"');\n"
},
{
"answer_id": 217434,
"author": "Oleg Barshay",
"author_id": 2043539,
"author_profile": "https://Stackoverflow.com/users/2043539",
"pm_score": 9,
"selected": true,
"text": "header(\"Content-type: text/csv\");\nheader(\"Content-Disposition: attachment; filename=file.csv\");\nheader(\"Pragma: no-cache\");\nheader(\"Expires: 0\");\n\necho \"record1,record2,record3\\n\";\ndie;\n function maybeEncodeCSVField($string) {\n if(strpos($string, ',') !== false || strpos($string, '\"') !== false || strpos($string, \"\\n\") !== false) {\n $string = '\"' . str_replace('\"', '\"\"', $string) . '\"';\n }\n return $string;\n}\n"
},
{
"answer_id": 217435,
"author": "typemismatch",
"author_id": 13714,
"author_profile": "https://Stackoverflow.com/users/13714",
"pm_score": 3,
"selected": false,
"text": "$fname = 'myCSV.csv';\n$fp = fopen($fname,'wb');\nfwrite($fp,$csvdata);\nfclose($fp);\n\nheader('Content-type: application/csv');\nheader(\"Content-Disposition: inline; filename=\".$fname);\nreadfile($fname);\n"
},
{
"answer_id": 360661,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<?\n // Connect to database\n $result = mysql_query(\"select id\n from tablename\n where shid=3\");\n list($DBshid) = mysql_fetch_row($result);\n\n /***********************************\n Write date to CSV file\n ***********************************/\n\n $_file = 'show.csv';\n $_fp = @fopen( $_file, 'wb' );\n\n $result = mysql_query(\"select name,compname,job_title,email_add,phone,url from UserTables where id=3\");\n\n while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))\n {\n $_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . \"\\n\";\n @fwrite( $_fp, $_csv_data);\n }\n @fclose( $_fp );\n?>\n"
},
{
"answer_id": 1749521,
"author": "Behzad Ravanbakhsh",
"author_id": 212959,
"author_profile": "https://Stackoverflow.com/users/212959",
"pm_score": 2,
"selected": false,
"text": "$CSV_string=\"No,Date,Email,Sender Name,Sender Email \\n\"; //making string, So \"\\n\" is used for newLine\n\n$rand = rand(1,50); //Make a random int number between 1 to 50.\n$file =\"export/export\".$rand.\".csv\"; //For avoiding cache in the client and on the server \n //side it is recommended that the file name be different.\n\nfile_put_contents($file,$CSV_string);\n\n/* Or try this code if $CSV_string is an array\n fh =fopen($file, 'w');\n fputcsv($fh , $CSV_string , \",\" , \"\\n\" ); // \",\" is delimiter // \"\\n\" is new line.\n fclose($fh);\n*/\n"
},
{
"answer_id": 2250821,
"author": "user244641",
"author_id": 244641,
"author_profile": "https://Stackoverflow.com/users/244641",
"pm_score": 2,
"selected": false,
"text": "$data = array (\n 'aaa,bbb,ccc,dddd',\n '123,456,789',\n '\"aaa\",\"bbb\"');\n\n$fp = fopen('data.csv', 'wb');\nforeach($data as $line){\n $val = explode(\",\",$line);\n fputcsv($fp, $val);\n}\nfclose($fp);\n $data"
},
{
"answer_id": 4053351,
"author": "Joshua",
"author_id": 491471,
"author_profile": "https://Stackoverflow.com/users/491471",
"pm_score": 1,
"selected": false,
"text": "$query = \"SELECT * FROM customers WHERE created>='{$start} 00:00:00' AND created<='{$end} 23:59:59' ORDER BY id\";\n$select_c = mysql_query($query) or die(mysql_error()); \n\nwhile ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))\n{\n $result.=\"{$row['email']},\";\n $result.=\"\\n\";\n echo $result;\n}\n $query = \"SELECT * FROM customers WHERE created>='{$start} 00:00:00' AND created<='{$end} 23:59:59' ORDER BY id\";\n$select_c = mysql_query($query) or die(mysql_error()); \n\nwhile ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))\n{\n echo implode(\",\", $row).\"\\n\";\n}\n"
},
{
"answer_id": 4214004,
"author": "Lorenzo Massacci",
"author_id": 511993,
"author_profile": "https://Stackoverflow.com/users/511993",
"pm_score": -1,
"selected": false,
"text": "$output header(\"Content-type: application/download\\r\\n\");\nheader(\"Content-disposition: filename=filename.csv\\r\\n\\r\\n\");\nheader(\"Content-Transfer-Encoding: ASCII\\r\\n\");\nheader(\"Content-length: \".strlen($output).\"\\r\\n\");\necho $output;\n"
},
{
"answer_id": 6493794,
"author": "multitask landscape",
"author_id": 355491,
"author_profile": "https://Stackoverflow.com/users/355491",
"pm_score": 9,
"selected": false,
"text": "header(\"Content-Type: text/csv\");\nheader(\"Content-Disposition: attachment; filename=file.csv\");\n\nfunction outputCSV($data) {\n $output = fopen(\"php://output\", \"wb\");\n foreach ($data as $row)\n fputcsv($output, $row); // here you can change delimiter/enclosure\n fclose($output);\n}\n\noutputCSV(array(\n array(\"name 1\", \"age 1\", \"city 1\"),\n array(\"name 2\", \"age 2\", \"city 2\"),\n array(\"name 3\", \"age 3\", \"city 3\")\n));\n"
},
{
"answer_id": 6820871,
"author": "Sergiu",
"author_id": 821495,
"author_profile": "https://Stackoverflow.com/users/821495",
"pm_score": 1,
"selected": false,
"text": "$csv = new csv();\n$csv->load_data(array(\n array('name'=>'John', 'age'=>35),\n array('name'=>'Adrian', 'age'=>23), \n array('name'=>'William', 'age'=>57) \n));\n$csv->send_file('age.csv'); \n"
},
{
"answer_id": 8455497,
"author": "LBJ",
"author_id": 1026111,
"author_profile": "https://Stackoverflow.com/users/1026111",
"pm_score": 3,
"selected": false,
"text": "<a href=\"my_csv_creator.php?user=23&othervariable=true\">Get CSV</a>\n User_John_Doe_10_Dec_11.csv\n"
},
{
"answer_id": 9282686,
"author": "Xeoncross",
"author_id": 99923,
"author_profile": "https://Stackoverflow.com/users/99923",
"pm_score": 4,
"selected": false,
"text": "function download_csv_results($results, $name = NULL)\n{\n if( ! $name)\n {\n $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';\n }\n\n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename='. $name);\n header('Pragma: no-cache');\n header(\"Expires: 0\");\n\n $outstream = fopen(\"php://output\", \"wb\");\n\n foreach($results as $result)\n {\n fputcsv($outstream, $result);\n }\n\n fclose($outstream);\n}\n download_csv_results($results, 'your_name_here.csv');\n exit()"
},
{
"answer_id": 13004367,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$CSVFileName = “test.csv”;\n$fp = fopen($CSVFileName, ‘wb’);\n\n//Multiple iterations to append the data using function fputs()\nforeach ($csv_post as $temp)\n{\n $line = “”;\n $line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;\n $line .= “\\n”;\n fputs($fp, $line);\n}\n"
},
{
"answer_id": 13917876,
"author": "zahid9i",
"author_id": 831910,
"author_profile": "https://Stackoverflow.com/users/831910",
"pm_score": 1,
"selected": false,
"text": "<?php\nextract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable\n\nheader(\"Content-type: text/csv\");\nheader(\"Content-Disposition: attachment; filename=$table.csv\");\nheader(\"Pragma: no-cache\");\nheader(\"Expires: 0\");\n\nrequire_once(\"includes/functions.php\"); //necessary mysql connection functions here\n\n//first of all I'll get the column name to put title of csv file.\n$query = \"SHOW columns FROM $table\";\n$headers = mysql_query($query) or die(mysql_error());\n$csv_head = array();\nwhile ($row = mysql_fetch_array($headers, MYSQL_ASSOC))\n{\n $csv_head[] = $row['Field'];\n}\necho implode(\",\", $csv_head).\"\\n\";\n\n//now I'll bring the data.\n$query = \"SELECT * FROM $table\";\n$select_c = mysql_query($query) or die(mysql_error()); \n\nwhile ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))\n{\n foreach ($row as $key => $value) {\n //there may be separator (here I have used comma) inside data. So need to put double quote around such data.\n if(strpos($value, ',') !== false || strpos($value, '\"') !== false || strpos($value, \"\\n\") !== false) {\n $row[$key] = '\"' . str_replace('\"', '\"\"', $value) . '\"';\n }\n }\n echo implode(\",\", $row).\"\\n\";\n}\n\n?>\n <a href=\"csv-download.php?table=tbl_vfm\"><img title=\"Download as Excel\" src=\"images/Excel-logo.gif\" alt=\"Download as Excel\" /><a/>\n"
},
{
"answer_id": 14876161,
"author": "Kaddy",
"author_id": 2072227,
"author_profile": "https://Stackoverflow.com/users/2072227",
"pm_score": 2,
"selected": false,
"text": "<?php\nheader(\"Content-type: application/csv\");\nheader(\"Content-Disposition: attachment; filename=file.csv\");\nheader(\"Pragma: no-cache\");\nheader(\"Expires: 0\");\n\nini_set('display_errors',1);\n$private=1;\nerror_reporting(E_ALL ^ E_NOTICE);\n\nmysql_connect(\"localhost\", \"user\", \"pass\") or die(mysql_error());\nmysql_select_db(\"db\") or die(mysql_error());\n\n$start = $_GET[\"start\"];\n$end = $_GET[\"end\"];\n\n$query = \"SELECT * FROM customers WHERE created>='{$start} 00:00:00' AND created<='{$end} 23:59:59' ORDER BY id\";\n$select_c = mysql_query($query) or die(mysql_error());\n\nwhile ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))\n{\n $result.=\"{$row['email']},\";\n $result.=\"\\n\";\n echo $result;\n}\n"
},
{
"answer_id": 15422151,
"author": "Stan",
"author_id": 596082,
"author_profile": "https://Stackoverflow.com/users/596082",
"pm_score": 4,
"selected": false,
"text": "header(\"Content-Transfer-Encoding: UTF-8\");\n"
},
{
"answer_id": 17410825,
"author": "Justin",
"author_id": 922522,
"author_profile": "https://Stackoverflow.com/users/922522",
"pm_score": 3,
"selected": false,
"text": "$query = $pdo->prepare('SELECT * FROM test WHERE id=?');\n$query->execute(array($id)); \n$results = $query->fetchAll(PDO::FETCH_ASSOC);\ndownload_csv_results($results, 'test.csv'); \nexit();\n\n\nfunction download_csv_results($results, $name)\n{ \n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename='. $name);\n header('Pragma: no-cache');\n header(\"Expires: 0\");\n\n $outstream = fopen(\"php://output\", \"wb\"); \n fputcsv($outstream, array_keys($results[0]));\n\n foreach($results as $result)\n {\n fputcsv($outstream, $result);\n }\n\n fclose($outstream);\n}\n"
},
{
"answer_id": 28894341,
"author": "Shahbaz",
"author_id": 1869193,
"author_profile": "https://Stackoverflow.com/users/1869193",
"pm_score": 2,
"selected": false,
"text": "$list[] = array(\"Cars\", \"Planes\", \"Ships\");\n$list[] = array(\"Car's2\", \"Planes2\", \"Ships2\");\n//define headers for CSV \nheader('Content-Type: text/csv; charset=utf-8');\nheader('Content-Disposition: attachment; filename=file_name.csv');\n//write data into CSV\n$fp = fopen('php://output', 'wb');\n//convert data to UTF-8 \nfprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));\nforeach ($list as $line) {\n fputcsv($fp, $line);\n}\nfclose($fp);\n"
},
{
"answer_id": 71347178,
"author": "manoj tiwari",
"author_id": 5060753,
"author_profile": "https://Stackoverflow.com/users/5060753",
"pm_score": 0,
"selected": false,
"text": " $fileName = '/tmp/notificationresponselogs_' . date('d-m-Y-g-i-h') . '.csv';\n $f = fopen($fileName, 'w'); \n fputs( $f, \"\\xEF\\xBB\\xBF\" ); //for utf8 support in csv\n\n\n\n $csv_fields=array();\n $csv_fields[] = 'heading1';\n $csv_fields[] = 'heading2';\n $csv_fields[] = 'heading3';\n $csv_fields[] = 'heading4';\n $csv_fields[] = 'heading5';\n $csv_fields[] = 'heading6';\n $csv_fields[] = 'heading7';\n $csv_fields[] = 'heading8';\n fputcsv($f, $csv_fields);\n\n \n$notification_log_arr = $notificationObj->getNotificationResponseForExport($params); //result from database\n\n if (count($notification_log_arr) > 0) {\n $serialNumber=1;\n foreach ($notification_log_arr AS $notifaction) {\n \n\n $fields = array();\n $fields['serialNumber']= $serialNumber ;\n $fields['fld_1']= $notifaction['fld_1'] ;\n $fields['fld_2']= $notifaction['fld_2'] ;\n $fields['fld_3']= $notifaction['fld_3'] ;\n $fields['fld_4']= $notifaction['fld_4'] ;\n $fields['fld_5']= $notifaction['fld_5'] ;\n $fields['fld_6']= $notifaction['fld_6'] ; \n $fields['fld_7']= $notifaction['fld_7'] ; \n // print_r($fields); die;\n fputcsv($f, $fields,\",\");\n \n $serialNumber++; }\n fclose($f);\n if (file_exists($fileName)) {\n \n header(\"Content-type: application/csv\");\n header(\"Content-Disposition: attachment; filename=\".\"exportlog\".date(\"Y-m-d_H:i\").\".csv\");\n header(\"Content-length: \" . filesize($fileName));\n header(\"Pragma: no-cache\"); \n header(\"Expires: 0\");\n readfile($fileName);\n unlink($fileName);\n exit;\n }\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,463
|
<p>After reading <a href="https://stackoverflow.com/questions/36127/any-recommended-vc-settings-for-better-pdb-analysis-on-release-builds">this discussion</a> and <a href="https://stackoverflow.com/questions/49224/good-crash-reporting-library-in-c">this discussion</a> about using CrashRpt to generate a crash dump and email it to the developers, I've been having a difficult time finding any instructions/tutorials for configuring the email settings used by the library to send the email.</p>
<p>When you call the install() function to initialize CrashRpt, you specify the email address you want the crash dump sent to, but how does the CrashPrt library know how to send the email to that address? Wouldn't the library have to know the email client settings for each individual user?</p>
<p>When a fatal crash occurs in my code, the CrashRpt dialog box pops up and when I enter my email address and click the send button, it takes me to a "Save File" dialog box where I can save the zipped package and the account specified in the Install() function never receives an email.</p>
<p>Thanks in advance for any and all help! I'm clearly missing something.</p>
|
[
{
"answer_id": 217474,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": true,
"text": " mainDlg.m_pUDFiles = &m_files;\n if (IDOK == mainDlg.DoModal())\n {\n //Put breakpoint here <---------\n if (m_sTo.IsEmpty() || \n !MailReport(rpt, sTempFileName, mainDlg.m_sEmail, mainDlg.m_sDescription))\n {\n SaveReport(rpt, sTempFileName);\n }\n }\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191808/"
] |
217,464
|
<p>I have a text file of this format: </p>
<pre><code>L O A D C A S E 1 O F 2 ...
J O I N T D I S P L A C E M E N T S (global)
Joint X-dsp Y-dsp Z-dsp X-rot Y-rot Z-rot
1 0.0 0.0 0.0 0.0 0.0 -0.001712
2 0.000646 -0.021756 0.0 0.0 0.0 -0.001339
3 0.003562 -0.038487 0.0 0.0 0.0 -0.000727
4 0.006478 -0.041661 0.0 0.0 0.0 0.000104
5 0.009536 -0.036266 0.0 0.0 0.0 0.000720
6 0.012595 -0.022824 0.0 0.0 0.0 0.001326
7 0.014724 0.0 0.0 0.0 0.0 0.001948
8 0.010000 -0.018686 0.0 0.0 0.0 -0.001117
9 0.009354 -0.036887 0.0 0.0 0.0 -0.000829
10 0.005767 -0.041661 0.0 0.0 0.0 0.000060
11 0.002180 -0.035866 0.0 0.0 0.0 0.000798
12 0.000051 -0.020695 0.0 0.0 0.0 0.001210
M E M B E R E N D F O R C E S (local)
Member Joint Nx Vy Vz Txx Myy Mzz
1 1 -16.138t 0.002 0.0 0.0 0.0 0.011
1 2 16.138t -0.002 0.0 0.0 0.0 0.017
2 2 -72.907t 0.003 0.0 0.0 0.0 0.013
2 3 72.907t -0.003 0.0 0.0 0.0 0.023
3 3 -72.909t -0.000 0.0 0.0 0.0 -0.009
3 4 72.909t 0.000 0.0 0.0 0.0 0.005
4 4 -76.455t -0.000 0.0 0.0 0.0 -0.007
4 5 76.455t 0.000 0.0 0.0 0.0 0.003
5 5 -76.453t -0.001 0.0 0.0 0.0 -0.010
5 6 76.453t 0.001 0.0 0.0 0.0 0.000
6 6 -53.226t -0.002 0.0 0.0 0.0 -0.018
6 7 53.226t 0.002 0.0 0.0 0.0 -0.008
7 1 108.570c -0.001 0.0 0.0 0.0 -0.011
7 8 -108.570c 0.001 0.0 0.0 0.0 -0.004
8 2 -76.765t -0.004 0.0 0.0 0.0 -0.024
8 8 76.765t 0.004 0.0 0.0 0.0 -0.021
9 2 80.278c -0.000 0.0 0.0 0.0 -0.006
9 9 -80.278c 0.000 0.0 0.0 0.0 -0.000
10 3 -39.997t -0.002 0.0 0.0 0.0 -0.014
10 9 39.997t 0.002 0.0 0.0 0.0 -0.016
11 4 -23.720t -0.000 0.0 0.0 0.0 0.004
11 9 23.720t 0.000 0.0 0.0 0.0 -0.007
12 4 -0.001t 0.000 0.0 0.0 0.0 0.002
12 10 0.001t -0.000 0.0 0.0 0.0 0.001
13 4 -18.706t 0.000 0.0 0.0 0.0 -0.003
13 11 18.706t -0.000 0.0 0.0 0.0 0.005
14 5 -10.000t 0.001 0.0 0.0 0.0 0.007
14 11 10.000t -0.001 0.0 0.0 0.0 0.008
15 6 32.845c 0.000 0.0 0.0 0.0 0.006
15 11 -32.845c -0.000 0.0 0.0 0.0 -0.000
16 6 -53.223t 0.002 0.0 0.0 0.0 0.012
16 12 53.223t -0.002 0.0 0.0 0.0 0.010
17 7 75.273c 0.000 0.0 0.0 0.0 0.008
17 12 -75.273c -0.000 0.0 0.0 0.0 -0.001
18 8 16.142c 0.005 0.0 0.0 0.0 0.025
18 9 -16.142c -0.005 0.0 0.0 0.0 0.030
19 9 89.682c 0.000 0.0 0.0 0.0 -0.007
19 10 -89.682c -0.000 0.0 0.0 0.0 0.008
20 10 89.682c -0.000 0.0 0.0 0.0 -0.009
20 11 -89.682c 0.000 0.0 0.0 0.0 0.003
21 11 53.228c -0.002 0.0 0.0 0.0 -0.016
21 12 -53.228c 0.002 0.0 0.0 0.0 -0.010
</code></pre>
<p>Is there any C# library that can be used to parse the information of this format?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 217479,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": true,
"text": "public static IEnumerable<string> ReadLinesFromFile(string filename)\n{\n using (StreamReader reader = new StreamReader(filename))\n {\n while (true)\n {\n string s = reader.ReadLine();\n if (s == null)\n break;\n yield return s;\n }\n }\n}\n var jointDisplacements = from line in ReadLinesFromFile(@\"c:\\import.txt\")\n let item = line.Split(new char[] { '\\t' })\n select new\n {\n Joint = Convert.ToInt32(item[0]),\n X-dsp = Convert.ToDouble(item[1]),\n Y-dsp = Convert.ToDouble(item[2]),\n Z-dsp = Convert.ToDouble(item[3]),\n X-rot = Convert.ToDouble(item[4]),\n Y-rot = Convert.ToDouble(item[5]),\n Z-rot = Convert.ToDouble(item[6])\n };\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
217,484
|
<p>I have developed a VB.NET WCF service that recives and sends back data. When the first client connects it starts the data output that continues also if the client is closed. If a new client connects then a new object is created and the data output starts at the begninning and continues in parallel with the old instance. Is there a way to read the same service object from multiple clients?</p>
<p>The service is self-hosted.</p>
<p><strong>UPDATE:</strong> I solved the problem adding the following bit of code to the service class:</p>
<pre><code><ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Multiple,
InstanceContextMode:=InstanceContextMode.Single)>
...
</code></pre>
<p>To use the ServiceHost overload that takes in the SingletonInstance, the service must be tagged with the appropriate ServiceBehaviours.</p>
|
[
{
"answer_id": 217479,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": true,
"text": "public static IEnumerable<string> ReadLinesFromFile(string filename)\n{\n using (StreamReader reader = new StreamReader(filename))\n {\n while (true)\n {\n string s = reader.ReadLine();\n if (s == null)\n break;\n yield return s;\n }\n }\n}\n var jointDisplacements = from line in ReadLinesFromFile(@\"c:\\import.txt\")\n let item = line.Split(new char[] { '\\t' })\n select new\n {\n Joint = Convert.ToInt32(item[0]),\n X-dsp = Convert.ToDouble(item[1]),\n Y-dsp = Convert.ToDouble(item[2]),\n Z-dsp = Convert.ToDouble(item[3]),\n X-rot = Convert.ToDouble(item[4]),\n Y-rot = Convert.ToDouble(item[5]),\n Z-rot = Convert.ToDouble(item[6])\n };\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26754/"
] |
217,523
|
<p>We are considering a move from SVN to Mercurial, and have encountered a stumbling block.</p>
<p>We currently use <code>svn:externals</code> to automatically pull a common set of libraries into the working directory. I can't find support for anything like this in Mercurial.</p>
<p>Is there a way to do this automatically with Mercurial, or do I need to fake it as part of my build process?</p>
|
[
{
"answer_id": 851714,
"author": "yanjost",
"author_id": 16718,
"author_profile": "https://Stackoverflow.com/users/16718",
"pm_score": 2,
"selected": false,
"text": "svn:externals"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/584/"
] |
217,532
|
<p>I'm trying to call the OpenThemeData (see msdn <a href="http://msdn.microsoft.com/en-us/library/bb759821%28v=VS.85%29.aspx" rel="noreferrer">OpenThemeData</a>) function but I couldn't determine what are the acceptable Class names to be passed in by the <code>pszClassList</code> parameter.</p>
<pre><code>HTHEME OpenThemeData(
HWND hwnd,
LPCWSTR pszClassList
);
</code></pre>
<p>Could anybody tell me what are the acceptable class names that I can pass into that parameter?
Thanks!</p>
|
[
{
"answer_id": 6539701,
"author": "splash",
"author_id": 256544,
"author_profile": "https://Stackoverflow.com/users/256544",
"pm_score": 4,
"selected": false,
"text": "Vsstyle.h Vssym32.h BUTTON, CLOCK, COMBOBOX, COMMUNICATIONS, CONTROLPANEL, DATEPICKER, DRAGDROP, \nEDIT, EXPLORERBAR, FLYOUT, GLOBALS, HEADER, LISTBOX, LISTVIEW, MENU, MENUBAND, \nNAVIGATION, PAGE, PROGRESS, REBAR, SCROLLBAR, SEARCHEDITBOX, SPIN, STARTPANEL, \nSTATUS, TAB, TASKBAND, TASKBAR, TASKDIALOG, TEXTSTYLE, TOOLBAR, TOOLTIP, \nTRACKBAR, TRAYNOTIFY, TREEVIEW, WINDOW\n"
},
{
"answer_id": 53415254,
"author": "Elmue",
"author_id": 1487529,
"author_profile": "https://Stackoverflow.com/users/1487529",
"pm_score": 3,
"selected": false,
"text": "C:\\Windows\\Resources\\Themes\\Aero NULL OpenThemeDataForDpi() OpenThemeData()"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28760/"
] |
217,549
|
<p>It is common knowledge that built-in enums in C++ are not typesafe.
I was wondering which classes implementing typesafe enums are used out there...
I myself use the following "bicycle", but it is somewhat verbose and limited:</p>
<p>typesafeenum.h:</p>
<pre><code>struct TypesafeEnum
{
// Construction:
public:
TypesafeEnum(): id (next_id++), name("") {}
TypesafeEnum(const std::string& n): id(next_id++), name(n) {}
// Operations:
public:
bool operator == (const TypesafeEnum& right) const;
bool operator != (const TypesafeEnum& right) const;
bool operator < (const TypesafeEnum& right) const;
std::string to_string() const { return name; }
// Implementation:
private:
static int next_id;
int id;
std::string name;
};
</code></pre>
<p>typesafeenum.cpp:</p>
<pre><code>int TypesafeEnum::next_id = 1;
bool TypesafeEnum::operator== (const TypesafeEnum& right) const
{ return id == right.id; }
bool TypesafeEnum::operator!= (const TypesafeEnum& right) const
{ return !operator== (right); }
bool TypesafeEnum::operator< (const TypesafeEnum& right) const
{ return id < right.id; }
</code></pre>
<p>Usage:</p>
<pre><code>class Dialog
{
...
struct Result: public TypesafeEnum
{
static const Result CANCEL("Cancel");
static const Result OK("Ok");
};
Result doModal();
...
};
const Dialog::Result Dialog::Result::OK;
const Dialog::Result Dialog::Result::CANCEL;
</code></pre>
<p><strong>Addition:</strong>
I think I should have been more specific about the requirements. I'll try to summarize them:</p>
<p>Priority 1: Setting an enum variable to an invalid value should be impossible (a compile-time error) with no exceptions.</p>
<p>Priority 2: Converting an enum value to/from an int should be possible with a single explicit function/method call.</p>
<p>Priority 3: As compact, elegant and convenient declaration and usage as possible</p>
<p>Priority 4: Converting enum values to and from strings.</p>
<p>Priority 5: (Nice to have) Possibility to iterate over enum values.</p>
|
[
{
"answer_id": 217560,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "enum public enum Result {\n OK(\"OK\"), CANCEL(\"Cancel\");\n\n private final String name;\n\n Result(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n}\n OK CANCEL Result Result EnumSet Set"
},
{
"answer_id": 217562,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 4,
"selected": false,
"text": "struct Flintstones {\n enum E {\n Fred,\n Barney,\n Wilma\n };\n};\n\nFlintstones::E fred = Flintstones::Fred;\nFlintstones::E barney = Flintstones::Barney;\n"
},
{
"answer_id": 439004,
"author": "Josh Kelley",
"author_id": 25507,
"author_profile": "https://Stackoverflow.com/users/25507",
"pm_score": 6,
"selected": true,
"text": "enum_rev4.6.zip BOOST_ENUM_VALUES(Level, const char*,\n (Abort)(\"unrecoverable problem\")\n (Error)(\"recoverable problem\")\n (Alert)(\"unexpected behavior\")\n (Info) (\"expected behavior\")\n (Trace)(\"normal flow of execution\")\n (Debug)(\"detailed object state listings\")\n)\n class Level : public boost::detail::enum_base<Level, string>\n{\npublic:\n enum domain\n {\n Abort,\n Error,\n Alert,\n Info,\n Trace,\n Debug,\n };\n\n BOOST_STATIC_CONSTANT(index_type, size = 6);\n\n Level() {}\n Level(domain index) : boost::detail::enum_base<Level, string>(index) {}\n\n typedef boost::optional<Level> optional;\n static optional get_by_name(const char* str)\n {\n if(strcmp(str, \"Abort\") == 0) return optional(Abort);\n if(strcmp(str, \"Error\") == 0) return optional(Error);\n if(strcmp(str, \"Alert\") == 0) return optional(Alert);\n if(strcmp(str, \"Info\") == 0) return optional(Info);\n if(strcmp(str, \"Trace\") == 0) return optional(Trace);\n if(strcmp(str, \"Debug\") == 0) return optional(Debug);\n return optional();\n }\n\nprivate:\n friend class boost::detail::enum_base<Level, string>;\n static const char* names(domain index)\n {\n switch(index)\n {\n case Abort: return \"Abort\";\n case Error: return \"Error\";\n case Alert: return \"Alert\";\n case Info: return \"Info\";\n case Trace: return \"Trace\";\n case Debug: return \"Debug\";\n default: return NULL;\n }\n }\n\n typedef boost::optional<value_type> optional_value;\n static optional_value values(domain index)\n {\n switch(index)\n {\n case Abort: return optional_value(\"unrecoverable problem\");\n case Error: return optional_value(\"recoverable problem\");\n case Alert: return optional_value(\"unexpected behavior\");\n case Info: return optional_value(\"expected behavior\");\n case Trace: return optional_value(\"normal flow of execution\");\n case Debug: return optional_value(\"detailed object state listings\");\n default: return optional_value();\n }\n }\n};\n"
},
{
"answer_id": 439057,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 4,
"selected": false,
"text": "enum class Result { Ok, Cancel};\n"
},
{
"answer_id": 11856721,
"author": "Luis Machuca",
"author_id": 399580,
"author_profile": "https://Stackoverflow.com/users/399580",
"pm_score": 2,
"selected": false,
"text": "begin end enum // This doesn't compile, and if it did it wouldn't work anyway\nenum colors { salmon, .... };\nenum fishes { salmon, .... };\n\n// This, however, works seamlessly.\nstruct colors_def { enum type { salmon, .... }; };\nstruct fishes_def { enum type { salmon, .... }; };\n\ntypedef typesafe_enum<colors_def> colors;\ntypedef typesafe_enum<fishes_def> fishes;\n enum enum int if (colors::salmon == fishes::salmon) { .../* Ooops! */... }\n enum // I'm using backports of C++11 utilities like static_assert and enable_if\ntemplate <typename Enum1, typename Enum2>\ntypename enable_if< (is_enum<Enum1>::value && is_enum<Enum2>::value) && (false == is_same<Enum1,Enum2>::value) , bool >\n::type operator== (Enum1, Enum2) {\n static_assert (false, \"Comparing enumerations of different types!\");\n}\n enum enum class enum"
},
{
"answer_id": 39904524,
"author": "Michael Fox",
"author_id": 914859,
"author_profile": "https://Stackoverflow.com/users/914859",
"pm_score": 0,
"selected": false,
"text": "boost::variant #include <iostream>\n#include <boost/variant.hpp>\n\nstruct A_t {};\nstatic const A_t A = A_t();\ntemplate <typename T>\nbool isA(const T & x) { if(boost::get<A_t>(&x)) return true; return false; }\n\nstruct B_t {};\nstatic const B_t B = B_t();\ntemplate <typename T>\nbool isB(const T & x) { if(boost::get<B_t>(&x)) return true; return false; }\n\nstruct C_t {};\nstatic const C_t C = C_t();\ntemplate <typename T>\nbool isC(const T & x) { if(boost::get<C_t>(&x)) return true; return false; }\n\ntypedef boost::variant<A_t, B_t> AB;\ntypedef boost::variant<B_t, C_t> BC;\n\nvoid ab(const AB & e)\n{\n if(isA(e))\n std::cerr << \"A!\" << std::endl;\n if(isB(e))\n std::cerr << \"B!\" << std::endl;\n // ERROR:\n // if(isC(e))\n // std::cerr << \"C!\" << std::endl;\n\n // ERROR:\n // if(e == 0)\n // std::cerr << \"B!\" << std::endl;\n}\n\nvoid bc(const BC & e)\n{\n // ERROR:\n // if(isA(e))\n // std::cerr << \"A!\" << std::endl;\n\n if(isB(e))\n std::cerr << \"B!\" << std::endl;\n if(isC(e))\n std::cerr << \"C!\" << std::endl;\n}\n\nint main() {\n AB a;\n a = A;\n AB b;\n b = B;\n ab(a);\n ab(b);\n ab(A);\n ab(B);\n // ab(C); // ERROR\n // bc(A); // ERROR\n bc(B);\n bc(C);\n}\n boost::variant<int, A_t, B_t, boost::none> #ifndef _TYPESAFE_ENUMS_H\n#define _TYPESAFE_ENUMS_H\n#include <string>\n#include <boost/variant.hpp>\n\n#define ITEM(NAME, VAL) \\\nstruct NAME##_t { \\\n std::string toStr() const { return std::string( #NAME ); } \\\n int toInt() const { return VAL; } \\\n}; \\\nstatic const NAME##_t NAME = NAME##_t(); \\\ntemplate <typename T> \\\nbool is##NAME(const T & x) { if(boost::get<NAME##_t>(&x)) return true; return false; } \\\n\n\nclass toStr_visitor: public boost::static_visitor<std::string> {\npublic:\n template<typename T>\n std::string operator()(const T & a) const {\n return a.toStr();\n }\n};\n\ntemplate<BOOST_VARIANT_ENUM_PARAMS(typename T)>\ninline static\nstd::string toStr(const boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> & a) {\n return boost::apply_visitor(toStr_visitor(), a);\n}\n\nclass toInt_visitor: public boost::static_visitor<int> {\npublic:\n template<typename T>\n int operator()(const T & a) const {\n return a.toInt();\n }\n};\n\ntemplate<BOOST_VARIANT_ENUM_PARAMS(typename T)>\ninline static\nint toInt(const boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> & a) {\n return boost::apply_visitor(toInt_visitor(), a);\n}\n\n#define ENUM(...) \\\ntypedef boost::variant<__VA_ARGS__>\n#endif\n ITEM(A, 0);\nITEM(B, 1);\nITEM(C, 2);\n\nENUM(A_t, B_t) AB;\nENUM(B_t, C_t) BC;\n A_t A ENUM toStr toInt"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22046/"
] |
217,551
|
<p>My component is handed a long value that I later use as a key into a cache. The key itself is a string representation of the long value as if it were unsigned 64-bit value. That is, when my component is handed -2944827264075010823L, I need to convert that into the string key "15501916809634540793".</p>
<p>I have a solution, but it seems brute force and it makes me a bit queasy. Essentially, I convert the long into a hexadecimal string representation (so -2944827264075010823L becomes "d721df34a7ec6cf9") and convert the hexadecimal string into a BigInteger:</p>
<pre><code>String longValueAsHexString = convertLongToHexString(longValue);
BigInteger bi = new BigInteger(longValueAsHexString, 16);
String longValueString = bi.toString();
</code></pre>
<p>I then use longValueString as the key into the cache.</p>
<p>I cannot use Long.toString(longValue,16), because it returns the hex string for the absolute value, prefixed by a "-".</p>
<p>So my convertLongToHexString looks like this:</p>
<pre><code>long mask = 0x00000000ffffffffL;
long bottomHalf = number & mask;
long upperHalf = (number >> 32) & mask;
String bottomHalfString = Long.toString(bottomHalf, 16);
if (bottomHalfString.length() != 8) {
String zeroes = "0000000000000000";
bottomHalfString = zeroes.substring(16-bottomHalfString.length()) + bottomHalfString;
}
return Long.toString(upperHalf,16)+bottomHalfString;
</code></pre>
<p>There must be a more elegant way of doing this. Any suggestions?</p>
|
[
{
"answer_id": 217582,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "long import java.math.BigInteger;\n\nclass UInt64Test {\n public static void main(String[] args) {\n for (String arg : args)\n System.out.println(toUnsignedString(Long.parseLong(arg)));\n }\n\n private static final BigInteger B64 = BigInteger.ZERO.setBit(64);\n public static String toUnsignedString(long num) {\n if (num >= 0)\n return String.valueOf(num);\n return BigInteger.valueOf(num).add(B64).toString();\n }\n}\n"
},
{
"answer_id": 217632,
"author": "Joshua Swink",
"author_id": 14732,
"author_profile": "https://Stackoverflow.com/users/14732",
"pm_score": 2,
"selected": false,
"text": "public static String longUnsignedString(long l) {\n byte[] bytes = new byte[9];\n\n for (int i = 1; i < 9; i++) {\n bytes[i] = (byte) ((l >> ((8 - i) * 8)) & 255);\n }\n\n return (new BigInteger(bytes)).toString();\n}\n"
},
{
"answer_id": 7417283,
"author": "Alexander Ashitkin",
"author_id": 598055,
"author_profile": "https://Stackoverflow.com/users/598055",
"pm_score": 1,
"selected": false,
"text": " byte[] bytes = ByteBuffer.allocate(8).putLong(1023L).array();\n System.out.println(new BigInteger(bytes).toString(2));\n"
},
{
"answer_id": 16819015,
"author": "Nayuki",
"author_id": 839689,
"author_profile": "https://Stackoverflow.com/users/839689",
"pm_score": 2,
"selected": false,
"text": "BigInteger public static String unsignedToString(long n) {\n long temp = (n >>> 1) / 5; // Unsigned divide by 10 and floor\n if (temp == 0)\n return Integer.toString((int)n); // Single digit\n else\n return Long.toString(temp) + (n - temp * 10); // Multiple digits\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,555
|
<p>How fast is <a href="http://php.net/manual/en/function.php-uname.php" rel="nofollow noreferrer">php_uname()</a> say doing <code>php_uname('s n')</code> or <code>php_uname('a')</code>. The reason I ask is because I'd like to use it to determine which server I'm on and therefore the configuration (paths, etc).</p>
<p>This is related to <a href="https://stackoverflow.com/questions/211885/is-there-a-php-function-or-variable-giving-the-local-host-name">Is there a PHP function or variable giving the local host name?</a></p>
|
[
{
"answer_id": 217570,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": true,
"text": "<?php\n $tstart = microtime(true);\n\n php_uname('a');\n\n print 'it took '. sprintf(\"%f\",microtime(true) - $tstart) .\" seconds\\n\";\n?>\n it took 0.000016 seconds\n"
},
{
"answer_id": 229195,
"author": "Steve",
"author_id": 21559,
"author_profile": "https://Stackoverflow.com/users/21559",
"pm_score": 0,
"selected": false,
"text": "$_SERVER['HTTP_HOST']\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
217,565
|
<p>By deterministic I vaguely mean that can be used in critical real-time software like aerospace flight software. Garbage collectors (and dynamic memory allocation for that matter) are big no-no's in flight software because they are considered non-deterministic. However, I know there's ongoing research on this, so I wonder if this problem has been solved yet.</p>
<p>I'm also including in the question any garbage collection algorithms that put restrictions on how they're used.</p>
|
[
{
"answer_id": 293664,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": false,
"text": "struct Block {\n Block *next;\n}\n\nBlock *free_list = NULL; /* you will need to populate this at start, an \n * easy way is to just call free on each block you \n * want to add */\n\nvoid release(void *p) {\n if(p != NULL) {\n struct Block *b_ptr = (struct Block *)p;\n b_ptr->next = free_list;\n free_list = b_ptr;\n }\n}\n\nvoid *acquire() {\n void *ret = (void *)free_list;\n if(free_list != NULL) {\n free_list = free_list->next;\n }\n return ret;\n}\n\n/* call this before you use acquire/free */\nvoid init() {\n /* example of an allocator supporting 100 blocks each 32-bytes big */\n static const int blocks = 100;\n static const int size = 32;\n static unsigned char mem[blocks * size];\n int i;\n for(i = 0; i < blocks; ++i) {\n free(&mem[i * size]);\n }\n}\n"
},
{
"answer_id": 621694,
"author": "doppelfish",
"author_id": 235914,
"author_profile": "https://Stackoverflow.com/users/235914",
"pm_score": 1,
"selected": false,
"text": "// assume that on `Link` object needs k bytes:\nclass Link {\n Link next = null;\n /* further fields */\n static Link head = null;\n}\n\npublic static void main (String args) {\n // assume we have N bytes free now\n // set n := floor (N/k), assume that n > 1\n\n for (int i = 0; i < n; i ++) {\n Link tmp = new Link ();\n tmp.next = Link.head;\n Link.head = tmp;\n } \n // (1)\n Link.head = Link.head.next; // (2)\n Link tmp = new Link (); // (3)\n}\n Link Link Link.static Link head"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,578
|
<p>I'm trying to create a <em>fast</em> 2D point inside polygon algorithm, for use in hit-testing (e.g. <code>Polygon.contains(p:Point)</code>). Suggestions for effective techniques would be appreciated.</p>
|
[
{
"answer_id": 218081,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 11,
"selected": true,
"text": "(9/1), (4/3), (2/7), (8/2), (3/6) // p is your point, p.x is the x coord, p.y is the y coord\nif (p.x < Xmin || p.x > Xmax || p.y < Ymin || p.y > Ymax) {\n // Definitely not within the polygon!\n}\n (Xmin - e/p.y) e e e side 1: (X1/Y1)-(X2/Y2)\nside 2: (X2/Y2)-(X3/Y3)\nside 3: (X3/Y3)-(X4/Y4)\n:\n // Test the ray against all sides\nint intersections = 0;\nfor (side = 0; side < numberOfSides; side++) {\n // Test if current side intersects with ray.\n // If yes, intersections++;\n}\nif ((intersections & 1) == 1) {\n // Inside of polygon\n} else {\n // Outside of polygon\n}\n #define NO 0\n#define YES 1\n#define COLLINEAR 2\n\nint areIntersecting(\n float v1x1, float v1y1, float v1x2, float v1y2,\n float v2x1, float v2y1, float v2x2, float v2y2\n) {\n float d1, d2;\n float a1, a2, b1, b2, c1, c2;\n\n // Convert vector 1 to a line (line 1) of infinite length.\n // We want the line in linear equation standard form: A*x + B*y + C = 0\n // See: http://en.wikipedia.org/wiki/Linear_equation\n a1 = v1y2 - v1y1;\n b1 = v1x1 - v1x2;\n c1 = (v1x2 * v1y1) - (v1x1 * v1y2);\n\n // Every point (x,y), that solves the equation above, is on the line,\n // every point that does not solve it, is not. The equation will have a\n // positive result if it is on one side of the line and a negative one \n // if is on the other side of it. We insert (x1,y1) and (x2,y2) of vector\n // 2 into the equation above.\n d1 = (a1 * v2x1) + (b1 * v2y1) + c1;\n d2 = (a1 * v2x2) + (b1 * v2y2) + c1;\n\n // If d1 and d2 both have the same sign, they are both on the same side\n // of our line 1 and in that case no intersection is possible. Careful, \n // 0 is a special case, that's why we don't test \">=\" and \"<=\", \n // but \"<\" and \">\".\n if (d1 > 0 && d2 > 0) return NO;\n if (d1 < 0 && d2 < 0) return NO;\n\n // The fact that vector 2 intersected the infinite line 1 above doesn't \n // mean it also intersects the vector 1. Vector 1 is only a subset of that\n // infinite line 1, so it may have intersected that line before the vector\n // started or after it ended. To know for sure, we have to repeat the\n // the same test the other way round. We start by calculating the \n // infinite line 2 in linear equation standard form.\n a2 = v2y2 - v2y1;\n b2 = v2x1 - v2x2;\n c2 = (v2x2 * v2y1) - (v2x1 * v2y2);\n\n // Calculate d1 and d2 again, this time using points of vector 1.\n d1 = (a2 * v1x1) + (b2 * v1y1) + c2;\n d2 = (a2 * v1x2) + (b2 * v1y2) + c2;\n\n // Again, if both have the same sign (and neither one is 0),\n // no intersection is possible.\n if (d1 > 0 && d2 > 0) return NO;\n if (d1 < 0 && d2 < 0) return NO;\n\n // If we get here, only two possibilities are left. Either the two\n // vectors intersect in exactly one point or they are collinear, which\n // means they intersect in any number of points from zero to infinite.\n if ((a1 * b2) - (a2 * b1) == 0.0f) return COLLINEAR;\n\n // If they are not collinear, they must intersect in exactly one point.\n return YES;\n}\n v1x1/v1y1 v1x2/v1y2 v2x1/v2y1 v2x2/v2y2 YES NO YES NO == 0.0f < epsilon"
},
{
"answer_id": 1972918,
"author": "Gavin",
"author_id": 78216,
"author_profile": "https://Stackoverflow.com/users/78216",
"pm_score": 5,
"selected": false,
"text": " number of edges per polygon\n 3 4 10 100 1000\nMacMartin 2.9 3.2 5.9 50.6 485\nCrossings 3.1 3.4 6.8 60.0 624\nTriangle Fan+edge sort 1.1 1.8 6.5 77.6 787\nTriangle Fan 1.2 2.1 7.3 85.4 865\nBarycentric 2.1 3.8 13.8 160.7 1665\nAngle Summation 56.2 70.4 153.6 1403.8 14693\n\nGrid (100x100) 1.5 1.5 1.6 2.1 9.8\nGrid (20x20) 1.7 1.7 1.9 5.7 42.2\nBins (100) 1.8 1.9 2.7 15.1 117\nBins (20) 2.1 2.2 3.7 26.3 278\n"
},
{
"answer_id": 2922778,
"author": "nirg",
"author_id": 1258650,
"author_profile": "https://Stackoverflow.com/users/1258650",
"pm_score": 9,
"selected": false,
"text": "int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)\n{\n int i, j, c = 0;\n for (i = 0, j = nvert-1; i < nvert; j = i++) {\n if ( ((verty[i]>testy) != (verty[j]>testy)) &&\n (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )\n c = !c;\n }\n return c;\n}\n"
},
{
"answer_id": 6907077,
"author": "diatrevolo",
"author_id": 239318,
"author_profile": "https://Stackoverflow.com/users/239318",
"pm_score": 2,
"selected": false,
"text": "- (BOOL)shape:(NSBezierPath *)path containsPoint:(NSPoint)point\n{\n NSBezierPath *currentPath = [path bezierPathByFlatteningPath];\n BOOL result;\n float aggregateX = 0; //I use these to calculate the centroid of the shape\n float aggregateY = 0;\n NSPoint firstPoint[1];\n [currentPath elementAtIndex:0 associatedPoints:firstPoint];\n float olderX = firstPoint[0].x;\n float olderY = firstPoint[0].y;\n NSPoint interPoint;\n int noOfIntersections = 0;\n\n for (int n = 0; n < [currentPath elementCount]; n++) {\n NSPoint points[1];\n [currentPath elementAtIndex:n associatedPoints:points];\n aggregateX += points[0].x;\n aggregateY += points[0].y;\n }\n\n for (int n = 0; n < [currentPath elementCount]; n++) {\n NSPoint points[1];\n\n [currentPath elementAtIndex:n associatedPoints:points];\n //line equations in Ax + By = C form\n float _A_FOO = (aggregateY/[currentPath elementCount]) - point.y; \n float _B_FOO = point.x - (aggregateX/[currentPath elementCount]);\n float _C_FOO = (_A_FOO * point.x) + (_B_FOO * point.y);\n\n float _A_BAR = olderY - points[0].y;\n float _B_BAR = points[0].x - olderX;\n float _C_BAR = (_A_BAR * olderX) + (_B_BAR * olderY);\n\n float det = (_A_FOO * _B_BAR) - (_A_BAR * _B_FOO);\n if (det != 0) {\n //intersection points with the edges\n float xIntersectionPoint = ((_B_BAR * _C_FOO) - (_B_FOO * _C_BAR)) / det;\n float yIntersectionPoint = ((_A_FOO * _C_BAR) - (_A_BAR * _C_FOO)) / det;\n interPoint = NSMakePoint(xIntersectionPoint, yIntersectionPoint);\n if (olderX <= points[0].x) {\n //doesn't matter in which direction the ray goes, so I send it right-ward.\n if ((interPoint.x >= olderX && interPoint.x <= points[0].x) && (interPoint.x > point.x)) { \n noOfIntersections++;\n }\n } else {\n if ((interPoint.x >= points[0].x && interPoint.x <= olderX) && (interPoint.x > point.x)) {\n noOfIntersections++;\n } \n }\n }\n olderX = points[0].x;\n olderY = points[0].y;\n }\n if (noOfIntersections % 2 == 0) {\n result = FALSE;\n } else {\n result = TRUE;\n }\n return result;\n}\n"
},
{
"answer_id": 9796169,
"author": "Aladar",
"author_id": 1282103,
"author_profile": "https://Stackoverflow.com/users/1282103",
"pm_score": 2,
"selected": false,
"text": " static void Main(string[] args)\n {\n\n Console.Write(\"Hola\");\n List<double> vertx = new List<double>();\n List<double> verty = new List<double>();\n\n int i, j, c = 0;\n\n vertx.Add(1);\n vertx.Add(2);\n vertx.Add(1);\n vertx.Add(4);\n vertx.Add(4);\n vertx.Add(1);\n\n verty.Add(1);\n verty.Add(2);\n verty.Add(4);\n verty.Add(4);\n verty.Add(1);\n verty.Add(1);\n\n int nvert = 6; //Vértices del poligono\n\n double testx = 2;\n double testy = 5;\n\n\n for (i = 0, j = nvert - 1; i < nvert; j = i++)\n {\n if (((verty[i] > testy) != (verty[j] > testy)) &&\n (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]))\n c = 1;\n }\n }\n"
},
{
"answer_id": 13967176,
"author": "Uğur Gümüşhan",
"author_id": 964196,
"author_profile": "https://Stackoverflow.com/users/964196",
"pm_score": 2,
"selected": false,
"text": "public static bool IsPointInPolygon(IList<Point> polygon, Point testPoint) {\n bool result = false;\n int j = polygon.Count() - 1;\n for (int i = 0; i < polygon.Count(); i++) {\n if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y) {\n if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < testPoint.X) {\n result = !result;\n }\n }\n j = i;\n }\n return result;\n }\n"
},
{
"answer_id": 15914133,
"author": "Jon",
"author_id": 1510181,
"author_profile": "https://Stackoverflow.com/users/1510181",
"pm_score": 2,
"selected": false,
"text": "- (BOOL)isPointInPolygon:(NSArray *)vertices point:(CGPoint)test {\n NSUInteger nvert = [vertices count];\n NSInteger i, j, c = 0;\n CGPoint verti, vertj;\n\n for (i = 0, j = nvert-1; i < nvert; j = i++) {\n verti = [(NSValue *)[vertices objectAtIndex:i] CGPointValue];\n vertj = [(NSValue *)[vertices objectAtIndex:j] CGPointValue];\n if (( (verti.y > test.y) != (vertj.y > test.y) ) &&\n ( test.x < ( vertj.x - verti.x ) * ( test.y - verti.y ) / ( vertj.y - verti.y ) + verti.x) )\n c = !c;\n }\n\n return (c ? YES : NO);\n}\n\n- (void)testPoint {\n\n NSArray *polygonVertices = [NSArray arrayWithObjects:\n [NSValue valueWithCGPoint:CGPointMake(13.5, 41.5)],\n [NSValue valueWithCGPoint:CGPointMake(42.5, 56.5)],\n [NSValue valueWithCGPoint:CGPointMake(39.5, 69.5)],\n [NSValue valueWithCGPoint:CGPointMake(42.5, 84.5)],\n [NSValue valueWithCGPoint:CGPointMake(13.5, 100.0)],\n [NSValue valueWithCGPoint:CGPointMake(6.0, 70.5)],\n nil\n ];\n\n CGPoint tappedPoint = CGPointMake(23.0, 70.0);\n\n if ([self isPointInPolygon:polygonVertices point:tappedPoint]) {\n NSLog(@\"YES\");\n } else {\n NSLog(@\"NO\");\n }\n}\n"
},
{
"answer_id": 16261774,
"author": "jdavid_1385",
"author_id": 1322628,
"author_profile": "https://Stackoverflow.com/users/1322628",
"pm_score": 2,
"selected": false,
"text": "exor(A,B):- \\+A,B;A,\\+B.\nin_range(Coordinate,CA,CB) :- exor((CA>Coordinate),(CB>Coordinate)).\n\ninside(false).\ninside(_,[_|[]]).\ninside(X:Y, [X1:Y1,X2:Y2|R]) :- in_range(Y,Y1,Y2), X > ( ((X2-X1)*(Y-Y1))/(Y2-Y1) + X1),toggle_ray, inside(X:Y, [X2:Y2|R]); inside(X:Y, [X2:Y2|R]).\n\nget_line(_,_,[]).\nget_line([XA:YA,XB:YB],[X1:Y1,X2:Y2|R]):- [XA:YA,XB:YB]=[X1:Y1,X2:Y2]; get_line([XA:YA,XB:YB],[X2:Y2|R]).\n (YB-YA)\n Y - YA = ------- * (X - XA) \n (XB-YB) \n (XB-XA)\n X < ------- * (Y - YA) + XA\n (YB-YA) \n is_left_half_plane(_,[],[],_).\nis_left_half_plane(X:Y,[XA:YA,XB:YB], [[X1:Y1,X2:Y2]|R], Test) :- [XA:YA, XB:YB] = [X1:Y1, X2:Y2], call(Test, X , (((XB - XA) * (Y - YA)) / (YB - YA) + XA)); \n is_left_half_plane(X:Y, [XA:YA, XB:YB], R, Test).\n\nin_y_range_at_poly(Y,[XA:YA,XB:YB],Polygon) :- get_line([XA:YA,XB:YB],Polygon), in_range(Y,YA,YB).\nall_in_range(Coordinate,Polygon,Lines) :- aggregate(bag(Line), in_y_range_at_poly(Coordinate,Line,Polygon), Lines).\n\ntraverses_ray(X:Y, Lines, Count) :- aggregate(bag(Line), is_left_half_plane(X:Y, Line, Lines, <), IntersectingLines), length(IntersectingLines, Count).\n\n% This is the entry point predicate\ninside_poly(X:Y,Polygon,Answer) :- all_in_range(Y,Polygon,Lines), traverses_ray(X:Y, Lines, Count), (1 is mod(Count,2)->Answer=inside;Answer=outside).\n"
},
{
"answer_id": 16391873,
"author": "M Katz",
"author_id": 384670,
"author_profile": "https://Stackoverflow.com/users/384670",
"pm_score": 7,
"selected": false,
"text": "public bool IsPointInPolygon( Point p, Point[] polygon )\n{\n double minX = polygon[ 0 ].X;\n double maxX = polygon[ 0 ].X;\n double minY = polygon[ 0 ].Y;\n double maxY = polygon[ 0 ].Y;\n for ( int i = 1 ; i < polygon.Length ; i++ )\n {\n Point q = polygon[ i ];\n minX = Math.Min( q.X, minX );\n maxX = Math.Max( q.X, maxX );\n minY = Math.Min( q.Y, minY );\n maxY = Math.Max( q.Y, maxY );\n }\n\n if ( p.X < minX || p.X > maxX || p.Y < minY || p.Y > maxY )\n {\n return false;\n }\n\n // https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html\n bool inside = false;\n for ( int i = 0, j = polygon.Length - 1 ; i < polygon.Length ; j = i++ )\n {\n if ( ( polygon[ i ].Y > p.Y ) != ( polygon[ j ].Y > p.Y ) &&\n p.X < ( polygon[ j ].X - polygon[ i ].X ) * ( p.Y - polygon[ i ].Y ) / ( polygon[ j ].Y - polygon[ i ].Y ) + polygon[ i ].X )\n {\n inside = !inside;\n }\n }\n\n return inside;\n}\n"
},
{
"answer_id": 17490457,
"author": "Dave Seidman",
"author_id": 2553979,
"author_profile": "https://Stackoverflow.com/users/2553979",
"pm_score": 4,
"selected": false,
"text": "function insidePoly(poly, pointx, pointy) {\n var i, j;\n var inside = false;\n for (i = 0, j = poly.length - 1; i < poly.length; j = i++) {\n if(((poly[i].y > pointy) != (poly[j].y > pointy)) && (pointx < (poly[j].x-poly[i].x) * (pointy-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) ) inside = !inside;\n }\n return inside;\n}\n"
},
{
"answer_id": 17490923,
"author": "Philipp Lenssen",
"author_id": 34170,
"author_profile": "https://Stackoverflow.com/users/34170",
"pm_score": 6,
"selected": false,
"text": "function pointIsInPoly(p, polygon) {\n var isInside = false;\n var minX = polygon[0].x, maxX = polygon[0].x;\n var minY = polygon[0].y, maxY = polygon[0].y;\n for (var n = 1; n < polygon.length; n++) {\n var q = polygon[n];\n minX = Math.min(q.x, minX);\n maxX = Math.max(q.x, maxX);\n minY = Math.min(q.y, minY);\n maxY = Math.max(q.y, maxY);\n }\n\n if (p.x < minX || p.x > maxX || p.y < minY || p.y > maxY) {\n return false;\n }\n\n var i = 0, j = polygon.length - 1;\n for (i, j; i < polygon.length; j = i++) {\n if ( (polygon[i].y > p.y) != (polygon[j].y > p.y) &&\n p.x < (polygon[j].x - polygon[i].x) * (p.y - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x ) {\n isInside = !isInside;\n }\n }\n\n return isInside;\n}\n"
},
{
"answer_id": 20156642,
"author": "YongJiang Zhang",
"author_id": 953991,
"author_profile": "https://Stackoverflow.com/users/953991",
"pm_score": 3,
"selected": false,
"text": "public class Geocode {\n private float latitude;\n private float longitude;\n\n public Geocode() {\n }\n\n public Geocode(float latitude, float longitude) {\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n public float getLatitude() {\n return latitude;\n }\n\n public void setLatitude(float latitude) {\n this.latitude = latitude;\n }\n\n public float getLongitude() {\n return longitude;\n }\n\n public void setLongitude(float longitude) {\n this.longitude = longitude;\n }\n}\n\npublic class GeoPolygon {\n private ArrayList<Geocode> points;\n\n public GeoPolygon() {\n this.points = new ArrayList<Geocode>();\n }\n\n public GeoPolygon(ArrayList<Geocode> points) {\n this.points = points;\n }\n\n public GeoPolygon add(Geocode geo) {\n points.add(geo);\n return this;\n }\n\n public boolean inside(Geocode geo) {\n int i, j;\n boolean c = false;\n for (i = 0, j = points.size() - 1; i < points.size(); j = i++) {\n if (((points.get(i).getLongitude() > geo.getLongitude()) != (points.get(j).getLongitude() > geo.getLongitude())) &&\n (geo.getLatitude() < (points.get(j).getLatitude() - points.get(i).getLatitude()) * (geo.getLongitude() - points.get(i).getLongitude()) / (points.get(j).getLongitude() - points.get(i).getLongitude()) + points.get(i).getLatitude()))\n c = !c;\n }\n return c;\n }\n\n}\n"
},
{
"answer_id": 20781455,
"author": "ideasman42",
"author_id": 432509,
"author_profile": "https://Stackoverflow.com/users/432509",
"pm_score": 1,
"selected": false,
"text": "use_holes /* math lib (defined below) */\nstatic float dot_v2v2(const float a[2], const float b[2]);\nstatic float angle_signed_v2v2(const float v1[2], const float v2[2]);\nstatic void copy_v2_v2(float r[2], const float a[2]);\n\n/* intersection function */\nbool isect_point_poly_v2(const float pt[2], const float verts[][2], const unsigned int nr,\n const bool use_holes)\n{\n /* we do the angle rule, define that all added angles should be about zero or (2 * PI) */\n float angletot = 0.0;\n float fp1[2], fp2[2];\n unsigned int i;\n const float *p1, *p2;\n\n p1 = verts[nr - 1];\n\n /* first vector */\n fp1[0] = p1[0] - pt[0];\n fp1[1] = p1[1] - pt[1];\n\n for (i = 0; i < nr; i++) {\n p2 = verts[i];\n\n /* second vector */\n fp2[0] = p2[0] - pt[0];\n fp2[1] = p2[1] - pt[1];\n\n /* dot and angle and cross */\n angletot += angle_signed_v2v2(fp1, fp2);\n\n /* circulate */\n copy_v2_v2(fp1, fp2);\n p1 = p2;\n }\n\n angletot = fabsf(angletot);\n if (use_holes) {\n const float nested = floorf((angletot / (float)(M_PI * 2.0)) + 0.00001f);\n angletot -= nested * (float)(M_PI * 2.0);\n return (angletot > 4.0f) != ((int)nested % 2);\n }\n else {\n return (angletot > 4.0f);\n }\n}\n\n/* math lib */\n\nstatic float dot_v2v2(const float a[2], const float b[2])\n{\n return a[0] * b[0] + a[1] * b[1];\n}\n\nstatic float angle_signed_v2v2(const float v1[2], const float v2[2])\n{\n const float perp_dot = (v1[1] * v2[0]) - (v1[0] * v2[1]);\n return atan2f(perp_dot, dot_v2v2(v1, v2));\n}\n\nstatic void copy_v2_v2(float r[2], const float a[2])\n{\n r[0] = a[0];\n r[1] = a[1];\n}\n atan2f"
},
{
"answer_id": 30436297,
"author": "bzz",
"author_id": 3310339,
"author_profile": "https://Stackoverflow.com/users/3310339",
"pm_score": 4,
"selected": false,
"text": "extension CGPoint {\n func isInsidePolygon(vertices: [CGPoint]) -> Bool {\n guard !vertices.isEmpty else { return false }\n var j = vertices.last!, c = false\n for i in vertices {\n let a = (i.y > y) != (j.y > y)\n let b = (x < (j.x - i.x) * (y - i.y) / (j.y - i.y) + i.x)\n if a && b { c = !c }\n j = i\n }\n return c\n }\n}\n"
},
{
"answer_id": 35334551,
"author": "Shanaka Rathnayaka",
"author_id": 2135103,
"author_profile": "https://Stackoverflow.com/users/2135103",
"pm_score": 0,
"selected": false,
"text": "var polygon = new google.maps.Polygon([], \"#000000\", 1, 1, \"#336699\", 0.3);\nvar isWithinPolygon = polygon.containsLatLng(40, -90);\n"
},
{
"answer_id": 36485156,
"author": "Colin Stadig",
"author_id": 5631681,
"author_profile": "https://Stackoverflow.com/users/5631681",
"pm_score": 2,
"selected": false,
"text": "Private pXValue As Double\nPrivate pYValue As Double\n\n'''''X Value Property'''''\n\nPublic Property Get X() As Double\n X = pXValue\nEnd Property\n\nPublic Property Let X(Value As Double)\n pXValue = Value\nEnd Property\n\n'''''Y Value Property'''''\n\nPublic Property Get Y() As Double\n Y = pYValue\nEnd Property\n\nPublic Property Let Y(Value As Double)\n pYValue = Value\nEnd Property\n Public Function isPointInPolygon(p As CPoint, polygon() As CPoint) As Boolean\n\n Dim i As Integer\n Dim j As Integer\n Dim q As Object\n Dim minX As Double\n Dim maxX As Double\n Dim minY As Double\n Dim maxY As Double\n minX = polygon(0).X\n maxX = polygon(0).X\n minY = polygon(0).Y\n maxY = polygon(0).Y\n\n For i = 1 To UBound(polygon)\n Set q = polygon(i)\n minX = vbMin(q.X, minX)\n maxX = vbMax(q.X, maxX)\n minY = vbMin(q.Y, minY)\n maxY = vbMax(q.Y, maxY)\n Next i\n\n If p.X < minX Or p.X > maxX Or p.Y < minY Or p.Y > maxY Then\n isPointInPolygon = False\n Exit Function\n End If\n\n\n ' SOURCE: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html\n\n isPointInPolygon = False\n i = 0\n j = UBound(polygon)\n\n Do While i < UBound(polygon) + 1\n If (polygon(i).Y > p.Y) Then\n If (polygon(j).Y < p.Y) Then\n If p.X < (polygon(j).X - polygon(i).X) * (p.Y - polygon(i).Y) / (polygon(j).Y - polygon(i).Y) + polygon(i).X Then\n isPointInPolygon = True\n Exit Function\n End If\n End If\n ElseIf (polygon(i).Y < p.Y) Then\n If (polygon(j).Y > p.Y) Then\n If p.X < (polygon(j).X - polygon(i).X) * (p.Y - polygon(i).Y) / (polygon(j).Y - polygon(i).Y) + polygon(i).X Then\n isPointInPolygon = True\n Exit Function\n End If\n End If\n End If\n j = i\n i = i + 1\n Loop \nEnd Function\n\nFunction vbMax(n1, n2) As Double\n vbMax = IIf(n1 > n2, n1, n2)\nEnd Function\n\nFunction vbMin(n1, n2) As Double\n vbMin = IIf(n1 > n2, n2, n1)\nEnd Function\n\n\nSub TestPointInPolygon()\n\n Dim i As Integer\n Dim InPolygon As Boolean\n\n' MARKER Object\n Dim p As CPoint\n Set p = New CPoint\n p.X = <ENTER X VALUE HERE>\n p.Y = <ENTER Y VALUE HERE>\n\n' POLYGON OBJECT\n Dim polygon() As CPoint\n ReDim polygon(<ENTER VALUE HERE>) 'Amount of vertices in polygon - 1\n For i = 0 To <ENTER VALUE HERE> 'Same value as above\n Set polygon(i) = New CPoint\n polygon(i).X = <ASSIGN X VALUE HERE> 'Source a list of values that can be looped through\n polgyon(i).Y = <ASSIGN Y VALUE HERE> 'Source a list of values that can be looped through\n Next i\n\n InPolygon = isPointInPolygon(p, polygon)\n MsgBox InPolygon\n\nEnd Sub\n"
},
{
"answer_id": 43822141,
"author": "Junbang Huang",
"author_id": 3077801,
"author_profile": "https://Stackoverflow.com/users/3077801",
"pm_score": 5,
"selected": false,
"text": "[[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]\n def isInside(self, border, target):\ndegree = 0\nfor i in range(len(border) - 1):\n a = border[i]\n b = border[i + 1]\n\n # calculate distance of vector\n A = getDistance(a[0], a[1], b[0], b[1]);\n B = getDistance(target[0], target[1], a[0], a[1])\n C = getDistance(target[0], target[1], b[0], b[1])\n\n # calculate direction of vector\n ta_x = a[0] - target[0]\n ta_y = a[1] - target[1]\n tb_x = b[0] - target[0]\n tb_y = b[1] - target[1]\n\n cross = tb_y * ta_x - tb_x * ta_y\n clockwise = cross < 0\n\n # calculate sum of angles\n if(clockwise):\n degree = degree + math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C)))\n else:\n degree = degree - math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C)))\n\nif(abs(round(degree) - 360) <= 3):\n return True\nreturn False\n"
},
{
"answer_id": 48811843,
"author": "Michael-7",
"author_id": 549296,
"author_profile": "https://Stackoverflow.com/users/549296",
"pm_score": 0,
"selected": false,
"text": "def inside(p: Point, polygon: Array[Point], bounds: Bounds): Boolean = {\n\n val length = polygon.length\n\n @tailrec\n def oddIntersections(i: Int, j: Int, tracker: Boolean): Boolean = {\n if (i == length)\n tracker\n else {\n val intersects = (polygon(i).y > p.y) != (polygon(j).y > p.y) && p.x < (polygon(j).x - polygon(i).x) * (p.y - polygon(i).y) / (polygon(j).y - polygon(i).y) + polygon(i).x\n oddIntersections(i + 1, i, if (intersects) !tracker else tracker)\n }\n }\n\n oddIntersections(0, length - 1, tracker = false)\n}\n"
},
{
"answer_id": 50352869,
"author": "Noresourses",
"author_id": 7575092,
"author_profile": "https://Stackoverflow.com/users/7575092",
"pm_score": 2,
"selected": false,
"text": "[(xcord, ycord), ...] def polygon_ray_casting(self, bounding_points, bounding_box_positions):\n # Arrays containing the x- and y-coordinates of the polygon's vertices.\n vertx = [point[0] for point in bounding_points]\n verty = [point[1] for point in bounding_points]\n # Number of vertices in the polygon\n nvert = len(bounding_points)\n # Points that are inside\n points_inside = []\n\n # For every candidate position within the bounding box\n for idx, pos in enumerate(bounding_box_positions):\n testx, testy = (pos[0], pos[1])\n c = 0\n for i in range(0, nvert):\n j = i - 1 if i != 0 else nvert - 1\n if( ((verty[i] > testy ) != (verty[j] > testy)) and\n (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]) ):\n c += 1\n # If odd, that means that we are inside the polygon\n if c % 2 == 1: \n points_inside.append(pos)\n\n\n return points_inside\n"
},
{
"answer_id": 53062837,
"author": "SamTech",
"author_id": 1870444,
"author_profile": "https://Stackoverflow.com/users/1870444",
"pm_score": 0,
"selected": false,
"text": "func isPointInPolygon(polygon []point, testp point) bool {\n minX := polygon[0].X\n maxX := polygon[0].X\n minY := polygon[0].Y\n maxY := polygon[0].Y\n\n for _, p := range polygon {\n minX = min(p.X, minX)\n maxX = max(p.X, maxX)\n minY = min(p.Y, minY)\n maxY = max(p.Y, maxY)\n }\n\n if testp.X < minX || testp.X > maxX || testp.Y < minY || testp.Y > maxY {\n return false\n }\n\n inside := false\n j := len(polygon) - 1\n for i := 0; i < len(polygon); i++ {\n if (polygon[i].Y > testp.Y) != (polygon[j].Y > testp.Y) && testp.X < (polygon[j].X-polygon[i].X)*(testp.Y-polygon[i].Y)/(polygon[j].Y-polygon[i].Y)+polygon[i].X {\n inside = !inside\n }\n j = i\n }\n\n return inside\n}\n"
},
{
"answer_id": 53858320,
"author": "Santiago M. Quintero",
"author_id": 6823310,
"author_profile": "https://Stackoverflow.com/users/6823310",
"pm_score": 2,
"selected": false,
"text": "Neighborhoods"
},
{
"answer_id": 59468599,
"author": "Dial",
"author_id": 7373870,
"author_profile": "https://Stackoverflow.com/users/7373870",
"pm_score": 0,
"selected": false,
"text": "pnpoly <- function(nvert,vertx,verty,testx,testy){\n c <- FALSE\n j <- nvert \n for (i in 1:nvert){\n if( ((verty[i]>testy) != (verty[j]>testy)) && \n (testx < (vertx[j]-vertx[i])*(testy-verty[i])/(verty[j]-verty[i])+vertx[i]))\n {c <- !c}\n j <- i}\n return(c)}\n"
},
{
"answer_id": 60732016,
"author": "Yuan Fu",
"author_id": 5023978,
"author_profile": "https://Stackoverflow.com/users/5023978",
"pm_score": 1,
"selected": false,
"text": "GMSGeometryContainsLocation if GMSGeometryContainsLocation(point, polygon, true) {\n print(\"Inside this polygon.\")\n} else {\n print(\"outside this polygon\")\n}\n"
},
{
"answer_id": 61303788,
"author": "Celdor",
"author_id": 1612369,
"author_profile": "https://Stackoverflow.com/users/1612369",
"pm_score": 0,
"selected": false,
"text": "function pnpoly(area, test)\n local inside = false\n local tx, ty = table.unpack(test)\n local j = #area\n for i=1, #area do\n local vxi, vyi = table.unpack(area[i])\n local vxj, vyj = table.unpack(area[j])\n if (vyi > ty) ~= (vyj > ty)\n and tx < (vxj - vxi)*(ty - vyi)/(vyj - vyi) + vxi\n then\n inside = not inside\n end\n j = i\n end\n return inside\nend\n area > A = {{2, 1}, {1, 2}, {15, 3}, {3, 4}, {5, 3}, {4, 1.5}}\n> T = {2, 1.1}\n> pnpoly(A, T)\ntrue\n"
},
{
"answer_id": 62254402,
"author": "TankorSmash",
"author_id": 541208,
"author_profile": "https://Stackoverflow.com/users/541208",
"pm_score": 1,
"selected": false,
"text": "std::vector<std::pair<double, double>> bool point_in_poly(std::vector<std::pair<double, double>>& verts, double point_x, double point_y)\n{\n bool in_poly = false;\n auto num_verts = verts.size();\n for (int i = 0, j = num_verts - 1; i < num_verts; j = i++) {\n double x1 = verts[i].first;\n double y1 = verts[i].second;\n double x2 = verts[j].first;\n double y2 = verts[j].second;\n\n if (((y1 > point_y) != (y2 > point_y)) &&\n (point_x < (x2 - x1) * (point_y - y1) / (y2 - y1) + x1))\n in_poly = !in_poly;\n }\n return in_poly;\n}\n int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)\n{\n int i, j, c = 0;\n for (i = 0, j = nvert-1; i < nvert; j = i++) {\n if ( ((verty[i]>testy) != (verty[j]>testy)) &&\n (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )\n c = !c;\n }\n return c;\n}\n"
},
{
"answer_id": 63436180,
"author": "timepp",
"author_id": 2608744,
"author_profile": "https://Stackoverflow.com/users/2608744",
"pm_score": 3,
"selected": false,
"text": "/** Get relationship between a point and a polygon using ray-casting algorithm\n * @param {{x:number, y:number}} P: point to check\n * @param {{x:number, y:number}[]} polygon: the polygon\n * @returns -1: outside, 0: on edge, 1: inside\n */\nfunction relationPP(P, polygon) {\n const between = (p, a, b) => p >= a && p <= b || p <= a && p >= b\n let inside = false\n for (let i = polygon.length-1, j = 0; j < polygon.length; i = j, j++) {\n const A = polygon[i]\n const B = polygon[j]\n // corner cases\n if (P.x == A.x && P.y == A.y || P.x == B.x && P.y == B.y) return 0\n if (A.y == B.y && P.y == A.y && between(P.x, A.x, B.x)) return 0\n\n if (between(P.y, A.y, B.y)) { // if P inside the vertical range\n // filter out \"ray pass vertex\" problem by treating the line a little lower\n if (P.y == A.y && B.y >= A.y || P.y == B.y && A.y >= B.y) continue\n // calc cross product `PA X PB`, P lays on left side of AB if c > 0 \n const c = (A.x - P.x) * (B.y - P.y) - (B.x - P.x) * (A.y - P.y)\n if (c == 0) return 0\n if ((A.y < B.y) == (c > 0)) inside = !inside\n }\n }\n\n return inside? 1 : -1\n}\n"
},
{
"answer_id": 66557037,
"author": "OneMadGypsy",
"author_id": 10292330,
"author_profile": "https://Stackoverflow.com/users/10292330",
"pm_score": 0,
"selected": false,
"text": "from typing import Iterable\n\ndef pnpoly(verts, x, y):\n #check if x and/or y is iterable\n xit, yit = isinstance(x, Iterable), isinstance(y, Iterable)\n #if not iterable, make an iterable of length 1\n X = x if xit else (x, )\n Y = y if yit else (y, )\n #store verts length as a range to juggle j\n r = range(len(verts))\n #final results if x or y is iterable\n results = []\n #traverse x and y coordinates\n for xp in X:\n for yp in Y:\n c = 0 #reset c at every new position\n for i in r:\n j = r[i-1] #set j to position before i\n #store a few arguments to shorten the if statement\n yneq = (verts[i][1] > yp) != (verts[j][1] > yp)\n xofs, yofs = (verts[j][0] - verts[i][0]), (verts[j][1] - verts[i][1])\n #if we have crossed a line, increment c\n if (yneq and (xp < xofs * (yp - verts[i][1]) / yofs + verts[i][0])):\n c += 1\n #if c is odd store the coordinates \n if c%2:\n results.append((xp, yp))\n #return either coordinates or a bool, depending if x or y was an iterable\n return results if (xit or yit) else bool(c%2)\n range x y list True vertices Iterable [(x1,y1), (x2,y2), ...] vertices = [(25,25), (75,25), (75,75), (25,75)]\npnpoly(vertices, 50, 50) #True\npnpoly(vertices, range(100), range(100)) #[(25,25), (25,26), (25,27), ...]\n pnpoly(vertices, 50, range(100)) #check 0 to 99 y at x of 50\npnpoly(vertices, range(100), 50) #check 0 to 99 x at y of 50\n"
},
{
"answer_id": 68294056,
"author": "Shaun Han",
"author_id": 13860719,
"author_profile": "https://Stackoverflow.com/users/13860719",
"pm_score": 1,
"selected": false,
"text": "[[139, 483], [227, 792], [482, 849], [523, 670], [352, 330]]\n [[248, 518], [336, 510], [341, 614], [250, 620]]\n [[416, 531], [505, 517], [495, 616]]\n [296, 557] [422, 730] [296, 557] [422, 730] numpy def detect(points, *polygons):\n import numpy as np\n endpoint1 = np.r_[tuple(np.roll(p, 1, 0) for p in polygons)][:, None] - points\n endpoint2 = np.r_[polygons][:, None] - points\n p1, p2 = np.cross(endpoint1, endpoint2), np.einsum('...i,...i', endpoint1, endpoint2)\n return ~((p1.sum(0) < 0) ^ (abs(np.arctan2(p1, p2).sum(0)) > np.pi) | ((p1 == 0) & (p2 <= 0)).any(0))\n points = [[296, 557], [422, 730]]\npolygon1 = [[139, 483], [227, 792], [482, 849], [523, 670], [352, 330]]\npolygon2 = [[248, 518], [336, 510], [341, 614], [250, 620]]\npolygon3 = [[416, 531], [505, 517], [495, 616]]\n\nprint(detect(points, polygon1, polygon2, polygon3))\n [False True]\n"
},
{
"answer_id": 71372722,
"author": "Michel Rouzic",
"author_id": 1675589,
"author_profile": "https://Stackoverflow.com/users/1675589",
"pm_score": 0,
"selected": false,
"text": "1.0 0.0 -1.0 NAN typedef struct { double x, y; } xy_t;\n\nxy_t sub_xy(xy_t a, xy_t b)\n{\n a.x -= b.x;\n a.y -= b.y;\n return a;\n}\n\ndouble calc_sharp_subtriangle_pixel_weight(xy_t p0, xy_t p1)\n{\n xy_t rot, r0, r1;\n double weight;\n\n // Rotate points (unnormalised)\n rot = sub_xy(p1, p0);\n r0.x = rot.x*p0.y - rot.y*p0.x;\n r0.y = rot.x*p0.x + rot.y*p0.y;\n r1.y = rot.x*p1.x + rot.y*p1.y;\n\n // Calc weight\n weight = subtriangle_angle_approx(r1.y, r0.x) - subtriangle_angle_approx(r0.y, r0.x);\n\n return weight;\n}\n\ndouble calc_sharp_polygon_pixel_weight(xy_t p, xy_t *corner, int corner_count)\n{\n int i;\n xy_t p0, p1;\n double weight = 0.;\n\n p0 = sub_xy(corner[corner_count-1], p);\n for (i=0; i < corner_count; i++)\n {\n // Transform corner coordinates\n p1 = sub_xy(corner[i], p);\n\n // Calculate weight for each subtriangle\n weight += calc_sharp_subtriangle_pixel_weight(p0, p1);\n p0 = p1;\n }\n\n return weight;\n}\n subtriangle_angle_approx(y, x) atan2(y, x) / (2.*pi) double subtriangle_angle_approx(double y, double x)\n{\n double angle, d;\n int obtuse;\n\n if (x == 0.)\n return NAN;\n\n obtuse = fabs(y) > fabs(x);\n if (obtuse)\n swap_double(&y, &x);\n\n // Core of the approximation, a very loosely approximate atan(y/x) / (2.*pi) over ]-1 , 1[\n d = y / x;\n angle = 0.13185 * d;\n\n if (obtuse)\n angle = sign(d)*0.25 - angle;\n\n return angle;\n}\n"
},
{
"answer_id": 73361074,
"author": "yong hu",
"author_id": 9741774,
"author_profile": "https://Stackoverflow.com/users/9741774",
"pm_score": 0,
"selected": false,
"text": "pub struct Point {\n x: f32,\n y: f32,\n}\npub fn point_is_in_poly(pt: Point, polygon: &Vec<Point>) -> bool {\n let mut is_inside = false;\n\n let max_x = polygon.iter().map(|pt| pt.x).reduce(f32::max).unwrap();\n let min_x = polygon.iter().map(|pt| pt.x).reduce(f32::min).unwrap();\n let max_y = polygon.iter().map(|pt| pt.y).reduce(f32::max).unwrap();\n let min_y = polygon.iter().map(|pt| pt.y).reduce(f32::min).unwrap();\n\n if pt.x < min_x || pt.x > max_x || pt.y < min_y || pt.y > max_y {\n return is_inside;\n }\n\n let len = polygon.len();\n let mut j = len - 1;\n\n for i in 0..len {\n let y_i_value = polygon[i].y > pt.y;\n let y_j_value = polygon[j].y > pt.y;\n let last_check = (polygon[j].x - polygon[i].x) * (pt.y - polygon[i].y)\n / (polygon[j].y - polygon[i].y)\n + polygon[i].x;\n if y_i_value != y_j_value && pt.x < last_check {\n is_inside = !is_inside;\n }\n j = i;\n }\n is_inside\n}\n\n\nlet pt = Point {\n x: 1266.753,\n y: 97.655,\n};\nlet polygon = vec![\n Point {\n x: 725.278,\n y: 203.586,\n },\n Point {\n x: 486.831,\n y: 441.931,\n },\n Point {\n x: 905.77,\n y: 445.241,\n },\n Point {\n x: 1026.649,\n y: 201.931,\n },\n];\nlet pt1 = Point {\n x: 725.278,\n y: 203.586,\n};\nlet pt2 = Point {\n x: 872.652,\n y: 321.103,\n};\nprintln!(\"{}\", point_is_in_poly(pt, &polygon));// false\nprintln!(\"{}\", point_is_in_poly(pt1, &polygon)); // true\nprintln!(\"{}\", point_is_in_poly(pt2, &polygon));// true\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11397/"
] |
217,591
|
<p>I have several xml files, the names of which are stored in another xml file. </p>
<p>I want to use xsl to produce a summary of the combination of the xml files. I remember there was a way to do this with the msxml extensions (I'm using msxml).</p>
<p>I know I can get the content of each file using <code>select="document(filename)"</code> but I'm not sure how to combine all these documents into one.</p>
<p>21-Oct-08 I should have mentioned that I want to do further processing on the combined xml, so it is not sufficient to just output it from the transform, I need to store it as a node set in a variable.</p>
|
[
{
"answer_id": 217662,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "document() document() <xsl:copy-of select=\"document(@href)/\"/>\n"
},
{
"answer_id": 217679,
"author": "GerG",
"author_id": 17249,
"author_profile": "https://Stackoverflow.com/users/17249",
"pm_score": 3,
"selected": true,
"text": "<foo>\n<bar>Text from file1</bar>\n</foo>\n <foo>\n<bar>Text from file2</bar>\n</foo>\n <index>\n<filename>file1.xml</filename>\n<filename>file2.xml</filename>\n <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" \n xmlns:exsl=\"http://exslt.org/common\"\n extension-element-prefixes=\"exsl\">\n\n <xsl:variable name=\"big-doc-rtf\">\n <xsl:for-each select=\"/index/filename\">\n <xsl:copy-of select=\"document(.)\"/>\n </xsl:for-each>\n </xsl:variable>\n\n <xsl:variable name=\"big-doc\" select=\"exsl:node-set($big-doc-rtf)\"/>\n\n <xsl:template match=\"/\">\n <xsl:element name=\"summary\">\n <xsl:apply-templates select=\"$big-doc/foo\"/>\n </xsl:element> \n </xsl:template>\n\n <xsl:template match=\"foo\">\n <xsl:element name=\"text\">\n <xsl:value-of select=\"bar\"/>\n </xsl:element> \n </xsl:template>\n\n</xsl:stylesheet>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?><summary><text>Text from file1</text><text>Text from file2</text></summary>\n"
},
{
"answer_id": 217686,
"author": "mbesso",
"author_id": 9510,
"author_profile": "https://Stackoverflow.com/users/9510",
"pm_score": 2,
"selected": false,
"text": "<files>\n <file>a.xml</file>\n <file>b.xml</file>\n</files>\n <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\"/>\n\n <xsl:template match=\"/\">\n <root>\n <xsl:apply-templates select=\"files/file\"/> \n </root>\n </xsl:template>\n\n <xsl:template match=\"file\">\n <xsl:copy-of select=\"document(.)\"/>\n </xsl:template>\n</xsl:stylesheet>\n"
},
{
"answer_id": 220484,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\" \nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\nxmlns:ms=\"urn:schemas-microsoft-com:xslt\">\n <xsl:output method=\"xml\"/>\n <xsl:template match=\"/\">\n <xsl:variable name=\"combined\">\n <xsl:apply-templates select=\"files\"/>\n </xsl:variable>\n <xsl:copy-of select=\"ms:node-set($combined)\"/>\n </xsl:template>\n <xsl:template match=\"files\">\n <multifile>\n <xsl:apply-templates select=\"file\"/>\n </multifile>\n </xsl:template>\n <xsl:template match=\"file\">\n <xsl:copy-of select=\"document(@name)\"/>\n </xsl:template>\n</xsl:stylesheet>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24355/"
] |
217,594
|
<p>I'm trying to determine the best way of having a PHP script determine which server the script/site is currently running on.</p>
<p>At the moment I have a <code>switch()</code> that uses <code>$_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']</code> to determine which server it's on. It then sets a few paths, db connection parameters, SMTP paramters and debug settings based on which server it's on. (There maybe additional parameters depending on the site needs.)</p>
<p>This means that I can simply drop the site onto any of the configured servers without having to change any code (specifically the configuration). If it's a new server, then I simply add a new <code>case</code> and it's ready from then on.</p>
<p>We have done loading config files based on the same <code>SERVER_NAME:SERVER_PORT</code> combination, but found that it's another file you have to maintain, plus we weren't sure on the speed of parsing ini files, (although having extra cases for each server may be just as slow).</p>
<p>Another problem we have is when a site is often moved between 2 servers, but we use the same <code>SERVER_NAME</code> and <code>SERVER_PORT</code> on each. This means we need to temporarily comment one case and ensure it doesn't get into the repo.</p>
<p>Another other ideas? It needs to be available on all servers (sometimes <code>SERVER_NAME</code> and <code>SERVER_PORT</code> are not). It would also be nice if it worked with the CLI PHP.</p>
|
[
{
"answer_id": 217598,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": true,
"text": "$id = $_SERVER['SERVER_ADDR'] . $_SERVER['DOCUMENT_ROOT'];\n"
},
{
"answer_id": 217705,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 2,
"selected": false,
"text": "$_SERVER['HTTP_HOST'];\n $_SERVER['USER'];\n$_SERVER['LOGNAME'];\n"
},
{
"answer_id": 221988,
"author": "duckyflip",
"author_id": 7370,
"author_profile": "https://Stackoverflow.com/users/7370",
"pm_score": 0,
"selected": false,
"text": "$posix_uname = function_exists('posix_uname') ? posix_uname() : null;\n$this_hostname = !empty($_SERVER[\"HOSTNAME\"]) ? $_SERVER[\"HOSTNAME\"] : $_ENV[\"HOSTNAME\"];\n$this_hostname = !empty($this_hostname) ? $this_hostname : $posix_uname['nodename'];\n"
},
{
"answer_id": 1376775,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 1,
"selected": false,
"text": "if(__FILE__ === '/Sites/mywebsite.com/includes/config.php')\n define('SERVER', 'DEV');\nelse\n define('SERVER', 'PRODUCTION');\n $_SERVER[HTTP_HOST]"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
217,595
|
<p>I have an existing Perl program that uses <code>Getopt</code> package and <code>Getopt::Long::Configure</code> with <code>permute</code> as one of the options. However, now I need to keep the order of the options entered by the user. There is an option <code>$RETURN_IN_ORDER</code> mentioned in the <code>Long.pm</code>, however doesn't seem to be used anywhere at all. </p>
<p>When I pass <code>return_in_order</code>, I am getting the following error.</p>
<hr>
<blockquote>
<p>Getopt::Long: unknown config parameter "return_in_order" at C:/Program Files/IBM/RationalSDLC/common/lib/perl5/5.8.6/Getopt/Long.pm line 1199.</p>
</blockquote>
<hr>
<p>Can someone please tell me if this is supported at all and if so, the right way to use? If not, I would like to know the other alternatives I have.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 217601,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "require_order"
},
{
"answer_id": 217646,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "-a file -b\n"
},
{
"answer_id": 217751,
"author": "tsee",
"author_id": 13164,
"author_profile": "https://Stackoverflow.com/users/13164",
"pm_score": 2,
"selected": false,
"text": "./foo --option1 --option2 file1 file2 file3\n #!/usr/bin/perl\nuse strict;\nuse warnings;\nuse Getopt::Long;\nmy @permute;\nGetOptions(\n 'p=s' => \\@permute,\n);\n\nprint \"$_\\n\" for @permute;\n 1\n2\n3\n4\n"
},
{
"answer_id": 18215293,
"author": "Alex Aminoff",
"author_id": 2679502,
"author_profile": "https://Stackoverflow.com/users/2679502",
"pm_score": 1,
"selected": false,
"text": "myscript /usr --include /usr/local/bin --exclude /usr/local"
},
{
"answer_id": 49534578,
"author": "cxw",
"author_id": 2877364,
"author_profile": "https://Stackoverflow.com/users/2877364",
"pm_score": 0,
"selected": false,
"text": "-e <foo> -f <foo> use Data::Dumper; use Getopt::Long; use strict; use warnings;\nmy @Sources; # Each element is [was -f, parameter]\n\nmy $dr_save_source = sub { # Called each time we see -e or -f\n my ($which, $text) = @_;\n push @Sources, [$which eq \"f\", $text];\n}; # dr_save_source\n\nGetOptions(\"e=s@\" => $dr_save_source, \"f=s@\" => $dr_save_source);\nprint Dumper(\\@Sources);\n $dr_save_source => $dr_save_source GetOptions"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23373/"
] |
217,612
|
<p>I'm a little confused by some PHP syntax I've come across. Here is an example:</p>
<pre><code>$k = $this->_tbl_key;
if( $this->$k)
{
$ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls );
}
else
{
$ret = $this->_db->insertObject( $this->_tbl, $this, $this->_tbl_key );
}
</code></pre>
<p>My question is basically what does <code>$this->$k</code> mean? I figured it might mean the member variable that goes by the name of whatever is in <code>$this->_tbl_key</code>, but how would that work? Is it possible to add member variables to a class at run-time?</p>
|
[
{
"answer_id": 217616,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "echo ($obj->myvar);\n\n####\n\n$k = \"myvar\";\necho ($obj->$k);\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
] |
217,614
|
<p>In data processing, I frequently need to create a lookup data structure to map one identifier to another. As a concrete example, let's take a structure which holds a 1-to-1 mapping between a country's 2 character code and its full name. In it we would have</p>
<pre><code>AD -> Andorra
AE -> United Arab Emirates
AF -> Afghanistan
</code></pre>
<p>What's a good name for the variable that would hold this map? Some ideas (I'll use camel-case names):</p>
<pre><code>countryNameByCode
nameByCodeLookup
nameCodeLookup
codeToName
</code></pre>
|
[
{
"answer_id": 217628,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 4,
"selected": true,
"text": "codeToName String country = codeToName[\"SV\"];\n"
},
{
"answer_id": 217639,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "countryNames\n countryCodes"
},
{
"answer_id": 217641,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "countryName = countries[countryCode];\n countries countryCode countryName countryName = countryCodesToNames[countryCode];\n"
},
{
"answer_id": 217658,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "CountryCodeToNameMapping countryCodeToNameMapping c m"
},
{
"answer_id": 217682,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "country_name = countries_by_code[country_code]\n"
},
{
"answer_id": 236063,
"author": "albertb",
"author_id": 26715,
"author_profile": "https://Stackoverflow.com/users/26715",
"pm_score": -1,
"selected": false,
"text": "country = countries[code]"
},
{
"answer_id": 64350114,
"author": "plexando",
"author_id": 10716984,
"author_profile": "https://Stackoverflow.com/users/10716984",
"pm_score": 0,
"selected": false,
"text": "countryName = countryByCode[\"DE\"]\n countryName = countryNameByCode[\"DE\"]\n countries countriesByCode countryName = CountryCodeToName[\"DE\"]\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2601671/"
] |
217,618
|
<p>Is there any advantage to using <code>__construct()</code> instead of the class's name for a constructor in PHP?</p>
<p>Example (<code>__construct</code>):</p>
<pre><code>class Foo {
function __construct(){
//do stuff
}
}
</code></pre>
<p>Example (named):</p>
<pre><code>class Foo {
function Foo(){
//do stuff
}
}
</code></pre>
<p>Having the <code>__construct</code> method (first example) is possible since PHP 5.</p>
<p>Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.</p>
|
[
{
"answer_id": 217622,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 4,
"selected": false,
"text": "__construct __construct"
},
{
"answer_id": 217625,
"author": "Steven Oxley",
"author_id": 3831,
"author_profile": "https://Stackoverflow.com/users/3831",
"pm_score": 2,
"selected": false,
"text": "__construct className __construct className"
},
{
"answer_id": 217876,
"author": "Bazman",
"author_id": 18521,
"author_profile": "https://Stackoverflow.com/users/18521",
"pm_score": 7,
"selected": true,
"text": "parent::__construct()\n"
},
{
"answer_id": 217888,
"author": "Ryan McCue",
"author_id": 2575,
"author_profile": "https://Stackoverflow.com/users/2575",
"pm_score": 3,
"selected": false,
"text": "__contruct() ClassName() parent::__construct() parent::ClassName()"
},
{
"answer_id": 17131739,
"author": "Jan Turoň",
"author_id": 343721,
"author_profile": "https://Stackoverflow.com/users/343721",
"pm_score": 4,
"selected": false,
"text": "__construct namespace Foo;\nclass Test {\n var $a = 3;\n\n function Test($a) {\n $this->a = $a;\n }\n\n function getA() {\n return $this->a;\n }\n}\n\n$test = new Test(4);\necho $test->getA(); // 3, Test is not a constructor, just ordinary function\n __construct getName()"
},
{
"answer_id": 29329911,
"author": "Rizier123",
"author_id": 3933332,
"author_profile": "https://Stackoverflow.com/users/3933332",
"pm_score": 2,
"selected": false,
"text": "E_DEPRECATED E_STRICT __construct() __construct()"
},
{
"answer_id": 30204934,
"author": "Levi Morrison",
"author_id": 538216,
"author_profile": "https://Stackoverflow.com/users/538216",
"pm_score": 3,
"selected": false,
"text": "Foo::Foo class Foo {\n // PHP 4 constructor\n function Foo(){\n //do stuff\n }\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29502/"
] |
217,665
|
<p>I have faced this problem quite often during the last couple of months, during which I've been building this system. The scenario is this: I have this kind of object that essentially is a list of other objects, but has some other properties specific of its nature. For example:</p>
<ul>
<li>Class <code>Tests</code>:
<ul>
<li>Contains many <code>Test</code> objects</li>
<li>Has properties:
<ul>
<li><code>DefaultTimeouts</code></li>
<li><code>DefaultNumberOfTries</code></li>
</ul></li>
</ul></li>
</ul>
<p>Should I have this class subclass <code>List<Test></code> or should I have it inheriting from <code>Object</code>, simply having the list as a property beside the other fields?</p>
<p>I know that this may be a bit subjective and personal taste might play a role here, but I'd wholeheartedly like to know your opinion on this.</p>
|
[
{
"answer_id": 217670,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 1,
"selected": false,
"text": "List List Tests List<Test> List<Test> List<Test>"
},
{
"answer_id": 217688,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "TestSuite List"
},
{
"answer_id": 217696,
"author": "André Chalella",
"author_id": 4850,
"author_profile": "https://Stackoverflow.com/users/4850",
"pm_score": 1,
"selected": false,
"text": "List<Test>"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4850/"
] |
217,666
|
<p>I've written a setup.py script for py2exe, generated an executable for my python GUI application and I have a whole bunch of files in the dist directory, including the app, w9xopen.exe and MSVCR71.dll. When I try to run the application, I get an error message that just says "see the logfile for details". The only problem is, the log file is empty. </p>
<p>The closest error I've seen is "The following modules appear to be missing" but I'm not using any of those modules as far as I know (especially since they seem to be of databases I'm not using) but digging up on Google suggests that these are relatively benign warnings.</p>
<p>I've written and packaged a console application as well as a wxpython one with py2exe and both applications have compiled and run successfully. I am using a new python toolkit called dabo, which in turn makes uses of wxpython modules so I can't figure out what I'm doing wrong. Where do I start investigating the problem since obviously the log file hasn't been too useful? </p>
<p><b>Edit 1:</b>
The python version is 2.5. py2exe is 0.6.8. There were no significant build errors. The only one was the bit about "The following modules appear to be missing..." which were non critical errors since the packages listed were ones I was definitely not using and shouldn't stop the execution of the app either. Running the executable produced a logfile which was completely empty. Previously it had an error about locales which I've since fixed but clearly something is wrong as the executable wasn't running. The setup.py file is based quite heavily on the original setup.py generated by running their "app wizard" and looking at the example that Ed Leafe and some others posted. Yes, I have a log file and it's not printing anything for me to use, which is why I'm asking if there's any other troubleshooting avenue I've missed which will help me find out what's going on. </p>
<p>I have even written a bare bones test application which simply produces a bare bones GUI - an empty frame with some default menu options. The code written itself is only 3 lines and the rest is in the 3rd party toolkit. Again, that compiled into an exe (as did my original app) but simply did not run. There were no error output in the run time log file either. </p>
<p><b>Edit 2:</b>
It turns out that switching from "windows" to "console" for initial debugging purposes was insightful. I've now got a basic running test app and on to compiling the real app! </p>
<p><i>The test app:</i></p>
<pre>
import dabo
app = dabo.dApp()
app.start()
</pre>
<p><i>The setup.py for test app:</i></p>
<pre>
import os
import sys
import glob
from distutils.core import setup
import py2exe
import dabo.icons
daboDir = os.path.split(dabo.__file__)[0]
# Find the location of the dabo icons:
iconDir = os.path.split(dabo.icons.__file__)[0]
iconSubDirs = []
def getIconSubDir(arg, dirname, fnames):
if ".svn" not in dirname and dirname[-1] != "\\":
icons = glob.glob(os.path.join(dirname, "*.png"))
if icons:
subdir = (os.path.join("resources", dirname[len(arg)+1:]), icons)
iconSubDirs.append(subdir)
os.path.walk(iconDir, getIconSubDir, iconDir)
# locales:
localeDir = "%s%slocale" % (daboDir, os.sep)
locales = []
def getLocales(arg, dirname, fnames):
if ".svn" not in dirname and dirname[-1] != "\\":
mo_files = tuple(glob.glob(os.path.join(dirname, "*.mo")))
if mo_files:
subdir = os.path.join("dabo.locale", dirname[len(arg)+1:])
locales.append((subdir, mo_files))
os.path.walk(localeDir, getLocales, localeDir)
data_files=[("resources", glob.glob(os.path.join(iconDir, "*.ico"))),
("resources", glob.glob("resources/*"))]
data_files.extend(iconSubDirs)
data_files.extend(locales)
setup(name="basicApp",
version='0.01',
description="Test Dabo Application",
options={"py2exe": {
"compressed": 1, "optimize": 2, "bundle_files": 1,
"excludes": ["Tkconstants","Tkinter","tcl",
"_imagingtk", "PIL._imagingtk",
"ImageTk", "PIL.ImageTk", "FixTk", "kinterbasdb",
"MySQLdb", 'Numeric', 'OpenGL.GL', 'OpenGL.GLUT',
'dbGadfly', 'email.Generator',
'email.Iterators', 'email.Utils', 'kinterbasdb',
'numarray', 'pymssql', 'pysqlite2', 'wx.BitmapFromImage'],
"includes": ["encodings", "locale", "wx.gizmos","wx.lib.calendar"]}},
zipfile=None,
windows=[{'script':'basicApp.py'}],
data_files=data_files
)
</pre>
|
[
{
"answer_id": 217670,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 1,
"selected": false,
"text": "List List Tests List<Test> List<Test> List<Test>"
},
{
"answer_id": 217688,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "TestSuite List"
},
{
"answer_id": 217696,
"author": "André Chalella",
"author_id": 4850,
"author_profile": "https://Stackoverflow.com/users/4850",
"pm_score": 1,
"selected": false,
"text": "List<Test>"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20879/"
] |
217,678
|
<p>As you can see this is a question from a non web developer. I would like to have an ASPX page which, under certain circumstances, can generate a 401 error from code. Ideally it would show the IIS standard page.</p>
|
[
{
"answer_id": 217689,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 4,
"selected": false,
"text": "Throw New HttpException(401, \"Auth Failed\")\n"
},
{
"answer_id": 217692,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": false,
"text": "Response.StatusCode = 401;\nResponse.End();\n"
},
{
"answer_id": 1627748,
"author": "Brian Ferguson",
"author_id": 196952,
"author_profile": "https://Stackoverflow.com/users/196952",
"pm_score": 5,
"selected": false,
"text": "throw new HttpException(401, \"Auth Failed\")\n Response.StatusCode <customErrors mode=\"On\" defaultRedirect=\"GenericErrorPage.htm\">\n <error statusCode=\"401\" redirect=\"AuthFailed.htm\" />\n <error statusCode=\"403\" redirect=\"NoAccess.htm\" />\n <error statusCode=\"404\" redirect=\"FileNotFound.htm\" />\n</customErrors>\n Response.StatusCode Response.StatusCode"
},
{
"answer_id": 7667927,
"author": "AnthonyVO",
"author_id": 438458,
"author_profile": "https://Stackoverflow.com/users/438458",
"pm_score": 3,
"selected": false,
"text": "Response.ClearContent();\nResponse.StatusCode = 401;\nResponse.End();\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1890/"
] |
217,707
|
<p>Do these two keywords have exactly the same effect, or is there something I should be aware of?</p>
|
[
{
"answer_id": 217716,
"author": "Keeg",
"author_id": 21059,
"author_profile": "https://Stackoverflow.com/users/21059",
"pm_score": 5,
"selected": true,
"text": "lock synchronized synchronized [MethodImpl(MethodImplOptions.Synchronized)]"
},
{
"answer_id": 217725,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "lock"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
217,710
|
<p>What's the best way to format this for readability?</p>
<pre><code>if (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false) {
createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
fwrite($log,date("Y-m-d")." @ ".date("H:i:s")." CREATED: $thumbsdir/$file\n");
}
</code></pre>
|
[
{
"answer_id": 217712,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 2,
"selected": false,
"text": "if ((strpos($file, '.jpg',1) ||\n strpos($file, '.gif',1) ||\n strpos($file, '.png',1))\n && file_exists(\"$thumbsdir/$file\") == false)\n{\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n}\n"
},
{
"answer_id": 217715,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "if (strpos($file, '.jpg',1) && file_exists(\"$thumbsdir/$file\") == false\n || strpos($file, '.gif',1) && file_exists(\"$thumbsdir/$file\") == false\n || strpos($file, '.png',1) && file_exists(\"$thumbsdir/$file\") == false) {\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n}\n"
},
{
"answer_id": 217717,
"author": "Neil Williams",
"author_id": 9617,
"author_profile": "https://Stackoverflow.com/users/9617",
"pm_score": 5,
"selected": true,
"text": "if function is_image($filename) {\n $image_extensions = array('png', 'gif', 'jpg');\n\n foreach ($image_extensions as $extension) \n if (strrpos($filename, \".$extension\") !== FALSE)\n return true;\n\n return false;\n}\n\nif (is_image($file) && !file_exists(\"$thumbsdir/$file\")) {\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n}\n"
},
{
"answer_id": 217719,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "file_exists file_exists if (file_exists(\"$thumbsdir/$file\") == false)\n{\n if(strpos($file, '.jpg',1) ||\n strpos($file, '.gif',1) ||\n strpos($file, '.png',1)\n {\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n }\n}\n"
},
{
"answer_id": 217720,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "function check_thumbnail($file)\n{\n return (strpos($file, '.jpg',1) && file_exists(\"$thumbsdir/$file\") == false ||\n strpos($file, '.gif',1) && file_exists(\"$thumbsdir/$file\") == false ||\n strpos($file, '.png',1) && file_exists(\"$thumbsdir/$file\") == false);\n}\n\nif (check_thumbnail ($file)) {\n createThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\n fwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n}\n function check_thumbnail($file)\n{\n return (strpos($file, '.jpg',1) ||\n strpos($file, '.gif',1) ||\n strpos($file, '.png',1)) &&\n (file_exists(\"$thumbsdir/$file\") == false);\n}\n"
},
{
"answer_id": 217724,
"author": "Rob Bell",
"author_id": 2179408,
"author_profile": "https://Stackoverflow.com/users/2179408",
"pm_score": 2,
"selected": false,
"text": "if (!strpos($file, '.jpg',1) && !strpos($file, '.gif',1) && !strpos($file, '.png',1))\n{\n return;\n}\n\nif(file_exists(\"$thumbsdir/$file\"))\n{\n return;\n}\n\ncreateThumb(\"$gallerydir/$file\", \"$thumbsdir/$file\",$thumbsize);\nfwrite($log,date(\"Y-m-d\").\" @ \".date(\"H:i:s\").\" CREATED: $thumbsdir/$file\\n\");\n"
},
{
"answer_id": 219058,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "// Extract image info if possible\n // Note: Error suppression is for missing file or non-image\nif (@$imageInfo = getimagesize(\"{$thumbsdir}/{$file}\")) {\n\n // Accept the following image types\n $acceptTypes = array(\n IMAGETYPE_JPEG,\n IMAGETYPE_GIF,\n IMAGETYPE_PNG,\n );\n\n // Proceed if image format is acceptable\n if (in_array($imageInfo[2], $acceptTypes)) {\n\n //createThumb(...);\n //fwrite(...);\n\n }\n\n}\n"
},
{
"answer_id": 236131,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 1,
"selected": false,
"text": "if(!file_exists($thumbsdir . '/' . $file) && preg_match('/\\.(?:jpe?g|png|gif)$/', $file)) {\n createThumb($gallerydir . '/' . $file, $thumbsdir . '/' . $file, $thumbsize);\n fwrite($log, date('Y-m-d @ H:i:s') . ' CREATED: ' . $thumbsdir . '/' . $file . \"\\n\");\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] |
217,713
|
<p>I have this HTML structure and want to convert it to an accordion.</p>
<pre><code><div class="accor">
<div class="section">
<h3>Sub section</h3>
<p>Sub section text</p>
</div>
<div class="section">
<h3>Sub section</h3>
<p>Sub section text</p>
</div>
<div class="section">
<h3>Sub section</h3>
<p>Sub section text</p>
</div>
</div>
</code></pre>
<p>Basically using the <code>h3</code>s as accordion headers, and the rest of the content in each <code>div.section</code> as the content for each accordion panel. (Also note: the headings could be anything between h2 and h6, depending on their nesting).</p>
<p>I figured that this would be easiest if the DOM tree were restructured so the <code>h3</code>s were outside each <code>div</code> since that's how the accordion works by default:</p>
<pre><code> <h3>Sub section</h3>
<div class="section">
<p>Sub section text</p>
</div>
</code></pre>
<p>The only problem is: how to move the headings around? (I don't have access to change the HTML).</p>
<pre><code>var $sections = $("div.accor > .section"),
$headings = $sections.find("> :header")
;
// I figured that inserting each heading to be before its parent might
// be the answer:
$headings.insertBefore($headings.find(":parent"));
// ... but that doesn't do anything
</code></pre>
|
[
{
"answer_id": 217721,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": true,
"text": "$.each() $headings.each(function(i, el) {\n var $this = $(el), $p = $this.parent();\n $this.insertBefore($p);\n});\n"
},
{
"answer_id": 217728,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 0,
"selected": false,
"text": "$('.accor .section').each(function() {\n $('h3', this).insertBefore($(this));\n});\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
217,718
|
<p>I would really like to annotate a method with a reference to a single property in a property file for injection.</p>
<pre><code>@Resource("${my.service.url}")
private String myServiceUrl;
</code></pre>
<p>Of course, this syntax does not work ;) Thats why I'm asking here.</p>
<p>I am aware that I can inject the full properties file, but that just seems excessive, I dont want the property file - I want the configured value.</p>
<p>Edit: I can only see PropertyPlaceholderConfigurer examples where XML is used to wire the property to the given field. I still cannot figure out how this can be achieved with an annotation ? </p>
|
[
{
"answer_id": 217882,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 0,
"selected": false,
"text": "<bean class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\">\n <property name=\"locations\">\n <value>classpath:com/foo/jdbc.properties</value>\n </property>\n</bean>\n<bean ...>\n <property name=\"myServiceUrl\" value=\"${my.service.url}\"/>\n</bean>\n"
},
{
"answer_id": 1293284,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@Component\npublic class SomeCompent{\n @Autowired(required=true \n @Resource(\"someStringBeanId\")\n private String aProperty;\n\n ...\n}\n\n<beans ....>\n <context:component-scan base-package=\"...\"/>\n\n <bean class=\"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer\">\n ...\n </bean>\n <bean id=\"someStringId\" class=\"java.lang.String\" factory-method=\"valueOf\">\n <constructor-arg value=\"${place-holder}\"/>\n </bean>\n</beans>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
217,731
|
<p>I'm in the process of trying to hack together the first bits of a kernel. I currently have the entire kernel compiled down as C code, and I've managed to get it displaying text in the console window and all of that fine goodness. Now, I want to start accepting keyboard input so I can actually make some use of the thing and get going on process management.</p>
<p>I'm using DJGPP to compile, and loading with GRUB. I'm also using a small bit of assembly which basically jumps directly into my compiled C code and I'm happy from there.</p>
<p>All the research I've done seems to point to an ISR at $0x16 to read in the next character from the keyboard buffer. From what I can tell, this is supposed to store the ASCII value in ah, and the keycode in al, or something to that effect. I'm attempting to code this using the following routine in inline assembly:</p>
<pre><code>char getc(void)
{
int output = 0;
//CRAZY VOODOO CODE
asm("xor %%ah, %%ah\n\t"
"int $0x16"
: "=a" (output)
: "a" (output)
:
);
return (char)output;
}
</code></pre>
<p>When this code is called, the core immediately crashes. (I'm running it on VirtualBox, I didn't feel the need to try something this basic on real hardware.)</p>
<p>Now I have actually a couple of questions. No one has been able to tell me if (since my code was launched from GRUB) I'm running in real mode or protected mode at the moment. I haven't made the jump one way or another, I was planning on running in real mode until I got a process handler set up.</p>
<p>So, assuming that I'm running in real mode, what am I doing wrong, and how do I fix it? I just need a basic getc routine, preferably non-blocking, but I'll be darned if google is helping on this one at all. Once I can do that, I can do the rest from there.</p>
<p>I guess what I'm asking here is, am I anywhere near the right track? How does one generally go about getting keyboard input on this level? </p>
<p>EDIT: OOhh... so I'm running in protected mode. This certainly explains the crash trying to access real mode functions then.</p>
<p>So then I guess I'm looking for how to access the keyboard IO from protected mode. I might be able to find that on my own, but if anyone happens to know feel free. Thanks again.</p>
|
[
{
"answer_id": 217750,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 1,
"selected": false,
"text": "In_Byte(KB_CMD);\n In_Byte(KB_DATA);\n KB_CMD KB_DATA"
},
{
"answer_id": 217759,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 0,
"selected": false,
"text": "console_checkkey INT 16H Function 01 console_checkkey movb $0x1, %ah\n %ah console_checkkey /*\n * int console_checkkey (void)\n * if there is a character pending, return it; otherwise return -1\n * BIOS call \"INT 16H Function 01H\" to check whether a character is pending\n * Call with %ah = 0x1\n * Return:\n * If key waiting to be input:\n * %ah = keyboard scan code\n * %al = ASCII character\n * Zero flag = clear\n * else\n * Zero flag = set\n */\n ENTRY(console_checkkey)\n push %ebp\n xorl %edx, %edx\n\n call EXT_C(prot_to_real) /* enter real mode */\n\n .code16\n\n sti /* checkkey needs interrupt on */\n\n movb $0x1, %ah\n int $0x16\n\n DATA32 jz notpending\n\n movw %ax, %dx\n //call translate_keycode\n call remap_ascii_char\n DATA32 jmp pending\n\nnotpending:\n movl $0xFFFFFFFF, %edx\n\npending:\n DATA32 call EXT_C(real_to_prot)\n .code32\n\n mov %edx, %eax\n\n pop %ebp\n ret\n"
},
{
"answer_id": 23559101,
"author": "Dirk Wolfgang Glomp",
"author_id": 2899900,
"author_profile": "https://Stackoverflow.com/users/2899900",
"pm_score": 0,
"selected": false,
"text": "Start:\n cli\n mov al,2 ; dissable IRQ 1\n out 21h,al\n sti\n\n;--------------------------------------\n; Main-Routine\nAGAIN:\n in al,64h ; get the status\n test al,1 ; check output buffer\n jz short NOKEY\n test al,20h ; check if it is a PS2Mouse-byte\n jnz short NOKEY\n in al,60h ; get the key\n\n; insert your code here (maybe for converting into ASCII...)\n\nNOKEY:\n jmp AGAIN\n;--------------------------------------\n; At the end\n cli\n xor al,al ; enable IRQ 1\n out 21h,al\n sti\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19521/"
] |
217,741
|
<p>I have the following html</p>
<pre><code> <div id="menu">
<ul class="horizMenu">
<li id="active"><a href="#" id="current">About</a></li>
<li><a href="#">Archive</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">Item four</a></li>
<li><a href="#">Item five</a></li>
</ul>
</div>
</code></pre>
<p>and in the css I have </p>
<pre><code>.horizMenu li
{
display: inline;
list-style-type: none;
padding-right: 20px;
}
#menu
{
text-align:center;
margin-bottom:10px;
letter-spacing:7px;
}
#menu a
{
color:red;
}
#menu a:hover
{
color:blue;
font-weight:bold;
}
</code></pre>
<p>Everything works pretty well, except that when I mouse over the links, the color changes and it becomes bold, which is what i want, but it also causes all of the other li elements to move slightly and then move back when you mouse-off. Is there an easy way to stop this from happening?</p>
|
[
{
"answer_id": 217744,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 2,
"selected": false,
"text": "#menu li\n{\n width: 150px;\n}\n"
},
{
"answer_id": 8672961,
"author": "Parziphal",
"author_id": 638668,
"author_profile": "https://Stackoverflow.com/users/638668",
"pm_score": 1,
"selected": false,
"text": "a:hover {\n color:blue;\n text-shadow:0px 0px 1px blue;\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
217,749
|
<p>Is there any way you can reset the visited status on links?</p>
<p>The scenario is this: On an intranet-site which naturally has a lot of links we want a link to have the status of "visited" for a set period of time only. I am therefore looking for a way to manipulate the visited status of links.</p>
<p>Is this doable? It should be cross-browser of course.</p>
<p>ETA: Client-side solutions are perfectly acceptable. Preferred even.. :-)</p>
<p>ETA-2: Cookies are allowed. No holds barred here :-)</p>
|
[
{
"answer_id": 217783,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 3,
"selected": false,
"text": ":visited visited"
},
{
"answer_id": 219435,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 3,
"selected": false,
"text": ":visited function clickHandler(event) {\n var href = /* (figure out which anchor was clicked and get the href) */\n // (you might need to escape the href)\n\n setCookie(href, \"visited\", 5); // set cookie for 5 days\n}\n function markVisitedLinks() {\n var anchors = document.getElementsByTagName(\"a\");\n\n for (var i = 0; i < anchors.length; i++) {\n if (readCookie(anchors[i].href) == \"visited\") {\n anchors[i].className += \" visited\";\n }\n }\n}\n"
},
{
"answer_id": 219515,
"author": "schonarth",
"author_id": 22116,
"author_profile": "https://Stackoverflow.com/users/22116",
"pm_score": 2,
"selected": false,
"text": ":visited a, a:visited {\n color: blue;\n text-decoration: underline\n }\n\n a:hover, a:active {\n color: orange;\n }\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4192/"
] |
217,761
|
<p>I would like to know if there is a way to disable automatic loading of child records in nHibernate ( for one:many relationships ).</p>
<p>We can easily switch off lazy loading on properties but what I want is to disable any kind of automatic loading ( lazy and non lazy both ). I only want to load data via query ( i.e. HQL or Criteria )</p>
<p>I would still like to define the relationship between parent child records in the mapping file to facilitate HQL and be able to join parent child entities, but I do not want the child records to be loaded as part of the parent record unless a query on the parent record
explicitly states that ( via eager fetch, etc ).</p>
<p>Example:
Fetching Department record from the database should not fetch all employee records from the database because it may never be needed.</p>
<p>One option here is to set the Employees collection on Department as lazy load. The problem with this approach is that once the object is given to the calling API it can 'touch' the lazy load property and that will fetch the entire list from the db.</p>
<p>I tried to use 'evict' - to disconnect the object but it does not seem to be working at all times and does not do a deep evict on the object.
Plus it abstracts the lazy loaded property type with a proxy class that plays havoc later in the code where we are trying to operate on the object via reflection and it encounters unexpended type on the object.</p>
<p>I am a beginner to nHibernate, any pointers or help would be of great help.</p>
|
[
{
"answer_id": 229701,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 3,
"selected": true,
"text": " public class Department \n { \n public int Id { get; protected set; }\n public string Name { get; set; }\n /* Equality and GetHashCode here */\n }\n public class Employee\n { \n public int Id { get; protected set; }\n public Name Name { get; set; }\n public Department Department { get; set; }\n /* Equality and GetHashCode here */\n }\n /*...*/\nsession.CreateCriteria(typeof(Employee))\n .Add(Restrictions.Eq(\"Department\", department)\n .List<Employee>();\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29443/"
] |
217,765
|
<p>I have a query that I use for charting in reporting services that looks something like:</p>
<pre>
(SELECT Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu,Nu, Xi from tbl
WHERE
Alpha in (@Alphas) and
Beta in (@Betas) and
Gamma in (@Gammas) and
Delta in (@Deltas) and
Epsilon in (@Epsilons) and
Zeta in (@Zetas) and
Eta in (@Etas) and
Theta in (@Thetas) )
UNION
(SELECT Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu,Nu, Omicron from tbl
WHERE
Alpha in (@Alphas) and
Beta in (@Betas) and
Gamma in (@Gammas) and
Delta in (@Deltas) and
Epsilon in (@Epsilons) and
Zeta in (@Zetas) and
Eta in (@Etas) and
Theta in (@Thetas))
</pre>
<p>Alpha through Theta are to be used to in a couple of calculated fields which concatenate them (say Alpha, Beta, Gamma) into a string in one field. The select statement for Omicron will generate the same number of rows as Xi but what I really want is to aggregate Omicron, so if the Select query with Xi produces 9 legend item, the aggregate select for Omicron should only produce one legend item because the values Alpha through Theta are not important for Omicron. How should the query be structured so I can use Alpha through Theta as parameters but still aggregate Omicron? </p>
|
[
{
"answer_id": 217774,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "(SELECT a,b,c,d FROM k\nWHERE a in (@a) and b in (@b) and c in (@c))\nUNION\n(SELECT NULL,NULL,NULL,sum(e) FROM k\nWHERE a in (@a) and b in (@b) and c in (@c) GROUP BY e)\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20879/"
] |
217,769
|
<p>I am <a href="https://stackoverflow.com/questions/211260/perl-extract-text-then-save<br">searching</a> for HF50(HF$HF) for example in "MyFile.txt" so that the extracted data must save to "save.txt". The data on "save.txt" now extracted again and fill the parameters and output on my table. But when I tried the code, I've got no output and "save.txt" is blank.?</p>
<p>Var $HF is not recognized whatever I type. Please help.</p>
<pre><code>#! /usr/bin/perl
print "Content-type:text/html\r\n\r\n";
use CGI qw(:standard);
use strict;
use warnings;
my ($file,$line,$tester,$HF,$keyword);
my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19);
my $keyWord=param('keyword');
$HF=$keyWord;
my $infile='MyFile.txt';
my $outfile='save.txt';
open (my $inhandle, '<',$infile) or die "Can't open $infile:$!";
open (my $outhandle, '>', $outfile) or die "Can't open $outfile:$!";
while (my $line=<$inhandle>){
if ($line=~ m/HF$HF/i) {
print {$outhandle}$line;
print $line;
print "<HTML>";
print "<head>";
print "<body bgcolor='#4682B4'>";
print "<title>FUSION SHIFT REPORT</title>";
print "<div align='left'>";
print "<FORM METHOD='get' ACTION='http://Shielex.com/pe/mrigos/mainhead.html'>";
print "<b>SEACRH:</b>";
print "<INPUT TYPE='text' NAME='rec' SIZE='12' MAXLENGHT='40'>";
print "<INPUT TYPE='submit' value='go'>";
print "</form>";
print "<TABLE CELLPADDING='1' CELLSPACING='1' BORDER='1' bordercolor=black width='100%'>";
print "<TR>";
print "<td width='11%'bgcolor='#00ff00'><font size='2'>TESTER No.</td>";
print "<td width='10%'bgcolor='#00ff00'><font size='2'>DATE</td>";
print "<td width='11%'bgcolor='#00ff00'><font size='2'>DEVICE NAME</td>";
print "<td bgcolor='#00ff00'><font size='2'>TEST PROGRAM</td>";
print "<td width='10%'bgcolor='#00ff00'><font size='2'>SMSLOT</td>";
print "<td width='12%'bgcolor='#00ff00'><font size='2'>LOADBOARD</td>";
print "<td width='10%'bgcolor='#00ff00'><font size='2'>CATEGORY</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 1</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 2</td>";
print "</tr>";
print "<TR>";
$file='save.txt';
open(F,$file)||die("Could not open $file");
while ($line=<F>)
{
my @cells=($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19)= split ',',$line;
print "<TD bgcolor='#ADD8E6'><font size='2'>$f2</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f3</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f5</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f6</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f8</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f10</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f17</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f18</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f19</TD>";
print "</tr>";
}
}
}
close F;
print "</TABLE>";
print "</body>";
print "<html>";
</code></pre>
<p><br></p>
<p>=<strong>MyFile.txt data</strong>=<br>
1,HF50,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br>
2,HF60,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br>
1,HF50,13-OCT-08,04:17:53,761503BZZGR-62,B2761503BP22.EVA,DWP,DWP,Calibration<br></p>
|
[
{
"answer_id": 217872,
"author": "Corion",
"author_id": 11253,
"author_profile": "https://Stackoverflow.com/users/11253",
"pm_score": 0,
"selected": false,
"text": "$outfile open()"
},
{
"answer_id": 218689,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 1,
"selected": false,
"text": "die"
},
{
"answer_id": 219112,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": -1,
"selected": false,
"text": "use CGI qw(:standard);\nuse IO::File;\nuse strict;\nuse warnings;\n\nmy ($file,$line,$HF); #,$tester,$HF,$keyword);\n# don't pollute -> my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10\n# ,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19);\n\n\n# my $keyWord=param('keyword'); <-- if you're not going to do anything with $keyWord\n$HF=param('keyword'); # <- assign it to the variable you're going to use\n\nmy $infile='MyFile.txt';\nmy $outfile='save.txt';\n\nopen (my $inhandle, '<',$infile) or die \"Can't open $infile:$!\";\nopen (my $outhandle, '>', $outfile) or die \"Can't open $outfile:$!\";\n# this would flush -> my $outhandle = IO::File->new( \">$outfile\" );\n\nprint q{Content-type:text/html\n\n<HTML>\n<head>\n<title>FUSION SHIFT REPORT</title>\n<style type=\"text/css\">\n.header { background-color : #0f0; font-size : 12pt }\n.detail { background-color : #ADD8E6; font-size : 12pt }\n</style>\n</head>\n<body bgcolor='#4682B4'>\n<div align='left'>\n<FORM METHOD='get' ACTION='http://Shielex.com/pe/mrigos/mainhead.html'>\n<b>SEACRH:</b>\n<input type='text' name='rec' size='12' maxlenght='40'>\n<input type='submit' value='go'>\n</form>\n<table cellpadding='1' cellspacing='1' border='1' bordercolor=black width='100%'>\n<tr>\n <td class=\"header\" width='11%'>TESTER No.</td>\n <td class=\"header\" width='10%'>DATE</td>\n <td class=\"header\" width='11%'>DEVICE NAME</td>\n <td class=\"header\" >TEST PROGRAM</td>\n <td class=\"header\" width='10%'>SMSLOT</td>\n <td class=\"header\" width='12%'>LOADBOARD</td>\n <td class=\"header\" width='10%'>CATEGORY</td>\n <td class=\"header\" width='13%'>ROOT CAUSE 1</td>\n <td class=\"header\" width='13%'>ROOT CAUSE 2</td>\n</tr>\n}; \n\nmy $hf_str = \",HF$HF,\";\n# OO -> $outhandle->autoflush(); <- set autoflush\nwhile (my $line=<$inhandle>){\n next unless index( $line, $hf_str ) > -1;\n # OO -> $outhandle->print( $line );\n # $outhandle->flush(); <- if autoflush not set, do it manually\n print *{$outhandle} $line;\n print \"<tr>\"\n , ( map { qq{<td class=\"detail\">$_</td>} } \n split ',', $line\n )\n , \"</tr>\\n\"\n ;\n}\nprint q{\n</table>\n</body>\n</html>\n};\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28607/"
] |
217,776
|
<p>I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?</p>
|
[
{
"answer_id": 217820,
"author": "Horst Gutmann",
"author_id": 22312,
"author_profile": "https://Stackoverflow.com/users/22312",
"pm_score": 6,
"selected": false,
"text": "var frm = frames['frame'].document;\nvar otherhead = frm.getElementsByTagName(\"head\")[0];\nvar link = frm.createElement(\"link\");\nlink.setAttribute(\"rel\", \"stylesheet\");\nlink.setAttribute(\"type\", \"text/css\");\nlink.setAttribute(\"href\", \"style.css\");\notherhead.appendChild(link);\n"
},
{
"answer_id": 217833,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 9,
"selected": false,
"text": "<iframe name=\"iframe1\" id=\"iframe1\" src=\"empty.htm\" \n frameborder=\"0\" border=\"0\" cellspacing=\"0\"\n style=\"border-style: none;width: 100%; height: 120px;\"></iframe>\n <link type=\"text/css\" rel=\"Stylesheet\" href=\"Style/simple.css\" />\n var cssLink = document.createElement(\"link\");\ncssLink.href = \"style.css\"; \ncssLink.rel = \"stylesheet\"; \ncssLink.type = \"text/css\"; \nframes['iframe1'].document.head.appendChild(cssLink);\n"
},
{
"answer_id": 1197178,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "var cssLink = document.createElement(\"link\") \ncssLink.href = \"pFstylesEditor.css\"; \ncssLink.rel = \"stylesheet\"; \ncssLink.type = \"text/css\"; \n\n//Instead of this\n//frames['frame1'].document.body.appendChild(cssLink);\n//Do this\n\nvar doc=document.getElementById(\"edit\").contentWindow.document;\n\n//If you are doing any dynamic writing do that first\ndoc.open();\ndoc.write(myData);\ndoc.close();\n\n//Then append child\ndoc.body.appendChild(cssLink);\n"
},
{
"answer_id": 2361446,
"author": "sorin",
"author_id": 99834,
"author_profile": "https://Stackoverflow.com/users/99834",
"pm_score": 4,
"selected": false,
"text": "<IFRAME> iframe robots.txt <html>\n <header>\n <script src=\"/js/jquery.js\" type=\"text/javascript\"></script>\n </header>\n <body>\n <div id='include-from-outside'></div>\n <script type='text/javascript'>\n $('#include-from-outside').load('http://example.com/included.html');\n </script> \n </body>\n</html>\n"
},
{
"answer_id": 4121704,
"author": "parham fazel",
"author_id": 500381,
"author_profile": "https://Stackoverflow.com/users/500381",
"pm_score": 3,
"selected": false,
"text": "doc.open();\n\ndoc.write('<!DOCTYPE html><html><head><meta charset=\"utf-8\"/><meta http-quiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>Print Frame</title><link rel=\"stylesheet\" type=\"text/css\" href=\"/css/print.css\"/></head><body><table id=\"' + gridId + 'Printable' + '\" class=\"print\" >' + out + '</table></body></html>');\n\ndoc.close();\n"
},
{
"answer_id": 4386073,
"author": "JannuD",
"author_id": 534801,
"author_profile": "https://Stackoverflow.com/users/534801",
"pm_score": -1,
"selected": false,
"text": "iframe iframe div divClass { width: 500px; height: 500px; }\ndivClass iframe { width: 100%; height: 100%; }\n"
},
{
"answer_id": 6100053,
"author": "peter",
"author_id": 766356,
"author_profile": "https://Stackoverflow.com/users/766356",
"pm_score": 4,
"selected": false,
"text": "var iframe = top.frames[name].document;\nvar css = '' +\n '<style type=\"text/css\">' +\n 'body{margin:0;padding:0;background:transparent}' +\n '</style>';\niframe.open();\niframe.write(css);\niframe.close();\n"
},
{
"answer_id": 12521755,
"author": "SequenceDigitale.com",
"author_id": 489281,
"author_profile": "https://Stackoverflow.com/users/489281",
"pm_score": 8,
"selected": false,
"text": "file_get_contents google.php $content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');\n $content = str_replace('</head>','<link rel=\"stylesheet\" href=\"http://www.yourwebsiteurl.com/google.css\" /></head>', $content);\n head $content = str_replace('</title>','</title><base href=\"https://www.google.com/calendar/\" />', $content);\n google.php <?php\n$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');\n$content = str_replace('</title>','</title><base href=\"https://www.google.com/calendar/\" />', $content);\n$content = str_replace('</head>','<link rel=\"stylesheet\" href=\"http://www.yourwebsiteurl.com/google.css\" /></head>', $content);\necho $content;\n iframe <iframe src=\"http://www.yourwebsiteurl.com/google.php\" style=\"border: 0\" width=\"800\" height=\"600\" frameborder=\"0\" scrolling=\"no\"></iframe>\n"
},
{
"answer_id": 13497458,
"author": "Rami Sarieddine",
"author_id": 694697,
"author_profile": "https://Stackoverflow.com/users/694697",
"pm_score": 6,
"selected": false,
"text": "var $head = $(\"#eFormIFrame\").contents().find(\"head\");\n\n$head.append($(\"<link/>\", {\n rel: \"stylesheet\",\n href: url,\n type: \"text/css\"\n}));\n"
},
{
"answer_id": 15543234,
"author": "Chris W",
"author_id": 890258,
"author_profile": "https://Stackoverflow.com/users/890258",
"pm_score": 4,
"selected": false,
"text": "<script type=\"text/javascript\">\n$(window).load(function () {\n var frame = $('iframe').get(0);\n if (frame != null) {\n var frmHead = $(frame).contents().find('head');\n if (frmHead != null) {\n frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link\n //frmHead.append($(\"<link/>\", { rel: \"stylesheet\", href: \"/styles/style.css\", type: \"text/css\" })); // or create css link yourself\n }\n } \n});\n</script>\n iframe <script type=\"text/javascript\">\nvar frameListener;\n$(window).load(function () {\n frameListener = setInterval(\"frameLoaded()\", 50);\n});\nfunction frameLoaded() {\n var frame = $('iframe').get(0);\n if (frame != null) {\n var frmHead = $(frame).contents().find('head');\n if (frmHead != null) {\n clearInterval(frameListener); // stop the listener\n frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link\n //frmHead.append($(\"<link/>\", { rel: \"stylesheet\", href: \"/styles/style.css\", type: \"text/css\" })); // or create css link yourself\n }\n }\n}\n</script>\n <script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js\" type=\"text/javascript\"></script>\n"
},
{
"answer_id": 17274115,
"author": "David Bradshaw",
"author_id": 2087070,
"author_profile": "https://Stackoverflow.com/users/2087070",
"pm_score": 4,
"selected": false,
"text": "$('iframe').each(function(){\n function injectCSS(){\n $iframe.contents().find('head').append(\n $('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })\n );\n }\n\n var $iframe = $(this);\n $iframe.on('load', injectCSS);\n injectCSS();\n});\n"
},
{
"answer_id": 19392394,
"author": "domih",
"author_id": 1037303,
"author_profile": "https://Stackoverflow.com/users/1037303",
"pm_score": 5,
"selected": false,
"text": "<link> var head = jQuery(\"#iframe\").contents().find(\"head\");\nvar css = '<style type=\"text/css\">' +\n '#banner{display:none}; ' +\n '</style>';\njQuery(head).append(css);\n"
},
{
"answer_id": 25058990,
"author": "Mateusz Winnicki",
"author_id": 2665870,
"author_profile": "https://Stackoverflow.com/users/2665870",
"pm_score": 2,
"selected": false,
"text": "z-index pointer-events:none"
},
{
"answer_id": 25626877,
"author": "Palanikumar",
"author_id": 1019435,
"author_profile": "https://Stackoverflow.com/users/1019435",
"pm_score": 2,
"selected": false,
"text": "<style type=\"text/css\" id=\"cssID\">\n.className\n{\n background-color: red;\n}\n</style>\n\n<iframe id=\"iFrameID\"></iframe>\n\n<script type=\"text/javascript\">\n $(function () {\n $(\"#iFrameID\").contents().find(\"head\")[0].appendChild(cssID);\n //Or $(\"#iFrameID\").contents().find(\"head\")[0].appendChild($('#cssID')[0]);\n });\n</script>\n"
},
{
"answer_id": 29125231,
"author": "jperelli",
"author_id": 912450,
"author_profile": "https://Stackoverflow.com/users/912450",
"pm_score": 2,
"selected": false,
"text": "<style id=\"iframestyle\">\n html {\n color: white;\n background: black;\n }\n</style>\n<style>\n html {\n color: initial;\n background: initial;\n }\n iframe {\n border: none;\n }\n</style>\n <iframe onload=\"iframe.document.head.appendChild(ifstyle)\" name=\"log\" src=\"/upgrading.log\"></iframe>\n <script>\n ifstyle = document.getElementById('iframestyle')\n iframe = top.frames[\"log\"];\n</script>\n"
},
{
"answer_id": 37333258,
"author": "CodeRows",
"author_id": 4724402,
"author_profile": "https://Stackoverflow.com/users/4724402",
"pm_score": 2,
"selected": false,
"text": "postMessage() iframenode.postMessage('h2{color:red;}','*');\n * window.addEventListener('message',function(e){\n\n if(e.data == 'send_user_details')\n document.head.appendChild('<style>'+e.data+'</style>');\n\n});\n"
},
{
"answer_id": 38236118,
"author": "2540625",
"author_id": 2540625,
"author_profile": "https://Stackoverflow.com/users/2540625",
"pm_score": 3,
"selected": false,
"text": "<style> var iframe = document.getElementById('the-iframe');\nvar style = document.createElement('style');\nstyle.textContent =\n '.some-class-name {' +\n ' some-style-name: some-value;' +\n '}' \n;\niframe.contentDocument.head.appendChild(style);\n"
},
{
"answer_id": 39839199,
"author": "karlisup",
"author_id": 492457,
"author_profile": "https://Stackoverflow.com/users/492457",
"pm_score": 1,
"selected": false,
"text": "// Single node\nvar component = document.querySelector('.component');\nvar iframe = iframify(component);\n\n// Collection of nodes\nvar components = document.querySelectorAll('.component');\nvar iframes = Array.prototype.map.call(components, function (component) {\n return iframify(component, {});\n});\n\n// With options\nvar component = document.querySelector('.component');\nvar iframe = iframify(component, {\n headExtra: '<style>.component { color: red; }</style>',\n metaViewport: '<meta name=\"viewport\" content=\"width=device-width\">'\n});\n"
},
{
"answer_id": 40081245,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": 0,
"selected": false,
"text": "style http://your_site.com/target.php?color=red\n a{color:red} urlencode target.php <head>\n..........\n$col = FILTER_VAR(SANITIZE_STRING, $_GET['color']);\n<style>.xyz{color: <?php echo (in_array( $col, ['red','yellow','green'])? $col : \"black\") ;?> } </style>\n..........\n"
},
{
"answer_id": 40297501,
"author": "Jeeva",
"author_id": 4737293,
"author_profile": "https://Stackoverflow.com/users/4737293",
"pm_score": 2,
"selected": false,
"text": "var link1 = document.createElement('link');\n link1.type = 'text/css';\n link1.rel = 'stylesheet';\n link1.href = \"../../assets/css/normalize.css\";\nwindow.frames['richTextField'].document.body.appendChild(link1);"
},
{
"answer_id": 41372866,
"author": "K.Suthagar",
"author_id": 6072891,
"author_profile": "https://Stackoverflow.com/users/6072891",
"pm_score": 2,
"selected": false,
"text": "id class <style>\n#my_iFrame{\nheight: 300px;\nwidth: 100%;\nposition:absolute;\ntop:0;\nleft:0;\nborder: 1px black solid;\n}\n</style>\n\n<iframe name='iframe1' id=\"my_iFrame\" src=\"#\" cellspacing=\"0\"></iframe>\n var cssFile = document.createElement(\"link\") \ncssFile.rel = \"stylesheet\"; \ncssFile.type = \"text/css\"; \ncssFile.href = \"iFramePage.css\"; \n //to Load in the Body Part\nframes['my_iFrame'].document.body.appendChild(cssFile); \n//to Load in the Head Part\nframes['my_iFrame'].document.head.appendChild(cssFile);\n var $iFrameHead = $(\"#my_iFrame\").contents().find(\"head\");\n$iFrameHead.append(\n $(\"<link/>\",{ \n rel: \"stylesheet\", \n href: urlPath, \n type: \"text/css\" }\n ));\n"
},
{
"answer_id": 45998038,
"author": "Therichpost",
"author_id": 2595012,
"author_profile": "https://Stackoverflow.com/users/2595012",
"pm_score": 4,
"selected": false,
"text": "$('iframe').load( function() {\n $('iframe').contents().find(\"head\")\n .append($(\"<style type='text/css'> .my-class{display:none;} </style>\"));\n });\n"
},
{
"answer_id": 58722845,
"author": "Supun Kavinda",
"author_id": 9059939,
"author_profile": "https://Stackoverflow.com/users/9059939",
"pm_score": 4,
"selected": false,
"text": "/**\n * Creates a messenger between two windows\n * which have two different domains\n */\nclass CrossMessenger {\n\n /**\n * \n * @param {object} otherWindow - window object of the other\n * @param {string} targetDomain - domain of the other window\n * @param {object} eventHandlers - all the event names and handlers\n */\n constructor(otherWindow, targetDomain, eventHandlers = {}) {\n this.otherWindow = otherWindow;\n this.targetDomain = targetDomain;\n this.eventHandlers = eventHandlers;\n\n window.addEventListener(\"message\", (e) => this.receive.call(this, e));\n }\n\n post(event, data) {\n\n try {\n // data obj should have event name\n var json = JSON.stringify({\n event,\n data\n });\n this.otherWindow.postMessage(json, this.targetDomain);\n\n } catch (e) {}\n }\n\n receive(e) {\n var json;\n try {\n json = JSON.parse(e.data ? e.data : \"{}\");\n } catch (e) {\n return;\n }\n var eventName = json.event,\n data = json.data;\n\n if (e.origin !== this.targetDomain)\n return;\n\n if (typeof this.eventHandlers[eventName] === \"function\") \n this.eventHandlers[eventName](data);\n }\n\n}\n var msger = new CrossMessenger(iframe.contentWindow, \"https://iframe.s.domain\");\n\nvar cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('\\n');\nmsger.post(\"cssContent\", {\n css: cssContent\n})\n var msger = new CrossMessenger(window.parent, \"https://parent.window.domain\", {\n cssContent: (data) => {\n var cssElem = document.createElement(\"style\");\n cssElem.innerHTML = data.css;\n document.head.appendChild(cssElem);\n }\n})\n"
},
{
"answer_id": 69998041,
"author": "Diego Fortes",
"author_id": 4781067,
"author_profile": "https://Stackoverflow.com/users/4781067",
"pm_score": 2,
"selected": false,
"text": " var $iframe = document.querySelector(`iframe`);\n var doc = $iframe.contentDocument;\n\n var style = doc.createElement(\"style\");\n style.textContent = `*{display:none!important;}`;\n doc.head.append(style);\n load var $iframe = document.querySelector(`iframe`);\n\n$iframe.addEventListener(\"load\", function() {\n var doc = $iframe.contentDocument;\n var style = doc.createElement(\"style\");\n style.textContent = `*{display:none!important;}`;\n doc.head.append(style);\n});\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,793
|
<p>Is there a way in Delphi to get the currect application's exe size in one or two lines of code?</p>
|
[
{
"answer_id": 217824,
"author": "Daniel Rikowski",
"author_id": 23368,
"author_profile": "https://Stackoverflow.com/users/23368",
"pm_score": 2,
"selected": false,
"text": "Application.ExeName FileOpen FileSize TFileStream size CreateFile GetFileSize FindFirst TSearchRec.FindData.nFileSizeLow nFileSizeHigh System.IO.FileInfo FileInfo.Create(filename).Length lstat64 Libc TStatBuf64.st_size"
},
{
"answer_id": 217856,
"author": "Germán Estévez -Neftalí-",
"author_id": 17487,
"author_profile": "https://Stackoverflow.com/users/17487",
"pm_score": 2,
"selected": false,
"text": " if FindFirst(ExpandFileName(Application.exename), faAnyFile, SearchRec) = 0 then\n MessageDlg(Format('Tamaño: <%d>',[SearchRec.Size]), mtInformation, [mbOK], 0);\n FindClose(SearchRec);\n"
},
{
"answer_id": 218662,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 5,
"selected": true,
"text": "var\n fs : tFilestream;\nbegin\n fs := tFilestream.create(paramstr(0),fmOpenRead or fmShareDenyNone);\n try\n result := fs.size;\n finally\n fs.free;\n end;\nend;\n"
},
{
"answer_id": 218753,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 2,
"selected": false,
"text": "with TFilestream.create(paramstr(0), fmOpenRead or fmShareDenyNone) do \n aFileSize := Size;\n Free;\nend;\n function DSiFileSize(const fileName: string): int64;\nvar\n fHandle: DWORD;\nbegin\n fHandle := CreateFile(PChar(fileName), 0, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);\n if fHandle = INVALID_HANDLE_VALUE then\n Result := -1\n else try\n Int64Rec(Result).Lo := GetFileSize(fHandle, @Int64Rec(Result).Hi);\n finally CloseHandle(fHandle); end;\nend; { DSiFileSize }\n"
},
{
"answer_id": 221623,
"author": "Mohammed Nasman",
"author_id": 24462,
"author_profile": "https://Stackoverflow.com/users/24462",
"pm_score": 0,
"selected": false,
"text": " with tFilestream.create(paramstr(0),fmOpenRead or fmShareDenyNone) do\n ShowMessage(IntToStr(size));\n"
},
{
"answer_id": 221694,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "procedure TForm1.Button1Click(Sender: TObject);\nbegin\n with TFileStream.Create(Application.ExeName,fmShareDenyNone) do\n ShowMessage(FloatToStr(Size/1024));\nend;\n"
},
{
"answer_id": 11808287,
"author": "tz.",
"author_id": 267377,
"author_profile": "https://Stackoverflow.com/users/267377",
"pm_score": 2,
"selected": false,
"text": "uses IdGlobalProtocols;\n\nvar\n ExeSize: Int64;\nbegin\n ExeSize := FileSizeByName(ParamStr(0)); \n // or\n ExeSize := FileSizeByName(Application.ExeName);\nend;\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
] |
217,801
|
<p>Anyone have any idea how to get the value of "Language for Non-Unicode Programs" in Control Panel Regional Settings programmatically using c#?</p>
<p>Already tried CultureInfo, RegionInfo and getting the default encoding using the Encoding object, but I can only get the Standards and Formats value or the main code page. </p>
|
[
{
"answer_id": 217858,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 0,
"selected": false,
"text": "Thread.CurrentUICulture"
},
{
"answer_id": 46383388,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 1,
"selected": false,
"text": "GetACP GetOEMCP"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18494/"
] |
217,805
|
<p>What is the most efficient way to write the old-school:</p>
<pre><code>StringBuilder sb = new StringBuilder();
if (strings.Count > 0)
{
foreach (string s in strings)
{
sb.Append(s + ", ");
}
sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();
</code></pre>
<p>...in LINQ?</p>
|
[
{
"answer_id": 122706,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 6,
"selected": false,
"text": "var sa = (new[] { \"yabba\", \"dabba\", \"doo\" }).Aggregate((a,b) => a + \",\" + b);\n"
},
{
"answer_id": 122760,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 7,
"selected": false,
"text": "string[] s = {\"foo\", \"bar\", \"baz\"};\nConsole.WriteLine(String.Join(\", \", s));\n IEnumerable<string> Aggregate"
},
{
"answer_id": 217813,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 6,
"selected": false,
"text": "return selected.Select(query => query.Name).Aggregate((a, b) => a + \", \" + b);\n"
},
{
"answer_id": 217814,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 10,
"selected": true,
"text": "Aggregate StringBuilder String.Join string[] words = { \"one\", \"two\", \"three\" };\nvar res = words.Aggregate(\n \"\", // start with empty string to handle empty list case.\n (current, next) => current + \", \" + next);\nConsole.WriteLine(res);\n Aggregate StringBuilder String.Join var res = words.Aggregate(\n new StringBuilder(), \n (current, next) => current.Append(current.Length == 0? \"\" : \", \").Append(next))\n .ToString();\n"
},
{
"answer_id": 218419,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 9,
"selected": false,
"text": "return string.Join(\", \", strings.ToArray());\n string.Join IEnumerable<string> return string.Join(\", \", strings);\n"
},
{
"answer_id": 840836,
"author": "Kieran Benton",
"author_id": 5777,
"author_profile": "https://Stackoverflow.com/users/5777",
"pm_score": 4,
"selected": false,
"text": "public static string JoinAsString<T>(this IEnumerable<T> input, string seperator)\n{\n var ar = input.Select(i => i.ToString());\n return string.Join(seperator, ar);\n}\n"
},
{
"answer_id": 1737341,
"author": "Patrik Hägne",
"author_id": 46187,
"author_profile": "https://Stackoverflow.com/users/46187",
"pm_score": 0,
"selected": false,
"text": "var sequence = new string[] { \"foo\", \"bar\" };\nstring result = sequence.Concatenate();\n var methodNames = typeof(IFoo).GetMethods().Select(x => x.Name);\nstring result = methodNames.Concatenate(\", \");\n"
},
{
"answer_id": 2686167,
"author": "Kelly",
"author_id": 107945,
"author_profile": "https://Stackoverflow.com/users/107945",
"pm_score": 2,
"selected": false,
"text": "StringBuilder builder = new StringBuilder();\nList<string> MyList = new List<string>() {\"one\",\"two\",\"three\"};\n\nMyList.ForEach(w => builder.Append(builder.Length > 0 ? \", \" + w : w));\nreturn builder.ToString();\n"
},
{
"answer_id": 2806960,
"author": "user337754",
"author_id": 337754,
"author_profile": "https://Stackoverflow.com/users/337754",
"pm_score": 5,
"selected": false,
"text": " [TestMethod()]\n public void LINQ_StringBuilder()\n {\n IList<int> ints = new List<int>();\n for (int i = 0; i < 3000;i++ )\n {\n ints.Add(i);\n }\n StringBuilder idString = new StringBuilder();\n foreach (int id in ints)\n {\n idString.Append(id + \", \");\n }\n }\n [TestMethod()]\n public void LINQ_SELECT()\n {\n IList<int> ints = new List<int>();\n for (int i = 0; i < 3000; i++)\n {\n ints.Add(i);\n }\n string ids = ints.Select(query => query.ToString())\n .Aggregate((a, b) => a + \", \" + b);\n }\n"
},
{
"answer_id": 2869220,
"author": "jonathan.s",
"author_id": 345486,
"author_profile": "https://Stackoverflow.com/users/345486",
"pm_score": 5,
"selected": false,
"text": "StringBuilder Aggregate List<string> strings = new List<string>() { \"one\", \"two\", \"three\" };\n\n StringBuilder sb = strings\n .Select(s => s)\n .Aggregate(new StringBuilder(), (ag, n) => ag.Append(n).Append(\", \"));\n\n if (sb.Length > 0) { sb.Remove(sb.Length - 2, 2); }\n\n Console.WriteLine(sb.ToString());\n Select"
},
{
"answer_id": 4872439,
"author": "Andiih",
"author_id": 107565,
"author_profile": "https://Stackoverflow.com/users/107565",
"pm_score": 2,
"selected": false,
"text": "string.join() filterset = String.Join(\",\",\n filterset.Split(',')\n .Where(f => mycomplicatedMatch(f,paramToMatch))\n );\n"
},
{
"answer_id": 7274252,
"author": "Chris Marisic",
"author_id": 37055,
"author_profile": "https://Stackoverflow.com/users/37055",
"pm_score": 2,
"selected": false,
"text": "List<string> strings = new List<string>() { \"one\", \"two\", \"three\" };\n\nstring concat = strings \n .Aggregate(new StringBuilder(\"\\a\"), \n (current, next) => current.Append(\", \").Append(next))\n .ToString()\n .Replace(\"\\a, \",string.Empty); \n .Replace(\"\\a\",string.Empty);"
},
{
"answer_id": 8509923,
"author": "Andy S.",
"author_id": 1016519,
"author_profile": "https://Stackoverflow.com/users/1016519",
"pm_score": 1,
"selected": false,
"text": " static void Main(string[] args)\n {\n\n Debug.WriteLine(DateTime.Now.ToString() + \" entering main\");\n\n // USED THIS DOS COMMAND TO GET ALL THE DAILY FILES INTO A SINGLE FILE: copy *.log target.log \n string[] lines = File.ReadAllLines(@\"C:\\Log File Analysis\\12-8 E5.log\");\n\n Debug.WriteLine(lines.Count().ToString());\n\n string[] a = lines.Where(x => !x.StartsWith(\"#Software:\") &&\n !x.StartsWith(\"#Version:\") &&\n !x.StartsWith(\"#Date:\") &&\n !x.StartsWith(\"#Fields:\") &&\n !x.Contains(\"_vti_\") &&\n !x.Contains(\"/c$\") &&\n !x.Contains(\"/favicon.ico\") &&\n !x.Contains(\"/ - 80\")\n ).ToArray();\n\n Debug.WriteLine(a.Count().ToString());\n\n string[] b = a\n .Select(l => l.Split(' '))\n .Select(words => string.Join(\",\", words))\n .ToArray()\n ;\n\n System.IO.File.WriteAllLines(@\"C:\\Log File Analysis\\12-8 E5.csv\", b);\n\n Debug.WriteLine(DateTime.Now.ToString() + \" leaving main\");\n\n }\n string[] b = a\n .Select(l => l.Split(' '))\n .Where(l => l.Length > 11)\n .Select(words => string.Format(\"{0},{1}\",\n words[6].ToUpper(), // virtual dir / service\n words[10]) // client ip\n ).Distinct().ToArray()\n ;\n"
},
{
"answer_id": 10618698,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 4,
"selected": false,
"text": "int totalEven = Enumerable.Sum(Enumerable.Where(myInts, i => i % 2 == 0));\n int totalEven = myInts.Where(i => i % 2 == 0).Sum();\n String.Join String.Join sa.Concatenate(\", \") public static class EnumerableStringExtensions\n{\n public static string Concatenate(this IEnumerable<string> strings, string separator)\n {\n return String.Join(separator, strings);\n }\n}\n"
},
{
"answer_id": 12242029,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 3,
"selected": false,
"text": "static string StringJoin(string sep, IEnumerable<string> strings) {\n return strings\n .Skip(1)\n .Aggregate(\n new StringBuilder().Append(strings.FirstOrDefault() ?? \"\"), \n (sb, x) => sb.Append(sep).Append(x));\n}\n"
},
{
"answer_id": 12734070,
"author": "brichins",
"author_id": 957950,
"author_profile": "https://Stackoverflow.com/users/957950",
"pm_score": 5,
"selected": false,
"text": "string Result = String.Join(\",\", split.Select(s => s.Name)); s string Result = String.Join(\",\", split.Select(s => s.ToString())); StringBuilder for foreach"
},
{
"answer_id": 73992905,
"author": "Alex from Jitbit",
"author_id": 56621,
"author_profile": "https://Stackoverflow.com/users/56621",
"pm_score": 0,
"selected": false,
"text": "string.Join .Aggregate"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
217,816
|
<p>I build VBA applications for both Word and Excel, is there any way to access the progress bar that sometimes appears in the Office status bar.</p>
|
[
{
"answer_id": 217840,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 0,
"selected": false,
"text": "Sub StatusBarExample()\n Application.ScreenUpdating = False \n ' turns off screen updating\n Application.DisplayStatusBar = True \n ' makes sure that the statusbar is visible\n Application.StatusBar = \"Please wait while performing task 1...\"\n ' add some code for task 1 that replaces the next sentence\n Application.Wait Now + TimeValue(\"00:00:02\")\n Application.StatusBar = \"Please wait while performing task 2...\"\n ' add some code for task 2 that replaces the next sentence\n Application.Wait Now + TimeValue(\"00:00:02\")\n Application.StatusBar = False \n ' gives control of the statusbar back to the programme\nEnd Sub\n"
},
{
"answer_id": 227229,
"author": "KnomDeGuerre",
"author_id": 24233,
"author_profile": "https://Stackoverflow.com/users/24233",
"pm_score": 2,
"selected": false,
"text": "Dim OldStatus\nWith Application\n OldStatus = .DisplayStatusBar\n .DisplayStatusBar = True\n .StatusBar = \"Doing my duty, please wait...\"\nEnd With\n' Do what you do best here (you can refresh the .StatusBar message with updted, as needed)\nWith Application\n .StatusBar = False\n .DisplayStatusBar = OldStatus\nEnd With\n"
},
{
"answer_id": 306163,
"author": "Carl G",
"author_id": 39396,
"author_profile": "https://Stackoverflow.com/users/39396",
"pm_score": 3,
"selected": true,
"text": "Public Sub UpdateStatusBar(percent As Double, Optional Message As String = \"\")\n\n Const maxBars As Long = 20\n Const before As String = \"[\"\n Const after As String = \"]\"\n\n Dim bar As String\n Dim notBar As String\n Dim numBars As Long\n\n bar = Chr(31)\n notBar = Chr(151)\n numBars = percent * maxBars\n\n Application.StatusBar = _\n before & Application.Rept(bar, numBars) & Application.Rept(notBar, maxBars - numBars) & after & \" \" & _\n Message & \" (\" & PercentageToString(percent) & \"%)\"\n\n DoEvents\n\nEnd Sub\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2665/"
] |
217,821
|
<p>Apart from just inserting and parsing text into a blank Word field, is there any way to programmatically build user-defined fields and field codes into my own templates with VBA? Furthermore, is there a way to make these fields show up in the list of available fields?</p>
|
[
{
"answer_id": 218304,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "{ DOCPROPERTY \"Test\" \\* MERGEFORMAT } \n Sub AutoNew()\nDim objCustomProperties As DocumentProperties\n\nSet objCustomProperties = ActiveDocument.CustomDocumentProperties\n\nobjCustomProperties.Add Name:=\"Test\", _\n Type:=msoPropertyTypeString, Value:=\"Blah\", _\n LinkToContent:=False\n\nEnd Sub\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2665/"
] |
217,825
|
<p><a href="http://en.wikipedia.org/wiki/Apple_Developer_Tools#Shark" rel="nofollow noreferrer">Shark</a> on Mac OS X is a great tool for profiling an application on a running system. Is there any similar tools for Linux? </p>
<p><a href="http://oprofile.sourceforge.net/about/" rel="nofollow noreferrer">OProfile</a> looks like it could be, anyone used it? </p>
|
[
{
"answer_id": 334829,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": 3,
"selected": false,
"text": "valgrind --tool=callgrind <name of your app> <your app's options>\n valgrind --tool=cachegrind <name of your app> <your app's options>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/842/"
] |
217,829
|
<p>A page executes a number of tasks and takes a long time to process. We want to give the user feedback as each task is completed. </p>
<p>In ASP.NET webforms we used <code>Response.Flush()</code></p>
<p>What way would you a approach this in ASP.NET MVC?</p>
|
[
{
"answer_id": 217899,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 3,
"selected": false,
"text": "this.PartialView(\"Progress\").ExecuteResult(this.ControllerContext);\nthis.Response.Flush();\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23393/"
] |
217,831
|
<p>Could someone explain to me how Any-related annotations (<code>@Any</code>, <code>@AnyMetaDef</code>, <code>@AnyMetaDefs</code> and <code>@ManyToAny</code>) work in practice. I have a hard time finding any useful documentation (JavaDoc alone isn't very helpful) about these.</p>
<p>I have thus far gathered that they somehow enable referencing to abstract and extended classes. If this is the case, why is there not an <code>@OneToAny</code> annotation? And is this 'any' referring to a single 'any', or multiple 'any'?</p>
<p>A short, practical and illustrating example would be very much appreciated (doesn't have to compile).</p>
<p><strong>Edit:</strong> as much as I would like to accept replies as answers and give credit where due, I found both Smink's and Sakana's answers informative. Because I can't accept several replies as <em>the answer</em>, I will unfortunately mark neither as the answer.</p>
|
[
{
"answer_id": 217848,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 5,
"selected": false,
"text": "@Entity\n@Table(name = \"BORROW\")\npublic class Borrow{\n\n @Id\n @GeneratedValue\n private Long id;\n\n @Any(metaColumn = @Column(name = \"ITEM_TYPE\"))\n @AnyMetaDef(idType = \"long\", metaType = \"string\", \n metaValues = { \n @MetaValue(targetEntity = Book.class, value = \"B\"),\n @MetaValue(targetEntity = VHS.class, value = \"V\"),\n @MetaValue(targetEntity = DVD.class, value = \"D\")\n })\n @JoinColumn(name=\"ITEM_ID\")\n private Object item;\n\n .......\n public Object getItem() {\n return item;\n }\n\n public void setItem(Object item) {\n this.item = item;\n }\n\n}\n"
},
{
"answer_id": 217880,
"author": "sakana",
"author_id": 28921,
"author_profile": "https://Stackoverflow.com/users/28921",
"pm_score": 5,
"selected": false,
"text": "@Any( metaColumn = @Column( name = \"property_type\" ), fetch=FetchType.EAGER )\n@AnyMetaDef(\n idType = \"integer\",\n metaType = \"string\",\n metaValues = {\n @MetaValue( value = \"S\", targetEntity = StringProperty.class ),\n @MetaValue( value = \"I\", targetEntity = IntegerProperty.class )\n} )\n@JoinColumn( name = \"property_id\" )\npublic Property getMainProperty() {\n return mainProperty;\n}\n //on a package\n@AnyMetaDef( name=\"property\"\nidType = \"integer\",\nmetaType = \"string\",\nmetaValues = {\n@MetaValue( value = \"S\", targetEntity = StringProperty.class ),\n@MetaValue( value = \"I\", targetEntity = IntegerProperty.class )\n} )\npackage org.hibernate.test.annotations.any;\n//in a class\n@Any( metaDef=\"property\", metaColumn = @Column( name = \"property_type\" ), fetch=FetchType.EAGER )\n@JoinColumn( name = \"property_id\" )\npublic Property getMainProperty() {\n return mainProperty;\n}\n @ManyToAny(\nmetaColumn = @Column( name = \"property_type\" ) )\n@AnyMetaDef(\n idType = \"integer\",\n metaType = \"string\",\n metaValues = {\n@MetaValue( value = \"S\", targetEntity = StringProperty.class ),\n@MetaValue( value = \"I\", targetEntity = IntegerProperty.class ) } )\n@Cascade( { org.hibernate.annotations.CascadeType.ALL } )\n@JoinTable( name = \"obj_properties\", joinColumns = @JoinColumn( name = \"obj_id\" ),\n inverseJoinColumns = @JoinColumn( name = \"property_id\" ) )\npublic List<Property> getGeneralProperties() {\n"
},
{
"answer_id": 32972919,
"author": "atorres",
"author_id": 1768466,
"author_profile": "https://Stackoverflow.com/users/1768466",
"pm_score": 2,
"selected": false,
"text": "@Entity\n@Table(name = \"BORROW\")\npublic class Borrow{\n//... id, ...\n@ManyToOne Item item;\n//...\n}\n\n@Entity\n@Table(name = \"ITEMS\")\n@Inheritance(strategy=JOINED)\npublic class Item{\n // id, ....\n // you can add a reverse OneToMany here to borrow.\n}\n\n@Entity\n@Table(name = \"BOOKS\") \npublic class Book extends Item {\n // book attributes\n}\n\n@Entity\n@Table(name = \"VHS\") \npublic class VHS extends Item {\n // VHSattributes\n}\n\n@Entity\n@Table(name = \"DVD\") \npublic class DVD extends Item {\n // DVD attributes\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
217,834
|
<p>In history-books you often have timeline, where events and periods are marked on a line in the correct relative distance to each other. How is it possible to create something similar in LaTeX?</p>
|
[
{
"answer_id": 219266,
"author": "Zoe Gagnon",
"author_id": 26929,
"author_profile": "https://Stackoverflow.com/users/26929",
"pm_score": 7,
"selected": true,
"text": "\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{snakes}\n\n\\begin{document}\n\n \\begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm]\n % draw horizontal line \n \\draw (0,0) -- (2,0);\n \\draw[snake] (2,0) -- (4,0);\n \\draw (4,0) -- (5,0);\n \\draw[snake] (5,0) -- (7,0);\n\n % draw vertical lines\n \\foreach \\x in {0,1,2,4,5,7}\n \\draw (\\x cm,3pt) -- (\\x cm,-3pt);\n\n % draw nodes\n \\draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};\n \\draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};\n \\draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};\n \\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$ $};\n \\draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};\n \\draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};\n \\draw (6,0) node[below=3pt] {$ $} node[above=3pt] {$ $};\n \\draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};\n \\end{tikzpicture}\n\n\\end{document}\n"
},
{
"answer_id": 729189,
"author": "saffsd",
"author_id": 37984,
"author_profile": "https://Stackoverflow.com/users/37984",
"pm_score": 2,
"selected": false,
"text": "%%% In LaTeX:\n%%% \\begin{timeline}{length}(start,stop)\n%%% .\n%%% .\n%%% .\n%%% \\end{timeline}\n%%%\n%%% in plain TeX\n%%% \\timeline{length}(start,stop)\n%%% .\n%%% .\n%%% .\n%%% \\endtimeline\n%%% in between the two, we may have:\n%%% \\item{date}{description}\n%%% \\item[sortkey]{date}{description}\n%%% \\optrule\n%%%\n%%% the options to timeline are:\n%%% length The amount of vertical space that the timeline should\n%%% use.\n%%% (start,stop) indicate the range of the timeline. All dates or\n%%% sortkeys should lie in the range [start,stop]\n%%%\n%%% \\item without the sort key expects date to be a number (such as a\n%%% year).\n%%% \\item with the sort key expects the sort key to be a number; date\n%%% can be anything. This can be used for log scale time lines\n%%% or dates that include months or days.\n%%% putting \\optrule inside of the timeline environment will cause a\n%%% vertical rule to be drawn down the center of the timeline.\n"
},
{
"answer_id": 957784,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 4,
"selected": false,
"text": "timeline.sty \\begin{timeline}{2008}{2010}{50}{250}\n \\MonthAndYearEvent{4}{2008}{First Podcast}\n \\MonthAndYearEvent{7}{2008}{Private Beta}\n \\MonthAndYearEvent{9}{2008}{Public Beta}\n \\YearEvent{2009}{IPO?}\n\\end{timeline}\n 2008 2010\n · · April, 2008 First Podcast ·\n · July, 2008 Private Beta\n · September, 2008 Public Beta\n · 2009 IPO?\n"
},
{
"answer_id": 2444380,
"author": "przemoc",
"author_id": 241521,
"author_profile": "https://Stackoverflow.com/users/241521",
"pm_score": 4,
"selected": false,
"text": "tikz \\documentclass[tikz]{standalone}\n\\usepackage{verbatim}\n\\begin{document}\n\\newlength\\yearposx\n\\begin{tikzpicture}[scale=0.57] % timeline 1990-2010->\n % define coordinates (begin, used, end, arrow)\n \\foreach \\x in {1990,1992,2000,2002,2004,2005,2008,2009,2010,2011}{\n \\pgfmathsetlength\\yearposx{(\\x-1990)*1cm};\n \\coordinate (y\\x) at (\\yearposx,0);\n \\coordinate (y\\x t) at (\\yearposx,+3pt);\n \\coordinate (y\\x b) at (\\yearposx,-3pt);\n }\n % draw horizontal line with arrow\n \\draw [->] (y1990) -- (y2011);\n % draw ticks\n \\foreach \\x in {1992,2000,2002,2004,2005,2008,2009}\n \\draw (y\\x t) -- (y\\x b);\n % annotate\n \\foreach \\x in {1992,2002,2005,2009}\n \\node at (y\\x) [below=3pt] {\\x};\n \\foreach \\x in {2000,2004,2008}\n \\node at (y\\x) [above=3pt] {\\x};\n \\begin{comment}\n % for use in beamer class\n \\only<2> {\\fill (y1992) circle (5pt);}\n \\only<3-5> {\\fill (y2000) circle (5pt);}\n \\only<4-5> {\\fill (y2002) circle (5pt);}\n \\only<5> {\\fill[red] (y2004) circle (5pt);}\n \\only<6> {\\fill (y2005) circle (5pt);}\n \\only<7> {\\fill[red] (y2005) circle (5pt);}\n \\only<8-11> {\\fill (y2008) circle (5pt);}\n \\only<11> {\\fill (y2009) circle (5pt);}\n \\end{comment}\n\\end{tikzpicture}\n\\end{document}\n \\newlength\\yearposx \\yearposx"
},
{
"answer_id": 4170985,
"author": "Cesar Rabak",
"author_id": 506482,
"author_profile": "https://Stackoverflow.com/users/506482",
"pm_score": 4,
"selected": false,
"text": "\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{decorations}\n\\begin{document}\n\\begin{tikzpicture}\n%draw horizontal line\n\\draw (0,0) -- (2,0);\n\\draw[decorate,decoration={snake,pre length=5mm, post length=5mm}] (2,0) -- (4,0);\n\\draw (4,0) -- (5,0);\n\\draw[decorate,decoration={snake,pre length=5mm, post length=5mm}] (5,0) -- (7,0);\n\n%draw vertical lines\n\\foreach \\x in {0,1,2,4,5,7}\n\\draw (\\x cm,3pt) -- (\\x cm,-3pt);\n\n%draw nodes\n\\draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};\n\\draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};\n\\draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};\n\\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$ $};\n\\draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};\n\\draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};\n\\draw (6,0) node[below=3pt] {$ $} node[above=3pt] {$ $};\n\\draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};\n\\end{tikzpicture}\n\n\\end{document}\n"
},
{
"answer_id": 4404915,
"author": "nibot",
"author_id": 462335,
"author_profile": "https://Stackoverflow.com/users/462335",
"pm_score": 6,
"selected": false,
"text": "\\documentclass{article}\n\\usepackage{chronology}\n\\begin{document}\n\n\\begin{chronology}[5]{1983}{2010}{3ex}[\\textwidth]\n\\event{1984}{one}\n\\event[1985]{1986}{two}\n\\event{\\decimaldate{25}{12}{2001}}{three}\n\\end{chronology}\n\n\\end{document}\n"
},
{
"answer_id": 65654066,
"author": "Nurlan Jahangirli",
"author_id": 14976775,
"author_profile": "https://Stackoverflow.com/users/14976775",
"pm_score": 2,
"selected": false,
"text": "\\documentclass{article}\n\\usepackage{tikz}\n\\usetikzlibrary{snakes}\n\\usepackage{rotating}\n\n\\begin{document}\n \n\\begin{center}\n \\begin{tikzpicture}\n % draw horizontal line \n \\draw (-5,0) -- (6,0);\n \n \n % draw vertical lines\n \\foreach \\x in {-5,-4,-3,-2, -1,0,1,2}\n \\draw (\\x cm,3pt) -- (\\x cm,-3pt);\n \n % draw nodes\n \\draw (-5,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};\n \\draw (-4,0) node[below=3pt] {$ 1 $} node[above=3pt] {$\\begin{turn}{45}\n All individuals vote\n \\end{turn}$};\n \\draw (-3,0) node[below=3pt] {$ 2 $} node[above=3pt] {$\\begin{turn}{45} \n Policy vector decided\n \\end{turn}$};\n \\draw (-2,0) node[below=3pt] {$ 3 $} node[above=3pt] {$\\begin{turn}{45} Becoming a bureaucrat \\end{turn} $};\n \\draw (-1,0) node[below=3pt] {$ 4 $} node[above=3pt] {$\\begin{turn}{45} Bureaucrats' effort choice \\end{turn}$};\n \\draw (0,0) node[below=3pt] {$ 5 $} node[above=3pt] {$\\begin{turn}{45} Tax evasion decision made \\end{turn}$};\n \\draw (1,0) node[below=3pt] {$ 6$} node[above=3pt] {$\\begin{turn}{45} $p(x_{t})$ tax evaders caught \\end{turn}$};\n \\draw (2,0) node[below=3pt] {$ 7 $} node[above=3pt] {$\\begin{turn}{45} $q_{t}$ shirking bureaucrats \\end{turn}$};\n \\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$\\begin{turn}{45} Public service provided \\end{turn} $};\n\\end{tikzpicture}\n\\end{center} \n\\end{document}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
217,841
|
<p>I have a .NET web-service client that has been autogenerated from a wsdl-file using the wsdl.exe tool.</p>
<p>When I first instantiate the generated class, it begins to request a bunch of documents from w3.org and others. The first one being <a href="http://www.w3.org/2001/XMLSchema.dtd" rel="nofollow noreferrer">http://www.w3.org/2001/XMLSchema.dtd</a></p>
<p>Besides not wanting to cause unnecessary traffic to w3.org, I need to be able to run the application without a connection to the Internet (the web-service is a "Intra-web-service").</p>
<p>Anyone know the solution?</p>
<p>If it helps, here is the stacktrace I get when I do not have Internet:</p>
<pre><code>"An error has occurred while opening external DTD 'http://www.w3.org/2001/XMLSchema.dtd': The remote name could not be resolved: 'www.w3.org'"
at System.Net.HttpWebRequest.GetResponse()
at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenStream(Uri uri)
at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId)
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId)
at System.Xml.XmlTextReaderImpl.DtdParserProxy.System.Xml.IDtdParserAdapter.PushExternalSubset(String systemId, String publicId)
at System.Xml.DtdParser.ParseExternalSubset()
at System.Xml.DtdParser.ParseInDocumentDtd(Boolean saveInternalSubset)
at System.Xml.DtdParser.Parse(Boolean saveInternalSubset)
at System.Xml.XmlTextReaderImpl.DtdParserProxy.Parse(Boolean saveInternalSubset)
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Schema.Parser.StartParsing(XmlReader reader, String targetNamespace)
at System.Xml.Schema.Parser.Parse(XmlReader reader, String targetNamespace)
at System.Xml.Schema.XmlSchemaSet.ParseSchema(String targetNamespace, XmlReader reader)
at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlReader schemaDocument)
at [...]WebServiceClientType..cctor() in [...]
</code></pre>
|
[
{
"answer_id": 218105,
"author": "tamberg",
"author_id": 3588,
"author_profile": "https://Stackoverflow.com/users/3588",
"pm_score": 2,
"selected": false,
"text": "XmlReader r = ...\nr.XmlResolver = null; // prevent xsd or dtd parsing\n"
},
{
"answer_id": 218124,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 3,
"selected": true,
"text": "public partial class [...]WebServiceClientType\n {\n private static readonly XmlSchemaSet _schema;\n\n static KeyImportFileType()\n {\n _schema = new XmlSchemaSet();\n _schema.Add(null, XmlResourceResolver.GetXmlReader(\"http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd\"));\n _schema.Add(null, XmlResourceResolver.GetXmlReader(\"http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd\"));\n _schema.Compile();\n }\n"
},
{
"answer_id": 689487,
"author": "AndyM",
"author_id": 77295,
"author_profile": "https://Stackoverflow.com/users/77295",
"pm_score": 0,
"selected": false,
"text": "XmlReader r = ...r.XmlResolver = null; // prevent xsd or dtd parsing\n"
},
{
"answer_id": 9339180,
"author": "Dave G",
"author_id": 1210180,
"author_profile": "https://Stackoverflow.com/users/1210180",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Xml;\nusing System.Net;\nusing System.Net.Cache;\nusing System.IO;\nusing System.Resources;\n\nnamespace AxureExport {\n\n //\n // redirect URL resolution to local resource (or cache)\n public class XmlCustomResolver : XmlUrlResolver {\n\n ICredentials _credentials;\n ResourceManager _resourceManager;\n\n public enum ResolverType { useDefault, useCache, useResource };\n ResolverType _resolverType;\n\n public XmlCustomResolver(ResolverType rt, ResourceManager rm = null) {\n _resourceManager = rm != null ? rm : AxureExport.Properties.Resources.ResourceManager;\n _resolverType = rt;\n }\n\n public override ICredentials Credentials {\n set {\n _credentials = value;\n base.Credentials = value;\n }\n }\n\n public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) {\n object response = null;\n\n if (absoluteUri == null)\n throw new ArgumentNullException(@\"absoluteUri\");\n\n switch (_resolverType) {\n default:\n case ResolverType.useDefault: // use the default behavior of the XmlUrlResolver\n response = defaultResponse(absoluteUri, role, ofObjectToReturn);\n break;\n\n case ResolverType.useCache: // resolve resources thru cache\n if (!isExternalRequest(absoluteUri, ofObjectToReturn)) {\n response = defaultResponse(absoluteUri, role, ofObjectToReturn);\n break;\n }\n\n WebRequest webReq = WebRequest.Create(absoluteUri);\n webReq.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);\n if (_credentials != null)\n webReq.Credentials = _credentials;\n\n WebResponse wr = webReq.GetResponse();\n response = wr.GetResponseStream();\n break;\n\n case ResolverType.useResource: // get resource from internal resource\n if (!isExternalRequest(absoluteUri, ofObjectToReturn)) {\n response = defaultResponse(absoluteUri, role, ofObjectToReturn); // not an external request\n break;\n }\n\n string resourceName = uriToResourceKey(absoluteUri);\n object resource = _resourceManager.GetObject(resourceName);\n if (resource == null)\n throw new ArgumentException(@\"Resource not found. Uri=\" + absoluteUri + @\" Local resourceName=\" + resourceName);\n\n if (resource.GetType() != typeof(System.String))\n throw new ArgumentException(resourceName + @\" is an unexpected resource type. (Are you setting resource FileType=Text?)\");\n\n response = ObjectToUTF8Stream(resource);\n break;\n }\n\n return response;\n }\n\n //\n // convert object to stream\n private static object ObjectToUTF8Stream(object o) {\n MemoryStream stream = new MemoryStream();\n\n StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);\n writer.Write(o);\n writer.Flush();\n stream.Position = 0;\n\n return stream;\n }\n\n //\n // default response is to call tbe base resolver\n private object defaultResponse(Uri absoluteUri, string role, Type ofObjectToReturn) {\n return base.GetEntity(absoluteUri, role, ofObjectToReturn);\n }\n\n //\n // determine whether this is an external request\n private static bool isExternalRequest(Uri absoluteUri, Type ofObjectToReturn) {\n return absoluteUri.Scheme == @\"http\" && (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream));\n }\n\n //\n // translate uri to format compatible with reource manager key naming rules\n // see: System.Resources.Tools.StronglyTypedResourceBuilder.VerifyResourceName Method\n // from http://msdn.microsoft.com/en-us/library/ms145952.aspx:\n private static string uriToResourceKey(Uri absoluteUri) {\n const string repl = @\"[ \\xA0\\.\\,\\;\\|\\~\\@\\#\\%\\^\\&\\*\\+\\-\\/\\\\\\<\\>\\?\\[\\]\\(\\)\\{\\}\\\" + \"\\\"\" + @\"\\'\\:\\!]+\";\n return Regex.Replace(Path.GetFileNameWithoutExtension(absoluteUri.LocalPath), repl, @\"_\");\n }\n }\n}\n"
},
{
"answer_id": 72623634,
"author": "WilliamK",
"author_id": 3123980,
"author_profile": "https://Stackoverflow.com/users/3123980",
"pm_score": 1,
"selected": false,
"text": "mage.exe hans-moleman.w3.org"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5542/"
] |
217,842
|
<p>Heres a screenshot to make it clear. I'm trying to figure out a robust way of making the bullet images vertically aligned to my li content. As you can see my content is currently too high.</p>
<p>Many thanks 'over-flowers'...</p>
<p><a href="http://dl.getdropbox.com/u/240752/list-example.gif" rel="nofollow noreferrer">http://dl.getdropbox.com/u/240752/list-example.gif</a></p>
|
[
{
"answer_id": 217850,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 2,
"selected": false,
"text": "#content li{\n\n list-style-image: url(../images/bullet.gif);\n\n}\n"
},
{
"answer_id": 217868,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 2,
"selected": false,
"text": ".box li{\n padding-left: 20px;\n background-image: url(\"img/list_icon.jpg\");\n background-repeat: no-repeat;\n background-position: 0px 2px;\n margin-top: 6px;\n}\n"
},
{
"answer_id": 218779,
"author": "Traingamer",
"author_id": 27609,
"author_profile": "https://Stackoverflow.com/users/27609",
"pm_score": 2,
"selected": false,
"text": "#content ul li {\n margin: 3px -20px 3px 20px;\n padding: 0 0 0 0;\n list-style: none;\n background: url(newbullet.gif) no-repeat 0 3px;\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
217,849
|
<p>Our 404 error logs show a lot of /SysVol http requests on our Windows Web Server 2008 for our website. It only has a webserver role and I believe that SysVol requests are meant for Domain Controllers? What's causing this and what would be the best solution to deal with these 404 requests?</p>
<p>I'm using code that access employee records via Active Directory (ldap) and the server is not trusted for delegaton in case this is related to the problem.</p>
|
[
{
"answer_id": 217850,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 2,
"selected": false,
"text": "#content li{\n\n list-style-image: url(../images/bullet.gif);\n\n}\n"
},
{
"answer_id": 217868,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 2,
"selected": false,
"text": ".box li{\n padding-left: 20px;\n background-image: url(\"img/list_icon.jpg\");\n background-repeat: no-repeat;\n background-position: 0px 2px;\n margin-top: 6px;\n}\n"
},
{
"answer_id": 218779,
"author": "Traingamer",
"author_id": 27609,
"author_profile": "https://Stackoverflow.com/users/27609",
"pm_score": 2,
"selected": false,
"text": "#content ul li {\n margin: 3px -20px 3px 20px;\n padding: 0 0 0 0;\n list-style: none;\n background: url(newbullet.gif) no-repeat 0 3px;\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997/"
] |
217,852
|
<p>I have a 30000x14000 sparse matrix in MATLAB (version 7), which I need to use in another program. Calling save won't write this as ASCII (not supported). Calling <code>full()</code> on this monster results in an <code>Out of Memory</code> error.<br>
How do I export it?</p>
|
[
{
"answer_id": 217891,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 3,
"selected": false,
"text": ".mat .mat scipy.io.mio.loadmat"
},
{
"answer_id": 239950,
"author": "Midhat",
"author_id": 9425,
"author_profile": "https://Stackoverflow.com/users/9425",
"pm_score": 3,
"selected": true,
"text": "\npw=java.io.PrintWriter(java.io.FileWriter('c:\\\\retail.txt'));\nline=num2str(0:size(data,2)-1);\npw.println(line);\nfor index=1:length(data)\n disp(index);\n line=num2str(full(data(index,:)));\n pw.println(line);\nend\npw.flush();\npw.close();\n data"
},
{
"answer_id": 240026,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 2,
"selected": false,
"text": "find idcs = find(data);\nvals = data(idcs);\n...save the index vector and value vector in whatever format you want...\n ind2sub spconvert"
},
{
"answer_id": 378328,
"author": "Matthieu",
"author_id": 9310,
"author_profile": "https://Stackoverflow.com/users/9310",
"pm_score": 5,
"selected": false,
"text": "[i,j,val] = find(data)\ndata_dump = [i,j,val]\n data = spconvert( data_dump )\n save -ascii data.txt data_dump\n fid = fopen('data.txt','w')\nfprintf( fid,'%d %d %f\\n', transpose(data_dump) )\nfclose(fid)\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9425/"
] |
217,853
|
<p>How to represent the start and end times for one day?</p>
<p>Using October 23, 2008 as an example, is it start 2008-10-23 12:00:00 AM and end 2008-10-23 11:59:59 PM?</p>
|
[
{
"answer_id": 217873,
"author": "Balint Pato",
"author_id": 19621,
"author_profile": "https://Stackoverflow.com/users/19621",
"pm_score": 4,
"selected": false,
"text": "hh:mm:ss\n 23:59:59\n 235959\n 23:59, 2359, or 23\n 23:59:59.9942 or 235959.9942\n 1995-02-04 24:00 = 1995-02-05 00:00\n"
},
{
"answer_id": 218026,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 1,
"selected": false,
"text": "2008-10-23 00:00:00 - 2008-10-23 23:59:59\n 2008-10-23 00:00:00 - 2008-10-24 00:00:00\n 2008-10-23 00:00:00 - 2008-10-23 24:00:00\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15396/"
] |
217,859
|
<p>When you start a Flex drag action, you pass in a proxy image to be displayed when you drag across the screen. When the drop occurs, I want to be able to grab this proxy but I can't find a way to from the DragEvent object.</p>
<p>Is it possible? What I want is to actually drop the dragged image when the mouse button is released... Flex automatically does a nice shrinking animation on the proxy but I don't want that.</p>
<p>The <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=dragdrop_7.html" rel="nofollow noreferrer">Flex examples</a> show what I don't want - the proxy is removed and a new image added but not in exactly the right place...</p>
<p>More info: I tried adding my Proxy Image as a data item to the DragSource. I was able to access this when the drop occurred and saw there is a class mx.managers.dragClasses.DragProxy which seems to have all the info I need... but this class is not documented?</p>
<p>So there's two questions really... how to get the proxy and find out the position of the mouse cursor within the proxy, and how to disable the Flex drop animation.</p>
|
[
{
"answer_id": 218524,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": 2,
"selected": false,
"text": "import mx_internal;\n var p:* = DragManager.mx_internal::dragProxy;\n"
},
{
"answer_id": 799670,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "var proxy:UIComponent = new UIComponent();\nproxy.graphics.lineStyle(1);\nproxy.graphics.beginFill(0xccddff);\nproxy.graphics.drawRect(0, 0, main.width, main.height);\nstage.addEventListener(MouseEvent.MOUSE_UP, function (e:MouseEvent):void {\n proxy.visible = false;\n});\n"
},
{
"answer_id": 873095,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "var drgSrc:DragSource = new DragSource();\ndrgSrc.addData( { x:e.currentTarget.contentMouseX, y:e.currentTarget.contentMouseY }, 'drgXY' );\n var newImg:Image = new Image();\nnewImg.x = drpCvs.contentMouseX - e.dragSource.dataForFormat( 'drgXY' ).x;\nnewImg.y = drpCvs.contentMouseY - e.dragSource.dataForFormat( 'drgXY' ).y;\n"
},
{
"answer_id": 3931374,
"author": "Tobias Heise",
"author_id": 475512,
"author_profile": "https://Stackoverflow.com/users/475512",
"pm_score": 0,
"selected": false,
"text": "protected function dragEnterHandler(event:DragEvent):void{\n\n DragManager.acceptDragDrop(this);\n\n this.dragProxy = DragManager.mx_internal::dragProxy;// get drag proxy\n\n var sm:ISystemManager = event.dragInitiator.systemManager.topLevelSystemManager as ISystemManager;\n var ed:IEventDispatcher = sm.getSandboxRoot();\n this.sandboxRoot = sm.getSandboxRoot();\n //remove\n ed.removeEventListener(MouseEvent.MOUSE_UP, dragProxy.mouseUpHandler, true);\n\n //attach own\n ed.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, true);\n ed.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);\n\n this.dragInitiator = event.dragInitiator;}\n"
},
{
"answer_id": 4011303,
"author": "Jeremy Herrman",
"author_id": 358182,
"author_profile": "https://Stackoverflow.com/users/358182",
"pm_score": 0,
"selected": false,
"text": "event.dragInitiator.visible = false;\n"
},
{
"answer_id": 7749449,
"author": "Slain",
"author_id": 992680,
"author_profile": "https://Stackoverflow.com/users/992680",
"pm_score": 2,
"selected": false,
"text": "override protected function dragCompleteHandler(e:DragEvent):void\n{\n DragManager.mx_internal::dragProxy.visible = false; // <- MAGIC!\n super.dragCompleteHandler(e);\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13220/"
] |
217,881
|
<p>What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?</p>
<p>As an example, I need to convert this:</p>
<pre><code>string = "*abc+de?"
</code></pre>
<p>to this:</p>
<pre><code>string = ".*abc.+de.?"
</code></pre>
<p>Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?</p>
|
[
{
"answer_id": 217896,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "replace def wildcard_to_regex(str):\n return str.replace(\"*\", \".*\").replace(\"?\", .?\").replace(\"#\", \"\\d\")\n"
},
{
"answer_id": 217933,
"author": "Paul Stephenson",
"author_id": 5536,
"author_profile": "https://Stackoverflow.com/users/5536",
"pm_score": 1,
"selected": false,
"text": "def wildcard_to_regex(wildcard):\n replacements = {\n '*': '.*',\n '?': '.?',\n '+': '.+',\n }\n regex = wildcard\n for (wildcard_pattern, regex_pattern) in replacements.items():\n regex = regex.replace(wildcard_pattern, regex_pattern)\n return regex\n wildcard_to_regex ? .? ? ."
},
{
"answer_id": 217978,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 2,
"selected": false,
"text": "wildcards= re.compile('([?*+])')\nescapewild= {'?': '.', '*': '.*', '+': '.+'}\n\ndef escapePart((parti, part)):\n if parti%2==0: # even items are literals\n return re.escape(part)\n else: # odd items are wildcards\n return escapewild[part]\n\ndef convertWildcardedToRegex(s):\n parts= map(escapePart, enumerate(wildcards.split(s)))\n return '^%s$' % (''.join(parts))\n"
},
{
"answer_id": 218102,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 4,
"selected": true,
"text": ">>> import fnmatch\n>>> fnmatch.fnmatch(\"fooabcdef\", \"*abcde?\")\nTrue\n>>> help(fnmatch.fnmatch)\nHelp on function fnmatch in module fnmatch:\n\nfnmatch(name, pat)\n Test whether FILENAME matches PATTERN.\n\n Patterns are Unix shell style:\n\n * matches everything\n ? matches any single character\n [seq] matches any character in seq\n [!seq] matches any char not in seq\n\n An initial period in FILENAME is not special.\n Both FILENAME and PATTERN are first case-normalized\n if the operating system requires it.\n If you don't want this, use fnmatchcase(FILENAME, PATTERN).\n\n>>> \n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909/"
] |
217,892
|
<p>Suppose I have a hash_map and a code like</p>
<pre><code>// i is an iterator
i = hash_map.erase(i)
</code></pre>
<p>But GCC's STL doesn't return iterator in erase, but a void. Now is a code like</p>
<pre><code>hash_map.erase(i++)
</code></pre>
<p>safe (i.e. does not invalidate the iterator or does any other unexpected or unpleasant things)? Please note this is a hash_map.</p>
|
[
{
"answer_id": 217904,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "i"
},
{
"answer_id": 220495,
"author": "Rodyland",
"author_id": 10681,
"author_profile": "https://Stackoverflow.com/users/10681",
"pm_score": -1,
"selected": false,
"text": "// tmp and i are both iterators\ntmp = i;\n++i;\nhash_map.erase(tmp);\n"
},
{
"answer_id": 2303719,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "namespace detail {\ntemplate<typename Container, typename R>\nstruct SelectErase {\n // by default, assume the next iterator is returned\n template<typename Iterator>\n Iterator erase(Container& c, Iterator where) {\n return c.erase(where);\n }\n};\n// specialize on return type void\ntemplate<typename Container>\nstruct SelectErase<Container, void> {\n template<typename Iterator>\n Iterator erase(Container& c, Iterator where) {\n Iterator next (where);\n ++next;\n c.erase(where);\n return next;\n }\n};\n\ntemplate<typename I, typename Container, typename R>\nSelectErase<Container,R> select_erase(R (Container::*)(I)) {\n return SelectErase<Container,R>();\n}\n} // namespace detail\n\ntemplate<typename Container, typename Iterator>\nIterator erase(Container& container, Iterator where) {\n return detail::select_erase<Iterator>(&Container::erase).erase(container, where);\n}\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
] |
217,900
|
<p>i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful </p>
|
[
{
"answer_id": 217925,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 3,
"selected": false,
"text": "import random\nimport unittest\n\nclass TestSequenceFunctions(unittest.TestCase):\n\n def setUp(self):\n self.seq = range(10)\n\n def testshuffle(self):\n # make sure the shuffled sequence does not lose any elements\n random.shuffle(self.seq)\n self.seq.sort()\n self.assertEqual(self.seq, range(10))\n\n def testchoice(self):\n element = random.choice(self.seq)\n self.assert_(element in self.seq)\n\n def testsample(self):\n self.assertRaises(ValueError, random.sample, self.seq, 20)\n for element in random.sample(self.seq, 5):\n self.assert_(element in self.seq)\n\nif __name__ == '__main__':\n unittest.main()\n"
},
{
"answer_id": 218489,
"author": "David Eyk",
"author_id": 18950,
"author_profile": "https://Stackoverflow.com/users/18950",
"pm_score": 2,
"selected": false,
"text": "unittest tests test test unittest"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17451/"
] |
217,901
|
<p>Below are lines from "the c++ programming language"</p>
<pre><code>template<class T > T sqrt(T );
template<class T > complex<T> sqrt(complex<T>);
double sqrt(double);
void f(complex<double> z )
{
s q r t (2 ); // sqrt<int>(int)
sqrt(2.0) ; // sqrt(double)
sqrt(z) ; // sqrt<double>(complex<double>)
}
</code></pre>
<p>I dont understand why sqrt(z) ; calls <code>sqrt<double>(complex<double>)</code> can any body please explain.</p>
<p>Author says,
<code>T sqrt<complex<T>></code> is more specialized than <code>T sqrt <T></code> but there is a seperate declaration for <code>template<class T > complex<T> sqrt(complex<T>);</code> why not use that?</p>
|
[
{
"answer_id": 217922,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 3,
"selected": true,
"text": "sqrt<double>(complex<double>) template <class T> complex<T> sqrt(complex<T>)"
},
{
"answer_id": 217943,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": false,
"text": "template<class T> T sqrt(T);\ntemplate<class U> complex<U> sqrt(complex<U>);\ndouble sqrt(double);\nvoid f(complex<double> z )\n{\n sqrt (2); // sqrt<int>(int)\n sqrt(2.0) ; // sqrt(double)\n sqrt(z) ; // sqrt<double>(complex<double>)\n}\n T=complex<U>"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
217,902
|
<p>Is there any class in the .NET framework that can read/write standard .ini files:</p>
<pre><code>[Section]
<keyname>=<value>
...
</code></pre>
<p>Delphi has the <code>TIniFile</code> component and I want to know if there is anything similar for C#? </p>
|
[
{
"answer_id": 217913,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 6,
"selected": false,
"text": "WritePrivateProfileString GetPrivateProfileString System.Runtime.InteropServices System.Text using INI;\n INIFile ini = new INIFile(\"C:\\\\test.ini\");\n IniWriteValue IniReadValue"
},
{
"answer_id": 5037497,
"author": "joerage",
"author_id": 197000,
"author_profile": "https://Stackoverflow.com/users/197000",
"pm_score": 6,
"selected": false,
"text": "public class TestParser\n{\n public static void Main()\n {\n IniParser parser = new IniParser(@\"C:\\test.ini\");\n\n String newMessage;\n\n newMessage = parser.GetSetting(\"appsettings\", \"msgpart1\");\n newMessage += parser.GetSetting(\"appsettings\", \"msgpart2\");\n newMessage += parser.GetSetting(\"punctuation\", \"ex\");\n\n //Returns \"Hello World!\"\n Console.WriteLine(newMessage);\n Console.ReadLine();\n }\n}\n using System;\nusing System.IO;\nusing System.Collections;\n\npublic class IniParser\n{\n private Hashtable keyPairs = new Hashtable();\n private String iniFilePath;\n\n private struct SectionPair\n {\n public String Section;\n public String Key;\n }\n\n /// <summary>\n /// Opens the INI file at the given path and enumerates the values in the IniParser.\n /// </summary>\n /// <param name=\"iniPath\">Full path to INI file.</param>\n public IniParser(String iniPath)\n {\n TextReader iniFile = null;\n String strLine = null;\n String currentRoot = null;\n String[] keyPair = null;\n\n iniFilePath = iniPath;\n\n if (File.Exists(iniPath))\n {\n try\n {\n iniFile = new StreamReader(iniPath);\n\n strLine = iniFile.ReadLine();\n\n while (strLine != null)\n {\n strLine = strLine.Trim().ToUpper();\n\n if (strLine != \"\")\n {\n if (strLine.StartsWith(\"[\") && strLine.EndsWith(\"]\"))\n {\n currentRoot = strLine.Substring(1, strLine.Length - 2);\n }\n else\n {\n keyPair = strLine.Split(new char[] { '=' }, 2);\n\n SectionPair sectionPair;\n String value = null;\n\n if (currentRoot == null)\n currentRoot = \"ROOT\";\n\n sectionPair.Section = currentRoot;\n sectionPair.Key = keyPair[0];\n\n if (keyPair.Length > 1)\n value = keyPair[1];\n\n keyPairs.Add(sectionPair, value);\n }\n }\n\n strLine = iniFile.ReadLine();\n }\n\n }\n catch (Exception ex)\n {\n throw ex;\n }\n finally\n {\n if (iniFile != null)\n iniFile.Close();\n }\n }\n else\n throw new FileNotFoundException(\"Unable to locate \" + iniPath);\n\n }\n\n /// <summary>\n /// Returns the value for the given section, key pair.\n /// </summary>\n /// <param name=\"sectionName\">Section name.</param>\n /// <param name=\"settingName\">Key name.</param>\n public String GetSetting(String sectionName, String settingName)\n {\n SectionPair sectionPair;\n sectionPair.Section = sectionName.ToUpper();\n sectionPair.Key = settingName.ToUpper();\n\n return (String)keyPairs[sectionPair];\n }\n\n /// <summary>\n /// Enumerates all lines for given section.\n /// </summary>\n /// <param name=\"sectionName\">Section to enum.</param>\n public String[] EnumSection(String sectionName)\n {\n ArrayList tmpArray = new ArrayList();\n\n foreach (SectionPair pair in keyPairs.Keys)\n {\n if (pair.Section == sectionName.ToUpper())\n tmpArray.Add(pair.Key);\n }\n\n return (String[])tmpArray.ToArray(typeof(String));\n }\n\n /// <summary>\n /// Adds or replaces a setting to the table to be saved.\n /// </summary>\n /// <param name=\"sectionName\">Section to add under.</param>\n /// <param name=\"settingName\">Key name to add.</param>\n /// <param name=\"settingValue\">Value of key.</param>\n public void AddSetting(String sectionName, String settingName, String settingValue)\n {\n SectionPair sectionPair;\n sectionPair.Section = sectionName.ToUpper();\n sectionPair.Key = settingName.ToUpper();\n\n if (keyPairs.ContainsKey(sectionPair))\n keyPairs.Remove(sectionPair);\n\n keyPairs.Add(sectionPair, settingValue);\n }\n\n /// <summary>\n /// Adds or replaces a setting to the table to be saved with a null value.\n /// </summary>\n /// <param name=\"sectionName\">Section to add under.</param>\n /// <param name=\"settingName\">Key name to add.</param>\n public void AddSetting(String sectionName, String settingName)\n {\n AddSetting(sectionName, settingName, null);\n }\n\n /// <summary>\n /// Remove a setting.\n /// </summary>\n /// <param name=\"sectionName\">Section to add under.</param>\n /// <param name=\"settingName\">Key name to add.</param>\n public void DeleteSetting(String sectionName, String settingName)\n {\n SectionPair sectionPair;\n sectionPair.Section = sectionName.ToUpper();\n sectionPair.Key = settingName.ToUpper();\n\n if (keyPairs.ContainsKey(sectionPair))\n keyPairs.Remove(sectionPair);\n }\n\n /// <summary>\n /// Save settings to new file.\n /// </summary>\n /// <param name=\"newFilePath\">New file path.</param>\n public void SaveSettings(String newFilePath)\n {\n ArrayList sections = new ArrayList();\n String tmpValue = \"\";\n String strToSave = \"\";\n\n foreach (SectionPair sectionPair in keyPairs.Keys)\n {\n if (!sections.Contains(sectionPair.Section))\n sections.Add(sectionPair.Section);\n }\n\n foreach (String section in sections)\n {\n strToSave += (\"[\" + section + \"]\\r\\n\");\n\n foreach (SectionPair sectionPair in keyPairs.Keys)\n {\n if (sectionPair.Section == section)\n {\n tmpValue = (String)keyPairs[sectionPair];\n\n if (tmpValue != null)\n tmpValue = \"=\" + tmpValue;\n\n strToSave += (sectionPair.Key + tmpValue + \"\\r\\n\");\n }\n }\n\n strToSave += \"\\r\\n\";\n }\n\n try\n {\n TextWriter tw = new StreamWriter(newFilePath);\n tw.Write(strToSave);\n tw.Close();\n }\n catch (Exception ex)\n {\n throw ex;\n }\n }\n\n /// <summary>\n /// Save settings back to ini file.\n /// </summary>\n public void SaveSettings()\n {\n SaveSettings(iniFilePath);\n }\n}\n"
},
{
"answer_id": 14906422,
"author": "Danny Beckett",
"author_id": 1563422,
"author_profile": "https://Stackoverflow.com/users/1563422",
"pm_score": 8,
"selected": false,
"text": "IniFile.cs using System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n// Change this to match your program's normal namespace\nnamespace MyProg\n{\n class IniFile // revision 11\n {\n string Path;\n string EXE = Assembly.GetExecutingAssembly().GetName().Name;\n\n [DllImport(\"kernel32\", CharSet = CharSet.Unicode)]\n static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);\n\n [DllImport(\"kernel32\", CharSet = CharSet.Unicode)]\n static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);\n\n public IniFile(string IniPath = null)\n {\n Path = new FileInfo(IniPath ?? EXE + \".ini\").FullName;\n }\n\n public string Read(string Key, string Section = null)\n {\n var RetVal = new StringBuilder(255);\n GetPrivateProfileString(Section ?? EXE, Key, \"\", RetVal, 255, Path);\n return RetVal.ToString();\n }\n\n public void Write(string Key, string Value, string Section = null)\n {\n WritePrivateProfileString(Section ?? EXE, Key, Value, Path);\n }\n\n public void DeleteKey(string Key, string Section = null)\n {\n Write(Key, null, Section ?? EXE);\n }\n\n public void DeleteSection(string Section = null)\n {\n Write(null, null, Section ?? EXE);\n }\n\n public bool KeyExists(string Key, string Section = null)\n {\n return Read(Key, Section).Length > 0;\n }\n }\n}\n // Creates or loads an INI file in the same directory as your executable\n// named EXE.ini (where EXE is the name of your executable)\nvar MyIni = new IniFile();\n\n// Or specify a specific name in the current dir\nvar MyIni = new IniFile(\"Settings.ini\");\n\n// Or specify a specific name in a specific dir\nvar MyIni = new IniFile(@\"C:\\Settings.ini\");\n MyIni.Write(\"DefaultVolume\", \"100\");\nMyIni.Write(\"HomePage\", \"http://www.google.com\");\n [MyProg]\nDefaultVolume=100\nHomePage=http://www.google.com\n var DefaultVolume = MyIni.Read(\"DefaultVolume\");\nvar HomePage = MyIni.Read(\"HomePage\");\n [Section] MyIni.Write(\"DefaultVolume\", \"100\", \"Audio\");\nMyIni.Write(\"HomePage\", \"http://www.google.com\", \"Web\");\n [Audio]\nDefaultVolume=100\n\n[Web]\nHomePage=http://www.google.com\n if(!MyIni.KeyExists(\"DefaultVolume\", \"Audio\"))\n{\n MyIni.Write(\"DefaultVolume\", \"100\", \"Audio\");\n}\n MyIni.DeleteKey(\"DefaultVolume\", \"Audio\");\n MyIni.DeleteSection(\"Web\");\n"
},
{
"answer_id": 16972767,
"author": "Larry",
"author_id": 24472,
"author_profile": "https://Stackoverflow.com/users/24472",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass IniReader\n{\n Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>(StringComparer.InvariantCultureIgnoreCase);\n\n public IniReader(string file)\n {\n var txt = File.ReadAllText(file);\n\n Dictionary<string, string> currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);\n\n ini[\"\"] = currentSection;\n\n foreach(var line in txt.Split(new[]{\"\\n\"}, StringSplitOptions.RemoveEmptyEntries)\n .Where(t => !string.IsNullOrWhiteSpace(t))\n .Select(t => t.Trim()))\n {\n if (line.StartsWith(\";\"))\n continue;\n\n if (line.StartsWith(\"[\") && line.EndsWith(\"]\"))\n {\n currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);\n ini[line.Substring(1, line.LastIndexOf(\"]\") - 1)] = currentSection;\n continue;\n }\n\n var idx = line.IndexOf(\"=\");\n if (idx == -1)\n currentSection[line] = \"\";\n else\n currentSection[line.Substring(0, idx)] = line.Substring(idx + 1);\n }\n }\n\n public string GetValue(string key)\n {\n return GetValue(key, \"\", \"\");\n }\n\n public string GetValue(string key, string section)\n {\n return GetValue(key, section, \"\");\n }\n\n public string GetValue(string key, string section, string @default)\n {\n if (!ini.ContainsKey(section))\n return @default;\n\n if (!ini[section].ContainsKey(key))\n return @default;\n\n return ini[section][key];\n }\n\n public string[] GetKeys(string section)\n {\n if (!ini.ContainsKey(section))\n return new string[0];\n\n return ini[section].Keys.ToArray();\n }\n\n public string[] GetSections()\n {\n return ini.Keys.Where(t => t != \"\").ToArray();\n }\n}\n"
},
{
"answer_id": 37772571,
"author": "BIOHAZARD",
"author_id": 1503846,
"author_profile": "https://Stackoverflow.com/users/1503846",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Tool\n{\n public class Config\n {\n Dictionary <string, string> values;\n public Config (string path)\n {\n values = File.ReadLines(path)\n .Where(line => (!String.IsNullOrWhiteSpace(line) && !line.StartsWith(\"#\")))\n .Select(line => line.Split(new char[] { '=' }, 2, 0))\n .ToDictionary(parts => parts[0].Trim(), parts => parts.Length>1?parts[1].Trim():null);\n }\n public string Value (string name, string value=null)\n {\n if (values!=null && values.ContainsKey(name))\n {\n return values[name];\n }\n return value;\n }\n }\n}\n file = new Tool.Config (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + \"\\\\config.ini\");\n command = file.Value (\"command\");\n action = file.Value (\"action\");\n string value;\n //second parameter is default value if no key found with this name\n value = file.Value(\"debug\",\"true\");\n this.debug = (value.ToLower()==\"true\" || value== \"1\");\n value = file.Value(\"plain\", \"false\");\n this.plain = (value.ToLower() == \"true\" || value == \"1\");\n #command to run\ncommand = php\n\n#default script\naction = index.php\n\n#debug mode\n#debug = true\n\n#plain text mode\n#plain = false\n\n#icon = favico.ico\n"
},
{
"answer_id": 40051727,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Loads .ini file into dictionary.\n/// </summary>\npublic static Dictionary<String, Dictionary<String, String>> loadIni(String file)\n{\n Dictionary<String, Dictionary<String, String>> d = new Dictionary<string, Dictionary<string, string>>();\n\n String ini = File.ReadAllText(file);\n\n // Remove comments, preserve linefeeds, if end-user needs to count line number.\n ini = Regex.Replace(ini, @\"^\\s*;.*$\", \"\", RegexOptions.Multiline);\n\n // Pick up all lines from first section to another section\n foreach (Match m in Regex.Matches(ini, \"(^|[\\r\\n])\\\\[([^\\r\\n]*)\\\\][\\r\\n]+(.*?)(\\\\[([^\\r\\n]*)\\\\][\\r\\n]+|$)\", RegexOptions.Singleline))\n {\n String sectionName = m.Groups[2].Value;\n Dictionary<String, String> lines = new Dictionary<String, String>();\n\n // Pick up \"key = value\" kind of syntax.\n foreach (Match l in Regex.Matches(ini, @\"^\\s*(.*?)\\s*=\\s*(.*?)\\s*$\", RegexOptions.Multiline))\n {\n String key = l.Groups[1].Value;\n String value = l.Groups[2].Value;\n\n // Open up quotation if any.\n value = Regex.Replace(value, \"^\\\"(.*)\\\"$\", \"$1\");\n\n if (!lines.ContainsKey(key))\n lines[key] = value;\n }\n\n if (!d.ContainsKey(sectionName))\n d[sectionName] = lines;\n }\n\n return d;\n}\n"
},
{
"answer_id": 42097645,
"author": "Petr Voborník",
"author_id": 1212428,
"author_profile": "https://Stackoverflow.com/users/1212428",
"pm_score": 2,
"selected": false,
"text": "public static Dictionary<string, string> ParseIniDataWithSections(string[] iniData)\n{\n var dict = new Dictionary<string, string>();\n var rows = iniData.Where(t => \n !String.IsNullOrEmpty(t.Trim()) && !t.StartsWith(\";\") && (t.Contains('[') || t.Contains('=')));\n if (rows == null || rows.Count() == 0) return dict;\n string section = \"\";\n foreach (string row in rows)\n {\n string rw = row.TrimStart();\n if (rw.StartsWith(\"[\"))\n section = rw.TrimStart('[').TrimEnd(']');\n else\n {\n int index = rw.IndexOf('=');\n dict[section + \"-\" + rw.Substring(0, index).Trim()] = rw.Substring(index+1).Trim().Trim('\"');\n }\n }\n return dict;\n}\n var dict = ParseIniDataWithSections(File.ReadAllLines(fileName));\n"
},
{
"answer_id": 44940171,
"author": "Scott Chamberlain",
"author_id": 80274,
"author_profile": "https://Stackoverflow.com/users/80274",
"pm_score": 4,
"selected": false,
"text": "Microsoft.Extensions.Confiuration Microsoft.Extensions.Configuration.Ini public Startup(IHostingEnvironment env)\n{\n var builder = new ConfigurationBuilder()\n .SetBasePath(env.ContentRootPath)\n .AddIniFile(\"SomeConfig.ini\", optional: false);\n Configuration = builder.Build();\n}\n"
},
{
"answer_id": 45761890,
"author": "unknown6656",
"author_id": 3902603,
"author_profile": "https://Stackoverflow.com/users/3902603",
"pm_score": 2,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nstatic bool match(this string str, string pat, out Match m) =>\n (m = Regex.Match(str, pat, RegexOptions.IgnoreCase)).Success;\n\nstatic void Main()\n{\n Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>();\n string section = \"\";\n\n foreach (string line in File.ReadAllLines(.........)) // read from file\n {\n string ln = (line.Contains('#') ? line.Remove(line.IndexOf('#')) : line).Trim();\n\n if (ln.match(@\"^[ \\t]*\\[(?<sec>[\\w\\-]+)\\]\", out Match m))\n section = m.Groups[\"sec\"].ToString();\n else if (ln.match(@\"^[ \\t]*(?<prop>[\\w\\-]+)\\=(?<val>.*)\", out m))\n {\n if (!ini.ContainsKey(section))\n ini[section] = new Dictionary<string, string>();\n\n ini[section][m.Groups[\"prop\"].ToString()] = m.Groups[\"val\"].ToString();\n }\n }\n\n\n // access the ini file as follows:\n string content = ini[\"section\"][\"property\"];\n}\n Dictionary<,> Dictionary<string, Dictionary<string, string>> .ini string targetpath = .........;\nDictionary<string, Dictionary<string, string>> ini = ........;\nStringBuilder sb = new StringBuilder();\n\nforeach (string section in ini.Keys)\n{\n sb.AppendLine($\"[{section}]\");\n\n foreach (string property in ini[section].Keys)\n sb.AppendLine($\"{property}={ini[section][property]\");\n}\n\nFile.WriteAllText(targetpath, sb.ToString());\n"
},
{
"answer_id": 52590951,
"author": "Erwin Draconis",
"author_id": 2760650,
"author_profile": "https://Stackoverflow.com/users/2760650",
"pm_score": -1,
"selected": false,
"text": "public static class IniFileManager\n{\n\n\n [DllImport(\"kernel32\")]\n private static extern long WritePrivateProfileString(string section,\n string key, string val, string filePath);\n [DllImport(\"kernel32\")]\n private static extern int GetPrivateProfileString(string section,\n string key, string def, StringBuilder retVal,\n int size, string filePath);\n [DllImport(\"kernel32.dll\")]\n private static extern int GetPrivateProfileSection(string lpAppName,\n byte[] lpszReturnBuffer, int nSize, string lpFileName);\n\n\n /// <summary>\n /// Write Data to the INI File\n /// </summary>\n /// <PARAM name=\"Section\"></PARAM>\n /// Section name\n /// <PARAM name=\"Key\"></PARAM>\n /// Key Name\n /// <PARAM name=\"Value\"></PARAM>\n /// Value Name\n public static void IniWriteValue(string sPath,string Section, string Key, string Value)\n {\n WritePrivateProfileString(Section, Key, Value, sPath);\n }\n\n /// <summary>\n /// Read Data Value From the Ini File\n /// </summary>\n /// <PARAM name=\"Section\"></PARAM>\n /// <PARAM name=\"Key\"></PARAM>\n /// <PARAM name=\"Path\"></PARAM>\n /// <returns></returns>\n public static string IniReadValue(string sPath,string Section, string Key)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(Section, Key, \"\", temp,\n 255, sPath);\n return temp.ToString();\n\n }\n"
},
{
"answer_id": 72558385,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 0,
"selected": false,
"text": "List<(string, string)> ini = File.ReadLines(filename)\n .Select(s => {\n var spl = s.Split('=', 2);\n return spl.Length == 2 ? (spl[0], spl[1]) : (s, \"\");\n })\n .Select(vt => (vt.Item1.Trim(), vt.Item2.Trim()))\n .Where(vt => vt.Item1 != \"\")\n .ToList();\n File.WriteAllLines(filename, ini.Select(vt => $\"{vt.Item1}={vt.Item2}\"));\n .ToDictionary() .ToList()"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25732/"
] |
217,911
|
<p>I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free':</p>
<ul>
<li>A default (empty) constructor</li>
<li>A copy constructor</li>
<li>A destructor</li>
<li>An assignment operator (<code>operator=</code>)</li>
</ul>
<p>But it cannot seem to give you any comparison operators - such as <code>operator==</code> or <code>operator!=</code>. For example:</p>
<pre><code>class foo
{
public:
std::string str_;
int n_;
};
foo f1; // Works
foo f2(f1); // Works
foo f3;
f3 = f2; // Works
if (f3 == f2) // Fails
{ }
if (f3 != f2) // Fails
{ }
</code></pre>
<p>Is there a good reason for this? Why would performing a member-by-member comparison be a problem? Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?</p>
|
[
{
"answer_id": 217950,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 4,
"selected": false,
"text": "default operator==;"
},
{
"answer_id": 218091,
"author": "sergtk",
"author_id": 13441,
"author_profile": "https://Stackoverflow.com/users/13441",
"pm_score": 4,
"selected": false,
"text": "== != == #include <utility>\nusing namespace std::rel_ops;\n...\n\nclass FooClass\n{\npublic:\n bool operator== (const FooClass& other) const {\n // ...\n }\n};\n operator< std::rel_ops std::rel_ops"
},
{
"answer_id": 218713,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 8,
"selected": false,
"text": "operator==() operator==() private:"
},
{
"answer_id": 27837789,
"author": "Anton Savin",
"author_id": 3959454,
"author_profile": "https://Stackoverflow.com/users/3959454",
"pm_score": 7,
"selected": false,
"text": "operator== struct foo\n{\n std::string str;\n int n;\n};\n\nassert(foo{\"Anton\", 1} == foo{\"Anton\", 1}); // ill-formed\n == struct foo\n{\n std::string str;\n int n;\n\n // either member form\n bool operator==(foo const&) const = default;\n // ... or friend form\n friend bool operator==(foo const&, foo const&) = default;\n};\n == == == != assert(foo{\"Anton\", 1} == foo{\"Anton\", 1}); // ok!\nassert(foo{\"Anton\", 1} != foo{\"Anton\", 2}); // ok!\n operator== == != operator<=>"
},
{
"answer_id": 34096496,
"author": "Museful",
"author_id": 827280,
"author_profile": "https://Stackoverflow.com/users/827280",
"pm_score": 2,
"selected": false,
"text": "verboseDescription class LocalWeatherRecord {\n std::string verboseDescription;\n std::tm date;\n bool operator==(const LocalWeatherRecord& other){\n return date==other.date\n && verboseDescription==other.verboseDescription;\n // The above makes a lot more sense than\n // return verboseDescription==other.verboseDescription\n // && date==other.date;\n // because some verboseDescriptions are liable to be same/similar\n }\n}\n"
},
{
"answer_id": 50345359,
"author": "VLL",
"author_id": 2527795,
"author_profile": "https://Stackoverflow.com/users/2527795",
"pm_score": 5,
"selected": false,
"text": "class Point {\n int x;\n int y;\npublic:\n auto operator<=>(const Point&) const = default;\n // ... non-comparison functions ...\n};\n\n// compiler implicitly declares operator== and all four relational operators work\nPoint pt1, pt2;\nif (pt1 == pt2) { /*...*/ } // ok, calls implicit Point::operator==\nstd::set<Point> s; // ok\ns.insert(pt1); // ok\nif (pt1 <= pt2) { /*...*/ } // ok, makes only a single call to Point::operator<=>\n"
},
{
"answer_id": 57822070,
"author": "Janek_Kozicki",
"author_id": 6657436,
"author_profile": "https://Stackoverflow.com/users/6657436",
"pm_score": 3,
"selected": false,
"text": "auto operator<=>(const foo&) const = default; <=> std::tie bool operator<(…) == #include <tuple>\n\nstruct S {\n………\nbool operator==(const S& rhs) const\n {\n // compares n to rhs.n,\n // then s to rhs.s,\n // then d to rhs.d\n return std::tie(n, s, d) == std::tie(rhs.n, rhs.s, rhs.d);\n }\n};\n std::tie"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
217,912
|
<p>I've got a text box bound to an object's property (in fact several text boxes) on a form. This for is an editor for an object. When i'm editing some objects and modify values in the one of the text boxes i can't exit from the text box (neither by tab nor clicking on another text box). However that's not always the case - when editing other objects (of the same type) it works fine.</p>
<p>Here's a code snipet:</p>
<pre><code>txtValue.DataBindings.Add("Text", _SourceObject, "PlannedValue", True, DataSourceUpdateMode.OnPropertyChanged, Nothing, "c")
txtEstPlacements.DataBindings.Add("Text", _SourceObject, "EstimatedPlacementCount")
txtReference.DataBindings.Add("Text", _SourceObject, "Reference")
</code></pre>
<p>Any suggestions?</p>
|
[
{
"answer_id": 9702855,
"author": "Thomas Brooks",
"author_id": 1269065,
"author_profile": "https://Stackoverflow.com/users/1269065",
"pm_score": 3,
"selected": false,
"text": "DBNull.Value TextBox1.DataBindings[\"Text\"].NullValue = string.Empty;\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10793/"
] |
217,928
|
<p>I have been trying to read a picture saved in Access DB as a OLE object in a PictureBox in a C# windows Application.</p>
<p>The code that does this is presented below:</p>
<pre><code> string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Rajesh\SampleDB_2003.mdb;";
OleDbConnection oConn = new OleDbConnection(connString);
oConn.Open();
string commandString = "select * from employee where id = " + id + "";
OleDbCommand oCmd = new OleDbCommand(commandString, oConn);
OleDbDataReader oReader = oCmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (oReader.Read())
{
txtID.Text = ((int)oReader.GetValue(0)).ToString();
txtName.Text = (string)oReader.GetValue(1);
txtAge.Text = ((int)oReader.GetValue(2)).ToString();
txtType.Text = (string)oReader.GetValue(3);
byte[] imageBytes = (byte[])oReader.GetValue(4);
MemoryStream ms = new MemoryStream();
ms.Write(imageBytes, 0, imageBytes.Length);
Bitmap bmp = new Bitmap(ms);
pbPassport.Image = bmp;
}
</code></pre>
<p>When I execute the above code, an 'Parameter is not valid' exception is thrown at the line:</p>
<pre><code>Bitmap bmp = new Bitmap(ms)
</code></pre>
<p>From the exception message, it is clear that 'ms' is in a format that is not recognisable. Any suggestion to get past this?</p>
|
[
{
"answer_id": 218080,
"author": "milot",
"author_id": 22637,
"author_profile": "https://Stackoverflow.com/users/22637",
"pm_score": 0,
"selected": false,
"text": "pbPassport.Image = Image.FromStream(ms);\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21995/"
] |
217,932
|
<p>I have had a bug recently that only manifested itself when the library was built as a release build rather than a debug build. The library is a .NET dll with a COM wrapper and I am using CoCreateInstance to create a class from the dll in an unmanaged c++ app. When I finally tracked the bug down it was caused by accessing a singleton object. I had the singleton instance declared like so:</p>
<pre><code>private static readonly MyObjectType s_instance = new MyObjectType;
</code></pre>
<p>and then accessed it with:</p>
<pre><code>public static MyObjectType Instance
{
get
{
return s_instance;
}
}
</code></pre>
<p>this was failing. Changing it to:</p>
<pre><code>private static MyObjectType s_instance;
public static MyObjectType Instance
{
get
{
if (s_instance==null)
{
s_instance = new MyObjectType();
}
return s_instance;
}
}
</code></pre>
<p>fixed the issue. Any ideas why the initial usage didn't work and if there are any downsides to doing it either way?</p>
<p>The release dll seemed to be perfectly usable from another managed app.</p>
|
[
{
"answer_id": 218005,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "beforefieldinit beforefieldinit"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,935
|
<p>On ASP.net MVC, what is the "correct" way to have a controller return a 301 Redirect to an external site?</p>
<p>The various RedirectTo-Function seem to only return either relative links or routes that i have mapped manually, but there is no way to say "Perform a 301 Redirect to <a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>".</p>
<p>I think I could just set Response.StatusCode or use Response.Redirect, but is that the way it should be done in MVC? Or is there an official "correct way" of performing redirects?</p>
<p><strong>Update:</strong> In the meantime, I wrote an ActionResult for that: <a href="http://www.stum.de/2008/10/22/permanentredirectresult/" rel="nofollow noreferrer">PermanentRedirectResult</a></p>
<p><strong>Update 2:</strong> Since ASP.net 4.0, Permanent Redirects are <a href="https://stackoverflow.com/a/11470379/91">part of the Framework</a>.</p>
|
[
{
"answer_id": 835366,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 1,
"selected": false,
"text": "Public Class ThingController\n Inherits System.Web.Mvc.Controller\n\n Function Details(ByVal id As String) As ActionResult\n Dim RedirectId As Guid\n Select Case key\n Case \"legacyurlone\"\n RedirectId = New Guid(\"c564c0c1-c365-4b0c-bc33-fd4eadf0551b\")\n Case \"legacyurltwo\"\n RedirectId = New Guid(\"157fa15b-8d5d-4f04-87cc-434f7ae93dfa\")\n Case Else\n RedirectId = Guid.Empty\n End Select\n If Not RedirectId = Guid.Empty Then\n Response.StatusCode = Net.HttpStatusCode.MovedPermanently\n Response.RedirectLocation = Url.RouteUrl(\"IdOnly\", New With {.id = RedirectId})\n Return Nothing\n End If\n Dim ThingId As Guid = New Guid(id)\n Dim db As New ThingEntities\n Dim Model As Thing = ...\n Return View(Model)\n End Function\n\n ...\n\nEnd Class\n"
},
{
"answer_id": 11470379,
"author": "Ben Barreth",
"author_id": 603670,
"author_profile": "https://Stackoverflow.com/users/603670",
"pm_score": 5,
"selected": false,
"text": "Response.RedirectPermanent(\"http://www.google.com\"); \n return RedirectPermanent(\"http://www.google.com\"); \n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
217,938
|
<p>I am designing a crawler which will get certain content from a webpage (using either string manipulation or regex).</p>
<p>I'm able to get the contents of the webpage as a response stream (using the whole httpwebrequest thing), and then for testing/dev purposes, I write the stream content to a multi-line textbox in my ASP.NET webpage.</p>
<p>Is it possible for me to loop through the content of the textbox and then say "If textbox1.text.contains (or save the textbox text as a string variable), a certain string then increment a count". The problem with the textbox is the string loses formatting, so it's in one long line with no line breaking. Can that be changed?</p>
<p>I'd like to do this rather than write the content to a file because writing to a file means I would have to handle all sorts of external issues. Of course, if this is the only way, then so be it. If I do have to write to a file, then what's the best strategy to loop through each and every line (I'm a little overwhelmed and thus confused as there's many logical and language methods to use), looking for a condition? So if I want to look for the string "Hello", in the following text:</p>
<p>My name is xyz
I am xyz years of age
Hello blah blah blah
Bye</p>
<p>When I reach hello I want to increment an integer variable.</p>
<p>Thanks,</p>
|
[
{
"answer_id": 217947,
"author": "Søren Pedersen",
"author_id": 379419,
"author_profile": "https://Stackoverflow.com/users/379419",
"pm_score": 0,
"selected": false,
"text": "string template = txtTemplate.Text;\n string[] lines = template.Split(Environment.NewLine.ToCharArray());\n"
},
{
"answer_id": 217965,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "public int CountOccurences(string searchString)\n{\n int i;\n var words = txtBox.Text.Split(\" \");\n\n foreach (var s in words)\n if (s.Contains(searchString))\n i++;\n\n return i;\n}\n"
},
{
"answer_id": 218906,
"author": "JSBձոգչ",
"author_id": 8078,
"author_profile": "https://Stackoverflow.com/users/8078",
"pm_score": 0,
"selected": false,
"text": " Stream response = webRequest.GetResponse().GetResponseStream();\n StreamReader reader = new StreamReader(response);\n String line = null;\n\n while ( line = reader.ReadLine() ) \n {\n if (line.Contains(\"hello\"))\n {\n // increment your counter\n }\n }\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,945
|
<p>Can I have multiple primary keys in a single table?</p>
|
[
{
"answer_id": 217952,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 9,
"selected": false,
"text": "CREATE TABLE userdata (\n userid INT,\n userdataid INT,\n info char(200),\n primary key (userid, userdataid)\n);\n"
},
{
"answer_id": 219306,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "AUTO_INCREMENT IDENTITY mysql> create table foo (\n id int primary key auto_increment, \n id2 int auto_increment\n);\nERROR 1075 (42000): Incorrect table definition; \nthere can be only one auto column and it must be defined as a key\n"
},
{
"answer_id": 420009,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "CREATE TABLE CHAPTER (\n BOOK_ISBN VARCHAR(50) NOT NULL,\n IDX INT NOT NULL,\n TITLE VARCHAR(100) NOT NULL,\n NUM_OF_PAGES INT,\n PRIMARY KEY (BOOK_ISBN, IDX)\n);\n"
},
{
"answer_id": 6383117,
"author": "esengineer",
"author_id": 556678,
"author_profile": "https://Stackoverflow.com/users/556678",
"pm_score": 4,
"selected": false,
"text": "DROP TABLE IF EXISTS `test`.`animals`;\nCREATE TABLE `test`.`animals` (\n `grp` char(30) NOT NULL,\n `id` mediumint(9) NOT NULL AUTO_INCREMENT,\n `name` char(30) NOT NULL,\n PRIMARY KEY (`grp`,`id`)\n) ENGINE=MyISAM;\n\nINSERT INTO animals (grp,name) VALUES\n ('mammal','dog'),('mammal','cat'),\n ('bird','penguin'),('fish','lax'),('mammal','whale'),\n ('bird','ostrich');\n\nSELECT * FROM animals ORDER BY grp,id;\n\nWhich returns:\n\n+--------+----+---------+\n| grp | id | name |\n+--------+----+---------+\n| fish | 1 | lax |\n| mammal | 1 | dog |\n| mammal | 2 | cat |\n| mammal | 3 | whale |\n| bird | 1 | penguin |\n| bird | 2 | ostrich |\n+--------+----+---------+\n"
},
{
"answer_id": 6383206,
"author": "Yet Another Geek",
"author_id": 689867,
"author_profile": "https://Stackoverflow.com/users/689867",
"pm_score": 3,
"selected": false,
"text": "Person(id, name, email, street, zip_code, area)\n id -> name,email, street, zip_code and area zip_code area zip_code -> area Person(id, name, email, street, zip_code)\nArea(zip_code, name)\n"
},
{
"answer_id": 36395434,
"author": "Pieter Geerkens",
"author_id": 1624450,
"author_profile": "https://Stackoverflow.com/users/1624450",
"pm_score": 3,
"selected": false,
"text": "ALTER TABLE Persons\nADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)\n"
},
{
"answer_id": 46497390,
"author": "Rusiru Adithya Samarasinghe",
"author_id": 3628865,
"author_profile": "https://Stackoverflow.com/users/3628865",
"pm_score": 2,
"selected": false,
"text": "CREATE t1(\nc1 int NOT NULL,\nc2 int NOT NULL UNIQUE,\n...,\nPRIMARY KEY (c1)\n);\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
217,951
|
<p>How can I retrieve the current working directory of cmd.exe? </p>
<p>This seems possible. For example using ProcessExplorer, select CMD.exe, right click, properties, Image tab, "Current Directory" relects the directory set using the CD or CHDIR commands.</p>
<p>I've looked at the .NET Process and ProcessStartInfo classes (ProcessStartInfo.WorkingDirectory always returns "") and can't seem to find a way of determining this. Nothing at <a href="http://www.pinvoke.net/" rel="noreferrer">PInvoke</a> stands out either. </p>
<p>As an example I'm looking to programmatically be able to say something like: Process.GetCurrentWorkingDirectory(processID) where processID is a Windows process ID of another running process. </p>
<p>Is there any solution, WinAPI or .NET?</p>
<p>[Update]</p>
<p>Reason for asking this question:</p>
<p>I've used the "Command Prompt Explorer Bar" for a while and it's great except if I "CD" to a new directory, the current Explorer window does not also change. (ie the Sync is only 1 way from Explorer to the commmand prompt). I'm looking to make this 2 way.</p>
|
[
{
"answer_id": 217963,
"author": "Veynom",
"author_id": 11670,
"author_profile": "https://Stackoverflow.com/users/11670",
"pm_score": 3,
"selected": false,
"text": "set OLDDIR=%CD%\n.. do stuff ..\nchdir /d %OLDDIR% &rem restore current directory\n $(get-location)\n"
},
{
"answer_id": 218723,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Diagnostics;\nusing System.IO;\n\nnamespace Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n Process[] procList = Process.GetProcessesByName(\"cmd\");\n\n string sFileName;\n\n for (int i = 0; i < procList.Length; i++ )\n {\n Console.Write(procList[i].Id);\n Console.Write(\" \");\n\n try\n {\n sFileName = procList[i].Modules[0].FileName;\n Console.Write(\"(\");\n Console.Write(Path.GetFileName(sFileName));\n Console.Write(\"): \");\n Console.WriteLine(Path.GetDirectoryName(sFileName));\n }\n catch (Exception ex)\n {\n // catch \"Access denied\" etc.\n Console.WriteLine(ex.Message);\n }\n\n\n }\n\n }\n }\n}\n"
},
{
"answer_id": 219312,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": "// Get Command Line Block\n\n// At offset 0x00020498 is the process current directory followed by\n\n// the system PATH. After that is the process full command line, followed\n\n// by the exe name and the windows station it's running on.\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/217951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.