qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
154,469
|
<p>A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:</p>
<pre><code>namespace {
int cannotAccessOutsideThisFile() { ... }
} // namespace
</code></pre>
<p>You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces <em>are</em> accessible within the file they're created in, as if you had an implicit using-clause to them.</p>
<p>My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?</p>
|
[
{
"answer_id": 154482,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 10,
"selected": true,
"text": "static static namespace namespace"
},
{
"answer_id": 155734,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "XmlUtil_I { ... } XmlUtil_I:: _I XmlUtil"
},
{
"answer_id": 156834,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 5,
"selected": false,
"text": "foo(void*) foo(S const &) template <typename T>\nint b1 (T const & t)\n{\n foo(t);\n}\n\nnamespace NS\n{\n namespace\n {\n struct S\n {\n public:\n operator void * () const;\n };\n\n void foo (void*);\n static void foo (S const &); // Not considered 14.6.4.2(b1)\n }\n\n}\n\nvoid b2()\n{\n NS::S s;\n b1 (s);\n}\n export static // bar.h\nexport template <typename T>\nint b1 (T const & t);\n\n// bar.cc\n#include \"bar.h\"\ntemplate <typename T>\nint b1 (T const & t)\n{\n foo(t);\n}\n\n// foo.cc\n#include \"bar.h\"\nnamespace NS\n{\n namespace\n {\n struct S\n {\n };\n\n void foo (S const & s); // Will be found by different TU 'bar.cc'\n }\n}\n\nvoid b2()\n{\n NS::S s;\n b1 (s);\n}\n static"
},
{
"answer_id": 8436207,
"author": "Chris",
"author_id": 1009377,
"author_profile": "https://Stackoverflow.com/users/1009377",
"pm_score": 2,
"selected": false,
"text": "namespace {\n static int flag;\n}\n"
},
{
"answer_id": 43464911,
"author": "masrtis",
"author_id": 1181561,
"author_profile": "https://Stackoverflow.com/users/1181561",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n\nnamespace\n{\n void unreferenced()\n {\n std::cout << \"Unreferenced\";\n }\n\n void referenced()\n {\n std::cout << \"Referenced\";\n }\n}\n\nstatic void static_unreferenced()\n{\n std::cout << \"Unreferenced\";\n}\n\nstatic void static_referenced()\n{\n std::cout << \"Referenced\";\n}\n\nint main()\n{\n referenced();\n static_referenced();\n return 0;\n}\n"
},
{
"answer_id": 62176221,
"author": "Lewis Kelsey",
"author_id": 7194773,
"author_profile": "https://Stackoverflow.com/users/7194773",
"pm_score": 3,
"selected": false,
"text": "_ZN12_GLOBAL__N_11bE _ZL1b .global #include<iostream>\nnamespace {\n int a = 3;\n}\n\nstatic int b = 4;\nint c = 5;\n\nint main (){\n std::cout << a << b << c;\n}\n\n .data\n .align 4\n .type _ZN12_GLOBAL__N_11aE, @object\n .size _ZN12_GLOBAL__N_11aE, 4\n_ZN12_GLOBAL__N_11aE:\n .long 3\n .align 4\n .type _ZL1b, @object\n .size _ZL1b, 4\n_ZL1b:\n .long 4\n .globl c\n .align 4\n .type c, @object\n .size c, 4\nc:\n .long 5\n .text\n namespace {\n namespace {\n int a = 3;\n }\n}\n\n .data\n .align 4\n .type _ZN12_GLOBAL__N_112_GLOBAL__N_11aE, @object\n .size _ZN12_GLOBAL__N_112_GLOBAL__N_11aE, 4\n_ZN12_GLOBAL__N_112_GLOBAL__N_11aE:\n .long 3\n namespace {\n namespace A {\n int a = 3;\n }\n}\n\n .data\n .align 4\n .type _ZN12_GLOBAL__N_11A1aE, @object\n .size _ZN12_GLOBAL__N_11A1aE, 4\n_ZN12_GLOBAL__N_11A1aE:\n .long 3\n\nwhich for the record demangles as:\n .data\n .align 4\n .type (anonymous namespace)::A::a, @object\n .size (anonymous namespace)::A::a, 4\n(anonymous namespace)::A::a:\n .long 3\n\n//inline has the same output\n inline inline namespace {\n inline namespace {\n int a = 3;\n }\n}\n _ZL1b _Z L static 1 b b _ZN12_GLOBAL__N_11aE _Z N 12 _GLOBAL__N_1 _GLOBAL__N_1 1 a a a E _ZN12_GLOBAL__N_11A1aE 1A A A _GLOBAL__N_1"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
154,483
|
<p>I would like to do some condition formatting of strings. I know that you can do some conditional formatting of integers and floats as follows:</p>
<pre><code>Int32 i = 0;
i.ToString("$#,##0.00;($#,##0.00);Zero");
</code></pre>
<p>The above code would result in one of three formats if the variable is positive, negative, or zero.</p>
<p>I would like to know if there is any way to use sections on string arguments. For a concrete, but <strong>contrived</strong> example, I would be looking to replace the "if" check in the following code:</p>
<pre><code>string MyFormatString(List<String> items, List<String> values)
{
string itemList = String.Join(", " items.ToArray());
string valueList = String.Join(", " values.ToArray());
string formatString;
if (items.Count > 0)
//this could easily be:
//if (!String.IsNullOrEmpty(itemList))
{
formatString = "Items: {0}; Values: {1}";
}
else
{
formatString = "Values: {1}";
}
return String.Format(formatString, itemList, valueList);
}
</code></pre>
|
[
{
"answer_id": 154487,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 1,
"selected": false,
"text": "formatString = (items.Count > 0) ? \"Items: {0}; Values: {1}\" : \"Values: {1}\";\n"
},
{
"answer_id": 154492,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 3,
"selected": false,
"text": "return items.Count > 0 \n ? String.Format(\"Items: {0}; Values: {1}\", itemList, valueList)\n : String.Format(\"Values: {0}\", valueList); \n"
},
{
"answer_id": 154493,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "string formatString = items.Count > 0 ? \"Items: {0}; Values: {1}\" : \"Values: {1}\";\nreturn string.Format(formatString, itemList, valueList);\n return string.Format(items.Count > 0 ? \"Items: {0}; Values: {1}\" : \"Values: {1}\",\n itemList, valueList);\n"
},
{
"answer_id": 154550,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "return String.Format(items.ToString(itemList + \" ;;\") + \"Values: {0}\", valueList);\n"
},
{
"answer_id": 154674,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "string.Format( (items.Count > 0 ? \"Items: {0}; \" : \"\") + \"Values {1}\"\n , itemList\n , valueList); \n"
},
{
"answer_id": 7014583,
"author": "Andrey Agibalov",
"author_id": 852604,
"author_profile": "https://Stackoverflow.com/users/852604",
"pm_score": 1,
"selected": false,
"text": "ToString() if"
},
{
"answer_id": 8526840,
"author": "JYelton",
"author_id": 161052,
"author_profile": "https://Stackoverflow.com/users/161052",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Like String.Format, but if any parameter is null, the nullOutput string is returned.\n/// </summary>\npublic static string StringFormatNull(string format, string nullOutput, params object[] args)\n{\n return args.Any(o => o == null) ? nullOutput : String.Format(format, args);\n}\n double? temp1 = 20.0;\ndouble? temp2 = null;\n\nstring out1 = StringFormatNull(\"{0}°C\", \"N/A\", temp1); // \"20°C\"\nstring out2 = StringFormatNull(\"{0}°C\", \"N/A\", temp2); // \"N/A\"\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] |
154,485
|
<p>The title pretty much says it all. I want to create a SqlConnection and then check that connection without opening a database, cause at that point I don't know yet where will I connect to. Is it possible to do that?
The SqlConnection class has a 'Open' member which tries to open the database you'd set in the Database property, and if you didn't set one, SqlServer tries with the master db. The thing is the user I'm trying to connect with (MACHINE\ASPNET) has access to some databases (which I don't know yet) and not the master db.</p>
<p>Regards,
Seba</p>
|
[
{
"answer_id": 154527,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "SELECT HAS_DBACCESS('Northwind');\n SELECT [Name] as DatabaseName from master.dbo.sysdatabases\nWHERE ISNULL(HAS_DBACCESS ([Name]),0)=1\nORDER BY [Name]\n"
},
{
"answer_id": 8276158,
"author": "soni",
"author_id": 1066540,
"author_profile": "https://Stackoverflow.com/users/1066540",
"pm_score": -1,
"selected": false,
"text": "dim con as new sqlconnection\ncon.connectionstring=\"<<put your conn string here>>\"\n'try...catch block fires exception if the con is not successfully opened\ntry\ncon.open()\ncatch ex as exception\nmsgbox ex.message\nend try\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23893/"
] |
154,489
|
<p>I've been trying this a few different ways, but I'm reaching the conclusion that it can't be done. It's a language feature I've enjoyed from other languages in the past. Is it just something I should just write off?</p>
|
[
{
"answer_id": 154524,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)\nEncoding y = Encoding[\"Foo\"]; // Equivalent to Encoding.GetEncoding(\"Foo\")\n"
},
{
"answer_id": 3510465,
"author": "Giorgi Chakhidze",
"author_id": 96009,
"author_profile": "https://Stackoverflow.com/users/96009",
"pm_score": 4,
"selected": false,
"text": "public class MyEncoding\n{\n public sealed class EncodingIndexer\n {\n public Encoding this[string name]\n {\n get { return Encoding.GetEncoding(name); }\n }\n\n public Encoding this[int codepage]\n {\n get { return Encoding.GetEncoding(codepage); }\n }\n }\n\n private static EncodingIndexer StaticIndexer;\n\n public static EncodingIndexer Items\n {\n get { return StaticIndexer ?? (StaticIndexer = new EncodingIndexer()); }\n }\n}\n Encoding x = MyEncoding.Items[28591]; // Equivalent to Encoding.GetEncoding(28591) \nEncoding y = MyEncoding.Items[\"Foo\"]; // Equivalent to Encoding.GetEncoding(\"Foo\") \n"
},
{
"answer_id": 35398508,
"author": "dynamichael",
"author_id": 1148881,
"author_profile": "https://Stackoverflow.com/users/1148881",
"pm_score": 0,
"selected": false,
"text": "namespace MyExample {\n\n public class Memory {\n public static readonly MemoryRegister Register = new MemoryRegister();\n\n public class MemoryRegister {\n private int[] _values = new int[100];\n\n public int this[int index] {\n get { return _values[index]; }\n set { _values[index] = value; }\n }\n }\n }\n}\n Memory.Register[0] = 12 * 12;\n?Memory.Register[0]\n144\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
154,501
|
<p>I'm looking for a program that I can install on a Mac that will tell me how many bytes I download each day, and store that info in such a way that I could later view the results.</p>
<p>Limiting by ports (80, 443, 21, 22) would be awesome as well.</p>
<p>Does such a thing exist?</p>
|
[
{
"answer_id": 155878,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": 0,
"selected": false,
"text": "netstat -ib\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12930/"
] |
154,502
|
<p>I'm having issues with color matching css background colors with colors in images on the same html page. What gives?</p>
|
[
{
"answer_id": 154512,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "pngcrush"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489/"
] |
154,533
|
<p>What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c">this question</a>, how (and is it possible to) do you do the same thing in WPF?</p>
|
[
{
"answer_id": 155585,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 2,
"selected": false,
"text": " public bool PlaySounds\n {\n get { return (bool)GetValue(PlaySoundsProperty); }\n set { SetValue(PlaySoundsProperty, value); }\n }\n\n public static readonly DependencyProperty PlaySoundsProperty =\n DependencyProperty.Register(\"PlaySounds\", typeof(bool), typeof(Options),\n new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnPlaySoundsChanged)));\n\n private static void OnPlaySoundsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n Properties.Settings.Default.PlaySounds = (bool)args.NewValue;\n Properties.Settings.Default.Save();\n }\n PlaySounds = Properties.Settings.Default.PlaySounds;\n <CheckBox Content=\"Play Sounds on new Tweets\" x:Name=\"PlaySoundsCheckBox\" IsChecked=\"{Binding Path=PlaySounds, ElementName=Window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\" />\n"
},
{
"answer_id": 263956,
"author": "Sacha Bruttin",
"author_id": 20761,
"author_profile": "https://Stackoverflow.com/users/20761",
"pm_score": 8,
"selected": true,
"text": "xmlns:p=\"clr-namespace:UserSettings.Properties\"\n UserSettings <TextBlock Height=\"{Binding Source={x:Static p:Settings.Default}, \n Path=Height, Mode=TwoWay}\" ....... />\n protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n{\n Properties.Settings.Default.Save();\n base.OnClosing(e); \n}\n"
},
{
"answer_id": 3972435,
"author": "Remus",
"author_id": 318854,
"author_profile": "https://Stackoverflow.com/users/318854",
"pm_score": 3,
"selected": false,
"text": "<TextBox Text={Binding Source={x:Static p:Settings.Default}, Path=myTextSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} ... />\n"
},
{
"answer_id": 9232225,
"author": "TknoSpz",
"author_id": 1202594,
"author_profile": "https://Stackoverflow.com/users/1202594",
"pm_score": 3,
"selected": false,
"text": "xmlns:p=\"clr-namespace:ThisApplication\"\n <TextBlock Height={Binding Source={x:Static p:MySettings.Default}, Path=Height, ...\n"
},
{
"answer_id": 17407961,
"author": "NathofGod",
"author_id": 985273,
"author_profile": "https://Stackoverflow.com/users/985273",
"pm_score": 2,
"selected": false,
"text": " public Boolean Value\n {\n get\n {\n return Settings.Default.Value;\n\n }\n set\n {\n Settings.Default.SomeValue= value;\n Settings.Default.Save();\n Notify(\"SomeValue\");\n }\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
154,535
|
<p>I have used Photoshop CS2's "Save for Web" feature to create a table of images for my site layout.</p>
<p>This HTML appears fine in a web browser, however when imported into Visual Studio and viewed in the site designer, the metrics are wrong and there are horizontal gaps between images (table cells).</p>
<p>The output from Photoshop does not refer to any stylesheets.<br>
The table attributes set border, cellpadding and cellspacing to 0.</p>
<p>Here is how it looks in the Designer:</p>
<p><img src="https://sites.google.com/site/sizerfx/Home/layout1.png?attredirects=0" alt="alt text"></p>
<p>And here is how it looks in the browser:</p>
<p><img src="https://sites.google.com/site/sizerfx/Home/layout2.png?attredirects=0" alt="alt text"></p>
<p>Is Visual Studio picky about layout of tables and images? Is this a bug in Visual Studio 2005?</p>
|
[
{
"answer_id": 155585,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 2,
"selected": false,
"text": " public bool PlaySounds\n {\n get { return (bool)GetValue(PlaySoundsProperty); }\n set { SetValue(PlaySoundsProperty, value); }\n }\n\n public static readonly DependencyProperty PlaySoundsProperty =\n DependencyProperty.Register(\"PlaySounds\", typeof(bool), typeof(Options),\n new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnPlaySoundsChanged)));\n\n private static void OnPlaySoundsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n {\n Properties.Settings.Default.PlaySounds = (bool)args.NewValue;\n Properties.Settings.Default.Save();\n }\n PlaySounds = Properties.Settings.Default.PlaySounds;\n <CheckBox Content=\"Play Sounds on new Tweets\" x:Name=\"PlaySoundsCheckBox\" IsChecked=\"{Binding Path=PlaySounds, ElementName=Window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\" />\n"
},
{
"answer_id": 263956,
"author": "Sacha Bruttin",
"author_id": 20761,
"author_profile": "https://Stackoverflow.com/users/20761",
"pm_score": 8,
"selected": true,
"text": "xmlns:p=\"clr-namespace:UserSettings.Properties\"\n UserSettings <TextBlock Height=\"{Binding Source={x:Static p:Settings.Default}, \n Path=Height, Mode=TwoWay}\" ....... />\n protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n{\n Properties.Settings.Default.Save();\n base.OnClosing(e); \n}\n"
},
{
"answer_id": 3972435,
"author": "Remus",
"author_id": 318854,
"author_profile": "https://Stackoverflow.com/users/318854",
"pm_score": 3,
"selected": false,
"text": "<TextBox Text={Binding Source={x:Static p:Settings.Default}, Path=myTextSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} ... />\n"
},
{
"answer_id": 9232225,
"author": "TknoSpz",
"author_id": 1202594,
"author_profile": "https://Stackoverflow.com/users/1202594",
"pm_score": 3,
"selected": false,
"text": "xmlns:p=\"clr-namespace:ThisApplication\"\n <TextBlock Height={Binding Source={x:Static p:MySettings.Default}, Path=Height, ...\n"
},
{
"answer_id": 17407961,
"author": "NathofGod",
"author_id": 985273,
"author_profile": "https://Stackoverflow.com/users/985273",
"pm_score": 2,
"selected": false,
"text": " public Boolean Value\n {\n get\n {\n return Settings.Default.Value;\n\n }\n set\n {\n Settings.Default.SomeValue= value;\n Settings.Default.Save();\n Notify(\"SomeValue\");\n }\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/414107/"
] |
154,536
|
<p>Does anyone know of any good C++ code that does this?</p>
|
[
{
"answer_id": 4823686,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "string urlDecode(string &SRC) {\n string ret;\n char ch;\n int i, ii;\n for (i=0; i<SRC.length(); i++) {\n if (SRC[i]=='%') {\n sscanf(SRC.substr(i+1,2).c_str(), \"%x\", &ii);\n ch=static_cast<char>(ii);\n ret+=ch;\n i=i+2;\n } else {\n ret+=SRC[i];\n }\n }\n return (ret);\n}\n"
},
{
"answer_id": 8732830,
"author": "moonlightdock",
"author_id": 117161,
"author_profile": "https://Stackoverflow.com/users/117161",
"pm_score": 3,
"selected": false,
"text": " LPTSTR lpOutputBuffer = new TCHAR[1];\n DWORD dwSize = 1;\n BOOL fRes = ::InternetCanonicalizeUrl(strUrl, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);\n DWORD dwError = ::GetLastError();\n if (!fRes && dwError == ERROR_INSUFFICIENT_BUFFER)\n {\n delete lpOutputBuffer;\n lpOutputBuffer = new TCHAR[dwSize];\n fRes = ::InternetCanonicalizeUrl(strUrl, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);\n if (fRes)\n {\n //lpOutputBuffer has decoded url\n }\n else\n {\n //failed to decode\n }\n if (lpOutputBuffer !=NULL)\n {\n delete [] lpOutputBuffer;\n lpOutputBuffer = NULL;\n }\n }\n else\n {\n //some other error OR the input string url is just 1 char and was successfully decoded\n }\n"
},
{
"answer_id": 17708801,
"author": "xperroni",
"author_id": 476920,
"author_profile": "https://Stackoverflow.com/users/476920",
"pm_score": 7,
"selected": false,
"text": "#include <cctype>\n#include <iomanip>\n#include <sstream>\n#include <string>\n\nusing namespace std;\n\nstring url_encode(const string &value) {\n ostringstream escaped;\n escaped.fill('0');\n escaped << hex;\n\n for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {\n string::value_type c = (*i);\n\n // Keep alphanumeric and other accepted characters intact\n if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {\n escaped << c;\n continue;\n }\n\n // Any other characters are percent-encoded\n escaped << uppercase;\n escaped << '%' << setw(2) << int((unsigned char) c);\n escaped << nouppercase;\n }\n\n return escaped.str();\n}\n"
},
{
"answer_id": 19875024,
"author": "Johan",
"author_id": 1405259,
"author_profile": "https://Stackoverflow.com/users/1405259",
"pm_score": 1,
"selected": false,
"text": "#include <string>\n#include <iostream>\n\nint main(int argc, char** argv)\n{\n const std::string src(\"/some.url/foo/../bar/%2e/\");\n std::cout << \"src=\\\"\" << src << \"\\\"\" << std::endl;\n\n // either do it the C++ conformant way:\n char* dst_buf = new char[src.size() + 1];\n urldecode(dst_buf, src.c_str(), 1);\n std::string dst1(dst_buf);\n delete[] dst_buf;\n std::cout << \"dst1=\\\"\" << dst1 << \"\\\"\" << std::endl;\n\n // or in-place with the &[0] trick to skip the new/delete\n std::string dst2;\n dst2.resize(src.size() + 1);\n dst2.resize(urldecode(&dst2[0], src.c_str(), 1));\n std::cout << \"dst2=\\\"\" << dst2 << \"\\\"\" << std::endl;\n}\n src=\"/some.url/foo/../bar/%2e/\"\ndst1=\"/some.url/bar/\"\ndst2=\"/some.url/bar/\"\n #include <stddef.h>\n#include <ctype.h>\n\n/**\n * decode a percent-encoded C string with optional path normalization\n *\n * The buffer pointed to by @dst must be at least strlen(@src) bytes.\n * Decoding stops at the first character from @src that decodes to null.\n * Path normalization will remove redundant slashes and slash+dot sequences,\n * as well as removing path components when slash+dot+dot is found. It will\n * keep the root slash (if one was present) and will stop normalization\n * at the first questionmark found (so query parameters won't be normalized).\n *\n * @param dst destination buffer\n * @param src source buffer\n * @param normalize perform path normalization if nonzero\n * @return number of valid characters in @dst\n * @author Johan Lindh <johan@linkdata.se>\n * @legalese BSD licensed (http://opensource.org/licenses/BSD-2-Clause)\n */\nptrdiff_t urldecode(char* dst, const char* src, int normalize)\n{\n char* org_dst = dst;\n int slash_dot_dot = 0;\n char ch, a, b;\n do {\n ch = *src++;\n if (ch == '%' && isxdigit(a = src[0]) && isxdigit(b = src[1])) {\n if (a < 'A') a -= '0';\n else if(a < 'a') a -= 'A' - 10;\n else a -= 'a' - 10;\n if (b < 'A') b -= '0';\n else if(b < 'a') b -= 'A' - 10;\n else b -= 'a' - 10;\n ch = 16 * a + b;\n src += 2;\n }\n if (normalize) {\n switch (ch) {\n case '/':\n if (slash_dot_dot < 3) {\n /* compress consecutive slashes and remove slash-dot */\n dst -= slash_dot_dot;\n slash_dot_dot = 1;\n break;\n }\n /* fall-through */\n case '?':\n /* at start of query, stop normalizing */\n if (ch == '?')\n normalize = 0;\n /* fall-through */\n case '\\0':\n if (slash_dot_dot > 1) {\n /* remove trailing slash-dot-(dot) */\n dst -= slash_dot_dot;\n /* remove parent directory if it was two dots */\n if (slash_dot_dot == 3)\n while (dst > org_dst && *--dst != '/')\n /* empty body */;\n slash_dot_dot = (ch == '/') ? 1 : 0;\n /* keep the root slash if any */\n if (!slash_dot_dot && dst == org_dst && *dst == '/')\n ++dst;\n }\n break;\n case '.':\n if (slash_dot_dot == 1 || slash_dot_dot == 2) {\n ++slash_dot_dot;\n break;\n }\n /* fall-through */\n default:\n slash_dot_dot = 0;\n }\n }\n *dst++ = ch;\n } while(ch);\n return (dst - org_dst) - 1;\n}\n"
},
{
"answer_id": 25335173,
"author": "Yuriy Petrovskiy",
"author_id": 614735,
"author_profile": "https://Stackoverflow.com/users/614735",
"pm_score": 4,
"selected": false,
"text": "namespace boost {\n namespace network {\n namespace uri { \n inline std::string decoded(const std::string &input);\n inline std::string encoded(const std::string &input);\n }\n }\n}\n"
},
{
"answer_id": 28326411,
"author": "Sergey K.",
"author_id": 1065190,
"author_profile": "https://Stackoverflow.com/users/1065190",
"pm_score": -1,
"selected": false,
"text": "clParseURL URL = clParseURL::ParseURL( \"https://name:pwd@github.com:80/path/res\" );\n\nif ( URL.IsValid() )\n{\n cout << \"Scheme : \" << URL.m_Scheme << endl;\n cout << \"Host : \" << URL.m_Host << endl;\n cout << \"Port : \" << URL.m_Port << endl;\n cout << \"Path : \" << URL.m_Path << endl;\n cout << \"Query : \" << URL.m_Query << endl;\n cout << \"Fragment : \" << URL.m_Fragment << endl;\n cout << \"User name : \" << URL.m_UserName << endl;\n cout << \"Password : \" << URL.m_Password << endl;\n}\n"
},
{
"answer_id": 29674916,
"author": "kreuzerkrieg",
"author_id": 1530018,
"author_profile": "https://Stackoverflow.com/users/1530018",
"pm_score": 3,
"selected": false,
"text": "namespace bsq = boost::spirit::qi;\nnamespace bk = boost::spirit::karma;\nbsq::int_parser<unsigned char, 16, 2, 2> hex_byte;\ntemplate <typename InputIterator>\nstruct unescaped_string\n : bsq::grammar<InputIterator, std::string(char const *)> {\n unescaped_string() : unescaped_string::base_type(unesc_str) {\n unesc_char.add(\"+\", ' ');\n\n unesc_str = *(unesc_char | \"%\" >> hex_byte | bsq::char_);\n }\n\n bsq::rule<InputIterator, std::string(char const *)> unesc_str;\n bsq::symbols<char const, char const> unesc_char;\n};\n\ntemplate <typename OutputIterator>\nstruct escaped_string : bk::grammar<OutputIterator, std::string(char const *)> {\n escaped_string() : escaped_string::base_type(esc_str) {\n\n esc_str = *(bk::char_(\"a-zA-Z0-9_.~-\") | \"%\" << bk::right_align(2,0)[bk::hex]);\n }\n bk::rule<OutputIterator, std::string(char const *)> esc_str;\n};\n std::string unescape(const std::string &input) {\n std::string retVal;\n retVal.reserve(input.size());\n typedef std::string::const_iterator iterator_type;\n\n char const *start = \"\";\n iterator_type beg = input.begin();\n iterator_type end = input.end();\n unescaped_string<iterator_type> p;\n\n if (!bsq::parse(beg, end, p(start), retVal))\n retVal = input;\n return retVal;\n}\n\nstd::string escape(const std::string &input) {\n typedef std::back_insert_iterator<std::string> sink_type;\n std::string retVal;\n retVal.reserve(input.size() * 3);\n sink_type sink(retVal);\n char const *start = \"\";\n\n escaped_string<sink_type> g;\n if (!bk::generate(sink, g(start), input))\n retVal = input;\n return retVal;\n}\n"
},
{
"answer_id": 29962178,
"author": "tormuto",
"author_id": 2298136,
"author_profile": "https://Stackoverflow.com/users/2298136",
"pm_score": 4,
"selected": false,
"text": "string urlEncode(string str){\n string new_str = \"\";\n char c;\n int ic;\n const char* chars = str.c_str();\n char bufHex[10];\n int len = strlen(chars);\n\n for(int i=0;i<len;i++){\n c = chars[i];\n ic = c;\n // uncomment this if you want to encode spaces with +\n /*if (c==' ') new_str += '+'; \n else */if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') new_str += c;\n else {\n sprintf(bufHex,\"%X\",c);\n if(ic < 16) \n new_str += \"%0\"; \n else\n new_str += \"%\";\n new_str += bufHex;\n }\n }\n return new_str;\n }\n\nstring urlDecode(string str){\n string ret;\n char ch;\n int i, ii, len = str.length();\n\n for (i=0; i < len; i++){\n if(str[i] != '%'){\n if(str[i] == '+')\n ret += ' ';\n else\n ret += str[i];\n }else{\n sscanf(str.substr(i + 1, 2).c_str(), \"%x\", &ii);\n ch = static_cast<char>(ii);\n ret += ch;\n i = i + 2;\n }\n }\n return ret;\n}\n"
},
{
"answer_id": 30499405,
"author": "Gabe Rainbow",
"author_id": 1869322,
"author_profile": "https://Stackoverflow.com/users/1869322",
"pm_score": 1,
"selected": false,
"text": "#include <ctype.h> // isdigit, tolower\n\nfrom_hex(char ch) {\n return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;\n}\n\nchar to_hex(char code) {\n static char hex[] = \"0123456789abcdef\";\n return hex[code & 15];\n}\n char d = from_hex(hex[0]) << 4 | from_hex(hex[1]);\n // %7B = '{'\n\nchar d = from_hex('7') << 4 | from_hex('B');\n"
},
{
"answer_id": 32595923,
"author": "kometen",
"author_id": 319826,
"author_profile": "https://Stackoverflow.com/users/319826",
"pm_score": 3,
"selected": false,
"text": "#include <iostream>\n#include <sstream>\n#include <string>\n\nusing namespace std;\n\nchar from_hex(char ch) {\n return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;\n}\n\nstring url_decode(string text) {\n char h;\n ostringstream escaped;\n escaped.fill('0');\n\n for (auto i = text.begin(), n = text.end(); i != n; ++i) {\n string::value_type c = (*i);\n\n if (c == '%') {\n if (i[1] && i[2]) {\n h = from_hex(i[1]) << 4 | from_hex(i[2]);\n escaped << h;\n i += 2;\n }\n } else if (c == '+') {\n escaped << ' ';\n } else {\n escaped << c;\n }\n }\n\n return escaped.str();\n}\n\nint main(int argc, char** argv) {\n string msg = \"J%C3%B8rn!\";\n cout << msg << endl;\n string decodemsg = url_decode(msg);\n cout << decodemsg << endl;\n\n return 0;\n}\n"
},
{
"answer_id": 33639602,
"author": "Alfredo Meraz",
"author_id": 3171390,
"author_profile": "https://Stackoverflow.com/users/3171390",
"pm_score": 0,
"selected": false,
"text": "void urlEncode(char *string)\n{\n char charToEncode;\n int posToEncode;\n while (((posToEncode=strspn(string,\"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~\"))!=0) &&(posToEncode<strlen(string)))\n {\n charToEncode=string[posToEncode];\n memmove(string+posToEncode+3,string+posToEncode+1,strlen(string+posToEncode));\n string[posToEncode]='%';\n string[posToEncode+1]=\"0123456789ABCDEF\"[charToEncode>>4];\n string[posToEncode+2]=\"0123456789ABCDEF\"[charToEncode&0xf];\n string+=posToEncode+3;\n }\n}\n"
},
{
"answer_id": 35941730,
"author": "Vineet Mimrot",
"author_id": 1400558,
"author_profile": "https://Stackoverflow.com/users/1400558",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <glib.h>\nint main() {\n char *uri = \"http://www.example.com?hello world\";\n char *encoded_uri = NULL;\n //as per wiki (https://en.wikipedia.org/wiki/Percent-encoding)\n char *escape_char_str = \"!*'();:@&=+$,/?#[]\"; \n encoded_uri = g_uri_escape_string(uri, escape_char_str, TRUE);\n printf(\"[%s]\\n\", encoded_uri);\n free(encoded_uri);\n\n return 0;\n}\n gcc encoding_URI.c `pkg-config --cflags --libs glib-2.0`\n"
},
{
"answer_id": 36432189,
"author": "Dalzhim",
"author_id": 1279096,
"author_profile": "https://Stackoverflow.com/users/1279096",
"pm_score": 2,
"selected": false,
"text": "folly::uriEscape folly::uriUnescape"
},
{
"answer_id": 41434414,
"author": "jamacoe",
"author_id": 4335480,
"author_profile": "https://Stackoverflow.com/users/4335480",
"pm_score": 2,
"selected": false,
"text": "#include <string>\n\nconst char HEX2DEC[55] =\n{\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,\n -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,\n -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,\n -1,10,11,12, 13,14,15\n};\n\n#define __x2d__(s) HEX2DEC[*(s)-48]\n#define __x2d2__(s) __x2d__(s) << 4 | __x2d__(s+1)\n\nstd::wstring decodeURI(const char * s) {\n unsigned char b;\n std::wstring ws;\n while (*s) {\n if (*s == '%')\n if ((b = __x2d2__(s + 1)) >= 0x80) {\n if (b >= 0xE0) { // three byte codepoint\n ws += ((b & 0b00001111) << 12) | ((__x2d2__(s + 4) & 0b00111111) << 6) | (__x2d2__(s + 7) & 0b00111111);\n s += 9;\n }\n else { // two byte codepoint\n ws += (__x2d2__(s + 4) & 0b00111111) | (b & 0b00000011) << 6;\n s += 6;\n }\n }\n else { // one byte codepoints\n ws += b;\n s += 3;\n }\n else { // no %\n ws += *s;\n s++;\n }\n }\n return ws;\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2033811/"
] |
154,538
|
<p>Long story short, I need to put some text in my Flex application and I don't want users to be able to copy. I was going to use a label, but apparently labels do not support text wrapping. Can I make it so that users cannot select text in a Flex Text control?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 154848,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": 0,
"selected": false,
"text": "print(\"\n <mx:Text enabled=\"false\" disabledColor=\"0x000000\" text=Text\"/>\n\");\n"
},
{
"answer_id": 155055,
"author": "Paul Mignard",
"author_id": 3435,
"author_profile": "https://Stackoverflow.com/users/3435",
"pm_score": 4,
"selected": true,
"text": " <mx:Text width=\"175\" selectable=\"false\" text=\"This is an example of a multiline text string in a Text control.\" />\n"
},
{
"answer_id": 2168175,
"author": "bugmenot",
"author_id": 262496,
"author_profile": "https://Stackoverflow.com/users/262496",
"pm_score": 2,
"selected": false,
"text": "\nprivate function onTextInput(e:flash.events.TextEvent):void\n{\n if (e.text.length > 1) \n e.preventDefault();\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
154,543
|
<p>If you create a panel on a form and set it to Dock=Top and drop another panel and set its Dock=Fill, it may fill the entire form, ignoring the first panel. Changing the tab order does nothing.</p>
|
[
{
"answer_id": 28459277,
"author": "Pandichie Anton-Valentin",
"author_id": 1561462,
"author_profile": "https://Stackoverflow.com/users/1561462",
"pm_score": 3,
"selected": false,
"text": "DockStyle.Fill DockStyle.Fill ComboBox cb = new ComboBox();\ncb.Dock = DockStyle.Top;\n\nGridView gv = new GridView();\ngv.Dock = DockStyle.Fill;\n\nControls.Add(gv); // this is okay\nControls.Add(cb);\n Controls.Add(cb);\nControls.Add(gv); // gv will overlap the combo box.\n"
},
{
"answer_id": 45008286,
"author": "Marcus",
"author_id": 6729394,
"author_profile": "https://Stackoverflow.com/users/6729394",
"pm_score": 2,
"selected": false,
"text": " //Container ------------------------------------\n Panel Container = new Panel();\n\n //Top-Docked Element ---------------------------\n ButtonArea = new FlowLayoutPanel();\n Container.Controls.Add(ButtonArea);\n Container.Controls.SetChildIndex(ButtonArea, 1);\n ButtonArea.Dock = DockStyle.Top;\n\n //Fill-Docked Element --------------------------\n box = new RichTextBox();\n Container.Controls.Add(box);\n Container.Controls.SetChildIndex(box, 0); //setting this to 0 does the trick\n box.Dock = DockStyle.Fill;\n"
},
{
"answer_id": 50235194,
"author": "Robert S.",
"author_id": 9758853,
"author_profile": "https://Stackoverflow.com/users/9758853",
"pm_score": 0,
"selected": false,
"text": "object.dock = Fill\nPanel.Controls.Add(object)\n"
},
{
"answer_id": 55936236,
"author": "DrLechter",
"author_id": 10671414,
"author_profile": "https://Stackoverflow.com/users/10671414",
"pm_score": 0,
"selected": false,
"text": "parentForm.Controls.SetChildIndex (myPanel, 0) \n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2277/"
] |
154,551
|
<p>Let's say that a class has a <code>public int counter</code> field that is accessed by multiple threads. This <code>int</code> is only incremented or decremented.</p>
<p>To increment this field, which approach should be used, and why?</p>
<ul>
<li><code>lock(this.locker) this.counter++;</code>,</li>
<li><code>Interlocked.Increment(ref this.counter);</code>,</li>
<li>Change the access modifier of <code>counter</code> to <code>public volatile</code>.</li>
</ul>
<p>Now that I've discovered <code>volatile</code>, I've been removing many <code>lock</code> statements and the use of <code>Interlocked</code>. But is there a reason not to do this?</p>
|
[
{
"answer_id": 154582,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": false,
"text": "Interlocked volatile"
},
{
"answer_id": 154590,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 6,
"selected": false,
"text": "volatile Interlocked.Increment Interlocked.Increment"
},
{
"answer_id": 154803,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 11,
"selected": true,
"text": "counter public volatile volatile volatile volatile lock(this.locker) this.counter++ lock this.counter locker locker Interlocked.Increment(ref this.counter); volatile queueLength queueLength"
},
{
"answer_id": 904842,
"author": "Kenneth Xu",
"author_id": 111877,
"author_profile": "https://Stackoverflow.com/users/111877",
"pm_score": 3,
"selected": false,
"text": "D:\\>InterlockVsMonitor.exe 16\nUsing 16 threads:\n InterlockAtomic.RunIncrement (ns): 8355 Average, 8302 Minimal, 8409 Maxmial\n MonitorVolatileAtomic.RunIncrement (ns): 7077 Average, 6843 Minimal, 7243 Maxmial\n\nD:\\>InterlockVsMonitor.exe 4\nUsing 4 threads:\n InterlockAtomic.RunIncrement (ns): 4319 Average, 4319 Minimal, 4321 Maxmial\n MonitorVolatileAtomic.RunIncrement (ns): 933 Average, 802 Minimal, 1018 Maxmial\n"
},
{
"answer_id": 6456302,
"author": "Zach Saw",
"author_id": 383306,
"author_profile": "https://Stackoverflow.com/users/383306",
"pm_score": 6,
"selected": false,
"text": "while (m_Var)\n{ }\n"
},
{
"answer_id": 53581921,
"author": "V. S.",
"author_id": 10014202,
"author_profile": "https://Stackoverflow.com/users/10014202",
"pm_score": 2,
"selected": false,
"text": "volatile Interlocked lock sbyte byte short ushort int uint char float bool byte sbyte short int uint IntPtr UIntPtr double long Interlocked lock"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] |
154,554
|
<p>I'm writing a simple web service using Microsoft Visual Web Developer 2005 (Express Edition), and the dynamically generated WSDL has a minOccurs="0" for all the parameters. </p>
<p>How do I get minOccurs="1" for the required parameters without resorting to creating a static WSDL file?</p>
<p>I need to do this <strong>using a ASP.NET Web Service</strong> (.NET v2). So, no WCF.</p>
|
[
{
"answer_id": 189317,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "XmlElement(IsNullable = true) using System.Xml.Serialization;\n\n[WebMethod]\npublic string MyService([XmlElement(IsNullable = true)] string arg)\n{\n return \"1\";\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23899/"
] |
154,577
|
<p>In terms of Java, when someone asks: </p>
<blockquote>
<p>what is polymorphism?</p>
</blockquote>
<p>Would <strong>overloading</strong> or <strong>overriding</strong> be an acceptable answer?</p>
<p>I think there is a bit more to it than that. </p>
<p><em>IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?</em></p>
<p>I think <strong>overloading</strong> is not the right answer for sure.</p>
|
[
{
"answer_id": 154594,
"author": "Clyde",
"author_id": 945,
"author_profile": "https://Stackoverflow.com/users/945",
"pm_score": 2,
"selected": false,
"text": "public int DoSomething(int objectId) { ... }\npublic int DoSomething(string objectName) { ... }\n"
},
{
"answer_id": 154628,
"author": "Mark A. Nicolosi",
"author_id": 1103052,
"author_profile": "https://Stackoverflow.com/users/1103052",
"pm_score": 5,
"selected": false,
"text": "class Animal\n{\n abstract string MakeNoise ();\n}\n\nclass Cat : Animal {\n string MakeNoise () {\n return \"Meow\";\n }\n}\n\nclass Dog : Animal {\n string MakeNoise () {\n return \"Bark\";\n }\n}\n\nMain () {\n Animal animal = Zoo.GetAnimal ();\n Console.WriteLine (animal.MakeNoise ());\n}\n"
},
{
"answer_id": 154631,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 6,
"selected": false,
"text": " abstract class Beverage {\n boolean isAcceptableTemperature();\n }\n\n class Coffee extends Beverage {\n boolean isAcceptableTemperature() { \n return temperature > 70;\n }\n }\n\n class Wine extends Beverage {\n boolean isAcceptableTemperature() { \n return temperature < 10;\n }\n }\n class Server {\n public void pour (Coffee liquid) {\n new Cup().fillToTopWith(liquid);\n }\n\n public void pour (Wine liquid) {\n new WineGlass().fillHalfwayWith(liquid);\n }\n\n public void pour (Lemonade liquid, boolean ice) {\n Glass glass = new Glass();\n if (ice) {\n glass.fillToTopWith(new Ice());\n }\n glass.fillToTopWith(liquid);\n }\n }\n"
},
{
"answer_id": 154646,
"author": "Jason Peacock",
"author_id": 18381,
"author_profile": "https://Stackoverflow.com/users/18381",
"pm_score": 2,
"selected": false,
"text": "int countStuff(List stuff) {\n return stuff.size();\n}\n List myStuff = new MyTotallyAwesomeList();\nint result = countStuff(myStuff);\n int countStuff(LinkedList stuff) {...}\nint countStuff(ArrayList stuff) {...}\nint countStuff(MyTotallyAwesomeList stuff) {...}\netc...\n"
},
{
"answer_id": 154668,
"author": "Lorenzo Boccaccia",
"author_id": 2273540,
"author_profile": "https://Stackoverflow.com/users/2273540",
"pm_score": 0,
"selected": false,
"text": "class animal {\n public void makeRumor(){\n print(\"thump\");\n }\n}\nclass dog extends animal {\n public void makeRumor(){\n print(\"woff\");\n }\n}\n\nanimal a = new dog();\ndog b = new dog();\n\na.makeRumor() -> prints thump\nb.makeRumor() -> prints woff\n a.makeRumor() -> prints thump\nb.makeRumor() -> prints woff\n"
},
{
"answer_id": 154939,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 11,
"selected": true,
"text": "public abstract class Human{\n ...\n public abstract void goPee();\n}\n goPee() public class Male extends Human{\n...\n @Override\n public void goPee(){\n System.out.println(\"Stand Up\");\n }\n}\n public class Female extends Human{\n...\n @Override\n public void goPee(){\n System.out.println(\"Sit Down\");\n }\n}\n public static void main(String[] args){\n ArrayList<Human> group = new ArrayList<Human>();\n group.add(new Male());\n group.add(new Female());\n // ... add more...\n\n // tell the class to take a pee break\n for (Human person : group) person.goPee();\n}\n Stand Up\nSit Down\n...\n"
},
{
"answer_id": 12371564,
"author": "Rajan",
"author_id": 1506709,
"author_profile": "https://Stackoverflow.com/users/1506709",
"pm_score": 2,
"selected": false,
"text": " public void See(Friend)\n {\n System.out.println(\"Talk\");\n }\n public void See(Enemy)\n {\n System.out.println(\"Run\");\n }\n"
},
{
"answer_id": 18818192,
"author": "Desolator",
"author_id": 326904,
"author_profile": "https://Stackoverflow.com/users/326904",
"pm_score": 2,
"selected": false,
"text": "Animals movement() movement() Dogs Cats Fish Animals movement() Interfaces"
},
{
"answer_id": 31455175,
"author": "bharanitharan",
"author_id": 358099,
"author_profile": "https://Stackoverflow.com/users/358099",
"pm_score": 1,
"selected": false,
"text": "import java.io.IOException;\n\nclass Super {\n\n protected Super getClassName(Super s) throws IOException {\n System.out.println(this.getClass().getSimpleName() + \" - I'm parent\");\n return null;\n }\n\n}\n\nclass SubOne extends Super {\n\n @Override\n protected Super getClassName(Super s) {\n System.out.println(this.getClass().getSimpleName() + \" - I'm Perfect Overriding\");\n return null;\n }\n\n}\n\nclass SubTwo extends Super {\n\n @Override\n protected Super getClassName(Super s) throws NullPointerException {\n System.out.println(this.getClass().getSimpleName() + \" - I'm Overriding and Throwing Runtime Exception\");\n return null;\n }\n\n}\n\nclass SubThree extends Super {\n\n @Override\n protected SubThree getClassName(Super s) {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Overriding and Returning SubClass Type\");\n return null;\n }\n\n}\n\nclass SubFour extends Super {\n\n @Override\n protected Super getClassName(Super s) throws IOException {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Overriding and Throwing Narrower Exception \");\n return null;\n }\n\n}\n\nclass SubFive extends Super {\n\n @Override\n public Super getClassName(Super s) {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Overriding and have broader Access \");\n return null;\n }\n\n}\n\nclass SubSix extends Super {\n\n public Super getClassName(Super s, String ol) {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Perfect Overloading \");\n return null;\n }\n\n}\n\nclass SubSeven extends Super {\n\n public Super getClassName(SubSeven s) {\n System.out.println(this.getClass().getSimpleName()+ \" - I'm Perfect Overloading because Method signature (Argument) changed.\");\n return null;\n }\n\n}\n\npublic class Test{\n\n public static void main(String[] args) throws Exception {\n\n System.out.println(\"Overriding\\n\");\n\n Super s1 = new SubOne(); s1.getClassName(null);\n\n Super s2 = new SubTwo(); s2.getClassName(null);\n\n Super s3 = new SubThree(); s3.getClassName(null);\n\n Super s4 = new SubFour(); s4.getClassName(null);\n\n Super s5 = new SubFive(); s5.getClassName(null);\n\n System.out.println(\"Overloading\\n\");\n\n SubSix s6 = new SubSix(); s6.getClassName(null, null);\n\n s6 = new SubSix(); s6.getClassName(null);\n\n SubSeven s7 = new SubSeven(); s7.getClassName(s7);\n\n s7 = new SubSeven(); s7.getClassName(new Super());\n\n }\n}\n"
},
{
"answer_id": 39532917,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 2,
"selected": false,
"text": "super.methodName() import java.util.HashMap;\n\nabstract class Game implements Runnable{\n\n protected boolean runGame = true;\n protected Player player1 = null;\n protected Player player2 = null;\n protected Player currentPlayer = null;\n\n public Game(){\n player1 = new Player(\"Player 1\");\n player2 = new Player(\"Player 2\");\n currentPlayer = player1;\n initializeGame();\n }\n\n /* Type 1: Let subclass define own implementation. Base class defines abstract method to force\n sub-classes to define implementation \n */\n\n protected abstract void initializeGame();\n\n /* Type 2: Sub-class can change the behaviour. If not, base class behaviour is applicable */\n protected void logTimeBetweenMoves(Player player){\n System.out.println(\"Base class: Move Duration: player.PlayerActTime - player.MoveShownTime\");\n }\n\n /* Type 3: Base class provides implementation. Sub-class can enhance base class implementation by calling\n super.methodName() in first line of the child class method and specific implementation later */\n protected void logGameStatistics(){\n System.out.println(\"Base class: logGameStatistics:\");\n }\n /* Type 4: Template method: Structure of base class can't be changed but sub-class can some part of behaviour */\n protected void runGame() throws Exception{\n System.out.println(\"Base class: Defining the flow for Game:\"); \n while ( runGame) {\n /*\n 1. Set current player\n 2. Get Player Move\n */\n validatePlayerMove(currentPlayer); \n logTimeBetweenMoves(currentPlayer);\n Thread.sleep(500);\n setNextPlayer();\n }\n logGameStatistics();\n }\n /* sub-part of the template method, which define child class behaviour */\n protected abstract void validatePlayerMove(Player p);\n\n protected void setRunGame(boolean status){\n this.runGame = status;\n }\n public void setCurrentPlayer(Player p){\n this.currentPlayer = p;\n }\n public void setNextPlayer(){\n if ( currentPlayer == player1) {\n currentPlayer = player2;\n }else{\n currentPlayer = player1;\n }\n }\n public void run(){\n try{\n runGame();\n }catch(Exception err){\n err.printStackTrace();\n }\n }\n}\n\nclass Player{\n String name;\n Player(String name){\n this.name = name;\n }\n public String getName(){\n return name;\n }\n}\n\n/* Concrete Game implementation */\nclass Chess extends Game{\n public Chess(){\n super();\n }\n public void initializeGame(){\n System.out.println(\"Child class: Initialized Chess game\");\n }\n protected void validatePlayerMove(Player p){\n System.out.println(\"Child class: Validate Chess move:\"+p.getName());\n }\n protected void logGameStatistics(){\n super.logGameStatistics();\n System.out.println(\"Child class: Add Chess specific logGameStatistics:\");\n }\n}\nclass TicTacToe extends Game{\n public TicTacToe(){\n super();\n }\n public void initializeGame(){\n System.out.println(\"Child class: Initialized TicTacToe game\");\n }\n protected void validatePlayerMove(Player p){\n System.out.println(\"Child class: Validate TicTacToe move:\"+p.getName());\n }\n}\n\npublic class Polymorphism{\n public static void main(String args[]){\n try{\n\n Game game = new Chess();\n Thread t1 = new Thread(game);\n t1.start();\n Thread.sleep(1000);\n game.setRunGame(false);\n Thread.sleep(1000);\n\n game = new TicTacToe();\n Thread t2 = new Thread(game);\n t2.start();\n Thread.sleep(1000);\n game.setRunGame(false);\n\n }catch(Exception err){\n err.printStackTrace();\n } \n }\n}\n Child class: Initialized Chess game\nBase class: Defining the flow for Game:\nChild class: Validate Chess move:Player 1\nBase class: Move Duration: player.PlayerActTime - player.MoveShownTime\nChild class: Validate Chess move:Player 2\nBase class: Move Duration: player.PlayerActTime - player.MoveShownTime\nBase class: logGameStatistics:\nChild class: Add Chess specific logGameStatistics:\nChild class: Initialized TicTacToe game\nBase class: Defining the flow for Game:\nChild class: Validate TicTacToe move:Player 1\nBase class: Move Duration: player.PlayerActTime - player.MoveShownTime\nChild class: Validate TicTacToe move:Player 2\nBase class: Move Duration: player.PlayerActTime - player.MoveShownTime\nBase class: logGameStatistics:\n"
},
{
"answer_id": 50202481,
"author": "Developer",
"author_id": 5465732,
"author_profile": "https://Stackoverflow.com/users/5465732",
"pm_score": 3,
"selected": false,
"text": "import java.util.Scanner; \nclass VolumeControllerV1 {\n private int value;\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of VolumeController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of VolumeController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\nclass BrightnessControllerV1 {\n private int value;\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of BrightnessController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of BrightnessController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\nclass ColourControllerV1 {\n private int value;\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of ColourController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of ColourController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\n\n/*\n * There can be n number of controllers\n * */\npublic class TvApplicationV1 {\n public static void main(String[] args) {\n VolumeControllerV1 volumeControllerV1 = new VolumeControllerV1();\n BrightnessControllerV1 brightnessControllerV1 = new BrightnessControllerV1();\n ColourControllerV1 colourControllerV1 = new ColourControllerV1();\n\n\n OUTER: while(true) {\n Scanner sc=new Scanner(System.in);\n System.out.println(\" Enter your option \\n Press 1 to increase volume \\n Press 2 to decrease volume\");\n System.out.println(\" Press 3 to increase brightness \\n Press 4 to decrease brightness\");\n System.out.println(\" Press 5 to increase color \\n Press 6 to decrease color\");\n System.out.println(\"Press any other Button to shutdown\");\n int button = sc.nextInt();\n switch (button) {\n case 1: {\n volumeControllerV1.adjust(5);\n break;\n }\n case 2: {\n volumeControllerV1.adjust(-5);\n break;\n }\n case 3: {\n brightnessControllerV1.adjust(5);\n break;\n }\n case 4: {\n brightnessControllerV1.adjust(-5);\n break;\n }\n case 5: {\n colourControllerV1.adjust(5);\n break;\n }\n case 6: {\n colourControllerV1.adjust(-5);\n break;\n }\n default:\n System.out.println(\"Shutting down...........\");\n break OUTER;\n }\n\n }\n }\n}\n import java.util.Scanner;\nclass VolumeControllerV2 {\n\n private int defaultValue = 25;\n private int value;\n\n int getDefaultValue() {\n return defaultValue;\n }\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of VolumeController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of VolumeController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\nclass BrightnessControllerV2 {\n\n private int defaultValue = 50;\n private int value;\n int get() {\n return value;\n }\n int getDefaultValue() {\n return defaultValue;\n }\n void set(int value) {\n System.out.println(\"Old value of BrightnessController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of BrightnessController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\nclass ColourControllerV2 {\n\n private int defaultValue = 40;\n private int value;\n int get() {\n return value;\n }\n int getDefaultValue() {\n return defaultValue;\n }\n void set(int value) {\n System.out.println(\"Old value of ColourController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of ColourController \\t\"+this.value);\n }\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\n\nclass ResetFunctionV2 {\n\n private VolumeControllerV2 volumeControllerV2 ;\n private BrightnessControllerV2 brightnessControllerV2;\n private ColourControllerV2 colourControllerV2;\n\n ResetFunctionV2(VolumeControllerV2 volumeControllerV2, BrightnessControllerV2 brightnessControllerV2, ColourControllerV2 colourControllerV2) {\n this.volumeControllerV2 = volumeControllerV2;\n this.brightnessControllerV2 = brightnessControllerV2;\n this.colourControllerV2 = colourControllerV2;\n }\n void onReset() {\n volumeControllerV2.set(volumeControllerV2.getDefaultValue());\n brightnessControllerV2.set(brightnessControllerV2.getDefaultValue());\n colourControllerV2.set(colourControllerV2.getDefaultValue());\n }\n}\n/*\n * so on\n * There can be n number of controllers\n *\n * */\npublic class TvApplicationV2 {\n public static void main(String[] args) {\n VolumeControllerV2 volumeControllerV2 = new VolumeControllerV2();\n BrightnessControllerV2 brightnessControllerV2 = new BrightnessControllerV2();\n ColourControllerV2 colourControllerV2 = new ColourControllerV2();\n\n ResetFunctionV2 resetFunctionV2 = new ResetFunctionV2(volumeControllerV2, brightnessControllerV2, colourControllerV2);\n\n OUTER: while(true) {\n Scanner sc=new Scanner(System.in);\n System.out.println(\" Enter your option \\n Press 1 to increase volume \\n Press 2 to decrease volume\");\n System.out.println(\" Press 3 to increase brightness \\n Press 4 to decrease brightness\");\n System.out.println(\" Press 5 to increase color \\n Press 6 to decrease color\");\n System.out.println(\" Press 7 to reset TV \\n Press any other Button to shutdown\");\n int button = sc.nextInt();\n switch (button) {\n case 1: {\n volumeControllerV2.adjust(5);\n break;\n }\n case 2: {\n volumeControllerV2.adjust(-5);\n break;\n }\n case 3: {\n brightnessControllerV2.adjust(5);\n break;\n }\n case 4: {\n brightnessControllerV2.adjust(-5);\n break;\n }\n case 5: {\n colourControllerV2.adjust(5);\n break;\n }\n case 6: {\n colourControllerV2.adjust(-5);\n break;\n }\n case 7: {\n resetFunctionV2.onReset();\n break;\n }\n default:\n System.out.println(\"Shutting down...........\");\n break OUTER;\n }\n\n }\n }\n}\n import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\nabstract class ControllerV3 {\n abstract void set(int value);\n abstract int get();\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n abstract void setDefault();\n}\nclass VolumeControllerV3 extends ControllerV3 {\n\n private int defaultValue = 25;\n private int value;\n\n public void setDefault() {\n set(defaultValue);\n }\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of VolumeController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of VolumeController \\t\"+this.value);\n }\n}\nclass BrightnessControllerV3 extends ControllerV3 {\n\n private int defaultValue = 50;\n private int value;\n\n public void setDefault() {\n set(defaultValue);\n }\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of BrightnessController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of BrightnessController \\t\"+this.value);\n }\n}\nclass ColourControllerV3 extends ControllerV3 {\n\n private int defaultValue = 40;\n private int value;\n\n public void setDefault() {\n set(defaultValue);\n }\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of ColourController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of ColourController \\t\"+this.value);\n }\n}\n\nclass ResetFunctionV3 {\n\n private List<ControllerV3> controllers = null;\n\n ResetFunctionV3(List<ControllerV3> controllers) {\n this.controllers = controllers;\n }\n void onReset() {\n for (ControllerV3 controllerV3 :this.controllers) {\n controllerV3.setDefault();\n }\n }\n}\n/*\n * so on\n * There can be n number of controllers\n *\n * */\npublic class TvApplicationV3 {\n public static void main(String[] args) {\n VolumeControllerV3 volumeControllerV3 = new VolumeControllerV3();\n BrightnessControllerV3 brightnessControllerV3 = new BrightnessControllerV3();\n ColourControllerV3 colourControllerV3 = new ColourControllerV3();\n\n List<ControllerV3> controllerV3s = new ArrayList<>();\n controllerV3s.add(volumeControllerV3);\n controllerV3s.add(brightnessControllerV3);\n controllerV3s.add(colourControllerV3);\n\n ResetFunctionV3 resetFunctionV3 = new ResetFunctionV3(controllerV3s);\n\n OUTER: while(true) {\n Scanner sc=new Scanner(System.in);\n System.out.println(\" Enter your option \\n Press 1 to increase volume \\n Press 2 to decrease volume\");\n System.out.println(\" Press 3 to increase brightness \\n Press 4 to decrease brightness\");\n System.out.println(\" Press 5 to increase color \\n Press 6 to decrease color\");\n System.out.println(\" Press 7 to reset TV \\n Press any other Button to shutdown\");\n int button = sc.nextInt();\n switch (button) {\n case 1: {\n volumeControllerV3.adjust(5);\n break;\n }\n case 2: {\n volumeControllerV3.adjust(-5);\n break;\n }\n case 3: {\n brightnessControllerV3.adjust(5);\n break;\n }\n case 4: {\n brightnessControllerV3.adjust(-5);\n break;\n }\n case 5: {\n colourControllerV3.adjust(5);\n break;\n }\n case 6: {\n colourControllerV3.adjust(-5);\n break;\n }\n case 7: {\n resetFunctionV3.onReset();\n break;\n }\n default:\n System.out.println(\"Shutting down...........\");\n break OUTER;\n }\n\n }\n }\n}\n import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\ninterface OnReset {\n void setDefault();\n}\ninterface OnStart {\n void checkForDriverUpdate();\n}\nabstract class ControllerV4 implements OnReset,OnStart {\n abstract void set(int value);\n abstract int get();\n void adjust(int value) {\n int temp = this.get();\n if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) {\n System.out.println(\"Can not adjust any further\");\n return;\n }\n this.set(temp + value);\n }\n}\n\nclass VolumeControllerV4 extends ControllerV4 {\n\n private int defaultValue = 25;\n private int value;\n @Override\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of VolumeController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of VolumeController \\t\"+this.value);\n }\n @Override\n public void setDefault() {\n set(defaultValue);\n }\n\n @Override\n public void checkForDriverUpdate() {\n System.out.println(\"Checking driver update for VolumeController .... Done\");\n }\n}\nclass BrightnessControllerV4 extends ControllerV4 {\n\n private int defaultValue = 50;\n private int value;\n @Override\n int get() {\n return value;\n }\n @Override\n void set(int value) {\n System.out.println(\"Old value of BrightnessController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of BrightnessController \\t\"+this.value);\n }\n\n @Override\n public void setDefault() {\n set(defaultValue);\n }\n\n @Override\n public void checkForDriverUpdate() {\n System.out.println(\"Checking driver update for BrightnessController .... Done\");\n }\n}\nclass ColourControllerV4 extends ControllerV4 {\n\n private int defaultValue = 40;\n private int value;\n @Override\n int get() {\n return value;\n }\n void set(int value) {\n System.out.println(\"Old value of ColourController \\t\"+this.value);\n this.value = value;\n System.out.println(\"New value of ColourController \\t\"+this.value);\n }\n @Override\n public void setDefault() {\n set(defaultValue);\n }\n\n @Override\n public void checkForDriverUpdate() {\n System.out.println(\"Checking driver update for ColourController .... Done\");\n }\n}\nclass ResetFunctionV4 {\n\n private List<OnReset> controllers = null;\n\n ResetFunctionV4(List<OnReset> controllers) {\n this.controllers = controllers;\n }\n void onReset() {\n for (OnReset onreset :this.controllers) {\n onreset.setDefault();\n }\n }\n}\nclass InitializeDeviceV4 {\n\n private List<OnStart> controllers = null;\n\n InitializeDeviceV4(List<OnStart> controllers) {\n this.controllers = controllers;\n }\n void initialize() {\n for (OnStart onStart :this.controllers) {\n onStart.checkForDriverUpdate();\n }\n }\n}\n/*\n* so on\n* There can be n number of controllers\n*\n* */\npublic class TvApplicationV4 {\n public static void main(String[] args) {\n VolumeControllerV4 volumeControllerV4 = new VolumeControllerV4();\n BrightnessControllerV4 brightnessControllerV4 = new BrightnessControllerV4();\n ColourControllerV4 colourControllerV4 = new ColourControllerV4();\n List<ControllerV4> controllerV4s = new ArrayList<>();\n controllerV4s.add(brightnessControllerV4);\n controllerV4s.add(volumeControllerV4);\n controllerV4s.add(colourControllerV4);\n\n List<OnStart> controllersToInitialize = new ArrayList<>();\n controllersToInitialize.addAll(controllerV4s);\n InitializeDeviceV4 initializeDeviceV4 = new InitializeDeviceV4(controllersToInitialize);\n initializeDeviceV4.initialize();\n\n List<OnReset> controllersToReset = new ArrayList<>();\n controllersToReset.addAll(controllerV4s);\n ResetFunctionV4 resetFunctionV4 = new ResetFunctionV4(controllersToReset);\n\n OUTER: while(true) {\n Scanner sc=new Scanner(System.in);\n System.out.println(\" Enter your option \\n Press 1 to increase volume \\n Press 2 to decrease volume\");\n System.out.println(\" Press 3 to increase brightness \\n Press 4 to decrease brightness\");\n System.out.println(\" Press 5 to increase color \\n Press 6 to decrease color\");\n System.out.println(\" Press 7 to reset TV \\n Press any other Button to shutdown\");\n int button = sc.nextInt();\n switch (button) {\n case 1: {\n volumeControllerV4.adjust(5);\n break;\n }\n case 2: {\n volumeControllerV4.adjust(-5);\n break;\n }\n case 3: {\n brightnessControllerV4.adjust(5);\n break;\n }\n case 4: {\n brightnessControllerV4.adjust(-5);\n break;\n }\n case 5: {\n colourControllerV4.adjust(5);\n break;\n }\n case 6: {\n colourControllerV4.adjust(-5);\n break;\n }\n case 7: {\n resetFunctionV4.onReset();\n break;\n }\n default:\n System.out.println(\"Shutting down...........\");\n break OUTER;\n }\n\n }\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
154,597
|
<p>Note, I realize that this has been addressed <a href="https://stackoverflow.com/questions/944/unhandled-exception-handler-in-net-11">here</a>. That post discusses exception handling in .NET 1.1 while implying that there is a better solution for >.NET 2.0 so this question is specifically about the more recent .NET versions.</p>
<p>I have a windows forms application which is expected to frequently and unexpectedly lose connectivity to the database, in which case it is to reset itself to its initial state.</p>
<p>I am already doing error logging, retry connection, etc. through a set of decorators on my custom DBWrapper object. After that is taken care of however, I would like to let the error fall through the stack. Once it reaches the top and is unhandled I would like it to be swallowed and my ApplicationResetter.Reset() method to be executed.</p>
<p>Can anyone tell me how to do this?</p>
<p>If this is impossible, then is there at least a way to handle this without introducing a dependency on ApplicationResetter to every class which might receive such an error and without actually shutting down and restarting my application (which would just look ugly)?</p>
|
[
{
"answer_id": 154656,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 1,
"selected": false,
"text": "static void Main()\n{\n Application.ThreadException += Application_ThreadException;\n //...\n }\n\n static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)\n {\n // call ApplicationResetter.Reset() here\n }\n"
},
{
"answer_id": 154665,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 1,
"selected": false,
"text": "System.Windows.Forms.Application.ThreadException System.AppDomain.CurrentDomain.UnhandledException"
},
{
"answer_id": 154792,
"author": "Qwertie",
"author_id": 22820,
"author_profile": "https://Stackoverflow.com/users/22820",
"pm_score": 1,
"selected": true,
"text": "Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);\nApplication.ThreadException += ShowUnhandledException;\nApplication.Run(...);\n static void ShowUnhandledException(object sender, ThreadExceptionEventArgs t)\n{\n Exception ex = t.Exception;\n try {\n // Build a message to show to the user\n bool first = true;\n string msg = string.Empty;\n for (int i = 0; i < 3 && ex != null; i++) {\n msg += string.Format(\"{0} {1}:\\n\\n{2}\\n\\n{3}\", \n first ? \"Unhandled \" : \"Inner exception \",\n ex.GetType().Name,\n ex.Message, \n i < 2 ? ex.StackTrace : \"\");\n ex = ex.InnerException;\n first = false;\n }\n msg += \"\\n\\nAttempt to continue? (click No to exit now)\";\n\n // Show the message\n if (MessageBox.Show(msg, \"Unhandled exception\", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.No)\n Application.Exit();\n } catch (Exception e2) {\n try {\n MessageBox.Show(e2.Message, \"Fatal error\", MessageBoxButtons.OK, MessageBoxIcon.Stop);\n } finally {\n Application.Exit();\n }\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
154,598
|
<p>IO.popen() and system() in Ruby is sorely lacking several useful features, such as:</p>
<ul>
<li>obtaining the return value of the function</li>
<li>capturing both stdout and stderr (seperately and merged)</li>
<li>running without spawning an extra cmd.exe or /bin/sh process</li>
</ul>
<p>Python has a module "subprocess" which I was thinking about using as inspiration for a similar module in Ruby. Now to the questions:</p>
<ul>
<li>How are Ruby-programmers working around the issues above, for example obtaining the return value when doing a popen() call?</li>
<li>Is this something which has already been implemented?</li>
</ul>
|
[
{
"answer_id": 154703,
"author": "Priit",
"author_id": 22964,
"author_profile": "https://Stackoverflow.com/users/22964",
"pm_score": 3,
"selected": false,
"text": "$?.exitstatus system 'command 2>&1'"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13051/"
] |
154,625
|
<p>I've noticed that sometimes wrapper scripts will use <code>${1:+"$@"}</code> for the parameters rather than just <code>"$@"</code>.</p>
<p>For example, <a href="http://svn.macosforge.org/repository/macports/trunk/dports/editors/vim-app/files/gvim.sh" rel="noreferrer">http://svn.macosforge.org/repository/macports/trunk/dports/editors/vim-app/files/gvim.sh</a> uses</p>
<pre><code>exec "$binary" $opts ${1:+"$@"}
</code></pre>
<p>Can anyone break <code>${1:+"$@"}</code> down into English and explain why it would be an advantage over plain <code>"$@"</code>?</p>
|
[
{
"answer_id": 154637,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": " ${parameter:+word}\n Use Alternate Value. If parameter is null or unset, nothing is\n substituted, otherwise the expansion of word is substituted.\n \"$@\" $1 \"$@\""
},
{
"answer_id": 155044,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 6,
"selected": true,
"text": "$1 \"\" \"$@\" command '' arg2 arg3 ...\n ${1+\"$@\"}\n $1"
},
{
"answer_id": 1601852,
"author": "Dennis Williamson",
"author_id": 26428,
"author_profile": "https://Stackoverflow.com/users/26428",
"pm_score": 2,
"selected": false,
"text": "man bash"
},
{
"answer_id": 73562238,
"author": "juj",
"author_id": 191096,
"author_profile": "https://Stackoverflow.com/users/191096",
"pm_score": 0,
"selected": false,
"text": "$* cat"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
154,630
|
<p>Other than <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall" rel="nofollow noreferrer">-Wall</a>, what other warnings have people found useful?</p>
<p><em><a href="http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html" rel="nofollow noreferrer">Options to Request or Suppress Warnings</a></em></p>
|
[
{
"answer_id": 154851,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 6,
"selected": false,
"text": "gcc -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wcast-qual \\\n -Wstrict-prototypes -Wmissing-prototypes\n"
},
{
"answer_id": 1308599,
"author": "amaterasu",
"author_id": 158234,
"author_profile": "https://Stackoverflow.com/users/158234",
"pm_score": 1,
"selected": false,
"text": "gcc -Wall -W -Wunused-parameter -Wmissing-declarations -Wstrict-prototypes -Wmissing-prototypes -Wsign-compare -Wconversion -Wshadow -Wcast-align -Wparentheses -Wsequence-point -Wdeclaration-after-statement -Wundef -Wpointer-arith -Wnested-externs -Wredundant-decls -Werror -Wdisabled-optimization -pedantic -funit-at-a-time -o\n"
},
{
"answer_id": 1667035,
"author": "Josh Lee",
"author_id": 19750,
"author_profile": "https://Stackoverflow.com/users/19750",
"pm_score": 1,
"selected": false,
"text": "-O -g -O -Wall -Werror -Wextra -pedantic -std=c99\n"
},
{
"answer_id": 1667114,
"author": "pmg",
"author_id": 25324,
"author_profile": "https://Stackoverflow.com/users/25324",
"pm_score": 6,
"selected": false,
"text": "gcc -std=c89 -pedantic -Wall \\\n -Wno-missing-braces -Wextra -Wno-missing-field-initializers \\\n -Wformat=2 -Wswitch-default -Wswitch-enum -Wcast-align \\\n -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 \\\n -Wstrict-prototypes -Winline -Wundef -Wnested-externs \\\n -Wcast-qual -Wshadow -Wunreachable-code -Wlogical-op \\\n -Wfloat-equal -Wstrict-aliasing=2 -Wredundant-decls \\\n -Wold-style-definition -Werror \\\n -ggdb3 \\\n -O0 \\\n -fno-omit-frame-pointer -ffloat-store \\\n -fno-common -fstrict-aliasing \\\n -lm\n gcc -std=c89 -pedantic -O3 -DNDEBUG -lm\n gcc -Wall -Wextra -Wformat=2 -Wswitch-default -Wcast-align \\\n -Wpointer-arith -Wbad-function-cast -Wstrict-prototypes \\\n -Winline -Wundef -Wnested-externs -Wcast-qual -Wshadow \\\n -Wwrite-strings -Wconversion -Wunreachable-code \\\n -Wstrict-aliasing=2 \\\n -ffloat-store -fno-common -fstrict-aliasing \\\n -lm -std=c89 -pedantic -O0 -ggdb3 -pg --coverage\n gcc -lm -std=c89 -pedantic -O3 -DNDEBUG --combine \\\n -fwhole-program -funroll-loops\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9831/"
] |
154,636
|
<p>At the moment we use <a href="http://www.hsqldb.org/" rel="noreferrer">HSQLDB</a> as an embedded database, but we search for a database with less memory footprint as the data volume grows.</p>
<p><a href="http://developers.sun.com/javadb/" rel="noreferrer">Derby / JavaDB</a> is not an option at the moment because it stores properties globally in the system properties. So we thought of <a href="http://www.h2database.com/html/main.html" rel="noreferrer">h2</a>.</p>
<p>While we used HSQLDB we created a Server-object, set the parameters and started it. This is described <a href="http://hsqldb.org/doc/guide/ch04.html#N10BBC" rel="noreferrer">here</a> (and given as example in the class org.hsqldb.test.TestBase).</p>
<p>The question is: Can this be done analogous with the h2 database, too? Do you have any code samples for that? Scanning the h2-page, I did not find an example.</p>
|
[
{
"answer_id": 155237,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 6,
"selected": true,
"text": "import org.h2.tools.Server;\n...\n// start the TCP Server\nServer server = Server.createTcpServer(args).start();\n...\n// stop the TCP Server\nserver.stop();\n"
},
{
"answer_id": 155423,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 6,
"selected": false,
"text": "* Add h2.jar to the classpath\n* Use the JDBC driver class: org.h2.Driver\n* The database URL jdbc:h2:~/test opens the database 'test' in your user home directory\n import org.h2.jdbcx.JdbcDataSource;\n// ...\nJdbcDataSource ds = new JdbcDataSource();\nds.setURL(\"jdbc:h2:˜/test\");\nds.setUser(\"sa\");\nds.setPassword(\"sa\");\nConnection conn = ds.getConnection();\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13209/"
] |
154,652
|
<p>Is anyone out there still using DataFlex? If so, what are you favorite tips and tricks for this venerable 4GL?</p>
|
[
{
"answer_id": 155555,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 3,
"selected": true,
"text": "clear orders\nmove const.complete to orders.status\nfind ge orders by index.2\nrepeat\n if orders.status ne const.complete indicate finderr true\n if (not(finderr)) begin\n send doYourStuffHere\n find gt orders by index.2\n end\nuntil (finderr)\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9345/"
] |
154,655
|
<p>We have a VXML project that a 3rd party parses to provide us with a phone navigation system. We require them to enter an id code to leave a message, which is later reviewed by our company.</p>
<p>We currently have this working as follows:</p>
<pre><code>Response.Cache.SetCacheability(HttpCacheability.NoCache);
Stream m = new MemoryStream(); //Create Memory Stream - Used to create XML document in Memory
XmlTextWriter XML_Writer = new XmlTextWriter(m, System.Text.Encoding.UTF8);
XML_Writer.Formatting = Formatting.Indented;
XML_Writer.WriteStartDocument();
/* snip - writing a valid XML document */
XML_Writer.WriteEndDocument();
XML_Writer.Flush();
m.Position = 0;
byte[] b = new byte[m.Length];
m.Read(b, 0, (int)m.Length);
XML_Writer.Close();
HttpContext.Current.Response.Write(System.Text.Encoding.UTF8.GetString(b, 0, b.Length));
</code></pre>
<p>I'm just maintaining this app, I didn't write it...but the end section seems convoluted to me.</p>
<p>I know it's taking the output stream and feeding the written XML into it...but why is it first reading the entire string? Isn't that inefficient?</p>
<p>Is there a better way to write the above code?</p>
|
[
{
"answer_id": 154684,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 2,
"selected": true,
"text": "Output OutputStream XmlTextWriter XML_Writer = new XmlTextWriter(HttpContext.Current.Response.OutputStream, HttpContext.Current.Response.Encoding);\n//...\nXML_Writer.Flush();\n"
},
{
"answer_id": 154700,
"author": "Boaz",
"author_id": 2892,
"author_profile": "https://Stackoverflow.com/users/2892",
"pm_score": 0,
"selected": false,
"text": "\nResponse.Cache.SetCacheability(HttpCacheability.NoCache); \n\n XmlWriter XML_Writer = XmlWriter.Create(HttpContext.Current.Response.Output);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23902/"
] |
154,661
|
<p>Due to the legacy nature of some of our code, we're still using Microsoft Visual 6.0 (SP6). When I attach to a running process to debug it for the first time, it has no knowledge of where the source files are located when I break into the process. It therefore asks me to navigate to the appropriate directory in my source tree, given a source file name. It remembers these directories, so I don't have to enter the same directory twice, but it's still painful.</p>
<p>Is there a way of pre-configuring VC6 with all the source file directories in my tree? Note that our project is built using makefiles (using nmake), rather than via DSPs.</p>
|
[
{
"answer_id": 173240,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 0,
"selected": false,
"text": "REGEDIT4\n\n[HKEY_CURRENT_USER\\Software\\Microsoft\\Devstudio\\6.0\\Build\nSystem\\Components\\Platforms\\Win32 (x86)\\Directories]\n\"Source Dirs\"=\"<path1>;<path2>\"\n msdev /useenv\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2193/"
] |
154,672
|
<p>I asked a question about Lua perfromance, and on of the <a href="https://stackoverflow.com/questions/124455/how-do-you-pre-size-an-array-in-lua#152894">responses</a> asked:</p>
<blockquote>
<p>Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.</p>
</blockquote>
<p>This is a slightly different question from <a href="https://stackoverflow.com/questions/89523/lua-patternstips-and-tricks">Lua Patterns,Tips and Tricks</a> because I'd like answers that specifically impact performance and (if possible) an explanation of why performance is impacted.</p>
<p>One tip per answer would be ideal.</p>
|
[
{
"answer_id": 12865406,
"author": "dualed",
"author_id": 1244588,
"author_profile": "https://Stackoverflow.com/users/1244588",
"pm_score": 7,
"selected": true,
"text": "do\n x = gFoo + gFoo;\nend\ndo -- this actually performs better.\n local lFoo = gFoo;\n x = lFoo + lFoo;\nend\n local x; for i=1, 1000 do x=i; end table.concat -- do NOT do something like this\nlocal ret = \"\";\nfor i=1, C do\n ret = ret..foo();\nend\n foo() A \"\" \"A\" \"AA\" \"AAA\" -- this is a lot faster\nlocal ret = {};\nfor i=1, C do\n ret[#ret+1] = foo();\nend\nret = table.concat(ret);\n foo \"AAAAAA...\" C i #ret+1 some_string:gsub(\".\", function(m)\n return \"A\";\nend);\n foo() foo() ipairs for k=1, #tbl do local v = tbl[k];\n #tbl __ipairs ipairs __len ipairs __len ipairs table.insert table.remove table.insert table.remove # table.insert(foo, bar);\n-- does the same as\nfoo[#foo+1] = bar;\n\nlocal x = table.remove(foo);\n-- does the same as\nlocal x = foo[#foo];\nfoo[#foo] = nil;\n table.remove(foo, 1) if a == \"C\" or a == \"D\" or a == \"E\" or a == \"F\" then\n ...\nend\n local compares = { C = true, D = true, E = true, F = true };\nif compares[a] then\n ...\nend\n pairs() function tmemoize(func)\n return setmetatable({}, {\n __index = function(self, k)\n local v = func(k);\n self[k] = v\n return v;\n end\n });\nend\n-- usage (does not support nil values!)\nlocal mf = tmemoize(myfunc);\nlocal v = mf[x];\n -- Normal function\nfunction foo(a, b, x)\n return cheaper_expression(expensive_expression(a,b), x);\nend\n-- foo(a,b,x1);\n-- foo(a,b,x2);\n-- ...\n\n-- Partial application\nfunction foo(a, b)\n local C = expensive_expression(a,b);\n return function(x)\n return cheaper_expression(C, x);\n end\nend\n-- local f = foo(a,b);\n-- f(x1);\n-- f(x2);\n-- ...\n get_color_values function LinearColorBlender(col_from, col_to)\n local cfr, cfg, cfb, cfa = get_color_values(col_from);\n local ctr, ctg, ctb, cta = get_color_values(col_to);\n local cdr, cdg, cdb, cda = ctr-cfr, ctg-cfg, ctb-cfb, cta-cfa;\n if not cfr or not ctr then\n error(\"One of given arguments is not a color.\");\n end\n\n return function(pos)\n if type(pos) ~= \"number\" then\n error(\"arg1 (pos) must be in range 0..1\");\n end\n if pos < 0 then pos = 0; end;\n if pos > 1 then pos = 1; end;\n return cfr + cdr*pos, cfg + cdg*pos, cfb + cdb*pos, cfa + cda*pos;\n end\nend\n-- Call \nlocal blender = LinearColorBlender({1,1,1,1},{0,0,0,1});\nobject:SetColor(blender(0.1));\nobject:SetColor(blender(0.3));\nobject:SetColor(blender(0.7));\n"
},
{
"answer_id": 44766479,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "struct class"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] |
154,680
|
<p>How would I create the equivalent Linq To Objects query?</p>
<pre><code>SELECT MIN(CASE WHEN p.type = "In" THEN p.PunchTime ELSE NULL END ) AS EarliestIn,
MAX(CASE WHEN p.type = "Out" THEN p.PunchTime ELSE NULL END ) AS LatestOUt
FROM Punches p
</code></pre>
|
[
{
"answer_id": 155059,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": " List<int> myInts = new List<int>() { 1, 4, 2, 0, 3 };\n var y = myInts.Aggregate(\n new { Min = int.MaxValue, Max = int.MinValue },\n (a, i) =>\n new\n {\n Min = (i < a.Min) ? i : a.Min,\n Max = (a.Max < i) ? i : a.Max\n });\n Console.WriteLine(\"{0} {1}\", y.Min, y.Max);\n"
},
{
"answer_id": 2094810,
"author": "DRBlaise",
"author_id": 234720,
"author_profile": "https://Stackoverflow.com/users/234720",
"pm_score": 0,
"selected": false,
"text": "var times = punches.Aggregate(\n new { EarliestIn = default(DateTime?), LatestOut = default(DateTime?) },\n (agg, p) => new {\n EarliestIn = Min(\n agg.EarliestIn,\n p.type == \"In\" ? (DateTime?)p.PunchTime : default(DateTime?)),\n LatestOut = Max(\n agg.LatestOut,\n p.type == \"Out\" ? (DateTime?)p.PunchTime : default(DateTime?)) \n }\n);\n public static DateTime? Max(DateTime? d1, DateTime? d2)\n{\n if (!d1.HasValue)\n return d2;\n if (!d2.HasValue)\n return d1;\n return d1.Value > d2.Value ? d1 : d2;\n}\npublic static DateTime? Min(DateTime? d1, DateTime? d2)\n{\n if (!d1.HasValue)\n return d2;\n if (!d2.HasValue)\n return d1;\n return d1.Value < d2.Value ? d1 : d2;\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6819/"
] |
154,686
|
<p>I've got a stock Debian Etch system, using Exim4. The domains are mostly local but there are some that are remote. To handle the delivery of remote mail I use the Debian configuration file:</p>
<pre><code> /etc/exim4/hubbed_hosts
</code></pre>
<p>This file lists the domain names, and remote MX machines to deliver to. For example:</p>
<pre><code> example.org: mx.example.com
example.com: mx2.example.com
</code></pre>
<p>Looking at the exim4 configuration file I see that this used as follows:</p>
<pre><code>hubbed_hosts:
debug_print = "R: hubbed_hosts for $domain"
driver = manualroute
domains = "${if exists{CONFDIR/hubbed_hosts}\
{partial-lsearch;CONFDIR/hubbed_hosts}\
fail}"
route_data = ${lookup{$domain}partial-lsearch{CONFDIR/hubbed_hosts}}
transport = remote_smtp
</code></pre>
<p>The issue I have is that <em>some</em> of the hosts I'm using need to have their mail delivered to a non-standard port. Unfortunately the Debian hubbed_hosts file doesn't work if I try to change it to include a port:</p>
<pre><code>example.org: mx1.example.org:2525
example.com: 1.2.3.4.2525
</code></pre>
<p>Is it possible to dynamically allow the port to be specified?</p>
|
[
{
"answer_id": 154711,
"author": "manicmethod",
"author_id": 12098,
"author_profile": "https://Stackoverflow.com/users/12098",
"pm_score": 1,
"selected": false,
"text": "remote_hub_2525:\ndriver = smtp\nport = 2525\n non_standard_hub:\ndriver = manualroute\ndomains = example.org : example.com\ntransport = remote_hub_2525\nno_more\n"
},
{
"answer_id": 154796,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": " port = ${if exists{/etc/exim4/ports.list}\\\n {${lookup{$domain}lsearch{/etc/exim4/ports.list}\\\n {$value}{25}}}{25}}\n example.org: 2525\n example.com: 26\n"
},
{
"answer_id": 159880,
"author": "Mark Baker",
"author_id": 11815,
"author_profile": "https://Stackoverflow.com/users/11815",
"pm_score": 2,
"selected": false,
"text": "route_data = ${extract{1}{:}{${lookup{$domain}partial-lsearch{CONFDIR/hubbed_hosts}}}}\n"
},
{
"answer_id": 1950359,
"author": "sherbang",
"author_id": 5026,
"author_profile": "https://Stackoverflow.com/users/5026",
"pm_score": 3,
"selected": false,
"text": "domain1: server1:server2::port:server3\ndomain2: server1::port\ndomain3: server1:server2\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
154,697
|
<p>I'm trying to retrieve numeric values from a <code>DataGridView</code>. So far, the only way I've found is to retrieve them as a string and convert them to numeric.</p>
<pre><code>Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString());
</code></pre>
<p>There must be an easier way. The cell is originally populated from a <code>DataSet</code> with a numeric field value but since the <code>DataGridViewCell</code> object returns it as an object, I can't do a straight assignment. I must be missing something simple here.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 154825,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 0,
"selected": false,
"text": "Convert.ToDouble ToString() TryParse"
},
{
"answer_id": 154945,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 1,
"selected": false,
"text": "DataGridViewCell ValueType if(MyGrid.SelectedRows[0].Cells[0].ValueType!=null &&\n MyGrid.SelectedRows[0].Cells[0].ValueType == Double)\n return (Double)MyGrid.SelectedRows[0].Cells[0].Value;\n"
},
{
"answer_id": 154963,
"author": "Leon Tayson",
"author_id": 18413,
"author_profile": "https://Stackoverflow.com/users/18413",
"pm_score": 0,
"selected": false,
"text": "DataGridViewCell.Value Double numeric DataGridView"
},
{
"answer_id": 155058,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "DataGridViewCell .Value DataTable Convert.To{blah}(...) Convert.ChangeType(...) using System.Data;\nusing System.Windows.Forms;\nstatic class Program\n{\n static void Main()\n {\n Application.EnableVisualStyles();\n DataTable table = new DataTable\n {\n Columns = {\n {\"Foo\", typeof(double)},\n {\"Bar\", typeof(string)}\n },\n Rows = {\n {123.45, \"abc\"},\n {678.90, \"def\"}\n }\n };\n Form form = new Form();\n DataGridView grid = new DataGridView {\n Dock = DockStyle.Fill, DataSource = table};\n form.Controls.Add(grid);\n grid.CurrentCellChanged += delegate\n {\n form.Text = string.Format(\"{0}: {1}\",\n grid.CurrentCell.Value.GetType(),\n grid.CurrentCell.Value);\n\n if (grid.CurrentCell.Value is double)\n {\n double val = (double)grid.CurrentCell.Value;\n form.Text += \" is a double: \" + val;\n }\n };\n Application.Run(form);\n\n }\n}\n"
},
{
"answer_id": 156197,
"author": "Fry",
"author_id": 23553,
"author_profile": "https://Stackoverflow.com/users/23553",
"pm_score": 2,
"selected": false,
"text": "TryParse null TryParse double d = 0;\nif(grid[col,row].Value != null)\n double.TryParse(grid[col,row].Value.ToString(), out d);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
154,698
|
<p>In java, I could do this with the 'final' keyword. I don't see 'final' in C#. Is there a substitute?</p>
|
[
{
"answer_id": 154699,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 6,
"selected": true,
"text": "sealed final"
},
{
"answer_id": 154770,
"author": "Nasir",
"author_id": 16522,
"author_profile": "https://Stackoverflow.com/users/16522",
"pm_score": 2,
"selected": false,
"text": "sealed final"
},
{
"answer_id": 154961,
"author": "dalle",
"author_id": 19100,
"author_profile": "https://Stackoverflow.com/users/19100",
"pm_score": 0,
"selected": false,
"text": "sealed"
},
{
"answer_id": 155552,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 1,
"selected": false,
"text": "sealed final static"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18931/"
] |
154,702
|
<p>We are using the MVC framework (release 5) and the CrystalReportViewer control to show our reports. I cannot get any of the buttons at the top of the report viewer control to work.</p>
<p>If I'm working with the report 'HoursSummary'. If I hover over any of the buttons on the report viewer in IE the displayed link at the bottom of the pages is '../HoursSummary'. This creates a url of '<a href="http://localhost/HoursSummary" rel="noreferrer">http://localhost/HoursSummary</a>'. There is no 'HoursSummary' controller so I keep receiving 404 errors.</p>
<ul>
<li>I believe I want to redirect to '<a href="http://localhost/reports/HoursSummary" rel="noreferrer">http://localhost/reports/HoursSummary</a>' since I do have a reports controller. If this is the correct method does anyone know which property I should set on the CrystalReportViewer control to make that happen?</li>
<li>Is there an easier method to handle this situation?</li>
</ul>
|
[
{
"answer_id": 154699,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 6,
"selected": true,
"text": "sealed final"
},
{
"answer_id": 154770,
"author": "Nasir",
"author_id": 16522,
"author_profile": "https://Stackoverflow.com/users/16522",
"pm_score": 2,
"selected": false,
"text": "sealed final"
},
{
"answer_id": 154961,
"author": "dalle",
"author_id": 19100,
"author_profile": "https://Stackoverflow.com/users/19100",
"pm_score": 0,
"selected": false,
"text": "sealed"
},
{
"answer_id": 155552,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 1,
"selected": false,
"text": "sealed final static"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7561/"
] |
154,706
|
<p>Unfortunately, there seems to be no string.Split(string separator), only string.Split(char speparator).</p>
<p>I want to break up my string based on a multi-character separator, a la VB6. Is there an easy (that is, not by referencing Microsoft.VisualBasic or having to learn RegExes) way to do this in c#?</p>
<p>EDIT: Using .NET Framework 3.5.</p>
|
[
{
"answer_id": 154716,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": ".Split(string[] separator, StringSplitOptions options) \n.Split(string[] separator, int count, StringSplitOptions options)\n"
},
{
"answer_id": 154723,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 4,
"selected": true,
"text": "String.Split() string[] string original = \"first;&second;&third\";\nstring[] splitResults = original.Split( new string[] { \";&\" }, StringSplitOptions.None );\n"
},
{
"answer_id": 154746,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 0,
"selected": false,
"text": "string[] y = { \"bar\" };\n\nstring x = \"foobarfoo\";\nforeach (string s in x.Split(y, StringSplitOptions.None))\n Console.WriteLine(s);\n"
},
{
"answer_id": 154755,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " string[] stringSeparators = new string[] {\"[stop]\"};\n string[] result;\nresult = someString.Split(stringSeparators, StringSplitOptions.None);\n"
},
{
"answer_id": 2210590,
"author": "J.Hendrix",
"author_id": 180385,
"author_profile": "https://Stackoverflow.com/users/180385",
"pm_score": 0,
"selected": false,
"text": "string[] args = \"first;&second;&third\".Split(\";&\".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
154,707
|
<p>I want to store a large number of sound files in a database, but I don't know if it is a good practice. I would like to know the pros and cons of doing it in this way.</p>
<p>I also thought on the possibility to have "links" to those files, but maybe this will carry more problems than solutions. Any experience in this direction will be welcome :)</p>
<p>Note: The database will be MySQL.</p>
|
[
{
"answer_id": 154793,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 3,
"selected": false,
"text": "C:\\MyProgram\\Data\\Sounds\\X\\XYZ.Wav\n X\\XYZ.Wav\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19689/"
] |
154,708
|
<p>Ok, Regex wizards. I want to be able to search through my logfile and find any sessions with the word 'error' in it and then return the entire session log entry.</p>
<p>I know I can do this with a string/array but I'd like to learn how to do it with Regex but here's the question. If I decide to do this with Regex do I <a href="http://www.codinghorror.com/blog/archives/001016.html" rel="nofollow noreferrer">have one or two problems</a>? ;o)</p>
<p>Here's the log:</p>
<p>PS: I'm using the perl Regex engine.</p>
<p><strong>Note</strong>: I don't think I can get this done in Regex. In other words, I now have two problems. ;o) I've tried the solutions below but, since I've confused the issue by stating that I was using a Perl engine, many of the answers were in Perl (which cannot be used in my case). I did however post my solution below.</p>
<hr>
<pre><code>2008.08.27 08:04:21 (Wed)------------Start of Session-----------------
Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19)
Sending stdin.txt to foo@bar.com
Subject: test 1
Login name is foo@bar.com
The SMTP server does not require AUTH LOGIN.
Are you sure server supports AUTH?
The SMTP server does not like the sender name.
Have you set your mail address correctly?
2008.08.27 08:04:24 (Wed)-------------End of Session------------------
2008.08.27 08:05:56 (Wed)------------Start of Session-----------------
Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19)
Error: Wait a bit (possible timeout).
SMTP server error
Error: Not a socket.
Error: Not a socket.
2008.08.27 08:06:26 (Wed)-------------End of Session------------------
2008.08.27 08:07:58 (Wed)------------Start of Session-----------------
Blat v2.6.2 w/GSS encryption (build : Feb 25 2007 12:06:19)
Sending stdin.txt to foo@bar.com
Subject: Lorem Update 08/27/2008
Login name is foo@bar.com
2008.08.27 08:07:58 (Wed)-------------End of Session------------------
</code></pre>
|
[
{
"answer_id": 154743,
"author": "Kyle",
"author_id": 2237619,
"author_profile": "https://Stackoverflow.com/users/2237619",
"pm_score": 3,
"selected": false,
"text": "\nperl -ne 'BEGIN{$/=\"\"} print if /error/i' < logfile\n"
},
{
"answer_id": 154886,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 3,
"selected": false,
"text": "my $re = qr{\n ( # capture in $1\n (?:\n (?!\\n\\n). # Any character that's not at a paragraph break\n )* # repeated\n error\n (?:\n (?!\\n\\n).\n )*\n )\n}msxi;\n\n\nwhile ($s =~ m/$re/g){\n print \"'$1'\\n\";\n}\n"
},
{
"answer_id": 154910,
"author": "KeyserSoze",
"author_id": 14116,
"author_profile": "https://Stackoverflow.com/users/14116",
"pm_score": 0,
"selected": false,
"text": "awk '/-Start of Session-/ { text=\"\"; gotError=0; } /Error/{gotError=1;}/-End of Session-/{ if(gotError) {print text}} { text=text \"\\n\" $0}' logFileName.txt awk -f errorLineParser.awk logFileName.txt"
},
{
"answer_id": 154913,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "Error:.+ \n (?ms)^Error:[^\\r\\n]+$\n Error:\\s*(\\S.+)\n"
},
{
"answer_id": 155013,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "/(?:[^\\n\\r]|\\r?\\n(?!\\r|\\n))*?Error:(?:[^\\n\\r]|\\r?\\n(?!\\r|\\n))*/g\n"
},
{
"answer_id": 162194,
"author": "Keng",
"author_id": 730,
"author_profile": "https://Stackoverflow.com/users/730",
"pm_score": 1,
"selected": true,
"text": "str a b email gp lgf\nlgf.getfile( \"C:\\blat\\log.txt\")\nforeach a lgf\n if(find(a \"--End of Session--\")>-1)\n gp.from(gp \"[]\" a)\n if(find(gp \"error\" 0 1)>-1)\n gp.trim\n email.from(email gp \"[]\")\n gp=\"\"\n continue\n gp.from(gp \"[]\" a)\nemail.trim\n"
},
{
"answer_id": 231530,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 0,
"selected": false,
"text": ":%s:$:# :%s:#\\n#\\n:#\\r@\\r :%s:#\\n:# :v/[Ee]rror/d :%s:#:\\r"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] |
154,718
|
<p>My web application sends email fairly often, and it sends 3 kinds of emails: initiated by user, in response to an event in the system, and in automatic response to an email received by the application.</p>
<p>I would like to make sure that the third type of email does not get stuck in an endless loop of auto-responders talking to each other. Currently, I use the header:</p>
<pre><code>Precedence: junk
</code></pre>
<p>but Yahoo! mail is treating these messages as spam. This is obviously not ideal, because we would like SOMEBODY to read our auto-response and make a decision on it, just not an out-of-office reply.</p>
<p><strong>What is the best way to send an email without triggering either junk filters or auto-responders?</strong></p>
<pre><code>Precedence: junk?
Precedence: bulk?
Precedence: list?
X-Priority: 2?
</code></pre>
|
[
{
"answer_id": 154794,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "Return-Path: <>\n Return-Path"
},
{
"answer_id": 301958,
"author": "user38936",
"author_id": 38936,
"author_profile": "https://Stackoverflow.com/users/38936",
"pm_score": 5,
"selected": false,
"text": "Return-Path Return-Path"
},
{
"answer_id": 8908739,
"author": "guettli",
"author_id": 633961,
"author_profile": "https://Stackoverflow.com/users/633961",
"pm_score": 3,
"selected": false,
"text": "Precedence: bulk\nAuto-Submitted: auto-generated\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3140/"
] |
154,722
|
<p>I've recently come across a feature of doing a large query in oracle, where changing one thing resulted in a query that used to take 10 minutes taking 3 hours.</p>
<p>To briefly summarise, I store a lot of coordinates in the database, with each coordinate having a probability. I then want to 'bin' these coordinates into 50 metre bins (basically round the coordinate down to the nearest 50 metres) and sum the probability.</p>
<p>To do this, part of the query is 'select x,y,sum(probability) from .... group by x,y'</p>
<p>Initially I was storing a large number of points with a probability of 0.1 and queries were running reasonably ok, taking about 10 minutes for each one.</p>
<p>Then I had a request to change how the probabilities were calculated to adjust the distribution, so rather than all of them being 0.1, they were different values (e.g. 0.03, 0.06, 0.12, 0.3, 0.12, 0.06, 0.03). Running exactly the same query resulted in queries of about 3 hours.</p>
<p>Changing back to all 0.1 brought the queries back to 10 minutes.</p>
<p>Looking at the query plan and performance of the system, it looked like the problem was with the 'hash group' functionality designed to speed up grouping in oracle. I'm guessing that it was creating hash entries for each unique x,y,probability value and then summing probability for each unique x,y value.</p>
<p>Can anyone explain this behaviour any better? </p>
<p><strong>Additional Info</strong></p>
<p>Thanks to the answers. They allowed me to verify what was going on. I'm currently running a query and the tempseg_size from v$sql_workarea_active is currently at 7502561280 and growing rapidly.</p>
<p>Given that the development server I'm running on only has 8gb of ram, it looks like the query needs to use temporary tables. </p>
<p>I've managed to workaround this for now by changing the types of queries and precalculating some of the information.</p>
|
[
{
"answer_id": 156072,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 2,
"selected": false,
"text": "explain plan for\nselect x,y,sum(probability) from .... group by x,y\n/\n\nselect * from table(dbms_xplan.display)\n/\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
] |
154,724
|
<p>The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When have you needed to use a <code>WeakHashMap</code> or <code>WeakReference</code> and how was it used?</p>
|
[
{
"answer_id": 155312,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": false,
"text": "private static IdMutexProvider MUTEX_PROVIDER = new IdMutexProvider();\n\npublic void performTask(String resourceId) {\n IdMutexProvider.Mutex mutext = MUTEX_PROVIDER.getMutex(resourceId);\n synchronized (mutext) {\n // look up the resource and do something with it\n }\n}\n WeakHashMap<Mutex, WeakReference<Mutex>>\n"
},
{
"answer_id": 155492,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 6,
"selected": false,
"text": "WeakReference SoftReference WeakReference SoftReference WeakReference SoftReference WeakReference WeakHashMap SoftReferences"
},
{
"answer_id": 205123,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 5,
"selected": false,
"text": "WeakReference WeakHashMap WeakHashMap java.awt.Component JButton JFrame JPanel"
},
{
"answer_id": 25241986,
"author": "icza",
"author_id": 1705598,
"author_profile": "https://Stackoverflow.com/users/1705598",
"pm_score": 5,
"selected": false,
"text": "WeakHashMap WeakReference manager.registerListener(myListenerImpl);\n manager WeakReference manager.removeListener(myListenerImpl) WeakHashMap WeakReference WeakHashSet WeakHashMap Set<ListenerType> listenerSet =\n Collections.newSetFromMap(new WeakHashMap<ListenerType, Boolean>());\n listenerSet"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12662/"
] |
154,730
|
<p>I am supposed to provide my users a really simple way of capturing video clips out of my OpenGL application's main window. I am thinking of adding buttons and/or keyboard shortcuts for starting and stopping the capture; when starting, I could ask for a filename and other options, if any. It has to run in Windows (XP/Vista), but I also wouldn't like to close the Linux door which I've so far been able to keep open.</p>
<p>The application uses OpenGL fragment and shader programs, the effects due to which I absolutely need to have in the eventual videos.</p>
<p>It looks to me like there might be even several different approaches that could potentially fulfill my requirements (but I don't really know where I should start):</p>
<ul>
<li><p>An encoding library with functions like startRecording(filename), stopRecording, and captureFrame. I could call captureFrame() after every frame rendered (or every second/third/whatever). If doing so makes my program run slower, it's not really a problem.</p></li>
<li><p>A standalone external program that can be programmatically controlled from my application. After all, a standalone program that can <em>not</em> be controlled almost does what I need... But as said, it should be really simple for the users to operate, and I would appreciate seamlessness as well; my application typically runs full-screen. Additionally, it should be possible to distribute as part of the installation package for my application, which I currently prepare using NSIS.</p></li>
<li><p>Use the Windows API to capture screenshots frame-by-frame, then employ (for example) one of the <a href="https://stackoverflow.com/questions/93954/how-to-programatically-create-videos">libraries mentioned here</a>. It seems to be easy enough to find examples of how to capture screenshots in Windows; however, I would love a solution which doesn't really force me to get my hands super-dirty on the WinAPI level.</p></li>
<li><p>Use OpenGL to render into an offscreen target, then use a library to produce the video. I don't know if this is even possible, and I'm afraid it might not be the path of least pain anyway. In particular, I would not like the actual rendering to take a different execution path depending on whether video is being captured or not. Additionally, I would avoid anything that might decrease the frame rate in the normal, non-capture mode.</p></li>
</ul>
<p>If the solution were free in either sense of the word, then that would be great, but it's not really an absolute requirement. In general, the less bloat there is, the better. On the other hand, for reasons beyond this question, I cannot link in any GPL-only code, unfortunately.</p>
<p>Regarding the file format, I cannot expect my users to start googling for any codecs, but as long as also <em>displaying</em> the videos is easy enough for a basic-level Windows user, I don't really care what the format is. However, it would be great if it were possible to control the compression quality of the output.</p>
<p>Just to clarify: I <em>don't</em> need to capture video from an external device like camcorder, nor am I really interested in mouse movements, even though getting them does not harm either. There are no requirements regarding audio; the application makes no noise whatsoever.</p>
<p>I write C++ using Visual Studio 2008, for this very application also taking benefit of GLUT and GLUI. I have a solid understanding regarding C++ and linking in libraries and that sort of stuff, but on the other hand OpenGL is quite new for me: so far, I've really only learnt the necessary bits to actually get my job done.</p>
<p>I don't need a solution super-urgently, so feel free to take your time :)</p>
|
[
{
"answer_id": 155043,
"author": "Reunanen",
"author_id": 19254,
"author_profile": "https://Stackoverflow.com/users/19254",
"pm_score": 1,
"selected": false,
"text": "glReadPixels"
},
{
"answer_id": 18703223,
"author": "tommy chheng",
"author_id": 337493,
"author_profile": "https://Stackoverflow.com/users/337493",
"pm_score": 0,
"selected": false,
"text": "glReadPixels cvWriteFrame"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19254/"
] |
154,754
|
<p>I would find out the <em>floppy inserted state</em>:</p>
<ul>
<li>no floppy inserted</li>
<li>unformatted floppy inserted</li>
<li>formatted floppy inserted</li>
</ul>
<p>Can this determined using "WMI" in the System.Management namespace?</p>
<p>If so, can I generate events when the <em>floppy inserted state</em> changes? </p>
|
[
{
"answer_id": 163970,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 2,
"selected": false,
"text": "strComputer = \".\"\nSet objWMIService = GetObject( _\n \"winmgmts:\\\\\" & strComputer & \"\\root\\cimv2\")\nSet colItems = objWMIService.ExecQuery _\n (\"Select * From Win32_LogicalDisk Where DeviceID = 'A:'\")\n\nFor Each objItem in colItems\n intFreeSpace = objItem.FreeSpace\n If IsNull(intFreeSpace) Then\n Wscript.Echo \"There is no disk in the floppy drive.\"\n Else\n Wscript.Echo \"There is a disk in the floppy drive.\"\n End If\nNext\n"
},
{
"answer_id": 168452,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 2,
"selected": true,
"text": " public static void TestFloppy( char driveLetter ) {\n using( var searcher = new ManagementObjectSearcher( @\"SELECT * FROM Win32_LogicalDisk WHERE DeviceID = '\" + driveLetter + \":'\" ) )\n using( var logicalDisks = searcher.Get() ) {\n foreach( ManagementObject logicalDisk in logicalDisks ) {\n var fs = logicalDisk[ \"FreeSpace\" ];\n Console.WriteLine( \"FreeSpace = \" + ( fs ?? \"Not Available\" ) );\n\n logicalDisk.Dispose();\n }\n }\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14841/"
] |
154,762
|
<p>I need to create XML in Perl. From what I read, <a href="http://search.cpan.org/dist/XML-LibXML" rel="noreferrer">XML::LibXML</a> is great for parsing and using XML that comes from somewhere else. Does anyone have any suggestions for an XML Writer? Is <a href="http://search.cpan.org/dist/XML-Writer" rel="noreferrer">XML::Writer</a> still maintained? Does anyone like/use it?</p>
<p>In addition to feature-completeness, I am interested an easy-to-use syntax, so please describe the syntax and any other reasons why you like that module in your answer.</p>
<p>Please respond with one suggestion per answer, and if someone has already answered with your favorite, please vote that answer up. Hopefully it will be easy to see what is most popular.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 155010,
"author": "Yanick",
"author_id": 10356,
"author_profile": "https://Stackoverflow.com/users/10356",
"pm_score": 6,
"selected": true,
"text": "use XML::Writer;\n\nmy $writer = new XML::Writer(); # will write to stdout\n$writer->startTag(\"greeting\", \n \"class\" => \"simple\");\n$writer->characters(\"Hello, world!\");\n$writer->endTag(\"greeting\");\n$writer->end();\n\n# produces <greeting class='simple'>Hello world!</greeting>\n"
},
{
"answer_id": 155192,
"author": "Matt Siegman",
"author_id": 12299,
"author_profile": "https://Stackoverflow.com/users/12299",
"pm_score": 3,
"selected": false,
"text": "use XML::Smart;\n\n## Create a null XML object:\nmy $XML = XML::Smart->new() ;\n\n## Add a server to the list:\n$XML->{server} = {\n os => 'Linux' ,\n type => 'mandrake' ,\n version => 8.9 ,\n address => [ '192.168.3.201', '192.168.3.202' ] ,\n} ;\n\n$XML->save('newfile.xml') ;\n <server os=\"Linux\" type=\"mandrake\" version=\"8.9\">\n <address>192.168.3.201</address>\n <address>192.168.3.202</address>\n</server>\n"
},
{
"answer_id": 2934794,
"author": "Cosimo",
"author_id": 11303,
"author_profile": "https://Stackoverflow.com/users/11303",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/env perl\n\n#\n# Create a simple XML document\n#\n\nuse strict;\nuse warnings;\nuse XML::LibXML;\n\nmy $doc = XML::LibXML::Document->new('1.0', 'utf-8');\n\nmy $root = $doc->createElement('my-root-element');\n$root->setAttribute('some-attr'=> 'some-value');\n\nmy %elements = (\n color => 'blue',\n metal => 'steel',\n);\n\nfor my $name (keys %elements) {\n my $tag = $doc->createElement($name);\n my $value = $elements{$name};\n $tag->appendTextNode($value);\n $root->appendChild($tag);\n}\n\n$doc->setDocumentElement($root);\nprint $doc->toString();\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<my-root-element some-attr=\"some-value\">\n <color>blue</color>\n <metal>steel</metal>\n</my-root-element>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4257/"
] |
154,791
|
<p>I'm writing a Java Tree in which tree nodes could have children that take a long time to compute (in this case, it's a file system, where there may be network timeouts that prevent getting a list of files from an attached drive).</p>
<p>The problem I'm finding is this:</p>
<ol>
<li><p><code>getChildCount()</code> is called before the user specifically requests opening a particular branch of the tree. I believe this is done so the <code>JTree</code> knows whether to show a + icon next to the node.</p></li>
<li><p>An accurate count of children from <code>getChildCount()</code> would need to perform the potentially expensive operation </p></li>
<li><p>If I fake the value of <code>getChildCount()</code>, the tree only allocates space for that many child nodes before asking for an enumeration of the children. (If I return '1', I'll only see 1 child listed, despite that there are more)</p></li>
</ol>
<p>The enumeration of the children can be expensive and time-consuming, I'm okay with that. But I'm not okay with <code>getChildCount()</code> needing to know the exact number of children.</p>
<p>Any way I can work around this?</p>
<p><strong>Added:</strong> The other problem is that if one of the nodes represents a floppy drive (how archaic!), the drive will be polled before the user asks for its files; if there's no disk in the drive, this results in a system error.</p>
<p><strong>Update:</strong> Unfortunately, implementing the <code>TreeWillExpand</code> listener isn't the solution. That can allow you to veto an expansion, but the number of nodes shown is still restricted by the value returned by <code>TreeNode.getChildCount()</code>.</p>
|
[
{
"answer_id": 155063,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 0,
"selected": false,
"text": "n0 cc n1 n1.cc + cc++ cc hasChildren getChildCount TreeNode hasHadChildren isVirgin"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197/"
] |
154,837
|
<p>We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection.</p>
<p>We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory.</p>
<p>But for some reason my Workflows just don't see the config file.</p>
<pre><code><configuration>
<appSettings>
<add key="ConnectString" value="Data Source=officeserver;Database=mydatabase;User ID=officeuser;Password=officeuser;" />
</appSettings>
</configuration>
</code></pre>
<p>Given the above config file, the following code prints an empty string:</p>
<pre><code>Console.WriteLine(ConfigurationManager.AppSettings["ConnectString"]);
</code></pre>
<p>I think what I want is to just specify a config filename, but I'm having problems here. I'm just not getting results.
Anyone have any pointers?</p>
|
[
{
"answer_id": 154914,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<applicationSettings>\n <MyLibrary.My.MySettings>\n <setting name=\"SomeSetting\" serializeAs=\"String\">\n <value>12345</value>\n </setting>\n </MyLibrary.My.MySettings>\n</applicationSettings>\n"
},
{
"answer_id": 155534,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 1,
"selected": false,
"text": "Assembly.GetExecutingAssembly .config XmlDocument <appSettings> NameValueSectionHandler Create"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23597/"
] |
154,842
|
<p>I posted an answer to <a href="https://stackoverflow.com/questions/154706">this question</a>, including a very short rant at the end about how String.Split() should accept IEnumerable<string> rather than string[]. </p>
<p>That got me thinking. What if the base Object class from which everything else inherits provided a default implementation for IEnumerable such that everything now returns an Enumerator over exactly one item (itself) -- unless it's overridden to do something else like with collections classes.</p>
<p>The idea is that then if methods like String.Split() did accept IEnumerable rather than an array I could pass a single string to the function and it would just work, rather than having to much about with creating a separator array.</p>
<p>I'm sure there are all kinds of reasons not to do this, not the least of which is that if everything implemented IEnumerable, then the few classes where the implementation strays from the default could behave differently than you'd expect in certain scenarios. But I still thought it would be a fun exercise: what other consequences would there be?</p>
|
[
{
"answer_id": 154932,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "public static IEnumerable<object> ToEnumerable(this object someObject)\n{\n return System.Linq.Enumerable.Repeat(someObject, 1);\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
154,845
|
<p>I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present. </p>
<p><strong>So something like:</strong></p>
<p><em>dr.ToString.Substring(1, dr.ToString.Length);</em></p>
<p>But more conditionally in case the dollar sign ever made an appearance again.</p>
<p>I am trying to do this with explicitly defining another string.</p>
|
[
{
"answer_id": 154857,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 5,
"selected": true,
"text": "Convert.ToString(dr(columnName)).Replace(\"$\", String.Empty)\n"
},
{
"answer_id": 154956,
"author": "Shaun Bowe",
"author_id": 1514,
"author_profile": "https://Stackoverflow.com/users/1514",
"pm_score": 3,
"selected": false,
"text": "public static string RemoveNonNumeric(this string s)\n{\n return s.Replace(\"$\", \"\");\n}\n ((String)dr[columnName]).RemoveNonNumeric();\n"
},
{
"answer_id": 155035,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 3,
"selected": false,
"text": "string trimmed = (dr as string).Trim('$');\n string trimmed = (dr as string).TrimStart('$');\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
154,846
|
<p>I'm looking for a way to create an online form that will update an Access database that has just a few tables. Does anyone know of a simple solution for this?</p>
|
[
{
"answer_id": 154857,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 5,
"selected": true,
"text": "Convert.ToString(dr(columnName)).Replace(\"$\", String.Empty)\n"
},
{
"answer_id": 154956,
"author": "Shaun Bowe",
"author_id": 1514,
"author_profile": "https://Stackoverflow.com/users/1514",
"pm_score": 3,
"selected": false,
"text": "public static string RemoveNonNumeric(this string s)\n{\n return s.Replace(\"$\", \"\");\n}\n ((String)dr[columnName]).RemoveNonNumeric();\n"
},
{
"answer_id": 155035,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 3,
"selected": false,
"text": "string trimmed = (dr as string).Trim('$');\n string trimmed = (dr as string).TrimStart('$');\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6958/"
] |
154,853
|
<p>I have a folder, <code>c:\websites\test</code>, and it contains folders and files that were checked out from a repository that no longer exists. How do I get Subversion to stop tracking that folder and any of the subfolders and files? </p>
<p>I know I could simply delete the <code>.svn</code> folder, but there are a lot of sub-folders in many layers.</p>
|
[
{
"answer_id": 154860,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 7,
"selected": false,
"text": "svn export /path/to/old/working/copy /path/to/plain/code\n"
},
{
"answer_id": 154874,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "svn export cd c:\\websites\\test\nsvn export c:\\websites\\test_copy\n"
},
{
"answer_id": 154887,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 5,
"selected": false,
"text": ".svn"
},
{
"answer_id": 154949,
"author": "Max Cantor",
"author_id": 16034,
"author_profile": "https://Stackoverflow.com/users/16034",
"pm_score": 7,
"selected": false,
"text": " find . -iname \".svn\" -print0 | xargs -0 rm -r\n"
},
{
"answer_id": 4880709,
"author": "I. J. Kennedy",
"author_id": 8677,
"author_profile": "https://Stackoverflow.com/users/8677",
"pm_score": 4,
"selected": false,
"text": "svn export --force .\n"
},
{
"answer_id": 9431463,
"author": "Tobias",
"author_id": 77722,
"author_profile": "https://Stackoverflow.com/users/77722",
"pm_score": 2,
"selected": false,
"text": "Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\Folder\\shell\\DeleteSVN]\n@=\"Delete SVN Folders\"\n\n[HKEY_CLASSES_ROOT\\Folder\\shell\\DeleteSVN\\command]\n@=\"cmd.exe /c \\\"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \\\"%1\\\" %%f IN (.svn) DO RD /s /q \\\"%%f\\\" \\\"\"\n"
},
{
"answer_id": 10501443,
"author": "bunteKnete",
"author_id": 1382442,
"author_profile": "https://Stackoverflow.com/users/1382442",
"pm_score": 5,
"selected": false,
"text": "svn delete --keep-local file_name\n"
},
{
"answer_id": 12265223,
"author": "user1439712",
"author_id": 1439712,
"author_profile": "https://Stackoverflow.com/users/1439712",
"pm_score": 4,
"selected": false,
"text": ".svn find . -name .svn -exec rm -r -f {} +\n\nrm = remove\n-r = recursive (folders)\n-f = force, avoids a lot of \"a your sure you want to delete file XY\".\n"
},
{
"answer_id": 15926791,
"author": "yeeking",
"author_id": 1240660,
"author_profile": "https://Stackoverflow.com/users/1240660",
"pm_score": 0,
"selected": false,
"text": "# copy folder src to srcStripped excluding subfolders named '.svn'. retain dates, verbose output\nrsync -av --exclude .svn src srcStripped\n"
},
{
"answer_id": 16696749,
"author": "Dougvj",
"author_id": 1420838,
"author_profile": "https://Stackoverflow.com/users/1420838",
"pm_score": 1,
"selected": false,
"text": "rm -r `find /path/to/foo -name .svn`\n"
},
{
"answer_id": 17990716,
"author": "Manikandan S",
"author_id": 1506356,
"author_profile": "https://Stackoverflow.com/users/1506356",
"pm_score": 3,
"selected": false,
"text": "find directory_to_delete/ -type d -name '*.svn' | xargs rm -rf\n"
},
{
"answer_id": 28307531,
"author": "brazilianldsjaguar",
"author_id": 1245766,
"author_profile": "https://Stackoverflow.com/users/1245766",
"pm_score": 3,
"selected": false,
"text": ".svn svn update --set-depth exclude <dir> Update to revision... Exclude"
},
{
"answer_id": 33218256,
"author": "Javier Salinas",
"author_id": 1300594,
"author_profile": "https://Stackoverflow.com/users/1300594",
"pm_score": 0,
"selected": false,
"text": "svn export svn rm --keep-local <folder/file>\n"
},
{
"answer_id": 33296718,
"author": "fatihk",
"author_id": 2183287,
"author_profile": "https://Stackoverflow.com/users/2183287",
"pm_score": 0,
"selected": false,
"text": "find cd [dir_to_delete_svn_folders]\nfind . -depth -name .svn -exec rm -fr {} \\;\n"
},
{
"answer_id": 36901615,
"author": "Praseeda",
"author_id": 6263798,
"author_profile": "https://Stackoverflow.com/users/6263798",
"pm_score": -1,
"selected": false,
"text": "Windows Explorer View View hidden files .svn"
},
{
"answer_id": 55283983,
"author": "Michael Ross",
"author_id": 1964414,
"author_profile": "https://Stackoverflow.com/users/1964414",
"pm_score": 0,
"selected": false,
"text": "rmdir .svn /s /q\n"
},
{
"answer_id": 61395394,
"author": "Ryan",
"author_id": 295704,
"author_profile": "https://Stackoverflow.com/users/295704",
"pm_score": 0,
"selected": false,
"text": "svn rm --keep-local <folder name> svn rm --keep-local <folder name>/* ~/code/web/sites/testapp $ svn rm --keep-local includes/data/*\nD includes/data/json\nD includes/data/json/index.html\nD includes/data/json/oembed\nD includes/data/json/oembed/1.0\nD includes/data/json/oembed/1.0/embed1.json\nD includes/data/json/oembed/1.0/embed2.json\nD includes/data/json/oembed/1.0/embed3.json\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
154,862
|
<p>How can I convert a JavaScript string value to be in all lower case letters?</p>
<p>Example: <code>"Your Name"</code> to <code>"your name"</code></p>
|
[
{
"answer_id": 154882,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 5,
"selected": false,
"text": "toLowerCase() \"Foo\".toLowerCase();\ndocument.getElementById('myField').value.toLowerCase();\n"
},
{
"answer_id": 154891,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 12,
"selected": true,
"text": "var lowerCaseName = \"Your Name\".toLowerCase();\n"
},
{
"answer_id": 155257,
"author": "Atif Aziz",
"author_id": 6682,
"author_profile": "https://Stackoverflow.com/users/6682",
"pm_score": 9,
"selected": false,
"text": "toLocaleLowerCase toLocaleLowerCase var lower = 'Your Name'.toLowerCase();\n toLowerCase toLocaleLowerCase String toLowerCase var lower = String.prototype.toLowerCase.apply(new Date());\n var lower = new Date().toString().toLowerCase();\n null toLowerCase toLocaleLowerCase null null"
},
{
"answer_id": 3845060,
"author": "ewwink",
"author_id": 458214,
"author_profile": "https://Stackoverflow.com/users/458214",
"pm_score": 4,
"selected": false,
"text": "toLowerCase() toUpperCase() toTitleCase() toProperCase() String.prototype.toTitleCase = function() {\n return this.split(' ').map(i => i[0].toUpperCase() + i.substring(1).toLowerCase()).join(' ');\n}\n\nString.prototype.toPropperCase = function() {\n return this.toTitleCase();\n}\n\nvar OriginalCase = 'Your Name';\nvar lowercase = OriginalCase.toLowerCase();\nvar upperCase = lowercase.toUpperCase();\nvar titleCase = upperCase.toTitleCase();\n\nconsole.log('Original: ' + OriginalCase);\nconsole.log('toLowerCase(): ' + lowercase);\nconsole.log('toUpperCase(): ' + upperCase);\nconsole.log('toTitleCase(): ' + titleCase);"
},
{
"answer_id": 7453032,
"author": "Dan",
"author_id": 139361,
"author_profile": "https://Stackoverflow.com/users/139361",
"pm_score": 4,
"selected": false,
"text": "strtolower() \"SomE StriNg\".toLowerCase() function strToLower (str) {\n return String(str).toLowerCase();\n}\n"
},
{
"answer_id": 10770658,
"author": "Paul Gorbas",
"author_id": 600889,
"author_profile": "https://Stackoverflow.com/users/600889",
"pm_score": 3,
"selected": false,
"text": " onChange: function(file, extension)\n {\n alert(\"extension.toLowerCase()=>\" + extension.toLowerCase() + \"<=\");\n alert(\"(typeof extension)=>\" + (typeof extension) + \"<=\");;\n var extension = String(extension);\n"
},
{
"answer_id": 17762625,
"author": "JackSparrow",
"author_id": 2309028,
"author_profile": "https://Stackoverflow.com/users/2309028",
"pm_score": 3,
"selected": false,
"text": "<script language=javascript>\n var ss = \" testing case conversion method \";\n var result = ss.toUpperCase();\n document.write(result);\n</script>\n <script language=javascript>\n var ss = \" TESTING LOWERCASE CONVERT FUNCTION \";\n var result = ss.toLowerCase();\n document.write(result);\n</script>\n"
},
{
"answer_id": 33918207,
"author": "Some Java Guy",
"author_id": 387774,
"author_profile": "https://Stackoverflow.com/users/387774",
"pm_score": -1,
"selected": false,
"text": "<input type=\"text\" style=\"text-transform: uppercase\"> <!-- uppercase -->\n<input type=\"text\" style=\"text-transform: lowercase\"> <!-- lowercase -->\n"
},
{
"answer_id": 46235553,
"author": "Siddhartha",
"author_id": 7840265,
"author_profile": "https://Stackoverflow.com/users/7840265",
"pm_score": 2,
"selected": false,
"text": "var x = 'ABC';\nx = x.toLowerCase();\n function convertToLowerCase(str) {\n var result = '';\n\n for (var i = 0; i < str.length; i++) {\n var code = str.charCodeAt(i);\n if (code > 64 && code < 91) {\n result += String.fromCharCode(code + 32);\n } else {\n result += str.charAt(i);\n }\n }\n return result;\n}\n x = convertToLowerCase(x);\n"
},
{
"answer_id": 50602049,
"author": "Harun Or Rashid",
"author_id": 4724147,
"author_profile": "https://Stackoverflow.com/users/4724147",
"pm_score": 2,
"selected": false,
"text": "toLowerCase() let v = \"Your Name\"\n let u = v.toLowerCase(); let u = \"Your Name\".toLowerCase();"
},
{
"answer_id": 55678237,
"author": "Praveen",
"author_id": 1175932,
"author_profile": "https://Stackoverflow.com/users/1175932",
"pm_score": -1,
"selected": false,
"text": "var x = \"Hello\";\nx.toLowerCase();\n"
},
{
"answer_id": 55868778,
"author": "Abdurahman Popal",
"author_id": 10020712,
"author_profile": "https://Stackoverflow.com/users/10020712",
"pm_score": -1,
"selected": false,
"text": "var lower = (str+\"\").toLowerCase();\n"
},
{
"answer_id": 56174904,
"author": "Javier Giovannini",
"author_id": 1277165,
"author_profile": "https://Stackoverflow.com/users/1277165",
"pm_score": -1,
"selected": false,
"text": "function toLowerCase(string) {\n\n let lowerCaseString = \"\";\n\n for (let i = 0; i < string.length; i++) {\n // Find ASCII charcode\n let charcode = string.charCodeAt(i);\n\n // If uppercase\n if (charcode > 64 && charcode < 97) {\n // Convert to lowercase\n charcode = charcode + 32\n }\n\n // Back to char\n let lowercase = String.fromCharCode(charcode);\n\n // Append\n lowerCaseString = lowerCaseString.concat(lowercase);\n }\n\n return lowerCaseString\n}\n"
},
{
"answer_id": 67386662,
"author": "Force Bolt",
"author_id": 15478252,
"author_profile": "https://Stackoverflow.com/users/15478252",
"pm_score": 0,
"selected": false,
"text": "const str = 'Your Name';\n\n// convert string to lowercase\nconst lowerStr = str.toLowerCase();\n\n// print the new string\nconsole.log(lowerStr);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5440/"
] |
154,897
|
<p>Did you ever had a bug in your code, you could not resolve? I hope I'm not the only one out there, who made this experience ...</p>
<p>There exist some classes of bugs, that are very hard to track down:</p>
<ul>
<li><strong>timing-related bugs</strong> (that occur during inter-process-communication for example)</li>
<li><strong>memory-related bugs</strong> (most of you know appropriate examples, I guess !!!)</li>
<li><strong>event-related bugs</strong> (hard to debug, because every break point you run into makes your IDE the target for mouse release/focus events ...)</li>
<li><strong>OS-dependent bugs</strong></li>
<li><strong>hardware dependent bugs</strong> (occurs on
release machine, but not on
developer machine)</li>
<li>...</li>
</ul>
<p>To be honest, from time to time I fail to fix such a bug on my own ... After debugging for hours (or sometimes even days) I feel very demoralized.</p>
<p>What do you do in this situation (apart from asking others for help which is not always possible)?</p>
<p>Do you</p>
<ul>
<li>use pencil and paper instead of a debugger</li>
<li>face for another thing and return to
this bug later</li>
<li>...</li>
</ul>
<p>Please let me know!</p>
|
[
{
"answer_id": 154931,
"author": "camflan",
"author_id": 22445,
"author_profile": "https://Stackoverflow.com/users/22445",
"pm_score": 1,
"selected": false,
"text": ": ; retab!"
},
{
"answer_id": 154990,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "kill -3"
},
{
"answer_id": 155032,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 2,
"selected": false,
"text": "Trace"
},
{
"answer_id": 155077,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 4,
"selected": false,
"text": "59 ERROR_UNEXP_NET_ERR 65 ERROR_NETWORK_ACCESS_DENIED"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012356/"
] |
154,900
|
<p>I was wrestling with some Perl that uses hash references.</p>
<p>In the end it turned out that my problem was the line:</p>
<pre><code>$myhash{$key} |= {};
</code></pre>
<p>That is, "assign $myhash{$key} a reference to an empty hash, unless it already has a value".</p>
<p>Dereferencing this and trying to use it as a hash reference, however, resulted in interpreter errors about using a string as a hash reference.</p>
<p>Changing it to:</p>
<pre><code>if( ! exists $myhash{$key}) {
$myhash{$key} = {};
}
</code></pre>
<p>... made things work.</p>
<p>So I don't have a <em>problem</em>. But I'm curious about what was going on.</p>
<p>Can anyone explain?</p>
|
[
{
"answer_id": 154916,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "my %myhash;\n$myhash{$key} ||= {};\n my my ||= |="
},
{
"answer_id": 154984,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 4,
"selected": false,
"text": "||= |= ||= //= //"
},
{
"answer_id": 154991,
"author": "Kyle",
"author_id": 2237619,
"author_profile": "https://Stackoverflow.com/users/2237619",
"pm_score": 2,
"selected": false,
"text": "|= ||= $myhash{$key} ||= {}"
},
{
"answer_id": 155026,
"author": "friedo",
"author_id": 20745,
"author_profile": "https://Stackoverflow.com/users/20745",
"pm_score": 5,
"selected": true,
"text": "|= $foo |= $bar;\n $foo = $foo | $bar\n $myhash{$key} $myhash{$key} HASH(0x80fc284) Data::Dumper perl -MData::Dumper -le '$hash{foo} |= { }; print Dumper \\%hash'\n $VAR1 = {\n 'foo' => 'HASH(0x80fc284)'\n };\n perl -MData::Dumper -le '$hash{foo} ||= { }; print Dumper \\%hash'\n $VAR1 = {\n 'foo' => {}\n };\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7512/"
] |
154,902
|
<p>I wrote a program in C with Ubuntu Linux and now I need to port it over to a UNIX machine (or what I believe to be a UNIX box). It compiles fine on my Ubuntu with GCC but when I try to compile it with GCC on the UNIX box, it gives this error:</p>
<pre><code>a.c: In function `goUpDir':
a.c:44: parse error before `char'
a.c:45: `newDir' undeclared (first use in this function)
a.c:45: (Each undeclared identifier is reported only once
a.c:45: for each function it appears in.)
a.c: In function `goIntoDir':
a.c:54: parse error before `char'
a.c:57: `newDir' undeclared (first use in this function)
a.c:57: `oldDir' undeclared (first use in this function)
</code></pre>
<p>The main problems seem to be the parse error before <code>char</code> (the others are related)</p>
<pre><code>44 char newDir[50] = "";
54 char* oldDir = (char*)get_current_dir_name();
</code></pre>
<p>These are just simple C-style strings declarations. Is there a header file that I need to include to get it to work in UNIX?</p>
<p>P.S. what is the command to see what version of unix and which version of gcc you are using? Knowing this will allow me to be more specific in my question.</p>
<p>Thanks</p>
|
[
{
"answer_id": 154937,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "gcc --version\n"
},
{
"answer_id": 154943,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "uname -a\ngcc -v\n"
},
{
"answer_id": 155219,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 1,
"selected": false,
"text": "-std=c89 -pedantic -Wall\n -std=gnu89 -pedantic -Wall\n"
},
{
"answer_id": 159480,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 1,
"selected": false,
"text": "parse error before 'char'"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
154,964
|
<p>I have a question regarding the two additional columns (timeCreated, timeLastUpdated) for each record that we see in many solutions. My question: Is there a better alternative?</p>
<p>Scenario: You have a huge DB (in terms of tables, not records), and then the customer comes and asks you to add "timestamping" to 80% of your tables.</p>
<p>I believe this can be accomplished by using a separate table (TIMESTAMPS). This table would have, in addition to the obvious timestamp column, the table name and the primary key for the table being updated. (I'm assuming here that you use an int as primary key for most of your tables, but the table name would most likely have to be a string).</p>
<p>To picture this suppose this basic scenario. We would have two tables:</p>
<p>PAYMENT :- (your usual records)<br>
TIMESTAMP :- {current timestamp} + {<code>TABLE_UPDATED</code>, <code>id_of_entry_updated</code>, <code>timestamp_type</code>}</p>
<p>Note that in this design you don't need those two "extra" columns in your native payment object (which, by the way, might make it thru your ORM solution) because you are now indexing by <code>TABLE_UPDATED</code> and <code>id_of_entry_updated</code>. In addition, <code>timestamp_type</code> will tell you if the entry is for insertion (e.g "1"), update (e.g "2"), and anything else you may want to add, like "deletion".</p>
<p>I would like to know what do you think about this design. I'm most interested in best practices, what works and scales over time. References, links, blog entries are more than welcome. I know of at least one patent (pending) that tries to address this problem, but it seems details are not public at this time.</p>
<p>Cheers,
Eduardo</p>
|
[
{
"answer_id": 154997,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "Change Data Capture"
},
{
"answer_id": 155015,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 3,
"selected": false,
"text": "create table NAME (\n name_id int,\n first_name varchar\n last_name varchar\n -- any other table/column constraints\n)\n\ncreate table NAME_AUDIT (\n name_audit_id int\n name_id int\n first_name varchar\n last_name varchar\n update_type char(1) -- 'U', 'D', 'C'\n update_date datetime\n -- no table constraints really, outside of name_audit_id as PK\n)\n NAME_AUDIT NAME"
},
{
"answer_id": 155016,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 1,
"selected": false,
"text": "LogID int\nAction varchar(1) -- ADDED (A)/UPDATED (U)/DELETED (D)\nUserID varchar(20) -- UserID of culprit :)\nTimestamp datetime -- Date/Time\nTableName varchar(50) -- Table Name or Stored Procedure ran\nUniqueID int -- Unique ID of record acted upon\nNotes varchar(1000) -- Other notes Stored Procedure or Application may provide\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/154964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23920/"
] |
155,022
|
<p>What is the easiest way to find out how much memory an object uses in .NET?</p>
<p>Preferably without having to resort to a third party tool. Marshal.SizeOf or the sizeof operator look useful but only work with a restricted range of types.</p>
<p>Some related posts:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/109836/object-memory-analysis-in-net">Object Memory Analysis in .NET</a></li>
<li><a href="https://stackoverflow.com/questions/151936/does-an-empty-array-in-net-use-any-space">Does an empty array in .NET use any space?</a></li>
</ul>
|
[
{
"answer_id": 155048,
"author": "Mladen",
"author_id": 21404,
"author_profile": "https://Stackoverflow.com/users/21404",
"pm_score": 1,
"selected": true,
"text": "int startMem = GC.GetTotalMemory(true);\nYourClass c = new YourClass();\nint endMem = GC.GetTotalMemory(true);\nint usedMeme = endMem - startMem;\n"
},
{
"answer_id": 14629091,
"author": "Kenzi",
"author_id": 557646,
"author_profile": "https://Stackoverflow.com/users/557646",
"pm_score": 0,
"selected": false,
"text": "RecursiveSizeOf(a) + RecursiveSizeOf(b) SimpleSizeOf(a) + SimpleSizeOf(b) + SimpleSizeOf(c) Marshal"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
] |
155,054
|
<p>Is it possible to define a timestamp column in a MySQL table that will automatically be updated every time a field in the same row is modified? Ideally this column should initially be set to the time a row was inserted.</p>
<p>Cheers,
Don</p>
|
[
{
"answer_id": 155096,
"author": "quickcel",
"author_id": 9129,
"author_profile": "https://Stackoverflow.com/users/9129",
"pm_score": 6,
"selected": false,
"text": "ALTER TABLE `table1` ADD `lastUpdated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;\n"
},
{
"answer_id": 4189360,
"author": "Petruza",
"author_id": 221650,
"author_profile": "https://Stackoverflow.com/users/221650",
"pm_score": 1,
"selected": false,
"text": "ALTER TABLE some_table ADD when TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
155,071
|
<p>Do you have a simple debounce routine handy to deal with a single switch input?</p>
<p>This is a simple bare metal system without any OS.</p>
<p>I would like to avoid a looping construct with a specific count, as the processor speed might fluctuate.</p>
|
[
{
"answer_id": 155137,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 5,
"selected": true,
"text": "#define CHECK_MSEC 5 // Read hardware every 5 msec\n#define PRESS_MSEC 10 // Stable time before registering pressed\n#define RELEASE_MSEC 100 // Stable time before registering released\n// This function reads the key state from the hardware.\nextern bool_t RawKeyPressed();\n// This holds the debounced state of the key.\nbool_t DebouncedKeyPress = false;\n// Service routine called every CHECK_MSEC to\n// debounce both edges\nvoid DebounceSwitch1(bool_t *Key_changed, bool_t *Key_pressed)\n{\n static uint8_t Count = RELEASE_MSEC / CHECK_MSEC;\n bool_t RawState;\n *Key_changed = false;\n *Key_pressed = DebouncedKeyPress;\n RawState = RawKeyPressed();\n if (RawState == DebouncedKeyPress) {\n // Set the timer which allows a change from current state.\n if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC;\n else Count = PRESS_MSEC / CHECK_MSEC;\n } else {\n // Key has changed - wait for new state to become stable.\n if (--Count == 0) {\n // Timer expired - accept the change.\n DebouncedKeyPress = RawState;\n *Key_changed=true;\n *Key_pressed=DebouncedKeyPress;\n // And reset the timer.\n if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC;\n else Count = PRESS_MSEC / CHECK_MSEC;\n }\n }\n"
},
{
"answer_id": 235938,
"author": "Justin Love",
"author_id": 30203,
"author_profile": "https://Stackoverflow.com/users/30203",
"pm_score": 0,
"selected": false,
"text": "input3 = input2;\ninput2 = input1;\ninput1 = (*PORTA);\n\ndebounced |= input1 & input2 & input3;\ndebounced &= (input1 | input2 | input3);\n input1 = 0110,\ninput2 = 1100,\ninput3 = 0100\n debounced |= (0100); //set only bit 2\ndebounced &= (1110); //clear only bit 0\n"
},
{
"answer_id": 28154521,
"author": "sorin",
"author_id": 1665786,
"author_profile": "https://Stackoverflow.com/users/1665786",
"pm_score": 0,
"selected": false,
"text": "static uint8_t Count = RELEASE_MSEC / CHECK_MSEC;\n static uint8_t Count = PRESS_MSEC / CHECK_MSEC;\n"
},
{
"answer_id": 40812488,
"author": "well but I'm",
"author_id": 6292763,
"author_profile": "https://Stackoverflow.com/users/6292763",
"pm_score": 0,
"selected": false,
"text": "while(keyvalue = maybepressed){\n//loop - wait for transition to notpressed\nsample keyvalue here;\nmaybe require it to be \"notpressed\" a number of times before you assume\nit's really notpressed;\n}\nwhile(keyvalue = notpressed){\n//loop - wait for transition to maybepressed\nsample keyvalue\nagain, maybe require a \"maybepressed\" value a number of times before you \ntransition\n}\nwhile(keyvalue=maybepressed){\n presstime+=1;\n if presstime>required_presstime return pressed_affirmative\n }\n}\nreturn pressed_negative\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] |
155,074
|
<p>I'm a newbie when it comes to SQL. When creating a stored procedure with parameters as such:</p>
<pre><code>@executed bit,
@failure bit,
@success bit,
@testID int,
@time float = 0,
@name varchar(200) = '',
@description varchar(200) = '',
@executionDateTime nvarchar(max) = '',
@message nvarchar(max) = ''
</code></pre>
<p>This is the correct form for default values in T-SQL? I have tried to use NULL instead of ''. </p>
<p>When I attempted to execute this procedure through C# I get an error referring to the fact that description is expected but not provided. When calling it like this:</p>
<pre><code> cmd.Parameters["@description"].Value = result.Description;
</code></pre>
<p>result.Description is null. Should this not default to NULL (well '' in my case right now) in SQL? </p>
<p>Here's the calling command:</p>
<pre><code> cmd.CommandText = "EXEC [dbo].insert_test_result @executed,
@failure, @success, @testID, @time, @name,
@description, @executionDateTime, @message;";
...
cmd.Parameters.Add("@description", SqlDbType.VarChar);
cmd.Parameters.Add("@executionDateTime", SqlDbType.VarChar);
cmd.Parameters.Add("@message", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = result.Name;
cmd.Parameters["@description"].Value = result.Description;
...
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
...
finally
{
connection.Close();
}
</code></pre>
|
[
{
"answer_id": 155082,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "cmd.CommandText = \"insert_test_result\";\ncmd.CommandType = CommandType.StoredProcedure;\n foreach (IDataParameter param in command.Parameters)\n {\n if (param.Value == null) param.Value = DBNull.Value;\n }\n"
},
{
"answer_id": 155099,
"author": "Dave Neeley",
"author_id": 9660,
"author_profile": "https://Stackoverflow.com/users/9660",
"pm_score": 0,
"selected": false,
"text": "EXEC [dbo].insert_test_result \n@executed = @executed,\n@failure = @failure, \n@success = @success, \n@testID = @testID, \n@time = @time, \n@name = @name, \n@description = @description, \n@executionDateTime = @executionDateTime, \n@message = @message;\n"
},
{
"answer_id": 169417,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 0,
"selected": false,
"text": "\ncmd.CommandText = \"insert_test_result\";\ncmd.Parameters.Add(new SQLParameter(\"@description\", result.Description));\ncmd.Parameters.Add(new SQLParameter(\"@message\", result.Message));\ntry\n{\n connection.Open();\n cmd.ExecuteNonQuery();\n}\nfinally\n{\n connection.Close();\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
] |
155,080
|
<p>I can get rootmenuitemlefthtml and rootmenuitemrighthtml to emit but not separator. Tried CDATA wrapping and setting SeparatorCssClass. I just want pipes between root menu items.</p>
<pre><code><dnn:SOLPARTMENU runat="server" id="dnnSOLPARTMENU" Separator="<![CDATA[|]]>" SeparatorCssClass="MainMenu_SeparatorCSS"
usearrows="false"
userootbreadcrumbarrow="false" usesubmenubreadcrumbarrow="false"
rootmenuitemlefthtml="&nbsp;&lt;span&gt;&nbsp;&nbsp;&nbsp;" rootmenuitemrighthtml="&nbsp;&nbsp;&nbsp;&lt;/span&gt;" rootmenuitemcssclass="rootmenuitem"
rootmenuitemselectedcssclass="rootmenuitemselected" rootmenuitembreadcrumbcssclass="rootmenuitembreadcrumb"
submenucssclass="submenu" submenuitemselectedcssclass="submenuitemselected" submenuitembreadcrumbcssclass="submenuitembreadcrumb"
CSSNodeSelectedRoot="rootmenuitembreadcrumb" CSSNodeSelectedSub="submenuitembreadcrumb"
MouseOverAction="False" MouseOutHideDelay="0"
delaysubmenuload="true" level="Root" />
</code></pre>
|
[
{
"answer_id": 391474,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<dnn:SOLPARTMENU runat=\"server\" ID=\"dnnHorizontalSolpart\" ProviderName=\"SolpartMenuNavigationProvider\"\n ClearDefaults=\"True\" MenuBarCssClass=\"Hmain_dnnmenu_bar\" MenuContainerCssClass=\"Hmain_dnnmenu_container\"\n MenuItemCssClass=\"Hmain_dnnmenu_rootitem\" MenuItemSelCssClass=\"Hmain_dnnmenu_itemhoverRoot\"\n MenuIconCssClass=\"Hmain_dnnmenu_icon\" MenuBreakCssClass=\"Hmain_dnnmenu_break\"\n SubMenuCssClass=\"Hmain_dnnmenu_submenu\" SubMenuItemSelectedCssClass=\"Hmain_dnnmenu_subselected\"\n CSSNodeSelectedRoot=\"Hmain_dnnmenu_rootselected\" MenuEffectsMouseOverDisplay=\"None\"\n Separator=\"|\" SeparatorCssClass=\"Hmain_dnnmenu_separator\" UseArrows=\"False\" UseRootBreadCrumbArrow=\"False\" />\n .Hmain_dnnmenu_separator\n{\n background-color: Transparent;\n color: #C55203;\n font-family: Arial;\n font-size: 11px;\n}\n.Hmain_dnnmenu_bar\n{\n cursor: pointer;\n cursor: hand;\n height: 30px;\n background-color: Transparent;\n}\n.Hmain_dnnmenu_container\n{\n background-color: Transparent;\n}\n.Hmain_dnnmenu_rootitem\n{\n background-color: #DBDBDB;\n cursor: pointer;\n cursor: hand;\n color: #C55203;\n font-family: Arial;\n font-size: 11px;\n _height: 30px;\n _padding: 5px;\n vertical-align: middle;\n text-decoration:underline;\n}\n.Hmain_dnnmenu_rootitem td\n{\n font-family: Arial;\n font-size: 11px;\n _height: 30px;\n _padding: 5px;\n vertical-align: middle;\n}\n.Hmain_dnnmenu_itemhoverRoot\n{\n background-color: #DBDBDB;\n color: #C55203;\n cursor: pointer;\n cursor: hand;\n font-family: Arial;\n font-size: 11px;\n _height: 30px;\n _padding: 5px;\n text-decoration:underline;\n vertical-align: middle;\n}\n.Hmain_dnnmenu_icon\n{\n cursor: pointer;\n cursor: hand;\n}\n.Hmain_dnnmenu_submenu\n{\n background-color: #DBDBDB;\n border: solid 1px #B7B7B7;\n cursor: pointer;\n cursor: hand;\n color: #C55203;\n font-family: Arial;\n font-size: 11px;\n text-align: left;\n text-decoration:none;\n z-index: 1000;\n}\n.Hmain_dnnmenu_submenu td\n{\n border-bottom: solid 1px #B7B7B7;\n font-family: Arial;\n font-size: 11px;\n text-align: left;\n text-decoration:none;\n}\n.Hmain_dnnmenu_break\n{\n font-family: Arial;\n font-size: 11px;\n}\n.Hmain_dnnmenu_rootselected\n{\n color: #C55203;\n cursor: pointer;\n cursor: hand;\n font-size: 11px;\n font-weight: lighter;\n font-style: normal;\n font-family: Arial;\n white-space: nowrap;\n vertical-align: middle;\n text-decoration: None;\n}\n.Hmain_dnnmenu_submenu_itemhover\n{\n background-color: #C55203;\n color: #FFFFFF;\n font-family: Arial;\n font-size: 11px;\n}\n.Hmain_dnnmenu_subselected\n{\n background-color: #C55203;\n color: #FFFFFF;\n font-family: Arial;\n font-size: 11px;\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489/"
] |
155,084
|
<p>I'm about to push out a website soon and so I've gotten in the last stages. Time to optimize the baby! The website performs pretty good overall, with an average framerate of 32fps. But at some heavy animation parts it likes to drop a couple of frames to about 22fps. Which is not that horrible. But I'm tweaking it as much as possible to keep it running at the highest speed possible.</p>
<p>I might overlooked some tips and tricks to make this baby run even smoother. </p>
<p>So hereby I open this thread to share whatever ninja tricks ever helped you in the past. A couple of mine which I can think of right now:</p>
<p><strong>Sequencing the animation:</strong></p>
<p>Let as less as possible transitions happen at the same time, try to make it act more as a transformer, one thing at a time. Next to gaining speed in animation, you probably end up gaining more flow.</p>
<p><strong>Keep the animating objects as small as possible:</strong></p>
<p>So flash has to calculate less pixels at the same time.</p>
<p><strong>cacheAsBitmap = true:</strong></p>
<p>Those big movieclips, vector shapes being moved around, are probably quicker moved when they are cached as a bitmap. Might take up some space in your memory, but anything for higher framerates ;)</p>
<p><strong>Destroy everything you do not use:</strong></p>
<p>Set those unused movieclips to null and then remove it as a child. So your garbage collector takes care of it.</p>
|
[
{
"answer_id": 155182,
"author": "Iain",
"author_id": 11911,
"author_profile": "https://Stackoverflow.com/users/11911",
"pm_score": 2,
"selected": false,
"text": "cacheAsBitmap = true:"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18671/"
] |
155,087
|
<p>Before you start firing at me, I'm NOT looking to do this, but someone in <a href="https://stackoverflow.com/questions/154698/how-can-i-keep-a-class-from-being-inherited-in-c">another post</a> said it was possible. How is it possible? I've never heard of inheriting from anything using reflection. But I've seen some strange things...</p>
|
[
{
"answer_id": 155185,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": true,
"text": "// error CS0549: 'Seal.GetName()' is a new virtual member in sealed class 'Seal'\n public abstract class Animal\n{\n private readonly string m_name;\n\n public virtual string GetName() { return m_name; }\n\n public Animal( string name )\n { m_name = name; }\n}\n\npublic sealed class Seal : Animal\n{\n public Seal( string name ) : base(name) {}\n}\n"
},
{
"answer_id": 156599,
"author": "dalle",
"author_id": 19100,
"author_profile": "https://Stackoverflow.com/users/19100",
"pm_score": 4,
"selected": false,
"text": "sealed class Sealed\n{\n public int x;\n public int y;\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n AppDomain ad = Thread.GetDomain();\n AssemblyName an = new AssemblyName();\n an.Name = \"MyAssembly\";\n AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);\n ModuleBuilder mb = ab.DefineDynamicModule(\"MyModule\");\n TypeBuilder tb = mb.DefineType(\"MyType\", TypeAttributes.Class, typeof(Sealed));\n\n // Following throws TypeLoadException: Could not load type 'MyType' from\n // assembly 'MyAssembly' because the parent type is sealed.\n Type t = tb.CreateType();\n }\n}\n"
},
{
"answer_id": 937631,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": " public class GenericKeyValueBase<TKey,TValue>\n {\n public TKey Key;\n public TValue Value;\n\n public GenericKeyValueBase(TKey ItemKey, TValue ItemValue)\n {\n Key = ItemKey;\n Value = ItemValue;\n }\n }\n class GenericCookieItem<TCookieKey, TCookieValue> : GenericKeyValueBase<TCookieKey,TCookieValue>\n {\n public GenericCookieItem(TCookieKey KeyValue, TCookieValue ItemValue) : base(KeyValue, ItemValue)\n {\n }\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] |
155,097
|
<p>I am programmatically exporting data (using PHP 5.2) into a .csv test file.<br>
Example data: <code>Numéro 1</code> (note the accented e).
The data is <code>utf-8</code> (no prepended BOM).</p>
<p>When I open this file in MS Excel is displays as <code>Numéro 1</code>.</p>
<p>I am able to open this in a text editor (UltraEdit) which displays it correctly. UE reports the character is <code>decimal 233</code>.</p>
<p>How can I <strong>export text</strong> data in a .csv file so <strong>that MS Excel will correctly render</strong> it, preferably without forcing the use of the import wizard, or non-default wizard settings?</p>
|
[
{
"answer_id": 155176,
"author": "James Baker",
"author_id": 9365,
"author_profile": "https://Stackoverflow.com/users/9365",
"pm_score": 9,
"selected": true,
"text": " Ã"
},
{
"answer_id": 595754,
"author": "Kristof Neirynck",
"author_id": 11451,
"author_profile": "https://Stackoverflow.com/users/11451",
"pm_score": 2,
"selected": false,
"text": "<%@LANGUAGE=\"JAVASCRIPT\" CODEPAGE=\"65001\"%>\n<%\nResponse.Clear();\nResponse.ContentType = \"text/csv\";\nResponse.Charset = \"utf-8\";\nResponse.AddHeader(\"Content-Disposition\", \"attachment; filename=excelTest.csv\");\nResponse.Write(\"\\uFEFF\");\n// csv text here\n%>\n"
},
{
"answer_id": 957886,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 2,
"selected": false,
"text": "<html>\n<meta http-equiv=\"Content-Type\" content=\"text/html\" charset=\"utf-8\" />\n<table>\n<tr>\n <th>id</th>\n <th>name</th>\n</tr>\n<tr>\n <td>4</td>\n <td>Hélène</td>\n</tr>\n</table>\n</html>\n"
},
{
"answer_id": 984796,
"author": "John Machin",
"author_id": 84270,
"author_profile": "https://Stackoverflow.com/users/84270",
"pm_score": 2,
"selected": false,
"text": "Old MacDonald had a farm,ÈÌÉÍØ >>> open('oldmac.csv', 'rb').read()\n'\\xef\\xbb\\xbfOld MacDonald had a farm,\\xc3\\x88\\xc3\\x8c\\xc3\\x89\\xc3\\x8d\\xc3\\x98\\r\\n'\n>>> ^Z\n"
},
{
"answer_id": 1648671,
"author": "Marc Carlucci",
"author_id": 199512,
"author_profile": "https://Stackoverflow.com/users/199512",
"pm_score": 5,
"selected": false,
"text": " /**\n * Export an array as downladable Excel CSV\n * @param array $header\n * @param array $data\n * @param string $filename\n */\n function toCSV($header, $data, $filename) {\n $sep = \"\\t\";\n $eol = \"\\n\";\n $csv = count($header) ? '\"'. implode('\"'.$sep.'\"', $header).'\"'.$eol : '';\n foreach($data as $line) {\n $csv .= '\"'. implode('\"'.$sep.'\"', $line).'\"'.$eol;\n }\n $encoded_csv = mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');\n header('Content-Description: File Transfer');\n header('Content-Type: application/vnd.ms-excel');\n header('Content-Disposition: attachment; filename=\"'.$filename.'.csv\"');\n header('Content-Transfer-Encoding: binary');\n header('Expires: 0');\n header('Cache-Control: must-revalidate, post-check=0, pre-check=0');\n header('Pragma: public');\n header('Content-Length: '. strlen($encoded_csv));\n echo chr(255) . chr(254) . $encoded_csv;\n exit;\n }\n"
},
{
"answer_id": 5489179,
"author": "Johal",
"author_id": 360818,
"author_profile": "https://Stackoverflow.com/users/360818",
"pm_score": 3,
"selected": false,
"text": "echo \"\\xEF\\xBB\\xBF\";\n"
},
{
"answer_id": 6139108,
"author": "Lukas Batteau",
"author_id": 771345,
"author_profile": "https://Stackoverflow.com/users/771345",
"pm_score": 1,
"selected": false,
"text": "def handlePersoonListExport(request):\n # Retrieve a query_set\n ...\n\n template = loader.get_template(\"export.csv\")\n context = Context({\n 'data': query_set,\n })\n\n response = HttpResponse()\n response['Content-Disposition'] = 'attachment; filename=export.csv'\n response['Content-Type'] = 'text/csv; charset=utf-8'\n response.write(\"\\xEF\\xBB\\xBF\")\n response.write(template.render(context))\n\n return response\n"
},
{
"answer_id": 7764980,
"author": "Antonio Bardazzi",
"author_id": 614407,
"author_profile": "https://Stackoverflow.com/users/614407",
"pm_score": 0,
"selected": false,
"text": "<% \n require 'fastercsv' \n fcsv_options = { \n :row_sep => \"\\n\", \n :col_sep => params[:delimiter], \n :force_quotes => @export_config.force_quotes, \n :headers => @export_columns.collect { |column| format_export_column_header_name(column) } \n } \n\n data = FasterCSV.generate(fcsv_options) do |csv| \n csv << fcsv_options[:headers] unless params[:skip_header] == 'true' \n @records.each do |record| \n csv << @export_columns.collect { |column| \n # Convert to UTF-16 discarding the BOM, required for Excel (> 2003 ?) \n Iconv.conv('UTF-16', 'UTF-8', get_export_column_value(record, column))[2..-1] \n } \n end \n end \n -%><%= data -%>\n Iconv.conv('UTF-16', 'UTF-8', get_export_column_value(record, column))[2..-1]\n"
},
{
"answer_id": 7824054,
"author": "creechy",
"author_id": 1003503,
"author_profile": "https://Stackoverflow.com/users/1003503",
"pm_score": 1,
"selected": false,
"text": "Content-Type text/csv; charset=Windows-1252"
},
{
"answer_id": 8299052,
"author": "Fred Reillier",
"author_id": 1069756,
"author_profile": "https://Stackoverflow.com/users/1069756",
"pm_score": 0,
"selected": false,
"text": ".xls .xlsx"
},
{
"answer_id": 8488101,
"author": "Johann",
"author_id": 638040,
"author_profile": "https://Stackoverflow.com/users/638040",
"pm_score": 0,
"selected": false,
"text": " Response.Clear()\n Response.ClearHeaders()\n Response.ContentType = \"text/csv\"\n Response.Expires = 0\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=export.csv;\")\n Using sw As StreamWriter = New StreamWriter(Context.Response.OutputStream, System.Text.Encoding.Unicode)\n sw.Write(csv)\n sw.Close()\n End Using\n Response.End()\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23598/"
] |
155,101
|
<p>When I parse my xml file (variable f) in this method, I get an error </p>
<blockquote>
<p>C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified)</p>
</blockquote>
<p>I know I do not have the dtd, nor do I need it. How can I parse this File object into a Document object while ignoring DTD reference errors?</p>
<pre><code>private static Document getDoc(File f, String docId) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
return doc;
}
</code></pre>
|
[
{
"answer_id": 155330,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 2,
"selected": false,
"text": "myDocumentBuilder.setEntityResolver(new EntityResolver() {\n public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId)\n throws SAXException, java.io.IOException\n {\n if (publicId.equals(\"--myDTDpublicID--\"))\n // this deactivates the open office DTD\n return new InputSource(new ByteArrayInputStream(\"<?xml version='1.0' encoding='UTF-8'?>\".getBytes()));\n else return null;\n }\n});\n"
},
{
"answer_id": 155353,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 7,
"selected": true,
"text": " builder.setEntityResolver(new EntityResolver() {\n @Override\n public InputSource resolveEntity(String publicId, String systemId)\n throws SAXException, IOException {\n if (systemId.contains(\"foo.dtd\")) {\n return new InputSource(new StringReader(\"\"));\n } else {\n return null;\n }\n }\n });\n"
},
{
"answer_id": 155874,
"author": "jt.",
"author_id": 4362,
"author_profile": "https://Stackoverflow.com/users/4362",
"pm_score": 7,
"selected": false,
"text": "DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n\ndbf.setValidating(false);\ndbf.setNamespaceAware(true);\ndbf.setFeature(\"http://xml.org/sax/features/namespaces\", false);\ndbf.setFeature(\"http://xml.org/sax/features/validation\", false);\ndbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\ndbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n\nDocumentBuilder db = dbf.newDocumentBuilder();\n...\n"
},
{
"answer_id": 5819461,
"author": "Peter J",
"author_id": 729412,
"author_profile": "https://Stackoverflow.com/users/729412",
"pm_score": 3,
"selected": false,
"text": "DocumentBuilder db = dbf.newDocumentBuilder();\ndb.setEntityResolver(new EntityResolver() {\n public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {\n if (systemId.contains(\"doc.dtd\")) {\n InputStream dtdStream = MyClass.class\n .getResourceAsStream(\"/my/package/doc.dtd\");\n return new InputSource(dtdStream);\n } else {\n return null;\n }\n }\n});\n"
},
{
"answer_id": 40529465,
"author": "Shoaib Khan",
"author_id": 2149956,
"author_profile": "https://Stackoverflow.com/users/2149956",
"pm_score": 3,
"selected": false,
"text": "<!DOCTYPE MYSERVICE SYSTEM \"./MYSERVICE.DTD\">\n<MYACCSERVICE>\n <REQ_PAYLOAD>\n <ACCOUNT>1234567890</ACCOUNT>\n <BRANCH>001</BRANCH>\n <CURRENCY>USD</CURRENCY>\n <TRANS_REFERENCE>201611100000777</TRANS_REFERENCE>\n </REQ_PAYLOAD>\n</MYACCSERVICE>\n public Document removeDTDFromXML(String payload) throws Exception {\n\n System.out.println(\"### Payload received in XMlDTDRemover: \" + payload);\n\n Document doc = null;\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n try {\n\n dbf.setValidating(false);\n dbf.setNamespaceAware(true);\n dbf.setFeature(\"http://xml.org/sax/features/namespaces\", false);\n dbf.setFeature(\"http://xml.org/sax/features/validation\", false);\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\n dbf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n\n DocumentBuilder db = dbf.newDocumentBuilder();\n\n InputSource is = new InputSource();\n is.setCharacterStream(new StringReader(payload));\n doc = db.parse(is); \n\n } catch (ParserConfigurationException e) {\n System.out.println(\"Parse Error: \" + e.getMessage());\n return null;\n } catch (SAXException e) {\n System.out.println(\"SAX Error: \" + e.getMessage());\n return null;\n } catch (IOException e) {\n System.out.println(\"IO Error: \" + e.getMessage());\n return null;\n }\n return doc;\n\n}\n <MYACCSERVICE>\n <REQ_PAYLOAD>\n <ACCOUNT>1234567890</ACCOUNT>\n <BRANCH>001</BRANCH>\n <CURRENCY>USD</CURRENCY>\n <TRANS_REFERENCE>201611100000777</TRANS_REFERENCE>\n </REQ_PAYLOAD>\n</MYACCSERVICE> \n"
},
{
"answer_id": 60079698,
"author": "McCoy",
"author_id": 2816092,
"author_profile": "https://Stackoverflow.com/users/2816092",
"pm_score": 0,
"selected": false,
"text": " factory = DocumentBuilderFactory.newInstance();\n\n factory.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true);\n\n // If you can't completely disable DTDs, then at least do the following:\n // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities\n // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities\n // JDK7+ - http://xml.org/sax/features/external-general-entities\n factory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n\n // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities\n // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities\n // JDK7+ - http://xml.org/sax/features/external-parameter-entities\n factory.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n\n // Disable external DTDs as well\n factory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n\n // and these as well, per Timothy Morgan's 2014 paper: \"XML Schema, DTD, and Entity Attacks\"\n factory.setXIncludeAware(false);\n factory.setExpandEntityReferences(false);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5653/"
] |
155,105
|
<p>I am getting the following error when I put class files in subfolders of my App_Code folder:</p>
<p>errorCS0246: The type or namespace name 'MyClassName' could not be found (are you missing a using directive or an assembly reference?)</p>
<p>This class is not in a namespace at all. Any ideas?</p>
|
[
{
"answer_id": 155149,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 5,
"selected": true,
"text": "<configuration>\n <system.web>\n <compilation>\n <codeSubDirectories>\n <add directoryName=\"View\"/>\n </codeSubDirectories>\n </compilation>\n </system.web>\n</configuration>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18926/"
] |
155,116
|
<p>I have several different c# worker applications that run various continuous tasks: sending emails from queue, importing new orders from website database to orders database, making database backups and restores, running data processing for OLTP -> OLAP, and other related tasks. Before, I released these as windows services, but currently I release them as regular console applications. They are all based on a common task runner framework I created, and I am happy with that, however I am not sure what is the best way to deploy these types of applications. I like the console version because it is quick and easy, and it is possible to quickly see program activity and output. The downside is that the worker computer has several console screens running and it gets messy. On the other hand the service method seems to take to long to deploy and I have to go through event logs to see messages. What are some experiences/comments on this?</p>
|
[
{
"answer_id": 155180,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "installutil MyApp.exe\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13855/"
] |
155,144
|
<p>I've got a relatively large .Net system that consists of a number of different applications. Rather than having lots of different app.config files, I would like to share a single configuration file between all the apps.</p>
<p>I would also like to have one version when developing on my machine, one version for someone else developing on their machine, one version for a test system and one version for a live system. </p>
<p>Is there an easy way of doing this? </p>
|
[
{
"answer_id": 155167,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 2,
"selected": false,
"text": "copy /Y c:\\path\\to\\master\\project\\app.config $(TargetPath).config\nexit 0\n <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n <DebugSymbols>true</DebugSymbols>\n <DebugType>full</DebugType>\n <Optimize>false</Optimize>\n <OutputPath>.\\bin\\Debug\\</OutputPath>\n <DefineConstants>DEBUG;TRACE</DefineConstants>\n <AppConfig>debug.app.config</AppConfig>\n </PropertyGroup>\n <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n <DebugSymbols>true</DebugSymbols>\n <DebugType>full</DebugType>\n <Optimize>false</Optimize>\n <OutputPath>.\\bin\\Devel\\</OutputPath>\n <DefineConstants>TRACE</DefineConstants>\n <AppConfig>release.app.config</AppConfig>\n </PropertyGroup>\n"
},
{
"answer_id": 155485,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "<add> <appSettings> file= <appSettings>"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
] |
155,152
|
<p>I'm building a form with php/mysql. I've got a table with a list of locations and sublocations. Each sublocation has a parent location. A column "parentid" references another locationid in the same table. I now want to load these values into a dropdown in the following manner:</p>
<pre><code>--Location 1
----Sublocation 1
----Sublocation 2
----Sublocation 3
--Location 2
----Sublocation 4
----Sublocation 5
</code></pre>
<p>etc. etc.</p>
<p>Did anyone get an elegant solution for doing this?</p>
|
[
{
"answer_id": 155177,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n$data = array(\n 'Location 1' => array(\n 'Sublocation1',\n 'Sublocation2',\n 'Sublocation3' => array(\n 'SubSublocation1',\n ),\n 'Location2'\n);\n\n$output = '<select name=\"location\">' . PHP_EOL;\n\nfunction build_items($input, $output)\n{\n if(is_array($input))\n {\n $output .= '<optgroup>' . $key . '</optgroup>' . PHP_EOL;\n foreach($input as $key => $value)\n {\n $output = build_items($value, $output);\n }\n }\n else\n {\n $output .= '<option>' . $value . '</option>' . PHP_EOL;\n }\n\n return $output;\n}\n\n$output = build_items($data, $output);\n\n$output .= '</select>' . PHP_EOL;\n\n?>\n"
},
{
"answer_id": 155208,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 2,
"selected": true,
"text": "$parentsql = \"SELECT parentid, parentname FROM table\";\n\n $result = mysql_query($parentsql);\n print \"<select>\";\n while($row = mysql_fetch_assoc($result)){\n $childsql = \"SELECT childID, childName from table where parentid=\".$row[\"parentID\"];\n $result2 = mysql_query($childsql);\n print \"<optgroup label=\\\".$row[\"parentname\"].\"\\\">\";\n while($row2 = mysql_fetch_assoc($result)){\n print \"<option value=\\\"\".$row[\"childID\"].\"\\\">\".$row[\"childName\"].\"</option>\\n\";\n }\n print \"</optgroup>\";\n}\n print \"</select>\";\n $sql = \"SELECT childId, childName, parentId, parentName FROM child LEFT JOIN parent ON child.parentId = parent.parentId ORDER BY parentID, childName\"; \n$result = mysql_query($sql);\n$currentParent = \"\";\n\nprint \"<select>\";\nwhile($row = mysql_fetch_assoc($result)){\n if($currentParent != $row[\"parentID\"]){\n if($currentParent != \"\"){\n print \"</optgroup>\";\n }\n print \"<optgroup label=\\\".$row[\"parentName\"].\"\\\">\";\n $currentParent = $row[\"parentName\"];\n }\n\n print \"<option value=\\\"\".$row[\"childID\"].\"\\\">\".$row[\"childName\"].\"</option>\\n\";\n}\nprint \"</optgroup>\"\nprint \"</select>\";\n"
},
{
"answer_id": 155530,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 0,
"selected": false,
"text": "<?php\n/*\nAssuming data that looks like this\n\nlocations\n+----+-----------+-------+\n| id | parent_id | descr |\n+----+-----------+-------+\n| 1 | null | Foo |\n| 2 | null | Bar |\n| 3 | 1 | Doe |\n| 4 | 2 | Rae |\n| 5 | 1 | Mi |\n| 6 | 2 | Fa |\n+----+-----------+-------+\n*/\n\n$result = mysql_query( \"SELECT id, parent_id, descr FROM locations order by coalesce(id, parent_id), descr\" );\n\necho \"<select>\";\nwhile ( $row = mysql_fetch_object( $result ) )\n{\n $optionName = htmlspecialchars( ( is_null( $row->parent_id ) ) ? \"--{$row->descr}\" : \"----{$row->desc}r\", ENT_COMPAT, 'UTF-8' );\n echo \"<option value=\\\"{$row->id}\\\">$optionName</option>\";\n}\necho \"</select>\";\n coalesce() ORDER BY"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22837/"
] |
155,188
|
<p>I have one text input and one button (see below). How can I use JavaScript to <strong>trigger the button's click event</strong> when the <kbd>Enter</kbd> key is pressed inside the text box?</p>
<p>There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I <em>only</em> want the <kbd>Enter</kbd> key to click this specific button if it is pressed from within this one text box, nothing else.</p>
<pre><code><input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
</code></pre>
|
[
{
"answer_id": 155193,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 6,
"selected": false,
"text": "<input type = \"submit\"\n id = \"btnSearch\"\n value = \"Search\"\n onclick = \"return doSomething();\"\n/>\n <form>"
},
{
"answer_id": 155263,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 12,
"selected": true,
"text": "$(\"#id_of_textbox\").keyup(function(event) {\n if (event.keyCode === 13) {\n $(\"#id_of_button\").click();\n }\n});\n $(\"#pw\").keyup(function(event) {\n if (event.keyCode === 13) {\n $(\"#myButton\").click();\n }\n});\n\n$(\"#myButton\").click(function() {\n alert(\"Button code executed.\");\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\nUsername:<input id=\"username\" type=\"text\"><br>\nPassword: <input id=\"pw\" type=\"password\"><br>\n<button id=\"myButton\">Submit</button> document.getElementById(\"id_of_textbox\")\n .addEventListener(\"keyup\", function(event) {\n event.preventDefault();\n if (event.keyCode === 13) {\n document.getElementById(\"id_of_button\").click();\n }\n});\n document.getElementById(\"pw\")\n .addEventListener(\"keyup\", function(event) {\n event.preventDefault();\n if (event.keyCode === 13) {\n document.getElementById(\"myButton\").click();\n }\n});\n\nfunction buttonCode()\n{\n alert(\"Button code executed.\");\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\nUsername:<input id=\"username\" type=\"text\"><br>\nPassword: <input id=\"pw\" type=\"password\"><br>\n<button id=\"myButton\" onclick=\"buttonCode()\">Submit</button>"
},
{
"answer_id": 155265,
"author": "kdenney",
"author_id": 23947,
"author_profile": "https://Stackoverflow.com/users/23947",
"pm_score": 8,
"selected": false,
"text": "<input type=\"text\" id=\"txtSearch\" onkeypress=\"return searchKeyPress(event);\" />\n<input type=\"button\" id=\"btnSearch\" Value=\"Search\" onclick=\"doSomething();\" />\n\n<script>\nfunction searchKeyPress(e)\n{\n // look for window.event in case event isn't passed in\n e = e || window.event;\n if (e.keyCode == 13)\n {\n document.getElementById('btnSearch').click();\n return false;\n }\n return true;\n}\n</script>\n"
},
{
"answer_id": 155272,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 9,
"selected": false,
"text": "<input type = \"text\"\n id = \"txtSearch\" \n onkeydown = \"if (event.keyCode == 13)\n document.getElementById('btnSearch').click()\" \n/>\n\n<input type = \"button\"\n id = \"btnSearch\"\n value = \"Search\"\n onclick = \"doSomething();\"\n/>\n"
},
{
"answer_id": 155274,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 4,
"selected": false,
"text": "onkeydown=\"javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};\"\n"
},
{
"answer_id": 2691390,
"author": "ELEK",
"author_id": 323305,
"author_profile": "https://Stackoverflow.com/users/323305",
"pm_score": 3,
"selected": false,
"text": "event.returnValue = false\n"
},
{
"answer_id": 2795390,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<input type=\"text\" id=\"txtSearch\" onchange=\"doSomething();\" />\n<input type=\"button\" id=\"btnSearch\" value=\"Search\" onclick=\"doSomething();\" />\n"
},
{
"answer_id": 4929676,
"author": "Varun",
"author_id": 519755,
"author_profile": "https://Stackoverflow.com/users/519755",
"pm_score": 6,
"selected": false,
"text": "if (document.layers) {\n document.captureEvents(Event.KEYDOWN);\n}\n\ndocument.onkeydown = function (evt) {\n var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;\n if (keyCode == 13) {\n // For Enter.\n // Your function here.\n }\n if (keyCode == 27) {\n // For Escape.\n // Your function here.\n } else {\n return true;\n }\n};\n"
},
{
"answer_id": 7400586,
"author": "Niraj Chauhan",
"author_id": 608388,
"author_profile": "https://Stackoverflow.com/users/608388",
"pm_score": -1,
"selected": false,
"text": "<script type=\"text/javascript\">\nfunction blank(a) { if(a.value == a.defaultValue) a.value = \"\"; }\n\nfunction unblank(a) { if(a.value == \"\") a.value = a.defaultValue; }\n</script> \n<input type=\"text\" value=\"email goes here\" onfocus=\"blank(this)\" onblur=\"unblank(this)\" />\n"
},
{
"answer_id": 7911458,
"author": "me_an",
"author_id": 1013810,
"author_profile": "https://Stackoverflow.com/users/1013810",
"pm_score": 4,
"selected": false,
"text": "$(document).keypress(function(event) {\n var keycode = (event.keyCode ? event.keyCode : event.which);\n if (keycode == '13') {\n $('#btnSearch').click();\n }\n}\n"
},
{
"answer_id": 10626419,
"author": "user1071182",
"author_id": 1071182,
"author_profile": "https://Stackoverflow.com/users/1071182",
"pm_score": 3,
"selected": false,
"text": "$('#id_of_textbox').live(\"keyup\", function(event) {\n if(event.keyCode == '13'){\n $('#id_of_button').click();\n }\n});\n"
},
{
"answer_id": 18513090,
"author": "frhd",
"author_id": 2491198,
"author_profile": "https://Stackoverflow.com/users/2491198",
"pm_score": 4,
"selected": false,
"text": "Y.on('keydown', function() {\n if(event.keyCode == 13){\n Y.one(\"#id_of_button\").simulate(\"click\");\n }\n}, '#id_of_textbox');\n"
},
{
"answer_id": 18772817,
"author": "Switters",
"author_id": 1860358,
"author_profile": "https://Stackoverflow.com/users/1860358",
"pm_score": 5,
"selected": false,
"text": "<form onsubmit=\"Search();\" action=\"javascript:void(0);\">\n <input type=\"text\" id=\"searchCriteria\" placeholder=\"Search Criteria\"/>\n <input type=\"button\" onclick=\"Search();\" value=\"Search\" id=\"searchBtn\"/>\n</form>\n"
},
{
"answer_id": 20064004,
"author": "icedwater",
"author_id": 1091386,
"author_profile": "https://Stackoverflow.com/users/1091386",
"pm_score": 6,
"selected": false,
"text": "addEventListener <input type = \"text\" id = \"txt\" />\n<input type = \"button\" id = \"go\" />\n var go = document.getElementById(\"go\");\nvar txt = document.getElementById(\"txt\");\n\ntxt.addEventListener(\"keypress\", function(event) {\n event.preventDefault();\n if (event.keyCode == 13)\n go.click();\n});\n <form> preventDefault"
},
{
"answer_id": 23738023,
"author": "Eric Engel",
"author_id": 1874272,
"author_profile": "https://Stackoverflow.com/users/1874272",
"pm_score": 3,
"selected": false,
"text": "document.onkeypress = function (e) {\n e = e || window.event;\n var charCode = (typeof e.which == \"number\") ? e.which : e.keyCode;\n if (charCode == 13) {\n\n // Do something here\n printResult();\n }\n};\n"
},
{
"answer_id": 28805055,
"author": "mahbub_siddique",
"author_id": 2081867,
"author_profile": "https://Stackoverflow.com/users/2081867",
"pm_score": 4,
"selected": false,
"text": "<input type=\"text\" id=\"txtSearch\"/>\n<input type=\"button\" id=\"btnSearch\" Value=\"Search\"/>\n\n<script> \n window.onload = function() {\n document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {\n if (event.keyCode == 13) {\n document.getElementById('btnSearch').click();\n }\n };\n\n document.getElementById('btnSearch').onclick =doSomething;\n}\n</script>\n"
},
{
"answer_id": 29409637,
"author": "Stephen Ngethe",
"author_id": 2398620,
"author_profile": "https://Stackoverflow.com/users/2398620",
"pm_score": 3,
"selected": false,
"text": "<input type=\"text\" id=\"txtSearch\" onkeydown=\"if (event.keyCode == 13)\n {document.getElementById('btnSearch').click(); return false;}\"/>\n<input type=\"button\" id=\"btnSearch\" value=\"Search\" onclick=\"doSomething();\" />\n"
},
{
"answer_id": 30809553,
"author": "clickbait",
"author_id": 4356188,
"author_profile": "https://Stackoverflow.com/users/4356188",
"pm_score": 2,
"selected": false,
"text": "$(\"#txtSearch\").on(\"keyup\", function (event) {\n if (event.keyCode==13) {\n $(\"#btnSearch\").get(0).click();\n }\n});\n document.getElementById(\"txtSearch\").addEventListener(\"keyup\", function (event) {\n if (event.keyCode==13) { \n document.getElementById(\"#btnSearch\").click();\n }\n});\n"
},
{
"answer_id": 32155821,
"author": "AlikElzin-kilaka",
"author_id": 435605,
"author_profile": "https://Stackoverflow.com/users/435605",
"pm_score": 4,
"selected": false,
"text": "(keyup.enter)=\"doSomething()\"\n"
},
{
"answer_id": 34441952,
"author": "ruffin",
"author_id": 1028230,
"author_profile": "https://Stackoverflow.com/users/1028230",
"pm_score": 3,
"selected": false,
"text": "form <body>\n <form>\n <input type=\"text\" id=\"txt\" />\n <input type=\"button\" id=\"go\" value=\"Click Me!\" />\n <div id=\"outige\"></div>\n </form>\n</body>\n // The document.addEventListener replicates $(document).ready() for\n// modern browsers (including IE9+), and is slightly more robust than `onload`.\n// More here: https://stackoverflow.com/a/21814964/1028230\ndocument.addEventListener(\"DOMContentLoaded\", function() {\n var go = document.getElementById(\"go\"),\n txt = document.getElementById(\"txt\"),\n outige = document.getElementById(\"outige\");\n\n // Note that jQuery handles \"empty\" selections \"for free\".\n // Since we're plain JavaScripting it, we need to make sure this DOM exists first.\n if (txt && go) {\n txt.addEventListener(\"keypress\", function (e) {\n if (event.keyCode === 13) {\n go.click();\n e.preventDefault(); // <<< Most important missing piece from icedwater\n }\n });\n\n go.addEventListener(\"click\", function () {\n if (outige) {\n outige.innerHTML += \"Clicked!<br />\";\n }\n });\n }\n});\n"
},
{
"answer_id": 38252483,
"author": "NVRM",
"author_id": 2494754,
"author_profile": "https://Stackoverflow.com/users/2494754",
"pm_score": 3,
"selected": false,
"text": "let client = navigator.userAgent.toLowerCase(),\n isLinux = client.indexOf(\"linux\") > -1,\n isWin = client.indexOf(\"windows\") > -1,\n isMac = client.indexOf(\"apple\") > -1,\n isFirefox = client.indexOf(\"firefox\") > -1,\n isWebkit = client.indexOf(\"webkit\") > -1,\n isOpera = client.indexOf(\"opera\") > -1,\n input = document.getElementById('guestInput');\n\nif(isFirefox) {\n input.setAttribute(\"placeholder\", \"ALT+SHIFT+Z\");\n} else if (isWin) {\n input.setAttribute(\"placeholder\", \"ALT+Z\");\n} else if (isMac) {\n input.setAttribute(\"placeholder\", \"CTRL+ALT+Z\");\n} else if (isOpera) {\n input.setAttribute(\"placeholder\", \"SHIFT+ESCAPE->Z\");\n} else {'Point me to operate...'} <input type=\"text\" id=\"guestInput\" accesskey=\"z\" placeholder=\"Acces shortcut:\"></input>"
},
{
"answer_id": 48488107,
"author": "Alexandr Tsyganok",
"author_id": 4645226,
"author_profile": "https://Stackoverflow.com/users/4645226",
"pm_score": 3,
"selected": false,
"text": "input.addEventListener('keydown', (e) => {if (e.keyCode == 13) doSomething()});\n"
},
{
"answer_id": 48855408,
"author": "Gibolt",
"author_id": 974045,
"author_profile": "https://Stackoverflow.com/users/974045",
"pm_score": 5,
"selected": false,
"text": "keypress event.key === \"Enter\" const textbox = document.getElementById(\"txtSearch\");\ntextbox.addEventListener(\"keypress\", function onEvent(event) {\n if (event.key === \"Enter\") {\n document.getElementById(\"btnSearch\").click();\n }\n});\n"
},
{
"answer_id": 51254652,
"author": "Unmitigated",
"author_id": 9513184,
"author_profile": "https://Stackoverflow.com/users/9513184",
"pm_score": 2,
"selected": false,
"text": "event.which==13 form $('#formid').submit() $('#textfield').keyup(function(event){\n if(event.which==13){\n $('#submit').click();\n }\n});\n$('#submit').click(function(e){\n if($('#textfield').val().trim().length){\n alert(\"Submitted!\");\n } else {\n alert(\"Field can not be empty!\");\n }\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<label for=\"textfield\">\nEnter Text:</label>\n<input id=\"textfield\" type=\"text\">\n<button id=\"submit\">\nSubmit\n</button>"
},
{
"answer_id": 54422802,
"author": "MCCCS",
"author_id": 6557621,
"author_profile": "https://Stackoverflow.com/users/6557621",
"pm_score": 4,
"selected": false,
"text": "keyCode onkeydown <input onkeypress=\"if(event.key == 'Enter') {console.log('Test')}\">\n"
},
{
"answer_id": 59156750,
"author": "Ravi Makwana",
"author_id": 6631280,
"author_profile": "https://Stackoverflow.com/users/6631280",
"pm_score": -1,
"selected": false,
"text": "<button type=\"button\" class=\"ctrl-p\">Custom Print</button> // find elements\nvar banner = $(\"#banner-message\")\nvar button = $(\"button\")\n\n// handle click and add class\nbutton.on(\"click\", function(){\n if(banner.hasClass(\"alt\"))\n banner.removeClass(\"alt\")\n else\n banner.addClass(\"alt\")\n})\n\n$(document).ready(function(){\n $(document).on('keydown', function (e) {\n \n if (e.ctrlKey) {\n $('[class*=\"ctrl-\"]:not([data-ctrl])').each(function (idx, item) {\n var Key = $(item).prop('class').substr($(item).prop('class').indexOf('ctrl-') + 5, 1).toUpperCase();\n $(item).attr(\"data-ctrl\", Key);\n $(item).append('<div class=\"tooltip fade top in tooltip-ctrl alter-info\" role=\"tooltip\" style=\"margin-top: -61px; display: block; visibility: visible;\"><div class=\"tooltip-arrow\" style=\"left: 49.5935%;\"></div><div class=\"tooltip-inner\"> CTRL + ' + Key + '</div></div>')\n });\n }\n \n if (e.ctrlKey && e.which != 17) {\n var Key = String.fromCharCode(e.which).toLowerCase();\n if( $('.ctrl-'+Key).length == 1) {\n e.preventDefault();\n if (!$('#divLoader').is(\":visible\"))\n $('.ctrl-'+Key).click();\n console.log(\"You pressed ctrl + \"+Key );\n }\n }\n });\n $(document).on('keyup', function (e) {\n if(!e.ctrlKey ){\n $('[class*=\"ctrl-\"]').removeAttr(\"data-ctrl\");\n $(\".tooltip-ctrl\").remove();\n }\n })\n}); #banner-message {\n background: #fff;\n border-radius: 4px;\n padding: 20px;\n font-size: 25px;\n text-align: center;\n transition: all 0.2s;\n margin: 0 auto;\n width: 300px;\n}\n\n#banner-message.alt {\n background: #0084ff;\n color: #fff;\n margin-top: 40px;\n width: 200px;\n}\n\n#banner-message.alt button {\n background: #fff;\n color: #000;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div id=\"banner-message\">\n <p>Hello World</p>\n <button class=\"ctrl-s\" title=\"s\">Change color</button><br/><br/>\n <span>Press CTRL+S to trigger click event of button</span>\n</div>"
},
{
"answer_id": 62578092,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "txtSearch.onkeydown= e => (e.key==\"Enter\") ? btnSearch.click() : 1\n txtSearch.onkeydown= e => (e.key==\"Enter\") ? btnSearch.click() : 1\n\nfunction doSomething() {\n console.log('');\n} <input type=\"text\" id=\"txtSearch\" />\n<input type=\"button\" id=\"btnSearch\" value=\"Search\" onclick=\"doSomething();\" />"
},
{
"answer_id": 63446199,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 2,
"selected": false,
"text": "change document.getElementById(\"txtSearch\").addEventListener('change',\n () => document.getElementById(\"btnSearch\").click()\n);\n"
},
{
"answer_id": 72821294,
"author": "RustyH",
"author_id": 1272209,
"author_profile": "https://Stackoverflow.com/users/1272209",
"pm_score": 0,
"selected": false,
"text": " <input type=\"text\" id=\"message\" onkeypress=\"enterKeyHandler(event,'sendmessage')\" />\n <input type=\"button\" id=\"sendmessage\" value=\"Send\"/>\n function enterKeyHandler(e,button) {\n e = e || window.event;\n if (e.key == 'Enter') {\n document.getElementById(button).click();\n }\n}\n"
},
{
"answer_id": 73601824,
"author": "rsmdh",
"author_id": 10995048,
"author_profile": "https://Stackoverflow.com/users/10995048",
"pm_score": 0,
"selected": false,
"text": "$(\"#txtSearch\").keyup(function(e) {\n e.preventDefault();\n var keycode = (e.keyCode ? e.keyCode : e.which);\n if (keycode === 13 || e.key === 'Enter') \n {\n $(\"#btnSearch\").click();\n }\n});\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23947/"
] |
155,191
|
<p>I have written something that uses the following includes:</p>
<pre><code>#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <commctrl.h>
</code></pre>
<p>This code works fine on 2 machines with the Platform SDK installed, but doesn't run (neither debug nor release versions) on clean installs of windows (VMs of course). It dies with the quite familiar:</p>
<pre><code>---------------------------
C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe
---------------------------
C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe
This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
---------------------------
OK
---------------------------
</code></pre>
<p>How can I make it run on clean installs? Which dll is it using which it can't find? My bet is on commctrl, but can someone enlighten me on why it's isn't with every windows?</p>
<p>Further more, if anyone has tips on how to debug such a thing, as my CPP is already rusty, as it seems :)</p>
<p>Edit - What worked for me is downloading the Redistributable for Visual Studio 2008. I don't think it's a good solution - downloading a 2MB file and an install to run a simple 11K tool. I think I'll change the code to use LoadLibrary to get the 2 or 3 functions I need from comctl32.dll. Thanks everyone :)</p>
|
[
{
"answer_id": 155431,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 1,
"selected": false,
"text": "msvcrt.dll msvcr71.dll mscorwks.dll"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23942/"
] |
155,202
|
<p>I am troubleshooting an issue with IIS6 where all sites bound to ip addresses other than the default give an error message "network location cannot be reached" when trying to start any of these sites.</p>
<p>The nic has all the ip addresses configured.
When I do a httpcfg query iplisten, I see only the default ip address.
When I added them with httpcfg, then all the web sites stopped working so I figured I didn something wrong so I removed them.</p>
<p>Two questions:
1- Why are those websites refusing to start?
2- What should be in the result of httpcfg query iplisten? All ip addresses or just one?</p>
<p>The websites used to work fine and something has changed. I applied a few Windows updates but I am not sure if they broke anything (I doubt it.. otherwise hundreds of web hosting companies would be screaming)</p>
|
[
{
"answer_id": 155348,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 0,
"selected": false,
"text": "ERROR_NETWORK_UNREACHABLE ERROR_HOST_UNREACHABLE ERROR_PROTOCOL_UNREACHABLE WinError.h"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232/"
] |
155,203
|
<p>What is a good error handling practice for an asp.net site? Examples? Thanks!</p>
|
[
{
"answer_id": 155238,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 4,
"selected": true,
"text": " try\n {\n //Code that could error here\n }\n catch (FormatException ex)\n {\n //Code to tell user of their error\n //all other errors will be handled \n //by the global error handler\n }\n"
},
{
"answer_id": 155242,
"author": "MrBoJangles",
"author_id": 13578,
"author_profile": "https://Stackoverflow.com/users/13578",
"pm_score": 0,
"selected": false,
"text": "try\n{\n ...\n}\ncatch{}\n"
},
{
"answer_id": 1747662,
"author": "234234",
"author_id": 212739,
"author_profile": "https://Stackoverflow.com/users/212739",
"pm_score": 0,
"selected": false,
"text": "public string BookLesson(Customer_Info oCustomerInfo, CustLessonBook_Info oCustLessonBookInfo)\n {\n string authenticationID = string.Empty;\n int customerID = 0;\n string message = string.Empty;\n DA_Customer oDACustomer = new DA_Customer();\n\n using (TransactionScope scope = new TransactionScope())\n {\n if (oDACustomer.ValidateCustomerLoginName(oCustomerInfo.CustId, oCustomerInfo.CustLoginName) == \"Y\")\n {\n // if a new student\n if (oCustomerInfo.CustId == 0)\n {\n oCustomerInfo.CustPassword = General.GeneratePassword(6, 8);\n oCustomerInfo.CustPassword = new DA_InternalUser().GetPassword(oCustomerInfo.CustPassword, false);\n authenticationID = oDACustomer.Register(oCustomerInfo, ref customerID);\n oCustLessonBookInfo.CustId = customerID;\n }\n else // if existing student\n {\n oCustomerInfo.UpdatedByCustomer = \"Y\";\n authenticationID = oDACustomer.CustomerUpdateProfile(oCustomerInfo);\n }\n message = authenticationID;\n // insert lesson booking details\n new DA_Lesson().BookLesson(oCustLessonBookInfo);\n }\n\n else\n {\n message = \"login exists\";\n }\n scope.Complete();\n return message;\n }\n\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
155,220
|
<p>We are trying to update our classic asp search engine to protect it from SQL injection. We have a VB 6 function which builds a query dynamically by concatenating a query together based on the various search parameters. We have converted this to a stored procedure using dynamic sql for all parameters except for the keywords.</p>
<p>The problem with keywords is that there are a variable number words supplied by the user and we want to search several columns for each keyword. Since we cannot create a separate parameter for each keyword, how can we build a safe query?</p>
<p>Example:</p>
<pre><code>@CustomerId AS INT
@Keywords AS NVARCHAR(MAX)
@sql = 'SELECT event_name FROM calendar WHERE customer_id = @CustomerId '
--(loop through each keyword passed in and concatenate)
@sql = @sql + 'AND (event_name LIKE ''%' + @Keywords + '%'' OR event_details LIKE ''%' + @Keywords + '%'')'
EXEC sp_executesql @sql N'@CustomerId INT, @CustomerId = @CustomerId
</code></pre>
<p>What is the best way to handle this and maintaining protection from SQL injection? </p>
|
[
{
"answer_id": 155332,
"author": "Rikalous",
"author_id": 4271,
"author_profile": "https://Stackoverflow.com/users/4271",
"pm_score": 2,
"selected": false,
"text": "string sql = \"SELECT Name, Title FROM Staff WHERE UserName=@UserId\";\nusing (SqlCommand cmd = new SqlCommand(sql))\n{\n cmd.Parameters.Add(\"@UserId\", SqlType.VarChar).Value = \"smithj\";\n"
},
{
"answer_id": 155362,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 1,
"selected": false,
"text": "SELECT * \nFROM calendar c\n JOIN dbo.fnListToTable(@Keywords) k \n ON c.keyword = k.keyword \n CREATE PROC spTest\n@Keyword1 varchar(100),\n@Keyword2 varchar(100),\n.... \n"
},
{
"answer_id": 156314,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "SELECT DISTINCT event_name\nFROM calendar\nINNER JOIN #keywords\n ON event_name LIKE '%' + #keywords.keyword + '%'\n OR event_description LIKE '%' + #keywords.keyword + '%'\n"
},
{
"answer_id": 3955689,
"author": "Ajascopee",
"author_id": 478838,
"author_profile": "https://Stackoverflow.com/users/478838",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM [tablename] WHERE LIKE % +keyword%\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23918/"
] |
155,234
|
<p>I have a cluster of three mongrels running under nginx, and I deploy the app using Capistrano 2.4.3. When I "cap deploy" when there is a running system, the behavior is: </p>
<ol>
<li>The app is deployed. The code is successfully updated. </li>
<li><p>In the cap deploy output, there is this: </p>
<ul>
<li>executing "sudo -p 'sudo password: '
mongrel_rails cluster::restart -C
/var/www/rails/myapp/current/config/mongrel_cluster.yml"</li>
<li>servers: ["myip"]</li>
<li>[myip] executing command</li>
<li>** [out :: myip] stopping port 9096</li>
<li>** [out :: myip] stopping port 9097</li>
<li>** [out :: myip] stopping port 9098</li>
<li>** [out :: myip] already started port 9096</li>
<li>** [out :: myip] already started port 9097</li>
<li>** [out :: myip] already started port 9098</li>
</ul></li>
<li>I check immediately on the server and find that Mongrel is still running, and the PID files are still present for the previous three instances. </li>
<li>A short time later (less than one minute), I find that Mongrel is no longer running, the PID files are gone, and it has failed to restart. </li>
<li>If I start mongrel on the server by hand, the app starts up just fine. </li>
</ol>
<p>It seems like 'mongrel_rails cluster::restart' isn't properly waiting for a full stop
before attempting a restart of the cluster. How do I diagnose and fix this issue?</p>
<p>EDIT: Here's the answer: </p>
<p>mongrel_cluster, in the "restart" task, simply does this: </p>
<pre><code> def run
stop
start
end
</code></pre>
<p>It doesn't do any waiting or checking to see that the process exited before invoking "start". This is <a href="http://rubyforge.org/tracker/index.php?func=detail&aid=19657&group_id=1336&atid=5291" rel="nofollow noreferrer">a known bug with an outstanding patch submitted</a>. I applied the patch to Mongrel Cluster and the problem disappeared. </p>
|
[
{
"answer_id": 156017,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 1,
"selected": false,
"text": "cap deploy:restart --debug --dry-run :runner nil :admin_runner cap deploy:restart"
},
{
"answer_id": 157964,
"author": "rwc9u",
"author_id": 7778,
"author_profile": "https://Stackoverflow.com/users/7778",
"pm_score": 3,
"selected": true,
"text": "# helps keep mongrel pid files clean\nset :mongrel_clean, true\n namespace :deploy do\n desc \"Restart the Mongrel processes on the app server.\"\n task :restart, :roles => :app do\n mongrel.cluster.stop\n sleep 2.5\n mongrel.cluster.start\n end\nend\n"
},
{
"answer_id": 257620,
"author": "chovy",
"author_id": 33522,
"author_profile": "https://Stackoverflow.com/users/33522",
"pm_score": 1,
"selected": false,
"text": "stop && start\n stop; start\n wait cluster_stop\nthen cluster_start\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13472/"
] |
155,243
|
<p>As a follow up to a <a href="https://stackoverflow.com/questions/151590/java-how-do-detect-a-remote-side-socket-close">recent question</a>, I wonder why it is impossible in Java, without attempting reading/writing on a TCP socket, to detect that the socket has been gracefully closed by the peer? This seems to be the case regardless of whether one uses the pre-NIO <code>Socket</code> or the NIO <code>SocketChannel</code>.</p>
<p>When a peer gracefully closes a TCP connection, the TCP stacks on both sides of the connection know about the fact. The server-side (the one that initiates the shutdown) ends up in state <code>FIN_WAIT2</code>, whereas the client-side (the one that does not explicitly respond to the shutdown) ends up in state <code>CLOSE_WAIT</code>. Why isn't there a method in <code>Socket</code> or <code>SocketChannel</code> that can query the TCP stack to see whether the underlying TCP connection has been terminated? Is it that the TCP stack doesn't provide such status information? Or is it a design decision to avoid a costly call into the kernel?</p>
<p>With the help of the users who have already posted some answers to this question, I think I see where the issue might be coming from. The side that doesn't explicitly close the connection ends up in TCP state <code>CLOSE_WAIT</code> meaning that the connection is in the process of shutting down and waits for the side to issue its own <code>CLOSE</code> operation. I suppose it's fair enough that <code>isConnected</code> returns <code>true</code> and <code>isClosed</code> returns <code>false</code>, but why isn't there something like <code>isClosing</code>?</p>
<p>Below are the test classes that use pre-NIO sockets. But identical results are obtained using NIO.</p>
<pre><code>import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args) throws Exception {
final ServerSocket ss = new ServerSocket(12345);
final Socket cs = ss.accept();
System.out.println("Accepted connection");
Thread.sleep(5000);
cs.close();
System.out.println("Closed connection");
ss.close();
Thread.sleep(100000);
}
}
import java.net.Socket;
public class MyClient {
public static void main(String[] args) throws Exception {
final Socket s = new Socket("localhost", 12345);
for (int i = 0; i < 10; i++) {
System.out.println("connected: " + s.isConnected() +
", closed: " + s.isClosed());
Thread.sleep(1000);
}
Thread.sleep(100000);
}
}
</code></pre>
<p>When the test client connects to the test server the output remains unchanged even after the server initiates the shutdown of the connection:</p>
<pre><code>connected: true, closed: false
connected: true, closed: false
...
</code></pre>
|
[
{
"answer_id": 157139,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 2,
"selected": false,
"text": "select(2)"
},
{
"answer_id": 157534,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 3,
"selected": false,
"text": "close() shutdownOutput() CLOSE_WAIT CLOSE_WAIT read/recv getsockopt() Socket isCloseWait()"
},
{
"answer_id": 476674,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 2,
"selected": false,
"text": "struct timeval tp; \nfd_set in; \nfd_set out; \nfd_set err; \n\nFD_ZERO (in); \nFD_ZERO (out); \nFD_ZERO (err); \n\nFD_SET(socket_handle, err); \n\ntp.tv_sec = 0; /* or however long you want to wait */ \ntp.tv_usec = 0; \nselect(socket_handle + 1, in, out, err, &tp); \n\nif (FD_ISSET(socket_handle, err) { \n /* handle closed socket */ \n} \n"
},
{
"answer_id": 9399617,
"author": "Matthieu",
"author_id": 1098603,
"author_profile": "https://Stackoverflow.com/users/1098603",
"pm_score": 5,
"selected": false,
"text": "shutdownOutput() Socket.close() Socket.getInputStream().read() < 0 InputStream read() close() InputStream Socket.close() InputStream OutputStream public void synchronizedClose(Socket sok) {\n InputStream is = sok.getInputStream();\n sok.shutdownOutput(); // Sends the 'FIN' on the network\n while (is.read() > 0) ; // \"read()\" returns '-1' when the 'FIN' is reached\n sok.close(); // or is.close(); Now we can close the Socket\n}\n while while"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16724/"
] |
155,246
|
<p>I have a test environment for a database that I want to reload with new data at the start of a testing cycle. I am not interested in rebuilding the entire database- just simply "re-setting" the data. </p>
<p>What is the best way to remove all the data from all the tables using TSQL? Are there system stored procedures, views, etc. that can be used? I do not want to manually create and maintain truncate table statements for each table- I would prefer it to be dynamic.</p>
|
[
{
"answer_id": 155270,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "tables sysobjects sp_execsql('truncate table ' + @table_name) iteration"
},
{
"answer_id": 155275,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 9,
"selected": true,
"text": "EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'\n"
},
{
"answer_id": 156813,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 9,
"selected": false,
"text": "-- disable all constraints\nEXEC sp_MSForEachTable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"\n\n-- delete data in all tables\nEXEC sp_MSForEachTable \"DELETE FROM ?\"\n\n-- enable all constraints\nexec sp_MSForEachTable \"ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\"\n EXEC sp_MSForEachTable \"DBCC CHECKIDENT ( '?', RESEED, 0)\"\n"
},
{
"answer_id": 12719464,
"author": "Chris KL",
"author_id": 58110,
"author_profile": "https://Stackoverflow.com/users/58110",
"pm_score": 6,
"selected": false,
"text": "SET QUOTED_IDENTIFIER ON;\nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? NOCHECK CONSTRAINT ALL' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? DISABLE TRIGGER ALL' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; DELETE FROM ?' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? CHECK CONSTRAINT ALL' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER TABLE ? ENABLE TRIGGER ALL' \nEXEC sp_MSforeachtable 'SET QUOTED_IDENTIFIER ON';\n\nIF NOT EXISTS (\n SELECT\n *\n FROM\n SYS.IDENTITY_COLUMNS\n JOIN SYS.TABLES ON SYS.IDENTITY_COLUMNS.Object_ID = SYS.TABLES.Object_ID\n WHERE\n SYS.TABLES.Object_ID = OBJECT_ID('?') AND SYS.IDENTITY_COLUMNS.Last_Value IS NULL\n)\nAND OBJECTPROPERTY( OBJECT_ID('?'), 'TableHasIdentity' ) = 1\n\n DBCC CHECKIDENT ('?', RESEED, 0) WITH NO_INFOMSGS;\n"
},
{
"answer_id": 18344855,
"author": "Chris Smith",
"author_id": 194872,
"author_profile": "https://Stackoverflow.com/users/194872",
"pm_score": 2,
"selected": false,
"text": "declare @LastObjectID int = 0\ndeclare @TableName nvarchar(100) = ''\nset @LastObjectID = (select top 1 [object_id] from sys.tables where [object_id] > @LastObjectID order by [object_id])\nwhile(@LastObjectID is not null)\nbegin\n set @TableName = (select top 1 [name] from sys.tables where [object_id] = @LastObjectID)\n\n if(@TableName not in ('Profiles', 'ClientDetails', 'Addresses', 'AgentDetails', 'ChainCodes', 'VendorDetails'))\n begin\n exec('truncate table [' + @TableName + ']')\n end \n\n set @LastObjectID = (select top 1 [object_id] from sys.tables where [object_id] > @LastObjectID order by [object_id])\nend\n"
},
{
"answer_id": 21463625,
"author": "Steve Hood",
"author_id": 2871082,
"author_profile": "https://Stackoverflow.com/users/2871082",
"pm_score": 1,
"selected": false,
"text": "/*\nCREATE TABLE _ScriptLog \n(\n ID Int NOT NULL Identity(1,1)\n , DateAdded DateTime2 NOT NULL DEFAULT GetDate()\n , Script NVarChar(4000) NOT NULL\n)\n\nCREATE UNIQUE CLUSTERED INDEX IX_ScriptLog_DateAdded_ID_U_C ON _ScriptLog\n(\n DateAdded\n , ID\n)\n\nCREATE TABLE _TruncateList\n(\n TableName SysName PRIMARY KEY\n)\n*/\nIF OBJECT_ID('TempDB..#DropFK') IS NOT NULL BEGIN\n DROP TABLE #DropFK\nEND\n\nIF OBJECT_ID('TempDB..#TruncateList') IS NOT NULL BEGIN\n DROP TABLE #TruncateList\nEND\n\nIF OBJECT_ID('TempDB..#CreateFK') IS NOT NULL BEGIN\n DROP TABLE #CreateFK\nEND\n\nSELECT Scripts = 'ALTER TABLE ' + '[' + OBJECT_NAME(f.parent_object_id)+ ']'+\n' DROP CONSTRAINT ' + '[' + f.name + ']'\nINTO #DropFK\nFROM .sys.foreign_keys AS f\nINNER JOIN .sys.foreign_key_columns AS fc\nON f.OBJECT_ID = fc.constraint_object_id\n\nSELECT TableName\nINTO #TruncateList\nFROM _TruncateList\n\nSELECT Scripts = 'ALTER TABLE ' + const.parent_obj + '\n ADD CONSTRAINT ' + const.const_name + ' FOREIGN KEY (\n ' + const.parent_col_csv + '\n ) REFERENCES ' + const.ref_obj + '(' + const.ref_col_csv + ')\n'\nINTO #CreateFK\nFROM (\n SELECT QUOTENAME(fk.NAME) AS [const_name]\n ,QUOTENAME(schParent.NAME) + '.' + QUOTENAME(OBJECT_name(fkc.parent_object_id)) AS [parent_obj]\n ,STUFF((\n SELECT ',' + QUOTENAME(COL_NAME(fcP.parent_object_id, fcp.parent_column_id))\n FROM sys.foreign_key_columns AS fcP\n WHERE fcp.constraint_object_id = fk.object_id\n FOR XML path('')\n ), 1, 1, '') AS [parent_col_csv]\n ,QUOTENAME(schRef.NAME) + '.' + QUOTENAME(OBJECT_NAME(fkc.referenced_object_id)) AS [ref_obj]\n ,STUFF((\n SELECT ',' + QUOTENAME(COL_NAME(fcR.referenced_object_id, fcR.referenced_column_id))\n FROM sys.foreign_key_columns AS fcR\n WHERE fcR.constraint_object_id = fk.object_id\n FOR XML path('')\n ), 1, 1, '') AS [ref_col_csv]\n FROM sys.foreign_key_columns AS fkc\n INNER JOIN sys.foreign_keys AS fk ON fk.object_id = fkc.constraint_object_id\n INNER JOIN sys.objects AS oParent ON oParent.object_id = fkc.parent_object_id\n INNER JOIN sys.schemas AS schParent ON schParent.schema_id = oParent.schema_id\n INNER JOIN sys.objects AS oRef ON oRef.object_id = fkc.referenced_object_id\n INNER JOIN sys.schemas AS schRef ON schRef.schema_id = oRef.schema_id\n GROUP BY fkc.parent_object_id\n ,fkc.referenced_object_id\n ,fk.NAME\n ,fk.object_id\n ,schParent.NAME\n ,schRef.NAME\n ) AS const\nORDER BY const.const_name\n\nINSERT INTO _ScriptLog (Script)\nSELECT Scripts\nFROM #CreateFK\n\nDECLARE @Cmd NVarChar(4000)\n , @TableName SysName\n\nWHILE 0 < (SELECT Count(1) FROM #DropFK) BEGIN\n SELECT TOP 1 @Cmd = Scripts \n FROM #DropFK\n\n EXEC (@Cmd)\n\n DELETE #DropFK WHERE Scripts = @Cmd\nEND\n\nWHILE 0 < (SELECT Count(1) FROM #TruncateList) BEGIN\n SELECT TOP 1 @Cmd = N'TRUNCATE TABLE ' + TableName\n , @TableName = TableName\n FROM #TruncateList\n\n EXEC (@Cmd)\n\n DELETE #TruncateList WHERE TableName = @TableName\nEND\n\nWHILE 0 < (SELECT Count(1) FROM #CreateFK) BEGIN\n SELECT TOP 1 @Cmd = Scripts \n FROM #CreateFK\n\n EXEC (@Cmd)\n\n DELETE #CreateFK WHERE Scripts = @Cmd\nEND\n"
},
{
"answer_id": 23136284,
"author": "Scott Allen",
"author_id": 1700309,
"author_profile": "https://Stackoverflow.com/users/1700309",
"pm_score": 2,
"selected": false,
"text": "DECLARE @myTempTable TABLE (tableName varchar(200))\nINSERT INTO @myTempTable(tableName) VALUES\n('TABLE_ONE'),\n('TABLE_TWO'),\n('TABLE_THREE')\n\n\n-- DROP FK Contraints\nSELECT 'alter table '+quotename(schema_name(ob.schema_id))+\n '.'+quotename(object_name(ob.object_id))+ ' drop constraint ' + quotename(fk.name) \n FROM sys.objects ob INNER JOIN sys.foreign_keys fk ON fk.parent_object_id = ob.object_id\n WHERE fk.referenced_object_id IN \n (\n SELECT so.object_id \n FROM sys.objects so JOIN sys.schemas sc\n ON so.schema_id = sc.schema_id\n WHERE so.name IN (SELECT * FROM @myTempTable) AND sc.name=N'dbo' AND type in (N'U'))\n\n\n -- CREATE FK Contraints\n SELECT 'ALTER TABLE [PIMSUser].[dbo].[' +cast(c.name as varchar(255)) + '] WITH NOCHECK ADD CONSTRAINT ['+ cast(f.name as varchar(255)) +'] FOREIGN KEY (['+ cast(fc.name as varchar(255)) +'])\n REFERENCES [PIMSUser].[dbo].['+ cast(p.name as varchar(255)) +'] (['+cast(rc.name as varchar(255))+'])'\nFROM sysobjects f\n INNER JOIN sys.sysobjects c ON f.parent_obj = c.id\n INNER JOIN sys.sysreferences r ON f.id = r.constid\n INNER JOIN sys.sysobjects p ON r.rkeyid = p.id\n INNER JOIN sys.syscolumns rc ON r.rkeyid = rc.id and r.rkey1 = rc.colid\n INNER JOIN sys.syscolumns fc ON r.fkeyid = fc.id and r.fkey1 = fc.colid\nWHERE \n f.type = 'F'\n AND\n cast(p.name as varchar(255)) IN (SELECT * FROM @myTempTable)\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
155,260
|
<p>I have been learning about the basics of C# but haven't come across a good explanation of what this is:</p>
<pre><code>var l = new List<string>();
</code></pre>
<p>I don't know what the <code><string></code> is doing or if it's the <code>List</code> that is doing the magic. I have also seen objects been thrown within the <code>< ></code> tags.</p>
<p>Can someone explain this to me with examples, please?</p>
|
[
{
"answer_id": 155280,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 1,
"selected": false,
"text": "int x = (int)myArrayList[4];\n int x = myList[4];\n"
},
{
"answer_id": 155286,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "List<int>\n"
},
{
"answer_id": 155296,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "ArrayList foos = new Arraylist();\nfoos.Add(\"Test\");\n foos.Add(\"Test\" as System.Object);\nstring s = foos[1] as String.\n ArrayList listOfStrings = new ArrayList();\nlistOfStrings.Add(1);\nlistOfStrings.Add(\"Test\");\n List<int> listOfIntegers = new List<int>();\nList<String> listOfStrings = new List<String>();\n\nlistOfIntegers.add(1);\n\n// Compile time error.\nlistOfIntegers.add(\"test\");\n public class Adder<T>\n{\n public T AddTwoThings(T t1, T t2)\n {\n return t1 + t2;\n }\n}\n\nAdder<String> stringAdder = new Adder<String>();\nConsole.Writeline(stringAdder.AddTwoThings(\"Test,\"123\"));\n\nAdder<int> intAdder = new Adder<int>();\nConsole.Writeline(intAdder.AddTwoThings(2,2));\n"
},
{
"answer_id": 155298,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "List listOfStrings = new List();\n listOfStrings.add(6); //Not a string\n List<string> listOfStrings = new List<string>();\nlistOfStrings.add(\"my name\"); //OK\nlistofStrings.add(6); //Throws a compiler error\n"
},
{
"answer_id": 155304,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 0,
"selected": false,
"text": "public class MyArray<T> {\n private T[] _list;\n\n public MyArray() : this.MyArray(10);\n public MyArray(int capacity)\n { _list = new T[capacity]; }\n\n T this[int index] {\n get { return _list[index]; }\n set { _list[index] = value; }\n }\n}\n MyArray<string> MyArray<bool>"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22459/"
] |
155,271
|
<p>Is there a way to hide the text limit line in netbeans 6.5?</p>
|
[
{
"answer_id": 1210584,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<entry javaType=\"java.lang.Boolean\" name=\"text-limit-line-visible\" xml:space=\"preserve\">\n<value><![CDATA[false]]></value></entry>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] |
155,279
|
<p>I have an AdvancedDataGrid that uses customer grouping of data. Not all of the groups will be at the same level in the hierarchy, and groups can contain both groups and members. We have a sort callback, but it's not being called except for groups at the leaf-most levels. See code below for an example -- expand all of the groups, then click the sort column on "date of birth" to get a reverse sort by date of birth. (Oddly, for some unfathomable reason, the first ascending sort works.)</p>
<p>We're not getting called for any of the data that's grouped at the same level as a group member.</p>
<p>How do I fix this?</p>
<p>Thanks.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white" >
<mx:Script>
<![CDATA[
import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
import mx.collections.HierarchicalData;
import mx.utils.ObjectUtil;
private var arrData : Array = [
{ name: "User A", dob: "04/14/1980" },
{ name: "User B", dob: "01/02/1975" },
{ name: "Group A", children: [
{ name: "User E", dob: "09/13/1972" },
{ name: "User F", dob: "11/22/1993" }
]
},
{ name: "Group B", children: [
{ name: "Group B1", children: [
{ name: "User I", dob: "01/23/1984" },
{ name: "User J", dob: "11/10/1948" }
]
},
{ name: "User G", dob: "04/09/1989" },
{ name: "User H", dob: "06/20/1963" }
]
},
{ name: "User C", dob: "12/30/1977" },
{ name: "User D", dob: "10/27/1968" }
];
private function date_sortCompareFunc(itemA:Object, itemB:Object):int
{
if ( itemA.hasOwnProperty("dob") && itemB.hasOwnProperty("dob"))
{
var dateA:Date = new Date(Date.parse(itemA.dob));
var dateB:Date = new Date(Date.parse(itemB.dob));
return ObjectUtil.dateCompare(dateA, dateB);
}
else if ( itemA.hasOwnProperty("dob"))
{
return 1;
}
else if (itemB.hasOwnProperty("dob"))
{
return -1;
}
return ObjectUtil.stringCompare(itemA.name, itemB.name);
}
private function date_dataTipFunc(item:Object):String
{
if (item.hasOwnProperty("dob"))
{
return dateFormatter.format(item.dob);
}
return "";
}
private function label_dob(item:Object, col:AdvancedDataGridColumn):String
{
var dob:String="";
if(item.hasOwnProperty("dob"))
{
dob=item.dob;
}
return dob;
}
]]>
</mx:Script>
<mx:DateFormatter id="dateFormatter" formatString="MMMM D, YYYY" />
<mx:AdvancedDataGrid id="adgTest" dataProvider="{new HierarchicalData(this.arrData)}" designViewDataType="tree" width="746" height="400">
<mx:columns>
<mx:AdvancedDataGridColumn headerText="Name" dataField="name"/>
<mx:AdvancedDataGridColumn dataField="dob" headerText="Date of birth"
labelFunction="label_dob"
sortCompareFunction="date_sortCompareFunc"
showDataTips="true"
dataTipFunction="date_dataTipFunc" />
</mx:columns>
</mx:AdvancedDataGrid>
</mx:Application>
</code></pre>
|
[
{
"answer_id": 156283,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 0,
"selected": false,
"text": "dob:\"01/01/1970\""
},
{
"answer_id": 1406772,
"author": "Invalid Character",
"author_id": 9610,
"author_profile": "https://Stackoverflow.com/users/9610",
"pm_score": 2,
"selected": false,
"text": " public function dateCellLabel(item:Object, column:AdvancedDataGridColumn):String\n {\n var date:String = item[column.dataField];\n\n if (date==\"1/1/1770\") \n return null; \n else\n return date;\n }\n"
},
{
"answer_id": 5328784,
"author": "Darren Bishop",
"author_id": 133330,
"author_profile": "https://Stackoverflow.com/users/133330",
"pm_score": 0,
"selected": false,
"text": "dataField <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" \n layout=\"vertical\" \n verticalAlign=\"middle\" \n backgroundColor=\"white\" >\n <mx:Script>\n <![CDATA[\n import mx.collections.HierarchicalData;\n import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;\n import mx.utils.ObjectUtil;\n\n private var arrData : Array = [\n { name: \"User A\", dob: \"04/14/1980\" },\n { name: \"User B\", dob: \"01/02/1975\" },\n { name: \"Group A\", dob: null, children: [\n { name: \"User E\", dob: \"09/13/1972\" },\n { name: \"User F\", dob: \"11/22/1993\" }\n ]\n },\n { name: \"Group B\", dob: null, children: [\n { name: \"Group B1\", dob: null, children: [\n { name: \"User I\", dob: \"01/23/1984\" },\n { name: \"User J\", dob: \"11/10/1948\" }\n ]\n },\n { name: \"User G\", dob: \"04/09/1989\" },\n { name: \"User H\", dob: \"06/20/1963\" }\n ]\n },\n { name: \"User C\", dob: \"12/30/1977\" },\n { name: \"User D\", dob: \"10/27/1968\" }\n ];\n\n private function dob_sort(itemA:Object, itemB:Object):int {\n var dateA:Date = itemA.dob ? new Date(itemA.dob) : null;\n var dateB:Date = itemB.dob ? new Date(itemB.dob) : null;\n return ObjectUtil.dateCompare(dateA, dateB);\n }\n\n private function dob_dataTip(item:Object):String {\n if (!item.hasOwnProperty('children') && item.hasOwnProperty(\"dob\")) {\n return dateFormatter.format(item.dob);\n }\n return null;\n }\n\n private function dob_label(item:Object, col:AdvancedDataGridColumn):String {\n if(!item.hasOwnProperty('children') && item.hasOwnProperty(\"dob\")) {\n return item.dob;\n }\n return null;\n }\n ]]>\n </mx:Script>\n\n <mx:DateFormatter id=\"dateFormatter\" formatString=\"MMMM D, YYYY\" />\n\n <mx:AdvancedDataGrid id=\"adgTest\" dataProvider=\"{new HierarchicalData(arrData)}\" designViewDataType=\"tree\" width=\"746\" height=\"400\">\n <mx:columns>\n <mx:AdvancedDataGridColumn headerText=\"Name\" dataField=\"name\"/>\n <mx:AdvancedDataGridColumn headerText=\"Date of birth\" dataField=\"dob\"\n labelFunction=\"dob_label\" \n dataTipFunction=\"dob_dataTip\"\n sortCompareFunction=\"dob_sort\"\n showDataTips=\"true\" />\n\n </mx:columns>\n </mx:AdvancedDataGrid>\n</mx:Application>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22809/"
] |
155,291
|
<p>I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything.</p>
<p>I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances.</p>
|
[
{
"answer_id": 155301,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 9,
"selected": false,
"text": "READONLY disabled // user allowed change\nif($user_allowed_edit)\n{\n echo '<input type=\"checkbox\" name=\"my_check\"> Check value';\n}\nelse\n{\n // Not allowed change - submit value..\n echo '<input type=\"hidden\" name=\"my_check\" value=\"1\" />';\n // .. and show user the value being submitted\n echo '<input type=\"checkbox\" disabled readonly> Check value';\n}\n"
},
{
"answer_id": 155324,
"author": "powtac",
"author_id": 22470,
"author_profile": "https://Stackoverflow.com/users/22470",
"pm_score": 9,
"selected": false,
"text": "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">\n disabled=\"disabled\" <input name=\"myvalue\" type=\"checkbox\" disabled=\"disabled\" checked=\"checked\"/>\n<input name=\"myvalue\" type=\"hidden\" value=\"true\"/>\n"
},
{
"answer_id": 155337,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": false,
"text": "var form = document.getElementById('yourform');\nform.onSubmit = function () \n{ \n var formElems = document.getElementsByTagName('INPUT');\n for (var i = 0; i , formElems.length; i++)\n { \n if (formElems[i].type == 'checkbox')\n { \n formElems[i].disabled = false;\n }\n }\n}\n"
},
{
"answer_id": 155349,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 6,
"selected": false,
"text": "<input type=\"checkbox\" onclick=\"this.checked=!this.checked;\">\n"
},
{
"answer_id": 734223,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "public function MakeDummyReadonlyCheckbox(i_strName, i_strChecked_TorF)\n\n dim strThisCheckedValue\n\n if (i_strChecked_TorF = \"T\") then\n strThisCheckedValue = \" checked \"\n i_strChecked_TorF = \"on\"\n else\n strThisCheckedValue = \"\"\n i_strChecked_TorF = \"\"\n end if\n\n MakeDummyReadonlyCheckbox = \"<input type='hidden' id='\" & i_strName & \"' name='\" & i_strName & \"' \" & _\n \"value='\" & i_strChecked_TorF & \"'>\" & _\n \"<input type='checkbox' disabled id='\" & i_strName & \"Dummy' name='\" & i_strName & \"Dummy' \" & _\n strThisCheckedValue & \">\" \nend function\n\npublic function GetCheckbox(i_objCheckbox)\n\n select case trim(i_objCheckbox)\n\n case \"\"\n GetCheckbox = \"F\"\n\n case else\n GetCheckbox = \"T\"\n\n end select\n\nend function\n strDataValue = GetCheckbox(Request.Form(\"chkTest\"))\n response.write MakeDummyReadonlyCheckbox(\"chkTest\", strDataValue)\n"
},
{
"answer_id": 1273173,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<input name=\"isActive\" id=\"isActive\" type=\"checkbox\" value=\"1\" checked=\"checked\" onclick=\"return false\"/>\n"
},
{
"answer_id": 2775421,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": -1,
"selected": false,
"text": "onclick=\"document.forms['form1'].submit(); $('#filters input').each(function() {this.disabled = true});\""
},
{
"answer_id": 3027466,
"author": "Jan",
"author_id": 51795,
"author_profile": "https://Stackoverflow.com/users/51795",
"pm_score": 5,
"selected": false,
"text": "<input type=\"checkbox\" readonly=\"readonly\" name=\"...\" />\n $(':checkbox[readonly]').click(function(){\n return false;\n });\n"
},
{
"answer_id": 3292768,
"author": "Sandman",
"author_id": 397109,
"author_profile": "https://Stackoverflow.com/users/397109",
"pm_score": 3,
"selected": false,
"text": "onclick=\"javascript: return false;\"\n"
},
{
"answer_id": 4069837,
"author": "user493687",
"author_id": 493687,
"author_profile": "https://Stackoverflow.com/users/493687",
"pm_score": -1,
"selected": false,
"text": "onclick=\"javascript:{this.checked = this.defaultChecked;}\"\n"
},
{
"answer_id": 6550080,
"author": "fdaines",
"author_id": 661143,
"author_profile": "https://Stackoverflow.com/users/661143",
"pm_score": -1,
"selected": false,
"text": "<input type=\"checkbox\" disabled checked>text\n <input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\" />text <!-- if yu have a checked box-->\n<input type=\"checkbox\" disabled=\"disabled\" />text <!-- if you have a unchecked box -->\n"
},
{
"answer_id": 6905050,
"author": "Yanni",
"author_id": 689782,
"author_profile": "https://Stackoverflow.com/users/689782",
"pm_score": 9,
"selected": false,
"text": "<input type=\"checkbox\" onclick=\"return false;\"/>\n"
},
{
"answer_id": 9172619,
"author": "Devner",
"author_id": 212889,
"author_profile": "https://Stackoverflow.com/users/212889",
"pm_score": -1,
"selected": false,
"text": "<input type=\"checkbox\" readonly=\"readonly\" onclick=\"this.checked =! this.checked;\">\n <input type=\"checkbox\" readonly=\"readonly\" disabled=\"disabled\" onclick=\"this.checked =! this.checked;\">\n"
},
{
"answer_id": 10327995,
"author": "Rinto George",
"author_id": 510754,
"author_profile": "https://Stackoverflow.com/users/510754",
"pm_score": 3,
"selected": false,
"text": "<input type=\"checkbox\" onclick=\"return false\" />"
},
{
"answer_id": 10377324,
"author": "Kamalam",
"author_id": 1235160,
"author_profile": "https://Stackoverflow.com/users/1235160",
"pm_score": -1,
"selected": false,
"text": "<input type=\"checkbox\" name=\"Name\" checked onchange='this.checked = true;'>\n"
},
{
"answer_id": 10832156,
"author": "Osama Javed",
"author_id": 832000,
"author_profile": "https://Stackoverflow.com/users/832000",
"pm_score": 5,
"selected": false,
"text": "<input type=checkbox onclick=\"return false;\" onkeydown=\"return false;\" />\n"
},
{
"answer_id": 11678624,
"author": "sksallaj",
"author_id": 1449587,
"author_profile": "https://Stackoverflow.com/users/1449587",
"pm_score": 2,
"selected": false,
"text": "<form id=\"aform\" name=\"aform\" method=\"POST\">\n <input name=\"chkBox_1\" type=\"checkbox\" checked value=\"1\" disabled=\"disabled\" />\n <input id=\"submitBttn\" type=\"button\" value=\"Submit\" onClick='return submitPage();'>\n</form>\n $(document).ready(function(){\n //first option, you don't need the disabled attribute, this will prevent\n //the user from changing the checkbox values\n $(\"input[name^='chkBox_1']\").click(function(e){\n e.preventDefault();\n });\n\n //second option, keep the disabled attribute, and disable it upon submit\n $(\"#submitBttn\").click(function(){\n $(\"input[name^='chkBox_1']\").attr(\"disabled\",false);\n $(\"#aform\").submit();\n });\n\n});\n"
},
{
"answer_id": 12971018,
"author": "summsel",
"author_id": 1758805,
"author_profile": "https://Stackoverflow.com/users/1758805",
"pm_score": 6,
"selected": false,
"text": "<!-- field that holds the data -->\n<input type=\"hidden\" name=\"my_name\" value=\"1\" /> \n<!-- visual dummy for the user -->\n<input type=\"checkbox\" name=\"my_name_visual_dummy\" value=\"1\" checked=\"checked\" disabled=\"disabled\" />\n"
},
{
"answer_id": 13650019,
"author": "Derrick",
"author_id": 561759,
"author_profile": "https://Stackoverflow.com/users/561759",
"pm_score": 2,
"selected": false,
"text": "<script>\n $(function () {\n $('.readonly input').attr('readonly', 'readonly');\n $('.readonly textarea').attr('readonly', 'readonly');\n $('.readonly input:checkbox').click(function(){return false;});\n $('.readonly input:checkbox').keydown(function () { return false; });\n });\n</script>\n <div class=\"editor-field readonly\">\n <input id=\"Date\" name=\"Date\" type=\"datetime\" value=\"11/29/2012 4:01:06 PM\" />\n</div>\n<fieldset class=\"flags-editor readonly\">\n <input checked=\"checked\" class=\"flags-editor\" id=\"Flag1\" name=\"Flags\" type=\"checkbox\" value=\"Flag1\" />\n</fieldset>\n"
},
{
"answer_id": 14588872,
"author": "Richard Maxwell",
"author_id": 902960,
"author_profile": "https://Stackoverflow.com/users/902960",
"pm_score": -1,
"selected": false,
"text": "@if (true)\n{\n @Html.HiddenFor(m => m)\n @(ViewData.Model ? Html.Raw(\"Yes\") : Html.Raw(\"No\"))\n} \nelse\n{ \n @Html.CheckBoxFor(m => m)\n}\n"
},
{
"answer_id": 16693321,
"author": "jortsc",
"author_id": 1913266,
"author_profile": "https://Stackoverflow.com/users/1913266",
"pm_score": 0,
"selected": false,
"text": "$('your selector').click(function(evt){evt.preventDefault()});\n"
},
{
"answer_id": 17796857,
"author": "frag",
"author_id": 451232,
"author_profile": "https://Stackoverflow.com/users/451232",
"pm_score": 2,
"selected": false,
"text": "<input type=\"radio\" name=\"alwaysOn\" onchange=\"this.checked=true\" checked=\"checked\">\n<input type=\"radio\" name=\"alwaysOff\" onchange=\"this.checked=false\" >\n"
},
{
"answer_id": 22821064,
"author": "Gotham's Reckoning",
"author_id": 2673410,
"author_profile": "https://Stackoverflow.com/users/2673410",
"pm_score": 4,
"selected": false,
"text": "$(document).ready(function() {\n $(\":checkbox\").bind(\"click\", false);\n});\n"
},
{
"answer_id": 23885043,
"author": "Md Rahman",
"author_id": 2791039,
"author_profile": "https://Stackoverflow.com/users/2791039",
"pm_score": -1,
"selected": false,
"text": "<input name=\"testName\" type=\"checkbox\" disabled>\n"
},
{
"answer_id": 24750387,
"author": "brad",
"author_id": 1823390,
"author_profile": "https://Stackoverflow.com/users/1823390",
"pm_score": -1,
"selected": false,
"text": "<div id='checkbox_wrap'>\n <div class='click_block'></div>\n <input type='checkbox' /> \n</div>\n #checkbox_wrap{\n height:10px;\n width:10px;\n }\n .click_block{\n height: 10px;\n width: 10px;\n position: absolute;\n z-index: 100;\n}\n"
},
{
"answer_id": 26019627,
"author": "bowlturner",
"author_id": 3825871,
"author_profile": "https://Stackoverflow.com/users/3825871",
"pm_score": 1,
"selected": false,
"text": " <div class=\"form-group\">\n @Html.LabelFor(model => model.Carrier.Exists, new { @class = \"control-label col-md-2\" })\n <div class=\"col-md-10\">\n @Html.HiddenFor(model => model.Carrier.Exists)\n @Html.CheckBoxFor(model => model.Carrier.Exists, new { @disabled = \"disabled\" })\n @Html.ValidationMessageFor(model => model.Carrier.Exists)\n </div>\n </div>\n"
},
{
"answer_id": 27324260,
"author": "David N. Jafferian",
"author_id": 1590397,
"author_profile": "https://Stackoverflow.com/users/1590397",
"pm_score": 2,
"selected": false,
"text": "if ($checked && $disabled)\n echo '<input type=\"hidden\" name=\"my_name\" value=\"1\" />';\necho '<input type=\"checkbox\" name=\"my_name\" value=\"1\" ',\n $checked ? 'checked=\"checked\" ' : '',\n $disabled ? 'disabled=\"disabled\" ' : '', '/>';\n"
},
{
"answer_id": 48861270,
"author": "Kavi",
"author_id": 2771583,
"author_profile": "https://Stackoverflow.com/users/2771583",
"pm_score": -1,
"selected": false,
"text": "$(\"#txtname\").prop('readonly', false);\n"
},
{
"answer_id": 52288861,
"author": "Timo Huovinen",
"author_id": 175071,
"author_profile": "https://Stackoverflow.com/users/175071",
"pm_score": 2,
"selected": false,
"text": "jQuery(document).on('click', function(e){\n // check for type, avoid selecting the element for performance\n if(e.target.type == 'checkbox') {\n var el = jQuery(e.target);\n if(el.prop('readonly')) {\n // prevent it from changing state\n e.preventDefault();\n }\n }\n}); input[type=checkbox][readonly] {\n cursor: not-allowed;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<label><input type=\"checkbox\" checked readonly> I'm readonly!</label>"
},
{
"answer_id": 53953323,
"author": "Nirbhay Rana",
"author_id": 5358054,
"author_profile": "https://Stackoverflow.com/users/5358054",
"pm_score": 0,
"selected": false,
"text": "<input type=\"checkbox\" name=\"email\" disabled>\n"
},
{
"answer_id": 54182054,
"author": "Daniel Ribeiro",
"author_id": 2175874,
"author_profile": "https://Stackoverflow.com/users/2175874",
"pm_score": 2,
"selected": false,
"text": "$(':checkbox').click(function () {\n if (typeof ($(this).attr('readonly')) != \"undefined\") {\n return false;\n }\n});\n"
},
{
"answer_id": 55009355,
"author": "Qwertiy",
"author_id": 4928642,
"author_profile": "https://Stackoverflow.com/users/4928642",
"pm_score": 3,
"selected": false,
"text": "pointer-events: none -1 label input[type=\"checkbox\"][readonly] {\n pointer-events: none !important;\n}\n\ntd {\n min-width: 5em;\n text-align: center;\n}\n\ntd:last-child {\n text-align: left;\n} <table>\n <tr>\n <th>usual\n <th>readonly\n <th>disabled\n </tr><tr>\n <td><input type=checkbox />\n <td><input type=checkbox readonly tabindex=-1 />\n <td><input type=checkbox disabled />\n <td>works\n </tr><tr>\n <td><input type=checkbox checked />\n <td><input type=checkbox readonly checked tabindex=-1 />\n <td><input type=checkbox disabled checked />\n <td>also works\n </tr><tr>\n <td><label><input type=checkbox checked /></label>\n <td><label><input type=checkbox readonly checked tabindex=-1 /></label>\n <td><label><input type=checkbox disabled checked /></label>\n <td>broken - don't use label tag\n </tr>\n</table>"
},
{
"answer_id": 56304217,
"author": "gordie",
"author_id": 782013,
"author_profile": "https://Stackoverflow.com/users/782013",
"pm_score": 5,
"selected": false,
"text": "<input type=\"checkbox\" readonly>\n input[type='checkbox'][readonly]{\n pointer-events: none;\n}\n input[type='checkbox']:read-only{ /*not working*/\n pointer-events: none;\n}\n"
},
{
"answer_id": 56322578,
"author": "Patanjali",
"author_id": 4188092,
"author_profile": "https://Stackoverflow.com/users/4188092",
"pm_score": 5,
"selected": false,
"text": "disabled yes false readonly <input type=\"checkbox\" checked=\"checked\" disabled=\"disabled\" />\n<input type=\"hidden\" name=\"fieldname\" value=\"fieldvalue\" /> <input type=\"checkbox\" disabled=\"disabled\" /> Status: none Status: implemented <p>Status: Implemented<input type=\"hidden\" name=\"status\" value=\"implemented\" /></p>"
},
{
"answer_id": 57916318,
"author": "little_birdie",
"author_id": 2945815,
"author_profile": "https://Stackoverflow.com/users/2945815",
"pm_score": 4,
"selected": false,
"text": "$('input[type=\"checkbox\"]').on('click keyup keypress keydown', function (event) {\n if($(this).is('[readonly]')) { return false; }\n});\n"
},
{
"answer_id": 65436265,
"author": "Tayyeb",
"author_id": 9950751,
"author_profile": "https://Stackoverflow.com/users/9950751",
"pm_score": -1,
"selected": false,
"text": " <input id=\"abc\" name=\"abc\" type=\"checkbox\" @(Model.IsEnabled ? \"checked=checked onclick=this.checked=!this.checked;\" : string.Empty) >\n"
},
{
"answer_id": 66783703,
"author": "groovyDynamics",
"author_id": 6493171,
"author_profile": "https://Stackoverflow.com/users/6493171",
"pm_score": 2,
"selected": false,
"text": "readonly <input type='checkbox'> $('form').submit(function(e) {\n $('input[type=\"checkbox\"]:disabled').each(function(e) {\n $(this).removeAttr('disabled');\n })\n});\n"
},
{
"answer_id": 71119242,
"author": "vincent salomon",
"author_id": 18183749,
"author_profile": "https://Stackoverflow.com/users/18183749",
"pm_score": 0,
"selected": false,
"text": " addReadOnlyToFormElements = function (idElement) {\n \n // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items\n $('#' + idElement + ' input[type=\"checkbox\"]:not(:checked)').prop('disabled',true); \n \n // and, on the selected ones, to disable mouse/keyoard events and mimic readOnly appearance\n $('#' + idElement + ' input[type=\"checkbox\"]:checked').prop('tabindex','-1').css('pointer-events','none').css('opacity','0.5');\n }\n removeReadOnlyFromFormElements = function (idElement) {\n\n // Remove the disabled attribut on non-selected\n $('#' + idElement + ' input[type=\"checkbox\"]:not(:checked)').prop('disabled',false);\n\n // Restore mouse/keyboard events and remove readOnly appearance on selected ones\n $('#' + idElement + ' input[type=\"checkbox\"]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');\n}\n"
},
{
"answer_id": 72115101,
"author": "Rodolfo Jorge Nemer Nogueira",
"author_id": 1102037,
"author_profile": "https://Stackoverflow.com/users/1102037",
"pm_score": 2,
"selected": false,
"text": "<input type=\"checkbox\" onclick=\"return false\">\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
155,303
|
<p>How do I go from this string: "ThisIsMyCapsDelimitedString"</p>
<p>...to this string: "This Is My Caps Delimited String"</p>
<p>Fewest lines of code in VB.net is preferred but C# is also welcome.</p>
<p>Cheers!</p>
|
[
{
"answer_id": 155331,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 0,
"selected": false,
"text": "string myString = \"ThisIsMyCapsDelimitedString\";\n\nfor (int i = 1; i < myString.Length; i++)\n{\n if (myString[i].ToString().ToUpper() == myString[i].ToString())\n {\n myString = myString.Insert(i, \" \");\n i++;\n }\n}\n"
},
{
"answer_id": 155336,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 4,
"selected": false,
"text": "Dim s As String = RegularExpressions.Regex.Replace(\"ThisIsMyCapsDelimitedString\", \"([A-Z])\", \" $1\")\n"
},
{
"answer_id": 155338,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "string s = \"ThisIsMyCapsDelimitedString\";\nstring t = Regex.Replace(s, \"([A-Z])\", \" $1\").Substring(1);\n"
},
{
"answer_id": 155340,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 5,
"selected": false,
"text": "Regex.Replace(\"ThisIsMyCapsDelimitedString\", \"(\\\\B[A-Z])\", \" $1\")\n"
},
{
"answer_id": 155350,
"author": "Geoff",
"author_id": 10427,
"author_profile": "https://Stackoverflow.com/users/10427",
"pm_score": 1,
"selected": false,
"text": "s = \"ThisIsMyCapsDelimitedString\"\nsplit = Regex.Replace(s, \"[A-Z0-9]\", \" $&\");\n"
},
{
"answer_id": 155486,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 4,
"selected": false,
"text": "public static class CamelSpaceExtensions\n{\n public static string SpaceCamelCase(this String input)\n {\n return new string(Enumerable.Concat(\n input.Take(1), // No space before initial cap\n InsertSpacesBeforeCaps(input.Skip(1))\n ).ToArray());\n }\n\n private static IEnumerable<char> InsertSpacesBeforeCaps(IEnumerable<char> input)\n {\n foreach (char c in input)\n {\n if (char.IsUpper(c)) \n { \n yield return ' '; \n }\n\n yield return c;\n }\n }\n}\n"
},
{
"answer_id": 155487,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 9,
"selected": true,
"text": "/([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g\n \"SimpleHTTPServer\" => [\"Simple\", \"HTTP\", \"Server\"]\n\"camelCase\" => [\"camel\", \"Case\"]\n Regex.Replace(s, \"([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))\", \"$1 \")\n /([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/g\n\nRegex.Replace(s,\"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))\",\"$1 \")\n"
},
{
"answer_id": 156029,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "public string FromCamelCase(string camel)\n{ // omitted checking camel for null\n StringBuilder sb = new StringBuilder();\n int upperCaseRun = 0;\n foreach (char c in camel)\n { // append a space only if we're not at the start\n // and we're not already in an all caps string.\n if (char.IsUpper(c))\n {\n if (upperCaseRun == 0 && sb.Length != 0)\n {\n sb.Append(' ');\n }\n upperCaseRun++;\n }\n else if( char.IsLower(c) )\n {\n if (upperCaseRun > 1) //The first new word will also be capitalized.\n {\n sb.Insert(sb.Length - 1, ' ');\n }\n upperCaseRun = 0;\n }\n else\n {\n upperCaseRun = 0;\n }\n sb.Append(c);\n }\n\n return sb.ToString();\n}\n"
},
{
"answer_id": 291870,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 4,
"selected": false,
"text": "Regex.Replace(s, \"([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))\", \"$1 \")\n"
},
{
"answer_id": 25479858,
"author": "Erxin",
"author_id": 1602830,
"author_profile": "https://Stackoverflow.com/users/1602830",
"pm_score": 0,
"selected": false,
"text": "\"([A-Z]*[^A-Z]*)\"\n Regex.Replace(\"AbcDefGH123Weh\", \"([A-Z]*[^A-Z]*)\", \"$1 \");\nAbc Def GH123 Weh \n\nRegex.Replace(\"camelCase\", \"([A-Z]*[^A-Z]*)\", \"$1 \");\ncamel Case \n"
},
{
"answer_id": 26876094,
"author": "Dan Malcolm",
"author_id": 146280,
"author_profile": "https://Stackoverflow.com/users/146280",
"pm_score": 3,
"selected": false,
"text": "Regex.Replace(value, @\"(?<!^)((?<!\\d)\\d|(?(?<=[A-Z])[A-Z](?=[a-z])|[A-Z]))\", \" $1\")\n using System.Text.RegularExpressions;\n\nnamespace Demo\n{\n public class IntercappedStringHelper\n {\n private static readonly Regex SeparatorRegex;\n\n static IntercappedStringHelper()\n {\n const string pattern = @\"\n (?<!^) # Not start\n (\n # Digit, not preceded by another digit\n (?<!\\d)\\d \n |\n # Upper-case letter, followed by lower-case letter if\n # preceded by another upper-case letter, e.g. 'G' in HTMLGuide\n (?(?<=[A-Z])[A-Z](?=[a-z])|[A-Z])\n )\";\n\n var options = RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled;\n\n SeparatorRegex = new Regex(pattern, options);\n }\n\n public static string SeparateWords(string value, string separator = \" \")\n {\n return SeparatorRegex.Replace(value, separator + \"$1\");\n }\n }\n}\n [Theory]\n[InlineData(\"PurchaseOrders\", \"Purchase-Orders\")]\n[InlineData(\"purchaseOrders\", \"purchase-Orders\")]\n[InlineData(\"2Unlimited\", \"2-Unlimited\")]\n[InlineData(\"The2Unlimited\", \"The-2-Unlimited\")]\n[InlineData(\"Unlimited2\", \"Unlimited-2\")]\n[InlineData(\"222Unlimited\", \"222-Unlimited\")]\n[InlineData(\"The222Unlimited\", \"The-222-Unlimited\")]\n[InlineData(\"Unlimited222\", \"Unlimited-222\")]\n[InlineData(\"ATeam\", \"A-Team\")]\n[InlineData(\"TheATeam\", \"The-A-Team\")]\n[InlineData(\"TeamA\", \"Team-A\")]\n[InlineData(\"HTMLGuide\", \"HTML-Guide\")]\n[InlineData(\"TheHTMLGuide\", \"The-HTML-Guide\")]\n[InlineData(\"TheGuideToHTML\", \"The-Guide-To-HTML\")]\n[InlineData(\"HTMLGuide5\", \"HTML-Guide-5\")]\n[InlineData(\"TheHTML5Guide\", \"The-HTML-5-Guide\")]\n[InlineData(\"TheGuideToHTML5\", \"The-Guide-To-HTML-5\")]\n[InlineData(\"TheUKAllStars\", \"The-UK-All-Stars\")]\n[InlineData(\"AllStarsUK\", \"All-Stars-UK\")]\n[InlineData(\"UKAllStars\", \"UK-All-Stars\")]\n"
},
{
"answer_id": 31796173,
"author": "Brantley Blanchard",
"author_id": 1191709,
"author_profile": "https://Stackoverflow.com/users/1191709",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n public static void Main()\n {\n var examples = new List<string> { \n \"THEQuickBrownFox\",\n \"theQUICKBrownFox\",\n \"TheQuickBrownFOX\",\n \"TheQuickBrownFox\",\n \"the_quick_brown_fox\",\n \"theFOX\",\n \"FOX\",\n \"QUICK\"\n };\n\n foreach (var example in examples)\n {\n Console.WriteLine(ToTitleCase(example));\n }\n }\n\n private static string ToTitleCase(string example)\n {\n var fromSnakeCase = example.Replace(\"_\", \" \");\n var lowerToUpper = Regex.Replace(fromSnakeCase, @\"(\\p{Ll})(\\p{Lu})\", \"$1 $2\");\n var sentenceCase = Regex.Replace(lowerToUpper, @\"(\\p{Lu}+)(\\p{Lu}\\p{Ll})\", \"$1 $2\");\n return new CultureInfo(\"en-US\", false).TextInfo.ToTitleCase(sentenceCase);\n }\n}\n THE Quick Brown Fox\nThe QUICK Brown Fox\nThe Quick Brown FOX\nThe Quick Brown Fox\nThe Quick Brown Fox\nThe FOX\nFOX\nQUICK\n"
},
{
"answer_id": 37231964,
"author": "shinzou",
"author_id": 4279201,
"author_profile": "https://Stackoverflow.com/users/4279201",
"pm_score": 0,
"selected": false,
"text": " private static StringBuilder camelCaseToRegular(string i_String)\n {\n StringBuilder output = new StringBuilder();\n int i = 0;\n foreach (char character in i_String)\n {\n if (character <= 'Z' && character >= 'A' && i > 0)\n {\n output.Append(\" \");\n }\n output.Append(character);\n i++;\n }\n return output;\n }\n"
},
{
"answer_id": 43970785,
"author": "Slai",
"author_id": 1383168,
"author_profile": "https://Stackoverflow.com/users/1383168",
"pm_score": 0,
"selected": false,
"text": "(?<=\\P{Lu})(?=\\p{Lu}) Dim s = Regex.Replace(\"CorrectHorseBatteryStaple\", \"(?<=\\P{Lu})(?=\\p{Lu})\", \" \")\n"
},
{
"answer_id": 46567461,
"author": "Zar Shardan",
"author_id": 913845,
"author_profile": "https://Stackoverflow.com/users/913845",
"pm_score": 2,
"selected": false,
"text": " public static string CamelCaseToSpaceSeparated(this string str)\n {\n if (string.IsNullOrEmpty(str))\n {\n return str;\n }\n\n var res = new StringBuilder();\n\n res.Append(str[0]);\n for (var i = 1; i < str.Length; i++)\n {\n if (char.IsUpper(str[i]))\n {\n res.Append(' ');\n }\n res.Append(str[i]);\n\n }\n return res.ToString();\n }\n"
},
{
"answer_id": 48185710,
"author": "Patrick from NDepend team",
"author_id": 27194,
"author_profile": "https://Stackoverflow.com/users/27194",
"pm_score": 0,
"selected": false,
"text": " /// <summary>\n /// Get the words in a code <paramref name=\"identifier\"/>.\n /// </summary>\n /// <param name=\"identifier\">The code <paramref name=\"identifier\"/></param> to extract words from.\n public static string[] GetWords(this string identifier) {\n Contract.Ensures(Contract.Result<string[]>() != null, \"returned array of string is not null but can be empty\");\n if (identifier == null) { return new string[0]; }\n if (identifier.Length == 0) { return new string[0]; }\n\n const int MIN_WORD_LENGTH = 2; // Ignore one letter or one digit words\n\n var length = identifier.Length;\n var list = new List<string>(1 + length/2); // Set capacity, not possible more words since we discard one char words\n var sb = new StringBuilder();\n CharKind cKindCurrent = GetCharKind(identifier[0]); // length is not zero here\n CharKind cKindNext = length == 1 ? CharKind.End : GetCharKind(identifier[1]);\n\n for (var i = 0; i < length; i++) {\n var c = identifier[i];\n CharKind cKindNextNext = (i >= length - 2) ? CharKind.End : GetCharKind(identifier[i + 2]);\n\n // Process cKindCurrent\n switch (cKindCurrent) {\n case CharKind.Digit:\n case CharKind.LowerCaseLetter:\n sb.Append(c); // Append digit or lowerCaseLetter to sb\n if (cKindNext == CharKind.UpperCaseLetter) {\n goto TURN_SB_INTO_WORD; // Finish word if next char is upper\n }\n goto CHAR_PROCESSED;\n case CharKind.Other:\n goto TURN_SB_INTO_WORD;\n default: // charCurrent is never Start or End\n Debug.Assert(cKindCurrent == CharKind.UpperCaseLetter);\n break;\n }\n\n // Here cKindCurrent is UpperCaseLetter\n // Append UpperCaseLetter to sb anyway\n sb.Append(c); \n\n switch (cKindNext) {\n default:\n goto CHAR_PROCESSED;\n\n case CharKind.UpperCaseLetter: \n // \"SimpleHTTPServer\" when we are at 'P' we need to see that NextNext is 'e' to get the word!\n if (cKindNextNext == CharKind.LowerCaseLetter) {\n goto TURN_SB_INTO_WORD;\n }\n goto CHAR_PROCESSED;\n\n case CharKind.End:\n case CharKind.Other:\n break; // goto TURN_SB_INTO_WORD;\n }\n\n //------------------------------------------------\n\n TURN_SB_INTO_WORD:\n string word = sb.ToString();\n sb.Length = 0;\n if (word.Length >= MIN_WORD_LENGTH) { \n list.Add(word);\n }\n\n CHAR_PROCESSED:\n // Shift left for next iteration!\n cKindCurrent = cKindNext;\n cKindNext = cKindNextNext;\n }\n\n string lastWord = sb.ToString();\n if (lastWord.Length >= MIN_WORD_LENGTH) {\n list.Add(lastWord);\n }\n return list.ToArray();\n }\n private static CharKind GetCharKind(char c) {\n if (char.IsDigit(c)) { return CharKind.Digit; }\n if (char.IsLetter(c)) {\n if (char.IsUpper(c)) { return CharKind.UpperCaseLetter; }\n Debug.Assert(char.IsLower(c));\n return CharKind.LowerCaseLetter;\n }\n return CharKind.Other;\n }\n enum CharKind {\n End, // For end of string\n Digit,\n UpperCaseLetter,\n LowerCaseLetter,\n Other\n }\n [TestCase((string)null, \"\")]\n [TestCase(\"\", \"\")]\n\n // Ignore one letter or one digit words\n [TestCase(\"A\", \"\")]\n [TestCase(\"4\", \"\")]\n [TestCase(\"_\", \"\")]\n [TestCase(\"Word_m_Field\", \"Word Field\")]\n [TestCase(\"Word_4_Field\", \"Word Field\")]\n\n [TestCase(\"a4\", \"a4\")]\n [TestCase(\"ABC\", \"ABC\")]\n [TestCase(\"abc\", \"abc\")]\n [TestCase(\"AbCd\", \"Ab Cd\")]\n [TestCase(\"AbcCde\", \"Abc Cde\")]\n [TestCase(\"ABCCde\", \"ABC Cde\")]\n\n [TestCase(\"Abc42Cde\", \"Abc42 Cde\")]\n [TestCase(\"Abc42cde\", \"Abc42cde\")]\n [TestCase(\"ABC42Cde\", \"ABC42 Cde\")]\n [TestCase(\"42ABC\", \"42 ABC\")]\n [TestCase(\"42abc\", \"42abc\")]\n\n [TestCase(\"abc_cde\", \"abc cde\")]\n [TestCase(\"Abc_Cde\", \"Abc Cde\")]\n [TestCase(\"_Abc__Cde_\", \"Abc Cde\")]\n [TestCase(\"ABC_CDE_FGH\", \"ABC CDE FGH\")]\n [TestCase(\"ABC CDE FGH\", \"ABC CDE FGH\")] // Should not happend (white char) anything that is not a letter/digit/'_' is considered as a separator\n [TestCase(\"ABC,CDE;FGH\", \"ABC CDE FGH\")] // Should not happend (,;) anything that is not a letter/digit/'_' is considered as a separator\n [TestCase(\"abc<cde\", \"abc cde\")]\n [TestCase(\"abc<>cde\", \"abc cde\")]\n [TestCase(\"abc<D>cde\", \"abc cde\")] // Ignore one letter or one digit words\n [TestCase(\"abc<Da>cde\", \"abc Da cde\")]\n [TestCase(\"abc<cde>\", \"abc cde\")]\n\n [TestCase(\"SimpleHTTPServer\", \"Simple HTTP Server\")]\n [TestCase(\"SimpleHTTPS2erver\", \"Simple HTTPS2erver\")]\n [TestCase(\"camelCase\", \"camel Case\")]\n [TestCase(\"m_Field\", \"Field\")]\n [TestCase(\"mm_Field\", \"mm Field\")]\n public void Test_GetWords(string identifier, string expectedWordsStr) {\n var expectedWords = expectedWordsStr.Split(' ');\n if (identifier == null || identifier.Length <= 1) {\n expectedWords = new string[0];\n }\n\n var words = identifier.GetWords();\n Assert.IsTrue(words.SequenceEqual(expectedWords));\n }\n"
},
{
"answer_id": 52978450,
"author": "John Smith",
"author_id": 3739391,
"author_profile": "https://Stackoverflow.com/users/3739391",
"pm_score": 0,
"selected": false,
"text": "string s1 = \"ThisIsATestStringAbcDefGhiJklMnoPqrStuVwxYz\";\nstring s2;\nStringBuilder sb = new StringBuilder();\n\nforeach (char c in s1)\n sb.Append(char.IsUpper(c)\n ? \" \" + c.ToString()\n : c.ToString());\n\ns2 = sb.ToString();\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17235/"
] |
155,306
|
<p>I have a textarea with many lines of input, and a JavaScript event fires that necessitates I scroll the textarea to line 345.</p>
<p><code>scrollTop</code> sort of does what I want, except as far as I can tell it's pixel level, and I want something that operates on a line level. What also complicates things is that, afaik once again, it's not possible to make textareas not line-wrap.</p>
|
[
{
"answer_id": 155404,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 5,
"selected": true,
"text": "<script type=\"text/javascript\" language=\"JavaScript\">\nfunction Jump(line)\n{\n var ta = document.getElementById(\"TextArea\");\n var lineHeight = ta.clientHeight / ta.rows;\n var jump = (line - 1) * lineHeight;\n ta.scrollTop = jump;\n}\n</script>\n\n<textarea name=\"TextArea\" id=\"TextArea\" \n rows=\"40\" cols=\"80\" title=\"Paste text here\"\n wrap=\"off\"></textarea>\n<input type=\"button\" onclick=\"Jump(98)\" title=\"Go!\" value=\"Jump\"/>\n"
},
{
"answer_id": 14199739,
"author": "tetkin",
"author_id": 1456378,
"author_profile": "https://Stackoverflow.com/users/1456378",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\" language=\"JavaScript\">\nfunction Jump(line)\n{\n var ta = document.getElementById(\"TextArea\");\n var lineHeight = ta.scrollHeight / ta.rows;\n var jump = (line - 1) * lineHeight;\n ta.scrollTop = jump;\n}\n</script>\n\n<textarea name=\"TextArea\" id=\"TextArea\" \n rows=\"40\" cols=\"80\" title=\"Paste text here\"\n wrap=\"off\"></textarea>\n<input type=\"button\" onclick=\"Jump(98)\" title=\"Go!\" value=\"Jump\"/>\n"
},
{
"answer_id": 49033334,
"author": "Darren Shewry",
"author_id": 142714,
"author_profile": "https://Stackoverflow.com/users/142714",
"pm_score": 0,
"selected": false,
"text": "rows textarea textarea ta.rows line-height textarea currentStyle getComputedStyle .css() function jump(line) {\n var ta = document.getElementById(\"TextArea\");\n var jump = line * parseInt(getStyle(ta, 'line-height'), 10);\n ta.scrollTop = jump;\n}\n\nfunction getStyle(el, styleProp) {\n if (el.currentStyle) {\n var y = el.currentStyle[styleProp];\n } else if (window.getComputedStyle) {\n var y = document.defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);\n }\n return y;\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23845/"
] |
155,308
|
<p>I'm trying to get a PHP site working in IIS on Windows Server with MySQL.</p>
<p>I'm getting this error…</p>
<p>Fatal error: Call to undefined function mysql_connect() in C:\inetpub...\adodb\drivers\adodb-mysql.inc.php on line 363</p>
<hr />
<p>Update…</p>
<p>This link outlines the steps I followed to install PHP on my server:<br />
<a href="https://stackoverflow.com/questions/11919/how-do-i-get-php-and-mysql-working-on-iis-70#94341">How do I get PHP and MySQL working on IIS 7.0 ?</a><br />
(note especially steps 6 and 8 regarting php.ini and php_mysql.dll).</p>
<p>Only two lines in the phpinfo report reference SQL:</p>
<pre><code><?php
phpinfo();
?>
</code></pre>
<blockquote>
<p>Configure Command:<br />
cscript /nologo configure.js "--enable-snapshot-build" "--enable-mysqlnd"</p>
<p>sql.safe_mode:<br />
Local Value Off, Master Value Off</p>
</blockquote>
<p><a href="http://img79.imageshack.us/img79/2373/configurecommandmw8.gif" rel="nofollow noreferrer">PHP Configure Command http://img79.imageshack.us/img79/2373/configurecommandmw8.gif</a></p>
<p><a href="http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif" rel="nofollow noreferrer">PHP sql.safe_mode http://img49.imageshack.us/img49/3066/sqlsafemoderu6.gif</a></p>
<hr />
<p>Update…</p>
<p>I found the solution: <a href="https://stackoverflow.com/questions/158279/how-do-i-install-mysql-modules-within-php#160746">How do I install MySQL modules within PHP?</a></p>
|
[
{
"answer_id": 155316,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 2,
"selected": false,
"text": "<?php\n phpinfo();\n?>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
155,311
|
<p>I would like invoke a function call in a one shot manner. What's the best way to do this in Boost / C++?</p>
<p>I would like to pass it two parameters and do not need a result.</p>
|
[
{
"answer_id": 155420,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "boost::thread some_thread(&SomeFunction, param1, param2);\n"
},
{
"answer_id": 155434,
"author": "David Smith",
"author_id": 17201,
"author_profile": "https://Stackoverflow.com/users/17201",
"pm_score": 2,
"selected": false,
"text": "void find_the_question(int the_answer);\n\nboost::thread deep_thought_2(find_the_question,42);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] |
155,314
|
<p>I'm looking to implement a function that retrieves a single frame from an input video, so I can use it as a thumbnail.</p>
<p>Something along these lines should work: </p>
<pre><code>// filename examples: "test.avi", "test.dvr-ms"
// position is from 0 to 100 percent (0.0 to 1.0)
// returns a bitmap
byte[] GetVideoThumbnail(string filename, float position)
{
}
</code></pre>
<p>Does anyone know how to do this in .Net 3.0? </p>
<p>The correct solution will be the "best" implementation of this function.
Bonus points for avoiding selection of blank frames. </p>
|
[
{
"answer_id": 6852123,
"author": "Ahmad Behjati",
"author_id": 866395,
"author_profile": "https://Stackoverflow.com/users/866395",
"pm_score": 2,
"selected": false,
"text": "Process ffmpeg;\n\nstring video;\nstring thumb;\n\nvideo = Server.MapPath(\"first.avi\");\nthumb = Server.MapPath(\"frame.jpg\");\n\nffmpeg = new Process();\n\nffmpeg.StartInfo.Arguments = \" -i \"+video+\" -ss 00:00:07 -vframes 1 -f image2 -vcodec mjpeg \"+thumb;\nffmpeg.StartInfo.FileName = Server.MapPath(\"ffmpeg.exe\");\nffmpeg.Start();\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
155,321
|
<p>I'm trying to build a mapping table to associate the IDs of new rows in a table with those that they're copied from. The OUTPUT INTO clause seems perfect for that, but it doesn't seem to behave according to the documentation. </p>
<p>My code:</p>
<pre><code>DECLARE @Missing TABLE (SrcContentID INT PRIMARY KEY )
INSERT INTO @Missing
( SrcContentID )
SELECT cshadow.ContentID
FROM Private.Content AS cshadow
LEFT JOIN Private.Content AS cglobal ON cshadow.Tag = cglobal.Tag
WHERE cglobal.ContentID IS NULL
PRINT 'Adding new content headers'
DECLARE @Inserted TABLE (SrcContentID INT PRIMARY KEY, TgtContentID INT )
INSERT INTO Private.Content
( Tag, Description, ContentDate, DateActivate, DateDeactivate, SortOrder, CreatedOn, IsDeleted, ContentClassCode, ContentGroupID, OrgUnitID )
OUTPUT cglobal.ContentID, INSERTED.ContentID INTO @Inserted (SrcContentID, TgtContentID)
SELECT Tag, Description, ContentDate, DateActivate, DateDeactivate, SortOrder, CreatedOn, IsDeleted, ContentClassCode, ContentGroupID, NULL
FROM Private.Content AS cglobal
INNER JOIN @Missing AS m ON cglobal.ContentID = m.SrcContentID
</code></pre>
<p>Results in the error message:</p>
<pre><code>Msg 207, Level 16, State 1, Line 34
Invalid column name 'SrcContentID'.
</code></pre>
<p>(line 34 being the one with the OUTPUT INTO)</p>
<p>Experimentation suggests that only rows that are actually present in the target of the INSERT can be selected in the OUTPUT INTO. But this contradicts the docs in the books online. The article on <strong>OUTPUT Clause</strong> has example E that describes a similar usage:</p>
<blockquote>
<p>The OUTPUT INTO clause returns values
from the table being updated
(WorkOrder) and also from the Product
table. The Product table is used in
the FROM clause to specify the rows to
update.</p>
</blockquote>
<p>Has anyone worked with this feature?</p>
<p>(In the meantime I've rewritten my code to do the job using a cursor loop, but that's ugly and I'm still curious)</p>
|
[
{
"answer_id": 156352,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 5,
"selected": true,
"text": "INSERTED from_table_name TRUNCATE TABLE main\n\nSELECT *\nFROM incoming\n\nSELECT *\nFROM main\n\nDECLARE @Missing TABLE (ContentID INT PRIMARY KEY)\nINSERT INTO @Missing(ContentID) \nSELECT incoming.ContentID\nFROM incoming\nLEFT JOIN main\n ON main.ContentID = incoming.ContentID\nWHERE main.ContentID IS NULL\n\nSELECT *\nFROM @Missing\n\nDECLARE @Inserted TABLE (ContentID INT PRIMARY KEY, [Content] varchar(50))\nINSERT INTO main(ContentID, [Content]) \nOUTPUT INSERTED.ContentID /* incoming doesn't work, m doesn't work */, INSERTED.[Content] INTO @Inserted (ContentID, [Content])\nSELECT incoming.ContentID, incoming.[Content] \nFROM incoming\nINNER JOIN @Missing AS m\n ON m.ContentID = incoming.ContentID\n\nSELECT *\nFROM @Inserted\n\nSELECT *\nFROM incoming\n\nSELECT *\nFROM main\n from_table_name DELETE UPDATE MERGE from_table_name FROM DELETE UPDATE FROM INSERTED DELETED"
},
{
"answer_id": 662046,
"author": "Roland Zwaga",
"author_id": 79594,
"author_profile": "https://Stackoverflow.com/users/79594",
"pm_score": 0,
"selected": false,
"text": "DECLARE @tmptable TABLE (uniqueid uniqueidentifier, original_id int, new_id int)\n insert into @tmptable\n(uniqueid,original_id,new_id)\nselect NewId(),id,0 from OriginalTable\n insert into OriginalTable\n(uniqueid)\nselect uniqueid from @tmptable\n update @tmptable\nset new_id = o.id\nfrom OriginalTable o inner join @tmptable tmp on tmp.uniqueid = o.uniqueid\n"
},
{
"answer_id": 4192191,
"author": "ArtOfCoding",
"author_id": 272067,
"author_profile": "https://Stackoverflow.com/users/272067",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO Private.Content \n (Tag) \n OUTPUT cglobal.ContentID, INSERTED.ContentID \n INTO @Inserted (SrcContentID, TgtContentID)\nSELECT Tag\n FROM Private.Content AS cglobal\n INNER JOIN @Missing AS m ON cglobal.ContentID = m.SrcContentID\n INSERT INTO con1 \n (Tag) \n OUTPUT **con2**.ContentID, INSERTED.ContentID \n INTO @Inserted (SrcContentID, TgtContentID)\nSELECT Tag\n FROM Private.Content con1\n **INNER JOIN Private.Content con2 ON con1.id=con2.id**\n INNER JOIN @Missing AS m ON con1.ContentID = m.SrcContentID\n"
},
{
"answer_id": 5423588,
"author": "Simon D",
"author_id": 161040,
"author_profile": "https://Stackoverflow.com/users/161040",
"pm_score": 4,
"selected": false,
"text": "--drop table A\ncreate table A (a int primary key identity(1, 1))\ninsert into A default values\ninsert into A default values\n\ndelete from A where a>=3\n\n-- insert two values into A and get the new primary keys\nMERGE a USING (SELECT a FROM A) AS B(a)\nON (1 = 0) -- ignore the values, NOT MATCHED will always be true\nWHEN NOT MATCHED THEN INSERT DEFAULT VALUES -- always insert here for this example\nOUTPUT $action, inserted.*, deleted.*, B.a; -- show the new primary key and source data\n INSERT, 3, NULL, 1\nINSERT, 4, NULL, 2\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10082/"
] |
155,366
|
<p>Rep steps:</p>
<ol>
<li>create example .NET form application</li>
<li>put a TextBox on the form</li>
<li>wire a function up to the TextBox's Enter event</li>
</ol>
<p>When you run this application, the <strong>Control.Enter</strong> event fires when focus first goes to the TextBox. However, if you click away into another application and then click back into the test application, the event will not fire again.</p>
<p>So <strong>moving between applications does not trigger Enter/Leave</strong>.</p>
<p>Is there another alternative <em>Control-level</em> event that I can use, which will fire in this scenario?</p>
<p>Ordinarily, I would use <strong>Form.Activated</strong>. Unfortunately, that is troublesome here because my component is hosted by a docking system that can undock my component into a new Form without notifying me.</p>
|
[
{
"answer_id": 158860,
"author": "Fry",
"author_id": 23553,
"author_profile": "https://Stackoverflow.com/users/23553",
"pm_score": 0,
"selected": false,
"text": "Grid currentGrid = (Grid)sender;\n"
},
{
"answer_id": 32187337,
"author": "user5261230",
"author_id": 5261230,
"author_profile": "https://Stackoverflow.com/users/5261230",
"pm_score": -1,
"selected": false,
"text": " using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Windows.Forms;\n\n namespace EnterBrokenExample\n {\n static class Program\n {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n\n Form Form1 = new Form();\n Form c1 = new Form();\n Form c2 = new Form();\n\n Form1.IsMdiContainer = true;\n\n c1.MdiParent = Form1;\n c2.MdiParent = Form1;\n\n c1.Show();\n c2.Show();\n\n TextBox tb1 = new TextBox();\n c1.Controls.Add(tb1);\n tb1.Enter += ontbenter;\n tb1.Text = \"Some Text\";\n tb1.GotFocus += ongotfocus;\n\n TextBox tb2 = new TextBox();\n c2.Controls.Add(tb2);\n tb2.Enter += ontbenter;\n tb2.Text = \"some other text\";\n tb2.GotFocus += ongotfocus;\n\n Application.Run(Form1);\n }\n static void ontbenter(object sender, EventArgs args)\n {\n if (!(sender is TextBox))\n return;\n TextBox s = (TextBox)sender;\n s.SelectAll();\n }\n\n static void ongotfocus(object sender, EventArgs args)\n {\n if (!(sender is TextBox))\n return;\n TextBox s = (TextBox)sender;\n s.SelectAll();\n }\n }\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23933/"
] |
155,367
|
<p>Change Data Capture is a new feature in SQL Server 2008. From MSDN:</p>
<blockquote>
<p>Change data capture provides
historical change information for a
user table by capturing both the fact
that DML changes were made and the
actual data that was changed. Changes
are captured by using an asynchronous
process that reads the transaction log
and has a low impact on the system</p>
</blockquote>
<p>This is highly sweet - no more adding CreatedDate and LastModifiedBy columns manually.</p>
<p>Does Oracle have anything like this?</p>
|
[
{
"answer_id": 49542172,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLESPACE SPACE_FOR_ARCHIVE \ndatafile 'C:\\ORACLE DB12\\ARCH_SPACE.DBF'size 50G;\n\nCREATE FLASHBACK ARCHIVE longterm\nTABLESPACE space_for_archive\nRETENTION 1 YEAR;\n\nALTER TABLE EMPLOYEES FLASHBACK ARCHIVE LONGTERM;\n\n\nselect EMPLOYEE_ID, FIRST_NAME, JOB_ID, VACATION_BALANCE,\n VERSIONS_STARTTIME TS,\n nvl(VERSIONS_OPERATION,'I') OP\nfrom EMPLOYEES\nversions between timestamp timestamp '2016-01-11 08:20:00' and systimestamp\nwhere EMPLOYEE_ID = 100\norder by EMPLOYEE_ID, ts;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
155,371
|
<p>I want to use XMLHttpRequest in JavaScript to POST a form that includes a file type input element so that I can avoid page refresh and get useful XML back.</p>
<p>I can submit the form without page refresh, using JavaScript to set the target attribute on the form to an iframe for MSIE or an object for Mozilla, but this has two problems. The minor problem is that target is not W3C compliant (which is why I set it in JavaScript, not in XHTML). The major problem is that the onload event doesn't fire, at least not on Mozilla on OS X Leopard. Besides, XMLHttpRequest would make for prettier response code because the returned data could be XML, not confined to XHTML as is the case with iframe.</p>
<p>Submitting the form results in HTTP that looks like: </p>
<pre><code>Content-Type: multipart/form-data;boundary=<boundary string>
Content-Length: <length>
--<boundary string>
Content-Disposition: form-data, name="<input element name>"
<input element value>
--<boundary string>
Content-Disposition: form-data, name=<input element name>"; filename="<input element value>"
Content-Type: application/octet-stream
<element body>
</code></pre>
<p>How do I get the XMLHttpRequest object's send method to duplicate the above HTTP stream?</p>
|
[
{
"answer_id": 155429,
"author": "helios",
"author_id": 9686,
"author_profile": "https://Stackoverflow.com/users/9686",
"pm_score": 0,
"selected": false,
"text": "var lFrame = document.getElementById('myframe');\nlFrame.onreadystatechange = function()\n{\n if (lFrame.readyState == 'complete')\n {\n // your frame is done, get the content...\n }\n};\n"
},
{
"answer_id": 155441,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "\n<form method=\"post\" target=\"myiframe\" action=\"handler.php\">\n...\n</form>\n<iframe id=\"myiframe\" style=\"display:none\" />\n"
},
{
"answer_id": 170789,
"author": "Komang",
"author_id": 19463,
"author_profile": "https://Stackoverflow.com/users/19463",
"pm_score": 0,
"selected": false,
"text": "if(window.attachEvent){\n document.getElementById(iframe).attachEvent('onload', some_method);\n}else{\n document.getElementById(iframe).addEventListener('load', some_method, false);\n} \n"
},
{
"answer_id": 4240940,
"author": "Alex Polo",
"author_id": 514852,
"author_profile": "https://Stackoverflow.com/users/514852",
"pm_score": 6,
"selected": true,
"text": "send send sendAsBinary XMLHttpRequest"
},
{
"answer_id": 48043063,
"author": "Romuald Brunet",
"author_id": 286182,
"author_profile": "https://Stackoverflow.com/users/286182",
"pm_score": 0,
"selected": false,
"text": "var form = document.querySelector('#myForm');\nform.addEventListener(\"submit\", function(e) {\n var xhr = new XMLHttpRequest();\n xhr.open(\"POST\", this.action);\n xhr.addEventListener(\"load\", function(e) {\n // Your callback\n });\n\n xhr.send(new FormData(this));\n\n e.preventDefault();\n});\n <form id=\"myForm\" action=\"...\" method=\"POST\" enctype=\"multipart/form-data\">\n <input type=\"file\" name=\"file0\">\n <input type=\"text\" name=\"some-text\">\n ...\n</form>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14405/"
] |
155,375
|
<p>I'm working with a datagrid and adapter that correspond with an MSAccess table through a stored query (named "UpdatePaid", 3 paramaters as shown below) like so:</p>
<pre><code> OleDbCommand odc = new OleDbCommand("UpdatePaid", connection);
OleDbParameter param;
odc.CommandType = CommandType.StoredProcedure;
param = odc.Parameters.Add("v_iid", OleDbType.Double);
param.SourceColumn = "I";
param.SourceVersion = DataRowVersion.Original;
param = odc.Parameters.Add("v_pd", OleDbType.Boolean);
param.SourceColumn = "Paid";
param.SourceVersion = DataRowVersion.Current;
param = odc.Parameters.Add("v_Projected", OleDbType.Currency);
param.SourceColumn = "ProjectedCost";
param.SourceVersion = DataRowVersion.Current;
odc.Prepare();
myAdapter.UpdateCommand = odc;
...
myAdapter.Update();
</code></pre>
<p>It works fine...but the really weird thing is that it <em>didn't</em> until I put in the <strong>odc.Prepare()</strong> call.<br><br>My question is thus: Do I need to do that all the time when working with OleDb stored procs/queries? Why? I also have another project coming up where I'll have to do the same thing with a SqlDbCommand... do I have to do it with those, too? </p>
|
[
{
"answer_id": 155571,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 0,
"selected": false,
"text": "Prepare() Prepare() System.Data.SqlClient"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13776/"
] |
155,378
|
<p>I have a <code>double</code> value <code>f</code> and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to the original but still strictly greater than (or less than) the original.</p>
<p>It doesn't have to be close down to the last bit—it's more important that whatever change I make is guaranteed to produce a different value and not round back to the original.</p>
|
[
{
"answer_id": 155397,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 7,
"selected": true,
"text": "nextafter nextafterf"
},
{
"answer_id": 155406,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "u64 &x = *(u64*)(&f);\nx++;\n u64 &x = *(u64*)(&f);\nif( ((x>>52) & 2047) != 2047 ) //if exponent is all 1's then f is a nan or inf.\n{\n x += f>0 ? 1 : -1;\n}\n"
},
{
"answer_id": 155413,
"author": "PixelSmack",
"author_id": 22978,
"author_profile": "https://Stackoverflow.com/users/22978",
"pm_score": -1,
"selected": false,
"text": "#include <stdio.h>\n\nint main()\n{\n /* two numbers to work with */\n double number1, number2; // result of calculation\n double result;\n int counter; // loop counter and accuracy check\n\n number1 = 1.0;\n number2 = 1.0;\n counter = 0;\n\n while (number1 + number2 != number1) {\n ++counter;\n number2 = number2 / 10;\n }\n printf(\"%2d digits accuracy in calculations\\n\", counter);\n\n number2 = 1.0;\n counter = 0;\n\n while (1) {\n result = number1 + number2;\n if (result == number1)\n break;\n ++counter;\n number2 = number2 / 10.0;\n }\n\n printf(\"%2d digits accuracy in storage\\n\", counter );\n\n return (0);\n}\n"
},
{
"answer_id": 155448,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 2,
"selected": false,
"text": "double DoubleIncrement(double value)\n{\n int exponent;\n double mantissa = frexp(value, &exponent);\n if(mantissa == 0)\n return DBL_MIN;\n\n mantissa += DBL_EPSILON/2.0f;\n value = ldexp(mantissa, exponent);\n return value;\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] |
155,388
|
<p>Suppose that I have interface MyInterface and 2 classes A, B which implement MyInterface.<br>
I declared 2 objects: <code>MyInterface a = new A()</code> , and <code>MyInterface b = new B()</code>.<br>
When I try to pass to a function - function <code>doSomething(A a){}</code> I am getting an error.</p>
<p>This is my code:</p>
<pre><code>public interface MyInterface {}
public class A implements MyInterface{}
public class B implements MyInterface{}
public class Tester {
public static void main(String[] args){
MyInterface a = new A();
MyInterface b = new B();
test(b);
}
public static void test(A a){
System.out.println("A");
}
public static void test(B b){
System.out.println("B");
}
}
</code></pre>
<p>My problem is that I am getting from some component interface which can be all sorts of classes and I need to write function for each class.<br>
So one way is to get interface and to check which type is it. (instance of A)</p>
<p>I would like to know how others deal with this problem??</p>
<p>Thx</p>
|
[
{
"answer_id": 155417,
"author": "perimosocordiae",
"author_id": 10601,
"author_profile": "https://Stackoverflow.com/users/10601",
"pm_score": 0,
"selected": false,
"text": "public abstract class Parent {} public class A extends Parent {...} public class B extends Parent {...}"
},
{
"answer_id": 155418,
"author": "Goran",
"author_id": 23164,
"author_profile": "https://Stackoverflow.com/users/23164",
"pm_score": 1,
"selected": false,
"text": "public interface Visitable { \n void accept(Tester tester) \n}\n\npublic interface MyInterface implements Visitable { \n}\n\npublic class A implements MyInterface{\n public void accept(Tester tester){\n tester.test(this);\n }\n}\n\npublic class B implements MyInterface{\n public void accept(Tester tester){\n tester.test(this);\n }\n}\n\npublic class Tester {\n\n public static void main(String[] args){\n MyInterface a = new A();\n MyInterface b = new B();\n a.accept(this);\n b.accept(this);\n }\n\n public void test(A a){\n System.out.println(\"A\");\n }\n\n public void test(B b){\n System.out.println(\"B\");\n }\n\n}\n"
},
{
"answer_id": 155428,
"author": "parkerfath",
"author_id": 6027,
"author_profile": "https://Stackoverflow.com/users/6027",
"pm_score": 1,
"selected": false,
"text": "public interface MyInterface { \n public void test();\n}\n\npublic class A implements MyInterface{\n public void test() {\n System.out.println(\"A\");\n }\n}\n\npublic class B implements MyInterface{\n public void test() {\n System.out.println(\"B\");\n }\n}\n\npublic class Tester {\n\n public static void main(String[] args){\n MyInterface a = new A();\n MyInterface b = new B();\n b.test();\n }\n}\n"
},
{
"answer_id": 155439,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 2,
"selected": false,
"text": "public static void test(MyInterface obj){\n if(obj instanceof A) {\n A tmp = (A)obj;\n } else if(obj instanceof B) {\n B tmp = (B)obj;\n } else {\n //handle error condition\n }\n}\n"
},
{
"answer_id": 155455,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 0,
"selected": false,
"text": "visit(Visitor) Visitor if-else test(MyInterface) ATester BTester ITester test(MyInterface) ATester MyInterface ITester if-else"
},
{
"answer_id": 16544865,
"author": "AllTooSir",
"author_id": 1163607,
"author_profile": "https://Stackoverflow.com/users/1163607",
"pm_score": 0,
"selected": false,
"text": "public interface MyInterface {}\n\npublic class A implements MyInterface{}\n\npublic class B implements MyInterface{}\n\npublic class Tester {\n\n public static void main(String[] args){\n MyInterface a = new A();\n MyInterface b = new B();\n test(b); // this is wrong\n }\n\n public static void test(A a){\n System.out.println(\"A\");\n }\n\n public static void test(B b){\n System.out.println(\"B\");\n }\n\n}\n MyInterface test(B b) MyInterface MyInterface B B public class B implements MyInterface {\n public void onlyBCanInvokeThis() {}\n\n}\n test(B b) public static void test(B b){\n b.onlyBCanInvokeThis();\n System.out.println(\"B\");\n}\n MyInterface a = new A();\n // since a is of type A. invoking onlyBCanInvokeThis()\n // inside test() method on a will throw exception.\n test(a); \n MyInterface public interface MyInterface { \n public void test();\n}\n\npublic class A implements MyInterface{\n public void test() {\n System.out.println(\"A\");\n }\n}\n\npublic class B implements MyInterface{\n public void test() {\n System.out.println(\"B\");\n }\n}\n\npublic class Tester {\n\n public static void main(String[] args){\n MyInterface a = new A();\n MyInterface b = new B();\n b.test(); // calls B's implementation of test()\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23968/"
] |
155,391
|
<p>What is the difference between a BitmapFrame and BitmapImage in WPF? Where would you use each (ie. why would you use a BitmapFrame rather than a BitmapImage?)</p>
|
[
{
"answer_id": 155433,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": true,
"text": "Uri uri = ...;\nBitmapSource bmp = new BitmapImage(uri);\nConsole.WriteLine(\"{0}x{1}\", bmp.PixelWIdth, bmp.PixelHeight);\n Uri uri = ...;\nBitmapDecoder dec = BitmapDecoder.Create(uri, BitmapCreateOptions.None, BitmapCacheOption.Default);\nBitmapSource bmp = dec.Frames[0];\nConsole.WriteLine(\"{0}x{1}\", bmp.PixelWIdth, bmp.PixelHeight);\n"
},
{
"answer_id": 24946309,
"author": "stritch000",
"author_id": 436717,
"author_profile": "https://Stackoverflow.com/users/436717",
"pm_score": 2,
"selected": false,
"text": "TiffBitmapDecoder TiffBitmapDecoder decoder = new TiffBitmapDecoder(\n new Uri(filename), \n BitmapCreateOptions.None, \n BitmapCacheOption.None);\n\nfor (int frameIndex = 0; frameIndex < decoder.Frames.Count; frameIndex++)\n{\n BitmapFrame frame = decoder.Frames[frameIndex];\n // Do something with the frame\n // (it inherits from BitmapSource, so the options are wide open)\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
155,426
|
<p>I tried to set innerHTML on an element in firefox and it worked fine, tried it in IE and got unexpected errors with no obvious reason why.</p>
<p>For example if you try and set the innerHTML of a table to " hi from stu " it will fail, because the table must be followed by a sequence.</p>
|
[
{
"answer_id": 161491,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 2,
"selected": false,
"text": "// removing the scripts to avoid any 'Permission Denied' errors in IE\nvar cleaned = html.replace(/<script(.|\\s)*?\\/script>/g, \"\");\n\n// IE is stricter on malformed HTML injecting direct into DOM. By injecting into \n// an element that's not yet part of DOM it's more lenient and will clean it up.\nif (jQuery.browser.msie)\n{\n var tempElement = document.createElement(\"DIV\");\n tempElement.innerHTML = cleaned;\n cleaned = tempElement.innerHTML;\n tempElement = null;\n}\n// now 'cleaned' is ready to use...\n"
},
{
"answer_id": 3767401,
"author": "Mark Dibley",
"author_id": 454793,
"author_profile": "https://Stackoverflow.com/users/454793",
"pm_score": 1,
"selected": false,
"text": "replaceInReadOnly(document.getElementById(\"links\"), \"<a href>........etc</a>\");\n\nfunction replaceInReadOnly(element, content){\n var newNode = document.createElement();\n newNode.innerHTML = content;\n var oldNode = element.firstChild;\n var output = element.replaceChild(newNode, oldNode);\n}\n"
},
{
"answer_id": 21251691,
"author": "Agamemnus",
"author_id": 1136569,
"author_profile": "https://Stackoverflow.com/users/1136569",
"pm_score": 0,
"selected": false,
"text": "if (/(msie|trident)/i.test(navigator.userAgent)) {\n var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, \"innerHTML\").get\n var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, \"innerHTML\").set\n Object.defineProperty(HTMLElement.prototype, \"innerHTML\", {\n get: function () {return innerhtml_get.call (this)},\n set: function(new_html) {\n var childNodes = this.childNodes\n for (var curlen = childNodes.length, i = curlen; i > 0; i--) {\n this.removeChild (childNodes[0])\n }\n innerhtml_set.call (this, new_html)\n }\n })\n}\n\nvar mydiv = document.createElement ('div')\nmydiv.innerHTML = \"test\"\ndocument.body.appendChild (mydiv)\n\ndocument.body.innerHTML = \"\"\nconsole.log (mydiv.innerHTML)\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386/"
] |
155,427
|
<p>I have a form element that I want to address via javascript, but it doesn't like the syntax.</p>
<pre><code><form name="mycache">
<input type="hidden" name="cache[m][2]">
<!-- ... -->
</form>
</code></pre>
<p>I want to be able to say:</p>
<pre><code>document.mycache.cache[m][2]
</code></pre>
<p>but obviously I need to indicate that <code>cache[m][2]</code> is the whole name, and not an array reference to <code>cache</code>. Can it be done?</p>
|
[
{
"answer_id": 155437,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 3,
"selected": true,
"text": "<html>\n<body>\n\n<form id=\"form1\">\n\n<input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/>\n\n<input type='button' value='Test' onclick='showtest();'/>\n\n<script type=\"text/javascript\">\nfunction showtest() {\n var value = document.getElementById(\"field[m][2]\").value;\n alert(value);\n}\n</script>\n\n</form>\n\n</body>\n</html>\n var value = document.forms.form1[\"field[m][2]\"].value;\n"
},
{
"answer_id": 155446,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "document.getElementsByName(\"input_name\")"
},
{
"answer_id": 156153,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 1,
"selected": false,
"text": "form.elements[\"cache[m][2]\"]\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14253/"
] |
155,435
|
<p>In JavaScript, you can do this:</p>
<pre><code>var a = null;
var b = "I'm a value";
var c = null;
var result = a || b || c;
</code></pre>
<p>And 'result' will get the value of 'b' because JavaScript short-circuits the 'or' operator.</p>
<p>I want a one-line idiom to do this in ColdFusion and the best I can come up with is:</p>
<pre><code><cfif LEN(c) GT 0><cfset result=c></cfif>
<cfif LEN(b) GT 0><cfset result=b></cfif>
<cfif LEN(a) GT 0><cfset result=a></cfif>
</code></pre>
<p>Can anyone do any better than this?</p>
|
[
{
"answer_id": 155529,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 4,
"selected": true,
"text": "<cfset result = ListFirst( \"#a#,#b#,#c#\" )/>\n"
},
{
"answer_id": 155550,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 1,
"selected": false,
"text": "<cffunction name=\"FirstNotNull\" returntype=\"any\" output=\"false\">\n <cfset var i = 0/>\n <cfloop index=\"i\" from=\"1\" to=\"#ArrayLen(Arguments)#\">\n <cfif NOT isNull(Arguments[i]) >\n <cfreturn Arguments[i] />\n </cfif>\n </cfloop>\n</cffunction>\n <cfset result = FirstNotNull( a , b , c ) />\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13958/"
] |
155,436
|
<p><strong>What are the best practices for naming unit test classes and test methods?</strong></p>
<p>This was discussed on SO before, at <a href="https://stackoverflow.com/questions/96297/naming-conventions-for-unit-tests">What are some popular naming conventions for Unit Tests?</a></p>
<p>I don't know if this is a very good approach, but currently in my testing projects, I have one-to-one mappings between each production class and a test class, e.g. <code>Product</code> and <code>ProductTest</code>.</p>
<p>In my test classes I then have methods with the names of the methods I am testing, an underscore, and then the situation and what I expect to happen, e.g. <code>Save_ShouldThrowExceptionWithNullName()</code>.</p>
|
[
{
"answer_id": 155475,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 6,
"selected": false,
"text": "[name of your 'unit']Tests\n test[feature being tested]\n class Person {\n int calculateAge() { ... }\n\n // other methods and properties\n}\n class PersonTests {\n\n testAgeCalculationWithNoBirthDate() { ... }\n\n // or\n\n testCalculateAge() { ... }\n}\n"
},
{
"answer_id": 155480,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 6,
"selected": false,
"text": "OrdersShouldBeCreated();\nOrdersWithNoProductsShouldFail();\n"
},
{
"answer_id": 155482,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "Can_add_user_to_domain - MyUnitTestProject \n + FTPServerTests <- Folder\n + UserManagerTests <- Test Fixture Class\n - Can_add_user_to_domain <- Test methods\n - Can_delete_user_from_domain\n - Can_reset_password\n"
},
{
"answer_id": 1014560,
"author": "Thorsten Lorenz",
"author_id": 97443,
"author_profile": "https://Stackoverflow.com/users/97443",
"pm_score": 3,
"selected": false,
"text": "Settings MyApp.Serialization MyApp.Serialization.Tests IfSettings SaveStrings() CanSaveStrings() MyApp.Serialization.Tests.IfSettings.CanSaveStrings DetectsInvalidUserInput ThrowsOnNotFound WillCloseTheDatabaseAfterTheTransaction [Test] public void detects_invalid_User_Input()\n"
},
{
"answer_id": 1549340,
"author": "grundoon",
"author_id": 179522,
"author_profile": "https://Stackoverflow.com/users/179522",
"pm_score": 4,
"selected": false,
"text": "StressTest SkinTest StressTestTest MeasurementUnit MeasurementUnitTest QaSkinTest QaMeasurementUnit WhenDivisorIsNonZero_ExpectDivisionResult\nWhenDivisorIsZero_ExpectError\nWhenInventoryIsBelowOrderQty_ExpectBackOrder\nWhenInventoryIsAboveOrderQty_ExpectReducedInventory\n"
},
{
"answer_id": 1594049,
"author": "Marc Climent",
"author_id": 58791,
"author_profile": "https://Stackoverflow.com/users/58791",
"pm_score": 10,
"selected": true,
"text": "Add_credit_updates_customer_balance Purchase_without_funds_is_not_possible Add_affiliate_discount [UnitOfWork_StateUnderTest_ExpectedBehavior] .Tests Tests [NameOfTheClassUnderTestTests]"
},
{
"answer_id": 7398606,
"author": "Jack Ukleja",
"author_id": 61714,
"author_profile": "https://Stackoverflow.com/users/61714",
"pm_score": 7,
"selected": false,
"text": "[TestFixture]\npublic class BankAccountTests\n{\n [Test]\n public void Should_Increase_Balance_When_Deposit_Is_Made()\n {\n var bankAccount = new BankAccount();\n bankAccount.Deposit(100);\n Assert.That(bankAccount.Balance, Is.EqualTo(100));\n }\n}\n <method>_Should<expected>_When<condition> Deposit_ShouldIncreaseBalance_WhenGivenPositiveValue()"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11829/"
] |
155,449
|
<p>Right now I have the following in my <code>.vimrc</code>:</p>
<pre><code>au BufWritePost *.c,*.cpp,*.h !ctags -R
</code></pre>
<p>There are a few problems with this:</p>
<ol>
<li>It's slow -- regenerates tags for files that haven't changed since the last tag generation.</li>
<li>I have to push the enter button <em>again</em> after writing the file because of an inevitable "press Enter or type command to continue".</li>
</ol>
<p>When you combine these two issues I end up pushing the additional enter too soon (before <code>ctags -R</code> has finished), then see the annoying error message, and have to push enter again.</p>
<p>I know it doesn't sound like a big deal, but with the amount of file writes I do on a given day it tends to get really annoying. There's gotta be a better way to do it!</p>
|
[
{
"answer_id": 155515,
"author": "Zathrus",
"author_id": 16220,
"author_profile": "https://Stackoverflow.com/users/16220",
"pm_score": 7,
"selected": true,
"text": "au BufWritePost *.c,*.cpp,*.h silent! !ctags -R & --append tagbsearch"
},
{
"answer_id": 156781,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 1,
"selected": false,
"text": "--append grep -v \" Options {{{1\nlet g:tags_options_cpp = '--c++-kinds=+p --fields=+imaS --extra=+q'\n\nfunction! s:CtagsExecutable()\n let tags_executable = lh#option#Get('tags_executable', s:tags_executable, 'bg')\n return tags_executable\nendfunction\n\nfunction! s:CtagsOptions()\n let ctags_options = lh#option#Get('tags_options_'.&ft, '')\n let ctags_options .= ' '.lh#option#Get('tags_options', '', 'wbg')\n return ctags_options\nendfunction\n\nfunction! s:CtagsDirname()\n let ctags_dirname = lh#option#Get('tags_dirname', '', 'b').'/'\n return ctags_dirname\nendfunction\n\nfunction! s:CtagsFilename()\n let ctags_filename = lh#option#Get('tags_filename', 'tags', 'bg')\n return ctags_filename\nendfunction\n\nfunction! s:CtagsCmdLine(ctags_pathname)\n let cmd_line = s:CtagsExecutable().' '.s:CtagsOptions().' -f '.a:ctags_pathname\n return cmd_line\nendfunction\n\n\n\" ######################################################################\n\" Tag generating functions {{{1\n\" ======================================================================\n\" Interface {{{2\n\" ======================================================================\n\" Mappings {{{3\n\" inoremap <expr> ; <sid>Run('UpdateTags_for_ModifiedFile',';')\n\nnnoremap <silent> <Plug>CTagsUpdateCurrent :call <sid>UpdateCurrent()<cr>\nif !hasmapto('<Plug>CTagsUpdateCurrent', 'n')\n nmap <silent> <c-x>tc <Plug>CTagsUpdateCurrent\nendif\n\nnnoremap <silent> <Plug>CTagsUpdateAll :call <sid>UpdateAll()<cr>\nif !hasmapto('<Plug>CTagsUpdateAll', 'n')\n nmap <silent> <c-x>ta <Plug>CTagsUpdateAll\nendif\n\n\n\" ======================================================================\n\" Auto command for automatically tagging a file when saved {{{3\naugroup LH_TAGS\n au!\n autocmd BufWritePost,FileWritePost * if ! lh#option#Get('LHT_no_auto', 0) | call s:Run('UpdateTags_for_SavedFile') | endif\naug END\n\n\" ======================================================================\n\" Internal functions {{{2\n\" ======================================================================\n\" generate tags on-the-fly {{{3\nfunction! UpdateTags_for_ModifiedFile(ctags_pathname)\n let source_name = expand('%')\n let temp_name = tempname()\n let temp_tags = tempname()\n\n \" 1- purge old references to the source name\n if filereadable(a:ctags_pathname)\n \" it exists => must be changed\n call system('grep -v \" '.source_name.' \" '.a:ctags_pathname.' > '.temp_tags.\n \\ ' && mv -f '.temp_tags.' '.a:ctags_pathname)\n endif\n\n \" 2- save the unsaved contents of the current file\n call writefile(getline(1, '$'), temp_name, 'b')\n\n \" 3- call ctags, and replace references to the temporary source file to the\n \" real source file\n let cmd_line = s:CtagsCmdLine(a:ctags_pathname).' '.source_name.' --append'\n let cmd_line .= ' && sed \"s#\\t'.temp_name.'\\t#\\t'.source_name.'\\t#\" > '.temp_tags\n let cmd_line .= ' && mv -f '.temp_tags.' '.a:ctags_pathname\n call system(cmd_line)\n call delete(temp_name)\n\n return ';'\nendfunction\n\n\" ======================================================================\n\" generate tags for all files {{{3\nfunction! s:UpdateTags_for_All(ctags_pathname)\n call delete(a:ctags_pathname)\n let cmd_line = 'cd '.s:CtagsDirname()\n \" todo => use project directory\n \"\n let cmd_line .= ' && '.s:CtagsCmdLine(a:ctags_pathname).' -R'\n echo cmd_line\n call system(cmd_line)\nendfunction\n\n\" ======================================================================\n\" generate tags for the current saved file {{{3\nfunction! s:UpdateTags_for_SavedFile(ctags_pathname)\n let source_name = expand('%')\n let temp_tags = tempname()\n\n if filereadable(a:ctags_pathname)\n \" it exists => must be changed\n call system('grep -v \" '.source_name.' \" '.a:ctags_pathname.' > '.temp_tags.' && mv -f '.temp_tags.' '.a:ctags_pathname)\n endif\n let cmd_line = 'cd '.s:CtagsDirname()\n let cmd_line .= ' && ' . s:CtagsCmdLine(a:ctags_pathname).' --append '.source_name\n \" echo cmd_line\n call system(cmd_line)\nendfunction\n\n\" ======================================================================\n\" (public) Run a tag generating function {{{3\nfunction! LHTagsRun(tag_function)\n call s:Run(a:tag_function)\nendfunction\n\n\" ======================================================================\n\" (private) Run a tag generating function {{{3\n\" See this function as a /template method/.\nfunction! s:Run(tag_function)\n try\n let ctags_dirname = s:CtagsDirname()\n if strlen(ctags_dirname)==1\n throw \"tags-error: empty dirname\"\n endif\n let ctags_filename = s:CtagsFilename()\n let ctags_pathname = ctags_dirname.ctags_filename\n if !filewritable(ctags_dirname) && !filewritable(ctags_pathname)\n throw \"tags-error: \".ctags_pathname.\" cannot be modified\"\n endif\n\n let Fn = function(\"s:\".a:tag_function)\n call Fn(ctags_pathname)\n catch /tags-error:/\n \" call lh#common#ErrorMsg(v:exception)\n return 0\n finally\n endtry\n\n echo ctags_pathname . ' updated.'\n return 1\nendfunction\n\nfunction! s:Irun(tag_function, res)\n call s:Run(a:tag_function)\n return a:res\nendfunction\n\n\" ======================================================================\n\" Main function for updating all tags {{{3\nfunction! s:UpdateAll()\n let done = s:Run('UpdateTags_for_All')\nendfunction\n\n\" Main function for updating the tags from one file {{{3\n\" @note the file may be saved or \"modified\".\nfunction! s:UpdateCurrent()\n if &modified\n let done = s:Run('UpdateTags_for_ModifiedFile')\n else\n let done = s:Run('UpdateTags_for_SavedFile')\n endif\nendfunction\n ^Xta ^Xtc"
},
{
"answer_id": 164404,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 4,
"selected": false,
"text": "au FileType {c,cpp} au BufWritePost <buffer> silent ! [ -e tags ] &&\n \\ ( awk -F'\\t' '$2\\!=\"%:gs/'/'\\''/\"{print}' tags ; ctags -f- '%:gs/'/'\\''/' )\n \\ | sort -t$'\\t' -k1,1 -o tags.new && mv tags.new tags\n BufWritePost % :gs tags ctags sort"
},
{
"answer_id": 4310892,
"author": "code933k",
"author_id": 194556,
"author_profile": "https://Stackoverflow.com/users/194556",
"pm_score": 3,
"selected": false,
"text": "/home/me/Code/c/that_program IN_DELETE,IN_CLOSE_WRITE ctags --sort=yes *.c\n"
},
{
"answer_id": 7269205,
"author": "rand_acs",
"author_id": 143219,
"author_profile": "https://Stackoverflow.com/users/143219",
"pm_score": 2,
"selected": false,
"text": "au BufWritePost *.c,*.cpp,*.h silent! !ctags -R &\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
155,458
|
<p>I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.</p>
<p>Here is the code :</p>
<pre><code> if (region != null)
{
....
}
</code></pre>
<p>This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when debugging, it doesn't go inside the IF statement... When I do a Quick Watch with these following expression : I see the (region == null) return false, AND (region != null) return false too... <strong>why and how?</strong></p>
<p><strong>Update</strong></p>
<p>Someone point out that the object was == and != overloaded:</p>
<pre><code> public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
public static bool operator !=(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) != 0 || r1.Id != r2.Id);
}
</code></pre>
|
[
{
"answer_id": 155467,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": true,
"text": "public static bool operator ==(Region r1, Region r2)\n{\n if (object.ReferenceEquals( r1, r2)) {\n // handles if both are null as well as object identity\n return true;\n }\n\n if ((object)r1 == null || (object)r2 == null)\n {\n return false;\n } \n\n return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);\n}\n\npublic static bool operator !=(Region r1, Region r2)\n{\n return !(r1 == r2);\n}\n"
},
{
"answer_id": 155488,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "if (object.ReferenceEquals(r1, r2))\n{\n return true;\n}\n"
},
{
"answer_id": 155489,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 0,
"selected": false,
"text": "public static bool operator !=(Region r1, Region r2)\n{\n if (object.ReferenceEquals(r1, null))\n {\n return false;\n }\n if (object.ReferenceEquals(r2, null))\n {\n return false;\n }\n...\n"
},
{
"answer_id": 155508,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 3,
"selected": false,
"text": " public static bool operator ==(Region r1, Region r2)\n {\n if (object.ReferenceEquals(r1, null))\n {\n return false;\n }\n if (object.ReferenceEquals(r2, null))\n {\n return false;\n }\n\n return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);\n }\n //ifs expanded a bit for readability\n public static bool operator ==(Region r1, Region r2)\n {\n if( (object)r1 == null && (object)r2 == null)\n {\n return true;\n }\n if( (object)r1 == null || (object)r2 == null)\n {\n return false;\n } \n //btw - a quick shortcut here is also object.ReferenceEquals(r1, r2)\n\n return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);\n }\n"
},
{
"answer_id": 735710,
"author": "Triynko",
"author_id": 88409,
"author_profile": "https://Stackoverflow.com/users/88409",
"pm_score": 2,
"selected": false,
"text": "int GetHashCode() //Overrides Object.GetHashCode\nbool Equals(object other) //Overrides Object.Equals; would correspond to IEquatable, if such an interface existed\nbool Equals(T other) //Implements IEquatable<T>; do this for each T you want to compare to\nstatic bool operator ==(T x, T y)\nstatic bool operator !=(T x, T y)\n IEquatable<T> Equals(T other) IEquatable<T2> bool Equals(object other)\n{\n if (other is T) //replicate this for each IEquatable<T2>, IEquatable<T3>, etc. you may implement\n return Equals( (T)other) ); //forward to IEquatable<T> implementation\n return false; //other is null or cannot be compared to this instance; therefore it is not equal\n}\n\nbool Equals(T other)\n{\n if ((object)other == null) //cast to object for reference equality comparison, or use object.ReferenceEquals\n return false;\n //if ((object)other == this) //possible performance boost, ONLY if object instance is frequently compared to itself! otherwise it's just an extra useless check\n //return true;\n return field1.Equals( other.field1 ) &&\n field2.Equals( other.field2 ); //compare type fields to determine equality\n}\n\npublic static bool operator ==( T x, T y )\n{\n if ((object)x != null) //cast to object for reference equality comparison, or use object.ReferenceEquals\n return x.Equals( y ); //forward to type-safe Equals on non-null instance x\n if ((object)y != null)\n return false; //x was null, y is not null\n return true; //both null\n}\n\npublic static bool operator !=( T x, T y )\n{\n if ((object)x != null)\n return !x.Equals( y ); //forward to type-safe Equals on non-null instance x\n if ((object)y != null)\n return true; //x was null, y is not null\n return false; //both null\n}\n IEquatable<T> == != != == !(obj1 == obj2) IEquatable<T> ReferenceEquals(obj1,obj2) Equals(object),Equals(T),==,!="
},
{
"answer_id": 13519359,
"author": "fernando",
"author_id": 1846008,
"author_profile": "https://Stackoverflow.com/users/1846008",
"pm_score": 0,
"selected": false,
"text": "bool comp;\nif (object.IsNullOrEmpty(r1))\n{\n comp = false;\n}\n\nif (object.IsNullOrEmpty(r2))\n{\n comp = false;\n}\nreturn comp;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
155,460
|
<p>I'm using LINQ to SQL and C#. I have two LINQ classes: User and Network. </p>
<p>User has UserID (primary key) and NetworkID</p>
<p>Network has NetworkID (primary key) and an AdminID (a UserID)</p>
<p>The following code works fine:</p>
<pre><code>user.Network.AdminID = 0;
db.SubmitChanges();
</code></pre>
<p>However, if I access the AdminID before making the change, the change never happens to the DB. So the following doesn't work:</p>
<pre><code>if(user.Network.AdminID == user.UserID)
{
user.Network.AdminID = 0;
db.SubmitChanges();
}
</code></pre>
<p>It is making it into the if statement and calling submit changes. For some reason, the changes to AdminID never make it to the DB. No error thrown, the change just never 'takes'.</p>
<p>Any idea what could be causing this?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 155658,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "{\n Contact previousValue = this._Contact.Entity;\n if (((previousValue != value)\n || (this._Contact.HasLoadedOrAssignedValue == false)))\n {\n this.SendPropertyChanging();\n if ((previousValue != null))\n {\n this._Contact.Entity = null;\n previousValue.ContactEvents.Remove(this);\n }\n this._Contact.Entity = value;\n if ((value != null))\n {\n value.ContactEvents.Add(this);\n this._ContactID = value.ID;\n }\n else\n {\n this._ContactID = default(int);\n }\n this.SendPropertyChanged(\"Contact\");\n }\n}\n this._Contact.Entity = value;\n value.ContactEvents.Add(this);\n myContactEvent.ContactID = myContact.ID;\n myContactEvent.Contact = myContact;\n myContact.ContactEvents.Add(myContactEvent);\n"
},
{
"answer_id": 3339204,
"author": "Alex Kazansky",
"author_id": 196837,
"author_profile": "https://Stackoverflow.com/users/196837",
"pm_score": 0,
"selected": false,
"text": "DBDataContext db { get { return new DBDataContext(); } }\n DBDataContext db = new DBDataContext();\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23971/"
] |
155,462
|
<p>In Ruby:</p>
<pre><code>for i in A do
# some code
end
</code></pre>
<p>is the same as: </p>
<pre><code>A.each do |i|
# some code
end
</code></pre>
<p><code>for</code> is not a kernel method:</p>
<ul>
<li>What exactly is "<code>for</code>" in ruby</li>
<li>Is there a way to use other keywords to do similar things? </li>
</ul>
<p>Something like:</p>
<pre><code> total = sum i in I {x[i]}
</code></pre>
<p>mapping to:</p>
<pre><code> total = I.sum {|i] x[i]}
</code></pre>
|
[
{
"answer_id": 155513,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": false,
"text": "for each for i in 1 do\nend\n NoMethodError: undefined method `each' for 1:Fixnum\n"
},
{
"answer_id": 155531,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 3,
"selected": false,
"text": "for aSong in songList\n aSong.play\nend\n songList.each do |aSong|\n aSong.play\nend\n for i in ['fee', 'fi', 'fo', 'fum']\n print i, \" \"\nend\nfor i in 1..3\n print i, \" \"\nend\nfor i in File.open(\"ordinal\").find_all { |l| l =~ /d$/}\n print i.chomp, \" \"\nend\n fee fi fo fum 1 2 3 second third\n class Periods\n def each\n yield \"Classical\"\n yield \"Jazz\"\n yield \"Rock\"\n end\nend\n\n\nperiods = Periods.new\nfor genre in periods\n print genre, \" \"\nend\n Classical Jazz Rock\n for arr.each {}"
},
{
"answer_id": 155543,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 7,
"selected": true,
"text": "for each for i in (1..3)\n x = i\nend\np x # => 3\n (1..3).each do |i|\n x = i\nend\np x # => undefined local variable or method `x' for main:Object\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167/"
] |
155,504
|
<p>I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API?</p>
<p>I know you can do this with the Java Mail API, but in the past I've found that very verbose and unpleasant to work with.</p>
<p><strong>EDIT</strong>: I've received several replies pointing towards tutorials that describe how to send mail with attachments, but what I'm asking about is how to <strong>read</strong> attachments from <strong>received</strong> mail.</p>
<p>Cheers,
Don</p>
|
[
{
"answer_id": 158511,
"author": "Steven M. Cherry",
"author_id": 24193,
"author_profile": "https://Stackoverflow.com/users/24193",
"pm_score": 5,
"selected": true,
"text": "/**\n * Copyright (c) 2008 Steven M. Cherry\n * All rights reserved.\n */\npackage utils.scheduled;\n\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.sql.Timestamp;\nimport java.util.Properties;\nimport java.util.Vector;\n\nimport javax.mail.Address;\nimport javax.mail.Flags;\nimport javax.mail.Folder;\nimport javax.mail.Message;\nimport javax.mail.Multipart;\nimport javax.mail.Part;\nimport javax.mail.Session;\nimport javax.mail.Store;\nimport javax.mail.internet.MimeBodyPart;\n\nimport glob.ActionLogicImplementation;\nimport glob.IOConn;\nimport glob.log.Log;\nimport logic.utils.sql.Settings;\nimport logic.utils.sqldo.EMail;\nimport logic.utils.sqldo.EMailAttach;\n\n/**\n * This will connect to our incoming e-mail server and download any e-mails\n * that are found on the server. The e-mails will be stored for further processing\n * in our internal database. Attachments will be written out to separate files\n * and then referred to by the database entries. This is intended to be run by \n * the scheduler every minute or so.\n *\n * @author Steven M. Cherry\n */\npublic class DownloadEMail implements ActionLogicImplementation {\n\n protected String receiving_host;\n protected String receiving_user;\n protected String receiving_pass;\n protected String receiving_protocol;\n protected boolean receiving_secure;\n protected String receiving_attachments;\n\n /** This will run our logic */\n public void ExecuteRequest(IOConn ioc) throws Exception {\n Log.Trace(\"Enter\");\n\n Log.Debug(\"Executing DownloadEMail\");\n ioc.initializeResponseDocument(\"DownloadEMail\");\n\n // pick up our configuration from the server:\n receiving_host = Settings.getValue(ioc, \"server.email.receiving.host\");\n receiving_user = Settings.getValue(ioc, \"server.email.receiving.username\");\n receiving_pass = Settings.getValue(ioc, \"server.email.receiving.password\");\n receiving_protocol = Settings.getValue(ioc, \"server.email.receiving.protocol\");\n String tmp_secure = Settings.getValue(ioc, \"server.email.receiving.secure\");\n receiving_attachments = Settings.getValue(ioc, \"server.email.receiving.attachments\");\n\n // sanity check on the parameters:\n if(receiving_host == null || receiving_host.length() == 0){\n ioc.SendReturn();\n ioc.Close();\n Log.Trace(\"Exit\");\n return; // no host defined.\n }\n if(receiving_user == null || receiving_user.length() == 0){\n ioc.SendReturn();\n ioc.Close();\n Log.Trace(\"Exit\");\n return; // no user defined.\n }\n if(receiving_pass == null || receiving_pass.length() == 0){\n ioc.SendReturn();\n ioc.Close();\n Log.Trace(\"Exit\");\n return; // no pass defined.\n }\n if(receiving_protocol == null || receiving_protocol.length() == 0){\n Log.Debug(\"EMail receiving protocol not defined, defaulting to POP\");\n receiving_protocol = \"POP\";\n }\n if(tmp_secure == null || \n tmp_secure.length() == 0 ||\n tmp_secure.compareToIgnoreCase(\"false\") == 0 ||\n tmp_secure.compareToIgnoreCase(\"no\") == 0\n ){\n receiving_secure = false;\n } else {\n receiving_secure = true;\n }\n if(receiving_attachments == null || receiving_attachments.length() == 0){\n Log.Debug(\"EMail receiving attachments not defined, defaulting to ./email/attachments/\");\n receiving_attachments = \"./email/attachments/\";\n }\n\n // now do the real work.\n doEMailDownload(ioc);\n\n ioc.SendReturn();\n ioc.Close();\n Log.Trace(\"Exit\");\n }\n\n protected void doEMailDownload(IOConn ioc) throws Exception {\n // Create empty properties\n Properties props = new Properties();\n // Get the session\n Session session = Session.getInstance(props, null);\n\n // Get the store\n Store store = session.getStore(receiving_protocol);\n store.connect(receiving_host, receiving_user, receiving_pass);\n\n // Get folder\n Folder folder = store.getFolder(\"INBOX\");\n folder.open(Folder.READ_WRITE);\n\n try {\n\n // Get directory listing\n Message messages[] = folder.getMessages();\n\n for (int i=0; i < messages.length; i++) {\n // get the details of the message:\n EMail email = new EMail();\n email.fromaddr = messages[i].getFrom()[0].toString();\n Address[] to = messages[i].getRecipients(Message.RecipientType.TO);\n email.toaddr = \"\";\n for(int j = 0; j < to.length; j++){\n email.toaddr += to[j].toString() + \"; \";\n }\n Address[] cc;\n try {\n cc = messages[i].getRecipients(Message.RecipientType.CC);\n } catch (Exception e){\n Log.Warn(\"Exception retrieving CC addrs: %s\", e.getLocalizedMessage());\n cc = null;\n }\n email.cc = \"\";\n if(cc != null){\n for(int j = 0; j < cc.length; j++){\n email.cc += cc[j].toString() + \"; \";\n }\n }\n email.subject = messages[i].getSubject();\n if(messages[i].getReceivedDate() != null){\n email.received_when = new Timestamp(messages[i].getReceivedDate().getTime());\n } else {\n email.received_when = new Timestamp( (new java.util.Date()).getTime());\n }\n\n\n email.body = \"\";\n Vector<EMailAttach> vema = new Vector<EMailAttach>();\n Object content = messages[i].getContent();\n if(content instanceof java.lang.String){\n email.body = (String)content;\n } else if(content instanceof Multipart){\n Multipart mp = (Multipart)content;\n\n for (int j=0; j < mp.getCount(); j++) {\n Part part = mp.getBodyPart(j);\n\n String disposition = part.getDisposition();\n\n if (disposition == null) {\n // Check if plain\n MimeBodyPart mbp = (MimeBodyPart)part;\n if (mbp.isMimeType(\"text/plain\")) {\n Log.Debug(\"Mime type is plain\");\n email.body += (String)mbp.getContent();\n } else {\n Log.Debug(\"Mime type is not plain\");\n // Special non-attachment cases here of \n // image/gif, text/html, ...\n EMailAttach ema = new EMailAttach();\n ema.name = decodeName(part.getFileName());\n File savedir = new File(receiving_attachments);\n savedir.mkdirs();\n File savefile = File.createTempFile(\"emailattach\", \".atch\", savedir );\n ema.path = savefile.getAbsolutePath();\n ema.size = part.getSize();\n vema.add(ema);\n ema.size = saveFile(savefile, part);\n }\n } else if ((disposition != null) && \n (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) ) \n ){\n // Check if plain\n MimeBodyPart mbp = (MimeBodyPart)part;\n if (mbp.isMimeType(\"text/plain\")) {\n Log.Debug(\"Mime type is plain\");\n email.body += (String)mbp.getContent();\n } else {\n Log.Debug(\"Save file (%s)\", part.getFileName() );\n EMailAttach ema = new EMailAttach();\n ema.name = decodeName(part.getFileName());\n File savedir = new File(receiving_attachments);\n savedir.mkdirs();\n File savefile = File.createTempFile(\"emailattach\", \".atch\", savedir );\n ema.path = savefile.getAbsolutePath();\n ema.size = part.getSize();\n vema.add(ema);\n ema.size = saveFile( savefile, part);\n }\n }\n }\n }\n\n // Insert everything into the database:\n logic.utils.sql.EMail.insertEMail(ioc, email);\n for(int j = 0; j < vema.size(); j++){\n vema.get(j).emailid = email.id;\n logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) );\n }\n\n // commit this message and all of it's attachments\n ioc.getDBConnection().commit();\n\n // Finally delete the message from the server.\n messages[i].setFlag(Flags.Flag.DELETED, true);\n }\n\n // Close connection \n folder.close(true); // true tells the mail server to expunge deleted messages.\n store.close();\n } catch (Exception e){\n folder.close(true); // true tells the mail server to expunge deleted messages.\n store.close();\n throw e;\n }\n\n }\n\n protected int saveFile(File saveFile, Part part) throws Exception {\n\n BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) );\n\n byte[] buff = new byte[2048];\n InputStream is = part.getInputStream();\n int ret = 0, count = 0;\n while( (ret = is.read(buff)) > 0 ){\n bos.write(buff, 0, ret);\n count += ret;\n }\n bos.close();\n is.close();\n return count;\n }\n\n protected String decodeName( String name ) throws Exception {\n if(name == null || name.length() == 0){\n return \"unknown\";\n }\n String ret = java.net.URLDecoder.decode( name, \"UTF-8\" );\n\n // also check for a few other things in the string:\n ret = ret.replaceAll(\"=\\\\?utf-8\\\\?q\\\\?\", \"\");\n ret = ret.replaceAll(\"\\\\?=\", \"\");\n ret = ret.replaceAll(\"=20\", \" \");\n\n return ret;\n }\n\n}\n"
},
{
"answer_id": 1490089,
"author": "Maciej Kreft",
"author_id": 180819,
"author_profile": "https://Stackoverflow.com/users/180819",
"pm_score": 2,
"selected": false,
"text": "else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT)\n || disposition.equals(Part.INLINE) ) \n else if ((disposition.equalsIgnoreCase(Part.ATTACHMENT)\n || disposition.equalsIgnoreCase(Part.INLINE))\n"
},
{
"answer_id": 4528035,
"author": "chad",
"author_id": 344269,
"author_profile": "https://Stackoverflow.com/users/344269",
"pm_score": 4,
"selected": false,
"text": "package utils;\n\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Properties;\n\nimport javax.mail.Address;\nimport javax.mail.Flags;\nimport javax.mail.Folder;\nimport javax.mail.Message;\nimport javax.mail.Multipart;\nimport javax.mail.Part;\nimport javax.mail.Session;\nimport javax.mail.Store;\nimport javax.mail.internet.MimeBodyPart;\n\npublic class IncomingMail {\n\n public static List<Email> downloadPop3(String host, String user, String pass, String downloadDir) throws Exception {\n\n List<Email> emails = new ArrayList<Email>();\n\n // Create empty properties\n Properties props = new Properties();\n\n // Get the session\n Session session = Session.getInstance(props, null);\n\n // Get the store\n Store store = session.getStore(\"pop3\");\n store.connect(host, user, pass);\n\n // Get folder\n Folder folder = store.getFolder(\"INBOX\");\n folder.open(Folder.READ_WRITE);\n\n try {\n // Get directory listing\n Message messages[] = folder.getMessages();\n for (int i = 0; i < messages.length; i++) {\n\n Email email = new Email();\n\n // from \n email.from = messages[i].getFrom()[0].toString();\n\n // to list\n Address[] toArray = messages[i] .getRecipients(Message.RecipientType.TO);\n for (Address to : toArray) { email.to.add(to.toString()); }\n\n // cc list\n Address[] ccArray = null;\n try {\n ccArray = messages[i] .getRecipients(Message.RecipientType.CC);\n } catch (Exception e) { ccArray = null; }\n if (ccArray != null) {\n for (Address c : ccArray) {\n email.cc.add(c.toString());\n }\n }\n\n // subject\n email.subject = messages[i].getSubject();\n\n // received date\n if (messages[i].getReceivedDate() != null) {\n email.received = messages[i].getReceivedDate();\n } else {\n email.received = new Date();\n }\n\n // body and attachments\n email.body = \"\";\n Object content = messages[i].getContent();\n if (content instanceof java.lang.String) {\n\n email.body = (String) content;\n\n } else if (content instanceof Multipart) {\n\n Multipart mp = (Multipart) content;\n\n for (int j = 0; j < mp.getCount(); j++) {\n\n Part part = mp.getBodyPart(j);\n String disposition = part.getDisposition();\n\n if (disposition == null) {\n\n MimeBodyPart mbp = (MimeBodyPart) part;\n if (mbp.isMimeType(\"text/plain\")) {\n // Plain\n email.body += (String) mbp.getContent();\n } \n\n } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition .equals(Part.INLINE))) {\n\n // Check if plain\n MimeBodyPart mbp = (MimeBodyPart) part;\n if (mbp.isMimeType(\"text/plain\")) {\n email.body += (String) mbp.getContent();\n } else {\n EmailAttachment attachment = new EmailAttachment();\n attachment.name = decodeName(part.getFileName());\n File savedir = new File(downloadDir);\n savedir.mkdirs();\n // File savefile = File.createTempFile( \"emailattach\", \".atch\", savedir);\n File savefile = new File(downloadDir,attachment.name);\n attachment.path = savefile.getAbsolutePath();\n attachment.size = saveFile(savefile, part);\n email.attachments.add(attachment);\n }\n }\n } // end of multipart for loop \n } // end messages for loop\n\n emails.add(email);\n\n // Finally delete the message from the server.\n messages[i].setFlag(Flags.Flag.DELETED, true);\n }\n\n // Close connection\n folder.close(true); // true tells the mail server to expunge deleted messages\n store.close();\n\n } catch (Exception e) {\n folder.close(true); // true tells the mail server to expunge deleted\n store.close();\n throw e;\n }\n\n return emails;\n }\n\n private static String decodeName(String name) throws Exception {\n if (name == null || name.length() == 0) {\n return \"unknown\";\n }\n String ret = java.net.URLDecoder.decode(name, \"UTF-8\");\n\n // also check for a few other things in the string:\n ret = ret.replaceAll(\"=\\\\?utf-8\\\\?q\\\\?\", \"\");\n ret = ret.replaceAll(\"\\\\?=\", \"\");\n ret = ret.replaceAll(\"=20\", \" \");\n\n return ret;\n }\n\n private static int saveFile(File saveFile, Part part) throws Exception {\n\n BufferedOutputStream bos = new BufferedOutputStream(\n new FileOutputStream(saveFile));\n\n byte[] buff = new byte[2048];\n InputStream is = part.getInputStream();\n int ret = 0, count = 0;\n while ((ret = is.read(buff)) > 0) {\n bos.write(buff, 0, ret);\n count += ret;\n }\n bos.close();\n is.close();\n return count;\n }\n\n}\n package utils;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\npublic class Email {\n\n public Date received;\n public String from;\n public List<String> to = new ArrayList<String>();\n public List<String> cc = new ArrayList<String>();\n public String subject;\n public String body;\n public List<EmailAttachment> attachments = new ArrayList<EmailAttachment>();\n}\n package utils;\n\npublic class EmailAttachment {\n\n public String name;\n public String path;\n public int size;\n}\n package utils;\n\nimport java.util.List;\n\n\npublic class Test {\n\n public static void main(String[] args) {\n\n String host = \"some host\";\n String user = \"some user\";\n String pass = \"some pass\";\n String downloadDir = \"/Temp\";\n try {\n List<Email> emails = IncomingMail.downloadPop3(host, user, pass, downloadDir);\n for ( Email email : emails ) {\n System.out.println(email.from);\n System.out.println(email.subject);\n System.out.println(email.body);\n List<EmailAttachment> attachments = email.attachments;\n for ( EmailAttachment attachment : attachments ) {\n System.out.println(attachment.path+\" \"+attachment.name);\n }\n }\n } catch (Exception e) { e.printStackTrace(); }\n\n }\n\n}\n"
},
{
"answer_id": 19317643,
"author": "Karthik Reddy",
"author_id": 1929603,
"author_profile": "https://Stackoverflow.com/users/1929603",
"pm_score": -1,
"selected": false,
"text": "import java.io.IOException;\nimport java.io.InputStream;\n\nimport javax.mail.internet.MimeMessage;\nimport javax.servlet.http.HttpServletRequest;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.core.io.InputStreamSource;\nimport org.springframework.mail.javamail.JavaMailSender;\nimport org.springframework.mail.javamail.MimeMessageHelper;\nimport org.springframework.mail.javamail.MimeMessagePreparator;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.multipart.commons.CommonsMultipartFile;\n\n@Controller\n@RequestMapping(\"/sendEmail.do\")\npublic class SendEmailAttachController {\n @Autowired\n private JavaMailSender mailSender;\n\n @RequestMapping(method = RequestMethod.POST)\n public String sendEmail(HttpServletRequest request,\n final @RequestParam CommonsMultipartFile attachFile) {\n\n // Input here\n final String emailTo = request.getParameter(\"mailTo\");\n final String subject = request.getParameter(\"subject\");\n final String yourmailid = request.getParameter(\"yourmail\");\n final String message = request.getParameter(\"message\");\n\n // Logging\n System.out.println(\"emailTo: \" + emailTo);\n System.out.println(\"subject: \" + subject);\n System.out.println(\"Your mail id is: \"+yourmailid);\n System.out.println(\"message: \" + message);\n System.out.println(\"attachFile: \" + attachFile.getOriginalFilename());\n\n mailSender.send(new MimeMessagePreparator() {\n\n @Override\n public void prepare(MimeMessage mimeMessage) throws Exception {\n MimeMessageHelper messageHelper = new MimeMessageHelper(\n mimeMessage, true, \"UTF-8\");\n messageHelper.setTo(emailTo);\n messageHelper.setSubject(subject);\n messageHelper.setReplyTo(yourmailid);\n messageHelper.setText(message);\n\n // Attachment with mail\n String attachName = attachFile.getOriginalFilename();\n if (!attachFile.equals(\"\")) {\n\n messageHelper.addAttachment(attachName, new InputStreamSource() {\n\n @Override\n public InputStream getInputStream() throws IOException {\n return attachFile.getInputStream();\n }\n });\n }\n\n }\n\n });\n\n return \"Result\";\n }\n}\n"
},
{
"answer_id": 20467580,
"author": "Faber",
"author_id": 2584278,
"author_profile": "https://Stackoverflow.com/users/2584278",
"pm_score": 1,
"selected": false,
"text": "import java.util.List;\nimport javax.activation.DataSource; \nimport javax.mail.internet.MimeMessage; \nimport org.apache.commons.mail.util.MimeMessageParser; \n\npublic List<DataSource> getAttachmentList(MimeMessage message) throws Exception {\n msgParser = new MimeMessageParser(message);\n msgParser.parse();\n return msgParser.getAttachmentList();\n}\n DataSource InputStream"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
155,507
|
<p>How exactly can I create a new directory using Emacs? What commands do I use? (If possible, please provide an example)</p>
|
[
{
"answer_id": 155510,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 9,
"selected": true,
"text": "dir/to/create M-x make-directory RET dir/to/create RET\n dir/parent1/node dir/parent2/node M-! mkdir -p dir/parent{1,2}/node RET\n bash zsh Dired +\n C-x d *.py RET ; shows python source files in the CWD in `Dired` mode\n+ test RET ; create `test` directory in the CWD\n CWD C-x C-f M-x make-directory RET RET\n"
},
{
"answer_id": 155519,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": 6,
"selected": false,
"text": "C-x d"
},
{
"answer_id": 155616,
"author": "Cristian",
"author_id": 680,
"author_profile": "https://Stackoverflow.com/users/680",
"pm_score": 3,
"selected": false,
"text": "M-! M-! mkdir /path/to/new_dir\n"
},
{
"answer_id": 156001,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 3,
"selected": false,
"text": "make-directory"
},
{
"answer_id": 7217039,
"author": "etank",
"author_id": 271884,
"author_profile": "https://Stackoverflow.com/users/271884",
"pm_score": 3,
"selected": false,
"text": "M-x shell-command\n mkdir -p topdir/subdir\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
155,514
|
<p>How do I convert a utf-8 string to a utf-16 string in PHP?</p>
|
[
{
"answer_id": 155528,
"author": "chroder",
"author_id": 18802,
"author_profile": "https://Stackoverflow.com/users/18802",
"pm_score": 4,
"selected": false,
"text": "mb_convert_encoding"
},
{
"answer_id": 901141,
"author": "Jesper Grann Laursen",
"author_id": 110214,
"author_profile": "https://Stackoverflow.com/users/110214",
"pm_score": 2,
"selected": false,
"text": "iconv"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23598/"
] |
155,517
|
<p>Is it possible to cancel out of a long running process in VB6.0 without using DoEvents?</p>
<p>For example:</p>
<pre><code>for i = 1 to someVeryHighNumber
' Do some work here '
...
if cancel then
exit for
end if
next
Sub btnCancel_Click()
cancel = true
End Sub
</code></pre>
<p>I assume I need a "DoEvents" before the "if cancel then..." is there a better way? It's been awhile...</p>
|
[
{
"answer_id": 160893,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 6,
"selected": true,
"text": "DoEvents GetQueueStatus GetQueueStatus ' at the top:\nDeclare Function GetQueueStatus Lib \"user32\" (ByVal qsFlags As Long) As Long\n\n' then call this instead of DoEvents:\nSub DoEventsIfNecessary()\n If GetQueueStatus(255) <> 0 Then DoEvents\nEnd Sub\n"
},
{
"answer_id": 206791,
"author": "Shane Miskin",
"author_id": 16415,
"author_profile": "https://Stackoverflow.com/users/16415",
"pm_score": 2,
"selected": false,
"text": "Option Explicit\n\nPrivate Declare Function GetAsyncKeyState Lib \"user32\" (ByVal nVirtKey As Long) As Integer\n\nPrivate Sub Command1_Click()\n Do\n Label1.Caption = Now()\n Label1.Refresh\n If WasKeyPressed(vbKeyEscape) Then Exit Do\n Loop\n\n Label1.Caption = \"Exited loop successfully\"\n\nEnd Sub\n\nFunction WasKeyPressed(ByVal plVirtualKey As Long) As Boolean\n If (GetAsyncKeyState(plVirtualKey) And &H8000) Then WasKeyPressed = True\nEnd Function\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
] |
155,532
|
<p>Are there any good methods for getting ASP.NET 2.0 to validate under the XHTML 1.0 Strict (or Transitional) DTD? I'm interested to hear some ideas before I hack up the core of the HTTP response.</p>
<p>One major problem is the form tag itself, this is the output I got from W3C when I tried to validate:</p>
<pre><code>Line 13, Column 11: there is no attribute "name".
<form name="aspnetForm" method="post" action="Default.aspx" onsubmit="javascript
</code></pre>
<p>That tag is very fundamental to ASP.NET, as you all know. Hmmmm.</p>
|
[
{
"answer_id": 156533,
"author": "Calroth",
"author_id": 23358,
"author_profile": "https://Stackoverflow.com/users/23358",
"pm_score": 5,
"selected": true,
"text": "<system.web>\n ... other configuration goes here ...\n <xhtmlConformance mode=\"Strict\" />\n</system.web>\n mode=\"Transitional\""
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12252/"
] |
155,540
|
<p>I'm writing a scheduler or sorts. It's basically a table with a list of exes (like "C:\a.exe") and a console app that looks at the records in the table every minute or so and runs the tasks that haven't been run yet.</p>
<p>I run the tasks like this:</p>
<pre><code>System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = someExe; // like "a.exe"
p.Start();
</code></pre>
<p>How can I tell if a particular task failed? For example what if a.exe throws an unhandled exception? I'd like the above code to know when this happens and update the tasks table with something like "the particular task failed" etc.</p>
<p>How can I do this?</p>
<p>I'm not using the Sql Agent or the Windows Scheduler because someone else told me not to. He has more "experience" so I'm basically just following orders. Feel free to suggest alternatives.</p>
|
[
{
"answer_id": 155563,
"author": "Pete",
"author_id": 76,
"author_profile": "https://Stackoverflow.com/users/76",
"pm_score": 2,
"selected": false,
"text": "string output = p.StandardOutput.ReadToEnd();\n"
},
{
"answer_id": 157096,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 0,
"selected": false,
"text": " p.Start();\n p.WaitForExit();\n int returnCode = p.ExitCode;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/155540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.