qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
300,669 | <p>How do I launch an app and capture the output via stdout and maybe stderr?</p>
<p>I am writing an automated build system and I need to capture the output to analyze. I'd like to update the svn repo and grab the revision number so I can move the files in autobuild/revNumber/ if successful. I also would like to build using make and upload the compile text to my server for everyone to see the warnings and errors on a failed build.</p>
<p>I can't find the <code>system()</code> function, but I found the <code>CreateProcess()</code> function on MSDN. I am able to launch what I need but I have no idea how to capture the stderr and stdout. I notice the process launches separately unless I set a breakpoint and keep my app exiting which it then will keep all the text in my app console window. I would also want to wait until all processes are finished and then scan the data it produced to do any additional operations I need. How do I do any of this?</p>
| [
{
"answer_id": 300680,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "program arg1 arg2 >/tmp/log.file 2>&1\n 2>&1 LOG=${TMPDIR:-/tmp}/log.$$.$(date +%Y%m%d-%H%M%S)\nprogram arg1 arg2 >$LOG 2>&1\n system() strftime() getenv() getpid() popen() 2>&1 FILE *pp = popen(\"program arg1 arg2 2>&1\", \"r\");\n"
},
{
"answer_id": 300711,
"author": "sep",
"author_id": 30333,
"author_profile": "https://Stackoverflow.com/users/30333",
"pm_score": 2,
"selected": false,
"text": "/* Assume you open a file handle or pipe called myoutput */\nSTARTUP_INFO si_startinfo;\nZeroMemory(&si_startinfo, sizeof(STARTUP_INFO));\nsi_startinfo.cb = sizeof(STARTUP_INFO);\nsi_startinfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);\nsi_startinfo.hStdOutput = myoutput;\nsi_startinfo.hStdError = myoutput;\nsi_startifno.dwFlags != STARTF_USEHANDLES;\n\nPROCESS_INFORMATION pi_procinfo;\nZeroMemory(&pi_procinfo, sizeof(PROCESS_INFORMATION);\n\nCreateProcess(NULL, cmdline, NULL, NULL, true, 0, NULL, pathname, &si_startinfo, &pi_procinfo);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
300,671 | <p>How do i parse a text file in c#?</p>
| [
{
"answer_id": 300704,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<string> file.ReadLine()"
},
{
"answer_id": 447046,
"author": "Perica Zivkovic",
"author_id": 31822,
"author_profile": "https://Stackoverflow.com/users/31822",
"pm_score": 3,
"selected": false,
"text": "using (TextReader rdr = new StreamReader(fullFilePath))\n{\n string line;\n\n while ((line = rdr.ReadLine()) != null)\n {\n // use line here\n }\n}\n"
},
{
"answer_id": 447132,
"author": "Coderer",
"author_id": 26286,
"author_profile": "https://Stackoverflow.com/users/26286",
"pm_score": 0,
"selected": false,
"text": "FileInfo txtFile = new FileInfo(\"c:\\myfile.txt\");\nif(!txtFile.Exists) { // error handling }\n\nusing (TextReader rdr = txtFile.OpenText())\n{\n // use the text file as Pero suggested\n}\n"
},
{
"answer_id": 1326961,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "using System.Data;\nusing System.IO;\nusing System.Text.RegularExpressions;\n public DataTable ParseCSV(string inputString) {\n\n DataTable dt=new DataTable();\n\n // declare the Regular Expression that will match versus the input string\n Regex re=new Regex(\"((?<field>[^\\\",\\\\r\\\\n]+)|\\\"(?<field>([^\\\"]|\\\"\\\")+)\\\")(,|(?<rowbreak>\\\\r\\\\n|\\\\n|$))\");\n\n ArrayList colArray=new ArrayList();\n ArrayList rowArray=new ArrayList();\n\n int colCount=0;\n int maxColCount=0;\n string rowbreak=\"\";\n string field=\"\";\n\n MatchCollection mc=re.Matches(inputString);\n\n foreach(Match m in mc) {\n\n // retrieve the field and replace two double-quotes with a single double-quote\n field=m.Result(\"${field}\").Replace(\"\\\"\\\"\",\"\\\"\");\n\n rowbreak=m.Result(\"${rowbreak}\");\n\n if (field.Length > 0) {\n colArray.Add(field); \n colCount++;\n }\n\n if (rowbreak.Length > 0) {\n\n // add the column array to the row Array List\n rowArray.Add(colArray.ToArray());\n\n // create a new Array List to hold the field values\n colArray=new ArrayList(); \n\n if (colCount > maxColCount)\n maxColCount=colCount;\n\n colCount=0;\n }\n }\n\n if (rowbreak.Length == 0) {\n // this is executed when the last line doesn't\n // end with a line break\n rowArray.Add(colArray.ToArray());\n if (colCount > maxColCount)\n maxColCount=colCount;\n }\n\n // create the columns for the table\n for(int i=0; i < maxColCount; i++)\n dt.Columns.Add(String.Format(\"col{0:000}\",i));\n\n // convert the row Array List into an Array object for easier access\n Array ra=rowArray.ToArray();\n for(int i=0; i < ra.Length; i++) { \n\n // create a new DataRow\n DataRow dr=dt.NewRow();\n\n // convert the column Array List into an Array object for easier access\n Array ca=(Array)(ra.GetValue(i)); \n\n // add each field into the new DataRow\n for(int j=0; j < ca.Length; j++)\n dr[j]=ca.GetValue(j);\n\n // add the new DataRow to the DataTable\n dt.Rows.Add(dr);\n }\n\n // in case no data was parsed, create a single column\n if (dt.Columns.Count == 0)\n dt.Columns.Add(\"NoData\");\n\n return dt;\n}\n public DataTable ParseCSVFile(string path) {\n\n string inputString=\"\";\n\n // check that the file exists before opening it\n if (File.Exists(path)) {\n\n StreamReader sr = new StreamReader(path);\n inputString = sr.ReadToEnd();\n sr.Close();\n\n }\n\n return ParseCSV(inputString);\n}\n protected System.Web.UI.WebControls.DataGrid DataGrid1;\n\nprivate void Page_Load(object sender, System.EventArgs e) {\n\n // call the parser\n DataTable dt=ParseCSVFile(Server.MapPath(\"./demo.csv\")); \n\n // bind the resulting DataTable to a DataGrid Web Control\n DataGrid1.DataSource=dt;\n DataGrid1.DataBind();\n}\n"
},
{
"answer_id": 11617534,
"author": "Ted Spence",
"author_id": 419830,
"author_profile": "https://Stackoverflow.com/users/419830",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Read in a line of text, and use the Add() function to add these items to the current CSV structure\n/// </summary>\n/// <param name=\"s\"></param>\npublic static bool TryParseCSVLine(string s, char delimiter, char text_qualifier, out string[] array)\n{\n bool success = true;\n List<string> list = new List<string>();\n StringBuilder work = new StringBuilder();\n for (int i = 0; i < s.Length; i++) {\n char c = s[i];\n\n // If we are starting a new field, is this field text qualified?\n if ((c == text_qualifier) && (work.Length == 0)) {\n int p2;\n while (true) {\n p2 = s.IndexOf(text_qualifier, i + 1);\n\n // for some reason, this text qualifier is broken\n if (p2 < 0) {\n work.Append(s.Substring(i + 1));\n i = s.Length;\n success = false;\n break;\n }\n\n // Append this qualified string\n work.Append(s.Substring(i + 1, p2 - i - 1));\n i = p2;\n\n // If this is a double quote, keep going!\n if (((p2 + 1) < s.Length) && (s[p2 + 1] == text_qualifier)) {\n work.Append(text_qualifier);\n i++;\n\n // otherwise, this is a single qualifier, we're done\n } else {\n break;\n }\n }\n\n // Does this start a new field?\n } else if (c == delimiter) {\n list.Add(work.ToString());\n work.Length = 0;\n\n // Test for special case: when the user has written a casual comma, space, and text qualifier, skip the space\n // Checks if the second parameter of the if statement will pass through successfully\n // e.g. \"bob\", \"mary\", \"bill\"\n if (i + 2 <= s.Length - 1) {\n if (s[i + 1].Equals(' ') && s[i + 2].Equals(text_qualifier)) {\n i++;\n }\n }\n } else {\n work.Append(c);\n }\n }\n list.Add(work.ToString());\n\n // If we have nothing in the list, and it's possible that this might be a tab delimited list, try that before giving up\n if (list.Count == 1 && delimiter != DEFAULT_TAB_DELIMITER) {\n string[] tab_delimited_array = ParseLine(s, DEFAULT_TAB_DELIMITER, DEFAULT_QUALIFIER);\n if (tab_delimited_array.Length > list.Count) {\n array = tab_delimited_array;\n return success;\n }\n }\n\n // Return the array we parsed\n array = list.ToArray();\n return success;\n}\n /// <summary>\n/// Parse a line whose values may include newline symbols or CR/LF\n/// </summary>\n/// <param name=\"sr\"></param>\n/// <returns></returns>\npublic static string[] ParseMultiLine(StreamReader sr, char delimiter, char text_qualifier)\n{\n StringBuilder sb = new StringBuilder();\n string[] array = null;\n while (!sr.EndOfStream) {\n\n // Read in a line\n sb.Append(sr.ReadLine());\n\n // Does it parse?\n string s = sb.ToString();\n if (TryParseCSVLine(s, delimiter, text_qualifier, out array)) {\n return array;\n }\n }\n\n // Fails to parse - return the best array we were able to get\n return array;\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
300,673 | <p>I was told this a few times in this very site, but I wanted to make sure this is really the case.</p>
<p>I was expecting to be able to sprinkle NSLog function calls throughout my code, and that Xcode/gcc would automatically strip those calls out when building my Release/Distribution builds.</p>
<p>Should I avoid using this? If so, what alternatives are most common between experienced Objective-C programmers?</p>
| [
{
"answer_id": 300783,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 4,
"selected": false,
"text": "DEBUG_MODE DEBUG_MODE"
},
{
"answer_id": 302246,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 9,
"selected": true,
"text": "#define DEBUG_MODE\n\n#ifdef DEBUG_MODE\n #define DebugLog( s, ... ) NSLog( @\"<%p %@:(%d)> %@\", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )\n#else\n #define DebugLog( s, ... ) \n#endif\n #define DEBUG_MODE"
},
{
"answer_id": 1484866,
"author": "ohhorob",
"author_id": 178831,
"author_profile": "https://Stackoverflow.com/users/178831",
"pm_score": 5,
"selected": false,
"text": "DEBUG_MODE DEBUG_MODE NSLog DEBUG_MODE NSLog GCC_PREPROCESSOR_DEFINITIONS DEBUG_MODE=1 DEBUG_MODE GCC_PREPROCESSOR_DEFINITIONS DEBUG_MACRO // Target > Get Info > Build > GCC_PREPROCESSOR_DEFINITIONS\n// Configuration = Release: <empty>\n// = Debug: DEBUG_MODE=1\n"
},
{
"answer_id": 12798923,
"author": "mmmmmm",
"author_id": 151019,
"author_profile": "https://Stackoverflow.com/users/151019",
"pm_score": 2,
"selected": false,
"text": "[DDLog addLogger:[DDASLLogger sharedInstance]];\n[DDLog addLogger:[DDTTYLogger sharedInstance]];\n"
},
{
"answer_id": 14903471,
"author": "jww",
"author_id": 608639,
"author_profile": "https://Stackoverflow.com/users/608639",
"pm_score": 2,
"selected": false,
"text": "NSLog NSLog"
},
{
"answer_id": 17206296,
"author": "roel",
"author_id": 627794,
"author_profile": "https://Stackoverflow.com/users/627794",
"pm_score": 6,
"selected": false,
"text": "#ifndef DEBUG\n #define NSLog(...) /* suppress NSLog when in release mode */\n#endif\n DEBUG"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35478/"
] |
300,674 | <p>I'm trying to trouble shoot a web service client in my current project. I'm not sure of the platform of the Service Server (Most likely LAMP). I believe there is a fault on their side of the fence as i have eliminated the potential issues with my client. The client is a standard ASMX type web reference proxy auto generated from the service WSDL.</p>
<p>What I need to get to is the RAW SOAP Messages (Request and Responses)</p>
<p>What is the best way to go about this?</p>
| [
{
"answer_id": 300821,
"author": "John Lemp",
"author_id": 12915,
"author_profile": "https://Stackoverflow.com/users/12915",
"pm_score": 5,
"selected": false,
"text": "public class SoapLoggerExtension : SoapExtension\n{\n private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n private Stream oldStream;\n private Stream newStream;\n\n public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)\n {\n return null;\n }\n\n public override object GetInitializer(Type serviceType)\n {\n return null;\n }\n\n public override void Initialize(object initializer)\n {\n\n }\n\n public override System.IO.Stream ChainStream(System.IO.Stream stream)\n {\n oldStream = stream;\n newStream = new MemoryStream();\n return newStream;\n }\n\n public override void ProcessMessage(SoapMessage message)\n {\n\n switch (message.Stage)\n {\n case SoapMessageStage.BeforeSerialize:\n break;\n case SoapMessageStage.AfterSerialize:\n Log(message, \"AfterSerialize\");\n CopyStream(newStream, oldStream);\n newStream.Position = 0;\n break;\n case SoapMessageStage.BeforeDeserialize:\n CopyStream(oldStream, newStream);\n Log(message, \"BeforeDeserialize\");\n break;\n case SoapMessageStage.AfterDeserialize:\n break;\n }\n }\n\n public void Log(SoapMessage message, string stage)\n {\n\n newStream.Position = 0;\n string contents = (message is SoapServerMessage) ? \"SoapRequest \" : \"SoapResponse \";\n contents += stage + \";\";\n\n StreamReader reader = new StreamReader(newStream);\n\n contents += reader.ReadToEnd();\n\n newStream.Position = 0;\n\n log.Debug(contents);\n }\n\n void ReturnStream()\n {\n CopyAndReverse(newStream, oldStream);\n }\n\n void ReceiveStream()\n {\n CopyAndReverse(newStream, oldStream);\n }\n\n public void ReverseIncomingStream()\n {\n ReverseStream(newStream);\n }\n\n public void ReverseOutgoingStream()\n {\n ReverseStream(newStream);\n }\n\n public void ReverseStream(Stream stream)\n {\n TextReader tr = new StreamReader(stream);\n string str = tr.ReadToEnd();\n char[] data = str.ToCharArray();\n Array.Reverse(data);\n string strReversed = new string(data);\n\n TextWriter tw = new StreamWriter(stream);\n stream.Position = 0;\n tw.Write(strReversed);\n tw.Flush();\n }\n void CopyAndReverse(Stream from, Stream to)\n {\n TextReader tr = new StreamReader(from);\n TextWriter tw = new StreamWriter(to);\n\n string str = tr.ReadToEnd();\n char[] data = str.ToCharArray();\n Array.Reverse(data);\n string strReversed = new string(data);\n tw.Write(strReversed);\n tw.Flush();\n }\n\n private void CopyStream(Stream fromStream, Stream toStream)\n {\n try\n {\n StreamReader sr = new StreamReader(fromStream);\n StreamWriter sw = new StreamWriter(toStream);\n sw.WriteLine(sr.ReadToEnd());\n sw.Flush();\n }\n catch (Exception ex)\n {\n string message = String.Format(\"CopyStream failed because: {0}\", ex.Message);\n log.Error(message, ex);\n }\n }\n}\n\n[AttributeUsage(AttributeTargets.Method)]\npublic class SoapLoggerExtensionAttribute : SoapExtensionAttribute\n{\n private int priority = 1; \n\n public override int Priority\n {\n get { return priority; }\n set { priority = value; }\n }\n\n public override System.Type ExtensionType\n {\n get { return typeof (SoapLoggerExtension); }\n }\n}\n <webServices>\n <soapExtensionTypes>\n <add type=\"YourNamespace.SoapLoggerExtension, YourAssembly\" \n priority=\"1\" group=\"0\" />\n </soapExtensionTypes>\n</webServices>\n"
},
{
"answer_id": 428223,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": true,
"text": "web.config trace.log <system.diagnostics>\n <trace autoflush=\"true\"/>\n <sources>\n <source name=\"System.Net\" maxdatasize=\"1024\">\n <listeners>\n <add name=\"TraceFile\"/>\n </listeners>\n </source>\n <source name=\"System.Net.Sockets\" maxdatasize=\"1024\">\n <listeners>\n <add name=\"TraceFile\"/>\n </listeners>\n </source>\n </sources>\n <sharedListeners>\n <add name=\"TraceFile\" type=\"System.Diagnostics.TextWriterTraceListener\"\n initializeData=\"trace.log\"/>\n </sharedListeners>\n <switches>\n <add name=\"System.Net\" value=\"Verbose\"/>\n <add name=\"System.Net.Sockets\" value=\"Verbose\"/>\n </switches>\n</system.diagnostics>\n"
},
{
"answer_id": 627239,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public class LoggerSoapExtension : SoapExtension\n{\n private static readonly string LOG_DIRECTORY = ConfigurationManager.AppSettings[\"LOG_DIRECTORY\"];\n private LogStream _logger;\n\n public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)\n {\n return null;\n }\n public override object GetInitializer(Type serviceType)\n {\n return null;\n }\n public override void Initialize(object initializer)\n {\n }\n public override System.IO.Stream ChainStream(System.IO.Stream stream)\n {\n _logger = new LogStream(stream);\n return _logger;\n }\n public override void ProcessMessage(SoapMessage message)\n {\n if (LOG_DIRECTORY != null)\n {\n switch (message.Stage)\n {\n case SoapMessageStage.BeforeSerialize:\n _logger.Type = \"request\";\n break;\n case SoapMessageStage.AfterSerialize:\n break;\n case SoapMessageStage.BeforeDeserialize:\n _logger.Type = \"response\";\n break;\n case SoapMessageStage.AfterDeserialize:\n break;\n }\n }\n }\n internal class LogStream : Stream\n {\n private Stream _source;\n private Stream _log;\n private bool _logSetup;\n private string _type;\n\n public LogStream(Stream source)\n {\n _source = source;\n }\n internal string Type\n {\n set { _type = value; }\n }\n private Stream Logger\n {\n get\n {\n if (!_logSetup)\n {\n if (LOG_DIRECTORY != null)\n {\n try\n {\n DateTime now = DateTime.Now;\n string folder = LOG_DIRECTORY + now.ToString(\"yyyyMMdd\");\n string subfolder = folder + \"\\\\\" + now.ToString(\"HH\");\n string client = System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null && System.Web.HttpContext.Current.Request.UserHostAddress != null ? System.Web.HttpContext.Current.Request.UserHostAddress : string.Empty;\n string ticks = now.ToString(\"yyyyMMdd'T'HHmmss.fffffff\");\n if (!Directory.Exists(folder))\n Directory.CreateDirectory(folder);\n if (!Directory.Exists(subfolder))\n Directory.CreateDirectory(subfolder);\n _log = new FileStream(new System.Text.StringBuilder(subfolder).Append('\\\\').Append(client).Append('_').Append(ticks).Append('_').Append(_type).Append(\".xml\").ToString(), FileMode.Create);\n }\n catch\n {\n _log = null;\n }\n }\n _logSetup = true;\n }\n return _log;\n }\n }\n public override bool CanRead\n {\n get\n {\n return _source.CanRead;\n }\n }\n public override bool CanSeek\n {\n get\n {\n return _source.CanSeek;\n }\n }\n\n public override bool CanWrite\n {\n get\n {\n return _source.CanWrite;\n }\n }\n\n public override long Length\n {\n get\n {\n return _source.Length;\n }\n }\n\n public override long Position\n {\n get\n {\n return _source.Position;\n }\n set\n {\n _source.Position = value;\n }\n }\n\n public override void Flush()\n {\n _source.Flush();\n if (Logger != null)\n Logger.Flush();\n }\n\n public override long Seek(long offset, SeekOrigin origin)\n {\n return _source.Seek(offset, origin);\n }\n\n public override void SetLength(long value)\n {\n _source.SetLength(value);\n }\n\n public override int Read(byte[] buffer, int offset, int count)\n {\n count = _source.Read(buffer, offset, count);\n if (Logger != null)\n Logger.Write(buffer, offset, count);\n return count;\n }\n\n public override void Write(byte[] buffer, int offset, int count)\n {\n _source.Write(buffer, offset, count);\n if (Logger != null)\n Logger.Write(buffer, offset, count);\n }\n public override int ReadByte()\n {\n int ret = _source.ReadByte();\n if (ret != -1 && Logger != null)\n Logger.WriteByte((byte)ret);\n return ret;\n }\n public override void Close()\n {\n _source.Close();\n if (Logger != null)\n Logger.Close();\n base.Close();\n }\n public override int ReadTimeout\n {\n get { return _source.ReadTimeout; }\n set { _source.ReadTimeout = value; }\n }\n public override int WriteTimeout\n {\n get { return _source.WriteTimeout; }\n set { _source.WriteTimeout = value; }\n }\n }\n}\n[AttributeUsage(AttributeTargets.Method)]\npublic class LoggerSoapExtensionAttribute : SoapExtensionAttribute\n{\n private int priority = 1;\n public override int Priority\n {\n get\n {\n return priority;\n }\n set\n {\n priority = value;\n }\n }\n public override System.Type ExtensionType\n {\n get\n {\n return typeof(LoggerSoapExtension);\n }\n }\n}\n"
},
{
"answer_id": 2609977,
"author": "Chuck Bevitt",
"author_id": 313077,
"author_profile": "https://Stackoverflow.com/users/313077",
"pm_score": 3,
"selected": false,
"text": "namespace ChuckBevitt\n{\n class GetRawResponseSoapExtension : SoapExtension\n {\n //must override these three methods\n public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)\n {\n return null;\n }\n public override object GetInitializer(Type serviceType)\n {\n return null;\n }\n public override void Initialize(object initializer)\n {\n }\n\n private bool IsResponse = false;\n\n public override void ProcessMessage(SoapMessage message)\n {\n //Note that ProcessMessage gets called AFTER ChainStream.\n //That's why I'm looking for AfterSerialize, rather than BeforeDeserialize\n if (message.Stage == SoapMessageStage.AfterSerialize)\n IsResponse = true;\n else\n IsResponse = false;\n }\n\n public override Stream ChainStream(Stream stream)\n {\n if (IsResponse)\n {\n StreamReader sr = new StreamReader(stream);\n string response = sr.ReadToEnd();\n sr.Close();\n sr.Dispose();\n\n File.WriteAllText(@\"C:\\test.txt\", response);\n\n byte[] ResponseBytes = Encoding.ASCII.GetBytes(response);\n MemoryStream ms = new MemoryStream(ResponseBytes);\n return ms;\n\n }\n else\n return stream;\n }\n }\n}\n <configuration>\n ...\n <system.web>\n <webServices>\n <soapExtensionTypes>\n <add type=\"ChuckBevitt.GetRawResponseSoapExtension, TestCallWebService\"\n priority=\"1\" group=\"0\" />\n </soapExtensionTypes>\n </webServices>\n </system.web>\n</configuration>\n public override void ProcessMessage(SoapMessage message)\n{\n if (message.Stage == SoapMessageStage.BeforeDeserialize)\n {\n StreamReader sr = new StreamReader(message.Stream);\n File.WriteAllText(@\"C:\\test.txt\", sr.ReadToEnd());\n message.Stream.Position = 0; //Will blow up 'cause type of stream (\"ConnectStream\") doesn't alow seek so can't reset position\n }\n}\n"
},
{
"answer_id": 28099938,
"author": "Bimmerbound",
"author_id": 4446207,
"author_profile": "https://Stackoverflow.com/users/4446207",
"pm_score": 5,
"selected": false,
"text": "XmlSerializer xmlSerializer = new XmlSerializer(myEnvelope.GetType());\n\nusing (StringWriter textWriter = new StringWriter())\n{\n xmlSerializer.Serialize(textWriter, myEnvelope);\n return textWriter.ToString();\n}\n"
},
{
"answer_id": 33043446,
"author": "user2366842",
"author_id": 2366842,
"author_profile": "https://Stackoverflow.com/users/2366842",
"pm_score": -1,
"selected": false,
"text": " Shared Function returnSerializedXML(ByVal obj As Object) As String\n Dim xmlSerializer As New System.Xml.Serialization.XmlSerializer(obj.GetType())\n Dim xmlSb As New StringBuilder\n Using textWriter As New IO.StringWriter(xmlSb)\n xmlSerializer.Serialize(textWriter, obj)\n End Using\n\n\n returnSerializedXML = xmlSb.ToString().Replace(vbCrLf, \"\")\n\nEnd Function\n"
},
{
"answer_id": 59582864,
"author": "Collin Anderson",
"author_id": 131881,
"author_profile": "https://Stackoverflow.com/users/131881",
"pm_score": 2,
"selected": false,
"text": "<configuration> web.config App.config trace.log bin/Debug initializeData <system.diagnostics>\n <trace autoflush=\"true\"/>\n <sources>\n <source name=\"System.Net\" maxdatasize=\"9999\" tracemode=\"protocolonly\">\n <listeners>\n <add name=\"TraceFile\" type=\"System.Diagnostics.TextWriterTraceListener\" initializeData=\"trace.log\"/>\n </listeners>\n </source>\n </sources>\n <switches>\n <add name=\"System.Net\" value=\"Verbose\"/>\n </switches>\n </system.diagnostics>\n maxdatasize tracemode"
},
{
"answer_id": 69914372,
"author": "Spilto",
"author_id": 16537752,
"author_profile": "https://Stackoverflow.com/users/16537752",
"pm_score": 0,
"selected": false,
"text": "OperationContext.Current.RequestContext.RequestMessage\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30576/"
] |
300,685 | <p>I would like to generate documentation for a RESTful web service API that is written in Python. Ideally it would look like Yahoo's RESTful web service docs. Does anyone have any ideas or references?</p>
| [
{
"answer_id": 5044368,
"author": "stw_dev",
"author_id": 206484,
"author_profile": "https://Stackoverflow.com/users/206484",
"pm_score": 2,
"selected": false,
"text": "restapi.py src src conf.py import sys, os\nsys.path.append(os.path.abspath('sphinxext'))\nextensions = ['sphinx.ext.autodoc']\n\nsys.path.append(os.path.abspath('src'))\n .. automodule:: restapi\n :members:\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14311/"
] |
300,692 | <p>I'd like to know how to convert Perforce depot locations to client view locations for the purpose of script writing.</p>
<p>I have a script that first checks out a file for edit in perforce and then interacts with the file. I need to have the depot location (i.e. \Projects\Project6) converted to the client view location. (i.e. d:\Projects\Project6).</p>
<p>Is this possible?</p>
| [
{
"answer_id": 300701,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 2,
"selected": false,
"text": "p4 have"
},
{
"answer_id": 300772,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 4,
"selected": false,
"text": "where -- Show how file names map through the client view\n\np4 where [ file ... ]\n\n Where shows how the named files map through the client view.\n For each argument, three names are produced: the name in the\n depot, the name on the client in Perforce syntax, and the name\n on the client in local syntax.\n\n If no file is given, the mapping for '...' (all files in the\n current directory and below) is shown.\n\n Note that 'p4 where' does not determine where any real files are.\n It only computes where they should be according to the client view.\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38774/"
] |
300,705 | <p>I have the following code:</p>
<pre><code>for attribute in site.device_attributes
device.attribute
end
</code></pre>
<p>where I would like the code to substitute the value of "attribute" for the method name.</p>
<p>I have tried <code>device."#{attribute}"</code> and various permutations.</p>
<p>Is this completely impossible? Am I missing something?</p>
<p>I have considered overriding method_missing, but I can't figure out how that would actually help me when my problem is that I need to call an "unknown" method.</p>
| [
{
"answer_id": 300723,
"author": "Matt Campbell",
"author_id": 27043,
"author_profile": "https://Stackoverflow.com/users/27043",
"pm_score": 4,
"selected": false,
"text": "object = \"upcase me!\"\nmethod = \"upcase\"\nobject.send(method.to_sym) # => \"UPCASE ME!\"\n"
},
{
"answer_id": 300805,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 2,
"selected": false,
"text": "device.instance_eval(attribute)\n"
},
{
"answer_id": 301849,
"author": "Maxim Kulkin",
"author_id": 1142754,
"author_profile": "https://Stackoverflow.com/users/1142754",
"pm_score": 7,
"selected": true,
"text": "object.send(:foo) # same as object.foo\n object.send(:foo, 1, \"bar\", 1.23) # same as object.foo(1, \"bar\", 1.23)\n object.send(attribute.to_sym)\n object.send(\"#{attribute}=\".to_sym, value)\n object.instance_eval {\n # code as block, can reference variables in current scope\n}\n\n# or\n\nobject.instance_eval <<-CODE\n # code as string, can generate any code text\nCODE\n public_send object.public_send :public_foo # ok\nobject.public_send :private_bar # exception\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/757/"
] |
300,746 | <p>I've been attempting to write embedded SQL statements for DB2 that ultimately gets compiled in C. </p>
<p>I couldn't find a tutorial or manual on the embedded SQL syntax for C for reference. One case I would like to do is to insert data into a table. I know most embedded sql statements need the initalizer <code>EXEC SQL</code>, but that's the extent of my knowledge generally. I'm doing this for an assignment and would appreciate if there are more information regarding this or solution. </p>
<p>Example of a statement to query the database:</p>
<pre><code>EXEC SQL SELECT SNAME, AGE into :sname, :sage
FROM ONE.SAILOR
WHERE sid = :sid;
</code></pre>
<p>I like to see what statement allows me to INSERT into the database. I've tried something like the following, but it doesn't work.</p>
<pre><code> EXEC SQL INSERT ....
</code></pre>
| [
{
"answer_id": 301082,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "EXEC SQL INSERT INTO SomeTable(Col1, Col2, Col3) VALUES(:hv1, :hv2, :hv3);\n EXEC SQL INSERT INTO SomeTable VALUES(:hv1, :hv2, :hv3);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38781/"
] |
300,749 | <p>Is it possible to protect flv files from download? I'd like to protect my files from download but I don't have the money for a streaming server which I think provides some sort of protection. The files are streamed via PHP and are located in an upload folder on my server.</p>
<p>I've used PHP to ensure that only subscribers can view the video but I basically want to go a step further and prevent subscribers from, upon login, downloading my videos with downloaders such as Sothink Flv Downloader for Firefox.</p>
| [
{
"answer_id": 1650655,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 5,
"selected": false,
"text": "FLV FLV"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
300,755 | <p>Ok... I'm new to WPF, but I kind of know how to do things using DataTriggers and Converters.</p>
<p>But, what I want to seems a little more complex than that. Let me give you the details:</p>
<p>The DataContext for the ListView control is an IList of objects (object=Room). These are the available rooms. I've got another control (let's say it's a TextBox) that it bound to one of the Room objects contained in the IList. I want to display an image only for the room (ListViewItem) that is bound to the other control.</p>
<p>This is some of my XAML:</p>
<pre><code><TextBox Name="Room" />
<ListView Name="RoomsList" SelectionMode="Single">
<ListView.View>
<GridView>
<GridViewColumn Width="32">
<GridViewColumn.CellTemplate>
<DataTemplate>
<!--
Here's where I want to change the Source property
depending on whether or not the item matches the
TextBox DataContext.
-->
<Image Source="Images/Check.png" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Room Name" Width="150" HeaderContainerStyle="{StaticResource textHeaderStyle}"
DisplayMemberBinding="{Binding Path=RoomName}" />
</GridView>
</ListView.View>
</ListView>
</code></pre>
<p>I'm kind of stuck on this one. Any ideas as to how to approach this?</p>
| [
{
"answer_id": 302113,
"author": "Bryan Anderson",
"author_id": 21186,
"author_profile": "https://Stackoverflow.com/users/21186",
"pm_score": 0,
"selected": false,
"text": "<TextBox Name=\"Room\" Text=\"{Binding ElementName=RoomsList.SelectedItem, Path=Picture}\" />\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21807/"
] |
300,757 | <p>I have a Flex application with multiple modules.</p>
<p>When I redeploy the application I was finding that modules (which are deployed as separate swf files) were being cached in the browser and the new versions weren't being loaded. </p>
<p>So i tried the age old trick of adding <code>?version=xxx</code> to all the modules when they are loaded. The value <code>xxx</code> is a global parameter which is actually stored in the host html page:</p>
<pre><code>var moduleSection:ModuleLoaderSection;
moduleSection = new ModuleLoaderSection();
moduleSection.visible = false;
moduleSection.moduleName = moduleName + "?version=" + MySite.masterVersion;
</code></pre>
<p>In addition I needed to add <code>?version=xxx</code> to the main .swf that was being loaded. Since this is done by HTML I had to do this by modifying my AC_OETags.js file as below :</p>
<pre><code>function AC_FL_RunContent(){
var ret =
AC_GetArgs
( arguments, ".swf?mv=" + getMasterVersion(), "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
, "application/x-shockwave-flash"
);
AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
</code></pre>
<p>This is all fine and works great. I just have a hard time believing that Adobe doesn't already have a way to handle this. Given that Flex is being targeted to design modular applications for business I find it especially surprising.</p>
<p>What do other people do? I need to make sure my application reloads correctly even if someone has <code>once per session</code> selected for their 'browser cache checking policy'.</p>
| [
{
"answer_id": 2916434,
"author": "user349449",
"author_id": 349449,
"author_profile": "https://Stackoverflow.com/users/349449",
"pm_score": 1,
"selected": false,
"text": " function AC_FL_RunContent(){\n var ret = AC_GetArgs(arguments, \".swf?ts=\" + getTS(), \"movie\", \n \"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\",\n \"application/x-shockwave-flash\");\n AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); \n }\n\n function getTS() {\n var ts = new Date().getTime();\n return ts;\n }\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
300,786 | <p>We have an application that generates simulated data for one of our services for testing purposes. Each data item has a unique Guid. However, when we ran a test after some minor code changes to the simulator all of the objects generated by it had the same Guid.</p>
<p>There was a single data object created, then a for loop where the properties of the object were modified, including a new unique Guid, and it was sent to the service via remoting (serializable, not marshal-by-ref, if that's what you're thinking), loop and do it again, etc.</p>
<p>If we put a small Thread.Sleep( ...) inside of the loop, it generated unique id's. I think that is a red-herring though. I created a test app that just created one guid after another and didn't get a single duplicate.</p>
<p>My theory is that the IL was optimized in a way that caused this behavior. But enough about my theories. What do YOU think? I'm open to suggestions and ways to test it.</p>
<p>UPDATE: There seems to be a lot of confusion about my question, so let me clarify. I DON'T think that NewGuid() is broken. Clearly it works. Its FINE! There is a bug somewhere though, that causes NewGuid() to either:
1) be called only once in my loop
2) be called everytime in my loop but assigned only once
3) something else I haven't thought of</p>
<p>This bug can be in my code (MOST likely) or in optimization somewhere.</p>
<p>So to reiterate my question, how should I debug this scenario? </p>
<p>(and thank you for the great discussion, this is really helping me clarify the problem in my mind) </p>
<p>UPDATE # 2: I'd love to post an example that shows the problem, but that's part of my problem. I can't duplicate it outside of the whole suite of applications (client and servers).</p>
<p>Here's a relevant snippet though:</p>
<pre><code>OrderTicket ticket = new OrderTicket(... );
for( int i = 0; i < _numOrders; i++ )
{
ticket.CacheId = Guid.NewGuid();
Submit( ticket ); // note that this simply makes a remoting call
}
</code></pre>
| [
{
"answer_id": 303936,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 5,
"selected": true,
"text": "for( int i = 0; i < _numOrders; i++ )\n{\n OrderTicket ticket = new OrderTicket(... );\n ticket.CacheId = Guid.NewGuid();\n Submit( ticket ); // note that this simply makes a remoting call\n}\n ticket.CacheId = new Guid(\"00000000-0000-0000-0000-\" + \n string.Format(\"{0:000000000000}\", i));\n"
},
{
"answer_id": 303997,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 0,
"selected": false,
"text": "class OrderTicket \n{\n Guid CacheId {set {_guid = new Guid(\"00000000-0000-0000-0000-\");}\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29021/"
] |
300,793 | <p>Building an iPhone project results in: </p>
<blockquote>
<p>Failed to launch simulated application: SpringBoard failed to launch application with error: 7</p>
</blockquote>
<p>And the app doesn't install on the simulator. What's this all about? What's SpringBoard and what is error 7?</p>
| [
{
"answer_id": 548034,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "sudo mkdir /usr/local/iphone-dirs sudo chmod 777 /usr/local/iphone-dirs mkdir /usr/local/iphone-dirs/my-dir cd \"~/Library/Application Support/\" rm -rf \"iPhone Simulator/\" ln -s /usr/local/iphone-dirs/my-dir/ \"iPhone Simulator\""
},
{
"answer_id": 3705982,
"author": "HotFudgeSunday",
"author_id": 435131,
"author_profile": "https://Stackoverflow.com/users/435131",
"pm_score": 0,
"selected": false,
"text": "2010-09-13 23:30:27.149 Appname[5580:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle:\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
300,808 | <p>I have been working on a legacy C++ application and am definitely outside of my comfort-zone (a good thing). I was wondering if anyone out there would be so kind as to give me a few pointers (pun intended).</p>
<p>I need to cast 2 bytes in an unsigned char array to an unsigned short. The bytes are consecutive. </p>
<p>For an example of what I am trying to do:</p>
<p>I receive a string from a socket and place it in an unsigned char array. I can ignore the first byte and then the next 2 bytes should be converted to an unsigned char. This will be on windows only so there are no Big/Little Endian issues (that I am aware of).</p>
<p>Here is what I have now (not working obviously):</p>
<pre><code>//packetBuffer is an unsigned char array containing the string "123456789" for testing
//I need to convert bytes 2 and 3 into the short, 2 being the most significant byte
//so I would expect to get 515 (2*256 + 3) instead all the code I have tried gives me
//either errors or 2 (only converting one byte
unsigned short myShort;
myShort = static_cast<unsigned_short>(packetBuffer[1])
</code></pre>
| [
{
"answer_id": 300812,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 1,
"selected": false,
"text": "unsigned short *myShort = static_cast<unsigned short*>(&packetBuffer[1]);\n"
},
{
"answer_id": 300837,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": true,
"text": "static_cast unsigned char* unsigned short* void* unsigned short* unsigned short *p = static_cast<unsigned short*>(static_cast<void*>(&packetBuffer[1]));\n unsigned short p = (packetBuffer[1] << 8) | packetBuffer[2];\n"
},
{
"answer_id": 300844,
"author": "PiNoYBoY82",
"author_id": 13646,
"author_profile": "https://Stackoverflow.com/users/13646",
"pm_score": 2,
"selected": false,
"text": "unsigned short myShort = *(unsigned short *)&packetBuffer[1];\n"
},
{
"answer_id": 300930,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 0,
"selected": false,
"text": "/* If it is a string as explicitly stated in the question.\n */\nint byte1 = packetBuffer[1] - '0'; // convert 1st byte from char to number.\nint byte2 = packetBuffer[2] - '0';\n\nunsigned short result = (byte1 * 256) + byte2;\n\n/* Alternatively if is an array of bytes.\n */\nint byte1 = packetBuffer[1];\nint byte2 = packetBuffer[2];\n\nunsigned short result = (byte1 * 256) + byte2;\n"
},
{
"answer_id": 301125,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "char packetBuffer[] = {1, 2, 3};\nunsigned short myShort = * reinterpret_cast<unsigned short*>(&packetBuffer[1]);\n"
},
{
"answer_id": 307299,
"author": "old_timer",
"author_id": 16007,
"author_profile": "https://Stackoverflow.com/users/16007",
"pm_score": 2,
"selected": false,
"text": "unsigned short p = (packetBuffer[1] << 8) | packetBuffer[2];\n packetBuffer packetBuffer packetBuffer[2]; unsigned short p;\np = packetBuffer[1]; p <<= 8; p |= packetBuffer[2];\n unsigned short p;\np = (((unsigned short)packetBuffer[1])<<8) | packetBuffer[2];\n unsigned short *s;\nunsigned char b[10];\n\ns=(unsigned short *)&b[0];\n\nif(b[0]&7)\n{\n *s = *s+8;\n *s &= ~7;\n}\n\ndo_something_With(b);\n\n*s=*s+8;\n\ndo_something_With(b);\n\n*s=*s+8;\n\ndo_something_With(b);\n b do_something_with() *s *s *s s"
},
{
"answer_id": 308495,
"author": "Richard",
"author_id": 19897,
"author_profile": "https://Stackoverflow.com/users/19897",
"pm_score": 0,
"selected": false,
"text": "unsigned short i = MAKEWORD(lowbyte,hibyte);\n"
},
{
"answer_id": 16673014,
"author": "ilkayaktas",
"author_id": 1835827,
"author_profile": "https://Stackoverflow.com/users/1835827",
"pm_score": 2,
"selected": false,
"text": "union CharToStruct {\n char charArray[2];\n unsigned short value;\n};\n\n\nshort toShort(char* value){\n CharToStruct cs;\n cs.charArray[0] = value[1]; // most significant bit of short is not first bit of char array\n cs.charArray[1] = value[0];\n return cs.value;\n}\n char array[2]; \narray[0] = 0x00;\narray[1] = 0x03;\nshort i = toShort(array);\ncout << i << endl; // or printf(\"%h\", i);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38784/"
] |
300,840 | <p>We have some integer arithmetic which for historical reasons has to work the same on PHP as it does in a few statically typed languages. Since we last upgraded PHP the behavior for overflowing integers has changed. Basically we are using following formula:</p>
<pre><code>function f($x1, $x2, $x3, $x4)
{
return (($x1 + $x2) ^ $x3) + $x4;
}
</code></pre>
<p>However, even with conversions:</p>
<pre><code>function f($x1, $x2, $x3, $x4)
{
return intval(intval(intval($x1 + $x2) ^ $x3) + $x4);
}
</code></pre>
<p>I am still ending up with the completely wrong number...</p>
<p>For example, with $x1 = -1580033017, $x2 = -2072974554, $x3 = -1170476976) and $x4 = -1007518822, I end up with -30512150 in PHP and 1617621783 in C#.</p>
<p>Just adding together $x1 and $x2 I cannot get the right answer:</p>
<p>In C# I get</p>
<pre><code>(-1580033017 + -2072974554) = 641959725
</code></pre>
<p>In PHP:</p>
<pre><code>intval(intval(-1580033017) + intval(-2072974554)) = -2147483648
</code></pre>
<p>which is the same as:</p>
<pre><code>intval(-1580033017 + -2072974554) = -2147483648
</code></pre>
<p>I don't mind writing a "IntegerOverflowAdd" function or something, but I can't quite figure out how (-1580033017 + -2072974554) equals 641959725. (I do recognize that it is -2147483648 + (2 * 2^31), but -2147483648 + 2^31 is -1505523923 which is greater than Int.Min so why is do you add 2*2^31 and not 2^31?)</p>
<p>Any help would be appreciated...</p>
| [
{
"answer_id": 300857,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "echo (-1580033017 + -2072974554) & 0xffffffff\n function s32add($a, $b) {\n return ($a + $b) & 0xffffffff;\n}\n"
},
{
"answer_id": 300902,
"author": "JasonMichael",
"author_id": 1935,
"author_profile": "https://Stackoverflow.com/users/1935",
"pm_score": 1,
"selected": false,
"text": "$x1 = -1580033017; \n$x2 = -2072974554; \n$x3 = -1170476976 ; \n$x4 = -1007518822;\necho f($x1, $x2, $x3, $x4);\n\nfunction f($x1, $x2, $x3, $x4)\n{\n return intval(intval(intval($x1 + $x2) ^ $x3) + $x4);\n}\n"
},
{
"answer_id": 303856,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 5,
"selected": true,
"text": "<?php\necho \"Php max int: \".PHP_INT_MAX.\"\\n\";\necho \"The Val: \".(-1580033017 + -2072974554).\"\\n\";\necho \"Intval of the val: \".intval(-3653007571).\"\\n\";\necho \"And 0xffffffff of the val: \".(-3653007571 & 0xffffffff).\"\\n\";\n?>\n Php max int: 2147483647\nThe Val: -3653007571\nIntval of the val: -2147483648\nAnd of the val: -2147483648\n Php max int: 2147483647\nThe Val: -3653007571\nIntval of the val: -641959725\nAnd of the val: -641959725\n Php max int: 2147483647\nThe Val: -3653007571\nIntval of the val: -3653007571\nAnd of the val: -641959725\n function thirtyTwoBitIntval($value)\n{\n if ($value < -2147483648)\n {\n return -(-($value) & 0xffffffff);\n }\n elseif ($value > 2147483647)\n {\n return ($value & 0xffffffff);\n }\n return $value;\n}\n"
},
{
"answer_id": 2123458,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "function intval32bits($value)\n{\n $value = ($value & 0xFFFFFFFF);\n\n if ($value & 0x80000000)\n $value = -((~$value & 0xFFFFFFFF) + 1);\n\n return $value;\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
300,841 | <p>How do you globally set the date format in ASP.NET?</p>
<p>My local machine and servers have Regional Settings set to "English (New Zealand)".</p>
<p>When I format a date with <code>dd/MM/yyyy</code> I expect to see <code>19/11/2008</code> for today for example.</p>
<p>Until recently, that is what I did in fact get from both my local machine and the servers.</p>
<p>Just recently, for some mysterious reason, our local machines have changed ever so slightly. Despite still be set to "English (New Zealand)", the date delimter has changed from <code>/</code> to <code>-</code>! The same change has not occurred on the servers which still show "English (New Zealand)" and the <code>/</code> for the date delimter.</p>
<p>So now for my local machine, for the format <code>dd/MM/yyyy</code> I get <code>19-11-2008</code> instead of <code>19/11/2008</code>.</p>
<p>This is a little disconcerting.</p>
<p>The only way around it that I can see so far is to escape the slashes and set the format to <code>dd\/MM\/yyyy</code>. It seems to work, but it doesn't seem to be the ideal solution.</p>
<p>Can anyone please help?</p>
<p>NOTE: This is for an intranet application and I do not care about true globalisation. I just want to fix the date format and not have it change on me.</p>
| [
{
"answer_id": 300853,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": true,
"text": "using System.Globalization;\nusing System.Threading;\n\n//...\nprotected void Application_BeginRequest(Object sender, EventArgs e)\n{ \n CultureInfo newCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();\n newCulture.DateTimeFormat.ShortDatePattern = \"dd-MMM-yyyy\";\n newCulture.DateTimeFormat.DateSeparator = \"-\";\n Thread.CurrentThread.CurrentCulture = newCulture;\n}\n"
},
{
"answer_id": 300885,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 2,
"selected": false,
"text": "\nusing System.Globalization;\nusing System.Threading;\n\n//...\nprotected void Application_BeginRequest(Object sender, EventArgs e)\n{\n Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo(\"en-NZ\");\n}\n"
},
{
"answer_id": 837751,
"author": "Serapth",
"author_id": 101767,
"author_profile": "https://Stackoverflow.com/users/101767",
"pm_score": 6,
"selected": false,
"text": "<system.web>\n <globalization culture=\"en-NZ\" uiCulture=\"en-NZ\"/>\n</system.web>\n"
},
{
"answer_id": 19802871,
"author": "cmujica",
"author_id": 491479,
"author_profile": "https://Stackoverflow.com/users/491479",
"pm_score": 3,
"selected": false,
"text": "<system.web> \n<globalization uiCulture=\"en\" culture=\"en-NZ\" />\n</system.web>\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19377/"
] |
300,849 | <p>I'm creating a small app in ASP.NET MVC that generates ics (iCal) files based on certain criterias. The generated files are accessible through a permanent URL (<a href="http://myserver/some/criterias.ics" rel="noreferrer">http://myserver/some/criterias.ics</a>).</p>
<p>I am looking for a way to display the calendar data on the page to give the user a preview of the generated file. Ideally, I'd like a Google Calendar type interface embedded in the page. Unfortunately, Google Calendar only seems to allow embedding calendars that have previously been added to their system.</p>
<p>Is there any free service or library that will allow me to embed a calendar for an arbitrary ics file on my site?</p>
| [
{
"answer_id": 700183,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Other Calenders"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5903/"
] |
300,854 | <p>Okay, I guess this is entirely subjective and whatnot, but I was thinking about entropy sources for random number generators. It goes that most generators are seeded with the current time, correct? Well, I was curious as to what other sources could be used to generate perfectly valid, random (The loose definition) numbers.</p>
<p>Would using multiple sources (Such as time + current HDD seek time [We're being fantastical here]) together create a "more random" number than a single source? What are the logical limits of the amount of sources? How much is really enough? Is the time chosen simply because it is convenient?</p>
<p>Excuse me if this sort of thing is not allowed, but I'm curious as to the theory behind the sources.</p>
| [
{
"answer_id": 523971,
"author": "klew",
"author_id": 58877,
"author_profile": "https://Stackoverflow.com/users/58877",
"pm_score": 0,
"selected": false,
"text": "int Random() {\n return Universe.object_id % MAX_INT;\n}\n"
},
{
"answer_id": 10201602,
"author": "pr1268",
"author_id": 512961,
"author_profile": "https://Stackoverflow.com/users/512961",
"pm_score": 1,
"selected": false,
"text": "/dev/urandom /proc /proc /proc/meminfo /proc/self/maps /proc/self/smaps /proc/interrupts /proc/diskstats /proc/self/stat /proc /proc/self/*"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31389/"
] |
300,855 | <p>I've looked into and considered many JavaScript unit tests and testing tools, but have been unable to find a suitable option to remain fully TDD compliant. So, is there a JavaScript unit test tool that is fully TDD compliant?</p>
| [
{
"answer_id": 680713,
"author": "gregers",
"author_id": 44643,
"author_profile": "https://Stackoverflow.com/users/44643",
"pm_score": 12,
"selected": true,
"text": "assert(!...) expect(...).not... refute(...) Buster.JS Buster.js"
},
{
"answer_id": 7660264,
"author": "kolen",
"author_id": 123642,
"author_profile": "https://Stackoverflow.com/users/123642",
"pm_score": 4,
"selected": false,
"text": "$tearDown $verifyAll"
},
{
"answer_id": 8811110,
"author": "alex.c",
"author_id": 1141866,
"author_profile": "https://Stackoverflow.com/users/1141866",
"pm_score": 2,
"selected": false,
"text": "@RunWith(STJSTestDriverRunner.class)\n@HTMLFixture(\"<div id='fortune'></div>\")\n\n@Scripts({ \"classpath://jquery.js\",\n \"classpath://jquery.mockjax.js\", \"classpath://json2.js\" })\npublic class MockjaxExampleTest {\n @Test\n public void myTest() {\n $.ajaxSetup($map(\"async\", false));\n $.mockjax(new MockjaxOptions() {\n {\n url = \"/restful/fortune\";\n responseText = new Fortune() {\n {\n status = \"success\";\n fortune = \"Are you a turtle?\";\n }\n };\n }\n });\n\n $.getJSON(\"/restful/fortune\", null, new Callback3<Fortune, String, JQueryXHR>() {\n @Override\n public void $invoke(Fortune response, String p2, JQueryXHR p3) {\n if (response.status.equals(\"success\")) {\n $(\"#fortune\").html(\"Your fortune is: \" + response.fortune);\n } else {\n $(\"#fortune\").html(\"Things do not look good, no fortune was told\");\n }\n\n }\n });\n assertEquals(\"Your fortune is: Are you a turtle?\", $(\"#fortune\").html());\n }\n\n private static class Fortune {\n public String status;\n public String fortune;\n }\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38792/"
] |
300,871 | <p>Given a point (pX, pY) and a circle with a known center (cX,cY) and radius (r), what is the shortest amount of code you can come up with to find the point on the circle closest to (pX, pY) ?</p>
<p>I've got some code kind of working but it involves converting the circle to an equation of the form (x - cX)^2 + (y - cY)^2 = r^2 (where r is radius) and using the equation of the line from point (pX, pY) to (cX, cY) to create a quadratic equation to be solved.</p>
<p>Once I iron out the bugs it'll do, but it seems such an inelegant solution.</p>
| [
{
"answer_id": 300894,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 7,
"selected": true,
"text": "V = (P - C); Answer = C + V / |V| * R;\n double vX = pX - cX;\ndouble vY = pY - cY;\ndouble magV = sqrt(vX*vX + vY*vY);\ndouble aX = cX + vX / magV * R;\ndouble aY = cY + vY / magV * R;\n"
},
{
"answer_id": 300959,
"author": "Alex",
"author_id": 30181,
"author_profile": "https://Stackoverflow.com/users/30181",
"pm_score": 1,
"selected": false,
"text": "m=(cY-pY)/(cX-pX); //slope\nb=cY-m*cX; //or Py-m*Px. Now you have a line in the form y=m*x+b\nX=( (2mcY)*((-2*m*cY)^2-4*(cY^2+cX^2-b^2-2*b*cY-r^2)*(-1-m^2))^(1/2) )/(2*(cY^2+cX^2-b^2-2*bc*Y-r^2));\nY=mX+b;\n"
},
{
"answer_id": 72400339,
"author": "Gullie667",
"author_id": 3660167,
"author_profile": "https://Stackoverflow.com/users/3660167",
"pm_score": 0,
"selected": false,
"text": "//Find closest point on circle\nVector3 closestPoint = transform.InverseTransformPoint(m_testPosition.position);\nclosestPoint.z = 0;\nclosestPoint = closestPoint.normalized * m_radius;\n\nGizmos.color = Color.yellow;\nGizmos.DrawWireSphere(transform.TransformPoint(closestPoint), 0.01f);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
300,911 | <p>For a deleted file what's the command to use to view the content of a old revision</p>
<pre><code>E:\Downloads\eeli\eel\eel>svn cat eel-scalable-font.h -r 2
svn: warning: 'eel-scalable-font.h' is not under version control
</code></pre>
| [
{
"answer_id": 300928,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 2,
"selected": false,
"text": "svn cat eel-scalable-font.h@2\n"
},
{
"answer_id": 301001,
"author": "nobody",
"author_id": 19405,
"author_profile": "https://Stackoverflow.com/users/19405",
"pm_score": 6,
"selected": true,
"text": "svn cat https://myhost/svn/eeli/eel/eel/eel-scalable-font.h@2\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30546/"
] |
300,929 | <p>EDIT: For the inner queries, there could be more than one match per inner query. It grabs a bunch of tags with the same game_ID. Thats why .First or .Max won't work.</p>
<p>Need some help, I have a query in LINQ that looks like this:</p>
<pre><code>from yy in Tags_Lookups
where yy.Tag_ID == (from xx in Tags_Lookups
where xx.Game_ID == new Guid("4962d645-711c-4db8-a7ce-ae9b36dd730c")
select xx.Tag_ID)
select yy
</code></pre>
<p>I am getting an error that looks like this:</p>
<p>Operator '==' cannot be applied to operands of type 'int' and 'System.Linq.IQueryable'</p>
<p>I have also tried this with no luck:</p>
<pre><code>from yy in Tags_Lookups
where yy.Tag_ID.Contains(from xx in Tags_Lookups
where xx.Game_ID == new Guid("4962d645-711c-4db8-a7ce-ae9b36dd730c")
select xx.Tag_ID)
select yy
</code></pre>
<p>With this Error:</p>
<p>'int' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'int' could be found</p>
<p>Can anyone help me write a good query that will work?</p>
| [
{
"answer_id": 300932,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "from yy in Tags_Lookups\nwhere (from xx in Tags_Lookups\n where xx.Game_ID == new Guid(\"4962d645-711c-4db8-a7ce-ae9b36dd730c\")\n select xx.Tag_ID).ToList()\n .Contains( yy.Tag_ID )\nselect yy\n"
},
{
"answer_id": 300963,
"author": "gfrizzle",
"author_id": 23935,
"author_profile": "https://Stackoverflow.com/users/23935",
"pm_score": 2,
"selected": false,
"text": "from yy in Tags_Lookups\njoin xx in Tags_Lookups on yy.Tag_ID Equals xx.Tag_ID\nwhere xx.Game_ID == new Guid(\"4962d645-711c-4db8-a7ce-ae9b36dd730c\")\nselect yy\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
] |
300,935 | <p>I'm trying to find the definition of a binary search tree and I keep finding different definitions everywhere. </p>
<p>Some say that for any given subtree the left child key is less than or equal to the root.</p>
<p>Some say that for any given subtree the right child key is greater than or equal to the root.</p>
<p>And my old college data structures book says "every element has a key and no two elements have the same key."</p>
<p>Is there a universal definition of a bst? Particularly in regards to what to do with trees with multiple instances of the same key.</p>
<p>EDIT: Maybe I was unclear, the definitions I'm seeing are</p>
<p>1) left <= root < right</p>
<p>2) left < root <= right</p>
<p>3) left < root < right, such that no duplicate keys exist.</p>
| [
{
"answer_id": 300962,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": false,
"text": " 14\n / \\\n 13 22\n / / \\\n1 16 29\n / \\\n 28 29\n def hasVal (node, srchval):\n if node == NULL:\n return false\n if node.val == srchval:\n return true\n if node.val > srchval:\n return hasVal (node.left, srchval)\n return hasVal (node.right, srchval)\n foundIt = hasVal (rootNode, valToLookFor)\n hasVal countVal i.c c i __14__ ___22.2___\n / \\ / \\\n 14 22 7.1 29.1\n / \\ / \\ / \\ / \\\n1 14 22 29 1.1 14.3 28.1 30.1\n \\ / \\\n 7 28 30\n 22 22-29-28-30 \\ \\\n 22 29\n \\ / \\\n 29 --> 28 30\n / \\ /\n 28 30 22\n 22.2 22.1"
},
{
"answer_id": 5627477,
"author": "Jherico",
"author_id": 85306,
"author_profile": "https://Stackoverflow.com/users/85306",
"pm_score": 2,
"selected": false,
"text": "left <= root <= right"
},
{
"answer_id": 20426419,
"author": "duilio",
"author_id": 2158621,
"author_profile": "https://Stackoverflow.com/users/2158621",
"pm_score": 6,
"selected": false,
"text": " 3\n / \\\n 2 4\n 3\n / \\\n 2 4\n \\\n 3\n 3(1)\n / \\\n 2(1) 4(1)\n 3(2)\n / \\\n 2(1) 4(1)\n"
},
{
"answer_id": 39364373,
"author": "Laurent Martin",
"author_id": 6803553,
"author_profile": "https://Stackoverflow.com/users/6803553",
"pm_score": 4,
"selected": false,
"text": "x y x y:key <= x:key y x y:key >= x:key"
},
{
"answer_id": 61292717,
"author": "Lazy Ren",
"author_id": 4294737,
"author_profile": "https://Stackoverflow.com/users/4294737",
"pm_score": 3,
"selected": false,
"text": " 12\n / \\\n 10 20\n / \\ /\n 9 11 12 \n / \\\n 10 12\n 12 - 12 - 12\n / \\\n10 - 10 20\n / \\\n 9 11\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36706/"
] |
300,950 | <p>I have a label function like :</p>
<pre><code>private function formatDate (item:Object, column:DataGridColumn):String
{
var df:DateFormatter = new DateFormatter();
df.formatString = "MM/DD/YY";
if (column.dataField == "startDate") {
return df.format(item.startDate);
}
return "ERR";
}
</code></pre>
<p>Which I use in a datacolumn by using <code>labelFunction</code>.</p>
<p>This works just fine if my data field is called 'startDate'. I want to make this function generic so I can use it everywhere.</p>
<p>How can I do this. i think i need to use some kind of 'reflection' - or perhaps another approach altogether?</p>
| [
{
"answer_id": 301295,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 5,
"selected": true,
"text": "partial function partial( func : Function, ...boundArgs ) : Function {\n return function( ...dynamicArgs ) : * {\n return func.apply(null, boundArgs.concat(dynamicArgs))\n }\n}\n private function formatDate( dataField : String, item : Object, column : DataGridColumn ) : String {\n var df : DateFormatter = new DateFormatter();\n\n df.formatString = \"MM/DD/YY\";\n\n if ( column.dataField == dataField ) {\n return df.format(item[dataField]);\n }\n\n return \"ERR\";\n}\n dataField var startDateLabelFunction : Function = partial(formatDate, \"startDate\");\nvar endDateLabelFunction : Function = partial(formatDate, \"endDate\");\n partial partial(formatDate, \"startDate\") function( ...dynamicArgs ) : * {\n return func.apply(null, boundArgs.concat(dynamicArgs));\n}\n func boundArgs partial function( ...dynamicArgs ) : * {\n return formatDate.apply(null, [\"startDate\"].concat(dynamicArgs));\n}\n function( item : Object, column : DataGridColumn ) : * {\n return formatDate(\"startDate\", item, column);\n}\n"
},
{
"answer_id": 773750,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "private function formatDate (item:Object, column:DataGridColumn):String\n{\n var df:DateFormatter = new DateFormatter();\n df.formatString = \"MM/DD/YY\";\n\n var value:object = item[column.dataField];\n\n return df.format(value);\n}\n"
},
{
"answer_id": 14201848,
"author": "Levancho",
"author_id": 1955652,
"author_profile": "https://Stackoverflow.com/users/1955652",
"pm_score": 1,
"selected": false,
"text": "public static function getDateLabelFunction(dateFormatString:String=null, mxFunction:Boolean = false) : Function {\n var retf:Function;\n\n // defaults\n if(dateFormatString == null) dateFormatString = \"MM/DD/YY\";\n if(mxFunction) {\n retf = function (item:Object, column:DataGridColumn):String\n {\n var df:DateFormatter = new DateFormatter();\n df.formatString = dateFormatString;\n\n var value:Object = item[column.dataField];\n\n return df.format(value);\n }\n }else {\n retf = function (item:Object, column:GridColumn):String\n {\n var df:DateFormatter = new DateFormatter();\n df.formatString = dateFormatString;\n\n var value:Object = item[column.dataField];\n\n return df.format(new Date(value));\n }\n }\n\n return retf;\n\n }\n var labelFunction = getDateLabelFunction();\n var labelFunction = getDateLabelFunction(null,true);\n var labelFunction = getDateLabelFunction(\"DD/MM/YYYY\",true);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
300,957 | <p>My question is similar to Engram's <a href="https://stackoverflow.com/questions/223149/how-do-you-handle-the-output-of-a-dynamically-generated-form-in-aspnet-mvc">here</a>, but my question goes a bit further. The way i intend it to work is I have a textbox asking how many entries a user is going to make. After they input the number, I need to create that many more textboxes to allow for entries (and then repeat the same process with those textboxes, but baby steps first...) I tried collecting the keys on the post, but it only returns the initial textbox asking for the number of entries. I'm still trying to get a grasp on MVC and the tutorials/videos so far don't delve this deep into it yet. Then again, I know this is probably something I could handle using JQuery, but I'd still be stuck in the same situation.</p>
<p>This is the controller I'm using:</p>
<pre><code>[AcceptVerbsAttribute("POST")]
public ActionResult Create(int tbxNumberOfExercises)
{
ViewData["number"] = tbxNumberOfExercises;
foreach (var key in Request.Form.Keys)
{
string keyString = key.ToString();
if (keyString.StartsWith("tbox_exercise", StringComparison.OrdinalIgnoreCase))
{
string recNum = keyString.Substring(13, keyString.Length - 13);
string approvedKey = Request.Form["tbox_exercise" + recNum];
int number;
int.TryParse(approvedKey, out number);
}
}
return View("Create");
}
</code></pre>
<p>And this is my aspx:</p>
<pre><code><form action="/CreateWorkout/Create" method="post">
Number of Exercises:
<%= Html.TextBox("tbxNumberOfExercises") %>
<br />
<br />
<input type="submit" value="Set Exercise Number" />
</form>
<% if (ViewData["number"] != null)%>
There are this many:<%=Html.Encode(ViewData["number"])%>
<br />
and this line should show up
<% if (ViewData["number"] != null)
{
int max = (int)ViewData["number"];
for (int i = 0; i < max; i++)
{%>
<br />
<br />
<%= Html.TextBox("tbox_exercise" + i) %>
<% }
} %>
<% if (ViewData["s"] != null) %>
<%=Html.Encode(ViewData["s"]) %>
</code></pre>
<p>Is there something I'm overlooking, not comprehending, or should I quit while I'm at it because it seems like I'll never get it?</p>
<p>Thanks in advance for any help -- I'm just trying to learn as most I can.</p>
| [
{
"answer_id": 301005,
"author": "Scott",
"author_id": 29640,
"author_profile": "https://Stackoverflow.com/users/29640",
"pm_score": 3,
"selected": true,
"text": "<form action=\"/Demo01/Create\" method=\"post\">\nNumber of Exercises:\n<%= Html.TextBox(\"tbxNumberOfExercises\") %>\n<br />\n<br />\n<input type=\"submit\" value=\"Set Exercise Number\" />\n</form>\n<% if (ViewData[\"number\"] != null) {%>\n<form action=\"/Demo01/Save\" method=\"post\">\nThere are this many:<%=Html.Encode(ViewData[\"number\"])%>\n<br />\nand this line should show up\n<% if (ViewData[\"number\"] != null) {\n int max = (int)ViewData[\"number\"];\n\n for (int i = 0; i < max; i++) {%>\n<br />\n<br />\n<%= Html.TextBox(\"tbox_exercise\" + i) %>\n<% }\n } %>\n<% if (ViewData[\"s\"] != null) %>\n<%=Html.Encode(ViewData[\"s\"]) %>\n<input type=\"submit\" value=\"Save Exercises\" />\n<% } %>\n</form>\n public class Demo01Controller : Controller {\n public ActionResult Create() {\n return View();\n }\n\n [AcceptVerbsAttribute(\"POST\")]\n public ActionResult Create(int tbxNumberOfExercises) {\n ViewData[\"number\"] = tbxNumberOfExercises;\n return View(\"Create\");\n }\n\n [AcceptVerbs(HttpVerbs.Post)]\n public ActionResult Save() {\n foreach (var key in Request.Form.Keys) {\n string keyString = key.ToString();\n if (keyString.StartsWith(\"tbox_exercise\", StringComparison.OrdinalIgnoreCase)) {\n string recNum = keyString.Substring(13, keyString.Length - 13);\n string approvedKey = Request.Form[\"tbox_exercise\" + recNum];\n int number;\n int.TryParse(approvedKey, out number);\n }\n }\n return View(); // return/redirect to wherever you want\n }\n}\n"
},
{
"answer_id": 301009,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 1,
"selected": false,
"text": "</form> <form action=\"/CreateWorkout/Create\" method=\"post\">\nNumber of Exercises:\n<%= Html.TextBox(\"tbxNumberOfExercises\") %>\n<br />\n<br />\n<input type=\"submit\" value=\"Set Exercise Number\" />\n<% if (ViewData[\"number\"] != null)%>\nThere are this many:<%=Html.Encode(ViewData[\"number\"])%>\n<br />\nand this line should show up\n<% if (ViewData[\"number\"] != null)\n {\n int max = (int)ViewData[\"number\"];\n\n for (int i = 0; i < max; i++)\n {%>\n <br />\n <br />\n <%= Html.TextBox(\"tbox_exercise\" + i) %>\n <% }\n } %>\n<% if (ViewData[\"s\"] != null) %>\n<%=Html.Encode(ViewData[\"s\"]) %>\n</form>\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30816/"
] |
300,971 | <p>I am using several NSButtonCell objects in an NSTableView. They are simple square buttons with custom images on them.</p>
<p>These buttons draw properly when they are not highlighted: all that is visible is the image, and the rest of the button rectangle is transparent. However, when I click on them, the entire button rectangle is highlighted, inverting the background in the parts that were transparent.</p>
<p>I would prefer to see the image drawn inverted, and the transparent parts remain transparent. How can this be done?</p>
| [
{
"answer_id": 301106,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 4,
"selected": true,
"text": "highlightsBy NSContentsCellMask awakeFromNib"
},
{
"answer_id": 27085790,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Square Button Momentary Light Momentary Push In Behaviour Momentary Change"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33686/"
] |
300,986 | <p>Is there ever a good reason to <em>not</em> declare a virtual destructor for a class? When should you specifically avoid writing one?</p>
| [
{
"answer_id": 301023,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 3,
"selected": false,
"text": "delete B A A *x = new B;\ndelete x; // ~B() called, even though x has type A*\n delete"
},
{
"answer_id": 302169,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 6,
"selected": false,
"text": "struct A {\n // virtual ~A ();\n int i;\n int j;\n};\nvoid foo () { \n A a = { 0, 1 }; // Will fail if virtual dtor declared\n}\n void bar (...);\nvoid foo (A & a) { \n bar (a); // Undefined behavior if virtual dtor declared\n}\n =default struct A {\n A(int i, int j);\n virtual ~A ();\n int i;\n\n int j;\n};\nvoid foo () { \n A a = { 0, 1 }; // OK\n}\n"
},
{
"answer_id": 308889,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 3,
"selected": false,
"text": "class MutexLock {\n mutex *mtx_;\npublic:\n explicit MutexLock(mutex *mtx) : mtx_(mtx) { mtx_->lock(); }\n ~MutexLock() { mtx_->unlock(); }\nprivate:\n MutexLock(const MutexLock &rhs);\n MutexLock &operator=(const MutexLock &rhs);\n};\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/300986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10606/"
] |
301,004 | <p>To calculate a top position for an element of variable height, I was thinking of doing the following:</p>
<ol>
<li>Move the element 1000px off the top of the viewport</li>
<li>Set the element to display: block</li>
<li>Get the height of the element</li>
<li>Set the element to display: none</li>
<li>Continue on as if everything is normal and good</li>
</ol>
<p>Any pitfalls in this approach? Is there a more elegant solution?</p>
| [
{
"answer_id": 301014,
"author": "wombleton",
"author_id": 22419,
"author_profile": "https://Stackoverflow.com/users/22419",
"pm_score": 3,
"selected": true,
"text": "getDimensions display:none"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
] |
301,008 | <p>We were using stringstream to prepare select queries in C++. But we were strongly advised to use QUERY PARAMETERS to submit db2 sql queries to avoid using of stringstream. Can anyone share what exactly meant by query parameter in C++? Also, share some practical sample code snippets.</p>
<p>Appreciate the help in advance.</p>
<p>Edit: It is stringstream and not strstream.</p>
<p>Thanks,
Mathew Liju</p>
| [
{
"answer_id": 301015,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 3,
"selected": true,
"text": "\"SELECT * FROM Customers WHERE CustomerId = \" + _customerId; \n \"SELECT * FROM Customers where CustomerId = @CustomerId\" \n"
},
{
"answer_id": 301029,
"author": "Nakul Chaudhary",
"author_id": 34588,
"author_profile": "https://Stackoverflow.com/users/34588",
"pm_score": 1,
"selected": false,
"text": "StringBuilder sqlstr = new StringBuilder(); \ncmd.Parameters.AddWithValue(\"@companyid\", CompanyID); \nsqlstr.Append(\"SELECT evtconfigurationId, companyid, \n configname, configimage FROM SCEVT_CONFIGURATIONS \");\nsqlstr.Append(\"WHERE companyid=@companyid \");\n StringBuilder sqlstr = new StringBuilder(); \nsqlstr.Append(\"SELECT evtconfigurationId, companyid, configname, \n configimage FROM SCEVT_CONFIGURATIONS \");\nsqlstr.Append(\"WHERE companyid\" + CompanyID);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18657/"
] |
301,039 | <p>I have a bash shell script that loops through all child directories (but not files) of a certain directory. The problem is that some of the directory names contain spaces. </p>
<p>Here are the contents of my test directory:</p>
<pre><code>$ls -F test
Baltimore/ Cherry Hill/ Edison/ New York City/ Philadelphia/ cities.txt
</code></pre>
<p>And the code that loops through the directories:</p>
<pre><code>for f in `find test/* -type d`; do
echo $f
done
</code></pre>
<p>Here's the output:</p>
<pre>
test/Baltimore
test/Cherry
Hill
test/Edison
test/New
York
City
test/Philadelphia
</pre>
<p>Cherry Hill and New York City are treated as 2 or 3 separate entries.</p>
<p>I tried quoting the filenames, like so:</p>
<pre><code>for f in `find test/* -type d | sed -e 's/^/\"/' | sed -e 's/$/\"/'`; do
echo $f
done
</code></pre>
<p>but to no avail.</p>
<p>There's got to be a simple way to do this.</p>
<hr>
<p>The answers below are great. But to make this more complicated - I don't always want to use the directories listed in my test directory. Sometimes I want to pass in the directory names as command-line parameters instead.</p>
<p>I took Charles' suggestion of setting the IFS and came up with the following:</p>
<pre><code>dirlist="${@}"
(
[[ -z "$dirlist" ]] && dirlist=`find test -mindepth 1 -type d` && IFS=$'\n'
for d in $dirlist; do
echo $d
done
)
</code></pre>
<p>and this works just fine unless there are spaces in the command line arguments (even if those arguments are quoted). For example, calling the script like this: <code>test.sh "Cherry Hill" "New York City"</code> produces the following output:</p>
<pre>
Cherry
Hill
New
York
City
</pre>
| [
{
"answer_id": 301059,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 8,
"selected": true,
"text": "find -exec # this is safe\nfind test -type d -exec echo '{}' +\n -print0 # this is safe\nwhile IFS= read -r -d '' n; do\n printf '%q\\n' \"$n\"\ndone < <(find test -mindepth 1 -type d -print0)\n # this is safe\ndeclare -a myarray\nwhile IFS= read -r -d '' n; do\n myarray+=( \"$n\" )\ndone < <(find test -mindepth 1 -type d -print0)\nprintf '%q\\n' \"${myarray[@]}\" # printf is an example; use it however you want\n -print0 # this is unsafe\nwhile IFS= read -r n; do\n printf '%q\\n' \"$n\"\ndone < <(find test -mindepth 1 -type d)\n IFS set -f [] * ? # this is unsafe (but less unsafe than it would be without the following precautions)\n(\n IFS=$'\\n' # split only on newlines\n set -f # disable globbing\n for n in $(find test -mindepth 1 -type d); do\n printf '%q\\n' \"$n\"\n done\n)\n # this is safe\nfor d in \"$@\"; do\n printf '%s\\n' \"$d\"\ndone\n $@ $* # this is safe\nentries=( test/* )\nfor d in \"${entries[@]}\"; do\n printf '%s\\n' \"$d\"\ndone\n"
},
{
"answer_id": 301065,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "find . -type d | while read file; do echo $file; done\n find . -type d -print0 | xargs -0 echo 'The directory is: '\n"
},
{
"answer_id": 301097,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "find -print0 xargs -0"
},
{
"answer_id": 301111,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "-print0 find xargs find test/* -type d -print0 | xargs -0 command\n command"
},
{
"answer_id": 794800,
"author": "Gordon Davisson",
"author_id": 89817,
"author_profile": "https://Stackoverflow.com/users/89817",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\nif [ $# -eq 0 ]; then\n # if no args supplies, build a list of subdirs of test/\n dirlist=() # start with empty list\n for f in test/*; do # for each item in test/ ...\n if [ -d \"$f\" ]; then # if it's a subdir...\n dirlist=(\"${dirlist[@]}\" \"$f\") # add it to the list\n fi\n done\nelse\n # if args were supplied, copy the list of args into dirlist\n dirlist=(\"$@\")\nfi\n# now loop through dirlist, operating on each one\nfor dir in \"${dirlist[@]}\"; do\n printf \"Directory: %s\\n\" \"$dir\"\ndone\n $ ls -F test\nBaltimore/\nCherry Hill/\nEdison/\nNew York City/\nPhiladelphia/\nthis is a dirname with quotes, lfs, escapes: \"\\''?'?\\e\\n\\d/\nthis is a file, not a directory\n$ ./test.sh \nDirectory: test/Baltimore\nDirectory: test/Cherry Hill\nDirectory: test/Edison\nDirectory: test/New York City\nDirectory: test/Philadelphia\nDirectory: test/this is a dirname with quotes, lfs, escapes: \"\\''\n'\n\\e\\n\\d\n$ ./test.sh \"Cherry Hill\" \"New York City\"\nDirectory: Cherry Hill\nDirectory: New York City\n"
},
{
"answer_id": 906000,
"author": "Jeffrey04",
"author_id": 5742,
"author_profile": "https://Stackoverflow.com/users/5742",
"pm_score": 0,
"selected": false,
"text": "test.sh \"Cherry Hill\" \"New York City\"\n for SOME_ARG in \"$@\"\ndo\n echo \"$SOME_ARG\";\ndone;\n"
},
{
"answer_id": 1111323,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "for item in /path/* function recursedir {\n local item\n for item in \"${1%/}\"/*\n do\n if [ -d \"$item\" ]\n then\n recursedir \"$item\"\n else\n command\n fi\n done\n}\n"
},
{
"answer_id": 1464836,
"author": "cbliard",
"author_id": 177665,
"author_profile": "https://Stackoverflow.com/users/177665",
"pm_score": 5,
"selected": false,
"text": "ls -F test\nBaltimore/ Cherry Hill/ Edison/ New York City/ Philadelphia/ cities.txt\n find test -type d | while read f ; do\n echo \"$f\"\ndone\n \"$f\" test/Baltimore\ntest/Cherry Hill\ntest/Edison\ntest/New York City\ntest/Philadelphia\n"
},
{
"answer_id": 2685898,
"author": "mark washeim",
"author_id": 322616,
"author_profile": "https://Stackoverflow.com/users/322616",
"pm_score": -1,
"selected": false,
"text": "for file in read `find . *.flv`; do ffmpeg -i ${file} -acodec copy ${file}.mp3;done\n "
},
{
"answer_id": 4214444,
"author": "Sony George",
"author_id": 512065,
"author_profile": "https://Stackoverflow.com/users/512065",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\n\ndirtys=()\n\nfor folder in *\ndo \n if [ -d \"$folder\" ]; then \n dirtys=(\"${dirtys[@]}\" \"$folder\") \n fi \ndone \n\nfor dir in \"${dirtys[@]}\" \ndo \n for file in \"$dir\"/\\*.mov # <== *.mov\n do \n #dir_e=`echo \"$dir\" | sed 's/[[:space:]]/\\\\\\ /g'` -- This line will replace each space into '\\ ' \n out=`echo \"$file\" | sed 's/\\(.*\\)\\/\\(.*\\)/\\2/'` # These two line code can be written in one line using multiple sed commands. \n out=`echo \"$out\" | sed 's/[[:space:]]/_/g'` \n #echo \"ffmpeg -i $out_e -sameq -vcodec msmpeg4v2 -acodec pcm_u8 $dir_e/${out/%mov/avi}\" \n `ffmpeg -i \"$file\" -sameq -vcodec msmpeg4v2 -acodec pcm_u8 \"$dir\"/${out/%mov/avi}` \n done \ndone\n [sony@localhost shell_tutorial]$ ls\nChapter 01 - Introduction Chapter 02 - Your First Shell Script\n[sony@localhost shell_tutorial]$ cd Chapter\\ 01\\ -\\ Introduction/\n[sony@localhost Chapter 01 - Introduction]$ ls\n0101 - About this Course.mov 0102 - Course Structure.mov\n[sony@localhost Chapter 01 - Introduction]$ ./above_script\n ... successfully executed.\n[sony@localhost Chapter 01 - Introduction]$ ls\n0101_-_About_this_Course.avi 0102_-_Course_Structure.avi\n0101 - About this Course.mov 0102 - Course Structure.mov\n[sony@localhost Chapter 01 - Introduction]$ CHEERS!\n"
},
{
"answer_id": 6674097,
"author": "AndrzejP",
"author_id": 841970,
"author_profile": "https://Stackoverflow.com/users/841970",
"pm_score": -1,
"selected": false,
"text": "for f in \"$(find ./test -type d)\" ; do\n echo \"$f\"\ndone\n"
},
{
"answer_id": 9452559,
"author": "oshunluvr",
"author_id": 1233693,
"author_profile": "https://Stackoverflow.com/users/1233693",
"pm_score": 2,
"selected": false,
"text": "IFS='\\n'\n"
},
{
"answer_id": 9724152,
"author": "Freakus",
"author_id": 1272095,
"author_profile": "https://Stackoverflow.com/users/1272095",
"pm_score": 2,
"selected": false,
"text": "find . -print0|while read -d $'\\0' file; do echo \"$file\"; done\n"
},
{
"answer_id": 10969478,
"author": "murpel",
"author_id": 1447441,
"author_profile": "https://Stackoverflow.com/users/1447441",
"pm_score": 2,
"selected": false,
"text": "SAVEIFS=$IFS\nIFS=$(echo -en \"\\n\\b\")\nfor f in $( find \"$1\" -type d ! -path \"$1\" )\ndo\n echo $f\ndone\nIFS=$SAVEIFS\n"
},
{
"answer_id": 12467157,
"author": "Steve Zobell",
"author_id": 1427011,
"author_profile": "https://Stackoverflow.com/users/1427011",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\n\n# This is the command where we want to convert the output to an array.\n# Output is: fileSize fileNameIncludingPath\nmultiLineCommand=\"find . -mindepth 1 -printf '%s %p\\\\n'\"\n\n# This eval converts the multi-line output of multiLineCommand to a\n# Bash array. To convert stdin, remove: < <(eval \"$multiLineCommand\" )\neval \"declare -a myArray=`( arr=(); while read -r line; do arr[${#arr[@]}]=\"$line\"; done; declare -p arr | sed -e 's/^declare -a arr=//' ) < <(eval \"$multiLineCommand\" )`\"\n\nfor f in \"${myArray[@]}\"\ndo\n echo \"Element: $f\"\ndone\n"
},
{
"answer_id": 13214657,
"author": "hardbutnot",
"author_id": 1797306,
"author_profile": "https://Stackoverflow.com/users/1797306",
"pm_score": 2,
"selected": false,
"text": "read artist;\n\nfind \"/mnt/2tb_USB_hard_disc/p_music/$artist\" -type f -name *.mp3 -exec mpg123 '{}' \\;\n"
},
{
"answer_id": 18422485,
"author": "Hìr0",
"author_id": 2714250,
"author_profile": "https://Stackoverflow.com/users/2714250",
"pm_score": 0,
"selected": false,
"text": "source=\"/xxx/xxx\"\ndest=\"/yyy/yyy\"\n\nn_max=`ls . | wc -l`\n\necho \"Loop over items...\"\ni=1\nwhile [ $i -le $n_max ];do\nitem=`ls . | awk 'NR=='$i'' `\necho \"File selected for compression: $item\"\ntar -cvzf $dest/\"$item\".tar.gz \"$item\"\ni=$(( i + 1 ))\ndone\necho \"Done!!!\"\n"
},
{
"answer_id": 34808444,
"author": "Johan Kasselman",
"author_id": 5793994,
"author_profile": "https://Stackoverflow.com/users/5793994",
"pm_score": 0,
"selected": false,
"text": "find Downloads -type f | while read file; do printf \"%q\\n\" \"$file\"; done\n"
},
{
"answer_id": 35886082,
"author": "amazingthere",
"author_id": 2049675,
"author_profile": "https://Stackoverflow.com/users/2049675",
"pm_score": 3,
"selected": false,
"text": "OLD_IFS=$IFS # Stores Default IFS\nIFS=$'\\n' # Set it to line break\nfor f in `find test/* -type d`; do\n echo $f\ndone\n\nIFS=$OLD_IFS\n"
},
{
"answer_id": 36549299,
"author": "Tebe",
"author_id": 758158,
"author_profile": "https://Stackoverflow.com/users/758158",
"pm_score": 1,
"selected": false,
"text": " find . -name \\*.dbf -print0 -exec mv '{}' . ';'\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094969/"
] |
301,045 | <p>For background see my question <a href="https://stackoverflow.com/questions/291761/converting-a-fairly-simple-c-class-library-into-a-com-object">here</a>.</p>
<p>So the problem now isn't that I can't send a <code>DataSet</code> to classic ASP but that it can't do anything with it. So I found some code to create a recordset xml structure from a <code>DataSet</code>.</p>
<p>I have tweaked it a little from it's original <a href="http://www.microsoft.com/mspress/books/companion/6235.aspx#Companion%20Content" rel="nofollow noreferrer">source</a>. The problem is that I can't seem to extract the base stream and use it instead of having to write to a file. What am I missing?</p>
<p>Here is how I am trying to test the class:</p>
<pre><code>[Test]
public void TestWriteToStream()
{
MemoryStream theStream = new MemoryStream();
XmlRecordsetWriter theWriter = new XmlRecordsetWriter(theStream);
theWriter.WriteRecordset( SomeFunctionThatReturnsADataSet() );
theStream = (MemoryStream)theWriter.BaseStream;
string xmlizedString = UTF8ByteArrayToString(theStream.ToArray());
xmlizedString = xmlizedString.Substring(1);
//Assert.AreEqual(m_XMLNotNull, xmlizedString);
Console.WriteLine(xmlizedString);
}
</code></pre>
<p>Here is my class:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;
namespace Core{
public class XmlRecordsetWriter : XmlTextWriter
{
#region Constructors
// Constructor(s)
public XmlRecordsetWriter(string filename) : base(filename, null) { SetupWriter(); }
public XmlRecordsetWriter(Stream s) : base(s, null) { SetupWriter(); }
public XmlRecordsetWriter(TextWriter tw) : base(tw) { SetupWriter(); }
protected void SetupWriter()
{
base.Formatting = Formatting.Indented;
base.Indentation = 3;
}
#endregion
#region Methods
// WriteRecordset
public void WriteRecordset(DataSet ds) { WriteRecordset(ds.Tables[0]); }
public void WriteRecordset(DataSet ds, string tableName) { WriteRecordset(ds.Tables[tableName]); }
public void WriteRecordset(DataView dv) { WriteRecordset(dv.Table); }
public void WriteRecordset(DataTable dt)
{
WriteStartDocument();
WriteSchema(dt);
WriteContent(dt);
WriteEndDocument();
}
// WriteStartDocument
public void WriteStartDocument()
{
base.WriteStartDocument();
base.WriteComment("Created by XmlRecordsetWriter");
base.WriteStartElement("xml");
base.WriteAttributeString("xmlns", "s", null, "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882");
base.WriteAttributeString("xmlns", "dt", null, "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882");
base.WriteAttributeString("xmlns", "rs", null, "urn:schemas-microsoft-com:rowset");
base.WriteAttributeString("xmlns", "z", null, "#RowsetSchema");
}
// WriteSchema
public void WriteSchema(DataSet ds) { WriteSchema(ds.Tables[0]); }
public void WriteSchema(DataSet ds, string tableName) { WriteSchema(ds.Tables[tableName]); }
public void WriteSchema(DataView dv){ WriteSchema(dv.Table); }
public void WriteSchema(DataTable dt)
{
// Open the schema tag (XDR)
base.WriteStartElement("s", "Schema", null);
base.WriteAttributeString("id", "RowsetSchema");
base.WriteStartElement("s", "ElementType", null);
base.WriteAttributeString("name", "row");
base.WriteAttributeString("content", "eltOnly");
// Write the column info
int index=0;
foreach(DataColumn dc in dt.Columns)
{
index ++;
base.WriteStartElement("s", "AttributeType", null);
base.WriteAttributeString("name", dc.ColumnName);
base.WriteAttributeString("rs", "number", null, index.ToString());
base.WriteEndElement();
}
// Close the schema tag
base.WriteStartElement("s", "extends", null);
base.WriteAttributeString("type", "rs:rowbase");
base.WriteEndElement();
base.WriteEndElement();
base.WriteEndElement();
}
// WriteContent
public void WriteContent(DataSet ds) { WriteContent(ds.Tables[0]); }
public void WriteContent(DataSet ds, string tableName) { WriteContent(ds.Tables[tableName]); }
public void WriteContent(DataView dv) { WriteContent(dv.Table); }
public void WriteContent(DataTable dt)
{
// Write data
base.WriteStartElement("rs", "data", null);
foreach(DataRow row in dt.Rows)
{
base.WriteStartElement("z", "row", null);
foreach(DataColumn dc in dt.Columns)
base.WriteAttributeString(dc.ColumnName, row[dc.ColumnName].ToString());
base.WriteEndElement();
}
base.WriteEndElement();
}
// WriteEndDocument
public void WriteEndDocument()
{
base.WriteEndDocument();
base.Flush();
base.Close();
}
#endregion
}
</code></pre>
<p>}</p>
| [
{
"answer_id": 378770,
"author": "Gregg",
"author_id": 18266,
"author_profile": "https://Stackoverflow.com/users/18266",
"pm_score": 0,
"selected": false,
"text": "theStream = (MemoryStream)theWriter.BaseStream;\n MemoryStream theWriter.Close();\ntheStream.Position = 0; // So you can start reading from the begining\n\nstring xml = null;\nusing (StringReader read = new StringReader(theStream))\n{\n xml = read.ReadToEnd();\n}\n XPathDocument XmlDocument"
},
{
"answer_id": 28859556,
"author": "shA.t",
"author_id": 4519059,
"author_profile": "https://Stackoverflow.com/users/4519059",
"pm_score": 1,
"selected": false,
"text": "ADODB DataTable ADODB.Recordset ConvertToRecordset() save() using ADODB;\nusing System;\nusing System.Data;\nusing System.IO;\n\nnamespace ConsoleApplicationTests\n{\n class Program\n {\n static void Main(string[] args)\n {\n Recordset rs = new Recordset();\n DataTable dt = sampleDataTable(); //-i. -> SomeFunctionThatReturnsADataTable() \n\n //-i. Convert DataTable to Recordset \n rs = ConvertToRecordset(dt);\n\n //-i. Sample Output File\n String filename = @\"C:\\yourXMLfile.xml\";\n FileStream fstream = new FileStream(filename, FileMode.Create);\n\n rs.Save(fstream, PersistFormatEnum.adPersistXML);\n }\n }\n}\n ADODB.Recordset rs.Open(fstream);\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29650/"
] |
301,053 | <p>Is it possible to re-assign the <kbd>Win</kbd>+<kbd>L</kbd> hotkey to another executable/shortcut?</p>
<p>Use-case - I would like to switch off the monitor of my laptop as soon as it is locked. I know of a executable which can lock and turn off the monitor but I do not want to change the way the system is locked (by running the program explicitly or by some other shortcut). It would be best if <kbd>Win</kbd>+<kbd>L</kbd> can be assigned to this executable.</p>
| [
{
"answer_id": 317550,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 4,
"selected": false,
"text": "WH_KEYBOARD_LL LRESULT CALLBACK LowLevelKeyboardProc(int code, WPARAM wparam, LPARAM lparam) {\n KBDLLHOOKSTRUCT& kllhs = *(KBDLLHOOKSTRUCT*)lparam;\n if (code == HC_ACTION) {\n // Test for an 'L' keypress with either Win key down.\n if (wparam == WM_KEYDOWN && kllhs.vkCode == 'L' && \n (GetAsyncKeyState(VK_LWIN) < 0 || GetAsyncKeyState(VK_RWIN) < 0))\n {\n // Place some code here to do whatever you want.\n // ...\n\n // Return non-zero to halt message propagation\n // and prevent the Win+L hotkey from getting activated.\n return 1;\n }\n }\n return CallNextHookEx(0, code, wparam, lparam);\n}\n WH_KEYBOARD"
},
{
"answer_id": 10987961,
"author": "franc0is",
"author_id": 376645,
"author_profile": "https://Stackoverflow.com/users/376645",
"pm_score": 5,
"selected": false,
"text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System] \"DisableLockWorkstation\"=dword:00000001\n"
},
{
"answer_id": 14805061,
"author": "Brent Faust",
"author_id": 225240,
"author_profile": "https://Stackoverflow.com/users/225240",
"pm_score": 2,
"selected": false,
"text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System]\n\"DisableLockWorkstation\"=dword:00000001\n [HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System]\n\"DisableLockWorkstation\"=dword:00000000\n"
},
{
"answer_id": 27975295,
"author": "Kyle Strand",
"author_id": 1858225,
"author_profile": "https://Stackoverflow.com/users/1858225",
"pm_score": 4,
"selected": false,
"text": "Start DisableLockWorkstation.reg Windows Registry Editor Version 5.00\n [HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System]\n \"DisableLockWorkstation\"=dword:00000001\n EnableLockWorkstation.reg Windows Registry Editor Version 5.00\n\n [HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System]\n \"DisableLockWorkstation\"=-\n .reg regedit /S EnableLockWorkstation.reg\nrundll32.exe user32.dll,LockWorkStation\nregedit /S DisableLockWorkstation.reg\n cmd.exe /C \"<path>\\lock.bat\" <path> lock.bat lock.bat \"C:\\Users\\ [user_name]\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\ [custom_folder]\\\"\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26090/"
] |
301,054 | <p>How can I determine if a Win32 thread has terminated?</p>
<p>The documentation for <strong><a href="http://msdn.microsoft.com/en-us/library/ms683190(VS.85).aspx" rel="noreferrer">GetExitCodeThread</a></strong> warns to not to use it for this reason since the error code STILL_ACTIVE can be returned for other reasons.</p>
<p>Thanks for the help! :)</p>
| [
{
"answer_id": 301067,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": false,
"text": "STILL_ACTIVE"
},
{
"answer_id": 301098,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": true,
"text": "DWORD result = WaitForSingleObject( hThread, 0);\n\nif (result == WAIT_OBJECT_0) {\n // the thread handle is signaled - the thread has terminated\n}\nelse {\n // the thread handle is not signaled - the thread is still alive\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19129/"
] |
301,060 | <p>say I want to find the latest added rows (UPDATE by any user, not necessarily the one which is executing UPDATE) in XX table.</p>
| [
{
"answer_id": 301088,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": false,
"text": " DBCC LOG(<database name>[,{0|1|2|3|4}]).\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38819/"
] |
301,066 | <p>I'm trying to measure height of some text for table printing purpose.</p>
<p>Here's the code. In my case it prints different numbers in preview and on actual page.
I can't try on any printers other than Microsoft Office Document Image Writer right now, but I'm pretty sure it isn't a printer issue.</p>
<p>Perhaps somebody have found a workaround for this problem?</p>
<pre><code> private void button1_Click(object sender, EventArgs e)
{
Print();
}
public void Print()
{
PrintDocument my_doc = new PrintDocument();
my_doc.PrintPage += new PrintPageEventHandler(this.PrintPage);
PrintPreviewDialog my_preview = new PrintPreviewDialog();
my_preview.Document = my_doc;
my_preview.ShowDialog();
my_doc.Dispose();
my_preview.Dispose();
}
private void PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.PageUnit = GraphicsUnit.Pixel;
string s = "String height is ";
SizeF h = e.Graphics.MeasureString(s, new Font("Arial", 24));
e.Graphics.DrawString(s + Convert.ToString(h.Height),
new Font("Arial", 24), new SolidBrush(Color.Black), 1, 1);
}
</code></pre>
| [
{
"answer_id": 354285,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 1,
"selected": false,
"text": "SizeF hT = TextRenderer.MeasureText(s, new Font(\"Arial\", 24));\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,068 | <p>I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:</p>
<pre><code>>>> foo = 'baz "\"'
>>> foo
'baz ""'
</code></pre>
<p>So instead of <code>baz "\"</code> like I want I'm getting <code>baz ""</code>. If I then try to escape the backslash, it doesn't help either:</p>
<pre><code>>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
</code></pre>
<p>Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?</p>
| [
{
"answer_id": 301075,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 8,
"selected": true,
"text": ">>> foo = 'baz \"\\\\\"'\n>>> foo\n'baz \"\\\\\"'\n>>> print(foo)\nbaz \"\\\"\n >>> print(r'baz \"\\\"')\nbaz \"\\\"\n"
},
{
"answer_id": 301076,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 6,
"selected": false,
"text": ">>> foo = r'baz \"\\\"'\n>>> foo\n'baz \"\\\\\"'\n foo foo __repr__() print >>> foo = r'baz \"\\\"'\n>>> foo\n'baz \"\\\\\"'\n>>> print(foo)\nbaz \"\\\"\n >>> foo = r'baz \\'\n File \"<stdin>\", line 1\n foo = r'baz \\'\n ^ \nSyntaxError: EOL while scanning single-quoted string\n >>> foo = 'baz \\\\'\n>>> print(foo)\nbaz \\\n os.path.normpath() myfile = os.path.normpath('c:/folder/subfolder/file.txt')\nopen(myfile)\n"
},
{
"answer_id": 301293,
"author": "babbageclunk",
"author_id": 38851,
"author_profile": "https://Stackoverflow.com/users/38851",
"pm_score": 3,
"selected": false,
"text": "infile = open('c:/folder/subfolder/file.txt')\n os.system subprocess"
},
{
"answer_id": 19167835,
"author": "James",
"author_id": 2844188,
"author_profile": "https://Stackoverflow.com/users/2844188",
"pm_score": -1,
"selected": false,
"text": ".strip() newString = string1 + \"\\ \".strip() + string2\n"
},
{
"answer_id": 65310436,
"author": "Stephan Yazvinski",
"author_id": 13457123,
"author_profile": "https://Stackoverflow.com/users/13457123",
"pm_score": -1,
"selected": false,
"text": "\"\\\\\" import os\npath = r\"c:\\file\"+\"\\\\\"+\"path\"\nos.path.normpath(path)\n c:\\file\\path"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
301,085 | <p>Anyone knows a way to define refactoring in a more formal way?</p>
<p>UPDATE.</p>
<blockquote>
<p>A refactoring is a pair R = (pre; T) where pre is the precondition that
the program must satisfy, and T is the program transformation.</p>
</blockquote>
| [
{
"answer_id": 301150,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "given program P implies R\nrefactoring transformation T(P) produces P'\nwhere (P' implies R') and (R' is equivalent to or subsumes R')\n P:I -> O\n T(P) -> R\n R:I -> O\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20915/"
] |
301,108 | <p>I realize that this could probably be done easier in any number of other scripting languages but started to do it quick in cmd and now Im curious.</p>
<p>Looking to start a process at an offset to the time that another process started. Lets say 5 minutes to keep it simple. Is there a way to add to the %TIME% variable?</p>
<p>For instance:</p>
<pre><code>start /b foo.exe
at %TIME% + 5 minutes bar.exe
</code></pre>
<p>Thanks for any assistance</p>
| [
{
"answer_id": 301141,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": false,
"text": "set/? set h=%TIME:~0,2%\nset m=%TIME:~3,2%\nset/a m2=\"m+5\"\nset t2=%h%:%m2%\nset t2\n"
},
{
"answer_id": 1254897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "set h=%TIME:~0,2%\nset m=%TIME:~3,2%\nset s=%TIME:~6,2%\nset time=%h%_%m%_%s%\nmkdir c:\\test\\%time%\nmove c:\\test\\*.* c:\\test\\%time%\n\"C:\\Program Files\\WinRAR\\RAR\" a -ep c:\\test\\%time%\\ -agDD-MM-YY_hh-mm-ss c:\\test\\%time%\\*.* -zc:\\arhiv\\HEADERS.TXT\nmove c:\\test\\%time%\\*.rar c:\\arhiv\\\nrmdir c:\\test\\%time% /S /Q\n"
},
{
"answer_id": 2854860,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 1,
"selected": false,
"text": " @echo off\n :: START USAGE ==================================================================\n ::SET THE NICETIME \n :: SET NICETIME=BOO\n :: CALL GetNiceTime.cmd \n\n :: ECHO NICETIME IS %NICETIME%\n\n :: echo nice time is %NICETIME%\n :: END USAGE ==================================================================\n\n echo set hhmmsss\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=:\" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c \n ::DEBUG ECHO hhmmsss IS %hhmmsss%\n ::DEBUG PAUSE\n echo %yyyymmdd%\n :: this is Regional settings dependant so tweak this according your current settings\n for /f \"tokens=1-3 delims=.\" %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D\n ::DEBUG ECHO yyyymmdd IS %yyyymmdd%\n ::DEBUG PAUSE\n\n\n set NICETIME=%yyyymmdd%_%hhmmsss%\n ::DEBUG echo THE NICETIME IS %NICETIME%\n\n ::DEBUG PAUSE\n"
},
{
"answer_id": 18362247,
"author": "Rob Bos",
"author_id": 2608053,
"author_profile": "https://Stackoverflow.com/users/2608053",
"pm_score": 2,
"selected": false,
"text": ":: Get an offset of 1 minute from the current time, accounting for edge cases\nset hr=%TIME:~0,2%\nset /a mn=%TIME:~3,2%+1\n:: check minutes; greater than 60? add n/60 to hour, n%60 to mins\nif %mn% geq 60 set /a hr=hr+mn/60 && set /a mn=mn%%60\nif %hr% geq 24 set /a h=0\n:: pad zeros if necessary\nif %mn% leq 9 set mn=0%mn%\nif %hr% leq 9 set hr=0%hr%\n"
},
{
"answer_id": 22801897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "set hr=%TIME:~0,2%\nif %hr% leq 9 set hr=0%hr:~1,1%\nset mydate=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%-%hr%%TIME:~3,2%%TIME:~6,2%\ncopy file.txt file-%mydate%.txt\npause\n"
},
{
"answer_id": 50844476,
"author": "le luxe fou",
"author_id": 2948559,
"author_profile": "https://Stackoverflow.com/users/2948559",
"pm_score": 0,
"selected": false,
"text": "echo ----- time -----\necho %time%\nset _hh=%time:~0,2%\nset _mm=%time:~3,2%\nset _ss=%time:~6,2%\nset __time=%_hh%%_mm%%_ss%\necho _%__time%_\necho ----- time -----\necho:\necho ----- date -----\necho %date%\nset _Y=%date:~0,4%\nset _M=%date:~5,2%\nset _D=%date:~8,2%\nset __date=%_Y%%_M%%_D%\necho _%__date%_\necho ----- date -----\npause\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,109 | <p>How would I implement "close all other tabs" function for a tab control using Context menu strip?</p>
| [
{
"answer_id": 301257,
"author": "Guge",
"author_id": 37771,
"author_profile": "https://Stackoverflow.com/users/37771",
"pm_score": 2,
"selected": false,
"text": " private void closeAllOtherToolStripMenuItem_Click(object sender, EventArgs e)\n {\n for (int i = 0; i < this.tabControl1.TabCount; i++)\n if (i != tabControl1.SelectedIndex)\n tabControl1.TabPages.RemoveAt(i--);\n }\n"
},
{
"answer_id": 26857914,
"author": "Selsons Software",
"author_id": 3395709,
"author_profile": "https://Stackoverflow.com/users/3395709",
"pm_score": 2,
"selected": false,
"text": "tabControl.TabPages.Clear()\n"
},
{
"answer_id": 46095473,
"author": "Amritendu Mukhopadhyay",
"author_id": 3843416,
"author_profile": "https://Stackoverflow.com/users/3843416",
"pm_score": 1,
"selected": false,
"text": " private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)\n {\n TabControl.TabPageCollection pages = tabControl1.TabPages;\n foreach (TabPage page in pages)\n {\n saveToolStripMenuItem_Click(sender, e);\n closeTabToolStripMenuItem_Click(sender, e);\n }\n\n }\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,129 | <p>In C++, how can I establish an SQL connection to store data in an SQL database?</p>
| [
{
"answer_id": 301462,
"author": "João Augusto",
"author_id": 6909,
"author_profile": "https://Stackoverflow.com/users/6909",
"pm_score": 0,
"selected": false,
"text": "#import \"c:\\Program Files\\Common Files\\System\\ADO\\msado15.dll\" no_namespace rename( \"EOF\", \"EndOfFile\" )\n // H\nclass CExtAdoDatabase\n{\n\npublic:\n CExtAdoDatabase( const char* p_cConnectString=\"\", const char* p_cUsername=\"\", const char* p_cPwd=\"\" );\n virtual ~CExtAdoDatabase();\n\n bool Open( const char* p_cConnectString=\"\", const char* p_cUsername=\"\", const char* p_cPwd=\"\" );\n bool Close();\n\n\n\nprivate:\n HRESULT _hInitRes;\n bool _bIsValid;\n\n _ConnectionPtr *_p_pConnection;\n};\n\n\n\n// CPP\nCExtAdoDatabase::CExtAdoDatabase( const char* p_cConnectString, const char* p_cUsername, const char* p_cPwd ) : _hInitRes( CoInitialize( NULL ))\n{\n _p_pConnection = new _ConnectionPtr( \"ADODB.Connection\" );\n\n if( FAILED( _hInitRes ))\n _bIsValid = false;\n else\n {\n _bIsValid = true;\n (*_p_pConnection)->ConnectionTimeout=0;\n (*_p_pConnection)->CommandTimeout=0;\n\n if( p_cConnectString != NULL && strlen(p_cConnectString) )\n {\n _bstr_t scs( p_cConnectString );\n _bstr_t susr( p_cUsername );\n _bstr_t spwd( p_cPwd );\n (*_p_pConnection)->Open( scs, susr, spwd, NULL );\n }\n }\n}\nCExtAdoDatabase::~CExtAdoDatabase()\n{\n Close();\n delete _p_pConnection;\n CoUninitialize();\n}\n\nbool CExtAdoDatabase::Open( const char* p_cConnectString, const char* p_cUsername, const char* p_cPwd )\n{\n if(_bIsValid)\n {\n _bstr_t scs( p_cConnectString );\n _bstr_t susr( p_cUsername );\n _bstr_t spwd( p_cPwd );\n return ((*_p_pConnection)->Open( scs, susr, spwd, NULL ) == S_OK);\n }\n else\n return false;\n}\n\nbool CExtAdoDatabase::Close()\n{\n if( _bIsValid )\n {\n if( (*_p_pConnection)->GetState() == adStateOpen )\n return !!(*_p_pConnection)->Close();\n else\n return true;\n }\n else\n return false;\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34588/"
] |
301,132 | <p>I would like to know the procedure to adopt to parse and obtain text content from Microsoft word (.doc and .docx) documents . programming language used should be plain "C" (should be gcc).</p>
<p>Are there any libraries that already do this job,</p>
<p>extension : can i use the same procedure to parse text from Microsoft power point files also ?</p>
| [
{
"answer_id": 301462,
"author": "João Augusto",
"author_id": 6909,
"author_profile": "https://Stackoverflow.com/users/6909",
"pm_score": 0,
"selected": false,
"text": "#import \"c:\\Program Files\\Common Files\\System\\ADO\\msado15.dll\" no_namespace rename( \"EOF\", \"EndOfFile\" )\n // H\nclass CExtAdoDatabase\n{\n\npublic:\n CExtAdoDatabase( const char* p_cConnectString=\"\", const char* p_cUsername=\"\", const char* p_cPwd=\"\" );\n virtual ~CExtAdoDatabase();\n\n bool Open( const char* p_cConnectString=\"\", const char* p_cUsername=\"\", const char* p_cPwd=\"\" );\n bool Close();\n\n\n\nprivate:\n HRESULT _hInitRes;\n bool _bIsValid;\n\n _ConnectionPtr *_p_pConnection;\n};\n\n\n\n// CPP\nCExtAdoDatabase::CExtAdoDatabase( const char* p_cConnectString, const char* p_cUsername, const char* p_cPwd ) : _hInitRes( CoInitialize( NULL ))\n{\n _p_pConnection = new _ConnectionPtr( \"ADODB.Connection\" );\n\n if( FAILED( _hInitRes ))\n _bIsValid = false;\n else\n {\n _bIsValid = true;\n (*_p_pConnection)->ConnectionTimeout=0;\n (*_p_pConnection)->CommandTimeout=0;\n\n if( p_cConnectString != NULL && strlen(p_cConnectString) )\n {\n _bstr_t scs( p_cConnectString );\n _bstr_t susr( p_cUsername );\n _bstr_t spwd( p_cPwd );\n (*_p_pConnection)->Open( scs, susr, spwd, NULL );\n }\n }\n}\nCExtAdoDatabase::~CExtAdoDatabase()\n{\n Close();\n delete _p_pConnection;\n CoUninitialize();\n}\n\nbool CExtAdoDatabase::Open( const char* p_cConnectString, const char* p_cUsername, const char* p_cPwd )\n{\n if(_bIsValid)\n {\n _bstr_t scs( p_cConnectString );\n _bstr_t susr( p_cUsername );\n _bstr_t spwd( p_cPwd );\n return ((*_p_pConnection)->Open( scs, susr, spwd, NULL ) == S_OK);\n }\n else\n return false;\n}\n\nbool CExtAdoDatabase::Close()\n{\n if( _bIsValid )\n {\n if( (*_p_pConnection)->GetState() == adStateOpen )\n return !!(*_p_pConnection)->Close();\n else\n return true;\n }\n else\n return false;\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34590/"
] |
301,134 | <p>I'm writing a Python application that takes a command as an argument, for example:</p>
<pre><code>$ python myapp.py command1
</code></pre>
<p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p>
<pre><code>myapp/
__init__.py
commands/
__init__.py
command1.py
command2.py
foo.py
bar.py
</code></pre>
<p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p>
<p>Python defines an <code>__import__()</code> function, which takes a string for a module name:</p>
<blockquote>
<p><code>__import__(name, globals=None, locals=None, fromlist=(), level=0)</code></p>
<p>The function imports the module <code>name</code>, potentially using the given <code>globals</code> and <code>locals</code> to determine how to interpret the name in a package context. The <code>fromlist</code> gives the names of objects or submodules that should be imported from the module given by <code>name</code>.</p>
<p>Source: <a href="https://docs.python.org/3/library/functions.html#__import_" rel="nofollow noreferrer">https://docs.python.org/3/library/functions.html#__import_</a>_</p>
</blockquote>
<p>So currently I have something like:</p>
<pre><code>command = sys.argv[1]
try:
command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
except ImportError:
# Display error message
command_module.run()
</code></pre>
<p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p>
<p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
<hr />
<p><sub><strong>See also:</strong> <a href="https://stackoverflow.com/questions/67631">How do I import a module given the full path?</a></sub></p>
| [
{
"answer_id": 301139,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "exec exec(\"import myapp.commands.%s\" % command)\n"
},
{
"answer_id": 301146,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 10,
"selected": true,
"text": "importlib.import_module exec __import__ >>> moduleNames = ['sys', 'os', 're', 'unittest'] \n>>> moduleNames\n['sys', 'os', 're', 'unittest']\n>>> modules = map(__import__, moduleNames)\n"
},
{
"answer_id": 301165,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 4,
"selected": false,
"text": "__import__()"
},
{
"answer_id": 301298,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 7,
"selected": false,
"text": "imp.load_source(name, path)\nimp.load_compiled(name, path)\n import imp\nimport os\n\ndef load_from_file(filepath):\n class_inst = None\n expected_class = 'MyClass'\n\n mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])\n\n if file_ext.lower() == '.py':\n py_mod = imp.load_source(mod_name, filepath)\n\n elif file_ext.lower() == '.pyc':\n py_mod = imp.load_compiled(mod_name, filepath)\n\n if hasattr(py_mod, expected_class):\n class_inst = getattr(py_mod, expected_class)()\n\n return class_inst\n"
},
{
"answer_id": 3529271,
"author": "Marc de Lignie",
"author_id": 426130,
"author_profile": "https://Stackoverflow.com/users/426130",
"pm_score": -1,
"selected": false,
"text": "import sys, glob\nsys.path.append('/home/marc/python/importtest/modus')\nfl = glob.glob('modus/*.py')\nmodulist = []\nadapters=[]\nfor i in range(len(fl)):\n fl[i] = fl[i].split('/')[1]\n fl[i] = fl[i][0:(len(fl[i])-3)]\n modulist.append(getattr(__import__(fl[i]),fl[i]))\n adapters.append(modulist[i]())\n class modu1():\n def __init__(self):\n self.x=1\n print self.x\n"
},
{
"answer_id": 8028743,
"author": "Jonathan Livni",
"author_id": 348545,
"author_profile": "https://Stackoverflow.com/users/348545",
"pm_score": 4,
"selected": false,
"text": ">>> mod = 'sys'\n>>> locals()['my_module'] = __import__(mod)\n>>> my_module.version\n'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'\n globals()"
},
{
"answer_id": 14000967,
"author": "Denis Malinovsky",
"author_id": 141343,
"author_profile": "https://Stackoverflow.com/users/141343",
"pm_score": 9,
"selected": false,
"text": "importlib importlib.import_module( name, package=None) pkg.mod ..mod import_module('..mod', 'pkg.subpkg') pkg.mod my_module = importlib.import_module('os.path')\n"
},
{
"answer_id": 17394692,
"author": "stamat",
"author_id": 1909864,
"author_profile": "https://Stackoverflow.com/users/1909864",
"pm_score": 2,
"selected": false,
"text": "import os\nimport imp\n\ndef importFromURI(uri, absl):\n mod = None\n if not absl:\n uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri))\n path, fname = os.path.split(uri)\n mname, ext = os.path.splitext(fname)\n\n if os.path.exists(os.path.join(path,mname)+'.pyc'):\n try:\n return imp.load_compiled(mname, uri)\n except:\n pass\n if os.path.exists(os.path.join(path,mname)+'.py'):\n try:\n return imp.load_source(mname, uri)\n except:\n pass\n\n return mod\n"
},
{
"answer_id": 46308436,
"author": "PanwarS87",
"author_id": 2528481,
"author_profile": "https://Stackoverflow.com/users/2528481",
"pm_score": 1,
"selected": false,
"text": ">>>import imp; \n>>>fp, pathname, description = imp.find_module(\"/home/test_module\"); \n>>>test_module = imp.load_module(\"test_module\", fp, pathname, description);\n>>>print test_module.print_hello();\n python -c '<above entire code in one line>'\n"
},
{
"answer_id": 54956419,
"author": "Brandt",
"author_id": 687896,
"author_profile": "https://Stackoverflow.com/users/687896",
"pm_score": 5,
"selected": false,
"text": "import sys\nimport importlib.util\n\nfile_path = 'pluginX.py'\nmodule_name = 'pluginX'\n\nspec = importlib.util.spec_from_file_location(module_name, file_path)\nmodule = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(module)\n\n# check if it's all there..\ndef bla(mod):\n print(dir(mod))\nbla(module)\n hello pluginX.py module module.hello() hello module pluginX sys.modules[module_name] = module\n\nfrom pluginX import hello\nhello()\n pluginX/__init__.py import importlib\n\npkg = importlib.import_module('pluginX')\n\n# check if it's all there..\ndef bla(mod):\n print(dir(mod))\nbla(pkg)\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15061/"
] |
301,143 | <p>My program works already, I have Perl (GUI Window) where I can input data, data passed to the webpage (using to Tomcat server, JSP) and then <strong>saved</strong> it to oracle database. What I want is to make search parameter (webapp) that <strong>retrieve/extract</strong> data from the Oracle database using Perl CGI. Is it possible? Or any suggestions to solve my program? Thanks!:-)</p>
| [
{
"answer_id": 301761,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 3,
"selected": false,
"text": "BEGIN {\n $ENV{ORACLE_HOME} = '/home/oracle/product/10.x.x';\n $ENV{TWO_TASK} = 'DB';\n}\n$dbh = DBI->connect('dbi:Oracle:','scott', 'tiger');\n# - or -\n$dbh = DBI->connect('dbi:Oracle:','scott/tiger');\n my $db = DBI->connect(\"dbi:Oracle:host=$host;sid=$database\", $user, $pass, \n { RaiseError => 0, PrintError => 0 } )\n or croak( \"Unable to connect to DB - $DBI::errstr\" );\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28607/"
] |
301,147 | <p>I want to show a table of fixed width at the center of browser window. Now I use</p>
<pre><code><table width="200" align="center">
</code></pre>
<p>But Visual Studio 2008 gives warning on this line:</p>
<p><em>Attribute 'align' is considered outdated. A newer construct is recommended.</em></p>
<p>What CSS style should I apply to the table to obtain the same layout?</p>
| [
{
"answer_id": 301152,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "style=\"text-align:center;\" \n"
},
{
"answer_id": 301161,
"author": "jalbert",
"author_id": 1360388,
"author_profile": "https://Stackoverflow.com/users/1360388",
"pm_score": 4,
"selected": false,
"text": "<table width=\"200\" style=\"margin-left:auto;margin-right:auto\">\n"
},
{
"answer_id": 301164,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 9,
"selected": true,
"text": "table\n{ \n margin-left: auto;\n margin-right: auto;\n}\n div.centered \n{\n text-align: center;\n}\n\ndiv.centered table \n{\n margin: 0 auto; \n text-align: left;\n}\n\n\n<div class=\"centered\">\n <table>\n …\n </table>\n</div>\n"
},
{
"answer_id": 301167,
"author": "Matt Howell",
"author_id": 2321,
"author_profile": "https://Stackoverflow.com/users/2321",
"pm_score": 0,
"selected": false,
"text": "<div style=\"text-align:center;\">\n <table style=\"margin: 0 auto;\">\n <!-- table markup here. -->\n </table>\n</div>\n"
},
{
"answer_id": 303365,
"author": "Ola Tuvesson",
"author_id": 6903,
"author_profile": "https://Stackoverflow.com/users/6903",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
},
{
"answer_id": 20678264,
"author": "Chandra Shekhar Sharma",
"author_id": 1175394,
"author_profile": "https://Stackoverflow.com/users/1175394",
"pm_score": 0,
"selected": false,
"text": "<style>\n .abc {\n text-align: center;\n }\n</style>\n\n<table class=\"abc\">\n <tr>\n <td>Item1</td>\n <td>Item2</td>\n </tr>\n</table>\n"
},
{
"answer_id": 33859478,
"author": "Mark Manning",
"author_id": 928121,
"author_profile": "https://Stackoverflow.com/users/928121",
"pm_score": 2,
"selected": false,
"text": "<center>\n<table>\n ...\n</table>\n</center>\n text-align: center;\n"
},
{
"answer_id": 57644530,
"author": "Khaled Mohab",
"author_id": 11746160,
"author_profile": "https://Stackoverflow.com/users/11746160",
"pm_score": 0,
"selected": false,
"text": "width: fit-content;\n"
},
{
"answer_id": 57644736,
"author": "Gourav Goutam",
"author_id": 11682270,
"author_profile": "https://Stackoverflow.com/users/11682270",
"pm_score": 0,
"selected": false,
"text": "<table align=\"center\">\n...\n <table style=\"text-align:center;\">\n <body style=\"text-align:center;\">\n<table>\n ...\n</table>\n"
},
{
"answer_id": 73863727,
"author": "Faiz Ma'ruf",
"author_id": 19208272,
"author_profile": "https://Stackoverflow.com/users/19208272",
"pm_score": 0,
"selected": false,
"text": "text-center <table class=\"table table-bordered text-center\">\n <thead>\n <tr>\n <th scope=\"col\">#</th>\n <th scope=\"col\">First</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th scope=\"row\">1</th>\n <td>Mark</td>\n </tr>\n <tr>\n <th scope=\"row\">2</th>\n <td>Jacob</td>\n </tr>\n </tbody>\n </table>\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
301,149 | <p>I am working on my website, and I am trying to get the url parameter "page" which is an integer that tells which entry to read in the MySQL database that hols the HTML for all the pages. Here is my code, with the MySQL username and password removed for security reasons:</p>
<pre><code> if ($_GET["page"]) {
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jmurano_pages", $con);
$title=mysql_query("SELECT title FROM pageContent WHERE pageID=" . $_GET['page']);
echo "<title>" . $title . "</title>\n";
echo "</head>\n";
echo "<body>\n";
$content = mysql_query("SELECT content FROM pageContent WHERE pageID=" . $_GET['page']);
echo $content;
echo "\n</body>\n</html>";
}
</code></pre>
<p>This puts the title as "Resource id #2" and the content as "Resource id #3". I can't think of what I may have done wrong.</p>
<hr>
<p>I'm still confused. I'm a complete PHP newbie. What exactly do I need to do to access the content and title?</p>
| [
{
"answer_id": 301163,
"author": "andy.gurin",
"author_id": 22388,
"author_profile": "https://Stackoverflow.com/users/22388",
"pm_score": 0,
"selected": false,
"text": "SELECT SHOW DESCRIBE EXPLAIN mysql_query() INSERT UPDATE DELETE DROP mysql_query() mysql_fetch_array()"
},
{
"answer_id": 301170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$page = $_GET[\"page\"];\n$escaped_page = mysql_real_escape_string($page);\n"
},
{
"answer_id": 301181,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 3,
"selected": true,
"text": " $res = mysql_query(\"SELECT title FROM pageContent WHERE pageID=\" . $escapedpage);\n $title = mysql_fetch_assoc($res);\n $title = $title['title']\n $res2 = mysql_query(\"SELECT content FROM pageContent WHERE pageID=\" . $escapedpage);\n $content = mysql_fetch_assoc($res2);\n $content = $content['content'];\n $res = mysql_query(\"SELECT title, content FROM pageContent WHERE pageID=\" . $escapedpage);\n$row = mysql_fetch_assoc($res);\n$title = $row['title'];\n$content = $row['content'];\n"
},
{
"answer_id": 301190,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$result = mysql_query($sql);\n\n//for each row in the result, do stuff with it...\nwhile ($row = mysql_fetch_array($result)){\n $title = $row[\"title\"];\n $content = $row[\"content\"];\n\n //this will show you the row data visually\n //var_dump($row);\n}\n"
},
{
"answer_id": 301248,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "mysql_query mysql_error() mysql_fetch_assoc() $row = mysql_fetch_assoc($resource); print_r($row); mysql_fetch_assoc() while ($row = mysql_fetch_assoc($resource)) { // do stuff }"
},
{
"answer_id": 301361,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": false,
"text": "<?php\nif (isset($_GET[\"page\"])) {\n $con = mysql_connect(\"localhost\",\"username\",\"password\");\n if (!$con) {\n die('Could not connect: ' . mysql_error());\n }\n mysql_select_db(\"jmurano_pages\", $con);\n\n $pageId = (int) $_GET['page'];\n\n $result = mysql_query('SELECT title, content FROM pageContent WHERE pageID= ' . $pageId);\n\n if (!$result) {\n die(mysql_error());\n }\n\n $row = mysql_fetch_assoc($result);\n\n if (!$row) {\n die('page not found');\n }\n\n echo \"<title>\" . $row['title'] . \"</title>\\n\";\n echo \"</head>\\n\";\n echo \"<body>\\n\";\n echo $row['content'];\n echo \"\\n</body>\\n</html>\";\n\n} else{ \n //what are you going to do if page is not passed?\n}\n?>\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60881/"
] |
301,158 | <p>I need rich UI designer for editing the web.config for ASP.net application.
From the designer We can edit the tags in config files</p>
<p>It may be any windows application going to edit my config files.</p>
| [
{
"answer_id": 301656,
"author": "Martin Kool",
"author_id": 216896,
"author_profile": "https://Stackoverflow.com/users/216896",
"pm_score": 1,
"selected": false,
"text": "C:\\Program Files\\Microsoft Visual Studio 9.0\\Xml\\Schemas\n <configuration xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\">\n <configuration>\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
301,160 | <p>Can someone explain the difference between:</p>
<ul>
<li>lock (someobject) {}</li>
<li>Using Mutex</li>
<li>Using Semaphore</li>
<li>Using Monitor</li>
<li>Using Other .Net synchronization classes</li>
</ul>
<p>I just can't figure it out. It seems to me the first two are the same?</p>
| [
{
"answer_id": 301175,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 4,
"selected": false,
"text": "object obj = x;\nSystem.Threading.Monitor.Enter(obj);\ntry {\n …\n}\nfinally {\n System.Threading.Monitor.Exit(obj);\n}\n"
},
{
"answer_id": 59976799,
"author": "Alexander Danilov",
"author_id": 1768179,
"author_profile": "https://Stackoverflow.com/users/1768179",
"pm_score": -1,
"selected": false,
"text": "System.Collections.Concurrent Objc/Swift"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38834/"
] |
301,162 | <p>Aside from using the region to infer which carrier the user is under.</p>
| [
{
"answer_id": 8797144,
"author": "Louie",
"author_id": 270760,
"author_profile": "https://Stackoverflow.com/users/270760",
"pm_score": 2,
"selected": false,
"text": "#import <CoreTelephony/CTTelephonyNetworkInfo.h> CTTelephonyNetworkInfo *phoneInfo = [[CTTelephonyNetworkInfo alloc] init];\nCTCarrier *phoneCarrier = [phoneInfo subscriberCellularProvider];\nNSLog(@\"Carrier = %@\", [phoneCarrier carrierName]);\n[phoneInfo release];\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38836/"
] |
301,168 | <p>Is there a way to define the timezone for an application in ASP.NET such that all times read from/compared to current server time are implicitly converted, or do I need to put in conversion statements as each and every DateTime.Now call?</p>
| [
{
"answer_id": 24683327,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 1,
"selected": false,
"text": "DateTime.Now DateTime.UtcNow DateTimeOffset DateTimeOffset.Now DateTimeOffset.UtcNow TimeZoneInfo"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
301,174 | <p>How to delete a file which is in use/open by some process in runtime.
I am using vb.net for my project and a image is shown in picturebox,
and that should be deleted, without closing that file.</p>
| [
{
"answer_id": 301188,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "MoveFileEx() MOVEFILE_DELAY_UNTIL_REBOOT NULL DeleteFile()"
},
{
"answer_id": 24577825,
"author": "SomeDude",
"author_id": 3806045,
"author_profile": "https://Stackoverflow.com/users/3806045",
"pm_score": 0,
"selected": false,
"text": "For Each proc As Process In System.Diagnostics.Process.GetProcessesByName(\"process name here\")\nproc.Kill()\nNext\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,176 | <p>I need to use a byte array as a profile property in a website. Normally I would declare the type as system.string or system.int32 but I have no idea what the type if for a byte array.</p>
<p>EDIT: I need to use this as profile property that is declared in the web.config like below:</p>
<pre><code><profile defaultProvider="ProfileProvider" enabled="true">
<properties>
<add name="Username" allowAnonymous="false" type="System.String" />
<add name="LoginToken" allowAnonymous="false" type=" System.Byte()" />
</properties>
</profile>
</code></pre>
| [
{
"answer_id": 301188,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "MoveFileEx() MOVEFILE_DELAY_UNTIL_REBOOT NULL DeleteFile()"
},
{
"answer_id": 24577825,
"author": "SomeDude",
"author_id": 3806045,
"author_profile": "https://Stackoverflow.com/users/3806045",
"pm_score": 0,
"selected": false,
"text": "For Each proc As Process In System.Diagnostics.Process.GetProcessesByName(\"process name here\")\nproc.Kill()\nNext\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23230/"
] |
301,193 | <p>how do I get information about a photo like the author, the license using PHP?</p>
| [
{
"answer_id": 558508,
"author": "Jeff Winkworth",
"author_id": 1306,
"author_profile": "https://Stackoverflow.com/users/1306",
"pm_score": 2,
"selected": false,
"text": "$query = \"http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=\" . API_KEY . \"&photo_id=\" . $photoid . \"&format=json&nojsoncallback=1\";\ndata = json_decode(file_get_contents($query));\n\necho \"created by: \" . data->photo->owner->username;\necho \"link to photopage: \" . \"http://www.flickr.com/photos/\" . data->photo->owner->nsid; . \"/\" . data->photo->id;\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,203 | <p>Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.</p>
<p>For example:</p>
<pre><code>typedef std::bitset<16> WordSet;
</code></pre>
<p>Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler specific implementations are welcome, though I'm particularly interested in <code>g++</code>.</p>
| [
{
"answer_id": 301228,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "std::bitset size() size_t sz = oh_my_word.size(); // sz is now 16\n template <int N>\nclass Foo\n{\npublic:\n int size() const { return N; }\n};\n"
},
{
"answer_id": 301274,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": true,
"text": "template<int N>\nstruct foo {\n static const int value = N;\n};\n template<typename T>\nstruct foo {\n typedef T type;\n};\n foo<39>::value foo<int>::type template<typename>\nstruct steal_it;\n\ntemplate<std::size_t N>\nstruct steal_it< std::bitset<N> > {\n static const std::size_t value = N;\n};\n steal_it< std::bitset<16> >::value template<typename T>\nchar (& getN(T const &) )[steal_it<T>::value]; \n\nint main() {\n std::bitset<16> b;\n sizeof getN(b); // assuming you don't know the type, you can use the object\n}\n"
},
{
"answer_id": 48202529,
"author": "Mark Garcia",
"author_id": 1619294,
"author_profile": "https://Stackoverflow.com/users/1619294",
"pm_score": 4,
"selected": false,
"text": "#include <type_traits>\n#include <iostream>\n\ntemplate<int>\nstruct foo {};\n\ntemplate<int arg_N>\nstruct val {\n static constexpr auto N = arg_N;\n};\n\ntemplate<template <int> typename T, int N>\nconstexpr auto extract(const T<N>&) -> val<N>;\n\ntemplate<typename T>\nconstexpr auto extract_N = decltype(extract(std::declval<T>()))::N;\n\n\nint main() {\n std::cout << extract_N<foo<5>>;\n}\n"
},
{
"answer_id": 48608671,
"author": "Amir Kirsh",
"author_id": 2085626,
"author_profile": "https://Stackoverflow.com/users/2085626",
"pm_score": 1,
"selected": false,
"text": "std::bitset size() template <template<std::size_t> typename T, std::size_t K>\nauto extractSize(const T<K>&) {\n return K;\n}\n\nint main() {\n std::bitset<6> f1;\n std::bitset<13> f2;\n std::cout << extractSize(f1) << std::endl;\n std::cout << extractSize(f2) << std::endl;\n}\n"
},
{
"answer_id": 58157754,
"author": "cd127",
"author_id": 2834727,
"author_profile": "https://Stackoverflow.com/users/2834727",
"pm_score": 3,
"selected": false,
"text": "#include <type_traits>\n#include <iostream>\n\ntemplate<int>\nstruct MyType {};\n\ntemplate<template <int> typename T, int N>\nconstexpr int extract(const T<N>&) { return N; }\n\nint main() {\n constexpr MyType<5> myObj;\n std::cout << extract(myObj);\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
301,215 | <p>How do I get the current wallpaper on a Mac? Just point me to an API function so I can Google more.</p>
<p>Edit: I think I found it. [NSUserDefaults standardUserDefaults] mentioned at <a href="http://lists.apple.com/archives/student-dev/2004/Aug/msg00140.html" rel="noreferrer">http://lists.apple.com/archives/student-dev/2004/Aug/msg00140.html</a></p>
<p>Also possible from shell:
defaults read com.apple.desktop Background</p>
<p>And from AppleScript:
<a href="http://discussions.apple.com/thread.jspa?messageID=7111272" rel="noreferrer">http://discussions.apple.com/thread.jspa?messageID=7111272</a></p>
| [
{
"answer_id": 301573,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 4,
"selected": true,
"text": "/Users/<current-user>/Application Support/Dock/desktoppicture.db \n sqlite3 \"/Application Support/Dock/desktoppicture.db\"\n SELECT display_uuid,space_uuid,value \nFROM preferences \nJOIN data ON preferences.data_id=data.ROWID \nJOIN pictures ON preferences.picture_id=pictures.ROWID\nJOIN displays ON pictures.display_id=displays.ROWID \nJOIN spaces ON pictures.space_id=spaces.ROWID ;\n <UID1>|<UID2>|<PicturePath>\n<UID1>|<UID2>|<PicturePath>\n:\n UID1 UID2 <PicturePath> sqlite .exit killall Dock killall -HUP Dock killall /Users/<current-user>/Library/Preferences/com.apple.desktop.plist\n default ImageFilePath"
},
{
"answer_id": 30753373,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\nosascript -e 'tell app \"finder\" to get posix path of (get desktop picture as alias)'\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005/"
] |
301,221 | <p>I am executing a <code>diff</code> command in <code>perl</code>.</p>
<pre><code>my @lines = `/usr/local/bin/diff -udr \"$expected_file\" \"$gen_file\"`;
if ($? != 0)
{
print ERRFILE "Diff between $expected_file and $gen_file failed\n";
return $diff_err;
}
</code></pre>
<p>Here the <code>diff</code> might have failed because of some reason. For example: the stderr showed that <em>/usr/local/bin/diff: test.txt: No such file or directory</em>. I want to read this message in the program. How I can find the stderr message of the <code>diff</code> command (or <code>grep</code> or any command I execute)?</p>
<p>Appreciate the help in advance.</p>
<p>Thanks,
Mathew Liju</p>
| [
{
"answer_id": 301428,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 5,
"selected": true,
"text": "2>file.txt"
},
{
"answer_id": 301764,
"author": "xdg",
"author_id": 11800,
"author_profile": "https://Stackoverflow.com/users/11800",
"pm_score": 2,
"selected": false,
"text": "use IO::CaptureOutput 'qxx';\n\n\nmy ($stdout, $stderr, $ok) = \n qxx( qq(/usr/local/bin/diff -udr \"$expected_file\" \"$gen_file\") );\n\nif (! $ok)\n{\n print ERRFILE \"Diff between $expected_file and $gen_file failed\\n\";\n return $stderr;\n}\n\nmy @lines = split /\\n/, $stdout;\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18657/"
] |
301,230 | <p>I'm trying to create routes which follow the structure of a tree navigation system, i.e I want to include the entire path in the tree in my route. So if I had a tree which looked like this</p>
<ul>
<li>Computers
<ul>
<li>Software
<ul>
<li>Development</li>
<li>Graphics</li>
</ul></li>
<li>Hardware
<ul>
<li>CPU</li>
<li>Graphics cards</li>
</ul></li>
</ul></li>
</ul>
<p>Then I would like to be able to have routes that looks like this</p>
<ul>
<li>site.com/catalog/computers/software/graphics</li>
</ul>
<p>This, on it's own is not hard and can be caught by a route which looks like this</p>
<ul>
<li>catalog/{*categories}</li>
</ul>
<p>However I want to be able to add the product information at the end of that URL, something like this</p>
<ul>
<li>site.com/catalog/computers/software/graphics/title=Photoshop</li>
</ul>
<p>Which would mean I would requite routes that were defined like the following examples</p>
<ul>
<li>site.com/{*categories}/title={name}</li>
<li>site.com/{*categories}</li>
</ul>
<p>However the first of these routes are invalid since nothing else can appear after a greedy parameter such as {*categories} so I'm a bit stuck. I've been thinking of implementing regex routes or perhaps use IRouteContraint to work my way around this but I can't think of a decent solution that would enable me to also use the <strong>Html.ActionLink(...)</strong> method to generate outbount URLs which filled in both {*categories} and {name}</p>
<p>Any advice is greatly apprechiated!</p>
<p><em>Some of you may have seen a similar question by me yesterday but that was deleted, by me, since I've since given it more thought and the old question contained incomplete descriptions of my problem</em></p>
<p><strong>UPDATE 2008/11/26</strong> I posted the solution at <a href="http://thecodejunkie.blogspot.com/2008/11/supporting-complex-route-patterns-with.html" rel="nofollow noreferrer">http://thecodejunkie.blogspot.com/2008/11/supporting-complex-route-patterns-with.html</a></p>
| [
{
"answer_id": 5308946,
"author": "Robert Koritnik",
"author_id": 75642,
"author_profile": "https://Stackoverflow.com/users/75642",
"pm_score": 2,
"selected": false,
"text": "GreedyRoute {segment}/{segment}/{*greedy} Route {segment}/{*greedy}/{segment} {*greedy}/{segment}/{segment}"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25319/"
] |
301,233 | <p>I am using Xcode to develop a GUI application. I have a model class and a controller class. I have a NSTextView data member in my controller class. How do I access this variable from the model class?</p>
| [
{
"answer_id": 301565,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 4,
"selected": false,
"text": "MyController * c = [[MyController alloc] init];\n// c has a member name textView, let's access it\n[c->textView ...];\n // This goes into the controller\n\n- (NSTextView) textView\n{\n return textView;\n}\n\n// This is called in the modell\n\n[[c textView] ...];\n // In the controller\n\n- (void) notifyContentHasChanged:(NSString *)name\n{\n // update the text view here ...\n}\n\n// In the modell\n\n[c notifyContentHasChanged:...];\n"
},
{
"answer_id": 309694,
"author": "Cody Brimhall",
"author_id": 18388,
"author_profile": "https://Stackoverflow.com/users/18388",
"pm_score": 1,
"selected": false,
"text": "#import @class *.m @class @class"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,234 | <p>I have a question regarding an update function I created...</p>
<pre><code>CREATE OR REPLACE FUNCTION rm_category_update(icompany bpchar, iraw_mat_cat_code bpchar, iraw_mat_cat_desc bpchar)
RETURNS character AS
$BODY$
DECLARE
loc_result CHAR(50);
BEGIN
UPDATE rm_category
SET
raw_mat_cat_code = iraw_mat_cat_code,
raw_mat_cat_desc = iraw_mat_cat_desc
WHERE company = icompany;
loc_result = 'success';
RETURN loc_result ;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION rm_category_update(icompany bpchar, iraw_mat_cat_code bpchar, iraw_mat_cat_desc bpchar) OWNER TO postgres;
</code></pre>
<p>Okay, so if I input a record that doesn't exist, for example 9, it returns success even though I know it has updated nothing! </p>
<p>Does SQL not throw errors if it is updating a non-existent row??</p>
<p>Thanks</p>
| [
{
"answer_id": 301565,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 4,
"selected": false,
"text": "MyController * c = [[MyController alloc] init];\n// c has a member name textView, let's access it\n[c->textView ...];\n // This goes into the controller\n\n- (NSTextView) textView\n{\n return textView;\n}\n\n// This is called in the modell\n\n[[c textView] ...];\n // In the controller\n\n- (void) notifyContentHasChanged:(NSString *)name\n{\n // update the text view here ...\n}\n\n// In the modell\n\n[c notifyContentHasChanged:...];\n"
},
{
"answer_id": 309694,
"author": "Cody Brimhall",
"author_id": 18388,
"author_profile": "https://Stackoverflow.com/users/18388",
"pm_score": 1,
"selected": false,
"text": "#import @class *.m @class @class"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,239 | <p>Well I testing my jython program, that does some neat [".xls", ".doc", ".rtf", ".tif", ".tiff", ".pdf" files] -> pdf (intermediary file) -> tif (final output) conversion using Open Office. We moved away from MS Office due to the problems we had with automation. Now it seems we have knocked down many bottles related to show stopper errors with one bottle remaining. OO hangs after a while. </p>
<p>It happens where you see this line '<<<<<<<<<<<<' in the code </p>
<p>What is the correct way for me to handle a stalled Open Office process. could you please provide useful links, and give me a good suggestion on the way out.<br>
Also one more question. </p>
<p>Sum up:<br>
* How to handle a stalled Open Office instance?<br>
* How to make conversion with java headless, so I dont have a GUI popping up all the time wasting memory.<br>
* also any general suggestions on code quality, optimizations and general coding standards will be most appreciated.</p>
<hr>
<p>Traceback (innermost last):<br>
File "dcmail.py", line 184, in ?<br>
File "dcmail.py", line 174, in main<br>
File "C:\DCMail\digestemails.py", line 126, in process_inbox<br>
File "C:\DCMail\digestemails.py", line 258, in _convert<br>
File "C:\DCMail\digestemails.py", line 284, in _choose_conversion_type<br>
File "C:\DCMail\digestemails.py", line 287, in _open_office_convert<br>
File "C:\DCMail\digestemails.py", line 299, in _load_attachment_to_convert<br>
com.sun.star.lang.DisposedException: java.io.EOFException<br>
at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDi
spatcher.run(java_remote_bridge.java:176) </p>
<p>com.sun.star.lang.DisposedException: com.sun.star.lang.DisposedException: java.i
o.EOFException </p>
<p>Just to clear up this exception only throws when I kill the open office process. Otherwise the program just waits for open office to complete. Indefinitely </p>
<hr>
<p>The Code (with non functional code tags) </p>
<p>[code] </p>
<blockquote>
<blockquote>
<pre><code>#ghost script handles these file types
GS_WHITELIST=[".pdf"]
#Open Office handles these file types
OO_WHITELIST=[".xls", ".doc", ".rtf", ".tif", ".tiff"]
#whitelist is used to check against any unsupported files.
WHITELIST=GS_WHITELIST + OO_WHITELIST
</code></pre>
</blockquote>
</blockquote>
<pre><code>def _get_service_manager(self):
try:
self._context=Bootstrap.bootstrap();
self._xMultiCompFactory=self._context.getServiceManager()
self._xcomponentloader=UnoRuntime.queryInterface(XComponentLoader, self._xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", self._context))
except:
raise OpenOfficeException("Exception Occurred with Open Office")
def _choose_conversion_type(self,fn):
ext=os.path.splitext(fn)[1]
if ext in GS_WHITELIST:
self._ghostscript_convert_to_tiff(fn)
elif ext in OO_WHITELIST:
self._open_office_convert(fn)
def _open_office_convert(self,fn):
self._load_attachment_to_convert(fn)
self._save_as_pdf(fn)
self._ghostscript_convert_to_tiff(fn)
def _load_attachment_to_convert(self, file):
file=self._create_UNO_File_URL(file)
properties=[]
p=PropertyValue()
p.Name="Hidden"
p.Value=True
properties.append(p)
properties=tuple(properties)
self._doc=self._xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) <<<<<<<<<<<<<<< here is line 299
def _create_UNO_File_URL(self, filepath):
try:
file=str("file:///" + filepath)
file=file.replace("\\", "/")
except MalformedURLException, e:
raise e
return file
def _save_as_pdf(self, docSource):
dirName=os.path.dirname(docSource)
baseName=os.path.basename(docSource)
baseName, ext=os.path.splitext(baseName)
dirTmpPdfConverted=os.path.join(dirName + DIR + PDF_TEMP_CONVERT_DIR)
if not os.path.exists(dirTmpPdfConverted):
os.makedirs(dirTmpPdfConverted)
pdfDest=os.path.join(dirTmpPdfConverted + DIR + baseName + ".pdf")
url_save=self._create_UNO_File_URL(pdfDest)
properties=self._create_properties(ext)
try:
try:
self._xstorable=UnoRuntime.queryInterface(XStorable, self._doc);
self._xstorable.storeToURL(url_save, properties)
except AttributeError,e:
self.logger.info("pdf file already created (" + str(e) + ")")
raise e
finally:
try:
self._doc.dispose()
except:
raise
def _create_properties(self,ext):
properties=[]
p=PropertyValue()
p.Name="Overwrite"
p.Value=True
properties.append(p)
p=PropertyValue()
p.Name="FilterName"
if ext==".doc":
p.Value='writer_pdf_Export'
elif ext==".rtf":
p.Value='writer_pdf_Export'
elif ext==".xls":
p.Value='calc_pdf_Export'
elif ext==".tif":
p.Value='draw_pdf_Export'
elif ext==".tiff":
p.Value='draw_pdf_Export'
properties.append(p)
return tuple(properties)
def _ghostscript_convert_to_tiff(self, docSource):
dest, source=self._get_dest_and_source_conversion_file(docSource)
try:
command = ' '.join([
self._ghostscriptPath + 'gswin32c.exe',
'-q',
'-dNOPAUSE',
'-dBATCH',
'-r500',
'-sDEVICE=tiffg4',
'-sPAPERSIZE=a4',
'-sOutputFile=%s %s' % (dest, source),
])
self._execute_ghostscript(command)
self.convertedTifDocList.append(dest)
except OSError, e:
self.logger.info(e)
raise e
except TypeError, (e):
raise e
except AttributeError, (e):
raise e
except:
raise
</code></pre>
<p>[/code]</p>
| [
{
"answer_id": 301565,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 4,
"selected": false,
"text": "MyController * c = [[MyController alloc] init];\n// c has a member name textView, let's access it\n[c->textView ...];\n // This goes into the controller\n\n- (NSTextView) textView\n{\n return textView;\n}\n\n// This is called in the modell\n\n[[c textView] ...];\n // In the controller\n\n- (void) notifyContentHasChanged:(NSString *)name\n{\n // update the text view here ...\n}\n\n// In the modell\n\n[c notifyContentHasChanged:...];\n"
},
{
"answer_id": 309694,
"author": "Cody Brimhall",
"author_id": 18388,
"author_profile": "https://Stackoverflow.com/users/18388",
"pm_score": 1,
"selected": false,
"text": "#import @class *.m @class @class"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
301,241 | <p>I am getting a web host and i have projects with teammats. I thought it be a nice idea to have my own paste site that has no expiry date on paste (i know <a href="http://pastie.org/" rel="nofollow noreferrer">http://pastie.org/</a> exist) and other things. i wanted to know. Whats a simple highlight lib i can use on code? i would be only using C/C++.</p>
| [
{
"answer_id": 301300,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "$cpplex = '/\n (?<string>\"(?:\\\\\\\\\"|.)*?\")|\n (?<char>\\'(?:\\\\\\\\\\'|.)*?\\')|\n (?<comment>\\\\/\\\\/.*?\\n|\\\\/\\*.*?\\*\\\\/)|\n (?<preprocessor>#\\w+(?:\\\\\\\\\\n|[^\\\\\\\\])*?\\n)| # This one is not perfect!\n (?<number>\n (?: # Integer followed by optional fractional part.\n (?:0(?:\n x[0-9a-f]+|[0-7]*)|\\d+)\n (?:\\.\\d*)?(?:e[+-]\\d+)?)\n |(?: # Just the fractional part.\n (?:\\.\\d*)(?:e[+-]\\d+)?))|\n (?<keyword>asm|auto|break|case…)| # TODO Complete. Include ciso646!\n (?<identifier>\\\\w(?:\\\\w|\\\\d)*)\n /xs';\n\n$matches = preg_match_all($cpplex, $input, $matches, PREG_OFFSET_CAPTURE);\n\nforeach ($matches as $match) {\n // TODO: determine which group was matched.\n // Don't forget lexemes that are *not* part of the expression:\n // i.e. whitespaces and operators. These are between the matches.\n echo \"<span class=\\\"$keyword\\\">$token</span>\";\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,247 | <p>The <strong><code>fuser</code></strong> command lets me know which processes are using a file or directory.</p>
<p>I'm looking for command that does the opposite: lets me know which files are being used by a process.</p>
<hr>
<h2>Update</h2>
<p>Forgot to mention that it's for a Solaris system.</p>
| [
{
"answer_id": 301255,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "lsof -p <pid>\n"
},
{
"answer_id": 301332,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "ls -la /proc/2055/fd \ntotal 0\ndr-x------ 2 kent kent 0 Nov 19 21:44 .\ndr-xr-xr-x 7 kent kent 0 Nov 19 21:42 ..\nlr-x------ 1 kent kent 64 Nov 19 21:44 0 -> /dev/null\nl-wx------ 1 kent kent 64 Nov 19 21:44 1 -> /home/kent/.xsession-errors\nlrwx------ 1 kent kent 64 Nov 19 21:44 10 -> socket:[3977613]\nlrwx------ 1 kent kent 64 Nov 19 21:44 11 -> /home/kent/.googleearth/Cache/dbCache.dat\nlrwx------ 1 kent kent 64 Nov 19 21:44 12 -> /home/kent/.googleearth/Cache/dbCache.dat.index\nlrwx------ 1 kent kent 64 Nov 19 21:44 13 -> socket:[3978765]\nlrwx------ 1 kent kent 64 Nov 19 21:44 14 -> socket:[3978763]\nlrwx------ 1 kent kent 64 Nov 19 21:44 15 -> socket:[3978766]\nlrwx------ 1 kent kent 64 Nov 19 21:44 17 -> socket:[3978764]\nl-wx------ 1 kent kent 64 Nov 19 21:44 2 -> /home/kent/.xsession-errors\nlr-x------ 1 kent kent 64 Nov 19 21:44 3 -> pipe:[3977583]\nl-wx------ 1 kent kent 64 Nov 19 21:44 4 -> pipe:[3977583]\nlr-x------ 1 kent kent 64 Nov 19 21:44 5 -> pipe:[3977584]\nl-wx------ 1 kent kent 64 Nov 19 21:44 6 -> pipe:[3977584]\nlr-x------ 1 kent kent 64 Nov 19 21:44 7 -> pipe:[3977587]\nl-wx------ 1 kent kent 64 Nov 19 21:44 8 -> pipe:[3977587]\nlrwx------ 1 kent kent 64 Nov 19 21:44 9 -> socket:[3977588]\n cat /proc/2055/fdinfo/11 \npos: 232741818\nflags: 02\n"
},
{
"answer_id": 391953,
"author": "tpgould",
"author_id": 32161,
"author_profile": "https://Stackoverflow.com/users/32161",
"pm_score": 5,
"selected": true,
"text": "% tail -f /etc/motd &\n[1] 6033\n\n% pfiles 6033\n6033: tail -f /etc/motd\n\n Current rlimit: 256 file descriptors\n 0: S_IFREG mode:0644 dev:182,65538 ino:163065 uid:0 gid:3 size:54\n O_RDONLY|O_LARGEFILE\n /etc/motd\n 1: S_IFCHR mode:0620 dev:299,0 ino:718837882 uid:101 gid:7 rdev:24,3\n O_RDWR|O_NOCTTY|O_LARGEFILE\n /dev/pts/3\n 2: S_IFCHR mode:0620 dev:299,0 ino:718837882 uid:101 gid:7 rdev:24,3\n O_RDWR|O_NOCTTY|O_LARGEFILE\n /dev/pts/3\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
301,283 | <p>I am developing a Java desktop application and would like to have an external configuration.xml.<br>
I am developing the application using Netbeans and tried to add the configuration.xml file in the dist directory so that it resides in the application work folder. But when Netbeans executes its clean operation it deletes the dist directory,<br>
Where should I put this configuration.xml file so that it will not be deleted and will exist in the application start-up directory.</p>
| [
{
"answer_id": 301405,
"author": "Michel",
"author_id": 7198,
"author_profile": "https://Stackoverflow.com/users/7198",
"pm_score": 5,
"selected": true,
"text": "<target name=\"-post-jar\">\n <copy todir=\"${dist.jar.dir}\">\n <fileset dir=\"resources\" includes=\"**\"/>\n </copy> \n</target>\n"
},
{
"answer_id": 7351287,
"author": "Robert Casey",
"author_id": 600584,
"author_profile": "https://Stackoverflow.com/users/600584",
"pm_score": 1,
"selected": false,
"text": " <target name=\"netbeans-extra\">\n <echo>Copying resources files to build cluster directory...</echo>\n <mkdir dir=\"${cluster}/resources\"/>\n <copy todir=\"${cluster}/resources\">\n <fileset dir=\"resources\" includes=\"**\"/>\n </copy>\n </target>\n"
},
{
"answer_id": 11078800,
"author": "Mata",
"author_id": 1463048,
"author_profile": "https://Stackoverflow.com/users/1463048",
"pm_score": 1,
"selected": false,
"text": "<target name=\"-pre-jar\">\n <echo>Copying resources files to build directory...</echo>\n <mkdir dir=\"${dist.jar.dir}/resources\"/>\n <copy todir=\"${dist.jar.dir}/resources\">\n <fileset dir=\"resources\" includes=\"**\"/>\n </copy>\n</target>\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34145/"
] |
301,284 | <p>I have example of code below. </p>
<pre><code><script type="text/javascript" src="assets/scripts/somescript.php">.
</script>
</code></pre>
<p>So, will my browser still cache this just by not setting this scripts headers meta tag cache to must-revalidate?</p>
| [
{
"answer_id": 301299,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 0,
"selected": false,
"text": "Content-type: text/javascript; charset=\"your_charset\" header()"
},
{
"answer_id": 301316,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": true,
"text": "header(\"Expires: \" . date(\"r\", time() + ( 60 * 60 * 24 * 7 * 1 ) ) ); // Expires in 1 week\nheader(\"Content-Type: application/x-javascript\");\n"
},
{
"answer_id": 301569,
"author": "Magnus Smith",
"author_id": 11461,
"author_profile": "https://Stackoverflow.com/users/11461",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"assets/scripts/somescript.php?date=20081118\"></script> \n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24744/"
] |
301,290 | <p>I want to increase the I/O priority of a process. Answers for both .NET and Windows Vista would be nice. processexplorer is ok as well.</p>
| [
{
"answer_id": 301333,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 6,
"selected": true,
"text": "FILE_IO_PRIORITY_HINT_INFO priorityHint;\npriorityHint.PriorityHint = IoPriorityHintLow;\nresult = SetFileInformationByHandle( hFile,\n FileIoPriorityHintInfo,\n &priorityHint,\n sizeof(PriorityHint));\n // reduce CPU, page and IO priority for the whole process\nresult = SetPriorityClass( GetCurrentProcess(),\n PROCESS_MODE_BACKGROUND_BEGIN);\n// do stuff\nresult = SetPriorityClass( GetCurrentProcess(),\n PROCESS_MODE_BACKGROUND_END);\n // reduce CPU, page and IO priority for the current thread\nSetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);\n// do stuff\nSetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);\n // reserve bandwidth of 200 bytes/sec\nresult = SetFileBandwidthReservation( hFile,\n 1000,\n 200,\n FALSE,\n &transferSize,\n &outstandingRequests );\n"
},
{
"answer_id": 3057675,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 4,
"selected": false,
"text": "NtSetInformationProcess ProcessIoPriority ExeTask::GetYourPrioritiesStraight PROCESS_INFORMATION_CLASS ProcessIoPriority Very Low: 0\nLow: 1\nNormal: 2\nHigh: 3 or above?\n SetPriorityClass PROCESS_MODE_BACKGROUND_BEGIN SetPriorityClass"
},
{
"answer_id": 5334669,
"author": "dodgy_coder",
"author_id": 507950,
"author_profile": "https://Stackoverflow.com/users/507950",
"pm_score": 1,
"selected": false,
"text": "// Set the current process to run at 'High' Priority\nSystem.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();\nprocess.PriorityClass = System.Diagnostics.ProcessPriorityClass.High;\n\n// Set the current thread to run at 'Highest' Priority\nThread thread = System.Threading.Thread.CurrentThread;\nthread.Priority = ThreadPriority.Highest;\n"
},
{
"answer_id": 16362414,
"author": "Michel Lemay",
"author_id": 1607185,
"author_profile": "https://Stackoverflow.com/users/1607185",
"pm_score": 2,
"selected": false,
"text": "FILE_IO_PRIORITY_HINT_INFO SetFileInformationByHandle ERROR_NOACCESS _declspec(align(8)) FILE_IO_PRIORITY_HINT_INFO priorityHint;\npriorityHint.PriorityHint = IoPriorityHintLow;\n\nBOOL ret = SetFileInformationByHandle(hFile, FileIoPriorityHintInfo, &priorityHint, sizeof(FILE_IO_PRIORITY_HINT_INFO));\nDWORD err = GetLastError();\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35012/"
] |
301,302 | <p>I'm using RSACryptoServiceProvider in .NET 2 and it seems that the Private part of a Public/Private key pair always contains the Public part as well.</p>
<p>I need to encrypt some info using my Public key, and allow the other party to ONLY DECRYPT what I encrypted. I don't want them to be able to know how I encrypted my message. Is that possible using RSACryptoServiceProvider in .NET?</p>
| [
{
"answer_id": 301313,
"author": "Stefan Schultze",
"author_id": 6358,
"author_profile": "https://Stackoverflow.com/users/6358",
"pm_score": 4,
"selected": false,
"text": " public static string Sign(string data, string privateAndPublicKey)\n {\n byte[] dataBytes = Encoding.UTF8.GetBytes(data);\n RSACryptoServiceProvider provider = CreateProviderFromKey(privateAndPublicKey);\n byte[] signatureBytes = provider.SignData(dataBytes, \"SHA1\");\n return Convert.ToBase64String(signatureBytes);\n }\n\n public static bool Verify(string data, string signature, string publicKey)\n {\n byte[] dataBytes = Encoding.UTF8.GetBytes(data);\n byte[] signatureBytes = Convert.FromBase64String(signature);\n RSACryptoServiceProvider provider = CreateProviderFromKey(publicKey);\n return provider.VerifyData(dataBytes, \"SHA1\", signatureBytes);\n }\n\n private static RSACryptoServiceProvider CreateProviderFromKey(string key)\n {\n RSACryptoServiceProvider provider = new RSACryptoServiceProvider();\n provider.FromXmlString(key);\n return provider;\n }\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,312 | <p>Is there a way to execute a query(containing built in DB function) using PreparedStatement?</p>
<p>Example:
insert into foo (location) values (pointfromtext('12.56666 13.67777',4130))
Here pointfromtext is a built in function.</p>
| [
{
"answer_id": 301368,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 0,
"selected": false,
"text": " PreparedStatement bar = connection.prepareStatement(\"insert into foo (location) values (pointfromtext('? ?',4130)))\");\n bar.setDouble(1, 13.67777);\n bar.setDouble(2, 13.67777); \n bar.executeUpdate();\n connection.commit(); \n"
},
{
"answer_id": 301459,
"author": "alexmeia",
"author_id": 36587,
"author_profile": "https://Stackoverflow.com/users/36587",
"pm_score": 0,
"selected": false,
"text": "String sql = \"insert into map_address (location) values(pointfromtext('POINT(\" + \"12.56565665\" + \" \" + \"12.57565757\" + \")',4130))\"\n\nPreparedStatement preparedStatement = getConnection().prepareStatement(sql);\n"
},
{
"answer_id": 302364,
"author": "Alexandre",
"author_id": 9025,
"author_profile": "https://Stackoverflow.com/users/9025",
"pm_score": 3,
"selected": true,
"text": "PreparedStatement preparedStatement = getConnection().prepareStatement(\"insert into map_address (location) values(pointfromtext('POINT(' || ? || ' ' || ? || ')',4130))\");\npreparedStatement.setString(1, \"12.56565665\");\npreparedStatement.setString(2, \"12.57565757\");\npreparedStatement.executeUpdate();\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38857/"
] |
301,330 | <p>If I have a template function, for example like this:</p>
<pre><code>template<typename T>
void func(const std::vector<T>& v)
</code></pre>
<p>Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:</p>
<pre><code>template<typename T>
void func(const std::vector<T*>& v)
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 301338,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": false,
"text": "template<typename T>\nstruct is_pointer { static const bool value = false; };\n\ntemplate<typename T>\nstruct is_pointer<T*> { static const bool value = true; };\n\ntemplate<typename T>\nvoid func(const std::vector<T>& v) {\n std::cout << \"is it a pointer? \" << is_pointer<T>::value << std::endl;\n}\n"
},
{
"answer_id": 15974269,
"author": "Begui",
"author_id": 224215,
"author_profile": "https://Stackoverflow.com/users/224215",
"pm_score": 6,
"selected": false,
"text": "std::is_pointer<T>::value bool #include <iostream>\n#include <type_traits>\n\nclass A {};\n\nint main() \n{\n std::cout << std::boolalpha;\n std::cout << std::is_pointer<A>::value << '\\n';\n std::cout << std::is_pointer<A*>::value << '\\n';\n std::cout << std::is_pointer<float>::value << '\\n';\n std::cout << std::is_pointer<int>::value << '\\n';\n std::cout << std::is_pointer<int*>::value << '\\n';\n std::cout << std::is_pointer<int**>::value << '\\n';\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,339 | <p>I wonder if <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx" rel="nofollow noreferrer">MailMessage</a> class is protected from <a href="http://en.wikipedia.org/wiki/E-mail_injection" rel="nofollow noreferrer">e-mail injection</a>. For example, should I check values before passing them to its constructor:</p>
<pre><code>MailMessage message = new MailMessage(fromTextBox.Text, toTextBox.Text);
</code></pre>
| [
{
"answer_id": 1000932,
"author": "SLaks",
"author_id": 34397,
"author_profile": "https://Stackoverflow.com/users/34397",
"pm_score": 3,
"selected": true,
"text": "MailAddress MailBnfHelper MailMessage"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
301,345 | <p>I use the Autocomplete extender feature to get the list of suggestions from my database. There is no scroll bar for this control, so I have added a scroll bar in a panel (MS .net 2.0) which i attach to my autocomplete extender.Now the issue is with the srcoll bar.
like this </p>
<pre><code><asp:Panel ID="autocompleteDropDownPanel" runat="server" ScrollBars="Auto" Height="100px" HorizontalAlign="Left" />
</code></pre>
<p>and add it to autocompete extender like this </p>
<pre><code>:CompletionListElementID="autocompleteDropDownPanel"
</code></pre>
<p>When I call my page, I get the list of suggestions and the scroll bar appears. When I click on scroll bar or try to drag, everything just disappears.</p>
<p>Am i doing something wrong? Is there any other way to add a scroll bar to my autocomplete extender control</p>
<p>Any hints would be very helpful.</p>
| [
{
"answer_id": 314150,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 1,
"selected": false,
"text": "MinimumPrefixLength"
},
{
"answer_id": 565554,
"author": "BigOmar",
"author_id": 2442689,
"author_profile": "https://Stackoverflow.com/users/2442689",
"pm_score": 1,
"selected": false,
"text": "overflow:auto;\nheight:60px;\n"
},
{
"answer_id": 824882,
"author": "wheelibin",
"author_id": 52349,
"author_profile": "https://Stackoverflow.com/users/52349",
"pm_score": 1,
"selected": false,
"text": "AutoCompleteExtender AutoPostBack=True"
},
{
"answer_id": 32527208,
"author": "Roenne",
"author_id": 5325996,
"author_profile": "https://Stackoverflow.com/users/5325996",
"pm_score": 0,
"selected": false,
"text": "AutoPostBack=false OnClientItemSelected"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,354 | <p>I am probably doing something wrong -- but cant figure why.
I have a DateTime field in my DB keeping a UTC time </p>
<p>My server is in the US, and the browser is in Europe. </p>
<p>The PageLoad Code is as follow:</p>
<pre><code>DateTime t = DateTime.SpecifyKind((DateTime)rdr["startTime"], DateTimeKind.Utc);
label1.Text = t.ToLocalTime().ToString();
</code></pre>
<p>The time displayed I get is US localtime and not Europe. What should I do to display the browser's localtime?</p>
<p>Thanks!</p>
| [
{
"answer_id": 301380,
"author": "J c",
"author_id": 25837,
"author_profile": "https://Stackoverflow.com/users/25837",
"pm_score": 3,
"selected": false,
"text": "alert((new Date()).getTimezoneOffset());\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37955/"
] |
301,357 | <p>I know that I am supposed to use <code>delete []</code> after I use <code>new []</code>, so using <code>auto_ptr</code> with <code>new []</code> is not such a bright idea.</p>
<p>However, while debugging <code>delete []</code> (using Visual Studio 2005), I noticed that the call went into a function that looked like this:</p>
<pre><code>void operator delete[]( void * p )
{
RTCCALLBACK(_RTC_Free_hook, (p, 0))
operator delete(p);
}
</code></pre>
<p>Does this mean, the <code>[]</code> syntax is lost on Visual C++? If so, why? Is it to relieve the developer from the burden of remembering the right syntax?</p>
| [
{
"answer_id": 301370,
"author": "CAdaker",
"author_id": 30579,
"author_profile": "https://Stackoverflow.com/users/30579",
"pm_score": 2,
"selected": false,
"text": "delete delete[]"
},
{
"answer_id": 301612,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 6,
"selected": true,
"text": "class DeleteMe\n{\npublic:\n ~DeleteMe()\n {\n std::cout << \"Thanks mate, I'm gone!\\n\";\n }\n};\n\nint main()\n{\n DeleteMe *arr = new DeleteMe[5];\n delete arr;\n return 0;\n}\n main() int main()\n{\n DeleteMe *arr = new DeleteMe[5];\n delete[] arr;\n return 0;\n}\n operator new operator delete"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1398/"
] |
301,365 | <p>My team is responsible for the development of an API for a large system that we also write. We need to provide example code so that other developers using our API can learn how to use it. We have been documenting the code using the xml document comments.
eg.</p>
<pre><code>/// <summary>Summary here</summary>
/// <example>Here is an example <code>example code here</code> </example>
public void SomeFunction()
</code></pre>
<p>We then use Sandcastle and build the help files we need (chm and an online website).</p>
<p>It is quite embarrassing when the example code doesnt work, and this is usually because some functionality has changed or a simple error.</p>
<p>Has anyone ever done something like this, but also configured unit tests to run on the example code so that they are known to work during the build?</p>
| [
{
"answer_id": 301415,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 0,
"selected": false,
"text": "#include \"samples/sampleA.h\"\n\nvoid main()\n{\n SomeFunction();\n}\n"
},
{
"answer_id": 301423,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "/// <summary>Summary here</summary>\n/// <example>Here is an example\n/// <code>!!sourcefile:SomeClassTest.cs#SomeFunction!!</code></example>\npublic void SomeFunction()\n"
},
{
"answer_id": 604525,
"author": "Wim Coenen",
"author_id": 52626,
"author_profile": "https://Stackoverflow.com/users/52626",
"pm_score": 4,
"selected": true,
"text": " /// <summary>\n /// Gizmo which can act as client or server.\n /// </summary>\n /// <example>\n /// The following example shows how to use the gizmo as a client:\n /// <code lang=\"cs\"\n /// source=\"..\\gizmo.unittests\\TestGizmo.cs\"\n /// region=\"GizmoClientSample\"/>\n /// </example>\n public class Gizmo\n [Test]\npublic GizmoCanActAsClient()\n{\n #region GizmoClientSample\n Gizmo gizmo = new Gizmo();\n gizmo.ActAsClient();\n #endregion\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33125/"
] |
301,366 | <p>I am using Oracle form 10
I want to know how can I access the parameters of URL in oracle form </p>
<p>Ex:
whenever I run the form it opens in a browser and the URL for the same is</p>
<p><a href="http://112.10.0.10:7778/forms/frmservlet?config=pkamble" rel="nofollow noreferrer">http://112.10.0.10:7778/forms/frmservlet?config=pkamble</a></p>
<p>I just want to know how can I access the value of 'config' parameter inside oracle form code.</p>
<p>when we run oracle form using 10g then </p>
<p>I will appreciate the help !! </p>
| [
{
"answer_id": 340000,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "http://112.10.0.10:7778/forms/frmservlet?config=pkamble&otherparams=name=value\n if :PARAMETER.name = 'value' then\n message('ok');\nend if;\n http://112.10.0.10:7778/forms/frmservlet?otherparams=name1=value1+name2=value2+name3=value3\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,369 | <p>How do I declare a session variable in PL/SQL - one that will persist for the duration of the session only, without me having to store it in the database itself?</p>
| [
{
"answer_id": 301418,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 4,
"selected": false,
"text": "CREATE OR REPLACE PACKAGE my_package\nAS\n FUNCTION get_a RETURN NUMBER;\nEND my_package;\n/\n\nCREATE OR REPLACE PACKAGE BODY my_package\nAS\n a NUMBER(20);\n\n FUNCTION get_a\n RETURN NUMBER\n IS\n BEGIN\n RETURN a;\n END get_a;\nEND my_package;\n/\n ORA-04068 SELECT my_package.get_a FROM DUAL;\n"
},
{
"answer_id": 302818,
"author": "user34850",
"author_id": 34850,
"author_profile": "https://Stackoverflow.com/users/34850",
"pm_score": 4,
"selected": false,
"text": "CREATE CONTEXT SYS_CONTEXT ('userenv', 'current_schema')|| '_ctx' USING PKG_COMMON\n CREATE OR REPLACE PACKAGE PKG_COMMON\nIS\n common_ctx_name CONSTANT VARCHAR2 (60)\n := SYS_CONTEXT ('userenv', 'current_schema')\n || '_ctx';\n\n FUNCTION fcn_get_context_name RETURN VARCHAR2;\n PROCEDURE prc_set_context_value (var_name VARCHAR2, var_value NUMBER);\nEND;\n\nCREATE OR REPLACE PACKAGE BODY PKG_COMMON\nIS\n FUNCTION fcn_get_context_name\n RETURN VARCHAR2\n IS\n BEGIN\n RETURN common_ctx_name;\n END;\n\n PROCEDURE prc_set_context_value (var_name VARCHAR2, var_value NUMBER)\n IS\n BEGIN\n DBMS_SESSION.set_context (common_ctx_name, var_name, var_value);\n END;\nEND;\n begin\n PKG_COMMON.prc_set_context_value('MyVariable', 9000)\nend;\n CREATE VIEW V_TEST AS\n SELECT ID, LOGIN, NAME \n FROM USERS \n WHERE ROLE_ID = SYS_CONTEXT(PKG_COMMON.FCN_GET_CONTEXT_NAME, 'MyVariable')\n"
},
{
"answer_id": 55333963,
"author": "Andreas Covidiot",
"author_id": 1915920,
"author_profile": "https://Stackoverflow.com/users/1915920",
"pm_score": 0,
"selected": false,
"text": "ctx foo varchar2 bar number select ctx.foo from dual -- => null (init)\nselect ctx.foo('a') from dual -- => 'a'\nselect ctx.foo('b') from dual ; select ctx.foo from dual -- => 'b', 'b'\n -- (optimizer should cause the subquerys unselected columns not to be executed:)\nselect 'ups' from (select ctx.foo('a') from dual) ; select ctx.foo from dual -- => null\n\nselect ctx.bar(1.5) from dual ; select ctx.bar from dual -- => 1.5, 1.5\n-- ...\n create or replace package ctx as\n\n -- select ctx.foo from dual -- => null (init)\n -- select ctx.foo('a') from dual -- => 'a'\n -- select ctx.foo('b') from dual ; select ctx.foo from dual -- => 'b', 'b'\n -- (optimizer should cause the subquerys unselected columns not to be executed:)\n -- select 'ups' from (select ctx.foo('a') from dual) ; select ctx.foo from dual\n -- => null\n -- parallel_enable for queries since it should not change inside of them\n function foo( set varchar2 := null ) return varchar2 parallel_enable;\n\n -- (samples like in foo above as executable test comments like in foo above skipped for \n -- brevity)\n function bar( set number := null ) return number parallel_enable;\n\nend;\n create or replace package body ctx as\n\n foo_ varchar2(30); -- e.g. 'blabla'\n bar_ number;\n\n\n -- internal helper function for varchars\n function set_if_not_null( ref in out varchar2, val varchar2 ) return varchar2 as \n begin\n if val is not null then ref := val; end if;\n return ref ;\n end;\n\n\n -- internal helper function for numbers\n function set_if_not_null( ref in out number, val number ) return number as begin\n if val is not null then ref := val; end if;\n return ref ;\n end;\n\n\n -- (same test comments like in foo above skipped for brevity) \n function foo( set varchar2 := null ) return varchar2 parallel_enable as begin\n return set_if_not_null( foo_, set ) ;\n end;\n\n\n -- (same test comments like in foo above skipped for brevity) \n function bar( set number := null ) return number parallel_enable as begin\n return set_if_not_null( bar_, set ) ;\n end;\n\nend;\n foo parallel_enable foo_reset()"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38871/"
] |
301,371 | <p>In most programming languages, dictionaries are preferred over hashtables.
What are the reasons behind that?</p>
| [
{
"answer_id": 301379,
"author": "gius",
"author_id": 19712,
"author_profile": "https://Stackoverflow.com/users/19712",
"pm_score": 8,
"selected": false,
"text": "Dictionary Dictionary<TKey, TValue> Object Hashtable var customers = new Dictionary<string, Customer>();\n...\nCustomer customer = customers[\"Ali G\"];\n var customers = new Hashtable();\n...\nCustomer customer = customers[\"Ali G\"] as Customer;\n Dictionary"
},
{
"answer_id": 301381,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": false,
"text": "Dictionary<,> HashTable"
},
{
"answer_id": 301383,
"author": "flesh",
"author_id": 27805,
"author_profile": "https://Stackoverflow.com/users/27805",
"pm_score": 4,
"selected": false,
"text": "Hashtable Hashtable Dictionary Hashtable Dictionary"
},
{
"answer_id": 301384,
"author": "Michael Madsen",
"author_id": 27528,
"author_profile": "https://Stackoverflow.com/users/27528",
"pm_score": 12,
"selected": true,
"text": "Dictionary<TKey, TValue> Hashtable Dictionary<TKey, TValue> Hashtable Dictionary<TKey, TValue> Dictionary<TKey, TValue> Hashtable"
},
{
"answer_id": 301674,
"author": "user38902",
"author_id": 38902,
"author_profile": "https://Stackoverflow.com/users/38902",
"pm_score": 7,
"selected": false,
"text": "Hashtable Dictionary Hashtable"
},
{
"answer_id": 301822,
"author": "rix0rrr",
"author_id": 2474,
"author_profile": "https://Stackoverflow.com/users/2474",
"pm_score": 5,
"selected": false,
"text": "Dictionary"
},
{
"answer_id": 2409689,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "[Serializable, ComVisible(true)]\npublic abstract class DictionaryBase : IDictionary, ICollection, IEnumerable\n{\n // Fields\n private Hashtable hashtable;\n\n // Methods\n protected DictionaryBase();\n public void Clear();\n.\n.\n.\n}\nTake note of these lines\n// Fields\nprivate Hashtable hashtable;\n"
},
{
"answer_id": 5742863,
"author": "Marcel Toth",
"author_id": 702199,
"author_profile": "https://Stackoverflow.com/users/702199",
"pm_score": 9,
"selected": false,
"text": "Dictionary Hashtable Synchronized() KeyValuePair DictionaryEntry GetHashCode() ConcurrentDictionary HybridDictionary OrderedDictionary SortedDictionary StringDictionary"
},
{
"answer_id": 10698133,
"author": "Kishore Kumar",
"author_id": 823369,
"author_profile": "https://Stackoverflow.com/users/823369",
"pm_score": 3,
"selected": false,
"text": "Dictionary<> Dictionary<int> Dictionary<string> Dictionary<> HashTable"
},
{
"answer_id": 12457994,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 5,
"selected": false,
"text": "Collections Generics IEnumerable ArrayList(Index-Value)) HashTable(Key-Value) ArrayList HashTable List Dictionary Arraylist HashTable HashTable Dictionary Dictionary Hastable HashTable dictionary class HashTableProgram\n{\n static void Main(string[] args)\n {\n Hashtable ht = new Hashtable();\n ht.Add(1, \"One\");\n ht.Add(2, \"Two\");\n ht.Add(3, \"Three\");\n foreach (DictionaryEntry de in ht)\n {\n int Key = (int)de.Key; //Casting\n string value = de.Value.ToString(); //Casting\n Console.WriteLine(Key + \" \" + value);\n }\n\n }\n}\n class DictionaryProgram\n{\n static void Main(string[] args)\n {\n Dictionary<int, string> dt = new Dictionary<int, string>();\n dt.Add(1, \"One\");\n dt.Add(2, \"Two\");\n dt.Add(3, \"Three\");\n foreach (KeyValuePair<int, String> kv in dt)\n {\n Console.WriteLine(kv.Key + \" \" + kv.Value);\n }\n }\n}\n"
},
{
"answer_id": 14335724,
"author": "Oliver",
"author_id": 1838048,
"author_profile": "https://Stackoverflow.com/users/1838048",
"pm_score": 4,
"selected": false,
"text": "HashSet<T> Dictionary<TKey, TValue> Dictionary<MyType, object> null HashSet<T>"
},
{
"answer_id": 23905753,
"author": "Altaf Patel",
"author_id": 704211,
"author_profile": "https://Stackoverflow.com/users/704211",
"pm_score": 4,
"selected": false,
"text": "Dictionary<string, string> <NameOfDictionaryVar> = \n new Dictionary<string, string>(); Keys Values"
},
{
"answer_id": 33669077,
"author": "NullReference",
"author_id": 2170850,
"author_profile": "https://Stackoverflow.com/users/2170850",
"pm_score": 3,
"selected": false,
"text": "Synchronized List<T>, Dictionary<TKey, TValue>"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34588/"
] |
301,372 | <p>Suppose I have a .NET assembly, A, which uses reflection to load assemblies B and C (also .NET). These two assemblies both implement a number of large interfaces (the same for both). When a method is called in A it tries to make B do the work. However, B is unreliable and might throw exceptions. Now A has two modes, one where it propagates the exceptions out to the caller of A and one where it calls matching methods on the more stable (but less performant) C.</p>
<p>Are there better ways (less code) to implement this scenario than wrapping all the methods B exposes in a huge implementation of all B's interfaces, only now surrounding every call with code as shown below? The assemblies B and C don't know anything about the error handling approach chosen, so they can't implemet the logic.</p>
<pre><code>public class BErrorWrapper : I1, I2, I3{
...
public int DoSomeWork(int num){
if (FailWithExceptions)
{
try
{
return B.DoSomeWork(num);
}
catch(MyLibException e)
{
return C.DoSomeWOrk(num);
}
}
else
{
return B.DoSomeWork(num);
}
}
...
}
</code></pre>
| [
{
"answer_id": 301389,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "public class BErrorWrapper : I1, I2, I3{\n ...\n public int DoSomeWork(int num){\n try\n {\n return B.DoSomeWork(num);\n }\n catch(MyLibException e)\n {\n if (FailWithExceptions) throw;\n return C.DoSomeWOrk(num);\n }\n }\n ...\n}\n"
},
{
"answer_id": 301399,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "FailWithExceptions static void TryWithFallback<T>(Action<T> primary, Action<T> fallback, T arg)\n {\n try\n {\n primary(arg);\n }\n catch // add your other regular code here...\n {\n fallback(arg);\n }\n }\n TryWithFallback(b.DoSomeWork, c.DoSomeWork, num);\n static TResult TryWithFallback<T, TResult>(Func<T, TResult> primary, Func<T, TResult> fallback, T arg)\n {\n try\n {\n return primary(arg);\n }\n catch\n {\n return fallback(arg);\n }\n }\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
301,374 | <p>In a PHP application I am writing, I would like to have users enter in text a mix of HTML and text with pointed-brackets, but when I display this text, I want to let the HTML tags be rendered by the non-HTML tags be shown literary, e.g. a user should be able to enter:</p>
<pre><code><b> 5 > 3 = true</b>
</code></pre>
<p>when displayed, the user should see:</p>
<p><strong>5 > 3 = true</strong></p>
<p>What is the best way to parse this, i.e. find all the non-HTML brackets, convert them to &gt; and &lt;?</p>
| [
{
"answer_id": 301387,
"author": "philistyne",
"author_id": 16597,
"author_profile": "https://Stackoverflow.com/users/16597",
"pm_score": 3,
"selected": true,
"text": "[b]This is bold[/b]\n[i]this is italic with a > 'greater than' sign there[/i]\n"
},
{
"answer_id": 301457,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 0,
"selected": false,
"text": "<b> </b>"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
301,376 | <p>I have the following markup for buttons (can be changed, but I really don't want to):</p>
<pre><code><a href="#" class="button">
Button text
<img src="someimage.png" />
</a>
</code></pre>
<p>This is styled using CSS to become a rather neat button with an icon on it. I am using jQuery to round the leftmost side of the buttons:</p>
<pre><code>$('a.button').corner('tl bl 10px');
</code></pre>
<p>This works like a charm. Now I want to also support buttons that do not have images, and therefore should be rounded on both sides. Simply rounding all edges for all buttons won't work, as the rounded corners plugin paints on top of the icons.</p>
<p>So, I am specifically looking for a selector to select <code><a class="button"></code> to does have <code><img></code>-child elements, and another to select <code><a class="button"></code>-elements that do not have <code><img></code>-child elements. Is this possible?</p>
<p>I know I could change the class of the button depending on whether or not it has an image inside it, but that just feels wrong.</p>
| [
{
"answer_id": 301397,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 5,
"selected": true,
"text": "$('a.button:has(img)')\n\n$('a.button:not(:has(img))')\n"
},
{
"answer_id": 301421,
"author": "Russ Cam",
"author_id": 1831,
"author_profile": "https://Stackoverflow.com/users/1831",
"pm_score": 2,
"selected": false,
"text": "$('a.button:has(img)').corner('tl bl 10px');\n $('a.button:not(:has(img))').corner() \n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606/"
] |
301,386 | <p>Should I use textbox.text.Trim() function every time when I insert any data from web page to database.</p>
<p>I just have a habit of using the trim function? Does it effect the performance any way? Should I use everytime or just when needed?</p>
| [
{
"answer_id": 301404,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 0,
"selected": false,
"text": "mysql_real_escape_string();\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,392 | <p>How do you traverse a folder structure using C# without falling into the trap of <a href="http://en.wikipedia.org/wiki/NTFS_junction_point" rel="nofollow noreferrer">junction points</a>? </p>
| [
{
"answer_id": 301398,
"author": "Pieter Breed",
"author_id": 24172,
"author_profile": "https://Stackoverflow.com/users/24172",
"pm_score": 4,
"selected": true,
"text": "given folder /a/b\nlet /a/b/c point to /a\nthen\n/a/b/c/b/c/b becomes valid folder locations.\n private void FindFilesRec(\n string newRootFolder,\n Predicate<FileInfo> fileMustBeProcessedP,\n Action<FileInfo> processFile)\n{\n var rootDir = new DirectoryInfo(newRootFolder);\n foreach (var file in from f in rootDir.GetFiles()\n where fileMustBeProcessedP(f)\n select f)\n {\n processFile(file);\n }\n\n foreach (var dir in from d in rootDir.GetDirectories()\n where (d.Attributes & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint\n select d)\n {\n FindFilesRec(\n dir.FullName,\n fileMustBeProcessedP,\n processFile);\n }\n}\n"
},
{
"answer_id": 301409,
"author": "Nakul Chaudhary",
"author_id": 34588,
"author_profile": "https://Stackoverflow.com/users/34588",
"pm_score": -1,
"selected": false,
"text": "private void processing(string directory)\n {\n cmbFilesTypesSelectedIndex = cmbFilesTypes.SelectedIndex;\n CheckForProjectFile(directory);\n DirectoryInfo dInfo = new DirectoryInfo(directory);\n DirectoryInfo[] dirs = dInfo.GetDirectories() ;\n foreach (DirectoryInfo subDir in dirs)\n {\n CheckForProjectFile(subDir.FullName);\n processing(subDir.FullName);\n }\n }\n\n private void CheckForProjectFile(string directory)\n {\n Boolean flag = false; \n DirectoryInfo dirInfo = new DirectoryInfo(directory);\n FileInfo[] files = dirInfo.GetFiles();\n //You can also traverse in files also\n foreach (FileInfo subfile in files)\n {\n //Do you want\n\n }\n }\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24172/"
] |
301,400 | <p>I am working with Rails fixtures for testing my rails application. It is all good except one of my database columns is supposed to hold YAML content. But, I am sure how to put the YAML markup I want to load into my database inside the YAML file. Here is an example:</p>
<pre><code>mvnforum:
name: mvnforum
abstraction_type: SVN
url: src: test username: admin #is this possible?
sourcepath: mvnforum/src/
webroot:
codesecure_project: mvnforum
</code></pre>
<p>If it is impossible to have YAML inside a YAML file what would be the best why to load this into a database for testing?</p>
| [
{
"answer_id": 301476,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 4,
"selected": true,
"text": "url: \"src: test username: admin\"\n mvnforum:\n name: mvnforum\n abstraction_type: SVN\n url: \"\nsrc: test\\n\nusername: admin\\n\n\"\n sourcepath: mvnforum/src/\n webroot:\n codesecure_project: mvnforum\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
301,425 | <p>I have a method to return a group of objects as a generic list which I then bind to a Repeater. I want to implement paging on the repeater using the PagedDataSource class but I'm not sure that this is possible as it doesn't seem to work.</p>
<p>Will I have to change the return type of my method or is it possible to bind the PagedDataSource to the generic list?</p>
| [
{
"answer_id": 301440,
"author": "Kieron",
"author_id": 5791,
"author_profile": "https://Stackoverflow.com/users/5791",
"pm_score": 3,
"selected": true,
"text": "void PopulateNewsItems (int? pageNo)\n{\n var model = ModelFactory.GetNewsModel ();\n var searchResults = model.GetNewsItems ();\n\n var dataSource = new PagedDataSource ();\n\n // CHANGED THE ARRAY OF NEWSITEMS INTO A GENERIC LIST OF NEWSITEMS.\n dataSource.DataSource = new List<NewsItem> (searchResults);\n dataSource.AllowPaging = true;\n\n var pageSizeFromConfig = ConfigurationManager.AppSettings[\"NewsItemsPageCount\"];\n var pageSize = 10;\n\n int.TryParse (pageSizeFromConfig, out pageSize);\n\n dataSource.PageSize = pageSize;\n dataSource.CurrentPageIndex = pageNo ?? 0;\n\n PagingPanel.Controls.Clear ();\n for (var i = 0; i < dataSource.PageCount; i++)\n {\n var linkButton = new LinkButton ();\n linkButton.CommandArgument = i.ToString ();\n linkButton.CommandName = \"PageNo\";\n linkButton.Command += NavigationCommand;\n linkButton.ID = string.Format (\"PageNo{0}LinkButton\", i);\n if (pageNo == i || (pageNo == null && i == 0))\n {\n linkButton.Enabled = false;\n linkButton.CssClass = \"SelectedPageLink\";\n }\n\n linkButton.Text = (i + 1).ToString ();\n\n PagingPanel.Controls.Add (linkButton);\n if (i < (dataSource.PageCount - 1))\n PagingPanel.Controls.Add (new LiteralControl (\"|\"));\n }\n\n NewsRepeater.DataSource = dataSource;\n NewsRepeater.DataBind ();\n}\n\nvoid NavigationCommand (object sender, CommandEventArgs e)\n{\n PopulateNewsItems (int.Parse ((string)e.CommandArgument));\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2913/"
] |
301,429 | <p>I have a table in Access 2003 VBA with 164 columns but the data I get has 181 column and it is possible that it will get bigger in the future.
I need to know how to resize my table an to add extra colums during the runtime
I know how to check how many colums I need so I just need to know how to resize my own table.</p>
<p>thanks</p>
| [
{
"answer_id": 301913,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 2,
"selected": false,
"text": " ID\n FirstName\n LastName\n ...\n Amount\n\n 1 Joe Smith ... $123\n 2 Bob Roberts ... $214\n 3 Jim Black ... $500\n RecordID\n FieldNumber\n FieldName\n FieldValue\n\n 1 1 FirstName Joe\n 1 2 LastName Smith\n ...\n 1 n Amount $123\n 2 1 FirstName Bob\n 2 2 Lastname Roberts\n ...\n 2 n Amount $214\n 3 1 FirstName Jim\n 3 2 LastName Black\n ...\n 3 n Amount $500\n"
},
{
"answer_id": 301941,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 2,
"selected": false,
"text": "Key, FieldName, FieldValue"
},
{
"answer_id": 302416,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": "strSQL=\"ALTER TABLE tblTable ADD COLUMN NewCol Text (25)\"\nCurrentDB.Execute strSQL,dbFailOnError\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,430 | <p>I'm trying to use some extension methods that I use to apply consistent formatting to DateTime and Int32 - which works absolutely fine in code behind, but I'm having issues with databinding.</p>
<p>I get:</p>
<pre><code>'System.DateTime' does not contain a definition for 'ToCustomShortDate'
</code></pre>
<p>for</p>
<pre><code><%# ((ProductionDetails)Container.DataItem).StartDate.ToCustomShortDate() %>
</code></pre>
<p>(inside a templatefield of a gridview contained on a usercontrol)</p>
<p>Even when I'm including the namespace that the extension method is defined in at the top of the usercontrol:</p>
<pre><code><%@ import namespace="MyAssembly.Formatting" %>
</code></pre>
<p>Has anyone else come across this and is there any way to resolve it?</p>
<p><b>EDIT:</b> My mistake, above should be:</p>
<pre><code><%@ import namespace="MyNamespace.Formatting" %>
</code></pre>
<p>ie. I'm not incorrectly referencing the namespace (works vertabim in the code behind)</p>
| [
{
"answer_id": 301477,
"author": "Rohan West",
"author_id": 38686,
"author_profile": "https://Stackoverflow.com/users/38686",
"pm_score": 0,
"selected": false,
"text": "namespace Formatting\n{\n\n public static class DateTimeExtender\n {\n public static string ToCustomShortDate(this DateTime date)\n {\n return date.ToString(\"dd MMM yyyy\");\n }\n }\n\n public class ProductionDetails\n {\n public DateTime StartDate { get; set; } \n }\n}\n <%@ Import Namespace=\"Formatting\" %>\n"
},
{
"answer_id": 301561,
"author": "Rohan West",
"author_id": 38686,
"author_profile": "https://Stackoverflow.com/users/38686",
"pm_score": 1,
"selected": false,
"text": "namespace MyNamespace.Formatting\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
] |
301,435 | <p>I have a form I am submitting via AJAX (using prototype and the built-in rails 'form_remote_tag' helper).<br>
What I would like is to update one div (a status area) if there are form validation errors but a different div (the div where the form lives) if the submit goes through sucessfully.</p>
<p>My code looks something like this:</p>
<pre><code><div id="recipe-status"><!-- I want form validation errors to go here --></div>
<div id="recipe">
<%= form_remote_tag(:update => "recipe-status",
:before => "Element.show('wait-indicator')",
:success => "Element.hide('wait-indicator')",
:complete => visual_effect(:appear, "recipe-status"),
:url => { :action => 'import', :id => @recipe.id },
:failure => "alert('Unable to import recipes at present')") %>
<-- Form goes here, I want this to be replaced if the submit succeeds -->
</div>
</code></pre>
<p>The only way I can think of doing this is to return a HTTP error status if there is a validation error but that seems like a bit of a hack.
Is there a cleaner way of doing it at all?</p>
| [
{
"answer_id": 301477,
"author": "Rohan West",
"author_id": 38686,
"author_profile": "https://Stackoverflow.com/users/38686",
"pm_score": 0,
"selected": false,
"text": "namespace Formatting\n{\n\n public static class DateTimeExtender\n {\n public static string ToCustomShortDate(this DateTime date)\n {\n return date.ToString(\"dd MMM yyyy\");\n }\n }\n\n public class ProductionDetails\n {\n public DateTime StartDate { get; set; } \n }\n}\n <%@ Import Namespace=\"Formatting\" %>\n"
},
{
"answer_id": 301561,
"author": "Rohan West",
"author_id": 38686,
"author_profile": "https://Stackoverflow.com/users/38686",
"pm_score": 1,
"selected": false,
"text": "namespace MyNamespace.Formatting\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151/"
] |
301,438 | <p>...or am I stuck rolling my own "XML chopping" functions. I'd like to create a small tasktray app so I can quickly re-point a Virual Directory to one of several of folders on my harddisk.</p>
<p><strong>Bit of background:</strong> </p>
<p>I have 3 different svn branches of our code base on my dev machine.</p>
<pre><code>Current Production Branch ( C:\Projects\....\branches\Prod\ )
Next Release Canidate Branch ( C:\Projects\....\branches\RCX\ )
Trunk ( C:\Projects\....\trunk\ )
</code></pre>
<p>Our app integrates with a 3rd party CMS which I've installed at</p>
<pre><code>http://localhost/cms/
</code></pre>
<p>In order to work our app has to live at the same root directory. so:</p>
<pre><code>http://localhost/app/
</code></pre>
<p>Depending on the branch I'm working on, I'm re-pointing the <code>/app/</code> directory to one of the 3 paths listed above by going into IIS Manager. Just thought it'd be handy to have a quick-app to do it for me.</p>
| [
{
"answer_id": 301724,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.DirectoryServices;\n\nnamespace Swapper\n{\n class Program\n {\n static void Main(string[] args)\n {\n using (DirectoryEntry appRoot = \n new DirectoryEntry(\"IIS://Localhost/W3SVC/1/root/app\"))\n {\n switch (args[0].ToLower())\n {\n case \"prod\":\n appRoot.Properties[\"Path\"].Value = @\"e:\\app\\prod\";\n appRoot.CommitChanges();\n break;\n\n case \"rcx\":\n appRoot.Properties[\"Path\"].Value = @\"e:\\app\\rcx\";\n appRoot.CommitChanges();\n break;\n\n case \"trunk\":\n appRoot.Properties[\"Path\"].Value = @\"e:\\app\\trunk\";\n appRoot.CommitChanges();\n break;\n\n default:\n Console.WriteLine(\"Don't know\");\n break;\n }\n }\n }\n }\n}\n C:\\>swapper prod\nC:\\>swapper rcx\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30155/"
] |
301,442 | <p>I want to create a compiled JavaScript file for my website. For development I would prefer to keep the JavaScript in separate files and just as part of my automated scripts concatenate the files into one and run the compressor over it.</p>
<p>My problem is that if I use the old DOS copy command it also puts in the EOF markers which the compressor complains about:</p>
<p>copy /A *.js compiled.js /Y</p>
<p>What are other people doing?</p>
| [
{
"answer_id": 301488,
"author": "eugensk",
"author_id": 17495,
"author_profile": "https://Stackoverflow.com/users/17495",
"pm_score": 4,
"selected": false,
"text": "copy /B *.js compiled.js /Y\n copy /A *.js compiled.js /B /Y\n copy /A *.js /B compiled.js /Y \n"
},
{
"answer_id": 301646,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "type *.js > compiled.js\n"
},
{
"answer_id": 301784,
"author": "David Brockman",
"author_id": 38912,
"author_profile": "https://Stackoverflow.com/users/38912",
"pm_score": 6,
"selected": true,
"text": "<target name=\"concatenate\" description=\"Concatenate all js files\">\n <concat destfile=\"build/application.js\">\n <fileset dir=\"src/js\" includes=\"*.js\" />\n </concat>\n</target>\n\n<target name=\"compress\" depends=\"concatenate\" description=\"Compress application.js to application-min.js\">\n <apply executable=\"java\" parallel=\"false\">\n <filelist dir=\"build\" files=\"application.js\" />\n <arg line=\"-jar\" />\n <arg path=\"path/to/yuicompressor-2.4.2.jar\" />\n <srcfile />\n <arg line=\"-o\" />\n <mapper type=\"glob\" from=\"*.js\" to=\"build/*-min.js\" />\n <targetfile />\n </apply>\n</target>\n"
},
{
"answer_id": 1111583,
"author": "Punit Vora",
"author_id": 125422,
"author_profile": "https://Stackoverflow.com/users/125422",
"pm_score": 3,
"selected": false,
"text": " <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\">\n <CompositeScript>\n <Scripts>\n <asp:ScriptReference Path=\"~/Scripts/Script1.js\" />\n <asp:ScriptReference Path=\"~/Scripts/Script2.js\" />\n <asp:ScriptReference Path=\"~/Scripts/Script3.js\" />\n </Scripts>\n </CompositeScript>\n </asp:ScriptManager>\n"
},
{
"answer_id": 7365400,
"author": "Alex Objelean",
"author_id": 859314,
"author_profile": "https://Stackoverflow.com/users/859314",
"pm_score": 0,
"selected": false,
"text": "<groups xmlns=\"http://www.isdc.ro/wro\">\n <group name=\"all\">\n <css>/asset/*.css</css>\n <js>/asset/*.js</js>\n </group>\n</groups> \n"
},
{
"answer_id": 24729883,
"author": "Fergal",
"author_id": 102641,
"author_profile": "https://Stackoverflow.com/users/102641",
"pm_score": 3,
"selected": false,
"text": "sudo npm -g install uglify-js\n cat myAppDir/*.js | uglifyjs > build/application.js\n"
},
{
"answer_id": 59945497,
"author": "Mig82",
"author_id": 4124574,
"author_profile": "https://Stackoverflow.com/users/4124574",
"pm_score": 1,
"selected": false,
"text": "require foobar.js main.js require(\"./doFoo\");\nrequire(\"./doBar\");\n browserify main.js -o foobar.js\n watchify main.js -o foobar.js\n doQux.js require(\"./doQux\");\nconst doBar = ()=>{\n //Do some bar stuff.\n}\nexports.doBar = doBar;\n doQux.js foobar.js"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24459/"
] |
301,466 | <p>This has always bugged me. When I ssh or telnet to a Unix server (whatever flavour) it always manages to guess correctly the terminal type I am logging in from and so the keyboard always acts 'normally' ... i.e. the backspace key works. </p>
<p>But then when I have successfully logged in, it often guesses incorrectly the terminal type I am using and makes incorrect key mappings - especially for the backspace key, meaning I have to issue a:</p>
<pre><code>stty erase ...
</code></pre>
<p>type command to fix it. </p>
<p>Any Unix gurus out there know why this happens?</p>
| [
{
"answer_id": 301535,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "stty erase '^H' stty erase 'X'"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21544/"
] |
301,468 | <p>I am currently migrating one of my clients sites to a windows server 2008 and SQL 2008 setup, but I am having massive problems with connecting to the database from the site.</p>
<p>I have restored the database from a SQL 2k backup into the SQL 2008 server, I have setup the user correctly and can login as that user in management studio fine. I have copied over the site .asp files which load fine when there is no database access. But when i try to access the database it fails with "Login Failed for user......". </p>
<p>I have reset the passwords, created new users, changed the connectionstring from OLEDB to SQL Native Client and back again but keep getting errors. I have even setup a dummy database and user and still have the same problem.</p>
<p>Does anyone know of a reason why this could be happening? Is there a setting in SQL or windows that I am missing?</p>
<p>I have been at this for hours and would really appreciate any ideas.</p>
<p>UPDATE : If I put the wrong login details in the connection string I get the error on conn.open but if I put in the correct login details I get the error on cmd.activeconnection = conn. Not sure if that helps.</p>
| [
{
"answer_id": 2391722,
"author": "shrikant",
"author_id": 287633,
"author_profile": "https://Stackoverflow.com/users/287633",
"pm_score": 0,
"selected": false,
"text": "myConnection.ConnectionString = \"Driver={SQL Server};Server=xxx.xxx.xxx.xxx,1533;Database=mydb;Uid=user123;Pwd=user123d;\"\n"
},
{
"answer_id": 14548857,
"author": "Rich",
"author_id": 147971,
"author_profile": "https://Stackoverflow.com/users/147971",
"pm_score": 0,
"selected": false,
"text": "DRIVER={SQL Server};SERVER=80.82.xxx.xxx;DATABASE=mydatabasename;UID=myusername;PWD=mypassword\n Provider=SQLNCLI10.1;SERVER=80.82.xxx.xxx;DATABASE=mydatabasename;UID=myusername;PWD=mypassword\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,471 | <p>I'm trying to load javascript code with a user web control into a page via a the Page.LoadControl method during an asyncron post back of an update panel.</p>
<p>I've tried the specially for that scenario designed methods of the scriptmanager, but the javascript just doens't get returned to the user.</p>
<p>To explain my scenario a bit better:</p>
<p>Master Page has the script manager and one page loads the user control via Page.LoadControl-method during an async post back. The custom control injects in the pre-render event handler the javascript. Is that a matter of timing to inject the js or is it just not possible to do so?</p>
| [
{
"answer_id": 301972,
"author": "rams",
"author_id": 3635,
"author_profile": "https://Stackoverflow.com/users/3635",
"pm_score": 2,
"selected": false,
"text": "Page.ClientScript.RegisterStartUpScript(GetType(Page), \"key\", <your script here>, addSctiptTags:=true)\n"
},
{
"answer_id": 303209,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 2,
"selected": false,
"text": "public partial class WebUserControl : System.Web.UI.UserControl\n{ \n protected void Page_PreRender(object sender, EventArgs e)\n {\n ScriptManager.RegisterStartupScript(this, GetType(), ClientID, \"alert(1)\", true);\n }\n}\n"
},
{
"answer_id": 332812,
"author": "rams",
"author_id": 3635,
"author_profile": "https://Stackoverflow.com/users/3635",
"pm_score": 3,
"selected": true,
"text": "string scr;\nscr = \"<script src='/scripts/myscript.js'></script>\"\nPage.ClientScript.RegisterStartupScript(GetType(Page), \"key\", scr, false)\n"
},
{
"answer_id": 1954915,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 2,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n ScriptManager.RegisterClientScriptInclude(\n this, GetType(), \"formatterScript\", ResolveUrl(\"~/js/formatter.js\"));\n ScriptManager.RegisterStartupScript(\n this, GetType(), \"formatTableFunction\", \"formatTable()\", true);\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36475/"
] |
301,473 | <p>I have several input and option elements on my page, each (well almost) have an event attached to update some text on the page once they change. I use jQuery which is really really cool :) </p>
<p>I also use Microsofts <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> framework, utilizing the UpdatePanel. The reason why I do that is that certain elements are created on the page based on some server-side logic. I don't really want to explain why I use the UpdatePanel - even if it could (it can with quite some effort) be rewritten to use only <a href="http://en.wikipedia.org/wiki/JQuery" rel="noreferrer">jQuery</a> I still want that UpdatePanel.</p>
<p>You probably guessed it - once I have a postback on the UpdatePanel the jQuery events stops working. I actually was expecting this, since the "postback" is not really a new postback so my code in document.ready that binds the events won't be fired again. I also confirmed my suspicion by reading up on it in the jQuery help libraries.</p>
<p>Anyway I'm left with the problem of rebinding my controls after the UpdatePanel is done updating the <a href="http://en.wikipedia.org/wiki/Document_Object_Model" rel="noreferrer">DOM</a>. I preferably need a solution that does not require adding more .js files (jQuery plug-ins) to the page but something as simple as being able to catch the UpdatePanel's 'afterupdating' where I can just call my method to rebind all the form elements.</p>
| [
{
"answer_id": 301489,
"author": "Phil Jenkins",
"author_id": 35496,
"author_profile": "https://Stackoverflow.com/users/35496",
"pm_score": 7,
"selected": true,
"text": "pageLoad function pageLoad(sender, args)\n{\n if (args.get_isPartialLoad())\n {\n //Specific code for partial postbacks can go in here.\n }\n}\n"
},
{
"answer_id": 304642,
"author": "Paulius",
"author_id": 30005,
"author_profile": "https://Stackoverflow.com/users/30005",
"pm_score": 5,
"selected": false,
"text": "Sys.Application.add_load(initSomething);\nfunction initSomething()\n{\n // will execute on load plus on every UpdatePanel postback\n}\n"
},
{
"answer_id": 547303,
"author": "George",
"author_id": 66215,
"author_profile": "https://Stackoverflow.com/users/66215",
"pm_score": 5,
"selected": false,
"text": "on()"
},
{
"answer_id": 1199185,
"author": "shatl",
"author_id": 87055,
"author_profile": "https://Stackoverflow.com/users/87055",
"pm_score": 3,
"selected": false,
"text": "Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);\n\nfunction pageLoaded(sender, args) {\n var updatedPanels = args.get_panelsUpdated();\n // check if Main Panel was updated \n for (idx = 0; idx < updatedPanels.length; idx++) {\n if (updatedPanels[idx].id == \"<%=upMain.ID %>\") {\n rebindEventsForMainPanel();\n break;\n }\n }\n}\n"
},
{
"answer_id": 2049747,
"author": "civanm",
"author_id": 237737,
"author_profile": "https://Stackoverflow.com/users/237737",
"pm_score": 2,
"selected": false,
"text": " <script type=\"text/javascript\">\n function pageLoad() {\n\n if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {\n\n\n }\n\n </script>\n\n </ContentTemplate>\n </asp:UpdatePanel>\n"
},
{
"answer_id": 4098788,
"author": "rocke_amiga",
"author_id": 497390,
"author_profile": "https://Stackoverflow.com/users/497390",
"pm_score": 3,
"selected": false,
"text": " <script type=\"text/javascript\" language=\"javascript\">\n\n Sys.WebForms.PageRequestManager.getInstance().add_endRequest(addDataPicker); \n function addDataPicker(sender, args)\n {\n var fchFacturacion = document.getElementById('<%= txtFechaFacturacion.ClientID %>');\n if (fchFacturacion != null) {\n $(fchFacturacion).datepicker({ onSelect: function () { }, changeMonth: true, changeYear: true, showOn: 'button', buttonImage: '../Imagenes/calendar.gif', buttonImageOnly: true});}\n } \n\n </script>\n\n <asp:UpdatePanel ID=\"upEjem\" runat=\"server\" UpdateMode=\"Conditional\">\n <ContentTemplate>\n <div id=\"div1\" runat=\"server\" visible=\"false\">\n <input type=\"text\" id=\"txtFechaFacturacion\" \n name=\"txtFechaFacturacion\" visible=\"true\"\n readonly=\"readonly\" runat=\"server\" />\n </div>\n </ContentTemplate>\n </asp:UpdatePanel>\n"
},
{
"answer_id": 11764353,
"author": "lambinator",
"author_id": 292008,
"author_profile": "https://Stackoverflow.com/users/292008",
"pm_score": 4,
"selected": false,
"text": "$(':input').on('change', function() {...});\n $(document).on('change', ':input', function() {...});\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11619/"
] |
301,479 | <p>Here is new C# future in version 4.0 known as dynamic. Show me the way i can use it in my code and how this future can help me?</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/298277/does-the-new-dynamic-c-40-keyword-deprecate-the-var-keyword">Does the new ‘dynamic’ C# 4.0 keyword deprecate the ‘var’ keyword ?</a></li>
<li><a href="https://stackoverflow.com/questions/244302/what-do-you-think-of-the-new-c-40-dynamic-keyword">What do you think of the new C# 4.0 ‘dynamic’ keyword?</a></li>
</ul>
| [
{
"answer_id": 301498,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "HtmlPage.Window.Invoke(\"HelloWorldFunction\");\n HtmlPage.Window.HelloWorldFunction();\n"
},
{
"answer_id": 365229,
"author": "amazedsaint",
"author_id": 45956,
"author_profile": "https://Stackoverflow.com/users/45956",
"pm_score": 2,
"selected": false,
"text": "public class DynamicReader : IDynamicObject\n {\n public MetaObject GetMetaObject\n (System.Linq.Expressions.Expression parameter)\n {\n return new DynamicReaderDispatch (parameter);\n }\n }\n\n public class DynamicReaderDispatch : MetaObject\n {\n public DynamicReaderDispatch (Expression parameter) \n : base(parameter, Restrictions.Empty){ }\n\n public override MetaObject Call(CallAction action, MetaObject[] args)\n {\n //You might implement logic for dynamic method calls. Action.name\n // will give you the method name\n\n Console.WriteLine(\"Logic to dispatch Method '{0}'\", action.Name);\n return this;\n }\n }\n dynamic reader=new DynamicReader();\ndynamic data=reader.Read();\n"
},
{
"answer_id": 2248396,
"author": "Peter Gfader",
"author_id": 35693,
"author_profile": "https://Stackoverflow.com/users/35693",
"pm_score": 2,
"selected": false,
"text": "[TestMethod()]\npublic void CalculatorThingAdd_2PositiveNumbers_ResultAdded()\n{\n CalculatorThing myCalculator = new CalculatorThing();\n int result = 0; \n int expcected = 3;\n\n // --> CalculatorThing does not contain a definition for 'Addition'\n result = myCalculator.Addition(1, 2);\n\n Assert.AreEqual(result, expcected);\n}\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208062/"
] |
301,482 | <p>I have a ListBox control that I want to change into having a toggle selection. i.e. Click once on an item selects it, click again it deselects it. Also, clicking another item in the list should do the default action of deselecting the previous item and selecting the new one.</p>
<p>What's the best way of achieving this?</p>
| [
{
"answer_id": 301852,
"author": "Bijington",
"author_id": 32348,
"author_profile": "https://Stackoverflow.com/users/32348",
"pm_score": 0,
"selected": false,
"text": "Point newPoint = e.GetPosition(backgroundImage);\n\nHitTestResult result = VisualTreeHelper.HitTest(this, newPoint);\n\nif (result.VisualHit is ListBoxItem)\n"
},
{
"answer_id": 9026415,
"author": "dahvyd",
"author_id": 818227,
"author_profile": "https://Stackoverflow.com/users/818227",
"pm_score": 0,
"selected": false,
"text": "ListBox.SelectionMode Multiple EventManager.RegisterClassHandler(typeof(ListBoxItem),\n ListBoxItem.MouseLeftButtonDownEvent,\n new RoutedEventHandler(this.HandleListBox_MouseDown));\n\n...\n\nvoid HandleListBox_MouseDown(object sender, RoutedEventArgs e)\n{\n var listBoxItem = (ListBoxItem)sender;\n if (ShouldDeselectOtherListItems(listBoxItem))\n {\n listBox.SelectedIndex = -1;\n }\n}\n\nbool ShouldDeselectOtherListItems(ListBoxItem listBoxItem)\n{\n return !listBoxItem.IsSelected\n && listBox.SelectedItems.Count > 0;\n}\n"
},
{
"answer_id": 52265997,
"author": "Insert Clever Username",
"author_id": 1839576,
"author_profile": "https://Stackoverflow.com/users/1839576",
"pm_score": 0,
"selected": false,
"text": "<ListBox ... PreviewMouseLeftButtonDown=\"ListBox_OnPreviewMouseLeftButtonDown\"... />\n private void ListBox_OnPreviewMouseLeftButtonDown (object sender, MouseButtonEventArgs e)\n{\n // I have a special extension for GetParent, numerous examples on the internet of how you would do that\n var lbi = ((DependencyObject) e.OriginalSource).GetParent<ListBoxItem>();\n if (lbi != null && lbi.IsSelected)\n {\n lbi.IsSelected = false;\n e.Handled = true;\n }\n}\n public static class ListBoxEx\n{\n private static DependencyProperty ToggleSelectionProperty = DependencyProperty.RegisterAttached(..., HandleToggleSelectionChanged);\n private static bool GetToggleSelection (DependencyObject obj) => (bool)obj.GetValue(ToggleSelectionProperty);\n private static void SetToggleSelection (DependencyObject obj, bool shouldToggle) => obj.SetValue(ToggleSelectionProperty, shouldToggle);\n\n private static void HandleToggleSelectionChanged (DependencyObject obj)\n {\n if (obj is ListBox listBoxObj)\n {\n bool shouldToggle = GetToggleSelection(obj);\n if (shouldToggle)\n {\n listBoxObj.PreviewMouseLeftButtonDown += ToggleListBox_OnPreviewMouseLeftButtonDown ;\n }\n else\n {\n listBoxObj.PreviewMouseLeftButtonDown -= ToggleListBox_OnPreviewMouseLeftButtonDown ;\n }\n }\n }\n\n private static void ToggleListBox_OnPreviewMouseLeftButtonDown (object sender, MouseButtonEventArgs e)\n {\n // I have a special extension for GetParent, numerous examples on the internet of how you would do that\n var lbi = ((DependencyObject) e.OriginalSource).GetParent<ListBoxItem>();\n if (lbi != null && lbi.IsSelected)\n {\n lbi.IsSelected = false;\n e.Handled = true;\n }\n }\n}\n <ListBox ... yourNamespace:ListBoxEx.ToggleSelection=\"True\" />\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
301,484 | <p>I am trying to create a dialog box that will appear only if the browser selected is IE (any version) however I get this error:</p>
<blockquote>
<p>Message: HTML Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917)</p>
</blockquote>
<p>That's all in "Line/Char/Code" 0 so I do not know where is the error. The code I'm using is this:</p>
<pre><code> <script type="text/javascript">
<!--
if(BrowserDetect.browser.contains("Explorer"))
{
var Nachricht = 'Hemos detectado que está utilizando ' + BrowserDetect.browser + ' ' +
BrowserDetect.version + '. Puede que algunas funciones no estén habilitadas. <p></p> Si desea experimentar todo el potencial del portal, por favor intente desde otro navegador (browser). <p></p>Gracias
showDialog('¡Aviso Importante!',Nachricht,'warning',10);
}
</script>
</code></pre>
<p>I've noticed if I remove the "BrowserDetect.browser" and .version it removes the error, but I need those to check =/...any ideas will be appreciated =).</p>
| [
{
"answer_id": 301677,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 2,
"selected": false,
"text": "<!--[if IE]>\n<script type=\"text/javascript\"> \n showDialog('¡Aviso Importante!','message','warning',10);\n </script>\n<![endif]-->\n <!--[if lte IE 7]>\n <script type=\"text/javascript\"> \n showDialog('¡Aviso Importante!','Your are using a too old version of Internet explorer. Please upgrade','warning',10);\n </script>\n<![endif]-->\n"
},
{
"answer_id": 303190,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 2,
"selected": false,
"text": "if (document.evaluate) {\n // go ahead and use it\n} else {\n // browser doesn't support it; do something else\n}\n"
},
{
"answer_id": 303945,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 6,
"selected": true,
"text": "</ <script> <\\/"
},
{
"answer_id": 1009296,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "div ready $(document).ready(function(){\n some_random_javascript_function();\n});\n"
},
{
"answer_id": 3830109,
"author": "Pablo Alba",
"author_id": 311791,
"author_profile": "https://Stackoverflow.com/users/311791",
"pm_score": 3,
"selected": false,
"text": "<script defer=true>\n"
},
{
"answer_id": 20182114,
"author": "Apeli",
"author_id": 1039556,
"author_profile": "https://Stackoverflow.com/users/1039556",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function(){\n var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;\n po.src = 'https://apis.google.com/js/plusone.js';\n var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);\n});\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28586/"
] |
301,490 | <p>I have a class like so:</p>
<pre><code>public class ClassA
{
public bool MethodA()
{
//do something complicated to test requiring a lot of setup
}
public bool MethodB()
{
if (MethodA())
//do something
else
//do something else
endif
}
}
</code></pre>
<p>I have tests for MethodA and want to test MethodB, but all I want to do is to verify that if MethodA returns true that something happens and if MethodA returns false that something else happens. Can I do this with Rhino Mocks? Or do I have to set up all of the same mocks that I have already in the tests for MethodA?</p>
| [
{
"answer_id": 301677,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 2,
"selected": false,
"text": "<!--[if IE]>\n<script type=\"text/javascript\"> \n showDialog('¡Aviso Importante!','message','warning',10);\n </script>\n<![endif]-->\n <!--[if lte IE 7]>\n <script type=\"text/javascript\"> \n showDialog('¡Aviso Importante!','Your are using a too old version of Internet explorer. Please upgrade','warning',10);\n </script>\n<![endif]-->\n"
},
{
"answer_id": 303190,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 2,
"selected": false,
"text": "if (document.evaluate) {\n // go ahead and use it\n} else {\n // browser doesn't support it; do something else\n}\n"
},
{
"answer_id": 303945,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 6,
"selected": true,
"text": "</ <script> <\\/"
},
{
"answer_id": 1009296,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "div ready $(document).ready(function(){\n some_random_javascript_function();\n});\n"
},
{
"answer_id": 3830109,
"author": "Pablo Alba",
"author_id": 311791,
"author_profile": "https://Stackoverflow.com/users/311791",
"pm_score": 3,
"selected": false,
"text": "<script defer=true>\n"
},
{
"answer_id": 20182114,
"author": "Apeli",
"author_id": 1039556,
"author_profile": "https://Stackoverflow.com/users/1039556",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function(){\n var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;\n po.src = 'https://apis.google.com/js/plusone.js';\n var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);\n});\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
301,493 | <p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with?
(It is a web-app)</p>
| [
{
"answer_id": 301630,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": true,
"text": ".ini .properties \"\"\"A particular XML parser. Formats change, so sometimes this changes, too.\"\"\"\n\nimport xml.etree.ElementTree as xml\n\nclass SSXML_Source( object ):\n ns0= \"urn:schemas-microsoft-com:office:spreadsheet\"\n ns1= \"urn:schemas-microsoft-com:office:excel\"\n def __init__( self, aFileName, *sheets ):\n \"\"\"Initialize a XML source.\n XXX - Create better sheet filtering here, in the constructor.\n @param aFileName: the file name.\n \"\"\"\n super( SSXML_Source, self ).__init__( aFileName )\n self.log= logging.getLogger( \"source.PCIX_XLS\" )\n self.dom= etree.parse( aFileName ).getroot()\n def sheets( self ):\n for wb in self.dom.getiterator(\"{%s}Workbook\" % ( self.ns0, ) ):\n for ws in wb.getiterator( \"{%s}Worksheet\" % ( self.ns0, ) ):\n yield ws\n def rows( self ):\n for s in self.sheets():\n print s.attrib[\"{%s}Name\" % ( self.ns0, ) ]\n for t in s.getiterator( \"{%s}Table\" % ( self.ns0, ) ):\n for r in t.getiterator( \"{%s}Row\" % ( self.ns0, ) ):\n # The XML may not be really useful.\n # In some cases, you may have to convert to something useful\n yield r\n \"\"\"This is your target object. \nIt's part of the problem domain; it rarely changes.\n\"\"\"\nclass MyTargetObject( object ):\n def __init__( self ):\n self.someAttr= \"\"\n self.anotherAttr= \"\"\n self.this= 0\n self.that= 3.14159\n def aMethod( self ):\n \"\"\"etc.\"\"\"\n pass\n \"\"\"One of many builders. This changes all the time to fit\nspecific needs and situations. The goal is to keep this\nshort and to-the-point so that it has the mapping and nothing\nbut the mapping.\n\"\"\"\n\nimport model\n\nclass MyTargetBuilder( object ):\n def makeFromXML( self, element ):\n result= model.MyTargetObject()\n result.someAttr= element.findtext( \"Some\" )\n result.anotherAttr= element.findtext( \"Another\" )\n result.this= int( element.findtext( \"This\" ) )\n result.that= float( element.findtext( \"that\" ) )\n return result\n \"\"\"An application that maps from XML to the domain object\nusing a configurable \"builder\".\n\"\"\"\nimport model\nimport source\nimport builder_1\nimport builder_2\nimport builder_today\n\n# Configure this: pick a builder is appropriate for the data:\nb= builder_today.MyTargetBuilder()\n\ns= source.SSXML_Source( sys.argv[1] )\nfor r in s.rows():\n data= b.makeFromXML( r )\n # ... persist data with a DB save or file write\n"
},
{
"answer_id": 301847,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 2,
"selected": false,
"text": "<Export>\n <Product>\n <SKU>403276</SKU>\n <ItemName>Trivet</ItemName>\n <CollectionNo>0</CollectionNo>\n <Pages>0</Pages>\n </Product>\n</Export>\n FIELDS = %w[SKU ItemName CollectionNo Pages]\n\ndoc = Hpricot.parse(File.read(\"my.xml\")) \n(doc/:product).each do |xml_product|\n product = Product.new\n for field in FIELDS\n product[field] = (xml_product/field.intern).first.innerHTML\n end\n product.save\nend\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613/"
] |
301,502 | <p>I just installed an application on a win2003 server and I'm getting this error:</p>
<pre><code>Line 149: <roleManager>
Line 150: <providers>
Line 151: <add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Line 152: <add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Line 153: </providers>
Source File: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config Line: 151
</code></pre>
<p>I'm using a RoleProvider and it's properly configured in web.config (it works on other servers) as follows:</p>
<pre><code><membership defaultProvider="AdminMembershipProvider">
<providers>
<clear/>
<add name="AdminMembershipProvider" connectionStringName="SiteSqlServer" type="MyApp.Providers.AdminMembershipProvider" applicationName="MyApp" writeExceptionsToEventLog="false" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" PasswordFormat="Clear" MinRequiredNonAlphanumericCharacters="1" MinRequiredPasswordLength="8" MaxInvalidPasswordAttempts="5" PasswordAttemptWindow="10">
</add>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AdminRoleProvider" cacheRolesInCookie="true">
<providers>
<add name="AdminRoleProvider" type="MyApp.Providers.AdminRoleProvider" writeExceptionsToEventLog="true"/>
</providers>
</roleManager>
</code></pre>
<p>Any hint on why it's looking for configuration on machine.config instead of web.config? How can I debug this?</p>
<p>Thank you.</p>
| [
{
"answer_id": 301630,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": true,
"text": ".ini .properties \"\"\"A particular XML parser. Formats change, so sometimes this changes, too.\"\"\"\n\nimport xml.etree.ElementTree as xml\n\nclass SSXML_Source( object ):\n ns0= \"urn:schemas-microsoft-com:office:spreadsheet\"\n ns1= \"urn:schemas-microsoft-com:office:excel\"\n def __init__( self, aFileName, *sheets ):\n \"\"\"Initialize a XML source.\n XXX - Create better sheet filtering here, in the constructor.\n @param aFileName: the file name.\n \"\"\"\n super( SSXML_Source, self ).__init__( aFileName )\n self.log= logging.getLogger( \"source.PCIX_XLS\" )\n self.dom= etree.parse( aFileName ).getroot()\n def sheets( self ):\n for wb in self.dom.getiterator(\"{%s}Workbook\" % ( self.ns0, ) ):\n for ws in wb.getiterator( \"{%s}Worksheet\" % ( self.ns0, ) ):\n yield ws\n def rows( self ):\n for s in self.sheets():\n print s.attrib[\"{%s}Name\" % ( self.ns0, ) ]\n for t in s.getiterator( \"{%s}Table\" % ( self.ns0, ) ):\n for r in t.getiterator( \"{%s}Row\" % ( self.ns0, ) ):\n # The XML may not be really useful.\n # In some cases, you may have to convert to something useful\n yield r\n \"\"\"This is your target object. \nIt's part of the problem domain; it rarely changes.\n\"\"\"\nclass MyTargetObject( object ):\n def __init__( self ):\n self.someAttr= \"\"\n self.anotherAttr= \"\"\n self.this= 0\n self.that= 3.14159\n def aMethod( self ):\n \"\"\"etc.\"\"\"\n pass\n \"\"\"One of many builders. This changes all the time to fit\nspecific needs and situations. The goal is to keep this\nshort and to-the-point so that it has the mapping and nothing\nbut the mapping.\n\"\"\"\n\nimport model\n\nclass MyTargetBuilder( object ):\n def makeFromXML( self, element ):\n result= model.MyTargetObject()\n result.someAttr= element.findtext( \"Some\" )\n result.anotherAttr= element.findtext( \"Another\" )\n result.this= int( element.findtext( \"This\" ) )\n result.that= float( element.findtext( \"that\" ) )\n return result\n \"\"\"An application that maps from XML to the domain object\nusing a configurable \"builder\".\n\"\"\"\nimport model\nimport source\nimport builder_1\nimport builder_2\nimport builder_today\n\n# Configure this: pick a builder is appropriate for the data:\nb= builder_today.MyTargetBuilder()\n\ns= source.SSXML_Source( sys.argv[1] )\nfor r in s.rows():\n data= b.makeFromXML( r )\n # ... persist data with a DB save or file write\n"
},
{
"answer_id": 301847,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 2,
"selected": false,
"text": "<Export>\n <Product>\n <SKU>403276</SKU>\n <ItemName>Trivet</ItemName>\n <CollectionNo>0</CollectionNo>\n <Pages>0</Pages>\n </Product>\n</Export>\n FIELDS = %w[SKU ItemName CollectionNo Pages]\n\ndoc = Hpricot.parse(File.read(\"my.xml\")) \n(doc/:product).each do |xml_product|\n product = Product.new\n for field in FIELDS\n product[field] = (xml_product/field.intern).first.innerHTML\n end\n product.save\nend\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7277/"
] |
301,504 | <p>A follow up to an earlier question, showing the part that fails when I try to get the error message from my target library:</p>
<pre><code>require 'gt4r'
@@test_environment = "INCLUDE=C:\\graphtalk\\env\\aiadev\\config\\aiadev.ini"
@@normal_user = "BMCHARGUE"
describe Gt4r do
it 'initializes' do
rv = Gt4r.gTD_initialize @@normal_user, @@normal_user, @@test_environment
Gt4r.gTD_get_error_message rv, @msg
@msg.should == ""
rv.should == 0
end
end
</code></pre>
<p>I expect the error message to be returned in @msg, but when run I get the following:</p>
<pre><code>Gt4r
(eval):5: [BUG] Segmentation fault
ruby 1.8.6 (2008-08-11) [i386-mswin32]
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
</code></pre>
<p>And this if I use a symbol (:msg) instead:</p>
<pre><code>C:\code\GraphTalk\gt4r_dl>spec -fs -rgt4r gt4r_spec.rb
Gt4r
- initializes (ERROR - 1)
1)
NoMethodError in 'Gt4r initializes'
undefined method `to_ptr' for :msg:Symbol
(eval):5:in `call'
(eval):5:in `gTD_get_error_message'
./gt4r_spec.rb:9:
Finished in 0.046 seconds
1 example, 1 failure
</code></pre>
<p>Clearly I am missing something about passing parameters between ruby and C. What kind of ruby variable do I need to get my value returned? </p>
| [
{
"answer_id": 301774,
"author": "a2800276",
"author_id": 27408,
"author_profile": "https://Stackoverflow.com/users/27408",
"pm_score": 2,
"selected": false,
"text": "Gt4r.gTD_get_error_message rv, @msg\n"
},
{
"answer_id": 301781,
"author": "a2800276",
"author_id": 27408,
"author_profile": "https://Stackoverflow.com/users/27408",
"pm_score": -1,
"selected": false,
"text": "Gt4r.gTD_get_error_message rv, @msg\n"
},
{
"answer_id": 14182967,
"author": "Assad Ebrahim",
"author_id": 181638,
"author_profile": "https://Stackoverflow.com/users/181638",
"pm_score": 0,
"selected": false,
"text": "FFI FFI"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32322/"
] |
301,510 | <p>I have an offline paper based form. I need to convert it into a software that people can use on their computers to fill and submit information. Since the form (it is a tax return) requires considerable time in filling, it is not convenient to have it online. I would much rather have a simple exe which gathers information, applies validation rules and then uploads a structured data file (like an XML file) containing the filled info.</p>
<hr>
<p>I mean that I have an offline paper based form. I need to convert it into a software that people can use on their computers to fill and submit information. Since the form (it is a tax return) requires considerable time in filling, it is not convenient to have it online only. I would much rather have a simple exe which gathers information, applies validation rules and then uploads a structured data file (like an XML file) containing the filled info.</p>
| [
{
"answer_id": 301521,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "/main"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22009/"
] |
301,525 | <p>What are the expert debugging hints for your favourite language, you think everyone should use?</p>
<p>As an example, I'll provide my C++ debugging hints, that between them help me shake out most of the bugs I come across, in this often hard-to-debug language.</p>
<p><B>C++</B></p>
<ul>
<li><p>Increase the warning level of your compiler to maximum, then stop those warnings which occur a lot and you've decided you don't care about (for me it's unused parameters). g++ doesn't warn about missing return statements in functions (a problem I find frequently) until the warning level is very high.</p></li>
<li><p>Learn how to turn on your compiler's debugging standard library, and use it! ( -D_GLIBCXX_DEBUG for g++). This finds lots of errors, and also helps show exactly where the errors occurred.</p></li>
<li><p>Always, always, always run your code through a really good memory checker, like <a href="http://valgrind.org/" rel="noreferrer">valgrind</a>, and fix all the problems it produces.</p></li>
</ul>
| [
{
"answer_id": 301857,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "echo '<pre>'; print_r($GLOBALS); echo '</pre>';\n"
},
{
"answer_id": 301900,
"author": "user38329",
"author_id": 38329,
"author_profile": "https://Stackoverflow.com/users/38329",
"pm_score": 0,
"selected": false,
"text": " class foo\n {\n int bar() { int i = func1(); int j = func2(i); return j; }\n };\n"
}
] | 2008/11/19 | [
"https://Stackoverflow.com/questions/301525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27074/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.