qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
206,805
<p>I'm trying to use <code>tasklist</code> to find out which process is consuming more than X percent of my CPU (to later kill it with <code>taskkill</code>.) </p> <p>How do I know what percent a time format represents?</p> <p>The documentations says:</p> <pre><code>TASKLIST options /FI filter </code></pre> <p>And one filter may be:</p> <pre><code>CPUTIME eq, ne, gt, lt, ge, le CPU time in the format: hh:mm:ss. hh - number of hours, mm - minutes, ss - seconds </code></pre> <p>If I try</p> <pre><code>tasklist /FI "CPUTIME gt 00:00:10" </code></pre> <p>it works.</p> <p>But if I </p> <pre><code>tasklist /FI "CPUTIME gt 90" </code></pre> <p>it doesn't.</p> <p>How can I know that time format represent 90%? Or 80%? What's the relationship between CPU usage time and the CPU usage percent?</p>
[ { "answer_id": 206893, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": true, "text": " (TotalProcessRuntime / CpuTime) / 100\n" }, { "answer_id": 207439, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "C:\\> wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime\n\nName PercentProcessorTime\nIdle 0\nSystem 0\nSmss 0\ncsrss 0\nwinlogon 0\nservices 0\nlsass 0\n\n[...]\n\nwmiprvse 100\nwmic 0\n_Total 100\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
206,806
<p>In vi[m] there is the <a href="http://www.softpanorama.org/Editors/Vimorama/vim_piping.shtml" rel="noreferrer"><code>!</code> command which lets me pipe text</a> through a shell command -- like sort or indent -- and get the filtered text back into the buffer. Is there an equivalent in emacs?</p>
[ { "answer_id": 206809, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 3, "selected": false, "text": "M-x shell-command-on-region M-| C-h f shell-command-on-region replace *scratch* M-x eval-buffer (defun shell-command-on-region-replace (start end command)\n \"Run shell-command-on-region interactivly replacing the region in place\"\n (interactive (let (string) \n (unless (mark)\n (error \"The mark is not set now, so there is no region\"))\n ;; Do this before calling region-beginning\n ;; and region-end, in case subprocess output\n ;; relocates them while we are in the minibuffer.\n ;; call-interactively recognizes region-beginning and\n ;; region-end specially, leaving them in the history.\n (setq string (read-from-minibuffer \"Shell command on region: \"\n nil nil nil\n 'shell-command-history))\n (list (region-beginning) (region-end)\n string)))\n (shell-command-on-region start end command t t)\n )\n C-space" }, { "answer_id": 207067, "author": "Greg Mattes", "author_id": 13940, "author_profile": "https://Stackoverflow.com/users/13940", "pm_score": 4, "selected": false, "text": "(defun generalized-shell-command (command arg)\n \"Unifies `shell-command' and `shell-command-on-region'. If no region is\nselected, run a shell command just like M-x shell-command (M-!). If\nno region is selected and an argument is a passed, run a shell command\nand place its output after the mark as in C-u M-x `shell-command' (C-u\nM-!). If a region is selected pass the text of that region to the\nshell and replace the text in that region with the output of the shell\ncommand as in C-u M-x `shell-command-on-region' (C-u M-|). If a region\nis selected AND an argument is passed (via C-u) send output to another\nbuffer instead of replacing the text in region.\"\n (interactive (list (read-from-minibuffer \"Shell command: \" nil nil nil 'shell-command-history)\n current-prefix-arg))\n (let ((p (if mark-active (region-beginning) 0))\n (m (if mark-active (region-end) 0)))\n (if (= p m)\n ;; No active region\n (if (eq arg nil)\n (shell-command command)\n (shell-command command t))\n ;; Active region\n (if (eq arg nil)\n (shell-command-on-region p m command t t)\n (shell-command-on-region p m command)))))\n F3 (global-set-key [f3] 'generalized-shell-command)\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27928/" ]
206,820
<p>I would like to either prevent or handle a <code>StackOverflowException</code> that I am getting from a call to the <code>XslCompiledTransform.Transform</code> method within an <code>Xsl Editor</code> I am writing. The problem seems to be that the user can write an <code>Xsl script</code> that is infinitely recursive, and it just blows up on the call to the <code>Transform</code> method. (That is, the problem is not just the typical programmatic error, which is usually the cause of such an exception.)</p> <p>Is there a way to detect and/or limit how many recursions are allowed? Or any other ideas to keep this code from just blowing up on me?</p>
[ { "answer_id": 206842, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 7, "selected": true, "text": "// This is just an example, obviously you'll want to pass args to this.\nProcess p1 = new Process();\np1.StartInfo.FileName = \"ApplyTransform.exe\";\np1.StartInfo.UseShellExecute = false;\np1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n\np1.Start();\np1.WaitForExit();\n\nif (p1.ExitCode == 1) \n Console.WriteLine(\"StackOverflow was thrown\");\n class Program\n{\n static void Main(string[] args)\n {\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);\n throw new StackOverflowException();\n }\n\n // We trap this, we can't save the process, \n // but we can prevent the \"ILLEGAL OPERATION\" window \n static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n {\n if (e.IsTerminating)\n {\n Environment.Exit(1);\n }\n }\n}\n" }, { "answer_id": 2117310, "author": "Dmitry Dzygin", "author_id": 256727, "author_profile": "https://Stackoverflow.com/users/256727", "pm_score": 3, "selected": false, "text": "public class LimitedDepthXmlWriter : XmlWriter\n{\n private readonly XmlWriter _innerWriter;\n private readonly int _maxDepth;\n private int _depth;\n\n public LimitedDepthXmlWriter(XmlWriter innerWriter): this(innerWriter, 100)\n {\n }\n\n public LimitedDepthXmlWriter(XmlWriter innerWriter, int maxDepth)\n {\n _maxDepth = maxDepth;\n _innerWriter = innerWriter;\n }\n\n public override void Close()\n {\n _innerWriter.Close();\n }\n\n public override void Flush()\n {\n _innerWriter.Flush();\n }\n\n public override string LookupPrefix(string ns)\n {\n return _innerWriter.LookupPrefix(ns);\n }\n\n public override void WriteBase64(byte[] buffer, int index, int count)\n {\n _innerWriter.WriteBase64(buffer, index, count);\n }\n\n public override void WriteCData(string text)\n {\n _innerWriter.WriteCData(text);\n }\n\n public override void WriteCharEntity(char ch)\n {\n _innerWriter.WriteCharEntity(ch);\n }\n\n public override void WriteChars(char[] buffer, int index, int count)\n {\n _innerWriter.WriteChars(buffer, index, count);\n }\n\n public override void WriteComment(string text)\n {\n _innerWriter.WriteComment(text);\n }\n\n public override void WriteDocType(string name, string pubid, string sysid, string subset)\n {\n _innerWriter.WriteDocType(name, pubid, sysid, subset);\n }\n\n public override void WriteEndAttribute()\n {\n _innerWriter.WriteEndAttribute();\n }\n\n public override void WriteEndDocument()\n {\n _innerWriter.WriteEndDocument();\n }\n\n public override void WriteEndElement()\n {\n _depth--;\n\n _innerWriter.WriteEndElement();\n }\n\n public override void WriteEntityRef(string name)\n {\n _innerWriter.WriteEntityRef(name);\n }\n\n public override void WriteFullEndElement()\n {\n _innerWriter.WriteFullEndElement();\n }\n\n public override void WriteProcessingInstruction(string name, string text)\n {\n _innerWriter.WriteProcessingInstruction(name, text);\n }\n\n public override void WriteRaw(string data)\n {\n _innerWriter.WriteRaw(data);\n }\n\n public override void WriteRaw(char[] buffer, int index, int count)\n {\n _innerWriter.WriteRaw(buffer, index, count);\n }\n\n public override void WriteStartAttribute(string prefix, string localName, string ns)\n {\n _innerWriter.WriteStartAttribute(prefix, localName, ns);\n }\n\n public override void WriteStartDocument(bool standalone)\n {\n _innerWriter.WriteStartDocument(standalone);\n }\n\n public override void WriteStartDocument()\n {\n _innerWriter.WriteStartDocument();\n }\n\n public override void WriteStartElement(string prefix, string localName, string ns)\n {\n if (_depth++ > _maxDepth) ThrowException();\n\n _innerWriter.WriteStartElement(prefix, localName, ns);\n }\n\n public override WriteState WriteState\n {\n get { return _innerWriter.WriteState; }\n }\n\n public override void WriteString(string text)\n {\n _innerWriter.WriteString(text);\n }\n\n public override void WriteSurrogateCharEntity(char lowChar, char highChar)\n {\n _innerWriter.WriteSurrogateCharEntity(lowChar, highChar);\n }\n\n public override void WriteWhitespace(string ws)\n {\n _innerWriter.WriteWhitespace(ws);\n }\n\n private void ThrowException()\n {\n throw new InvalidOperationException(string.Format(\"Result xml has more than {0} nested tags. It is possible that xslt transformation contains an endless recursive call.\", _maxDepth));\n }\n}\n" }, { "answer_id": 3564654, "author": "jdehaan", "author_id": 170443, "author_profile": "https://Stackoverflow.com/users/170443", "pm_score": 1, "selected": false, "text": "HandleProcessCorruptedStateExceptions using System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Runtime.ExceptionServices;\n\nnamespace ExceptionCatching\n{\n public class Test\n {\n public void StackOverflow()\n {\n StackOverflow();\n }\n\n public void CustomException()\n {\n throw new Exception();\n }\n\n public unsafe void AccessViolation()\n {\n byte b = *(byte*)(8762765876);\n }\n }\n\n class Program\n {\n [HandleProcessCorruptedStateExceptions]\n static void Main(string[] args)\n {\n Test test = new Test();\n try {\n //test.StackOverflow();\n test.AccessViolation();\n //test.CustomException();\n }\n catch\n {\n Console.WriteLine(\"Caught.\");\n }\n\n Console.WriteLine(\"End of program\");\n\n }\n\n } \n}\n" }, { "answer_id": 14059270, "author": "sharp12345", "author_id": 1279594, "author_profile": "https://Stackoverflow.com/users/1279594", "pm_score": -1, "selected": false, "text": "Environment.StackTrace" }, { "answer_id": 17553381, "author": "Fixation", "author_id": 2565370, "author_profile": "https://Stackoverflow.com/users/2565370", "pm_score": 2, "selected": false, "text": " class Foo\n {\n public Foo()\n {\n Go();\n }\n\n public void Go()\n {\n for (float i = float.MinValue; i < float.MaxValue; i+= 0.000000000000001f)\n {\n byte[] b = new byte[1]; // Causes stackoverflow\n }\n }\n }\n class Foo\n{\n public Foo()\n {\n GoHelper();\n }\n\n public void GoHelper()\n {\n for (float i = float.MinValue; i < float.MaxValue; i+= 0.000000000000001f)\n {\n Go();\n }\n }\n\n public void Go()\n {\n byte[] b = new byte[1]; // Will get cleaned by GC\n } // right now\n}\n" }, { "answer_id": 30681031, "author": "atlaste", "author_id": 1031591, "author_profile": "https://Stackoverflow.com/users/1031591", "pm_score": 5, "selected": false, "text": "class StackOverflowDetector\n{\n static int Recur()\n {\n int variable = 1;\n return variable + Recur();\n }\n\n static void Start()\n {\n int depth = 1 + Recur();\n }\n\n static void Main(string[] args)\n {\n Thread t = new Thread(Start, 1);\n t.Start();\n t.Join();\n Console.WriteLine();\n Console.ReadLine();\n }\n}\n StackOverflowException class StackOverflowDetector\n{\n static void CheckStackDepth()\n {\n if (new StackTrace().FrameCount > 10) // some arbitrary limit\n {\n throw new StackOverflowException(\"Bad thread.\");\n }\n }\n\n static int Recur()\n {\n CheckStackDepth();\n int variable = 1;\n return variable + Recur();\n }\n\n static void Main(string[] args)\n {\n try\n {\n int depth = 1 + Recur();\n }\n catch (ThreadAbortException e)\n {\n Console.WriteLine(\"We've been a {0}\", e.ExceptionState);\n }\n Console.WriteLine();\n Console.ReadLine();\n }\n}\n class StackOverflowDetector\n{\n static int Recur()\n {\n Thread.Sleep(1); // simulate that we're actually doing something :-)\n int variable = 1;\n return variable + Recur();\n }\n\n static void Start()\n {\n try\n {\n int depth = 1 + Recur();\n }\n catch (ThreadAbortException e)\n {\n Console.WriteLine(\"We've been a {0}\", e.ExceptionState);\n }\n }\n\n static void Main(string[] args)\n {\n // Prepare the execution thread\n Thread t = new Thread(Start);\n t.Priority = ThreadPriority.Lowest;\n\n // Create the watch thread\n Thread watcher = new Thread(Watcher);\n watcher.Priority = ThreadPriority.Highest;\n watcher.Start(t);\n\n // Start the execution thread\n t.Start();\n t.Join();\n\n watcher.Abort();\n Console.WriteLine();\n Console.ReadLine();\n }\n\n private static void Watcher(object o)\n {\n Thread towatch = (Thread)o;\n\n while (true)\n {\n if (towatch.ThreadState == System.Threading.ThreadState.Running)\n {\n towatch.Suspend();\n var frames = new System.Diagnostics.StackTrace(towatch, false);\n if (frames.FrameCount > 20)\n {\n towatch.Resume();\n towatch.Abort(\"Bad bad thread!\");\n }\n else\n {\n towatch.Resume();\n }\n }\n }\n }\n}\n // A simple decompiler that extracts all method tokens (that is: call, callvirt, newobj in IL)\ninternal class Decompiler\n{\n private Decompiler() { }\n\n static Decompiler()\n {\n singleByteOpcodes = new OpCode[0x100];\n multiByteOpcodes = new OpCode[0x100];\n FieldInfo[] infoArray1 = typeof(OpCodes).GetFields();\n for (int num1 = 0; num1 < infoArray1.Length; num1++)\n {\n FieldInfo info1 = infoArray1[num1];\n if (info1.FieldType == typeof(OpCode))\n {\n OpCode code1 = (OpCode)info1.GetValue(null);\n ushort num2 = (ushort)code1.Value;\n if (num2 < 0x100)\n {\n singleByteOpcodes[(int)num2] = code1;\n }\n else\n {\n if ((num2 & 0xff00) != 0xfe00)\n {\n throw new Exception(\"Invalid opcode: \" + num2.ToString());\n }\n multiByteOpcodes[num2 & 0xff] = code1;\n }\n }\n }\n }\n\n private static OpCode[] singleByteOpcodes;\n private static OpCode[] multiByteOpcodes;\n\n public static MethodBase[] Decompile(MethodBase mi, byte[] ildata)\n {\n HashSet<MethodBase> result = new HashSet<MethodBase>();\n\n Module module = mi.Module;\n\n int position = 0;\n while (position < ildata.Length)\n {\n OpCode code = OpCodes.Nop;\n\n ushort b = ildata[position++];\n if (b != 0xfe)\n {\n code = singleByteOpcodes[b];\n }\n else\n {\n b = ildata[position++];\n code = multiByteOpcodes[b];\n b |= (ushort)(0xfe00);\n }\n\n switch (code.OperandType)\n {\n case OperandType.InlineNone:\n break;\n case OperandType.ShortInlineBrTarget:\n case OperandType.ShortInlineI:\n case OperandType.ShortInlineVar:\n position += 1;\n break;\n case OperandType.InlineVar:\n position += 2;\n break;\n case OperandType.InlineBrTarget:\n case OperandType.InlineField:\n case OperandType.InlineI:\n case OperandType.InlineSig:\n case OperandType.InlineString:\n case OperandType.InlineTok:\n case OperandType.InlineType:\n case OperandType.ShortInlineR:\n position += 4;\n break;\n case OperandType.InlineR:\n case OperandType.InlineI8:\n position += 8;\n break;\n case OperandType.InlineSwitch:\n int count = BitConverter.ToInt32(ildata, position);\n position += count * 4 + 4;\n break;\n\n case OperandType.InlineMethod:\n int methodId = BitConverter.ToInt32(ildata, position);\n position += 4;\n try\n {\n if (mi is ConstructorInfo)\n {\n result.Add((MethodBase)module.ResolveMember(methodId, mi.DeclaringType.GetGenericArguments(), Type.EmptyTypes));\n }\n else\n {\n result.Add((MethodBase)module.ResolveMember(methodId, mi.DeclaringType.GetGenericArguments(), mi.GetGenericArguments()));\n }\n }\n catch { } \n break;\n \n\n default:\n throw new Exception(\"Unknown instruction operand; cannot continue. Operand type: \" + code.OperandType);\n }\n }\n return result.ToArray();\n }\n}\n\nclass StackOverflowDetector\n{\n // This method will be found:\n static int Recur()\n {\n CheckStackDepth();\n int variable = 1;\n return variable + Recur();\n }\n\n static void Main(string[] args)\n {\n RecursionDetector();\n Console.WriteLine();\n Console.ReadLine();\n }\n\n static void RecursionDetector()\n {\n // First decompile all methods in the assembly:\n Dictionary<MethodBase, MethodBase[]> calling = new Dictionary<MethodBase, MethodBase[]>();\n var assembly = typeof(StackOverflowDetector).Assembly;\n\n foreach (var type in assembly.GetTypes())\n {\n foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).OfType<MethodBase>())\n {\n var body = member.GetMethodBody();\n if (body!=null)\n {\n var bytes = body.GetILAsByteArray();\n if (bytes != null)\n {\n // Store all the calls of this method:\n var calls = Decompiler.Decompile(member, bytes);\n calling[member] = calls;\n }\n }\n }\n }\n\n // Check every method:\n foreach (var method in calling.Keys)\n {\n // If method A -> ... -> method A, we have a possible infinite recursion\n CheckRecursion(method, calling, new HashSet<MethodBase>());\n }\n }\n" }, { "answer_id": 30681654, "author": "Jeremy Thompson", "author_id": 495455, "author_profile": "https://Stackoverflow.com/users/495455", "pm_score": 3, "selected": false, "text": "StackTrace().FrameCount" }, { "answer_id": 30782671, "author": "Nick Mertin", "author_id": 3402566, "author_profile": "https://Stackoverflow.com/users/3402566", "pm_score": 0, "selected": false, "text": "StackOverflowException AppDomain using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing System.Threading;\n\nnamespace StackOverflowExceptionAppDomainTest\n{\n class Program\n {\n static void recrusiveAlgorithm()\n {\n recrusiveAlgorithm();\n }\n static void Main(string[] args)\n {\n if(args.Length>0&&args[0]==\"--child\")\n {\n recrusiveAlgorithm();\n }\n else\n {\n var domain = AppDomain.CreateDomain(\"Child domain to test StackOverflowException in.\");\n domain.ExecuteAssembly(Assembly.GetEntryAssembly().CodeBase, new[] { \"--child\" });\n domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>\n {\n Console.WriteLine(\"Detected unhandled exception: \" + e.ExceptionObject.ToString());\n };\n while (true)\n {\n Console.WriteLine(\"*\");\n Thread.Sleep(1000);\n }\n }\n }\n }\n}\n Process.Exited Process.StandardOutput" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27109/" ]
206,853
<p>I'm running a console app (myApp.exe) which outputs a pseudo localized (unicode) string to the standard output. If I run this in a regular command prompt(cmd.exe), the unicode data gets lost. If I run this in a unicode command prompt(cmd.exe /u) or set the properties of the console to "Lucida Console" then the unicode string is maintained.</p> <p>I'd like to run this app in C# and redirect the unicode string into a local variable. I'm using a Process object with RedirectStandardOutput = true, but the unicode string is always lost. </p> <p>How can I specify to persist this unicode info?</p> <pre><code> private static int RunDISM(string Args, out string ConsoleOutput) { Process process = new Process(); process.StartInfo.FileName = "myApp.exe"; process.StartInfo.Arguments = Args; try { process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; process.Start(); process.WaitForExit(Int32.MaxValue); } catch (Exception e) { WEX.Logging.Interop.Log.Assert("Failure while starting or running process.\nERROR: " + e.Message); ConsoleOutput = null; return EXITCODE_ERROR; } ConsoleOutput = process.StandardOutput.ReadToEnd(); return process.ExitCode; } </code></pre>
[ { "answer_id": 207129, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 2, "selected": false, "text": "process.StartInfo.StandardOutputEncoding = Encoding.Unicode;\n" }, { "answer_id": 2067280, "author": "ziya", "author_id": 248393, "author_profile": "https://Stackoverflow.com/users/248393", "pm_score": 2, "selected": false, "text": "var b = p.StandardOutput.CurrentEncoding.GetBytes(p.StandardOutput.ReadToEnd());\n" }, { "answer_id": 60586335, "author": "CSharper", "author_id": 70799, "author_profile": "https://Stackoverflow.com/users/70799", "pm_score": 0, "selected": false, "text": "process.StartInfo.StandardOutputEncoding = Encoding.Default Control Panel Region Administrative Change system locale..." } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165305/" ]
206,857
<p>I would like to implement a producer/consumer scenario that obeys interfaces that are roughly:</p> <pre><code>class Consumer { private: vector&lt;char&gt; read(size_t n) { // If the internal buffer has `n` elements, then dequeue them // Otherwise wait for more data and try again } public: void run() { read(10); read(4839); // etc } void feed(const vector&lt;char&gt; &amp;more) { // Safely queue the data // Notify `read` that there is now more data } }; </code></pre> <p>In this case, <code>feed</code> and <code>run</code> will run on separate threads and <code>read</code> should be a blocking read (like <code>recv</code> and <code>fread</code>). Obviously, I will need some kind of mutual exclusion on my deque, and I will need some kind of notification system to inform <code>read</code> to try again.</p> <p>I hear <strong>condition variables</strong> are the way to go, but all my multithreading experience lies with Windows and am having a hard time wrapping my head around them. </p> <p>Thanks for any help!</p> <p>(Yes, I know it's inefficient to return vectors. Let's not get into that.)</p>
[ { "answer_id": 206868, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 1, "selected": false, "text": "class piper\n{\npthread_mutex queuemutex;\npthread_mutex readymutex;\nbool isReady; //init to false by constructor\n\n//whatever else\n};\n\npiper::read()\n{//whatever\npthread_mutex_lock(&queuemutex)\nif(myqueue.size() >= n)\n{ \n return_queue_vector.push_back(/* you know what to do here */)\n\n pthread_mutex_lock(&readymutex)\n isReady = false;\n pthread_mutex_unlock(&readymutex)\n}\npthread_mutex_unlock(&queuemutex)\n}\n\npiper::push_em_in()\n{\n//more whatever\npthread_mutex_lock(&queuemutex)\n//push push push\nif(myqueue.size() >= n)\n{\n pthread_mutex_lock(&readymutex)\n isReady = true;\n pthread_mutex_unlock(&readymutex)\n}\npthread_mutex_unlock(&queuemutex)\n}\n" }, { "answer_id": 206926, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": true, "text": "#include <iostream>\n#include <vector>\n#include <pthread.h>\n\nclass LockThread\n{\n public:\n LockThread(pthread_mutex_t& m)\n :mutex(m)\n {\n pthread_mutex_lock(&mutex);\n }\n ~LockThread()\n {\n pthread_mutex_unlock(&mutex);\n }\n private:\n pthread_mutex_t& mutex;\n};\nclass Consumer\n{\n pthread_mutex_t lock;\n pthread_cond_t cond;\n std::vector<char> unreadData;\n public:\n Consumer()\n {\n pthread_mutex_init(&lock,NULL);\n pthread_cond_init(&cond,NULL);\n }\n ~Consumer()\n {\n pthread_cond_destroy(&cond);\n pthread_mutex_destroy(&lock);\n }\n\n private:\n std::vector<char> read(size_t n)\n {\n LockThread locker(lock);\n while (unreadData.size() < n)\n {\n // Must wait until we have n char.\n // This is a while loop because feed may not put enough in.\n\n // pthread_cond() releases the lock.\n // Thread will not be allowed to continue until\n // signal is called and this thread reacquires the lock.\n\n pthread_cond_wait(&cond,&lock);\n\n // Once released from the condition you will have re-aquired the lock.\n // Thus feed() must have exited and released the lock first.\n }\n\n /*\n * Not sure if this is exactly what you wanted.\n * But the data is copied out of the thread safe buffer\n * into something that can be returned.\n */\n std::vector<char> result(n); // init result with size n\n std::copy(&unreadData[0],\n &unreadData[n],\n &result[0]);\n\n unreadData.erase(unreadData.begin(),\n unreadData.begin() + n);\n return (result);\n }\npublic:\n void run()\n {\n read(10);\n read(4839);\n // etc\n }\n void feed(const std::vector<char> &more)\n {\n LockThread locker(lock);\n\n // Once we acquire the lock we can safely modify the buffer.\n std::copy(more.begin(),more.end(),std::back_inserter(unreadData));\n\n // Only signal the thread if you have the lock\n // Otherwise race conditions happen.\n pthread_cond_signal(&cond);\n\n // destructor releases the lock and thus allows read thread to continue.\n }\n};\n\n\nint main()\n{\n Consumer c;\n}\n" }, { "answer_id": 206944, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 2, "selected": false, "text": "#ifndef SYNCQUEUE_20061005_H_\n#define SYNCQUEUE_20061005_H_\n\n#include <queue>\n#include \"Semaphore.h\"\n\n// similar, but slightly simpler interface to std::queue\n// this queue implementation will serialize pushes and pops\n// and block on a pop while empty (as apposed to throwing an exception)\n// it also locks as neccessary on insertion and removal to avoid race \n// conditions\n\ntemplate <class T, class C = std::deque<T> > class SyncQueue {\nprotected:\n std::queue<T, C> m_Queue;\n Semaphore m_Semaphore;\n Mutex m_Mutex;\n\npublic:\n typedef typename std::queue<T, C>::value_type value_type;\n typedef typename std::queue<T, C>::size_type size_type;\n\n explicit SyncQueue(const C& a = C()) : m_Queue(a), m_Semaphore(0) {}\n\n bool empty() const { return m_Queue.empty(); }\n size_type size() const { return m_Queue.size(); }\n\n void push(const value_type& x);\n value_type pop();\n};\n\ntemplate <class T, class C>\nvoid SyncQueue<T, C>::push(const SyncQueue<T, C>::value_type &x) {\n // atomically push item\n m_Mutex.lock(); \n m_Queue.push(x); \n m_Mutex.unlock(); \n\n // let blocking semaphore know another item has arrived\n m_Semaphore.v();\n}\n\ntemplate <class T, class C>\ntypename SyncQueue<T, C>::value_type SyncQueue<T, C>::pop() {\n // block until we have at least one item\n m_Semaphore.p();\n\n // atomically read and pop front item\n m_Mutex.lock();\n value_type ret = m_Queue.front();\n m_Queue.pop();\n m_Mutex.unlock();\n\n return ret;\n}\n\n#endif\n std::vector<char> func(int size) {\n std::vector<char> result;\n while(result.size() != size) {\n result.push_back(my_sync_queue.pop());\n }\n return result;\n}\n" }, { "answer_id": 206961, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "boost::mutex access;\nboost::condition cond;\n\n// consumer\ndata read()\n{\n boost::mutex::scoped_lock lock(access);\n // this blocks until the data is ready\n cond.wait(lock);\n\n // queue is ready\n return data_from_queue();\n}\n\n// producer\nvoid push(data)\n{\n boost::mutex::scoped_lock lock(access);\n // add data to queue\n\n if (queue_has_enough_data())\n cond.notify_one(); \n}\n" }, { "answer_id": 207026, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "#include <algorithm>\n#include <deque>\n#include <pthread.h>\n\ntemplate<typename T>\nclass MultithreadedReader {\n std::deque<T> buffer;\n pthread_mutex_t moreDataMutex;\n pthread_cond_t moreDataCond;\n\nprotected:\n template<typename OutputIterator>\n void read(size_t count, OutputIterator result) {\n pthread_mutex_lock(&moreDataMutex);\n\n while (buffer.size() < count) {\n pthread_cond_wait(&moreDataCond, &moreDataMutex);\n }\n std::copy(buffer.begin(), buffer.begin() + count, result);\n buffer.erase(buffer.begin(), buffer.begin() + count);\n\n pthread_mutex_unlock(&moreDataMutex);\n }\n\npublic:\n MultithreadedReader() {\n pthread_mutex_init(&moreDataMutex, 0);\n pthread_cond_init(&moreDataCond, 0);\n }\n\n ~MultithreadedReader() {\n pthread_cond_destroy(&moreDataCond);\n pthread_mutex_destroy(&moreDataMutex);\n }\n\n template<typename InputIterator>\n void feed(InputIterator first, InputIterator last) {\n pthread_mutex_lock(&moreDataMutex);\n\n buffer.insert(buffer.end(), first, last);\n pthread_cond_signal(&moreDataCond);\n\n pthread_mutex_unlock(&moreDataMutex);\n }\n};\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
206,867
<p>I've done some research and I can't really find a preferred way to do updating of form controls from a worker thread in C#. I know about the BackgroundWorker component, but what is the best way to do it without using the BackgroundWorker component?</p>
[ { "answer_id": 206884, "author": "AR.", "author_id": 1354, "author_profile": "https://Stackoverflow.com/users/1354", "pm_score": 4, "selected": true, "text": "// Updates the textbox text.\nprivate void UpdateText(string text)\n{\n // Set the textbox text.\n m_TextBox.Text = text;\n}\n\npublic delegate void UpdateTextCallback(string text);\n\n// Then from your thread you can call this...\nm_TextBox.Invoke(new UpdateTextCallback(this.UpdateText),\n new object[]{\"Text generated on non-UI thread.\"});\n" }, { "answer_id": 206984, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "if (InvokeRequired)\n {\n //This.Invoke added to circumvent cross threading exceptions.\n this.Invoke(new UpdateProgressBarHandler(UpdateProgressBar), new object[] { progressPercentage });\n }\n else\n {\n UpdateProgressBar(progressPercentage);\n }\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12172/" ]
206,885
<p>Let's say I've got some Perl code that increments a column in a specific row of a database each time it's hit, and I'm expecting it to be hit pretty frequently, so I'd like to optimize it with FCGI. Right now, I basically wrapped most of the code in something like this:</p> <pre><code>while (FCGI::accept() &gt;= 0) { [code which currently creates a db connection and makes calls through it] } </code></pre> <p>I'm wondering if it's better to put the database connection (my $dbh = DBI->connect(etc)) outside of the FCGI loop so that the script keeps the connection alive, or will I still gain the advantages of FCGI in speed &amp; resources by leaving it in the loop?</p>
[ { "answer_id": 207160, "author": "mpeters", "author_id": 12094, "author_profile": "https://Stackoverflow.com/users/12094", "pm_score": 2, "selected": false, "text": "ping() Apache::DBI" }, { "answer_id": 214773, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 2, "selected": false, "text": "DBI->connect_cached()" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,899
<p>What is the best way to truncate a URL when displaying it within a web page? I don't mean a link but literally displaying the URL as a value to the user, assuming that the text might be in a container of fixed width and you don't want to wrap or run outside of the container?</p> <p>Is it better to truncate from the end, favouring the early part of the url:</p> <p>eg. http/really.long/urlthaticantf...ere.html</p> <p>Or place the '...' in the middle to favour the start and end of the link as the most value in terms of giving context:</p> <p>eg. http/really.long/ur...aticantfithere.html</p> <p>Also, what is a good rule of thumb when choosing how long to make the truncated URL? Should you be pessimistic and pick a likely wide-character such as capital 'M' and see how many of these fit in the layout? This tends to give really short URLs in general as most characters are much narrower than 'M'.</p> <p>Or should you be optimistic and use a truncation that generally gives a good length but risk overrunning when the URL contains many large characters?</p>
[ { "answer_id": 207708, "author": "PHLAK", "author_id": 27025, "author_profile": "https://Stackoverflow.com/users/27025", "pm_score": 2, "selected": false, "text": "http://www.domainname.com/folder/.../file.php\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5303/" ]
206,916
<p>I'm writing some code in python and I'm having trouble when trying to retrieve content of an Entry widget. The thing is: I want to limit the characters that can be typed, so I'm trying to clear the Entry widget when I reach the specific number of characters (2 in this case), but it looks like I always miss the last typed character. I added the lost character in a print to show.</p> <p>Here's the sample code:</p> <pre><code>from Tkinter import * class sampleFrame: def __init__(self, master): self.__frame = Frame(master) self.__frame.pack() def get_frame(self): return self.__frame class sampleClass: def __init__(self, master): self.__aLabel = Label(master,text="aLabel", width=10) self.__aLabel.pack(side=LEFT) self.__aEntry = Entry (master, width=2) self.__aEntry.bind('&lt;Key&gt;', lambda event: self.callback(event, self.__aEntry)) self.__aEntry.pack(side=LEFT) def callback(self, event, widgetName): self.__value = widgetName.get()+event.char print self.__value if len(self.__value)&gt;2: widgetName.delete(2,4) root = Tk() aSampleFrame = sampleFrame(root) aSampleClass = sampleClass(aSampleFrame.get_frame()) root.mainloop() </code></pre> <p>Any help will be much appreciated!</p> <p>Thanks in advance</p>
[ { "answer_id": 207018, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": true, "text": "if len(self.__value) > 2:\n widgetName.delete(2,4)\n return \"break\" # add this line\n self.__aEntry.bind('<Key>', self.callback) # ※ here!\n self.__aEntry.pack(side=LEFT)\n\ndef callback(self, event):\n self.__value = event.widget.get()+event.char # ※ here!\n print self.__value\n if len(self.__value)>2:\n event.widget.delete(2,4) # ※ here!\n return \"break\"\n" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,924
<p>I would like to program Java servlets using Eclipse and I plan on deploying them using Tomcat. I think I can build the projects using Ant which is bundled with Eclipse. I have the standard Eclipse IDE. What options do I have for doing Servlet development in Eclipse? What changes do I need to make to Eclipse? Do I need to install a plug-in?</p>
[ { "answer_id": 206940, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 7, "selected": false, "text": "doGet()" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,950
<p>I am having trouble in exporting to excel and it crashes out at the .set_Value function.</p> <p>It seems to work if I change object[,] to string[,] but by doing this I lose the formatting.</p> <p>Anyone Help?</p>
[ { "answer_id": 206960, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "null System.Reflection.Missing.Value" }, { "answer_id": 210351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Missing.Value = if substring(0,1) == \"=\" ' =" } ]
2008/10/15
[ "https://Stackoverflow.com/questions/206950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
206,953
<p>I've got a collection (List&lt;Rectangle&gt;) which I need to sort left-right. That part's easy. Then I want to iterate through the Rectangles in their <em>original</em> order, but easily find their index in the sorted collection. indexOf() won't work, since I may have a number of equal objects. I can't help feeling there should be an easy way to do this.</p>
[ { "answer_id": 207015, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 3, "selected": true, "text": "List<Rectangle> originalRects = ...;\n\n/* record index of each rectangle object.\n * Using a hash map makes lookups efficient,\n * and using an IdentityHashMap means we lookup by object identity\n * not value.\n */\nIdentityHashMap<Rectangle, Integer> originalIndices = new IdentityHashMap<Rectangle, Integer>();\nfor(int i=0; i<originalRects.size(); i++) {\n originalIndices.put(originalRects.get(i), i);\n}\n\n/* copy rectangle list */\nList<Rectangle> sortedRects = new ArrayList<Rectangle>();\nsortedRects.addAll(originalRects);\n\n/* and sort */\nCollections.sort(sortedRects, new LeftToRightComparator());\n\n/* Loop through original list */\nfor(int i=0; i<sortedRects.size(); i++) {\n Rectangle rect = sortedRects.get(i);\n /* Lookup original index efficiently */\n int origIndex = originalIndices.get(rect);\n\n /* I know the original, and sorted indices plus the rectangle itself */\n...\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26334/" ]
206,968
<p>Scenario: I have a function that I need to tweak in some way (example; make it work slightly different in different places). For some reason I end up having to add something ugly to the code, either in the function or at existing call sites. Assume that the sum total "ugly" is the same in both cases.</p> <p>The question is which choice should I pick and why? </p> <p>Should I encapsulate it so I don't need to look at it or should I extract it so that it doesn't add semantic trash to the function?</p> <p>What would effect your choice? What about if:</p> <ul> <li>The function will "never" be called except from the current locations.</li> <li>New calls to the function won't need the "ugliness".</li> <li>The function is really clean and generic right now</li> <li>The function is already a hack job.</li> <li>you wrote the function</li> <li>you didn't wright the function</li> <li>etc.</li> </ul>
[ { "answer_id": 207231, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 0, "selected": false, "text": "//old call\ncall_some_function_with_ugly(params, case)\n\n// new call\ncall_some_function(params)\n\nvoid call_some_function(params){ }\n\nvoid call_some_function_with_ugly(params, case){\n // do ugly depending on case\n switch(case) { ... }\n\n call_some_function(params);\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
206,970
<p>I have a web-based application that notifies users of activity on the site via email. Users can choose which kinds of notifcations they want to receive. So far there are about 10 different options (each one is a true/false).</p> <p>I'm currently storing this in one varchar field as a 0 or 1 separated by commas. For example: 1,0,0,0,1,1,1,1,0,0</p> <p>This works but it's difficult to add new notification flags and keep track of which flag belongs to which notification. Is there an accepted standard for doing this? I was thinking of adding another table with a column for each notification type. Then I can add new columns if I need, but I'm not sure how efficient this is.</p> <p>Thanks in advance!</p>
[ { "answer_id": 206990, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": "create table notifications (\n user_id int,\n notification_type int\n);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18234/" ]
206,983
<p>How do I put a gridview row in edit mode programmatically?</p>
[ { "answer_id": 206999, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 2, "selected": false, "text": "protected void Row_Editing(object sender, GridViewEditArgs e) \n{\n myGridView.EditItemIndex = e.EditItemIndex; \n BindData(); \n}\n" }, { "answer_id": 4817809, "author": "Asrij Siraj", "author_id": 592364, "author_profile": "https://Stackoverflow.com/users/592364", "pm_score": 1, "selected": false, "text": "protected void btnEdit_Click(object sender, EventArgs e)\n{\n GridView1.EditIndex = 1;\n}\n" }, { "answer_id": 5413499, "author": "user356978", "author_id": 356978, "author_profile": "https://Stackoverflow.com/users/356978", "pm_score": 2, "selected": false, "text": "protected void gridview_RowEditing(object sender, GridViewEditEventArgs e)\n{\n GridView gv = (GridView)sender;\n // Change the row state\n gv.Rows[e.NewEditIndex].RowState = DataControlRowState.Edit; \n}\n" }, { "answer_id": 11313655, "author": "Weston", "author_id": 768145, "author_profile": "https://Stackoverflow.com/users/768145", "pm_score": 2, "selected": false, "text": "Sub gridView1_rowCanceling(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)\n gridView1.EditIndex = -1\n BindData() // <-- Whatever procedure you use to bind your data to the gridView\nEnd Sub\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5232/" ]
206,988
<p>How do I remove the key 'bar' from an array foo so that 'bar' won't show up in</p> <pre><code>for(key in foo){alert(key);} </code></pre>
[ { "answer_id": 206994, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "delete foo[key];\n" }, { "answer_id": 1345122, "author": "going", "author_id": 139196, "author_profile": "https://Stackoverflow.com/users/139196", "pm_score": 9, "selected": true, "text": "myArray.splice(key, 1);\n for (var key in myArray) {\n if (key == 'bar') {\n myArray.splice(key, 1);\n }\n}\n for (var key in myArray) {\n if (myArray[key] == 'bar') {\n myArray.splice(key, 1);\n }\n}\n" }, { "answer_id": 6938020, "author": "ling", "author_id": 878118, "author_profile": "https://Stackoverflow.com/users/878118", "pm_score": 1, "selected": false, "text": "removeKey(arrayName,key);\n\nfunction removeKey(arrayName,key)\n{\n var x;\n var tmpArray = new Array();\n for(x in arrayName)\n {\n if(x!=key) { tmpArray[x] = arrayName[x]; }\n }\n return tmpArray;\n}\n" }, { "answer_id": 21020282, "author": "user3177525", "author_id": 3177525, "author_profile": "https://Stackoverflow.com/users/3177525", "pm_score": 5, "selected": false, "text": "delete array['key_name']\n" }, { "answer_id": 46702773, "author": "stackoverflows", "author_id": 3796011, "author_profile": "https://Stackoverflow.com/users/3796011", "pm_score": 3, "selected": false, "text": " myArray.splice( myArray.indexOf('bar') , 1) \n" }, { "answer_id": 71779762, "author": "MD SHAYON", "author_id": 8725395, "author_profile": "https://Stackoverflow.com/users/8725395", "pm_score": 0, "selected": false, "text": "var ar = [1, 2, 3, 4, 5, 6];\nar.pop(); // returns 6\nconsole.log( ar ); // [1, 2, 3, 4, 5]\n var ar = ['zero', 'one', 'two', 'three'];\nar.shift(); // returns \"zero\"\nconsole.log( ar ); // [\"one\", \"two\", \"three\"]\n var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];\nvar removed = arr.splice(2,2);\n\nvar list = [\"bar\", \"baz\", \"foo\", \"qux\"];\n \nlist.splice(0, 2); \n// Starting at index position 0, remove two elements [\"bar\", \"baz\"] and retains [\"foo\", \"qux\"].\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ]
206,997
<p>I have this bit of script to widen a text box on mouseover and shorten it on mouseoff.</p> <p>The problem I am having is that Internet Explorer doesn't seem to extend it's hover over the options of a select box.</p> <p>This means in IE I can click the select, have the options drop down, but if I try to select one, they vanish and the select box re-sizes as soon as I move off the select box itself.</p> <p>Example Code:</p> <pre><code>&lt;script type='text/javascript'&gt; $(function() { $('#TheSelect').hover( function(e){ $('#TheText').val('OVER'); $(this).width( 600 ); }, function(e){ $('#TheText').val('OUT'); $(this).width( 50 ); } ); }); &lt;/script&gt; </code></pre> <p>And:</p> <pre><code>&lt;input type='text' id='TheText' /&gt;&lt;br /&gt;&lt;br /&gt; &lt;select id='TheSelect' style='width:50px;'&gt; &lt;option value='1'&gt;One&lt;/option&gt; &lt;option value='2'&gt;Two&lt;/option&gt; &lt;option value='3'&gt;Three&lt;/option&gt; &lt;option value='42,693,748,756'&gt;Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... &lt;/option&gt; &lt;option value='5'&gt;Five&lt;/option&gt; &lt;option value='6'&gt;Six&lt;/option&gt; &lt;option value='7'&gt;Seven...&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Are there any workarounds for select boxes in IE? I would even consider a jquery replacement if anyone can recommend one that is really reliable.</p> <p>Thanks!</p>
[ { "answer_id": 207168, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 4, "selected": true, "text": "$(function() {\n var expand = function(){ $(this).width(600) }\n var contract = function(){ if (!this.noHide) $(this).width(50) }\n var focus = function(){ this.noHide = true }\n var blur = function(){ this.noHide = false; contract.call(this) }\n $('#TheSelect')\n .hover(expand, contract)\n .focus(focus)\n .click(focus)\n .blur(blur)\n .change(blur)\n});\n" }, { "answer_id": 811994, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "$(document).ready(function(){\n $(\".dropdownClassName select\").mouseleave(function(event){\n event.stopPropagation();\n });\n});\n" }, { "answer_id": 1835178, "author": "Scott G", "author_id": 223169, "author_profile": "https://Stackoverflow.com/users/223169", "pm_score": 1, "selected": false, "text": "$(\".containerClass\").hover(function() {\n $(this).children(\"img\").hide();\n $('#idOfSelectElement').mouseleave(function(event) { event.stopPropagation(); });\n}, function() {\n $(this).children('img').show();\n $('#idOfSelectElement').mouseleave(function(event) { event.stopPropagation(); });\n\n});\n" }, { "answer_id": 14206374, "author": "Sam", "author_id": 37575, "author_profile": "https://Stackoverflow.com/users/37575", "pm_score": 1, "selected": false, "text": "element.find('select').bind('mouseenter mouseleave',function(){\n //Prevent hover bubbling\n return false;\n});\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
206,998
<p>After some find and replace refactoring I ended up with this gem:</p> <pre><code>const class A { }; </code></pre> <p>What does "const class" mean? It seems to compile ok.</p>
[ { "answer_id": 207003, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": false, "text": "const class A\n{\n} a;\n" }, { "answer_id": 207007, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 6, "selected": false, "text": "const } ; const \nconst class A\n{\npublic:\n int x, y;\n} anInstance = {3, 4};\n\n// The above is equivalent to:\nconst A anInstance = {3, 4};\n" }, { "answer_id": 1616961, "author": "Matt Joiner", "author_id": 149482, "author_profile": "https://Stackoverflow.com/users/149482", "pm_score": 3, "selected": false, "text": "const // It is a const object...\nclass nullptr_t \n{\n public:\n template<class T>\n operator T*() const // convertible to any type of null non-member pointer...\n { return 0; }\n\n template<class C, class T>\n operator T C::*() const // or any type of null member pointer...\n { return 0; }\n\n private:\n void operator&() const; // Can't take address of nullptr\n\n} nullptr = {};\n nullptr" }, { "answer_id": 50000062, "author": "dr__noob", "author_id": 5242007, "author_profile": "https://Stackoverflow.com/users/5242007", "pm_score": 1, "selected": false, "text": "error: qualifiers can only be specified for objects and functions. const class A {}; const A a ;" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
207,000
<p>Is there any meaningful distinction between:</p> <pre><code>class A(object): foo = 5 # some default value </code></pre> <p>vs.</p> <pre><code>class B(object): def __init__(self, foo=5): self.foo = foo </code></pre> <p>If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?</p>
[ { "answer_id": 207128, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 8, "selected": true, "text": ">>> class A: foo = []\n>>> a, b = A(), A()\n>>> a.foo.append(5)\n>>> b.foo\n[5]\n>>> class A:\n... def __init__(self): self.foo = []\n>>> a, b = A(), A()\n>>> a.foo.append(5)\n>>> b.foo \n[]\n" }, { "answer_id": 26642476, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 5, "selected": false, "text": "id is >>> class A: foo = object()\n>>> a, b = A(), A()\n>>> a.foo is b.foo\nTrue\n>>> class A:\n... def __init__(self): self.foo = object()\n>>> a, b = A(), A()\n>>> a.foo is b.foo\nFalse\n object() 5 5 5 object() a.foo.append(5) b.foo a.foo = 5 a.foo = 5 b.foo a.foo = 5 a.foo 5 b.foo a.foo shared_ptr<T> T" }, { "answer_id": 34126204, "author": "zangw", "author_id": 3011380, "author_profile": "https://Stackoverflow.com/users/3011380", "pm_score": 5, "selected": false, "text": "class Bar(object):\n ## No need for dot syntax\n class_var = 1\n\n def __init__(self, i_var):\n self.i_var = i_var\n\n## Need dot syntax as we've left scope of class namespace\nBar.class_var\n## 1\nfoo = MyClass(2)\n\n## Finds i_var in foo's instance namespace\nfoo.i_var\n## 2\n\n## Doesn't find class_var in instance namespace…\n## So look's in class namespace (Bar.__dict__)\nfoo.class_var\n## 1\n foo = Bar(2)\nfoo.class_var\n## 1\nBar.class_var = 2\nfoo.class_var\n## 2\n foo = Bar(2)\nfoo.class_var\n## 1\nfoo.class_var = 2\nfoo.class_var\n## 2\nBar.class_var\n## 1\n class Circle(object):\n pi = 3.14159\n\n def __init__(self, radius):\n self.radius = radius \n def area(self):\n return Circle.pi * self.radius * self.radius\n\nCircle.pi\n## 3.14159\nc = Circle(10)\nc.pi\n## 3.14159\nc.area()\n## 314.159\n class MyClass(object):\n limit = 10\n\n def __init__(self):\n self.data = []\n def item(self, i):\n return self.data[i]\n\n def add(self, e):\n if len(self.data) >= self.limit:\n raise Exception(\"Too many elements\")\n self.data.append(e)\n\n MyClass.limit\n ## 10\n" }, { "answer_id": 44694103, "author": "SimonShyu", "author_id": 4015691, "author_profile": "https://Stackoverflow.com/users/4015691", "pm_score": 0, "selected": false, "text": "# -*- encoding: utf-8 -*-\n\n\nclass RevealAccess(object):\n def __init__(self, initval=None, name='var'):\n self.val = initval\n self.name = name\n\n def __get__(self, obj, objtype):\n return self.val\n\n\nclass Base(object):\n attr_1 = RevealAccess(10, 'var \"x\"')\n\n def __init__(self):\n self.attr_2 = RevealAccess(10, 'var \"x\"')\n\n\ndef main():\n b = Base()\n print(\"Access to class attribute, return: \", Base.attr_1)\n print(\"Access to instance attribute, return: \", b.attr_2)\n\nif __name__ == '__main__':\n main()\n ('Access to class attribute, return: ', 10)\n('Access to instance attribute, return: ', <__main__.RevealAccess object at 0x10184eb50>)\n __get__ __set__ __get__" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22897/" ]
207,002
<p>Is there a way of using an 'OR' operator or equivalent in a PHP switch?</p> <p>For example, something like this:</p> <pre><code>switch ($value) { case 1 || 2: echo 'the value is either 1 or 2'; break; } </code></pre>
[ { "answer_id": 207006, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "switch ($value)\n{\n case 1:\n case 2:\n echo \"the value is either 1 or 2.\";\n break;\n}\n" }, { "answer_id": 207012, "author": "Craig", "author_id": 27294, "author_profile": "https://Stackoverflow.com/users/27294", "pm_score": 4, "selected": false, "text": "switch($value) {\n case 1:\n case 2:\n echo \"the value is either 1 or 2\";\n break;\n}\n" }, { "answer_id": 207176, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 6, "selected": false, "text": "if switch switch (true) {\n case ($value > 3) :\n // value is greater than 3\n break;\n case ($value >= 4 && $value <= 6) :\n // value is between 4 and 6\n break;\n}\n if" }, { "answer_id": 6313466, "author": "ahmed", "author_id": 793566, "author_profile": "https://Stackoverflow.com/users/793566", "pm_score": -1, "selected": false, "text": "<?php \n$go = $_REQUEST['go'];\n?>\n<?php if ($go == 'general_information'){?>\n<div>\necho \"hello\";\n}?>\n" }, { "answer_id": 13634224, "author": "Baba", "author_id": 1226894, "author_profile": "https://Stackoverflow.com/users/1226894", "pm_score": 7, "selected": false, "text": "|| switch $v = 1;\nswitch (true) {\n case ($v == 1 || $v == 2):\n echo 'the value is either 1 or 2';\n break;\n}\n switch($v) {\n case 1:\n case 2:\n echo \"the value is either 1 or 2\";\n break;\n}\n 1 100 $r1 = range(1, 100);\n$r2 = range(100, 200);\n$v = 76;\nswitch (true) {\n case in_array($v, $r1) :\n echo 'the value is in range 1 to 100';\n break;\n case in_array($v, $r2) :\n echo 'the value is in range 100 to 200';\n break;\n}\n" }, { "answer_id": 13681131, "author": "RaJeSh", "author_id": 1765172, "author_profile": "https://Stackoverflow.com/users/1765172", "pm_score": 1, "selected": false, "text": "switch($a) {\n case 1:\n case 2:\n .......\n .......\n .......\n break;\n}\n" }, { "answer_id": 13717760, "author": "Tapas Pal", "author_id": 1810390, "author_profile": "https://Stackoverflow.com/users/1810390", "pm_score": 0, "selected": false, "text": "switch ($value) \n{\n case 1:\n case 2:\n echo 'the value is either 1 or 2';\n break;\n}\n" }, { "answer_id": 13725859, "author": "Abhishek Jaiswal", "author_id": 1287741, "author_profile": "https://Stackoverflow.com/users/1287741", "pm_score": 3, "selected": false, "text": "switch ($your_variable)\n{\n case 1:\n case 2:\n echo \"the value is either 1 or 2.\";\n break;\n}\n" }, { "answer_id": 13738007, "author": "John Peter", "author_id": 713009, "author_profile": "https://Stackoverflow.com/users/713009", "pm_score": 5, "selected": false, "text": "switch($bar)\n{\n case 4:\n echo \"This is not the number you're looking for.\\n\";\n $foo = 92;\n}\n case 4:\n echo \"This is not the number you're looking for.\\n\";\n $foo = 92;\n break;\n\ncase 5:\n echo \"A copy of Ringworld is on its way to you!\\n\";\n $foo = 34;\n break;\n case 3:\ncase 4:\n echo \"This is not the number you're looking for.\\n\";\n $foo = 92;\n break;\n\ncase 5:\n echo \"A copy of Ringworld is on its way to you!\\n\";\n $foo = 34;\n break;\n switch(true)\n{\n case (strlen($foo) > 30):\n $error = \"The value provided is too long.\";\n $valid = false;\n break;\n\n case (!preg_match('/^[A-Z0-9]+$/i', $foo)):\n $error = \"The value must be alphanumeric.\";\n $valid = false;\n break;\n\n default:\n $valid = true;\n break;\n}\n" }, { "answer_id": 49624719, "author": "Md Nazrul Islam", "author_id": 7362068, "author_profile": "https://Stackoverflow.com/users/7362068", "pm_score": -1, "selected": false, "text": "$today = date(\"D\");\n\n switch($today){\n\n case \"Mon\":\n\n case \"Tue\":\n\n echo \"Today is Tuesday or Monday. Buy some food.\";\n\n break;\n\n case \"Wed\":\n\n echo \"Today is Wednesday. Visit a doctor.\";\n\n break;\n\n case \"Thu\":\n\n echo \"Today is Thursday. Repair your car.\";\n\n break;\n\n default:\n\n echo \"No information available for that day.\";\n\n break;\n\n }\n" }, { "answer_id": 65026643, "author": "t_dom93", "author_id": 6774916, "author_profile": "https://Stackoverflow.com/users/6774916", "pm_score": 3, "selected": false, "text": "match switch break UnhandledMatchError match ($value) {\n 0 => '0',\n 1, 2 => \"1 or 2\",\n default => \"3\",\n}\n" }, { "answer_id": 65148225, "author": "COil", "author_id": 633864, "author_profile": "https://Stackoverflow.com/users/633864", "pm_score": 1, "selected": false, "text": "$otherVar = (static function($value) {\n switch ($value) {\n case 0:\n return 4;\n case 1:\n return 6;\n case 2:\n case 3:\n return 5;\n default:\n return null;\n }\n})($i);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,022
<p>My problem is that I can't seem to get the image from my bundle to display properly. This method is in the view controller that controls the tableview. <em>headerView</em> is loaded with the tableview in the .nib file and contains a few UILabels (not shown) that load just fine. Any ideas?</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; [[self view] setTableHeaderView:headerView]; NSBundle *bundle = [NSBundle mainBundle]; NSString *imagePath = [bundle pathForResource:@"awesome_lolcat" ofType:@"jpeg"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; imageView = [[UIImageView alloc] initWithImage:image]; } </code></pre>
[ { "answer_id": 207227, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "\n //this assumes that headerView is an already created UIView, perhaps an IBOutlet\n\n UIImage *image = [UIImage imageNamed: @\"awesome_lolcat.jpeg\"];\n UIImageView *imageView = [[UIImageView alloc] initWithImage: image];\n [headerView addSubview: [imageView autorelease]];\n [[self view] setTableHeaderView: headerView];\n\n" }, { "answer_id": 208561, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 3, "selected": true, "text": "\n //this assumes that headerView is an already created UIView, perhaps an IBOutlet\n //also, imageViewOutlet is an IB outlet hooked up to a UIImageView, and added as\n //a subview of headerView.\n\n //you can also set the image directly from within IB\n imageViewOutlet.image = [UIImage imageNamed: @\"awesome_lolcat.jpeg\"];\n [[self view] setTableHeaderView: headerView];\n\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28422/" ]
207,025
<p>I want to enforce CHECK constraint on a date range such that all dates in column BIRTH_DATE are less than tomorrow and greater than or equal to 100 years ago. I tried this expression in a CHECK constraint:</p> <pre><code>BIRTH_DATE &gt;= (sysdate - numtoyminterval(100, 'YEAR')) AND BIRTH_DATE &lt; sysdate + 1 </code></pre> <p>But I received the error "ORA-02436: date or system variable wrongly specified in CHECK constraint"</p> <p>Is there a way to accomplish this using a CHECK constraint instead of a trigger?</p>
[ { "answer_id": 207087, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 3, "selected": true, "text": "* Subqueries and scalar subquery expressions\n* Calls to the functions that are not deterministic (CURRENT_DATE,\n" }, { "answer_id": 208114, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "BIRTH_DATE >= (CREATED_DATE - numtoyminterval(100, 'YEAR')) \nAND BIRTH_DATE < CREATED_DATE + 1\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3401/" ]
207,038
<p>What is the best way to approach removing items from a collection in C#, once the item is known, but not it's index. This is one way to do it, but it seems inelegant at best.</p> <pre><code>//Remove the existing role assignment for the user. int cnt = 0; int assToDelete = 0; foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments) { if (spAssignment.Member.Name == shortName) { assToDelete = cnt; } cnt++; } workspace.RoleAssignments.Remove(assToDelete); </code></pre> <p>What I would really like to do is find the item to remove by property (in this case, name) without looping through the entire collection and using 2 additional variables.</p>
[ { "answer_id": 207048, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 6, "selected": true, "text": "Dictionary<T> KeyedCollection<T> foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)\n{\n if (spAssignment.Member.Name == shortName)\n {\n workspace.RoleAssignments.Remove(spAssignment);\n break;\n }\n}\n" }, { "answer_id": 207084, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 7, "selected": false, "text": "List<T> workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);\n" }, { "answer_id": 207088, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 3, "selected": false, "text": "int cnt = workspace.RoleAssignments\n .RemoveAll(spa => spa.Member.Name == shortName)\n var toRemove = workspace.RoleAssignments\n .FirstOrDefault(spa => spa.Member.Name == shortName)\n if (toRemove != null) workspace.RoleAssignments.Remove(toRemove);\n" }, { "answer_id": 207100, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": " workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);\n List<int> list2 = new List<int>() ; \nforeach (int i in GetList())\n{\n if (!(i % 2 == 0))\n {\n list2.Add(i);\n }\n}\nlist2 = list2;\n" }, { "answer_id": 207457, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 5, "selected": false, "text": "\"Bob\" 999\n\"Mary\" 999\n\"Ted\" 1000\n for( int idx = 0; idx < list.Count ; idx++ )\n{\n if( list[idx].Rating < 1000 )\n {\n list.RemoveAt(idx); // whoops!\n }\n}\n Bob Ted Mary Mary for (int idx = list.Count-1; idx >= 0; idx--)\n{\n if (list[idx].Rating < 1000)\n {\n list.RemoveAt(idx);\n }\n}\n list.RemoveAll(o => o.Rating < 1000);\n int removeIndex = list.FindIndex(o => o.Name == \"Ted\");\nif( removeIndex != -1 )\n{\n list.RemoveAt(removeIndex);\n}\n" }, { "answer_id": 208741, "author": "Dan", "author_id": 18449, "author_profile": "https://Stackoverflow.com/users/18449", "pm_score": 0, "selected": false, "text": "foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)\n{\n if (spAssignment.Member.Name != shortName) continue;\n workspace.RoleAssignments.Remove((SPPrincipal)spAssignment.Member);\n break;\n}\n" }, { "answer_id": 1416579, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " System.Collections.ArrayList arr = new System.Collections.ArrayList();\n arr.Add(\"1\");\n arr.Add(\"2\");\n arr.Add(\"3\");\n\n /*This throws an exception\n foreach (string s in arr)\n {\n arr.Remove(s);\n }\n */\n\n //where as this works correctly\n Console.WriteLine(arr.Count);\n foreach (string s in new System.Collections.ArrayList(arr)) \n {\n arr.Remove(s);\n }\n Console.WriteLine(arr.Count);\n Console.ReadKey();\n" }, { "answer_id": 2283964, "author": "Jalal El-Shaer", "author_id": 95380, "author_profile": "https://Stackoverflow.com/users/95380", "pm_score": 2, "selected": false, "text": "public static IEnumerable<T> Remove<T>(this IEnumerable<T> items, Func<T, bool> match)\n {\n var list = items.ToList();\n for (int idx = 0; idx < list.Count(); idx++)\n {\n if (match(list[idx]))\n {\n list.RemoveAt(idx);\n idx--; // the list is 1 item shorter\n }\n }\n return list.AsEnumerable();\n }\n var result = string[]{\"mike\", \"john\", \"ali\"}\nresult = result.Remove(x => x.Username == \"mike\").ToArray();\nAssert.IsTrue(result.Length == 2);\n" }, { "answer_id": 10488103, "author": "Anthony Shaw", "author_id": 117350, "author_profile": "https://Stackoverflow.com/users/117350", "pm_score": 0, "selected": false, "text": "foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments.ToList())\n{\n if (spAssignment.Member.Name == shortName)\n {\n workspace.RoleAssignments.Remove(spAssignment);\n }\n}\n" }, { "answer_id": 16058577, "author": "Colin", "author_id": 150342, "author_profile": "https://Stackoverflow.com/users/150342", "pm_score": 4, "selected": false, "text": "ICollection RemoveAll public static void RemoveAll<T>(this ICollection<T> source, \n Func<T, bool> predicate)\n {\n if (source == null)\n throw new ArgumentNullException(\"source\", \"source is null.\");\n\n if (predicate == null)\n throw new ArgumentNullException(\"predicate\", \"predicate is null.\");\n\n source.Where(predicate).ToList().ForEach(e => source.Remove(e));\n }\n" }, { "answer_id": 25671555, "author": "Sai", "author_id": 2466650, "author_profile": "https://Stackoverflow.com/users/2466650", "pm_score": 0, "selected": false, "text": "Dictionary<string, bool> sourceDict = new Dictionary<string, bool>();\nsourceDict.Add(\"Sai\", true);\nsourceDict.Add(\"Sri\", false);\nsourceDict.Add(\"SaiSri\", true);\nsourceDict.Add(\"SaiSriMahi\", true);\n\nvar itemsToDelete = sourceDict.Where(DictItem => DictItem.Value == false);\n\nforeach (var item in itemsToDelete)\n{\n sourceDict.Remove(item.Key);\n}\n var itemsToDelete = sourceDict.Where(DictItem => DictItem.Value == false).ToList();\n" }, { "answer_id": 34989767, "author": "Stas BZ", "author_id": 3540044, "author_profile": "https://Stackoverflow.com/users/3540044", "pm_score": 0, "selected": false, "text": "var itemsToDelete = Items.Where(x => !!!your condition!!!).ToArray();\nfor (int i = 0; i < itemsToDelete.Length; ++i)\n Items.Remove(itemsToDelete[i]);\n GetHashCode()" }, { "answer_id": 49980458, "author": "john.kernel", "author_id": 8082886, "author_profile": "https://Stackoverflow.com/users/8082886", "pm_score": 0, "selected": false, "text": " public class Product\n {\n public string Name { get; set; }\n public string Price { get; set; } \n }\n var subCollection = collection1.RemoveAll(w => collection2.Any(q => q.Name == w.Name));\n collection1 Name Name collection2 using System.Linq;" }, { "answer_id": 63097230, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 0, "selected": false, "text": "List<T> List<T>.RemoveAll IList<T> ICollection<T> public static void RemoveAll<T>(this IList<T> ilist, Predicate<T> predicate) // O(N^2)\n {\n for (var index = ilist.Count - 1; index >= 0; index--)\n {\n var item = ilist[index];\n if (predicate(item))\n {\n ilist.RemoveAt(index);\n }\n }\n }\n public static void RemoveAll<T>(this ICollection<T> icollection, Predicate<T> predicate) // O(N)\n {\n var nonMatchingItems = new List<T>();\n\n // Move all the items that do not match to another collection.\n foreach (var item in icollection) \n {\n if (!predicate(item))\n {\n nonMatchingItems.Add(item);\n }\n }\n\n // Clear the collection and then copy back the non-matched items.\n icollection.Clear();\n foreach (var item in nonMatchingItems)\n {\n icollection.Add(item);\n }\n }\n public static void RemoveAll<T>(this ICollection<T> icollection, Func<T, bool> predicate) // O(N^2)\n {\n foreach (var item in icollection.Where(predicate).ToList())\n {\n icollection.Remove(item);\n }\n }\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18449/" ]
207,045
<p>Can an ArrayList of Node contain a non-Node type? </p> <p>Is there a very dirty method of doing this with type casting?</p>
[ { "answer_id": 207052, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 4, "selected": true, "text": "import java.util.*;\nimport java.awt.Rectangle;\n\npublic class test {\n public static void main(String args[]) {\n List<Rectangle> list = new ArrayList<Rectangle>();\n /* Evil hack */\n List lst = (List)list;\n\n /* Works */\n lst.add(\"Test\");\n\n /* Works, and prints \"Test\" */\n for(Object o: lst) {\n System.err.println(o);\n }\n\n /* Dies horribly due to implicitly casting \"Test\" to a Rectangle */\n for(Rectangle r: list) {\n System.err.println(r);\n }\n }\n}\n" }, { "answer_id": 207072, "author": "Chris Dolan", "author_id": 14783, "author_profile": "https://Stackoverflow.com/users/14783", "pm_score": 1, "selected": false, "text": " List<Node> nodelist = new ArrayList<Node>();\n Object toAdd = new Object();\n ((List) nodelist).add(toAdd);\n ((List<Object>) nodelist).add(toAdd);\n List<Object> mixedList = new ArrayList<Object>(list);\n mixedList.add(toAdd);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27570/" ]
207,069
<p>I have a shared library that I wish to link an executable against using GCC. The shared library has a nonstandard name not of the form libNAME.so, so I can not use the usual -l option. (It happens to also be a Python extension, and so has no 'lib' prefix.)</p> <p>I am able to pass the path to the library file directly to the link command line, but this causes the library path to be hardcoded into the executable.</p> <p>For example:</p> <pre><code>g++ -o build/bin/myapp build/bin/_mylib.so </code></pre> <p>Is there a way to link to this library without causing the path to be hardcoded into the executable?</p>
[ { "answer_id": 207149, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "g++ -o build/bin/myapp _mylib.so other_source_files\n" }, { "answer_id": 207152, "author": "Chris Roland", "author_id": 27975, "author_profile": "https://Stackoverflow.com/users/27975", "pm_score": 1, "selected": false, "text": "ln -s build/bin/_mylib.so build/bin/lib_mylib.so -l_mylib http://en.wikipedia.org/wiki/Symbolic_link" }, { "answer_id": 281253, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 7, "selected": true, "text": "g++ -o build/bin/myapp -l:_mylib.so other_source_files\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13402/" ]
207,150
<p>I have a view using a master page that contains some javascript that needs to be executed using the OnLoad of the Body. What is the best way to set the OnLoad on my MasterPage only for certain views?</p> <p>On idea I tried was to pass the name of the javascript function as ViewData. But I dont really want my Controllers to have to know about the javascript on the page. I really don't like this approach...</p> <pre><code>&lt;body onload="&lt;%=ViewData["Body_OnLoad"]%&gt;"&gt; &lt;asp:ContentPlaceHolder ID="MainContent" runat="server" /&gt; </code></pre> <p>Edit - I suppose one idea would be to use jQuery's document ready event instead...</p> <p>Any other ideas?</p>
[ { "answer_id": 238589, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 3, "selected": false, "text": "<script language=\"javascript\" type=\"text/javascript\" src=\"../../Scripts/jquery-1.2.6-intellisense.js\"></script> \n $(document).ready(function() {\n // do stuff when DOM is ready\n});\n <asp:contentplaceholder id=\"JavascriptPlaceholder\" runat=\"server\"></asp:contentplaceholder> \n" }, { "answer_id": 253152, "author": "Robert Vuković", "author_id": 438025, "author_profile": "https://Stackoverflow.com/users/438025", "pm_score": 3, "selected": false, "text": "MasterPage.master\n\n<head>\n<asp:ContentPlaceHolder runat=\"server\" id=\"Headers\">\n</asp:ContentPlaceHolder>\n<script language=javascript>\n function mp_onload() {\n if(window.body_onload != null)\n window.body_onload();\n }\n</script>\n</head>\n<body onload=\"mp_onload();\">\n\nDefault.aspx\n\n<asp:Content ID=\"Content2\" ContentPlaceHolderID=\"Headers\" Runat=\"Server\">\n<script language=\"javascript\">\n function body_onload()\n {\n //do something\n }\n</script>\n</asp:Content>\n " } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10941/" ]
207,157
<p>I have this XML in a column in my table:</p> <pre><code>&lt;keywords&gt; &lt;keyword name="First Name" value="|FIRSTNAME|" display="Jack" /&gt; &lt;keyword name="Last Name" value="|LASTNAME|" display="Jones" /&gt; &lt;keyword name="City" value="|CITY|" display="Anytown" /&gt; &lt;keyword name="State" value="|STATE|" display="MD" /&gt; &lt;/keywords&gt; </code></pre> <p>I'm getting a record out of that table using LINQ to SQL via this:</p> <pre><code>GeneratedArticle ga = db.GeneratedArticles.Single(p =&gt; p.GeneratedArticleId == generatedArticleId); </code></pre> <p>That works, I get my GeneratedArticle object just fine.</p> <p>I'd like to walk through the data in the ArticleKeywords field, which is XML. I started doing this:</p> <pre><code>var keywords = from k in ga.ArticleKeywords.Elements("Keywords") select k; foreach (var keyword in keywords) { //what goes here? } </code></pre> <p>I'm not 100% sure that I'm getting that data correctly. I need help with the proper syntax to get the value and display out of my XML field.</p>
[ { "answer_id": 207196, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 0, "selected": false, "text": "var keywordData = from k in ga.ArticleKeywords.Elements(\"Keywords\")\n select new { Value = k.Attributes[\"value\"].Value,\n Display = k.Attributes[\"display\"].Value};\n" }, { "answer_id": 207203, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": true, "text": "// IEnumerable sequence with keywords data\nvar keywords = from kw in ga.ArticleKeywords.Elements(\"keyword\")\n select new {\n Name = (string)kw.Attribute(\"name\"),\n Value = (string)kw.Attribute(\"value\"),\n Display = (string)kw.Attribute(\"display\")\n };\n\n\nforeach (var keyword in keywords)\n{\n var kw = \"Name: \" + keyword.Name + \n \" Value: \" + keyword.Value + \n \" Display: \" + keyword.Display;\n Console.WriteLine(kw);\n}\n" }, { "answer_id": 219838, "author": "user22367", "author_id": 22367, "author_profile": "https://Stackoverflow.com/users/22367", "pm_score": 2, "selected": false, "text": "var keywords = from kw in ga.ArticleKeywords.Element(\"keywords\").Elements()\n var keywords = from kw in ga.ArticleKeywords.Element(\"keywords\").Elements(\"keyword\")\n var keywords = from kw in ga.ArticleKeywords.Descendants(\"keyword\")\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1989/" ]
207,190
<p>I want to convert a string like this:</p> <pre><code>'10/15/2008 10:06:32 PM' </code></pre> <p>into the equivalent DATETIME value in Sql Server.</p> <p>In Oracle, I would say this:</p> <pre><code>TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM') </code></pre> <p><a href="https://stackoverflow.com/questions/202243/custom-datetime-formatting-in-sql-server">This question</a> implies that I must parse the string into one of the <a href="http://www.sql-server-helper.com/tips/date-formats.aspx" rel="noreferrer">standard formats</a>, and then convert using one of those codes. That seems ludicrous for such a mundane operation. Is there an easier way?</p>
[ { "answer_id": 207232, "author": "Taptronic", "author_id": 14728, "author_profile": "https://Stackoverflow.com/users/14728", "pm_score": 6, "selected": false, "text": "Declare @d datetime\nselect @d = getdate()\n\nselect @d as OriginalDate,\nconvert(varchar,@d,100) as ConvertedDate,\n100 as FormatValue,\n'mon dd yyyy hh:miAM (or PM)' as OutputFormat\nunion all\nselect @d,convert(varchar,@d,101),101,'mm/dd/yy'\nunion all\nselect @d,convert(varchar,@d,102),102,'yy.mm.dd'\nunion all\nselect @d,convert(varchar,@d,103),103,'dd/mm/yy'\nunion all\nselect @d,convert(varchar,@d,104),104,'dd.mm.yy'\nunion all\nselect @d,convert(varchar,@d,105),105,'dd-mm-yy'\nunion all\nselect @d,convert(varchar,@d,106),106,'dd mon yy'\nunion all\nselect @d,convert(varchar,@d,107),107,'Mon dd, yy'\nunion all\nselect @d,convert(varchar,@d,108),108,'hh:mm:ss'\nunion all\nselect @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'\nunion all\nselect @d,convert(varchar,@d,110),110,'mm-dd-yy'\nunion all\nselect @d,convert(varchar,@d,111),111,'yy/mm/dd'\nunion all\nselect @d,convert(varchar,@d,12),12,'yymmdd'\nunion all\nselect @d,convert(varchar,@d,112),112,'yyyymmdd'\nunion all\nselect @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'\nunion all\nselect @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'\nunion all\nselect @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'\nunion all\nselect @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'\nunion all\nselect @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'\n" }, { "answer_id": 7162573, "author": "Scott Gollaglee", "author_id": 907906, "author_profile": "https://Stackoverflow.com/users/907906", "pm_score": 3, "selected": false, "text": "SELECT convert(date, '10/15/2011 00:00:00', 101) as [MM/dd/YYYY]\n" }, { "answer_id": 7175369, "author": "gauravg", "author_id": 909590, "author_profile": "https://Stackoverflow.com/users/909590", "pm_score": 9, "selected": true, "text": "Cast('7/7/2011' as datetime)\n Convert(DATETIME, '7/7/2011', 101)\n" }, { "answer_id": 7183924, "author": "Aaron Bertrand", "author_id": 61305, "author_profile": "https://Stackoverflow.com/users/61305", "pm_score": 6, "selected": false, "text": "DECLARE @d DATETIME = '2008-10-13 18:45:19';\n\n-- returns Oct-13/2008 18:45:19:\nSELECT FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss');\n\n-- returns NULL if the conversion fails:\nSELECT TRY_PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);\n\n-- returns an error if the conversion fails:\nSELECT PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);\n SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');\nSELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');\n 2008-10-15 22:06:32.000\n2008-10-15 22:06:32.000\n 6/9/2012" }, { "answer_id": 48497669, "author": "Simone", "author_id": 3603386, "author_profile": "https://Stackoverflow.com/users/3603386", "pm_score": 4, "selected": false, "text": "SELECT convert(datetime, '2018-10-25 20:44:11.500', 121) -- yyyy-mm-dd hh:mm:ss.mmm\n" }, { "answer_id": 58087634, "author": "Jar", "author_id": 8840359, "author_profile": "https://Stackoverflow.com/users/8840359", "pm_score": 3, "selected": false, "text": "SELECT DATEFROMPARTS(2013, 8, 19);\n select\nDATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'\nfrom MyTable\n" }, { "answer_id": 58956298, "author": "Yaroslav", "author_id": 12404511, "author_profile": "https://Stackoverflow.com/users/12404511", "pm_score": -1, "selected": false, "text": "dateadd(day,0,'10/15/2008 10:06:32 PM')\n" }, { "answer_id": 60265766, "author": "user12913610", "author_id": 12913610, "author_profile": "https://Stackoverflow.com/users/12913610", "pm_score": 0, "selected": false, "text": "create table tmp \n(\n ENTRYDATETIME datetime\n);\n\ninsert into tmp (ENTRYDATETIME) values (getdate());\ninsert into tmp (ENTRYDATETIME) values ('20190101'); --convert string 'yyyymmdd' to datetime\n\n\nselect * from tmp where ENTRYDATETIME > '20190925' --yyyymmdd \nselect * from tmp where ENTRYDATETIME > '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS\n\n\n\n" }, { "answer_id": 67071424, "author": "Abd Abughazaleh", "author_id": 8370334, "author_profile": "https://Stackoverflow.com/users/8370334", "pm_score": -1, "selected": false, "text": "convert(date,YOUR_DATE,104)\n timestamp convert(datetime,YOUR_DATE,104)\n" }, { "answer_id": 69457829, "author": "luiscla27", "author_id": 1657465, "author_profile": "https://Stackoverflow.com/users/1657465", "pm_score": 2, "selected": false, "text": "0-100 106 107 109 113 130 ISO 12 112 23 126 Convert(varchar(30), '210510', 12) -- yymmdd\nConvert(varchar(30), '20210510', 112) -- yyyymmdd\nConvert(varchar(30), '2021-05-10', 23) -- yyyy-mm-dd\nConvert(varchar(30), '2021-05-10T17:01:33.777', 126) -- yyyy-mm-ddThh:mi:ss.mmm (no spaces)\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
207,195
<p>Without using Javascript, is there a way to make a CSS property toggle on and off through nested elements.</p> <p>The problem I'm trying to solve is that I have a number of tags and classes which make some text italic (<code>&lt;em&gt;</code>, <code>&lt;blockquote&gt;</code>, <code>&lt;cite&gt;</code>, <code>&lt;q&gt;</code>, <code>&lt;dfn&gt;</code>, and some other classes), and when one of these is inside another one of these, the italicisation needs to toggle.</p> <pre> &lt;blockquote> And so the man said, &lt;q>That's not from &lt;cite>Catcher In The Rye&lt;/cite>, dear fellow!&lt;/q>, can you believe that?! &lt;/blockquote> </pre> <p>Should render as:</p> <blockquote> <p><em>And so the man said,</em> "That's not from <em>Catcher In The Rye</em>, dear fellow!"<em>, can you believe that?!</em></p> </blockquote> <p>The CSS I've got for this is getting a bit messy:</p> <pre><code>q, em, dfn, cite, blockquote { font-style: italic; } q q, q em, q dfn, q cite, em q, em em, em dfn, em cite, dfn q, dfn em, dfn dfn, dfn cite, cite q, cite em, cite dfn, cite cite, blockquote q, blockquote em, blockquote dfn, blockquote cite { font-style: normal; } </code></pre> <p>...and I'm pretty sure that won't even work past one level of nesting (as in my example).</p> <p>Is there a way I can do this without have to list every permutation of the tags?</p>
[ { "answer_id": 207447, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 3, "selected": true, "text": ":not" }, { "answer_id": 20359229, "author": "Thorsten Kück", "author_id": 2284809, "author_profile": "https://Stackoverflow.com/users/2284809", "pm_score": 0, "selected": false, "text": "em {\n font-style: toggle(italic, normal);\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
207,212
<p>I'm writing an application in Delphi which uses an SQLite3 database. I'd like to be able to start the application while holding some modifier keys, such as CTRL + SHIFT, to signal reinitialization of the database.</p> <p>How can I capture that the application was started while these keys were held?</p>
[ { "answer_id": 207369, "author": "Tim Knipe", "author_id": 10493, "author_profile": "https://Stackoverflow.com/users/10493", "pm_score": 3, "selected": false, "text": "if (GetKeyState(VK_SHIFT) < 0) and (GetKeyState(VK_CONTROL) < 0) then\n ReinitializeDatabase;\n" }, { "answer_id": 207456, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 4, "selected": true, "text": "procedure TForm56.Button1Click(Sender: TObject);\nbegin\n if fNeedReinit then\n ReinitializeDatabase;\nend;\n\nprocedure TForm56.FormCreate(Sender: TObject);\nbegin\n fNeedReinit := False;\nend;\n\nprocedure TForm56.FormShow(Sender: TObject);\nbegin\n fNeedReinit := (GetKeyState(VK_SHIFT) < 0) and (GetKeyState(VK_CONTROL) < 0);\nend;\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10519/" ]
207,223
<p>I've got a script that dynamically calls and displays images from a directory, what would be the best way to paginate this? I'd like to be able to control the number of images that are displayed per page through a variable within the script. I'm thinking of using URL varriables (ie - <a href="http://domain.com/page.php?page=1" rel="noreferrer">http://domain.com/page.php?page=1</a>) but am unsure how to go about this.</p> <p>Thanks for the help.</p>
[ { "answer_id": 207287, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "$itemsPerPage = 5;\n\n$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;\n$totalItems = getTotalItems();\n$totalPages = ceil($totalItems / $itemsPerPage);\n\nfunction getTotalItems() {\n// since they're images, perhaps we'll scan a directory of images to determine\n// how many images we have in total\n}\n\nfunction getItemsFromPage($page, $itemsPerPage) {\n// function to grab $itemsPerPage based on which $page we're on\n}\n\nfunction getPager($totalPages, $currentPage) {\n// build your pager\n}\n" }, { "answer_id": 207462, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 3, "selected": false, "text": "function paginate($page, $total, $per_page) {\n if(!is_numeric($page)) { $page = 1; }\n if(!is_numeric($per_page)) { $per_page = 10; }\n if($page > ceil($total / $per_page)) $page = 1;\n if($page == \"\" || $page == 0) { \n $page = 1;\n $start = 0;\n $end = $per_page;\n } else {\n $start = ($page * $per_page) - ($per_page);\n $end = $per_page;\n }\n\n $prev_page = \"\";\n $next_page = \"\";\n $all_pages = array();\n $selected = \"\";\n $enabled = false;\n\n if($total > $per_page) {\n $enabled = true;\n $prev = $page - 1;\n $prev_page = ($prev == 0) ? 0 : $prev;\n\n $next = $page + 1;\n $total_pages = ceil($total/$per_page);\n\n $next_page = ($next <= $total_pages) ? $next : 0;\n\n for($x=1;$x<=$total_pages;$x++) {\n $all_pages[] = $x;\n $selected = ($x == $page) ? $x : $selected; \n }\n }\n\n return array(\n \"per_page\" => $per_page,\n \"page\" => $page,\n \"prev_page\" => $prev_page,\n \"all_pages\" => $all_pages,\n \"next_page\" => $next_page,\n \"selected\" => $selected,\n \"start\" => $start,\n \"end\" => $end,\n \"enabled\" => $enabled\n );\n}\n\n// ex: we are in page 2, we have 50 items, and we're showing 10 per page\nprint_r(paginate(2, 50, 10));\n Array\n(\n [per_page] => 10\n [page] => 2\n [prev_page] => 1\n [all_pages] => Array\n (\n [0] => 1\n [1] => 2\n [2] => 3\n [3] => 4\n [4] => 5\n )\n [next_page] => 3\n [selected] => 2\n [start] => 10\n [end] => 10\n [enabled] => 1\n)\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
207,234
<p>How can I get a list of the IP addresses or host names from a local network easily in Python?</p> <p>It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.</p> <p><strong>Edit:</strong> By local I mean all <strong>active</strong> addresses within a local network, such as <code>192.168.xxx.xxx</code>.</p> <p>So, if the IP address of my computer (within the local network) is <code>192.168.1.1</code>, and I have three other connected computers, I would want it to return the IP addresses <code>192.168.1.2</code>, <code>192.168.1.3</code>, <code>192.168.1.4</code>, and possibly their hostnames.</p>
[ { "answer_id": 207775, "author": "Mapad", "author_id": 28165, "author_profile": "https://Stackoverflow.com/users/28165", "pm_score": 4, "selected": false, "text": "import socket\nIP1 = socket.gethostbyname(socket.gethostname()) # local IP adress of your computer\nIP2 = socket.gethostbyname('name_of_your_computer') # IP adress of remote computer\n" }, { "answer_id": 602965, "author": "Benedikt Waldvogel", "author_id": 4308, "author_profile": "https://Stackoverflow.com/users/4308", "pm_score": 5, "selected": false, "text": "arping()" }, { "answer_id": 12027431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "import socket\n\nprint ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1])\n" }, { "answer_id": 48607794, "author": "Santi Peñate-Vera", "author_id": 3020849, "author_profile": "https://Stackoverflow.com/users/3020849", "pm_score": 3, "selected": false, "text": "import os\nimport socket \nimport multiprocessing\nimport subprocess\n\n\ndef pinger(job_q, results_q):\n \"\"\"\n Do Ping\n :param job_q:\n :param results_q:\n :return:\n \"\"\"\n DEVNULL = open(os.devnull, 'w')\n while True:\n\n ip = job_q.get()\n\n if ip is None:\n break\n\n try:\n subprocess.check_call(['ping', '-c1', ip],\n stdout=DEVNULL)\n results_q.put(ip)\n except:\n pass\n\n\ndef get_my_ip():\n \"\"\"\n Find my IP address\n :return:\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n ip = s.getsockname()[0]\n s.close()\n return ip\n\n\ndef map_network(pool_size=255):\n \"\"\"\n Maps the network\n :param pool_size: amount of parallel ping processes\n :return: list of valid ip addresses\n \"\"\"\n \n ip_list = list()\n \n # get my IP and compose a base like 192.168.1.xxx\n ip_parts = get_my_ip().split('.')\n base_ip = ip_parts[0] + '.' + ip_parts[1] + '.' + ip_parts[2] + '.'\n \n # prepare the jobs queue\n jobs = multiprocessing.Queue()\n results = multiprocessing.Queue()\n \n pool = [multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size)]\n \n for p in pool:\n p.start()\n \n # cue hte ping processes\n for i in range(1, 255):\n jobs.put(base_ip + '{0}'.format(i))\n \n for p in pool:\n jobs.put(None)\n \n for p in pool:\n p.join()\n \n # collect he results\n while not results.empty():\n ip = results.get()\n ip_list.append(ip)\n\n return ip_list\n\n\nif __name__ == '__main__':\n\n print('Mapping...')\n lst = map_network()\n print(lst)\n" }, { "answer_id": 56950161, "author": "Grebtsew", "author_id": 10796389, "author_profile": "https://Stackoverflow.com/users/10796389", "pm_score": 3, "selected": false, "text": "linux: [20, 21, 22, 23, 25, 80, 111, 443, 445, 631, 993, 995]\nwindows: [135, 137, 138, 139, 445]\nmac: [22, 445, 548, 631]\n import socket\n\ndef connect(hostname, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket.setdefaulttimeout(1)\n result = sock.connect_ex((hostname, port))\n sock.close()\n return result == 0\n\nfor i in range(0,255):\n res = connect(\"192.168.1.\"+str(i), 22)\n if res:\n print(\"Device found at: \", \"192.168.1.\"+str(i) + \":\"+str(22))\n from threading import Thread, Lock\nfrom time import perf_counter\nfrom sys import stderr\nfrom time import sleep\nimport socket\n\n\n# I changed this from \"192.168.1.%i\" to \"192.168.0.%i\"\nBASE_IP = \"192.168.0.%i\"\nPORT = 80\n\n\nclass Threader:\n \"\"\"\n This is a class that calls a list of functions in a limited number of\n threads. It uses locks to make sure the data is thread safe.\n Usage:\n from time import sleep\n\n def function(i):\n sleep(2)\n with threader.print_lock:\n print(i)\n\n threader = Threader(10) # The maximum number of threads = 10\n for i in range(20):\n threader.append(function, i)\n threader.start()\n threader.join()\n\n This class also provides a lock called: `<Threader>.print_lock`\n \"\"\"\n def __init__(self, threads=30):\n self.thread_lock = Lock()\n self.functions_lock = Lock()\n self.functions = []\n self.threads = []\n self.nthreads = threads\n self.running = True\n self.print_lock = Lock()\n\n def stop(self) -> None:\n # Signal all worker threads to stop\n self.running = False\n\n def append(self, function, *args) -> None:\n # Add the function to a list of functions to be run\n self.functions.append((function, args))\n\n def start(self) -> None:\n # Create a limited number of threads\n for i in range(self.nthreads):\n thread = Thread(target=self.worker, daemon=True)\n # We need to pass in `thread` as a parameter so we\n # have to use `<threading.Thread>._args` like this:\n thread._args = (thread, )\n self.threads.append(thread)\n thread.start()\n\n def join(self) -> None:\n # Joins the threads one by one until all of them are done.\n for thread in self.threads:\n thread.join()\n\n def worker(self, thread:Thread) -> None:\n # While we are running and there are functions to call:\n while self.running and (len(self.functions) > 0):\n # Get a function\n with self.functions_lock:\n function, args = self.functions.pop(0)\n # Call that function\n function(*args)\n\n # Remove the thread from the list of threads.\n # This may cause issues if the user calls `<Threader>.join()`\n # But I haven't seen this problem while testing/using it.\n with self.thread_lock:\n self.threads.remove(thread)\n\n\nstart = perf_counter()\n# I didn't need a timeout of 1 so I used 0.1\nsocket.setdefaulttimeout(0.1)\n\ndef connect(hostname, port):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n result = sock.connect_ex((hostname, port))\n with threader.print_lock:\n if result == 0:\n stderr.write(f\"[{perf_counter() - start:.5f}] Found {hostname}\\n\")\n\nthreader = Threader(10)\nfor i in range(255):\n threader.append(connect, BASE_IP%i, PORT)\nthreader.start()\nthreader.join()\nprint(f\"[{perf_counter() - start:.5f}] Done searching\")\ninput(\"Press enter to exit.\\n? \")\n" }, { "answer_id": 58629591, "author": "shashika11", "author_id": 12298563, "author_profile": "https://Stackoverflow.com/users/12298563", "pm_score": 0, "selected": false, "text": "#running windows cmd line statement and put output into a string\ncmd_out = os.popen(\"arp -a\").read()\nline_arr = cmd_out.split('\\n')\nline_count = len(line_arr)\n\n\n#search in all lines for ip\nfor i in range(0, line_count):\n y = line_arr[i]\n z = y.find(mac_address)\n\n #if mac address is found then get the ip using regex matching\n if z > 0:\n ip_out= re.search('[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+', y, re.M | re.I)\n" }, { "answer_id": 59525143, "author": "trozzel", "author_id": 12011902, "author_profile": "https://Stackoverflow.com/users/12011902", "pm_score": 3, "selected": false, "text": "arp -a devices = []\nfor device in os.popen('arp -a'): devices.append(device)\n" }, { "answer_id": 70724942, "author": "Hans", "author_id": 15096247, "author_profile": "https://Stackoverflow.com/users/15096247", "pm_score": 0, "selected": false, "text": "import kthread #pip install kthread\nfrom time import sleep\nimport subprocess\n\ndef getips():\n ipadressen = {}\n def ping(ipadresse):\n try:\n outputcap = subprocess.run([f'ping', ipadresse, '-n', '1'], capture_output=True) #sends only one package, faster\n ipadressen[ipadresse] = outputcap\n except Exception as Fehler:\n print(Fehler)\n t = [kthread.KThread(target = ping, name = f\"ipgetter{ipend}\", args=(f'192.168.0.{ipend}',)) for ipend in range(255)] #prepares threads\n [kk.start() for kk in t] #starts 255 threads\n while len(ipadressen) < 255:\n print('Searching network')\n sleep(.3)\n alldevices = []\n for key, item in ipadressen.items():\n if not 'unreachable' in item.stdout.decode('utf-8') and 'failure' not in item.stdout.decode('utf-8'): #checks if there wasn't neither general failure nor 'unrechable host'\n alldevices.append(key)\n return alldevices\n\nallips = getips() #takes 1.5 seconds on my pc\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
207,237
<p>What is the best way to allow a team of programmers to use Netbeans, Eclipse and IntelliJ on the same project, thus eliminating the "which IDE is better" question.</p> <p>Which files should or should not be checked into source code control?</p>
[ { "answer_id": 207241, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 3, "selected": false, "text": ".project .classpath Java Project" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,256
<p>I've created the following regex pattern in an attempt to match a string 6 characters in length ending in either "PRI" or "SEC", unless the string = "SIGSEC". For example, I want to match ABCPRI, XYZPRI, ABCSEC and XYZSEC, but not SIGSEC.</p> <pre><code>(\w{3}PRI$|[^SIG].*SEC$) </code></pre> <p>It is very close and sort of works (if I pass in "SINSEC", it returns a partial match on "NSEC"), but I don't have a good feeling about it in its current form. Also, I may have a need to add more exclusions besides "SIG" later and realize that this probably won't scale too well. Any ideas?</p> <p>BTW, I'm using System.Text.RegularExpressions.Regex.Match() in C#</p> <p>Thanks, Rich</p>
[ { "answer_id": 207262, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 4, "selected": true, "text": "((?!SIGSEC)\\w{3}(?:SEC|PRI))\n" }, { "answer_id": 207266, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "exclude = 'someexpression'; prefix = 'list of prefixes'; suffix = 'list of suffixes'; expression = '{prefix}{exclude}{suffix}';" }, { "answer_id": 207274, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "if ( ( $str =~ /^\\w{3}(?:PRI|SEC)$/ ) && ( $str ne 'SIGSEC' ) )\n" }, { "answer_id": 207275, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "@\"\\w{3}(?:PRI|(?<!SIG)SEC)\"\n @\"\\w{3}(?:PRI|(?<!SIG|FOO)SEC)\"\n" }, { "answer_id": 207280, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 2, "selected": false, "text": "( // outer capturing group to bind everything\n (?!SIGSEC) // negative lookahead: a match only works if \"SIGSEC\" does not appear next\n \\w{3} // exactly three \"word\" characters\n (?: // non-capturing group - we don't care which of the following things matched\n SEC|PRI // either \"SEC\" or \"PRI\"\n )\n)\n" }, { "answer_id": 207850, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "private Boolean HasValidEnding(String input)\n{\n if (input.EndsWith(\"SEC\",StringComparison.Ordinal) || input.EndsWith(\"PRI\",StringComparison.Ordinal))\n {\n if (!input.Equals(\"SIGSEC\",StringComparison.Ordinal))\n {\n return true;\n }\n }\n return false;\n}\n private Boolean HasValidEnding(String input)\n{\n return (input.EndsWith(\"SEC\",StringComparison.Ordinal) || input.EndsWith(\"PRI\",StringComparison.Ordinal)) && !input.Equals(\"SIGSEC\",StringComparison.Ordinal);\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28442/" ]
207,260
<p>i noticed that paypal displays a very different favicon, one that's not just a simple 16x16 icon and is lengthy? anyone can teach me?</p>
[ { "answer_id": 58583952, "author": "Abhinav Pundi", "author_id": 12283143, "author_profile": "https://Stackoverflow.com/users/12283143", "pm_score": 0, "selected": false, "text": "<link rel=\"shortcut icon\" type=\"image/png\" href=\"images/favicon.png\">" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24744/" ]
207,267
<p>I have recently started working on a very large C++ project that, after completing 90% of the implementation, has determined that they need to demonstrate 100% branch coverage during testing. The project is hosted on an embedded platform (Green Hills Integrity). I'm looking for suggestions and experiences from others on StackOverflow that have used code coverage products in similar environments. I'm interested in both positive and negative comments regarding these types of tools.</p>
[ { "answer_id": 207672, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": false, "text": "int div(int a, int b)\n{\nreturn (a/b);\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19853/" ]
207,276
<p>I am just getting started with Silverlight and have recently added a Silverlight project to an established solution. In this particular scenario my solution included an existing ASP.NET web site (not application) which Visual Studio kindly offered to integrated my Silverlight application into, which I accepted.</p> <p>So everything is fine and all, and the Silverlight XAP is being copied to the web site's ClientBin directory. Now I have decided to start a new ASP.NET MVC web application that will eventually replace the older (non-MVC) web site. But I cannot for the life of me figure out what Visual Studio modified to get the XAP to automatically appear in the web site's ClientBin on build, so that I can reproduce that on my MVC site.</p> <p>So my question is essentially, what are the manually steps for getting Visual Studio to autocopy a Silverlight application's XAP to a newly added ASP.NET MVC web application?</p>
[ { "answer_id": 3218716, "author": "Amit", "author_id": 147613, "author_profile": "https://Stackoverflow.com/users/147613", "pm_score": 2, "selected": false, "text": "copy $(TargetDir)*.xap $(SolutionDir)<youar web solution folder name such as app.web>\\ClientBin\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27860/" ]
207,283
<p>OS: Vista enterprise</p> <p>When i switch between my home and office network, i always face issues with getting connected to the network. Almost always I have to use the diagnostic service in 'Network and sharing center' and the problem gets solved when i use the reset network adapter option.</p> <p>This takes a lot of time (3-4 min) and so i was trying to find either a command or a powershell script/cmdlet which i can use directly to reset the network adapter and save myself these 5 mins every time i have to switch between the networks. Any pointers?</p>
[ { "answer_id": 207402, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 3, "selected": false, "text": "Restart-NetAdapter -Name \"Your Name Here\"\n Get-NetAdapter\n" }, { "answer_id": 207418, "author": "JFV", "author_id": 1391, "author_profile": "https://Stackoverflow.com/users/1391", "pm_score": 3, "selected": false, "text": "ipconfig /release\nipconfig /renew\narp -d *\nnbtstat -R\nnbtstat -RR\nipconfig /flushdns\nipconfig /registerdns\n" }, { "answer_id": 207500, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 6, "selected": true, "text": "$adaptor = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like \"*Wireless*\"}\n$adaptor.Disable()\n$adaptor.Enable()\n" }, { "answer_id": 2395962, "author": "Andrew Strong", "author_id": 98143, "author_profile": "https://Stackoverflow.com/users/98143", "pm_score": 2, "selected": false, "text": "devcon listclass net devcon restart PCI\\VEN_16* '*'" }, { "answer_id": 5487369, "author": "Claudio Maranta", "author_id": 683731, "author_profile": "https://Stackoverflow.com/users/683731", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Management;\n\nnamespace ResetNetworkAdapter\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args.Length != 1)\n {\n Console.WriteLine(\"ResetNetworkAdapter [adapter name]\");\n Console.WriteLine(\"disables and re-enables (restarts) network adapters containing [adapter name] in their name\");\n return;\n }\n\n // commandline parameter is a string to be contained in the searched network adapter name\n string AdapterNameLike = args[0];\n\n // get network adapter node \n SelectQuery query = new SelectQuery(\"Win32_NetworkAdapter\");\n ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);\n ManagementObjectCollection adapters = searcher.Get();\n\n // enumerate all network adapters\n foreach (ManagementObject adapter in adapters)\n {\n // find the matching adapter\n string Name = (string)adapter.Properties[\"Name\"].Value;\n if (Name.ToLower().Contains(AdapterNameLike.ToLower()))\n {\n // disable and re-enable the adapter\n adapter.InvokeMethod(\"Disable\", null);\n adapter.InvokeMethod(\"Enable\", null);\n }\n }\n }\n }\n}\n" }, { "answer_id": 14086103, "author": "Protector one", "author_id": 125938, "author_profile": "https://Stackoverflow.com/users/125938", "pm_score": 0, "selected": false, "text": "netsh netsh wlan disconnect && netsh wlan connect [ONE OF YOUR WLAN PROFILES]\n netsh wlan show profiles\n" }, { "answer_id": 22194384, "author": "Zitrax", "author_id": 11722, "author_profile": "https://Stackoverflow.com/users/11722", "pm_score": 3, "selected": false, "text": "netsh interface show interface\n netsh interface set interface \"Ethernet 2\" DISABLED\nnetsh interface set interface \"Ethernet 2\" ENABLED\n" }, { "answer_id": 27209828, "author": "Andrew C", "author_id": 4307871, "author_profile": "https://Stackoverflow.com/users/4307871", "pm_score": 4, "selected": false, "text": "netsh interface set interface \"InterfaceName\" DISABLED\nnetsh interface set interface \"InterfaceName\" ENABLED\n" }, { "answer_id": 36101044, "author": "Santa", "author_id": 3552195, "author_profile": "https://Stackoverflow.com/users/3552195", "pm_score": 2, "selected": false, "text": "Restart-NetAdapter -Name \"ethernet\" Restart-NetAdapter -Name \"ethernet\" .ps1 .ps1 .ps1 Get-NetAdapter" }, { "answer_id": 36716072, "author": "Lunudeus1", "author_id": 6224403, "author_profile": "https://Stackoverflow.com/users/6224403", "pm_score": 1, "selected": false, "text": "C:\\>wmic nic get name, index \n wmic path win32_networkadapter where index=1 call disable\n wmic path win32_networkadapter where index=1 call enable\n" }, { "answer_id": 37534313, "author": "Alahndro", "author_id": 6402161, "author_profile": "https://Stackoverflow.com/users/6402161", "pm_score": 0, "selected": false, "text": "@echo off\nnetsh interface set interface \"%1\" DISABLED\nnetsh interface set interface \"%1\" ENABLED\n" }, { "answer_id": 39371605, "author": "Leigh", "author_id": 513450, "author_profile": "https://Stackoverflow.com/users/513450", "pm_score": 3, "selected": false, "text": "Restart-NetAdapter -Name \"Ethernet 2\"\n script.PS1" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26090/" ]
207,290
<p>I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form <code>${</code><em>expr</em><code>}</code>, for example, where <em>expr</em> is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with <code>compile()</code>, evaluate it against a particular scope with <code>eval()</code>, and perhaps even substitute the result into the original string. People must do very similar things all the time.</p> <p>I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of <em>expr</em> is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any <em>expr</em> that has balanced curly braces.</p> <p>What's your sense?</p> <h2>Update:</h2> <p>Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text.</p> <p>The <code>${</code><em>expr</em><code>}</code> syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used <code>$(</code><em>expr</em><code>)</code> as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of <code>re.finditer(r'$\{([^}]+)\}', s)</code>, a bit easier to see. Python expressions can (and often do) contain the <code>)</code> (or <code>}</code>) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case!</p> <p>Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing.</p> <p>Thanks for your patience!</p>
[ { "answer_id": 207502, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python\n\nimport sys\nimport re\n\nFILE = sys.argv[1]\n\nhandle = open(FILE)\nfcontent = handle.read()\nhandle.close()\n\nfor myexpr in re.finditer(r'\\${([^}]+)}', fcontent, re.M|re.S):\n text = myexpr.group(1)\n try:\n exec text\n except SyntaxError:\n print \"ERROR: unable to compile expression '%s'\" % (text)\n This is some random text, with embedded python like \n${print \"foo\"} and some bogus python like\n\n${any:thing}.\n\nAnd a multiline statement, just for kicks: \n\n${\ndef multiline_stmt(foo):\n print foo\n\nmultiline_stmt(\"ahem\")\n}\n\nMore text here.\n [user@host]$ ./exec_embedded_python.py test.txt\nfoo\nERROR: unable to compile expression 'any:thing'\nahem\n" }, { "answer_id": 209420, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "{'{spam': 42}[\"spam}\"]" }, { "answer_id": 210716, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 0, "selected": false, "text": "${ } compile() } } } ${ } } def findExpr(s, i0=0, begin='${', end='}', compArgs=('<string>', 'eval')):\n assert '\\n' not in s, 'line numbers not implemented'\n i0 = s.index(begin, i0) + len(begin)\n i1 = s.index(end, i0)\n code = errMsg = None\n while code is None and errMsg is None:\n expr = s[i0:i1]\n try: code = compile(expr, *compArgs)\n except SyntaxError, e:\n i1 = s.find(end, i1 + 1)\n if i1 < 0: errMsg, i1 = e.msg, i0 + e.offset\n return i0, i1, code, errMsg\n '''\nSearch s for a (possibly invalid) Python expression bracketed by begin\nand end, which default to '${' and '}'. Return a 4-tuple.\n\n>>> s = 'foo ${a*b + c*d} bar'\n>>> i0, i1, code, errMsg = findExpr(s)\n>>> i0, i1, s[i0:i1], errMsg\n(6, 15, 'a*b + c*d', None)\n>>> ' '.join('%02x' % ord(byte) for byte in code.co_code)\n'65 00 00 65 01 00 14 65 02 00 65 03 00 14 17 53'\n>>> code.co_names\n('a', 'b', 'c', 'd')\n>>> eval(code, {'a': 1, 'b': 2, 'c': 3, 'd': 4})\n14\n>>> eval(code, {'a': 'a', 'b': 2, 'c': 'c', 'd': 4})\n'aacccc'\n>>> eval(code, {'a': None})\nTraceback (most recent call last):\n ...\nNameError: name 'b' is not defined\n\nExpressions containing start and/or end are allowed.\n\n>>> s = '{foo ${{\"}\": \"${\"}[\"}\"]} bar}'\n>>> i0, i1, code, errMsg = findExpr(s)\n>>> i0, i1, s[i0:i1], errMsg\n(7, 23, '{\"}\": \"${\"}[\"}\"]', None)\n\nIf the first match is syntactically invalid Python, i0 points to the\nstart of the match, i1 points to the parse error, code is None and\nerrMsg contains a message from the compiler.\n\n>>> s = '{foo ${qwerty asdf zxcvbnm!!!} ${7} bar}'\n>>> i0, i1, code, errMsg = findExpr(s)\n>>> i0, i1, s[i0:i1], errMsg\n(7, 18, 'qwerty asdf', 'invalid syntax')\n>>> print code\nNone\n\nIf a second argument is given, start searching there.\n\n>>> i0, i1, code, errMsg = findExpr(s, i1)\n>>> i0, i1, s[i0:i1], errMsg\n(33, 34, '7', None)\n\nRaise ValueError if there are no further matches.\n\n>>> i0, i1, code, errMsg = findExpr(s, i1)\nTraceback (most recent call last):\n ...\nValueError: substring not found\n\nIn ambiguous cases, match the shortest valid expression. This is not\nalways ideal behavior.\n\n>>> s = '{foo ${x or {} # return {} instead of None} bar}'\n>>> i0, i1, code, errMsg = findExpr(s)\n>>> i0, i1, s[i0:i1], errMsg\n(7, 25, 'x or {} # return {', None)\n\nThis implementation must not be used with multi-line strings. It does\nnot adjust line number information in the returned code object, and it\ndoes not take the line number into account when computing the offset\nof a parse error.\n\n'''\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13871/" ]
207,306
<p>I'm using the MonthCalendar control and want to programmatically select a date range. When I do so the control doesn't paint properly if <code>Application.EnableVisualStyles()</code> has been called. This is a known issue according to MSDN. </p> <blockquote> <p>Using the MonthCalendar with visual styles enabled will cause a selection range for the MonthCalendar control to not paint correctly (from: <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.monthcalendar.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.monthcalendar.aspx</a>)</p> </blockquote> <p>Is there really no fix for this other than not calling <code>EnableVisualStyles</code>? This seems to make that particular control entirely useless for a range of applications and a rather glaring oversight from my perspective.</p>
[ { "answer_id": 1410399, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "public class MonthCalendarEx : System.Windows.Forms.MonthCalendar\n{\n private int _offsetX;\n private int _offsetY;\n private int _dayBoxWidth;\n private int _dayBoxHeight;\n\n private bool _repaintSelectedDays = false;\n\n public MonthCalendarEx() : base()\n {\n OnSizeChanged(null, null);\n this.SizeChanged += OnSizeChanged;\n this.DateChanged += OnSelectionChanged;\n this.DateSelected += OnSelectionChanged;\n }\n\n protected static int WM_PAINT = 0x000F;\n\n protected override void WndProc(ref System.Windows.Forms.Message m)\n {\n base.WndProc(ref m);\n if (m.Msg == WM_PAINT)\n {\n Graphics graphics = Graphics.FromHwnd(this.Handle);\n PaintEventArgs pe = new PaintEventArgs(\n graphics, new Rectangle(0, 0, this.Width, this.Height));\n OnPaint(pe);\n }\n }\n\n private void OnSelectionChanged(object sender, EventArgs e)\n {\n _repaintSelectedDays = true;\n }\n\n private void OnSizeChanged(object sender, EventArgs e)\n { \n _offsetX = 0;\n _offsetY = 0;\n\n // determine Y offset of days area \n while (\n HitTest(Width / 2, _offsetY).HitArea != HitArea.PrevMonthDate &&\n HitTest(Width / 2, _offsetY).HitArea != HitArea.Date)\n {\n _offsetY++;\n }\n\n // determine X offset of days area \n while (HitTest(_offsetX, Height / 2).HitArea != HitArea.Date)\n {\n _offsetX++;\n }\n\n // determine width of a single day box\n _dayBoxWidth = 0;\n DateTime dt1 = HitTest(Width / 2, _offsetY).Time;\n\n while (HitTest(Width / 2, _offsetY + _dayBoxHeight).Time == dt1)\n {\n _dayBoxHeight++;\n }\n\n // determine height of a single day box\n _dayBoxWidth = 0;\n DateTime dt2 = HitTest(_offsetX, Height / 2).Time;\n\n while (HitTest(_offsetX + _dayBoxWidth, Height / 2).Time == dt2)\n {\n _dayBoxWidth++;\n }\n }\n\n protected override void OnPaint(PaintEventArgs e)\n { \n base.OnPaint(e);\n\n if (_repaintSelectedDays)\n {\n Graphics graphics = e.Graphics;\n SelectionRange calendarRange = GetDisplayRange(false);\n Rectangle currentDayFrame = new Rectangle(\n -1, -1, _dayBoxWidth, _dayBoxHeight);\n\n DateTime current = SelectionStart;\n while (current <= SelectionEnd) \n {\n Rectangle currentDayRectangle;\n\n using (Brush selectionBrush = new SolidBrush(\n Color.FromArgb(\n 255, System.Drawing.SystemColors.ActiveCaption))) \n { \n TimeSpan span = current.Subtract(calendarRange.Start); \n int row = span.Days / 7; \n int col = span.Days % 7; \n\n currentDayRectangle = new Rectangle(\n _offsetX + (col + (ShowWeekNumbers ? 1 : 0)) * _dayBoxWidth, \n _offsetY + row * _dayBoxHeight, \n _dayBoxWidth, \n _dayBoxHeight);\n\n graphics.FillRectangle(selectionBrush, currentDayRectangle); \n }\n\n TextRenderer.DrawText(\n graphics, \n current.Day.ToString(), \n Font, \n currentDayRectangle, \n System.Drawing.SystemColors.ActiveCaptionText, \n TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);\n\n if (current == this.TodayDate)\n {\n currentDayFrame = currentDayRectangle;\n }\n\n current = current.AddDays(1);\n }\n\n if (currentDayFrame.X > 0)\n {\n graphics.DrawRectangle(new Pen(\n new SolidBrush(Color.Red)), currentDayFrame);\n }\n\n _repaintSelectedDays = false;\n }\n }\n}\n" }, { "answer_id": 3062317, "author": "Mark Cranness", "author_id": 365611, "author_profile": "https://Stackoverflow.com/users/365611", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// When Visual Styles are enabled on Windows XP, the MonthCalendar.SelectionRange\n/// does not paint correctly when more than one date is selected.\n/// See: http://msdn.microsoft.com/en-us/library/5d1acks5(VS.80).aspx\n/// \"Additionally, if you enable visual styles on some controls, the control might display incorrectly\n/// in certain situations. These include the MonthCalendar control with a selection range set...\n/// This class fixes that problem.\n/// </summary>\n/// <remarks>Author: Mark Cranness</remarks>\npublic class FixVisualStylesMonthCalendar : System.Windows.Forms.MonthCalendar {\n\n /// <summary>\n /// The width of a single cell (date) in the calendar.\n /// </summary>\n private int dayCellWidth;\n /// <summary>\n /// The height of a single cell (date) in the calendar.\n /// </summary>\n private int dayCellHeight;\n\n /// <summary>\n /// The calendar first day of the week actually used.\n /// </summary>\n private DayOfWeek calendarFirstDayOfWeek;\n\n /// <summary>\n /// Only repaint when VisualStyles enabled on Windows XP.\n /// </summary>\n private bool repaintSelectionRange = false;\n\n /// <summary>\n /// A MonthCalendar class that fixes SelectionRange painting problems \n /// on Windows XP when Visual Styles is enabled.\n /// </summary>\n public FixVisualStylesMonthCalendar() {\n\n if (Application.RenderWithVisualStyles\n && Environment.OSVersion.Version < new Version(6, 0)) {\n\n // If Visual Styles are enabled, and XP, then fix-up the painting of SelectionRange\n this.repaintSelectionRange = true;\n this.OnSizeChanged(this, EventArgs.Empty);\n this.SizeChanged += new EventHandler(this.OnSizeChanged);\n\n }\n }\n\n /// <summary>\n /// The WM_PAINT message is sent to make a request to paint a portion of a window.\n /// </summary>\n public const int WM_PAINT = 0x000F;\n\n /// <summary>\n /// Override WM_PAINT to repaint the selection range.\n /// </summary>\n [System.Diagnostics.DebuggerStepThroughAttribute()]\n protected override void WndProc(ref Message m)\n {\n base.WndProc(ref m);\n if (m.Msg == WM_PAINT\n && !this.DesignMode\n && this.repaintSelectionRange) {\n // MonthCalendar is ControlStyles.UserPaint=false => Paint event is not raised\n this.RepaintSelectionRange(ref m);\n }\n }\n\n /// <summary>\n /// Repaint the SelectionRange.\n /// </summary>\n private void RepaintSelectionRange(ref Message m) {\n\n using (Graphics graphics = this.CreateGraphics())\n using (Brush backBrush\n = new SolidBrush(graphics.GetNearestColor(this.BackColor)))\n using (Brush selectionBrush\n = new SolidBrush(graphics.GetNearestColor(SystemColors.ActiveCaption))) {\n\n Rectangle todayFrame = Rectangle.Empty;\n\n // For each day in SelectionRange...\n for (DateTime selectionDate = this.SelectionStart;\n selectionDate <= this.SelectionEnd;\n selectionDate = selectionDate.AddDays(1)) {\n\n Rectangle selectionDayRectangle = this.GetSelectionDayRectangle(selectionDate);\n if (selectionDayRectangle.IsEmpty) continue;\n\n if (selectionDate.Date == this.TodayDate) {\n todayFrame = selectionDayRectangle;\n }\n\n // Paint as 'selected' a little smaller than the whole rectangle\n Rectangle highlightRectangle = Rectangle.Inflate(selectionDayRectangle, 0, -2);\n if (selectionDate == this.SelectionStart) {\n highlightRectangle.X += 2;\n highlightRectangle.Width -= 2;\n }\n if (selectionDate == this.SelectionEnd) {\n highlightRectangle.Width -= 2;\n }\n\n // Paint background, selection and day-of-month text\n graphics.FillRectangle(backBrush, selectionDayRectangle);\n graphics.FillRectangle(selectionBrush, highlightRectangle);\n TextRenderer.DrawText(\n graphics,\n selectionDate.Day.ToString(),\n this.Font,\n selectionDayRectangle,\n SystemColors.ActiveCaptionText,\n TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);\n\n }\n\n if (this.ShowTodayCircle && !todayFrame.IsEmpty) {\n // Redraw the ShowTodayCircle (square) that we painted over above\n using (Pen redPen = new Pen(Color.Red)) {\n todayFrame.Width--;\n todayFrame.Height--;\n graphics.DrawRectangle(redPen, todayFrame);\n }\n }\n\n }\n }\n\n /// <summary>\n /// When displayed dates changed, clear the cached month locations.\n /// </summary>\n private SelectionRange previousDisplayedDates = new SelectionRange();\n\n /// <summary>\n /// Gets a graphics Rectangle for the area corresponding to a single date on the calendar.\n /// </summary>\n private Rectangle GetSelectionDayRectangle(DateTime selectionDateTime) {\n\n // Handle the leading and trailing dates from the previous and next months\n SelectionRange allDisplayedDates = this.GetDisplayRange(false);\n SelectionRange fullMonthDates = this.GetDisplayRange(true);\n int adjust1Week;\n DateTime selectionDate = selectionDateTime.Date;\n if (selectionDate < allDisplayedDates.Start \n || selectionDate > allDisplayedDates.End) {\n // Selection Date is not displayed on calendar\n return Rectangle.Empty;\n } else if (selectionDate < fullMonthDates.Start) {\n // Selection Date is trailing from the previous partial month\n selectionDate = selectionDate.AddDays(7);\n adjust1Week = -1;\n } else if (selectionDate > fullMonthDates.End) {\n // Selection Date is leading from the next partial month\n selectionDate = selectionDate.AddDays(-14);\n adjust1Week = +2;\n } else {\n // A mainline date\n adjust1Week = 0;\n }\n\n // Discard cached month locations when calendar moves\n if (this.previousDisplayedDates.Start != allDisplayedDates.Start\n || this.previousDisplayedDates.End != allDisplayedDates.End) {\n this.DiscardCachedMonthDateAreaLocations();\n this.previousDisplayedDates.Start = allDisplayedDates.Start;\n this.previousDisplayedDates.End = allDisplayedDates.End;\n }\n\n Point monthDateAreaLocation = this.GetMonthDateAreaLocation(selectionDate);\n if (monthDateAreaLocation.IsEmpty) return Rectangle.Empty;\n\n DayOfWeek monthFirstDayOfWeek = (new DateTime(selectionDate.Year, selectionDate.Month, 1)).DayOfWeek;\n int dayOfWeekAdjust = (int)monthFirstDayOfWeek - (int)this.calendarFirstDayOfWeek;\n if (dayOfWeekAdjust < 0) dayOfWeekAdjust += 7;\n int row = (selectionDate.Day - 1 + dayOfWeekAdjust) / 7;\n int col = (selectionDate.Day - 1 + dayOfWeekAdjust) % 7;\n row += adjust1Week;\n\n return new Rectangle(\n monthDateAreaLocation.X + col * this.dayCellWidth,\n monthDateAreaLocation.Y + row * this.dayCellHeight,\n this.dayCellWidth,\n this.dayCellHeight);\n\n }\n\n /// <summary>\n /// Cached calendar location from the last lookup.\n /// </summary>\n private Point[] cachedMonthDateAreaLocation = new Point[13];\n\n /// <summary>\n /// Discard the cached month locations when calendar moves.\n /// </summary>\n private void DiscardCachedMonthDateAreaLocations() {\n for (int i = 0; i < 13; i++) this.cachedMonthDateAreaLocation[i] = Point.Empty;\n }\n\n /// <summary>\n /// Gets the graphics location (x,y point) of the top left of the\n /// calendar date area for the month containing the specified date.\n /// </summary>\n private Point GetMonthDateAreaLocation(DateTime selectionDate) {\n\n Point monthDateAreaLocation = this.cachedMonthDateAreaLocation[selectionDate.Month];\n HitTestInfo hitInfo;\n if (!monthDateAreaLocation.IsEmpty\n && (hitInfo = this.HitTest(monthDateAreaLocation.X, monthDateAreaLocation.Y + this.dayCellHeight))\n .HitArea == HitArea.Date\n && hitInfo.Time.Year == selectionDate.Year\n && hitInfo.Time.Month == selectionDate.Month) {\n\n // Use previously cached lookup\n return monthDateAreaLocation;\n\n } else {\n\n // Assume the worst (Error: empty)\n monthDateAreaLocation = this.cachedMonthDateAreaLocation[selectionDate.Month] = Point.Empty;\n\n Point monthDataAreaPoint = this.GetMonthDateAreaMiddle(selectionDate);\n if (monthDataAreaPoint.IsEmpty) return Point.Empty;\n\n // Move left from the middle to find the left edge of the Date area\n monthDateAreaLocation.X = monthDataAreaPoint.X--;\n HitTestInfo hitInfo1, hitInfo2;\n while ((hitInfo1 = this.HitTest(monthDataAreaPoint.X, monthDataAreaPoint.Y))\n .HitArea == HitArea.Date\n && hitInfo1.Time.Month == selectionDate.Month\n || (hitInfo2 = this.HitTest(monthDataAreaPoint.X, monthDataAreaPoint.Y + this.dayCellHeight))\n .HitArea == HitArea.Date\n && hitInfo2.Time.Month == selectionDate.Month) {\n monthDateAreaLocation.X = monthDataAreaPoint.X--;\n if (monthDateAreaLocation.X < 0) return Point.Empty; // Error: bail\n }\n\n // Move up from the last column to find the top edge of the Date area\n int monthLastDayOfWeekX = monthDateAreaLocation.X + (this.dayCellWidth * 7 * 13) / 14;\n monthDateAreaLocation.Y = monthDataAreaPoint.Y--;\n while (this.HitTest(monthLastDayOfWeekX, monthDataAreaPoint.Y).HitArea == HitArea.Date) {\n monthDateAreaLocation.Y = monthDataAreaPoint.Y--;\n if (monthDateAreaLocation.Y < 0) return Point.Empty; // Error: bail\n }\n\n // Got it\n this.cachedMonthDateAreaLocation[selectionDate.Month] = monthDateAreaLocation;\n return monthDateAreaLocation;\n\n }\n }\n\n /// <summary>\n /// Paranoid fudge/wobble of the GetMonthDateAreaMiddle in case \n /// our first estimate to hit the month misses.\n /// (Needed? perhaps not.)\n /// </summary>\n private static Point[] searchSpiral = {\n new Point( 0, 0),\n new Point(-1,+1), new Point(+1,+1), new Point(+1,-1), new Point(-1,-1), \n new Point(-2,+2), new Point(+2,+2), new Point(+2,-2), new Point(-2,-2)\n };\n\n /// <summary>\n /// Gets a point somewhere inside the calendar date area of\n /// the month containing the given selection date.\n /// </summary>\n /// <remarks>The point returned will be HitArea.Date, and match the year and\n /// month of the selection date; otherwise it will be Point.Empty.</remarks>\n private Point GetMonthDateAreaMiddle(DateTime selectionDate) {\n\n // Iterate over all displayed months, and a search spiral (needed? perhaps not)\n for (int dimX = 1; dimX <= this.CalendarDimensions.Width; dimX++) {\n for (int dimY = 1; dimY <= this.CalendarDimensions.Height; dimY++) {\n foreach (Point search in searchSpiral) {\n\n Point monthDateAreaMiddle = new Point(\n ((dimX - 1) * 2 + 1) * this.Width / (2 * this.CalendarDimensions.Width)\n + this.dayCellWidth * search.X,\n ((dimY - 1) * 2 + 1) * this.Height / (2 * this.CalendarDimensions.Height)\n + this.dayCellHeight * search.Y);\n HitTestInfo hitInfo = this.HitTest(monthDateAreaMiddle);\n if (hitInfo.HitArea == HitArea.Date) {\n // Got the Date Area of the month\n if (hitInfo.Time.Year == selectionDate.Year\n && hitInfo.Time.Month == selectionDate.Month) {\n // For the correct month\n return monthDateAreaMiddle;\n } else {\n // Keep looking in the other months\n break;\n }\n }\n\n }\n }\n }\n return Point.Empty; // Error: not found\n\n }\n\n /// <summary>\n /// When this MonthCalendar is resized, recalculate the size of a day cell.\n /// </summary>\n private void OnSizeChanged(object sender, EventArgs e) {\n\n // Discard previous cached Month Area Location\n DiscardCachedMonthDateAreaLocations();\n this.dayCellWidth = this.dayCellHeight = 0;\n\n // Without this, the repaint sometimes does not happen...\n this.Invalidate();\n\n // Determine Y offset of days area\n int middle = this.Width / (2 * this.CalendarDimensions.Width);\n int dateAreaTop = 0;\n while (this.HitTest(middle, dateAreaTop).HitArea != HitArea.PrevMonthDate\n && this.HitTest(middle, dateAreaTop).HitArea != HitArea.Date) {\n dateAreaTop++;\n if (dateAreaTop > this.ClientSize.Height) return; // Error: bail\n }\n\n // Determine height of a single day box\n int dayCellHeight = 1;\n DateTime dayCellTime = this.HitTest(middle, dateAreaTop).Time;\n while (this.HitTest(middle, dateAreaTop + dayCellHeight).Time == dayCellTime) {\n dayCellHeight++;\n }\n\n // Determine X offset of days area\n middle = this.Height / (2 * this.CalendarDimensions.Height);\n int dateAreaLeft = 0;\n while (this.HitTest(dateAreaLeft, middle).HitArea != HitArea.Date) {\n dateAreaLeft++;\n if (dateAreaLeft > this.ClientSize.Width) return; // Error: bail\n }\n\n // Determine width of a single day box\n int dayCellWidth = 1;\n dayCellTime = this.HitTest(dateAreaLeft, middle).Time;\n while (this.HitTest(dateAreaLeft + dayCellWidth, middle).Time == dayCellTime) {\n dayCellWidth++;\n }\n\n // Record day box size and actual first day of the month used\n this.calendarFirstDayOfWeek = dayCellTime.DayOfWeek;\n this.dayCellWidth = dayCellWidth;\n this.dayCellHeight = dayCellHeight;\n\n }\n\n}\n" }, { "answer_id": 7012966, "author": "H B", "author_id": 521443, "author_profile": "https://Stackoverflow.com/users/521443", "pm_score": 2, "selected": false, "text": "if (Application.VisualStyleState != System.Windows.Forms.VisualStyles.VisualStyleState.NoneEnabled && \n Environment.OSVersion.Version < new Version(6, 0))\n /// <summary>\n/// When Visual Styles are enabled on Windows XP, the MonthCalendar.SelectionRange\n/// does not paint correctly when more than one date is selected.\n/// See: http://msdn.microsoft.com/en-us/library/5d1acks5(VS.80).aspx\n/// \"Additionally, if you enable visual styles on some controls, the control might display incorrectly\n/// in certain situations. These include the MonthCalendar control with a selection range set...\n/// This class fixes that problem.\n/// </summary>\n/// <remarks>Author: Mark Cranness - PatronBase Limited.</remarks>\npublic class FixVisualStylesMonthCalendar : System.Windows.Forms.MonthCalendar\n{\n\n /// <summary>\n /// The width of a single cell (date) in the calendar.\n /// </summary>\n private int dayCellWidth;\n /// <summary>\n /// The height of a single cell (date) in the calendar.\n /// </summary>\n private int dayCellHeight;\n\n /// <summary>\n /// The calendar first day of the week actually used.\n /// </summary>\n private DayOfWeek calendarFirstDayOfWeek;\n\n /// <summary>\n /// Only repaint when VisualStyles enabled on Windows XP.\n /// </summary>\n private bool repaintSelectionRange = false;\n\n /// <summary>\n /// A MonthCalendar class that fixes SelectionRange painting problems \n /// on Windows XP when Visual Styles is enabled.\n /// </summary>\n public FixVisualStylesMonthCalendar()\n {\n\n if (Application.VisualStyleState != System.Windows.Forms.VisualStyles.VisualStyleState.NoneEnabled && //Application.RenderWithVisualStyles && \n Environment.OSVersion.Version < new Version(6, 0))\n {\n // If Visual Styles are enabled, and XP, then fix-up the painting of SelectionRange\n this.repaintSelectionRange = true;\n this.OnSizeChanged(this, EventArgs.Empty);\n this.SizeChanged += new EventHandler(this.OnSizeChanged);\n }\n }\n\n /// <summary>\n /// The WM_PAINT message is sent to make a request to paint a portion of a window.\n /// </summary>\n public const int WM_PAINT = 0x000F;\n\n /// <summary>\n /// Override WM_PAINT to repaint the selection range.\n /// </summary>\n [System.Diagnostics.DebuggerStepThroughAttribute()]\n protected override void WndProc(ref Message m)\n {\n base.WndProc(ref m);\n if (m.Msg == WM_PAINT\n && !this.DesignMode\n && this.repaintSelectionRange)\n {\n // MonthCalendar is ControlStyles.UserPaint=false => Paint event is not raised\n this.RepaintSelectionRange(ref m);\n }\n }\n\n /// <summary>\n /// Repaint the SelectionRange.\n /// </summary>\n private void RepaintSelectionRange(ref Message m)\n {\n\n using (Graphics graphics = this.CreateGraphics())\n using (Brush backBrush\n = new SolidBrush(graphics.GetNearestColor(this.BackColor)))\n using (Brush selectionBrush\n = new SolidBrush(graphics.GetNearestColor(SystemColors.ActiveCaption)))\n {\n\n Rectangle todayFrame = Rectangle.Empty;\n\n // For each day in SelectionRange...\n for (DateTime selectionDate = this.SelectionStart;\n selectionDate <= this.SelectionEnd;\n selectionDate = selectionDate.AddDays(1))\n {\n\n Rectangle selectionDayRectangle = this.GetSelectionDayRectangle(selectionDate);\n if (selectionDayRectangle.IsEmpty) continue;\n\n if (selectionDate.Date == this.TodayDate)\n {\n todayFrame = selectionDayRectangle;\n }\n\n // Paint as 'selected' a little smaller than the whole rectangle\n Rectangle highlightRectangle = Rectangle.Inflate(selectionDayRectangle, 0, -2);\n if (selectionDate == this.SelectionStart)\n {\n highlightRectangle.X += 2;\n highlightRectangle.Width -= 2;\n }\n if (selectionDate == this.SelectionEnd)\n {\n highlightRectangle.Width -= 2;\n }\n\n // Paint background, selection and day-of-month text\n graphics.FillRectangle(backBrush, selectionDayRectangle);\n graphics.FillRectangle(selectionBrush, highlightRectangle);\n TextRenderer.DrawText(\n graphics,\n selectionDate.Day.ToString(),\n this.Font,\n selectionDayRectangle,\n SystemColors.ActiveCaptionText,\n TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);\n\n }\n\n if (this.ShowTodayCircle && !todayFrame.IsEmpty)\n {\n // Redraw the ShowTodayCircle (square) that we painted over above\n using (Pen redPen = new Pen(Color.Red))\n {\n todayFrame.Width--;\n todayFrame.Height--;\n graphics.DrawRectangle(redPen, todayFrame);\n }\n }\n\n }\n }\n\n /// <summary>\n /// When displayed dates changed, clear the cached month locations.\n /// </summary>\n private SelectionRange previousDisplayedDates = new SelectionRange();\n\n /// <summary>\n /// Gets a graphics Rectangle for the area corresponding to a single date on the calendar.\n /// </summary>\n private Rectangle GetSelectionDayRectangle(DateTime selectionDateTime)\n {\n\n // Handle the leading and trailing dates from the previous and next months\n SelectionRange allDisplayedDates = this.GetDisplayRange(false);\n SelectionRange fullMonthDates = this.GetDisplayRange(true);\n int adjust1Week;\n DateTime selectionDate = selectionDateTime.Date;\n if (selectionDate < allDisplayedDates.Start\n || selectionDate > allDisplayedDates.End)\n {\n // Selection Date is not displayed on calendar\n return Rectangle.Empty;\n }\n else if (selectionDate < fullMonthDates.Start)\n {\n // Selection Date is trailing from the previous partial month\n selectionDate = selectionDate.AddDays(7);\n adjust1Week = -1;\n }\n else if (selectionDate > fullMonthDates.End)\n {\n // Selection Date is leading from the next partial month\n selectionDate = selectionDate.AddDays(-14);\n adjust1Week = +2;\n }\n else\n {\n // A mainline date\n adjust1Week = 0;\n }\n\n // Discard cached month locations when calendar moves\n if (this.previousDisplayedDates.Start != allDisplayedDates.Start\n || this.previousDisplayedDates.End != allDisplayedDates.End)\n {\n this.DiscardCachedMonthDateAreaLocations();\n this.previousDisplayedDates.Start = allDisplayedDates.Start;\n this.previousDisplayedDates.End = allDisplayedDates.End;\n }\n\n Point monthDateAreaLocation = this.GetMonthDateAreaLocation(selectionDate);\n if (monthDateAreaLocation.IsEmpty) return Rectangle.Empty;\n\n DayOfWeek monthFirstDayOfWeek = (new DateTime(selectionDate.Year, selectionDate.Month, 1)).DayOfWeek;\n int dayOfWeekAdjust = (int)monthFirstDayOfWeek - (int)this.calendarFirstDayOfWeek;\n if (dayOfWeekAdjust < 0) dayOfWeekAdjust += 7;\n int row = (selectionDate.Day - 1 + dayOfWeekAdjust) / 7;\n int col = (selectionDate.Day - 1 + dayOfWeekAdjust) % 7;\n row += adjust1Week;\n\n return new Rectangle(\n monthDateAreaLocation.X + col * this.dayCellWidth,\n monthDateAreaLocation.Y + row * this.dayCellHeight,\n this.dayCellWidth,\n this.dayCellHeight);\n\n }\n\n /// <summary>\n /// Cached calendar location from the last lookup.\n /// </summary>\n private Point[] cachedMonthDateAreaLocation = new Point[13];\n\n /// <summary>\n /// Discard the cached month locations when calendar moves.\n /// </summary>\n private void DiscardCachedMonthDateAreaLocations()\n {\n for (int i = 0; i < 13; i++) this.cachedMonthDateAreaLocation[i] = Point.Empty;\n }\n\n /// <summary>\n /// Gets the graphics location (x,y point) of the top left of the\n /// calendar date area for the month containing the specified date.\n /// </summary>\n private Point GetMonthDateAreaLocation(DateTime selectionDate)\n {\n\n Point monthDateAreaLocation = this.cachedMonthDateAreaLocation[selectionDate.Month];\n HitTestInfo hitInfo;\n if (!monthDateAreaLocation.IsEmpty\n && (hitInfo = this.HitTest(monthDateAreaLocation.X, monthDateAreaLocation.Y + this.dayCellHeight))\n .HitArea == HitArea.Date\n && hitInfo.Time.Year == selectionDate.Year\n && hitInfo.Time.Month == selectionDate.Month)\n {\n\n // Use previously cached lookup\n return monthDateAreaLocation;\n\n }\n else\n {\n\n // Assume the worst (Error: empty)\n monthDateAreaLocation = this.cachedMonthDateAreaLocation[selectionDate.Month] = Point.Empty;\n\n Point monthDataAreaPoint = this.GetMonthDateAreaMiddle(selectionDate);\n if (monthDataAreaPoint.IsEmpty) return Point.Empty;\n\n // Move left from the middle to find the left edge of the Date area\n monthDateAreaLocation.X = monthDataAreaPoint.X--;\n HitTestInfo hitInfo1, hitInfo2;\n while ((hitInfo1 = this.HitTest(monthDataAreaPoint.X, monthDataAreaPoint.Y))\n .HitArea == HitArea.Date\n && hitInfo1.Time.Month == selectionDate.Month\n || (hitInfo2 = this.HitTest(monthDataAreaPoint.X, monthDataAreaPoint.Y + this.dayCellHeight))\n .HitArea == HitArea.Date\n && hitInfo2.Time.Month == selectionDate.Month)\n {\n monthDateAreaLocation.X = monthDataAreaPoint.X--;\n if (monthDateAreaLocation.X < 0) return Point.Empty; // Error: bail\n }\n\n // Move up from the last column to find the top edge of the Date area\n int monthLastDayOfWeekX = monthDateAreaLocation.X + (this.dayCellWidth * 7 * 13) / 14;\n monthDateAreaLocation.Y = monthDataAreaPoint.Y--;\n while (this.HitTest(monthLastDayOfWeekX, monthDataAreaPoint.Y).HitArea == HitArea.Date)\n {\n monthDateAreaLocation.Y = monthDataAreaPoint.Y--;\n if (monthDateAreaLocation.Y < 0) return Point.Empty; // Error: bail\n }\n\n // Got it\n this.cachedMonthDateAreaLocation[selectionDate.Month] = monthDateAreaLocation;\n return monthDateAreaLocation;\n\n }\n }\n\n /// <summary>\n /// Paranoid fudge/wobble of the GetMonthDateAreaMiddle in case \n /// our first estimate to hit the month misses.\n /// (Needed? perhaps not.)\n /// </summary>\n private static Point[] searchSpiral = {\n new Point( 0, 0),\n new Point(-1,+1), new Point(+1,+1), new Point(+1,-1), new Point(-1,-1), \n new Point(-2,+2), new Point(+2,+2), new Point(+2,-2), new Point(-2,-2)\n};\n\n /// <summary>\n /// Gets a point somewhere inside the calendar date area of\n /// the month containing the given selection date.\n /// </summary>\n /// <remarks>The point returned will be HitArea.Date, and match the year and\n /// month of the selection date; otherwise it will be Point.Empty.</remarks>\n private Point GetMonthDateAreaMiddle(DateTime selectionDate)\n {\n\n // Iterate over all displayed months, and a search spiral (needed? perhaps not)\n for (int dimX = 1; dimX <= this.CalendarDimensions.Width; dimX++)\n {\n for (int dimY = 1; dimY <= this.CalendarDimensions.Height; dimY++)\n {\n foreach (Point search in searchSpiral)\n {\n\n Point monthDateAreaMiddle = new Point(\n ((dimX - 1) * 2 + 1) * this.Width / (2 * this.CalendarDimensions.Width)\n + this.dayCellWidth * search.X,\n ((dimY - 1) * 2 + 1) * this.Height / (2 * this.CalendarDimensions.Height)\n + this.dayCellHeight * search.Y);\n HitTestInfo hitInfo = this.HitTest(monthDateAreaMiddle);\n if (hitInfo.HitArea == HitArea.Date)\n {\n // Got the Date Area of the month\n if (hitInfo.Time.Year == selectionDate.Year\n && hitInfo.Time.Month == selectionDate.Month)\n {\n // For the correct month\n return monthDateAreaMiddle;\n }\n else\n {\n // Keep looking in the other months\n break;\n }\n }\n\n }\n }\n }\n return Point.Empty; // Error: not found\n\n }\n\n /// <summary>\n /// When this MonthCalendar is resized, recalculate the size of a day cell.\n /// </summary>\n private void OnSizeChanged(object sender, EventArgs e)\n {\n\n // Discard previous cached Month Area Location\n DiscardCachedMonthDateAreaLocations();\n this.dayCellWidth = this.dayCellHeight = 0;\n\n // Without this, the repaint sometimes does not happen...\n this.Invalidate();\n\n // Determine Y offset of days area\n int middle = this.Width / (2 * this.CalendarDimensions.Width);\n int dateAreaTop = 0;\n while (this.HitTest(middle, dateAreaTop).HitArea != HitArea.PrevMonthDate\n && this.HitTest(middle, dateAreaTop).HitArea != HitArea.Date)\n {\n dateAreaTop++;\n if (dateAreaTop > this.ClientSize.Height) return; // Error: bail\n }\n\n // Determine height of a single day box\n int dayCellHeight = 1;\n DateTime dayCellTime = this.HitTest(middle, dateAreaTop).Time;\n while (this.HitTest(middle, dateAreaTop + dayCellHeight).Time == dayCellTime)\n {\n dayCellHeight++;\n }\n\n // Determine X offset of days area\n middle = this.Height / (2 * this.CalendarDimensions.Height);\n int dateAreaLeft = 0;\n while (this.HitTest(dateAreaLeft, middle).HitArea != HitArea.Date)\n {\n dateAreaLeft++;\n if (dateAreaLeft > this.ClientSize.Width) return; // Error: bail\n }\n\n // Determine width of a single day box\n int dayCellWidth = 1;\n dayCellTime = this.HitTest(dateAreaLeft, middle).Time;\n while (this.HitTest(dateAreaLeft + dayCellWidth, middle).Time == dayCellTime)\n {\n dayCellWidth++;\n }\n\n // Record day box size and actual first day of the month used\n this.calendarFirstDayOfWeek = dayCellTime.DayOfWeek;\n this.dayCellWidth = dayCellWidth;\n this.dayCellHeight = dayCellHeight;\n\n }\n}\n" }, { "answer_id": 7583552, "author": "herry", "author_id": 932213, "author_profile": "https://Stackoverflow.com/users/932213", "pm_score": 1, "selected": false, "text": "Dim StartDate As Date = New DateTime(2011, 9, 21)\nDim EndDate As Date = New DateTime(2011, 9, 25)\nMonthCalendar1.SelectionRange = New SelectionRange(StartDate, EndDate)\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6255/" ]
207,309
<p>I have db table with parent child relationship as:</p> <pre><code>NodeId NodeName ParentId ------------------------------ 1 Node1 0 2 Node2 0 3 Node3 1 4 Node4 1 5 Node5 3 6 Node6 5 7 Node7 2 </code></pre> <p>Here parentId = 0 means that it is a root level node. Now I want to write an SQL Query which will return child at all level of a parent category.</p> <p>e.g. for nodeId = 1, it should return 3, 4, 5, 6.</p> <p>I am using MS SQL Server 2005 </p>
[ { "answer_id": 207324, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 4, "selected": true, "text": "with [CTE] as (\n select * from [TheTable] c where c.[ParentId] = 1\n union all\n select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]\n)\nselect * from [CTE]\n" }, { "answer_id": 828322, "author": "Coolcoder", "author_id": 42434, "author_profile": "https://Stackoverflow.com/users/42434", "pm_score": 2, "selected": false, "text": " with [CTE] as (\n select * from [TheTable] c where c.[ParentId] = 1\n union all\n select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]\n and c.[ParentId] <> c.[NodeId]\n )\n select * from [CTE]\n" }, { "answer_id": 4744637, "author": "Raju", "author_id": 582617, "author_profile": "https://Stackoverflow.com/users/582617", "pm_score": 1, "selected": false, "text": " WITH Temp_Menu AS\n ( \n SELECT AM.* from FCB_AccessMenu AM where AM.[ParentId] = 6 \n\n UNION ALL \n\n SELECT AM.* FROM FCB_AccessMenu AM ,Temp_Menu TM WHERE AM.[ParentID]=TM.[MenuID] \n\n ) \n\n SELECT * FROM Temp_Menu ORDER BY ParentID\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28243/" ]
207,337
<p>The Oracle view V$OSSTAT holds a few operating statistics, including:</p> <ul> <li>IDLE_TICKS Number of hundredths of a second that a processor has been idle, totalled over all processors</li> <li>BUSY_TICKS Number of hundredths of a second that a processor has been busy executing user or kernel code, totalled over all processors</li> </ul> <p>The documentation I've read has not been clear as to whether these are ever reset. Does anyone know?</p> <p>Another question I have is that I'd like to work out the average CPU load the system is experiencing. To do so I expect I have to go:</p> <pre><code>busy_ticks / (idle_ticks + busy_ticks) </code></pre> <p>Is this correct?</p> <p><strong>Update Nov 08</strong></p> <p>Oracle 10g r2 includes a stat called LOAD in this table. It provides the current load of the machine as at the time the value is read. This is much better than using the other information as the *_ticks data is "since instance start" not as of the current point in time.</p>
[ { "answer_id": 208455, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 3, "selected": true, "text": "SELECT (select value from v$osstat where stat_name = 'BUSY_TICKS') /\n(\n NVL((select value from v$osstat where stat_name = 'IDLE_TICKS'),0) +\n NVL((select value from v$osstat where stat_name = 'BUSY_TICKS'),0) +\n NVL((select value from v$osstat where stat_name = 'IOWAIT_TICKS'),0)\n)\nFROM DUAL;\n" }, { "answer_id": 210176, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 0, "selected": false, "text": "\"...been busy executing user or kernel code, totalled over all processors\"\n" }, { "answer_id": 210683, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 0, "selected": false, "text": "SELECT (\n(select value from v$osstat where stat_name = 'BUSY_TICKS') +\n(select value from v$osstat where stat_name = 'IOWAIT_TICKS'))\n/\n(\n NVL((select value from v$osstat where stat_name = 'IDLE_TICKS'),0) +\n NVL((select value from v$osstat where stat_name = 'BUSY_TICKS'),0) +\n NVL((select value from v$osstat where stat_name = 'IOWAIT_TICKS'),0)\n)\nFROM DUAL;\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27308/" ]
207,343
<p>I'm writing a data structure in C# (a priority queue using a <a href="http://en.wikipedia.org/wiki/Fibonacci_heap" rel="nofollow noreferrer">fibonacci heap</a>) and I'm trying to use it as a learning experience for TDD which I'm quite new to. </p> <p>I understand that each test should only test one piece of the class so that a failure in one unit doesn't confuse me with multiple test failures, but I'm not sure how to do this when the state of the data structure is important for a test. </p> <p>For example, </p> <pre><code>private PriorityQueue&lt;int&gt; queue; [SetUp] public void Initialize() { this.queue = new PriorityQueue&lt;int&gt;(); } [Test] public void PeekShouldReturnMinimumItem() { this.queue.Enqueue(2); this.queue.Enqueue(1); Assert.That(this.queue.Peek(), Is.EqualTo(1)); } </code></pre> <p>This test would break if either <code>Enqueue</code> or <code>Peek</code> broke. </p> <p>I was thinking that I could somehow have the test manually set up the underlying data structure's heap, but I'm not sure how to do that without exposing the implementation to the world.</p> <p>Is there a better way to do this? Is relying on other parts ok? </p> <p>I have a <code>SetUp</code> in place, just left it out for simplicity.</p>
[ { "answer_id": 207350, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "SetUp TearDown" }, { "answer_id": 207366, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 2, "selected": false, "text": "Enqueue Peek Dequeue Count Enqueue Enqueue" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9617/" ]
207,404
<p>In Groovy, how do I grab a web page and remove HTML tags, etc., leaving only the document's text? I'd like the results dumped into a collection so I can build a word frequency counter.</p> <p>Finally, let me mention again that I'd like to do this in Groovy.</p>
[ { "answer_id": 209245, "author": "mbrevoort", "author_id": 18228, "author_profile": "https://Stackoverflow.com/users/18228", "pm_score": 1, "selected": false, "text": "def records = new XmlSlurper().parseText(YOURHTMLSTRING)\ndef allNodes = records.depthFirst().collect{ it }\ndef list = []\nallNodes.each {\n it.text().tokenize().each {\n list << it\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,454
<p>I've been trying to programatically feed the paper on a pos printer (Epson TM-U220D). The problem I have is that the last line of the document don't get printed, instead, it is printed as the first line of the next document printed. I tried POS for .NET sending the "ESC|flF" command, also tried to send the raw esc/pos command using the serial port, but it doesn't work. Any ideas?</p>
[ { "answer_id": 207527, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 0, "selected": false, "text": "\"ECHO \" & Chr(12) & \">LPT1\"\n" }, { "answer_id": 207586, "author": "alexandrul", "author_id": 19756, "author_profile": "https://Stackoverflow.com/users/19756", "pm_score": 2, "selected": false, "text": "ESC/POS Application Programming Guide FAQ for ESC/POS LF ASCII: LF Hex: 0A Decimal: 10" }, { "answer_id": 207626, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 0, "selected": false, "text": "fprintf(printerfile,\"%c\",12);\n fprintf(printerfile,\"%c%c\",12,13);\nfflush(printerfile);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26727/" ]
207,464
<p>I'm refactoring a number of classes in an application to use interfaces instead of base classes. Here's the interfaces I created so far:</p> <ul> <li>ICarryable implemented by all Item objects </li> <li>IActable implemented by all Actor objects</li> <li>IUseable implemented by some Item sub-classes</li> <li>IWieldable implemented by some Item sub-classes</li> </ul> <p>You can see the major base-classes are still Item and Actor. These have a common interface in that they both are located on a Map, so they have a Location property. The Map shouldn't care whether the object is an Actor or an Item, so I want to create an interface for it. Here's what the interface would look like</p> <pre><code>public interface IUnnameable { event EventHandler&lt;LocationChangedEventArgs&gt; LocationChanged; Location Location { get; set; } } </code></pre> <p>That's no problem, but I can't think of what to call this interface. IMappable comes to mind by seems a bit lame. Any ideas?</p>
[ { "answer_id": 207489, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 1, "selected": false, "text": "ICanHasLocation IHasLocation ImInYourProgramHavingALocation" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103052/" ]
207,477
<p>I'm looking for a reasonable way to represent searches as a RESTful URLs.</p> <p>The setup: I have two models, Cars and Garages, where Cars can be in Garages. So my urls look like:</p> <pre><code>/car/xxxx xxx == car id returns car with given id /garage/yyy yyy = garage id returns garage with given id </code></pre> <p>A Car can exist on its own (hence the /car), or it can exist in a garage. What's the right way to represent, say, all the cars in a given garage? Something like:</p> <pre><code>/garage/yyy/cars ? </code></pre> <p>How about the union of cars in garage yyy and zzz?</p> <p>What's the right way to represent a search for cars with certain attributes? Say: show me all blue sedans with 4 doors :</p> <pre><code>/car/search?color=blue&amp;type=sedan&amp;doors=4 </code></pre> <p>or should it be /cars instead?</p> <p>The use of "search" seems inappropriate there - what's a better way / term? Should it just be:</p> <pre><code>/cars/?color=blue&amp;type=sedan&amp;doors=4 </code></pre> <p>Should the search parameters be part of the PATHINFO or QUERYSTRING?</p> <p>In short, I'm looking for guidance for cross-model REST url design, and for search.</p> <p>[Update] I like Justin's answer, but he doesn't cover the multi-field search case:</p> <pre><code>/cars/color:blue/type:sedan/doors:4 </code></pre> <p>or something like that. How do we go from</p> <pre><code>/cars/color/blue </code></pre> <p>to the multiple field case?</p>
[ { "answer_id": 207493, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": -1, "selected": false, "text": "/garages\n Returns list of garages (think JSON array here)\n/garages/yyy\n Returns specific garage\n/garage/yyy/cars\n Returns list of cars in garage\n/garages/cars\n Returns list of all cars in all garages (may not be practical of course)\n/cars\n Returns list of all cars\n/cars/xxx\n Returns specific car\n/cars/colors\n Returns lists of all posible colors for cars\n/cars/colors/red,blue,green\n Returns list of cars of the specific colors (yes commas are allowed :) )\n /cars/colors/red,blue,green/doors/2\n Returns list of all red,blue, and green cars with 2 doors.\n/cars/type/hatchback,coupe/colors/red,blue,green/\n Same idea as the above but a lil more intuitive.\n/cars/colors/red,blue,green/doors/two-door,four-door\n All cars that are red, blue, green and have either two or four doors.\n" }, { "answer_id": 208090, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 4, "selected": false, "text": "/search/{searchQuery}\n /search/{savedSearchName}\n" }, { "answer_id": 926706, "author": "Doug Domeny", "author_id": 113701, "author_profile": "https://Stackoverflow.com/users/113701", "pm_score": 5, "selected": false, "text": "/cars/doors/driver/lock/combination combination /car/doors[id='driver' and lock/combination='1234'] /cars/colors /cars/colors/red,blue,green /cars?color=red,blue,green /cars/search?color=red,blue,green /garages/yyy/cars /garage/yyy/cars /person/yyy/friends /people/yyy" }, { "answer_id": 926793, "author": "Rich Apodaca", "author_id": 54426, "author_profile": "https://Stackoverflow.com/users/54426", "pm_score": 5, "selected": false, "text": "POST /searches # create a new search\nGET /searches # list all searches (admin)\nGET /searches/{id} # show the results of a previously-run search\nDELETE /searches/{id} # delete a search (admin)\n" }, { "answer_id": 1081720, "author": "pbreitenbach", "author_id": 42048, "author_profile": "https://Stackoverflow.com/users/42048", "pm_score": 10, "selected": true, "text": "/cars?color=blue&type=sedan&doors=4\n" }, { "answer_id": 15433368, "author": "Qwerty", "author_id": 985454, "author_profile": "https://Stackoverflow.com/users/985454", "pm_score": 7, "selected": false, "text": "/ -id /garage-id/cars/car-id\n/cars/car-id #for cars not in garages\n /car-id cars /car-id /car/id /cars?color=blue;type=sedan #most prefered by me\n/cars;color-blue+doors-4+type-sedan #looks good when using car-id\n/cars?color=blue&doors=4&type=sedan #also possible, but & blends in with text\n /cars[?;]color[=-:]blue[,;+&] & /cars?color=black,blue,red;doors=3,5;type=sedan #most prefered by me\n/cars?color:black:blue:red;doors:3:5;type:sedan\n/cars?color(black,blue,red);doors(3,5);type(sedan) #does not look bad at all\n/cars?color:(black,blue,red);doors:(3,5);type:sedan #little difference\n ?color=!black,!red color:(!black,!red) /garage[id=1-20,101-103,999,!5]/cars[color=red,blue,black;doors=3] user*=bar /directory/file /collection/node/item /articles/{year}/{month}/{day} a-zA-Z0-9_.-~ $-_.+!*'(), ;/?:@=& <>\"#%{}|^~[]` :/?#[]@ !$&'()*+,;=" }, { "answer_id": 26301675, "author": "user2108278", "author_id": 2108278, "author_profile": "https://Stackoverflow.com/users/2108278", "pm_score": 3, "selected": false, "text": " /cars?q.garage.id.eq=1\n /cars?q.garage.street.eq=FirstStreet&q.color.ne=red&offset=300&max=100\n POST /searches => Create\n GET /searches/1 => Recover search\n GET /searches/1?offset=300&max=100 => pagination in search\n { \n \"$class\":\"test.Car\",\n \"$q\":{\n \"$eq\" : { \"color\" : \"red\" },\n \"garage\" : {\n \"$ne\" : { \"street\" : \"FirstStreet\" }\n }\n }\n }\n" }, { "answer_id": 34754395, "author": "aux", "author_id": 1293433, "author_profile": "https://Stackoverflow.com/users/1293433", "pm_score": 2, "selected": false, "text": "/cars/search/all{?color,model,year}\n/cars/search/by-parameters{?color,model,year}\n/cars/search/by-vendor{?vendor}\n Search Cars" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
207,485
<p>When you plot things in Matlab, the most recently plotted data series is placed on top of whatever's already there. For example:</p> <pre><code>figure; hold on plot(sin(linspace(0,pi)),'linewidth',4,'color',[0 0 1]) plot(cos(linspace(0,pi)),'linewidth',4,'color',[1 0 0]) </code></pre> <p>Here, the red line is shown on top of the blue line (where they intersect). Is there any way to set "how deep" a line is drawn, so that you can plot things <em>beneath</em> what's already there?</p>
[ { "answer_id": 207603, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 5, "selected": true, "text": "h1 = plot(1:10, 'b');\nhold on;\nh2 = plot(1:10, 'r');\n uistack(h1);\n" }, { "answer_id": 207828, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 2, "selected": false, "text": "figure; hold on\nh1 = plot(sin(linspace(0,pi)),'linewidth',4,'color',[0 0 1]);\nh2 = plot(cos(linspace(0,pi)),'linewidth',4,'color',[1 0 0]);\nh = get(gca, 'Children');\n h = flipud(h);\nset(gca, 'Children', h);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
207,490
<p>I am working on a new version of a firefox extension, but after releasing it, and incrementing the em:version in install.rdf and update.rdf, when I click "Find updates" Firefox reports that "No updates were found." When I run it with debugging on, the output in the console is actually identical to what I see when I don't put the update live. </p> <p>It starts with RDFItemUpdater:checkForUpdates with all of the parameters, and returns with Addon Update Ended and status: 8.</p> <p>I verified with McCoy tool that the extension is signed, and has the same Id as the old one, etc. I'm not sure what else to try. Any advice would be appreciated. This is with Firefox 3 (and the extension is marked as compatible with it... that didn't change).</p>
[ { "answer_id": 2410957, "author": "Jason", "author_id": 7745, "author_profile": "https://Stackoverflow.com/users/7745", "pm_score": 0, "selected": false, "text": "minVersion=\"3.0.*\" minVersion=\"3.0\"" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26624/" ]
207,494
<p>Its a little tricky to search for 'var:*' because most search engines wont find it.</p> <p>I'm not clear exactly what var:* means, compared to say var:Object</p> <p>I thought it would let me set arbitrary properties on an object like :</p> <pre><code>var x:* = myObject; x.nonExistantProperty = "123"; </code></pre> <p>but this gives me an error :</p> <pre><code>Property nonExistantProperty not found on x </code></pre> <p>What does * mean exactly?</p> <p><strong>Edit:</strong> I fixed the original var:* to the correct var x:*. Lost my internet connection</p>
[ { "answer_id": 207505, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 1, "selected": false, "text": "var x = myObject;\n" }, { "answer_id": 207508, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 1, "selected": false, "text": "var x:*;\n" }, { "answer_id": 207556, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "var x:* = oneTypeObject;\n oneTypeObject var x:* = anotherTypeObject;\n oneTypeObject anotherTypeObject x" }, { "answer_id": 210780, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 4, "selected": false, "text": "var x:* = {};\nvar y = {}; // equivalent\n var o:Object = {};\no.foo = 1; // fine\nvar a:* = o;\na.bar = 1; // again, fine\n\nvar s:String = \"\";\ns.foo = 1; // compile-time error\nvar b:* = s;\nb.bar = 1; // run-time error\n b" }, { "answer_id": 14883943, "author": "Nathan", "author_id": 2073542, "author_profile": "https://Stackoverflow.com/users/2073542", "pm_score": 0, "selected": false, "text": "var untyped:* = functionThatReturnsSomeValue();\n var name:String = untyped.name;\n (elsewhere)\npublic class TypedObject()\n{\n public var name:String = \"\";\n}\n\n(and the code at hand)\nvar typed:TypedObject = functionThatReturnsTypedObject();\nvar name:String = typed.name;\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
207,496
<p>So my code is below. I'm not getting any errors and it places everything in the node just fine. But based on my debug statements Everytime anything is inserted it's finding the root. I'm not sure if that is right. But according to output file for the assignment, my answers are different when it comes to the height of the tree, the traversals, and I just flat am still having troubles with my leaf count function. Another story though.</p> <p>Based on the debug statements it looks like everything is going right where they should. But I figure I might need fresh eyes. I don't see how my traversals could change at all since it is really only a matter of where I'm proccessing the node that should effect the Inorder, preorder, and postorder. </p> <pre><code>template &lt;class T&gt; void BT&lt;T&gt;::insert(const T&amp; item) { Node&lt;T&gt;* newNode; newNode = new Node&lt;T&gt;(item); insert(root, newNode); } template &lt;class T&gt; void BT&lt;T&gt;::insert(struct Node&lt;T&gt; *&amp;root, struct Node&lt;T&gt; *newNode) { if (root == NULL) { cout &lt;&lt; "Root Found" &lt;&lt; newNode-&gt;data &lt;&lt; endl; root = newNode; } else { if (newNode-&gt;data &lt; root-&gt;data) { insert(root-&gt;left, newNode); cout &lt;&lt; "Inserting Left" &lt;&lt; newNode-&gt; data &lt;&lt; endl; } else { insert(root-&gt;right, newNode); cout &lt;&lt; "Inserting Right" &lt;&lt; newNode-&gt;data &lt;&lt; endl; } } } </code></pre> <p>My height function is as follows just in case my insert is actually fine.</p> <pre><code>template &lt;class T&gt; int BT&lt;T&gt;::height() const { return height(root); } template &lt;class T&gt; int BT&lt;T&gt;::height(Node&lt;T&gt;* root) const { if (root == NULL) return 0; else { if (height(root-&gt;right) &gt; height(root-&gt;left)) return 1 + height(root-&gt; right); return 1 + height(root-&gt;left); } } </code></pre>
[ { "answer_id": 207503, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": true, "text": " cout << \"Leaf Node Found\" << newNode->data << endl;\n template <class T>\nint BT<T>::height(Node<T>* root) const\n{\n if (root == NULL) {return 0;}\n\n return 1 + max(height(root->left),height(root->right));\n}\n" }, { "answer_id": 207580, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "template <class T>\nvoid BT<T>::BT() \n{ root = 0;}\n\ntemplate <class T>\nvoid BT<T>::insert(const T& item)\n {\n Node<T>* newNode;\n newNode = new Node<T>(item);\n insert(root, newNode);\n }\n\ntemplate <class T>\nvoid BT<T>::insert(struct Node<T> *root, struct Node<T> *newNode)\n{\n /*stuff*/\n}\n" }, { "answer_id": 207614, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "template <class T>\nvoid BT<T>::insert(struct Node<T>** root, struct Node<T>* newNode)\n {\n if (*root == NULL)\n {\n cout << \"Root Found\" << newNode->data << endl;\n *root = newNode;\n }\n insert(&root, newNode);\n template class<T>\nvoid printTree(struct Node<T>* node, int level=0)\n{\n if (!node) {\n for (int i=0; i<level; ++i)\n cout << \" \";\n cout << \"NULL\" << endl;\n\n return;\n }\n\n printTree(node->left, level+1);\n\n for (int i=0; i<level; ++i)\n cout << \" \";\n cout << node->data << endl;\n\n printTree(node->right, level+1);\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28392/" ]
207,497
<p>I am looking to set full trust for a single web part, is this possible? manifest.xml maybe?</p>
[ { "answer_id": 207515, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 2, "selected": true, "text": "gacutil.exe \\i C:\\Path\\To\\Dll.dll\n" }, { "answer_id": 207641, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 1, "selected": false, "text": "STSADM -o addwppack -filename yourwebpart.cab -globalinstall\n <Assembly Location=\"yourassembly.dll\" DeploymentTarget=\"GlobalAssemblyCache\">\n STSADM -o AddSolution -filename yourwebpart.wsp\n\nSTSADM -o DeploySolution -name yourwebpart.wsp -allcontenturls -immediate -force -allowGacDeployment\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
207,498
<p>I am running both maven inside the m2eclipse plugin, windows command line and my cygwin command line.</p> <p>cygwin's bash shell dumps artifacts into the cygwin /home/me/.m2 directory</p> <p>but m2eclipse &amp; windows shell (on vista) uses /Users/me/Documents/.m2</p> <p>Is it possible to tell the mvn command to use one central .m2 directory ?</p> <p>Thanks</p>
[ { "answer_id": 207559, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 4, "selected": false, "text": "<settings xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n <localRepository>/my/secret/repository</localRepository>\n</settings>\n" }, { "answer_id": 207573, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 4, "selected": true, "text": "MAVEN_OPTS=\"-Dmaven.repo.local=c:\\documents and settings\\user\\.m2\\repository\"\nexport MAVEN_OPTS\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24457/" ]
207,504
<p>I have a UserControl with some predefined controls (groupbox,button,datagridview) on it, these controls are marked as protected and the components variable is also marked as protected.</p> <p>I then want to inherit from this base UserControl to another UserControl, however the DataGridView is always locked in the designer.</p> <p>I suspect it may have something to do with the DataGridView implementing ISupportInitilize.</p> <pre><code>public class BaseGridDetail : UserControl </code></pre> <p>Has a DataGridView control (et al) defined.</p> <p><br></p> <pre><code>public class InheritedDetail : BaseGridDetail </code></pre> <p>The DataGridView control is locked</p> <p><br>Does anyone have any ideas how to make this control available in the designer after inheritenace?</p>
[ { "answer_id": 207511, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "// in base UserControl\npublic BaseGridDetail()\n{\n InitializeComponent();\n\n InitGridColumns(dataGridView1.Columns);\n}\n\nprotected virtual void InitGridColumns(DataGridViewColumnCollection columns)\n{\n columns.Clear();\n}\n // in InheritedDetail\nprotected override void InitGridColumns(DataGridViewColumnCollection columns)\n{\n base.InitGridColumns(columns);\n // add my own custom columns\n}\n" }, { "answer_id": 3649360, "author": "Robocide", "author_id": 179744, "author_profile": "https://Stackoverflow.com/users/179744", "pm_score": 3, "selected": false, "text": "[Designer(typeof System.Windows.Forms.Design.ControlDesigner))]\npublic class InheritedDataGridView : DataGridView { }\n" }, { "answer_id": 38318390, "author": "Na Youngmin", "author_id": 6576986, "author_profile": "https://Stackoverflow.com/users/6576986", "pm_score": -1, "selected": false, "text": " private System.Windows.Forms.Button btnSave;\n protected System.Windows.Forms.Button btnSave;\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
207,510
<p>If I click on File -> Close, it closes the buffer like I want, but doesn't list a key mapping. What is the key mapping?</p>
[ { "answer_id": 207610, "author": "Miserable Variable", "author_id": 18573, "author_profile": "https://Stackoverflow.com/users/18573", "pm_score": 5, "selected": false, "text": "C-h b" }, { "answer_id": 12098186, "author": "Anish", "author_id": 1389198, "author_profile": "https://Stackoverflow.com/users/1389198", "pm_score": 8, "selected": true, "text": "C-x k" }, { "answer_id": 17936850, "author": "Sazid", "author_id": 1941132, "author_profile": "https://Stackoverflow.com/users/1941132", "pm_score": 5, "selected": false, "text": "Help kill-buffer" }, { "answer_id": 26592985, "author": "David J.", "author_id": 109618, "author_profile": "https://Stackoverflow.com/users/109618", "pm_score": 5, "selected": false, "text": "M-x kill-this-buffer s-k" }, { "answer_id": 63972550, "author": "nomad", "author_id": 12207627, "author_profile": "https://Stackoverflow.com/users/12207627", "pm_score": 3, "selected": false, "text": "C-x k C-x 0 C-x 1" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4960/" ]
207,513
<p>Is there any tool that enables you to "hot swap" JavaScript contents while executing a webpage? </p> <p>I am looking for something similar to what HotSpot does for Java, a way to "hot deploy" new JS code without having to reload the whole page.</p> <p>Is there anything like that out there?</p> <p><strong>Clarifying in case people don't understand "hot swap", as indicated by <em>lock</em>:</strong></p> <p>By "hot swap" I mean allowing me to change parts of the code contained on the page itself and its .js files. </p> <p>Then this framework would detect the change - either automagically or by some indication from my end - and reload the code dynamically, avoiding the new server-side post (reload). </p> <p>That kind of approach would simplify debugging and error fixing, since you don't need to reload the page and start the interaction all over again, from scratch.</p>
[ { "answer_id": 207769, "author": "Erlend Halvorsen", "author_id": 1920, "author_profile": "https://Stackoverflow.com/users/1920", "pm_score": 3, "selected": true, "text": "function reload(){var scripts=document.getElementsByTagName(\"script\");var head=document.getElementsByTagName(\"head\")[0];var newScripts=[];var removeScripts=[];for(var i=0;i<scripts.length;i++){var parent=scripts[i].parentNode;if(parent==head&&scripts[i].src){var newScript={};newScript.src=scripts[i].src;newScript.innerHTML=scripts[i].innerHTML;newScripts.push(newScript);removeScripts.push(scripts[i]);}}for(var i=0;i<removeScripts.length;i++){head.removeChild(removeScripts[i]);}for(var i=0;i<newScripts.length;i++){var script=document.createElement(\"script\");script.src=newScripts[i].src;script.type=\"text/javascript\";script.innerHTML=newScripts[i].innerHTML;head.appendChild(script);}}\n function reload() {\n var scripts = document.getElementsByTagName(\"script\");\n var head = document.getElementsByTagName(\"head\")[0];\n var newScripts = [];\n var removeScripts = [];\n for(var i=0; i < scripts.length; i++) {\n var parent = scripts[i].parentNode;\n if(parent == head && scripts[i].src) {\n var newScript = {};\n newScript.src = scripts[i].src;\n newScript.innerHTML = scripts[i].innerHTML;\n newScripts.push(newScript);\n removeScripts.push(scripts[i]);\n }\n }\n\n for(var i=0; i < removeScripts.length; i++) {\n head.removeChild(removeScripts[i]);\n }\n\n for(var i=0; i < newScripts.length; i++) {\n var script = document.createElement(\"script\");\n script.src = newScripts[i].src;\n script.type = \"text/javascript\";\n script.innerHTML = newScripts[i].innerHTML;\n head.appendChild(script);\n }\n}\n" }, { "answer_id": 22435892, "author": "geoathome", "author_id": 3351763, "author_profile": "https://Stackoverflow.com/users/3351763", "pm_score": 2, "selected": false, "text": "<script src=\"hotswap.js\"></script>\n // refresh .js files\nhotswap.refreshAllJs(arrExcludedFiles);\nhotswap.refreshJs(arrIncludedFiles);\n\n// refresh .css files\nhotswap.refreshAllCss(arrExcludedFiles);\nhotswap.refreshCss(arrIncludedFiles);\n\n// refresh images\nhotswap.refreshAllImg(arrExcludedFiles);\nhotswap.refreshImg(arrIncludedFiles);\n\n// show a gui (this is optional and not required for hotswap to work) (Click on the \"H\").\nhotswap.createGui();\n\n// Examples:\n// refresh all .js files\nhotswap.refreshAllJs();\n\n// refresh main.css only\nhotswap.refreshCss( [\"main.js\"] );\n\n// refresh all images (img tags) except \"dont-refreh-me.png\".\nhotswap.refreshAllImg( [\"dont-refreh-me.png\"] );\n (function() {\n var root = this;\n var previousHotswap = root.hotswap;\n var hotswap = function()\n {\n if (!(this instanceof hotswap))\n {\n return new hotswap();\n }\n else\n {\n return this;\n }\n };\n root.hotswap = hotswap();\n hotswap.prototype.VERSION = '0.2.0';\n hotswap.prototype.RND_PARAM_NAME = 'hs982345jkasg89zqnsl';\n hotswap.prototype.FILE_REMOVAL_DELAY = 400;\n hotswap.prototype.CSS_HTML_PREFIX = 'hs982345jkasg89zqnsl';\n hotswap.prototype._prefix = false;\n hotswap.prototype._prefixCache = [];\n hotswap.prototype._guiCache = {};\n hotswap.prototype._guiGuiRefreshInterval = null;\n hotswap.prototype._guiHtml = '' +\n '<style type=\"text/css\">'+\n ' #PREFIX'+\n ' {'+\n ' display: block;'+\n ' position: fixed;'+\n ' top: 20%;/*distance from top*/'+\n ' right: 0;'+\n ' z-index: 99999;'+\n ' width: 20em;'+\n ' height: auto;'+\n ' color: black;'+\n ' background-color: #666666;'+\n ' font-family: Verdana, sans-serif;'+\n ' font-size: 0.8em;'+\n ' -webkit-box-shadow: 0 0px 0.3em 0.1em #999999;'+\n ' -moz-box-shadow: 0 0px 0.3em 0.1em #999999;'+\n ' box-shadow: 0 0px 0.3em 0.1em #999999;'+\n ' }'+\n ' #PREFIX.mini'+\n ' {'+\n ' width: 2.9em;'+\n ' height: 2.9em;'+\n ' overflow:hidden;'+\n ' }'+\n ' #PREFIX.mini .PREFIX-header input, #PREFIX.mini .PREFIX-list, #PREFIX.mini .PREFIX-footer'+\n ' {'+\n ' display:none;'+\n ' }'+\n ' #PREFIX.mini .PREFIX-header div'+\n ' {'+\n ' display: block;'+\n ' width: 100%;'+\n ' height: 100%;'+\n ' }'+\n ' #PREFIX input'+\n ' {'+\n ' font-size: 1.0em;'+\n ' border: 0.1em solid #999999;'+\n ' border-radius: 0.2em;'+\n ' padding: 0.2em 0.1em;'+\n ' }'+\n ' #PREFIX .PREFIX-header'+\n ' {'+\n ' height: 2.4em;'+\n ' overflow:hidden;'+\n ' padding: 0.4em;'+\n ' color: white;'+\n ' background-color: black;'+\n ' }'+\n ' #PREFIX .PREFIX-header input'+\n ' {'+\n ' width: 83.5%;'+\n ' height: 1.6em;'+\n ' }'+\n ' #PREFIX .PREFIX-header div'+\n ' {'+\n ' position: absolute;'+\n ' top:0;'+\n ' right:0;'+\n ' width: 14.5%;'+\n ' height: 1.6em;'+\n ' line-height: 1.4em;'+\n ' text-align: center;'+\n ' font-size: 2em;'+\n ' font-weight: bold;'+\n ' cursor: pointer;'+\n ' }'+\n ' #PREFIX .PREFIX-header div:hover'+\n ' {'+\n ' background-color: #444444;'+\n ' }'+\n ' #PREFIX .PREFIX-list'+\n ' {'+\n ' width: 100%;'+\n ' height: 22em;'+\n ' overflow: auto;'+\n ' }'+\n ' #PREFIX ul'+\n ' {'+\n ' list-style-type: none;'+\n ' list-style-position: inside;'+\n ' padding: 0;'+\n ' margin: 0.5em 0.5em 1.2em 0.5em;'+\n ' }'+\n ' #PREFIX ul li'+\n ' {'+\n ' margin: 0.3em;'+\n ' padding: 0.5em 0.5em;'+\n ' color: white;'+\n ' background-color: #717171;'+\n ' font-size: 0.9em;'+\n ' line-height: 1.5em;'+\n ' cursor: pointer;'+\n ' }'+\n ' #PREFIX ul li:hover'+\n ' {'+\n ' background-color: #797979;'+\n ' }'+\n ' #PREFIX ul li.template'+\n ' {'+\n ' display: none;'+\n ' }'+\n ' #PREFIX ul li.active'+\n ' {'+\n ' background-color: black;'+\n ' }'+\n ' #PREFIX ul li.PREFIX-headline'+\n ' {'+\n ' color: white;'+\n ' background-color: transparent;'+\n ' text-align: center;'+\n ' font-weight: bold;'+\n ' cursor: default;'+\n ' }'+\n ' #PREFIX .PREFIX-footer'+\n ' {'+\n ' padding: 0;'+\n ' margin:0;'+\n ' background-color: #444444;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul'+\n ' {'+\n ' margin: 0;'+\n ' padding: 0.5em;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul li'+\n ' {'+\n ' color: white;'+\n ' background-color: black;'+\n ' font-size: 1.0em;'+\n ' border-radius: 0.5em;'+\n ' text-align: center;'+\n ' height: 2.2em;'+\n ' line-height: 2.2em;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul li input.PREFIX-seconds'+\n ' {'+\n ' text-align: center;'+\n ' width: 2em;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul li:hover'+\n ' {'+\n ' background-color: #222222;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul li.inactive'+\n ' {'+\n ' background-color: #666666;'+\n ' cursor: default;'+\n ' }'+\n ' </style>'+\n ' <div id=\"PREFIX\" class=\"mini\">'+\n ' <div class=\"PREFIX-header\">'+\n ' <input id=\"PREFIX-prefix\" placeholder=\"prefix\" type=\"text\" name=\"\" />'+\n ' <div id=\"PREFIX-toggle\">H</div>'+\n ' </div>'+\n ' <div class=\"PREFIX-list\">'+\n ' <ul id=\"PREFIX-css\">'+\n ' <li class=\"PREFIX-headline\">CSS</li>'+\n ' <li class=\"template\"></li>'+\n ' </ul>'+\n ' <ul id=\"PREFIX-js\">'+\n ' <li class=\"PREFIX-headline\">JS</li>'+\n ' <li class=\"template\"></li>'+\n ' </ul>'+\n ' <ul id=\"PREFIX-img\">'+\n ' <li class=\"PREFIX-headline\">IMG</li>'+\n ' <li class=\"template\"></li>'+\n ' </ul>'+\n ' </div>'+\n ' <div class=\"PREFIX-footer\">'+\n ' <ul>'+\n ' <li id=\"PREFIX-submit-selected\">refresh selected</li>'+\n ' <li id=\"PREFIX-submit-start\">refresh every <input class=\"PREFIX-seconds\" type=\"text\" value=\"1\" /> sec.</li>'+\n ' <li id=\"PREFIX-submit-stop\" class=\"inactive\">stop refreshing</li>'+\n ' <li id=\"PREFIX-submit-refresh-list\">refresh list</li>'+\n ' </ul>'+\n ' </div>'+\n ' </div>';\n var\n xGetElementById = function(sId){ return document.getElementById(sId) },\n xGetElementsByTagName = function(sTags){ return document.getElementsByTagName(sTags) },\n xAppendChild = function(parent, child){ return parent.appendChild(child) },\n xCloneNode = function(node){ return document.cloneNode(node) },\n xCreateElement = function(sTag){ return document.createElement(sTag) },\n xCloneNode = function(ele, deep){ return ele.cloneNode(deep) },\n xRemove = function(ele)\n {\n if( typeof ele.parentNode != \"undefined\" && ele.parentNode )\n {\n ele.parentNode.removeChild( ele );\n }\n },\n xAddEventListener = function(ele, sEvent, fn, bCaptureOrBubble)\n {\n if( xIsEmpty(bCaptureOrBubble) )\n {\n bCaptureOrBubble = false;\n }\n if (ele.addEventListener)\n {\n ele.addEventListener(sEvent, fn, bCaptureOrBubble);\n return true;\n }\n else if (ele.attachEvent)\n {\n return ele.attachEvent('on' + sEvent, fn);\n }\n else\n {\n ele['on' + sEvent] = fn;\n }\n },\n xStopPropagation = function(evt)\n {\n if (evt && evt.stopPropogation)\n {\n evt.stopPropogation();\n }\n else if (window.event && window.event.cancelBubble)\n {\n window.event.cancelBubble = true;\n }\n },\n xPreventDefault = function(evt)\n {\n if (evt && evt.preventDefault)\n {\n evt.preventDefault();\n }\n else if (window.event && window.event.returnValue)\n {\n window.eventReturnValue = false;\n }\n },\n xContains = function(sHaystack, sNeedle)\n {\n return sHaystack.indexOf(sNeedle) >= 0\n },\n xStartsWith = function(sHaystack, sNeedle)\n {\n return sHaystack.indexOf(sNeedle) === 0\n },\n xReplace = function(sHaystack, sNeedle, sReplacement)\n {\n if( xIsEmpty(sReplacement) )\n {\n sReplacement = \"\";\n }\n return sHaystack.split(sNeedle).join(sReplacement);\n },\n xGetAttribute = function(ele, sAttr)\n {\n var result = (ele.getAttribute && ele.getAttribute(sAttr)) || null;\n if( !result ) {\n result = ele[sAttr];\n }\n if( !result ) {\n var attrs = ele.attributes;\n var length = attrs.length;\n for(var i = 0; i < length; i++)\n if(attrs[i].nodeName === sAttr)\n result = attrs[i].nodeValue;\n }\n return result;\n },\n xSetAttribute = function(ele, sAttr, value)\n {\n if(ele.setAttribute)\n {\n ele.setAttribute(sAttr, value)\n }\n else\n {\n ele[sAttr] = value;\n }\n },\n xGetParent = function(ele)\n {\n return ele.parentNode || ele.parentElement;\n },\n xInsertAfter = function( refEle, newEle )\n {\n return xGetParent(refEle).insertBefore(newEle, refEle.nextSibling);\n },\n xBind = function(func, context)\n {\n if (Function.prototype.bind && func.bind === Function.prototype.bind)\n {\n return func.bind(context);\n }\n else\n {\n return function() {\n if( arguments.length > 2 )\n {\n return func.apply(context, arguments.slice(2));\n }\n else\n {\n return func.apply(context);\n }\n };\n }\n },\n xIsEmpty = function(value)\n {\n var ret = true;\n if( value instanceof Object )\n {\n for(var i in value){ if(value.hasOwnProperty(i)){return false}}\n return true;\n }\n ret = typeof value === \"undefined\" || value === undefined || value === null || value === \"\";\n return ret;\n },\n xAddClass = function(ele, sClass)\n {\n var clazz = xGetAttribute( ele, \"class\" );\n if( !xHasClass(ele, sClass) )\n {\n xSetAttribute( ele, \"class\", clazz + \" \" + sClass );\n }\n },\n xRemoveClass = function(ele, sClass)\n {\n var clazz = xGetAttribute( ele, \"class\" );\n if( xHasClass(ele, sClass) )\n {\n xSetAttribute( ele, \"class\", xReplace( clazz, sClass, \"\" ) );\n }\n },\n xHasClass = function(ele, sClass)\n {\n var clazz = xGetAttribute( ele, \"class\" );\n return !xIsEmpty(clazz) && xContains( clazz, sClass );\n };\n hotswap.prototype._recreate = function( type, xcludedFiles, xcludeComparator, nDeleteDelay, bForceRecreation )\n {\n if( typeof nDeleteDelay == \"undefined\")\n {\n nDeleteDelay = 0;\n }\n\n if( typeof bForceRecreation == \"undefined\")\n {\n bForceRecreation = false;\n }\n\n var tags = this._getFilesByType(type, xcludedFiles, xcludeComparator);\n var newTags = [];\n var removeTags = [];\n var i, src, detected, node, srcAttributeName;\n for(i=0; i<tags.length; i++)\n {\n node = tags[i].node;\n srcAttributeName = tags[i].srcAttributeName;\n var newNode = {\n node: null,\n oldNode: node,\n parent: xGetParent(node)\n };\n if( bForceRecreation )\n {\n newNode.node = xCreateElement(\"script\");\n }\n else\n {\n newNode.node = xCloneNode(node, false);\n }\n for (var p in node) {\n if (node.hasOwnProperty(p)) {\n newNode.node.p = node.p;\n }\n }\n src = xGetAttribute( node, srcAttributeName );\n xSetAttribute( newNode.node, srcAttributeName, this._updatedUrl(src) );\n newTags.push(newNode);\n removeTags.push(node);\n }\n for(var i=0; i < newTags.length; i++) {\n xInsertAfter(newTags[i].oldNode, newTags[i].node);\n }\n if( nDeleteDelay > 0 )\n {\n for(var i=0; i < removeTags.length; i++) {\n xSetAttribute(removeTags[i], \"data-hotswap-deleted\", \"1\");\n }\n\n setTimeout( function() {\n for(var i=0; i < removeTags.length; i++) {\n xRemove(removeTags[i]);\n }\n }, nDeleteDelay);\n }\n else\n {\n for(var i=0; i < removeTags.length; i++) {\n xRemove(removeTags[i]);\n }\n }\n };\n hotswap.prototype._reload = function( type, xcludedFiles, xcludeComparator )\n {\n var tags = this._getFilesByType(type, xcludedFiles, xcludeComparator);\n var i, src, node, srcAttributeName;\n for(i=0; i<tags.length; i++)\n {\n node = tags[i].node;\n srcAttributeName = tags[i].srcAttributeName;\n // update the src property\n src = xGetAttribute( node, srcAttributeName );\n xSetAttribute( node, srcAttributeName, this._updatedUrl(src) );\n }\n };\n hotswap.prototype._getFilesByType = function( type, xcludedFiles, xcludeComparator )\n {\n var files;\n switch(type)\n {\n case \"css\":\n files = this._getFiles(\n \"css\",\n \"link\",\n function(ele)\n {\n return (xGetAttribute(ele, \"rel\") == \"stylesheet\" || xGetAttribute(ele, \"type\") == \"text/css\");\n },\n \"href\",\n xcludedFiles,\n xcludeComparator\n )\n break;\n\n case \"js\":\n files = this._getFiles(\n \"js\",\n \"script\",\n function(ele)\n {\n return (xGetAttribute(ele, \"type\") == \"\" || xGetAttribute(ele, \"type\") == \"text/javascript\");\n },\n \"src\",\n xcludedFiles,\n xcludeComparator\n )\n break;\n\n case \"img\":\n files = this._getFiles(\n \"img\",\n \"img\",\n function(ele)\n {\n return (xGetAttribute(ele, \"src\") != \"\");\n },\n \"src\",\n xcludedFiles,\n xcludeComparator\n )\n break;\n }\n\n return files;\n }\n hotswap.prototype._getFiles = function( type, tagName, tagFilterFunc, srcAttributeName, xcludedFiles, xcludeComparator )\n {\n if( typeof xcludedFiles == \"undefined\" || !xcludedFiles)\n {\n xcludedFiles = [];\n }\n\n if( typeof xcludeComparator == \"undefined\" || !xcludeComparator)\n {\n xcludeComparator = false;\n }\n\n var fileNodes = [];\n var tags = xGetElementsByTagName(tagName);\n var src, detected, node;\n for(var i=0; i<tags.length; i++) {\n node = tags[i];\n src = xGetAttribute(node,[srcAttributeName]);\n if( xIsEmpty( xGetAttribute(node, \"data-hotswap-deleted\") ) )\n {\n if(src && tagFilterFunc(node))\n {\n detected = false;\n for(var j=0; j<xcludedFiles.length; j++) {\n if( xContains(src,xcludedFiles[j]) )\n {\n detected = true;\n break;\n }\n }\n if( detected == xcludeComparator )\n {\n fileNodes.push({\n type: type,\n node : node,\n tagName : tagName,\n srcAttributeName : srcAttributeName\n });\n }\n }\n }\n }\n\n return fileNodes;\n };\n hotswap.prototype._updatedUrl = function( url, getCleanUrl )\n {\n var cleanUrl;\n if( typeof getCleanUrl == \"undefined\")\n {\n getCleanUrl = false;\n }\n url = cleanUrl = url.replace(new RegExp(\"(\\\\?|&)\"+this.RND_PARAM_NAME+\"=[0-9.]*\",\"g\"), \"\");\n var queryString = \"\", randomizedQueryString = \"\";\n if( xContains(url, \"?\") )\n {\n if(xContains(url, \"&\" + this.RND_PARAM_NAME))\n {\n queryString = url.split(\"&\" + this.RND_PARAM_NAME).slice(1,-1).join(\"\");\n }\n randomizedQueryString = queryString + \"&\" + this.RND_PARAM_NAME + \"=\" + Math.random() * 99999999;\n }\n else\n {\n if(xContains(url, \"?\" + this.RND_PARAM_NAME))\n {\n queryString = url.split(\"?\" + this.RND_PARAM_NAME).slice(1,-1).join(\"\");\n }\n randomizedQueryString = queryString + \"?\" + this.RND_PARAM_NAME + \"=\" + Math.random() * 99999999;\n }\n var foundAt = -1;\n if( !xIsEmpty( this._prefixCache ) )\n {\n for(var i=0; i<this._prefixCache.length; ++i)\n {\n if( !xIsEmpty(this._prefixCache[i]) && foundAt < 0 )\n {\n for(var h=0; h<this._prefixCache[i].length; ++h)\n {\n if( this._prefixCache[i][h] == cleanUrl + queryString )\n {\n cleanUrl = this._prefixCache[i][0];\n foundAt = i;\n break;\n }\n }\n }\n }\n }\n\n var prefixHistory = [cleanUrl + queryString];\n var applyPrefix = true;\n if( prefixHistory[0].match( new RegExp('^[A-Za-z0-9-_]+://') ) )\n {\n applyPrefix = false;\n }\n var prefix = this._prefix;\n if( !xIsEmpty(this._prefix) && this._prefix )\n {\n prefixHistory.push( this._prefix + cleanUrl + queryString );\n if(foundAt >= 0)\n {\n this._prefixCache[foundAt] = prefixHistory;\n }\n else\n {\n this._prefixCache.push( prefixHistory );\n }\n }\n else\n {\n prefix = \"\";\n }\n if( !applyPrefix )\n {\n prefix = \"\";\n }\n url = prefix + cleanUrl + randomizedQueryString;\n\n return (getCleanUrl) ? (cleanUrl + queryString) : url;\n }\n hotswap.prototype.refreshAllJs = function( excludedFiles )\n {\n if( typeof excludedFiles == \"undefined\" || !excludedFiles)\n {\n excludedFiles = []\n }\n excludedFiles.push(\"hotswap.js\");\n\n this._recreate( \"js\", excludedFiles, false, 0, true );\n };\n hotswap.prototype.refreshJs = function( includedFiles )\n {\n this._recreate( \"js\", includedFiles, true, 0, true );\n };\n hotswap.prototype.refreshAllCss = function( excludedFiles )\n {\n this._recreate( \"css\", excludedFiles, false, this.FILE_REMOVAL_DELAY );\n };\n hotswap.prototype.refreshCss = function( includedFiles )\n {\n this._recreate( \"css\", includedFiles, true, this.FILE_REMOVAL_DELAY );\n };\n hotswap.prototype.refreshAllImg = function( excludedFiles )\n {\n this._reload( \"img\", excludedFiles, false );\n };\n hotswap.prototype.refreshImg = function( includedFiles )\n {\n this._reload( \"img\", includedFiles, true );\n };\n hotswap.prototype.setPrefix = function( prefix )\n {\n this._prefix = prefix;\n var gui = xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\");\n if( gui )\n {\n if( !xIsEmpty(this._prefix) && this._prefix )\n {\n xGetElementById(this.CSS_HTML_PREFIX+\"-prefix\").value = this._prefix;\n }\n else\n {\n xGetElementById(this.CSS_HTML_PREFIX+\"-prefix\").value = \"\";\n }\n }\n }\n hotswap.prototype.getPrefix = function()\n {\n return this._prefix;\n }\n hotswap.prototype.createGui = function( nDistanceFromTopInPercent )\n {\n if( xIsEmpty(nDistanceFromTopInPercent) )\n {\n nDistanceFromTopInPercent = 20;\n }\n var gui = xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\");\n if( gui )\n {\n xRemove(xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\"));\n }\n gui = xCreateElement(\"div\");\n xSetAttribute( gui, \"id\", this.CSS_HTML_PREFIX + \"_wrapper\" );\n var guiHtml = xReplace( this._guiHtml, \"PREFIX\", this.CSS_HTML_PREFIX );\n guiHtml = xReplace( guiHtml, '20%;/*distance from top*/', nDistanceFromTopInPercent+'%;/*distance from top*/' );\n gui.innerHTML = guiHtml;\n xAppendChild( xGetElementsByTagName(\"body\")[0], gui );\n if( !xIsEmpty(this._guiCache) )\n {\n this._guiCache = {};\n }\n this._guiCreateFilesList();\n if( !xIsEmpty(this._prefix) && this._prefix )\n {\n xGetElementById(this.CSS_HTML_PREFIX+\"-prefix\").value = this._prefix;\n }\n var self = this;\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-toggle\"), \"click\", function(evt)\n {\n var gui = xGetElementById(self.CSS_HTML_PREFIX);\n if( xHasClass(gui, \"mini\") )\n {\n xRemoveClass( gui, \"mini\" );\n }\n else\n {\n xAddClass( gui, \"mini\" );\n }\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-prefix\"), \"blur\", function(evt)\n {\n self._guiPrefixChanged(evt.target);\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-selected\"), \"click\", function(evt)\n {\n self._guiRefreshSelected()\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-start\"), \"click\", function(evt)\n {\n if( xGetAttribute(evt.target, \"class\") != this.CSS_HTML_PREFIX+\"-seconds\" )\n {\n var input, nSeconds = 1;\n var children = evt.target.children;\n for(var i=0; i<children.length; ++i)\n {\n if( xGetAttribute(children[i], \"class\") == this.CSS_HTML_PREFIX+\"-seconds\" )\n {\n nSeconds = children[i].value;\n }\n }\n\n self._guiRefreshSelected();\n self._guiRefreshStart( nSeconds );\n }\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-stop\"), \"click\", function(evt)\n {\n self._guiRefreshStop();\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-refresh-list\"), \"click\", xBind(self.guiRefreshFilesList,self) );\n }\n\n hotswap.prototype._guiCreateFilesList = function()\n {\n this._guiCache.files = [];\n this._guiCache.activeFiles = {\n \"css\" : [],\n \"js\" : [],\n \"img\" : []\n };\n\n var self = this;\n var createFilesList = function(list, files)\n {\n var i, j, r, clone, template, file, fileName, nodesToRemove = [];\n for(j=0; j<list.children.length; ++j)\n {\n if( xHasClass( list.children[j], \"template\" ) )\n {\n template = list.children[j];\n }\n else\n {\n if( !xHasClass( list.children[j], self.CSS_HTML_PREFIX + \"-headline\" ) )\n {\n nodesToRemove.push(list.children[j]);\n }\n }\n }\n for(r=0; r<nodesToRemove.length; ++r)\n {\n xRemove( nodesToRemove[r] );\n }\n for(i=0; i<files.length; ++i)\n {\n file = files[i];\n clone = xCloneNode( template );\n xRemoveClass( clone, \"template\" );\n fileName = self._updatedUrl( xGetAttribute( file.node, file.srcAttributeName ), true );\n if( !xContains(self._guiCache.files,fileName) )\n {\n self._guiCache.files.push(fileName);\n clone.innerHTML = fileName;\n xAppendChild( list, clone );\n xAddEventListener( clone, \"click\", (function(type, fileName){\n return function(evt){\n xStopPropagation(evt);\n xPreventDefault(evt);\n self._guiClickedFile(evt.target, type, fileName);\n };\n })(file.type, fileName)\n );\n }\n }\n }\n\n createFilesList( xGetElementById(this.CSS_HTML_PREFIX+\"-css\"), this._getFilesByType(\"css\") );\n createFilesList( xGetElementById(this.CSS_HTML_PREFIX+\"-js\"), this._getFilesByType(\"js\", [\"hotswap.js\"]) );\n createFilesList( xGetElementById(this.CSS_HTML_PREFIX+\"-img\"), this._getFilesByType(\"img\") );\n }\n hotswap.prototype.deleteGui = function()\n {\n var gui = xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\");\n if( gui )\n {\n xRemove(xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\"));\n }\n }\n hotswap.prototype._guiPrefixChanged = function(ele)\n {\n if( ele )\n {\n this.setPrefix(ele.value);\n }\n },\n\n hotswap.prototype._guiClickedFile = function( ele, sType, sFileName )\n {\n var activeFiles = this._guiCache.activeFiles[sType];\n if( xContains( activeFiles, sFileName ) )\n {\n xRemoveClass(ele, \"active\");\n activeFiles.splice( activeFiles.indexOf(sFileName), 1 )\n }\n else\n {\n xAddClass(ele, \"active\");\n activeFiles.push( sFileName );\n }\n },\n\n hotswap.prototype._guiRefreshSelected = function()\n {\n var activeFiles = this._guiCache.activeFiles;\n if( activeFiles['css'].length > 0 )\n {\n this.refreshCss( activeFiles['css'] );\n }\n if( activeFiles['js'].length > 0 )\n {\n this.refreshJs( activeFiles['js'] );\n }\n if( activeFiles['img'].length > 0 )\n {\n this.refreshImg( activeFiles['img'] );\n }\n },\n\n hotswap.prototype._guiRefreshStart = function( nSeconds )\n {\n if( this._guiGuiRefreshInterval !== null )\n {\n this._guiRefreshStop();\n }\n var self = this;\n this._guiGuiRefreshInterval = setInterval( xBind(this._guiRefreshSelected, this), nSeconds * 1000 );\n xAddClass( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-start\"), \"inactive\" );\n xRemoveClass( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-stop\"), \"inactive\" );\n },\n\n hotswap.prototype._guiRefreshStop = function()\n {\n if( this._guiGuiRefreshInterval !== null )\n {\n clearInterval(this._guiGuiRefreshInterval);\n }\n this._guiGuiRefreshInterval = null;\n xRemoveClass( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-start\"), \"inactive\" );\n xAddClass( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-stop\"), \"inactive\" );\n }\n\n hotswap.prototype.guiRefreshFilesList = function()\n {\n this._guiCreateFilesList();\n }\n\n}).call(this);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540/" ]
207,542
<p>I would like to programatically shutdown a Windows Mobile device using Compact framework 2.0, Windows mobile 5.0 SDK.</p> <p>Regards,</p>
[ { "answer_id": 208331, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 3, "selected": true, "text": "[Flags]\npublic enum ExitFlags\n{\n Reboot = 0x02,\n PowerOff = 0x08\n}\n\n[DllImport(\"coredll\")]\npublic static extern int ExitWindowsEx(ExitFlags flags, int reserved);\n\n...\n\nExitWindowsEx(ExitFlags.PowerOff, 0);\n" }, { "answer_id": 286795, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "OpenNetCF.WindowsCE.PowerManagement" }, { "answer_id": 33116140, "author": "kachun wong", "author_id": 5443365, "author_profile": "https://Stackoverflow.com/users/5443365", "pm_score": 0, "selected": false, "text": "Process.Start(\"cmd\", \"/c shutdown.exe\")\n<br/>\nMe.Close()\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254/" ]
207,554
<p>I'm working on an intranet with several subdomains. I have control over each subdomain, so security of cross-site requests is not a concern. I have PHP scripts with JSON responses I'd like to call from multiple subdomains without duplication. For GET requests, I can do this with AJAX and JSONP, but that doesn't work with POST requests. Some alternatives I see, none of which seem very good:</p> <ul> <li>POST to a copy on local subdomain with minimal response, then GET full response from central location with JSONP</li> <li>Both POST and GET to a copy on local subdomain with JSON</li> <li>Use mod_rewrite to use local URLs with a central script on back end with JSON</li> <li>Use symlinks to use local URLs with a central script on back end with JSON</li> </ul> <p>Am I missing something simpler? What would you do here?</p>
[ { "answer_id": 207668, "author": "Rik Heywood", "author_id": 4012, "author_profile": "https://Stackoverflow.com/users/4012", "pm_score": 2, "selected": false, "text": "<?php\n// Set header so our output looks like a PNG\nheader(\"Content-Type: image/png\");\n\n// Reflect the image from googles chart API\necho file_get_contents('http://chart.apis.google.com/chart?'.$_SERVER['QUERY_STRING']);\n?>\n" }, { "answer_id": 245869, "author": "Jarett Millard", "author_id": 15882, "author_profile": "https://Stackoverflow.com/users/15882", "pm_score": 0, "selected": false, "text": "document.domain = 'domain.com';\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10837/" ]
207,592
<p>I have a class, and I want to inspect its fields and report eventually how many bytes each field takes. I assume all fields are of type Int32, byte, etc.</p> <p>How can I find out easily how many bytes does the field take?</p> <p>I need something like:</p> <pre><code>Int32 a; // int a_size = a.GetSizeInBytes; // a_size should be 4 </code></pre>
[ { "answer_id": 207601, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Runtime.InteropServices;\n\npublic class MyClass\n{\n public static void Main()\n {\n Int32 a = 10;\n Console.WriteLine(Marshal.SizeOf(a));\n Console.ReadLine();\n }\n}\n" }, { "answer_id": 207605, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "class FourBytes { byte a, b, c, d; }\nclass FiveBytes { byte a, b, c, d, e; }\n" }, { "answer_id": 13069336, "author": "Jesper Niedermann", "author_id": 358847, "author_profile": "https://Stackoverflow.com/users/358847", "pm_score": 4, "selected": false, "text": "public class MeasureSize<T>\n{\n private readonly Func<T> _generator;\n private const int NumberOfInstances = 10000;\n private readonly T[] _memArray;\n\n public MeasureSize(Func<T> generator)\n {\n _generator = generator;\n _memArray = new T[NumberOfInstances];\n }\n\n public long GetByteSize()\n {\n //Make one to make sure it is jitted\n _generator();\n\n long oldSize = GC.GetTotalMemory(false);\n for(int i=0; i < NumberOfInstances; i++)\n {\n _memArray[i] = _generator();\n }\n long newSize = GC.GetTotalMemory(false);\n return (newSize - oldSize) / NumberOfInstances;\n }\n}\n public long SizeOfSomeObject()\n {\n var measure = new MeasureSize<SomeObject>(() => new SomeObject());\n return measure.GetByteSize();\n }\n" }, { "answer_id": 13372626, "author": "Earlz", "author_id": 69742, "author_profile": "https://Stackoverflow.com/users/69742", "pm_score": 3, "selected": false, "text": "using Earlz.BareMetal;\n\n...\nConsole.WriteLine(BareMetal.SizeOf<int>()); //returns 4 everywhere I've tested\nConsole.WriteLine(BareMetal.SizeOf<string>()); //returns 8 on 64-bit platforms and 4 on 32-bit\nConsole.WriteLine(BareMetal.SizeOf<Foo>()); //returns 16 in some places, 24 in others. Varies by platform and framework version\n\n...\n\nstruct Foo\n{\n int a, b;\n byte c;\n object foo;\n}\n sizeof T sizeof sizeof sizeof" }, { "answer_id": 33714394, "author": "David Chen", "author_id": 5563048, "author_profile": "https://Stackoverflow.com/users/5563048", "pm_score": 0, "selected": false, "text": "public static int FieldSize(int Field) { return sizeof(int); }\npublic static int FieldSize(bool Field) { return sizeof(bool); }\npublic static int FieldSize(SomeStructType Field) { return sizeof(SomeStructType); }\n" }, { "answer_id": 55406877, "author": "TakeMeAsAGuest", "author_id": 699229, "author_profile": "https://Stackoverflow.com/users/699229", "pm_score": 0, "selected": false, "text": "int size = *((int*)type.TypeHandle.Value + 1) [StructLayout(LayoutKind.Auto)] BindingFlags.DeclaredOnly" }, { "answer_id": 58753714, "author": "Bruno Zell", "author_id": 5185376, "author_profile": "https://Stackoverflow.com/users/5185376", "pm_score": 0, "selected": false, "text": "System.Runtime.CompilerServices.Unsafe.SizeOf<T>() where T: unmanaged sizeof unmanaged" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,599
<p>I just wrote a new web part and now I am getting this error when I try to deploy them on my non-dev servers:</p> <blockquote> <p>the default namespace '<a href="http://schemas.microsoft.com/WebPart/v2" rel="nofollow noreferrer">http://schemas.microsoft.com/WebPart/v2</a>' is a reserved namespace for base Web Part propertiees. Custom Web Part properties require a unique namespace (specified through an XmlElementAttribute on the property , or an XmlRootAttribute on the class).</p> </blockquote> <p>I am writing the web parts into CAB files and deploying them with this:</p> <pre><code>stsadm -o addwppack -filename web_part_name.CAB -url http://your_url_here -globalinstall -force </code></pre> <p>Everything works fine until I try to add the web part, then I get this error in a popup. It works just fine on my dev VM...?</p> <p>Any ideas would be appreciate, thank you.</p>
[ { "answer_id": 207686, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 0, "selected": false, "text": "[XmlRoot(Namespace = \"Your.Namespace\")]\npublic class YourWebPart: WebPart\n{\n...\n [DefaultValue(0)]\n [WebPartStorage(Storage.Shared)]\n [Browsable(false)]\n [XmlElement(ElementName = \"YourProperty\")]\n public Int64 YourProperty\n { \n ...\n }\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
207,608
<p>There is this style of exception system where a component throws component-specific exception. For example, all data access classes throw <code>DataAccessException</code>.</p> <p>In this style, I often find myself having to catch and rethrow the component specific exception, because called methods are delcared as <code>throws Exception</code>:</p> <pre><code>try { int foo = foo(); if (foo != expectedValue) { throw new ComponentException("bad result from foo(): " + foo); } bar(); } catch (ComponentException e) { throw e; } catch (Exception e) { throw new ComponentException(e); } </code></pre> <p>Do you find yourself doing the same? Do you find it ugly?</p> <p>This question is not about validity of this style, but something within the constraints of this style.</p>
[ { "answer_id": 207634, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "try {\n componentCall();\n} catch (ComponentException e) {\n Throwable t = e.getCause();\n //Handle each possible cause\n}\n try {\n int foo = foo();\n if (foo != expectedValue) {\n throw new InvalidFooException(\"bad result from foo(): \" + foo);\n }\n bar();\n}\ncatch (Exception e) { \n throw new ComponentException(e); \n}\n" }, { "answer_id": 207820, "author": "Vinze", "author_id": 26859, "author_profile": "https://Stackoverflow.com/users/26859", "pm_score": 0, "selected": false, "text": "int foo;\ntry {\n foo = foo();\n}\ncatch (Exception e) { \n throw new ComponentException(e); \n}\nif (foo != expectedValue) {\n throw new ComponentException(\"bad result from foo(): \" + foo);\n}\nbar();\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18573/" ]
207,613
<p>Please one library per answer so that people can vote for the individually.</p>
[ { "answer_id": 207808, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 2, "selected": false, "text": "var cal = new scal('samplecal', updateelement, {\n oncalchange: function(d) {\n alert('Calendar Change: ' + d.format('yyyy-mm-dd'));\n }\n});\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3547/" ]
207,631
<p>Does some article or proof exist that .NET applications are immune to low level errors? </p> <p>I'm talking about the classic pointer errors we can see in a C++ application, memory overflow, problems from the Intel <a href="http://en.wikipedia.org/wiki/NX_bit" rel="nofollow noreferrer">DEP</a> and so on.</p> <p>I'm talking about .NET applications that do not use "unsafe" code, from what is my experience in this case only problems can be that of a memory leak or classic coding errors (like stack overflows) but I've never seen low level errors.</p> <p>Could someone comment on this?</p>
[ { "answer_id": 18925326, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "new delete new delete" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11673/" ]
207,633
<p>Can we somehow extend the RuleSetDialog class and host in our windows application?</p>
[ { "answer_id": 682151, "author": "Mel", "author_id": 1763, "author_profile": "https://Stackoverflow.com/users/1763", "pm_score": 0, "selected": false, "text": "var dialog = new RuleSetDialog(activityType, null, ruleset);\ndialog.Controls[\"headerTextLabel\"].Visible = false;\ndialog.Controls[\"pictureBoxHeader\"].Visible = false;\n\n...\n\nvar ruleGroupBox = dialog.Controls[\"ruleGroupBox\"];\nruleGroupbox.Top -= 46;\n\n... etc.\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11039/" ]
207,636
<p>I have a Java method which starts up a Process with ProcessBuilder, and pipes its output into a byte array, and then returns its byte array when the process is finished.</p> <p>Pseudo-code:</p> <pre><code>ProcessBuilder b = new ProcessBuilder("my.exe") Process p = b.start(); ... // get output from process, close process </code></pre> <p>What would be the best way to go about unit testing this method? I haven't found a way to mock ProcessBuilder (it's final), even with the incredibly awesome <a href="http://jmockit.org" rel="noreferrer">JMockit</a>, it gives me a NoClassDefFoundError:</p> <pre><code>java.lang.NoClassDefFoundError: test/MockProcessBuilder at java.lang.ProcessBuilder.&lt;init&gt;(ProcessBuilder.java) at mypackage.MyProcess.start(ReportReaderWrapperImpl.java:97) at test.MyProcessTest.testStart(ReportReaderWrapperImplTest.java:28) </code></pre> <p>Any thoughts?</p> <hr> <p><strong>Answer</strong> - As Olaf recommended, I ended up refactoring those lines to an interface</p> <pre><code>Process start(String param) throws IOException; </code></pre> <p>I now pass an instance of this interface into the class I wanted to test (in its constructor), normally using a default implementation with the original lines. When I want to test I simply use a mock implementation of the interface. Works like a charm, though I do wonder if I'm over-interfacing here...</p>
[ { "answer_id": 1024931, "author": "Rogério", "author_id": 2326914, "author_profile": "https://Stackoverflow.com/users/2326914", "pm_score": 2, "selected": false, "text": "public class MyProcessTest\n{\n public static class MyProcess {\n public byte[] run() throws IOException, InterruptedException {\n Process process = new ProcessBuilder(\"my.exe\").start();\n process.waitFor();\n\n // Simplified example solution:\n InputStream processOutput = process.getInputStream();\n byte[] output = new byte[8192];\n int bytesRead = processOutput.read(output);\n\n return Arrays.copyOf(output, bytesRead);\n }\n }\n\n @Test\n public void runProcessReadingItsOutput(@Mocked final ProcessBuilder pb)\n throws Exception\n {\n byte[] expectedOutput = \"mocked output\".getBytes();\n final InputStream output = new ByteArrayInputStream(expectedOutput);\n new Expectations() {{ pb.start().getInputStream(); result = output; }};\n\n byte[] processOutput = new MyProcess().run();\n\n assertArrayEquals(expectedOutput, processOutput);\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
207,642
<p>There are so many options when it comes to PHP development environments and you have to piece it all together yourself.</p> <p>I'm wondering if someone has come up with what they think is the ideal setup that gets out of your way and lets you develop.</p> <p>Right now I use vim and svn from the command-line. I write scripts to manage builds but I'm thinking about looking into Phing.</p> <p>I love vim but I'm seriously thinking of trying Eclipse with the PHP plugin because I imagine it makes common SVN options a bit easier (moving files around in a project).</p> <p>Something to support continuous integration on the database would be a major plus!</p> <p>UPDATE: Just wanted to stress that previous line up there. I realize some frameworks will help with this, but I don't use a framework. Is there some simple module out there (included in the IDE or not) that will let me easily tie my database schemas/data to a subversion revision, letting me rollback and forward, tag, branch, etc?</p> <p>Any comments on things beyond the editor? For example: Builds, managing staging/production/development environments, automated testing and building upon SVN commit, etc. Ideally we can make this post a "Go to Whoah" for setting up a professional PHP team development environment.</p>
[ { "answer_id": 207685, "author": "Richard Turner", "author_id": 12559, "author_profile": "https://Stackoverflow.com/users/12559", "pm_score": 1, "selected": false, "text": "var_dump();exit;" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,646
<p>I am having an VB Script. I need to log the error information in a file. I need to log every information like error number error description and in which sub routine does the error occured.</p> <p>Please provide some code</p>
[ { "answer_id": 207697, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": -1, "selected": true, "text": "On Error Resume Next '' ignore errors\nSomeIgnorableFunction()\n\nOn Error GoTo 0 '' removes error ignoring\nSomeImportantFunction()\n\nOn Error GoTo HandleError '' on error will code jump to specified signal\nDim a\na = 15 / 0\n\nGoTo Finish '' skips error handling\n\nHandleError:\nDim msg\nSet msg = Err.Description & vbCrLf & Err.Number\nMsgBox msg\n\nFinish:\n'' there is end of sciprt\n" }, { "answer_id": 208005, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 2, "selected": false, "text": "Option Explicit\n\nOn Error Resume Next ' Potential error coming up\nDim MyArray(5)\nMyArray(7) = \"BWA HA HA\"\nIf Err.Number <> 0 Then\n LogError(Err)\n Err.Clear\nEnd If\nOn Error Goto 0 ' Stop looking for errors \n\nSub LogError(Details)\n Dim fs : Set fs = CreateObject(\"Scripting.FileSystemObject\")\n Dim logFile : Set logFile = fs.OpenTextFile(\"c:\\errors.log\", 8, True)\n logFile.WriteLine(Now() & \": Error: \" & Details.Number & \" Details: \" & Details.Description)\nEnd Sub\n" }, { "answer_id": 4356830, "author": "Larry", "author_id": 530895, "author_profile": "https://Stackoverflow.com/users/530895", "pm_score": 1, "selected": false, "text": "private sub BucketList()\ndo while 1=1\n ClimbMountain(top)\n if err.Number <> 0 then exit do\n SwimOcean(deep)\n if err.Number <> 0 then exit do\n GiveErrorHandlingToVBS(isNeverGoingToHappen)\n if err.Number <> 0 then exit do\n\n exit do\nloop\n\n'Error Handler\nif err.Number <> 0 then\n 'handle error\nend if\n\nend sub\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
207,662
<p>I'm trying to write a wstring to file with ofstream in binary mode, but I think I'm doing something wrong. This is what I've tried:</p> <pre><code>ofstream outFile("test.txt", std::ios::out | std::ios::binary); wstring hello = L"hello"; outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t)); outFile.close(); </code></pre> <p>Opening test.txt in for example Firefox with encoding set to UTF16 it will show as:</p> <p>h�e�l�l�o�</p> <p>Could anyone tell me why this happens? </p> <p><strong>EDIT:</strong></p> <p>Opening the file in a hex editor I get:</p> <pre><code>FF FE 68 00 00 00 65 00 00 00 6C 00 00 00 6C 00 00 00 6F 00 00 00 </code></pre> <p>Looks like I get two extra bytes in between every character for some reason?</p>
[ { "answer_id": 208431, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": false, "text": "#include <locale>\n#include <fstream>\n#include <iostream>\n// See Below for the facet\n#include \"UTF16Facet.h\"\n\nint main(int argc,char* argv[])\n{\n // construct a custom unicode facet and add it to a local.\n UTF16Facet *unicodeFacet = new UTF16Facet();\n const std::locale unicodeLocale(std::cout.getloc(), unicodeFacet);\n\n // Create a stream and imbue it with the facet\n std::wofstream saveFile;\n saveFile.imbue(unicodeLocale);\n\n\n // Now the stream is imbued we can open it.\n // NB If you open the file stream first. Any attempt to imbue it with a local will silently fail.\n saveFile.open(\"output.uni\");\n saveFile << L\"This is my Data\\n\";\n\n\n return(0);\n} \n #include <locale>\n\nclass UTF16Facet: public std::codecvt<wchar_t,char,std::char_traits<wchar_t>::state_type>\n{\n typedef std::codecvt<wchar_t,char,std::char_traits<wchar_t>::state_type> MyType;\n typedef MyType::state_type state_type;\n typedef MyType::result result;\n\n\n /* This function deals with converting data from the input stream into the internal stream.*/\n /*\n * from, from_end: Points to the beginning and end of the input that we are converting 'from'.\n * to, to_limit: Points to where we are writing the conversion 'to'\n * from_next: When the function exits this should have been updated to point at the next location\n * to read from. (ie the first unconverted input character)\n * to_next: When the function exits this should have been updated to point at the next location\n * to write to.\n *\n * status: This indicates the status of the conversion.\n * possible values are:\n * error: An error occurred the bad file bit will be set.\n * ok: Everything went to plan\n * partial: Not enough input data was supplied to complete any conversion.\n * nonconv: no conversion was done.\n */\n virtual result do_in(state_type &s,\n const char *from,const char *from_end,const char* &from_next,\n wchar_t *to, wchar_t *to_limit,wchar_t* &to_next) const\n {\n // Loop over both the input and output array/\n for(;(from < from_end) && (to < to_limit);from += 2,++to)\n {\n /*Input the Data*/\n /* As the input 16 bits may not fill the wchar_t object\n * Initialise it so that zero out all its bit's. This\n * is important on systems with 32bit wchar_t objects.\n */\n (*to) = L'\\0';\n\n /* Next read the data from the input stream into\n * wchar_t object. Remember that we need to copy\n * into the bottom 16 bits no matter what size the\n * the wchar_t object is.\n */\n reinterpret_cast<char*>(to)[0] = from[0];\n reinterpret_cast<char*>(to)[1] = from[1];\n }\n from_next = from;\n to_next = to;\n\n return((from > from_end)?partial:ok);\n }\n\n\n\n /* This function deals with converting data from the internal stream to a C/C++ file stream.*/\n /*\n * from, from_end: Points to the beginning and end of the input that we are converting 'from'.\n * to, to_limit: Points to where we are writing the conversion 'to'\n * from_next: When the function exits this should have been updated to point at the next location\n * to read from. (ie the first unconverted input character)\n * to_next: When the function exits this should have been updated to point at the next location\n * to write to.\n *\n * status: This indicates the status of the conversion.\n * possible values are:\n * error: An error occurred the bad file bit will be set.\n * ok: Everything went to plan\n * partial: Not enough input data was supplied to complete any conversion.\n * nonconv: no conversion was done.\n */\n virtual result do_out(state_type &state,\n const wchar_t *from, const wchar_t *from_end, const wchar_t* &from_next,\n char *to, char *to_limit, char* &to_next) const\n {\n for(;(from < from_end) && (to < to_limit);++from,to += 2)\n {\n /* Output the Data */\n /* NB I am assuming the characters are encoded as UTF-16.\n * This means they are 16 bits inside a wchar_t object.\n * As the size of wchar_t varies between platforms I need\n * to take this into consideration and only take the bottom\n * 16 bits of each wchar_t object.\n */\n to[0] = reinterpret_cast<const char*>(from)[0];\n to[1] = reinterpret_cast<const char*>(from)[1];\n\n }\n from_next = from;\n to_next = to;\n\n return((to > to_limit)?partial:ok);\n }\n};\n" }, { "answer_id": 10958021, "author": "NuNuNO Griesbach", "author_id": 1445696, "author_profile": "https://Stackoverflow.com/users/1445696", "pm_score": 1, "selected": false, "text": "Utf16Facet gcc UTF-16LE UTF-16BE do_in do_out to[0] = from[1] to[1] = from[0] #include <locale>\n#include <bits/codecvt.h>\n\n\nclass UTF16Facet: public std::codecvt<wchar_t,char,std::char_traits<wchar_t>::state_type>\n{\n typedef std::codecvt<wchar_t,char,std::char_traits<wchar_t>::state_type> MyType;\n typedef MyType::state_type state_type;\n typedef MyType::result result;\n\n\n /* This function deals with converting data from the input stream into the internal stream.*/\n /*\n * from, from_end: Points to the beginning and end of the input that we are converting 'from'.\n * to, to_limit: Points to where we are writing the conversion 'to'\n * from_next: When the function exits this should have been updated to point at the next location\n * to read from. (ie the first unconverted input character)\n * to_next: When the function exits this should have been updated to point at the next location\n * to write to.\n *\n * status: This indicates the status of the conversion.\n * possible values are:\n * error: An error occurred the bad file bit will be set.\n * ok: Everything went to plan\n * partial: Not enough input data was supplied to complete any conversion.\n * nonconv: no conversion was done.\n */\n virtual result do_in(state_type &s,\n const char *from,const char *from_end,const char* &from_next,\n wchar_t *to, wchar_t *to_limit,wchar_t* &to_next) const\n {\n\n for(;from < from_end;from += 2,++to)\n {\n if(to<=to_limit){\n (*to) = L'\\0';\n\n reinterpret_cast<char*>(to)[0] = from[0];\n reinterpret_cast<char*>(to)[1] = from[1];\n\n from_next = from;\n to_next = to;\n }\n }\n\n return((to != to_limit)?partial:ok);\n }\n\n\n\n /* This function deals with converting data from the internal stream to a C/C++ file stream.*/\n /*\n * from, from_end: Points to the beginning and end of the input that we are converting 'from'.\n * to, to_limit: Points to where we are writing the conversion 'to'\n * from_next: When the function exits this should have been updated to point at the next location\n * to read from. (ie the first unconverted input character)\n * to_next: When the function exits this should have been updated to point at the next location\n * to write to.\n *\n * status: This indicates the status of the conversion.\n * possible values are:\n * error: An error occurred the bad file bit will be set.\n * ok: Everything went to plan\n * partial: Not enough input data was supplied to complete any conversion.\n * nonconv: no conversion was done.\n */\n virtual result do_out(state_type &state,\n const wchar_t *from, const wchar_t *from_end, const wchar_t* &from_next,\n char *to, char *to_limit, char* &to_next) const\n {\n\n for(;(from < from_end);++from, to += 2)\n {\n if(to <= to_limit){\n\n to[0] = reinterpret_cast<const char*>(from)[0];\n to[1] = reinterpret_cast<const char*>(from)[1];\n\n from_next = from;\n to_next = to;\n }\n }\n\n return((to != to_limit)?partial:ok);\n }\n};\n" }, { "answer_id": 12508122, "author": "Yarkov Anton", "author_id": 1850869, "author_profile": "https://Stackoverflow.com/users/1850869", "pm_score": 3, "selected": false, "text": "C++11 \"utf8\" stxutif.h std::ofstream fs;\nfs.open(filepath, std::ios::out|std::ios::binary);\n\nunsigned char smarker[3];\nsmarker[0] = 0xEF;\nsmarker[1] = 0xBB;\nsmarker[2] = 0xBF;\n\nfs << smarker;\nfs.close();\n UTF std::wofstream fs;\nfs.open(filepath, std::ios::out|std::ios::app);\n\nstd::locale utf8_locale(std::locale(), new utf8cvt<false>);\nfs.imbue(utf8_locale); \n\nfs << .. // Write anything you want...\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22283/" ]
207,693
<p>The following code returns data from a spreadsheet into a grid perfectly</p> <pre><code>[ string excelConnectString = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source = " + excelFileName + ";" + "Extended Properties = Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(excelConnectString); OleDbCommand objCmd = new OleDbCommand("Select * From [Accounts$]", objConn); OleDbDataAdapter objDatAdap = new OleDbDataAdapter(); objDatAdap.SelectCommand = objCmd; DataSet ds = new DataSet(); objDatAdap.Fill(ds); fpDataSet_Sheet1.DataSource = ds;//fill a grid with data ] </code></pre> <p>The spreadsheet I'm using has columns named from A and so on( just standard column names ) and the sheet name is Accounts.</p> <p>I have a problem with the query ...</p> <pre><code> [OleDbCommand objCmd = new OleDbCommand("Select * From [Accounts$]", objConn);] </code></pre> <p>How can I make the query string like this...</p> <pre><code>"Select &lt;columnA&gt;,&lt;columnB&gt;,SUM&lt;columnG&gt; from [Accounts$] group by &lt;columnA&gt;,&lt;columnB&gt;" </code></pre> <p>..so that it returns the results of this query</p> <p>Note : columnA is A on Sheet , columnB is B on Sheet and columnG is G on Sheet</p> <p>Other possible Alternatives:</p> <ol> <li>I have the data of that excel spread into a DataTable object, how can I query the DataTAble object</li> <li>I read about a DataView object that it can take a table and return the table manipulated according to (<code>&lt;dataviewObject&gt;.RowFilter = "where..."</code>) , but I don't know how to use the query I want.</li> </ol>
[ { "answer_id": 281829, "author": "Jason Anderson", "author_id": 1530166, "author_profile": "https://Stackoverflow.com/users/1530166", "pm_score": 0, "selected": false, "text": "SUM Column A, B, C, D, etc... ColumnA, ColumnB, ColumnC, ColumnD, etc... query Select ColumnA, ColumnB, ColumnC from [Accounts$] Select * from [Accounts$] connection string connection string excelConnectString = \"Provider = Microsoft.Jet.OLEDB.4.0;\" + \"Data Source = \" \n+ excelFileName + \";\" + \"Extended Properties = Excel 8.0; HDR=Yes;\";\n HDR=Yes Select DataView's RowFilter property" }, { "answer_id": 421145, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 2, "selected": false, "text": "string salary = empTable.Compute(\"SUM( Salary )\", \"\").ToString();\nstring averageSalaryJan = empTable.Compute(\"AVG( Salary )\", \"Month = 1\").ToString();\n// Assuming you have month stored in Month column and Salary stored in Salary column\n" }, { "answer_id": 421217, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": " SELECT Sum([NameOfFieldAsPerHeader]) FROM [Accounts$]\n SELECT [ForExampleEmployeeID], Sum([NameOfFieldAsPerHeader]) FROM [Accounts$]\n GROUP BY [ForExampleEmployeeID]\n SELECT [ForExampleEmployeeID], Year([SomeDate]), Sum([NameOfFieldAsPerHeader]) \n FROM [Accounts$]\n GROUP BY [ForExampleEmployeeID], Year([SomeDate])\n SELECT [ForExampleEmployeeID], Year([SomeDate]), Sum([NameOfFieldAsPerHeader]) \n FROM [Accounts$]\n WHERE Year([SomeDate])>2000\n GROUP BY [ForExampleEmployeeID], Year([SomeDate])\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,703
<p>I have a touch screen kiosk that displays a webpage and a pdf document. Can I remove the menu bar? Users must not have "save", "print" and other such features.</p> <p>Update</p> <p><a href="http://flickr.com/photos/23021917@N05/2209106577/" rel="nofollow noreferrer">random screenshot on flickr</a> - I am refering to the print, back/forward, zoom bar that controls the PDF -- not the browser menu. Sorry for not beeing specific.</p>
[ { "answer_id": 208160, "author": "charlesbridge", "author_id": 22738, "author_profile": "https://Stackoverflow.com/users/22738", "pm_score": 2, "selected": false, "text": "File->Export as PDF->User Interface" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3718/" ]
207,720
<p>One of the most difficult problems in my javascript experience has been the correct (that is "cross-browser") computing of a <strong>iframe height</strong>. In my applications I have a lot of dynamically generated iframe and I want them all do a sort of autoresize at the end of the load event to adjust their height and width.</p> <p>In the case of <strong>height</strong> computing my best solution is the following (with the help of jQuery):</p> <pre><code>function getDocumentHeight(doc) { var mdoc = doc || document; if (mdoc.compatMode=='CSS1Compat') { return mdoc.body.offsetHeight; } else { if ($.browser.msie) return mdoc.body.scrollHeight; else return Math.max($(mdoc).height(), $(mdoc.body).height()); } } </code></pre> <p>I searched the internet without success. I also tested Yahoo library that has some methods for document and viewport dimensions, but it's not satisfactory. My solution works decently, but sometimes it calculates a taller height. I've studied and tested tons of properties regarding document height in Firefox/IE/Safari: <code>documentElement.clientHeight, documentElement.offsetHeight, documentElement.scrollHeight, body.offsetHeight, body.scrollHeight, ...</code> Also jQuery doesn't have a coherent behavior in various browser with the calls <code>$(document.body).height(), $('html', doc).height(), $(window).height()</code></p> <p>I call the above function not only at the end of load event, but also in the case of dynamically inserted DOM elements or elements hidden or shown. This is a case that sometimes breaks the code that works only in the load event.</p> <p>Does someone have a real cross-browser (at least Firefox/IE/Safari) solution? Some tips or hints?</p>
[ { "answer_id": 749417, "author": "Brian Grinstead", "author_id": 76137, "author_profile": "https://Stackoverflow.com/users/76137", "pm_score": 0, "selected": false, "text": "function getDocumentHeight(doc) {\n var mdoc = doc || document; \n var docHeight = mdoc.body.scrollHeight;\n\n if ($.browser.msie) {\n // IE 6/7 don't report body height correctly. \n // Instead, insert a temporary div containing the contents.\n\n var child = $(\"<div>\" + mdoc.body.innerHTML + \"</div>\", mdoc);\n $(\"body\", mdoc).prepend(child);\n docHeight = child.height();\n child.remove();\n }\n\n return docHeight;\n}\n" }, { "answer_id": 1279668, "author": "mothmonsterman", "author_id": 152640, "author_profile": "https://Stackoverflow.com/users/152640", "pm_score": 0, "selected": false, "text": "// sizing - slight delay for good scrollheight\nsetTimeout(function() {\n var intContentHeight = objContentDoc.body.scrollHeight;\n var $wrap = $(\"#divContentWrapper\", objContentFrameDoc);\n var intMaxHeight = getMaxLayeredContentHeight($wrap);\n $this.height(intContentHeight > intMaxHeight ? intMaxHeight : intContentHeight);\n\n // animate\n fireLayeredContentAnimation($wrap);\n}, 100);\n" }, { "answer_id": 5523176, "author": "Udo G", "author_id": 688869, "author_profile": "https://Stackoverflow.com/users/688869", "pm_score": 1, "selected": false, "text": "...\n<body>\n <div id=\"content\">\n ...\n </div>\n</body>\n function getDocumentHeight(mdoc) {\n return mdoc.getElementById(\"content\").clientHeight;\n }\n var mdoc = doc || document;" }, { "answer_id": 8333677, "author": "0x6A75616E", "author_id": 62747, "author_profile": "https://Stackoverflow.com/users/62747", "pm_score": 2, "selected": false, "text": "// executes when a message is received from the iframe, to adjust \n// the iframe's height\n $.receiveMessage(\n function( event ){\n $( 'my_iframe' ).css({\n height: event.data\n });\n });\n\n// Please note this function could also verify event.origin and other security-related checks.\n $(function(){\n\n // Sends a message to the parent window to tell it the height of the \n // iframe's body\n\n var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);\n\n $.postMessage(\n $('body').outerHeight( true ) + 'px',\n '*',\n target\n );\n\n});\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27789/" ]
207,721
<p>As I mention in an earlier question, I'm refactoring a project I'm working on. Right now, everything depends on everything else. Everything is separated into namespaces I created early on, but I don't think my method of separtion was very good. I'm trying to eliminate cases where an object depends on another object in a different namespace that depends on the other object.</p> <p>The way I'm doing this, is by partitioning my project (a game) into a few assemblies:</p> <pre><code>GameName.Engine GameName.Rules GameName.Content GameName.Gui </code></pre> <p>The <code>GameName.Engine</code> assembly contains a bunch of interfaces, so other parts of the program don't need to depend on any particular implementation. For instance, I have a <code>GameName.Engine.ICarryable</code> interface that is primarily implemented by <code>GameName.Content.Item</code> class (and its sub-classes). I also have an object to allow an <code>Actor</code> to pick up an <code>ICarryable</code>: <code>PickupAction</code>. <code>Previously</code>, it required an Item, but this exposes unneccessary methods and properties, where it really only needed the methods required to pick it up and carry it. That's why I've created the <code>ICarryable</code> interface.</p> <p>Now that's all good, so to my question. <code>GameName.Gui</code> should only depend on <code>GameName.Engine</code>, not any implementation. Inside <code>GameName.Gui</code> I have a <code>MapView</code> object that displays a <code>Map</code> and any <code>IRenderable</code> objects on it.</p> <p><code>IRenderable</code> is basically just an interface that exposes an image and some strings describing the object. But, the MapView also needs the object to implement <code>ILocateable</code>, so it can see its location and know when it's changed via an event, <code>LocationChanged</code>, inside <code>ILocateable</code>.</p> <p>These two interfaces are implemented by both <code>Item</code> and <code>Actor</code> objects. Which, again are defined in <code>GameName.Content</code>. Since it needs both interfaces, I have two choices:</p> <ol> <li><p>Make <code>GameName.Gui</code> depend on <code>GameName.Content</code> and require an <code>Entity</code> (base-class of <code>Item</code> and <code>Actor</code>).</p></li> <li><p>Make an interface inside <code>GameName.Engine</code> that looks like this:</p> <pre><code>interface ILocateableRenderable : ILocateable, IRenderable { } </code></pre> <p>And then make my <code>Actor</code> and <code>Item</code> objects implement that interface instead of the two individually.</p></li> </ol> <p>Anyone have any suggestions on which method is the best? Is it appropriate to create an interface with no methods or properties, that only enforces implementing two other interfaces?</p> <p><em>Clarification: <code>MapView</code> works on a <code>Map</code>, which is composed of <code>Entity</code> objects. I don't want to expose the <code>Entity</code> objects to the <code>MapView</code>, it only needs to know their location (<code>ILocateable</code>) and how to render them (<code>IRenderable</code>).</em></p>
[ { "answer_id": 207753, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": true, "text": "public void Whatever(IRenderable renderable)\n{\n if (renderable is ILocateable)\n {\n ((ILocateable) renderable).LocationChanged += myEventHandler;\n }\n\n // Do normal stuff\n}\n interface IMappable: IRenderable, ILocateable {}\n\npublic void Whatever(IMappable mappable)\n{\n mappable.LocationChanged += myEventHandler;\n\n // Do normal stuff\n} \n interface IRenderable: ILocateable\n{\n // IRenderable interface\n}\n\n\npublic void Whatever(IRenderable renderable)\n{\n renderable.LocationChanged += myEventHandler;\n\n // Do normal stuff\n} \n" }, { "answer_id": 207906, "author": "Mark A. Nicolosi", "author_id": 1103052, "author_profile": "https://Stackoverflow.com/users/1103052", "pm_score": 2, "selected": false, "text": "public interface IRenderable : ILocateable\n{\n // IRenderable interface\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103052/" ]
207,730
<p>I'm trying to create a C++ class, with a templated superclass. The idea being, I can easily create lots of similar subclasses from a number of superclasses which have similar characteristics.</p> <p>I have distilled the problematic code as follows:</p> <p><code>template_test.h</code>:</p> <pre><code>template&lt;class BaseClass&gt; class Templated : public BaseClass { public: Templated(int a); virtual int Foo(); }; class Base { protected: Base(int a); public: virtual int Foo() = 0; protected: int b; }; </code></pre> <p><code>template_test.cpp</code>:</p> <pre><code>#include "template_test.h" Base::Base(int a) : b(a+1) { } template&lt;class BaseClass&gt; Templated&lt;BaseClass&gt;::Templated(int a) : BaseClass(a) { } template&lt;class BaseClass&gt; int Templated&lt;BaseClass&gt;::Foo() { return this-&gt;b; } </code></pre> <p><code>main.cpp</code>:</p> <pre><code>#include "template_test.h" int main() { Templated&lt;Base&gt; test(1); return test.Foo(); } </code></pre> <p>When I build the code, I get linker errors, saying that the symbols <code>Templated&lt;Base&gt;::Templated(int)</code> and <code>Templated&lt;Base&gt;::Foo()</code> cannot be found.</p> <p>A quick Google suggests that adding the following to <code>main.cpp</code> will solve the problem:</p> <pre><code>template&lt;&gt; Templated&lt;Base&gt;::Templated(int a); template&lt;&gt; int Templated&lt;Base&gt;::Foo(); </code></pre> <p>But this does not solve the problem. Adding the lines to <code>main.cpp</code> does not work either. (Though, interestingly, adding them to both gives 'multiply defined symbol' errors from the linker, so they must be doing something...)</p> <p><em>However</em>, putting all the code in one source file does solve the problem. While this would be ok for the noddy example above, the real application I'm looking at would become unmanageable very fast if I was forced to put the whole lot in one cpp file.</p> <p>Does anyone know if what I'm doing is even possible? (How) can I solve my linker errors?</p> <p>I would assume that I could make all the methods in <code>class Templated</code> inline and this would work, but this doesn't seem ideal either.</p>
[ { "answer_id": 207743, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": ".inl .tcc #include #include template_test.cpp template_test.inl template_test.tcc #include \"template_test.inl\" template_test.h #endif" }, { "answer_id": 207782, "author": "Andrew Stapleton", "author_id": 28506, "author_profile": "https://Stackoverflow.com/users/28506", "pm_score": -1, "selected": false, "text": "template<class BaseClass>\nclass Templated : public BaseClass\n {\npublic:\n Templated(int a) : BaseClass(a) {}\n virtual int Foo() { return BaseClass::b; }\n };\n void Nobody_Ever_Calls_This()\n{\n Templated<Base> dummy(1);\n}\n Templated<Widget>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17938/" ]
207,734
<p>we can use <code>time</code> in a unix environment to see how long something took...</p> <pre><code>shell&gt; time some_random_command real 0m0.709s user 0m0.008s sys 0m0.012s </code></pre> <p>is there an equivalent for recording memory usage of the process(es)?</p> <p>in particular i'm interested in peak allocation.</p>
[ { "answer_id": 208346, "author": "Andy Whitfield", "author_id": 4805, "author_profile": "https://Stackoverflow.com/users/4805", "pm_score": 0, "selected": false, "text": "ps v <pid>" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26094/" ]
207,744
<p>I'm looking for a good algorithm that can give me the unique edges from a set of polygon data. In this case, the polygons are defined by two arrays. One array is the number of points per polygon, and the other array is a list of vertex indices.</p> <p>I have a version that is working, but performance gets slow when reaching over 500,000 polys. My version walks over each face and adds each edge's sorted vertices to an stl::set. My data set will be primarily triangle and quad polys, and most edges will be shared.</p> <p>Is there a smarter algorithm for this?</p>
[ { "answer_id": 207757, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "A +-----+ B\n \\ |\\\n \\ 1 | \\\n \\ | \\\n \\ | 2 \\\n \\| \\\n C +-----+ D\n A - B -+\nB - C +- first polygon\nC - A -+\n\nB - D -+\nD - C +- second polygon\nC - B -+\n" }, { "answer_id": 10001827, "author": "namespace sid", "author_id": 708995, "author_profile": "https://Stackoverflow.com/users/708995", "pm_score": 0, "selected": false, "text": "typedef std::pair<int, int> Edge; Edge sampleEdge; std::map<Edge, bool> uniqueEdges; uniqueEdges[sampleEdge] = true;" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17209/" ]
207,763
<p>I recently saw an announcement and <a href="http://www.linux.com/feature/150399" rel="nofollow noreferrer">article</a> outlining the release of the first <a href="http://www.python.org/download/releases/3.0/" rel="nofollow noreferrer">Python 3.0</a> release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.</p>
[ { "answer_id": 209303, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 4, "selected": true, "text": "print print" }, { "answer_id": 800310, "author": "Zxaos", "author_id": 4924, "author_profile": "https://Stackoverflow.com/users/4924", "pm_score": 0, "selected": false, "text": "except urllib.error.URLError as e:\n if hasattr(e, 'reason'):\n #...\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416/" ]
207,768
<p>I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:</p> <pre><code>void IndexArray( unsigned int length, std::vector&lt;unsigned int&gt;&amp; v ) { v.resize(length); for ( unsigned int i = 0; i &lt; length; ++i ) { v[i] = i; } } </code></pre> <p>But this is a for-loop. Is there an elegant way to do this with less lines of code using stl functionality (and <strong>not</strong> using Boost)?</p>
[ { "answer_id": 207777, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 5, "selected": true, "text": "#include <iostream>\n#include <algorithm>\n#include <vector>\n\nstruct c_unique {\n int current;\n c_unique() {current=0;}\n int operator()() {return ++current;}\n} UniqueNumber;\n\n\nint main () {\n vector<int> myvector (8);\n generate (myvector.begin(), myvector.end(), UniqueNumber);\n\n cout << \"\\nmyvector contains:\";\n for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)\n cout << \" \" << *it;\n\n cout << endl;\n\n return 0;\n}\n" }, { "answer_id": 207795, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "iota void IndexArray(unsigned int length, vector<unsigned int>& v)\n{\n vector<unsigned int>(length).swap(v);\n iota(v.begin(), v.end(), 0);\n}\n" }, { "answer_id": 208141, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "std::generate template <typename T>\nstruct gen {\n T x;\n gen(T seed) : x(seed) { }\n\n T operator ()() { return x++; }\n};\n\ngenerate(a.begin(), a.end(), gen<int>(0));\n" }, { "answer_id": 208255, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 2, "selected": false, "text": "iota()" }, { "answer_id": 209440, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 0, "selected": false, "text": "int c_array[] = {3,4,5};\n\nconst int* pbegin = &c_array[0];\nconst size_t c_array_size = sizeof(c_array) / sizeof(c_array[0]);\nconst int* pend = pbegin + c_array_size;\n\nstd::vector<int> v;\nv.reserve(c_array_size);\nstd::copy(pbegin, pend, std:back_inserter(v));\n" }, { "answer_id": 5540676, "author": "Rick", "author_id": 634705, "author_profile": "https://Stackoverflow.com/users/634705", "pm_score": 1, "selected": false, "text": "// fill algorithm example\n#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\n\nint main () {\n vector<int> myvector (8); // myvector: 0 0 0 0 0 0 0 0\n\n fill (myvector.begin(),myvector.begin()+4,5); // myvector: 5 5 5 5 0 0 0 0\n fill (myvector.begin()+3,myvector.end()-2,8); // myvector: 5 5 5 8 8 8 0 0\n\n cout << \"myvector contains:\";\n for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)\n cout << \" \" << *it;\n\n cout << endl;\n\n return 0;\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
207,786
<p>I develop using MAMP pro on my Mac. When I start MAMP it prompts me for a password if I use port 80. If I use a higher port it doesn't prompt me, but I have to append the port number in the URL ( eg dev.local:8888 ). Does anyone know how to make it not prompt for password when using standard ports? Thank you.</p>
[ { "answer_id": 15050843, "author": "Anonymous", "author_id": 945722, "author_profile": "https://Stackoverflow.com/users/945722", "pm_score": 2, "selected": false, "text": "YOURPASSWORD YOURUSERNAME run-only do shell script \"/Applications/MAMP/bin/startApache.sh &\" password \"YOURPASSWORD\" user name \"YOURUSERNAME\" with administrator privileges\ndo shell script \"/Applications/MAMP/bin/startMysql.sh > /dev/null 2>&1\"\n startmySQL.sh startMysql.sh" }, { "answer_id": 17238053, "author": "bw_qa", "author_id": 1881324, "author_profile": "https://Stackoverflow.com/users/1881324", "pm_score": 1, "selected": false, "text": "sudo ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
207,789
<p>I am using sql express 2008 and vs2008, writing in c#.</p> <p>I have a db table with a Geography column in it, into which I need to put gps data I collected. When I tried creating an Entity-Framework mapping for this table, it just ignored the column with some warning about not being able to map such column types. I then looked at nHibernate.Spatial project, but it seems like it only translates the Geometry types, not the Geography. No luck there. I've been told I can use a view with casting the Geography to VarBinary, and then in the created entity class add another Property that deserializes the binary back into Geography. I guess that will work for reading the data from the db, but I also need to insert those rows into my db, and I can't add rows to the view. Is there some other trick I can use in order to easily read and write Geography data from my db, in my c# code?</p>
[ { "answer_id": 214159, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": true, "text": "IUserType" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28505/" ]
207,791
<p>It doesn't look like basic javascript but nor can I use JQuery commands like <code>$('myId')</code>. Is this or similar functions documented anywhere?</p> <p>For reason I don't want to go into, I am not able to use 3rd party libraries like JQuery but if some powerful javascript extensions come with asp then I would like to know about them. </p>
[ { "answer_id": 207846, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 1, "selected": false, "text": "\nfunction $()\n{\n alert('foo');\n} \n\n$();\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
207,793
<p>Is it possible to pass a path such as subject/name to a template then to use that path which is passed in the template as a path and not as a textual string. I am finding that the path is treated as text rather than a path.</p>
[ { "answer_id": 208838, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 1, "selected": false, "text": "dyn:evaluate()" }, { "answer_id": 217438, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 1, "selected": false, "text": "<xsl:varialble name=\"myvar\" select=\"document(somepath)/somenode\" />\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,800
<p>I am new to C and i have this question. why does the following code crash:</p> <pre><code>int *a = 10; *a = 100; </code></pre>
[ { "answer_id": 207807, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": false, "text": "int cell = 10;\nint *a = &cell; // a points to address of cell\n*a = 100; // content of cell changed\n" }, { "answer_id": 207810, "author": "zoul", "author_id": 17279, "author_profile": "https://Stackoverflow.com/users/17279", "pm_score": 1, "selected": false, "text": "int *a;\na = malloc(sizeof(int));\n*a = 10;\nprintf(\"a=%i\\n\", *a);\nfree(a);\n" }, { "answer_id": 207811, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "int * int *a = (int *) 10;\n*a = 100;\n" }, { "answer_id": 207813, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 2, "selected": false, "text": "int *a = 10;\n *a = 100;\n" }, { "answer_id": 207814, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 5, "selected": true, "text": "int *a = 10;\n int *a = malloc(sizeof(int));\n*a = 100;\n" }, { "answer_id": 207853, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "a = malloc(sizeof(int));\n long *a;\n int long a = malloc(sizeof *a);\n int sizeof sizeof" }, { "answer_id": 207911, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 0, "selected": false, "text": "(int*) a = 10;\n(*a) = 100;\n (void*) v = NULL;\n struct Hello {\n int id;\n char* name;\n};\n\n...\n\nstruct Hello* hello_ptr = malloc(sizeof Hello);\nhello_ptr->id = 5;\nhello_ptr->name = \"Cheery\";\n void* malloc(size_t size);\n free(hello_ptr);\n 0.1.2.3.4.5. 6\nC h e e r y \\0\n" }, { "answer_id": 207922, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 0, "selected": false, "text": "int* a = 10;\n*a = 100;\n \"Pointer-to-int 'a' becomes 10\"\n\"Value-pointed-to-by 'a' becomes 100\"\n \"Value-pointed-to-by 10 becomes 100\"\n int* ptr = (int*)10; // You've guessed at a memory address, and probably got it wrong\nint* ptr = malloc(sizeof(int)); // OS gives you a memory address at runtime \n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,824
<p><a href="http://wiki.eclipse.org/index.php/ATF/JSDT" rel="nofollow noreferrer">Javascript Developer Tools</a> (JSDT) for Eclipse provides a nice outline view of Javascript classes, with a little symbol next to them to indicate visibility. </p> <p>Looking at <em>Preferences->Javascript->Appearance->Members Sort Order</em>, it seems able to indicate whether a method is public, private or protected, but all of my use the "default" marker, a blue triangle.</p> <p>Does anyone know how it determines which symbol to use? I've tried using Javadoc and JSDoc formatted comments. My private methods start with a leading underscore, and that doesn't give it a hint either.</p> <p>Not a big deal, just would be nice to know...</p>
[ { "answer_id": 609438, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 0, "selected": false, "text": "@private" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6521/" ]
207,829
<p>I have a List object being accessed by multiple threads. There is mostly one thread, and in some conditions two threads, that updates the list. There are one to five threads that can read from this list, depending on the number of user requests being processed. The list is not a queue of tasks to perform, it is a list of domain objects that are being retrieved and updated concurrently.</p> <p>Now there are several ways to make the access to this list thread-safe:<br> -use synchronized block<br> -use normal <em>Lock</em> (i.e. read and write ops share same lock)<br> -use <em>ReadWriteLock</em><br> -use one of the new <em>ConcurrentBLABLBA</em> collection classes </p> <p><strong>My question:</strong><br> What is the optimal approach to use, given that the cricital sections typically do not contain a lot of operations (mostly just adding/removing/inserting or getting elements from the list)?<br> Can you recommend another approach, not listed above?</p> <p><strong>Some constrains</strong><br> -optimal performance is critical, memory usage not so much<br> -it must be an ordered list (currently synchronizing on an <em>ArrayList</em>), although not a sorted list (i.e. not sorted using Comparable or Comparator, but according to insertion order)<br> -the list will is big, containing up to 100000 domain objects, thus using something like CopyOnWriteArrayList not feasible<br> -the write/update ciritical sections are typically very quick, doing simple add/remove/insert or replace (set)<br> -the read operations will do primarily a elementAt(index) call most of the time, although some read operations might do a binary search, or indexOf(element)<br> -no direct iteration over the list is done, though operation like indexOf(..) will traverse list </p>
[ { "answer_id": 207937, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "ConcurrentHashMap ReadWriteLock ConcurrentSkipListMap" }, { "answer_id": 208953, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 1, "selected": false, "text": "class ServerCacheViewThingy {\n private static final int ACCEPTABLE_SIZE = 500;\n private int viewStart, viewLength;\n final Map<Integer, Record> items\n = new HashMap<Integer, Record>(1000);\n final ConcurrentLinkedQueue<Callback> callbackQueue\n = new ConcurrentLinkedQueue<Callback>();\n\n public void getRecords (int start, int length, ViewReciever reciever) {\n // remember the current view, to prevent records within\n // this view from being accidentally pruned.\n viewStart = start;\n viewLenght = length;\n\n // if the selected area is not already loaded, send a request\n // to load that area\n if (!rangeLoaded(start, length))\n addLoadRequest(start, length);\n\n // add the reciever to the queue, so it will be processed\n // when the data has arrived\n if (reciever != null)\n callbackQueue.add(new Callback(start, length, reciever));\n }\n\n class Callback {\n int start;\n int length;\n ViewReciever reciever;\n ...\n }\n\n class EditorThread extends Thread {\n\n private void prune () {\n if (items.size() <= ACCEPTABLE_SIZE)\n return;\n for (Map.Entry<Integer, Record> entry : items.entrySet()) {\n int position = entry.key();\n // if the position is outside the current view,\n // remove that item from the cache\n ...\n }\n }\n\n private void markDirty (int from) { ... }\n\n ....\n }\n\n class CallbackThread extends Thread {\n public void notifyCallback (Callback callback);\n private void processCallback (Callback) {\n readRecords\n }\n }\n}\n\ninterface ViewReciever {\n void recieveData (int viewStart, Record[] records);\n void recieveTimeout ();\n}\n" }, { "answer_id": 673863, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "import java.util.Collections;\nimport java.util.ArrayList;\n\nArrayList list = new ArrayList();\nList syncList = Collections.synchronizedList(list);\n\n// make sure you only use syncList for your future calls... \n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27602/" ]
207,837
<p>In a <a href="https://stackoverflow.com/questions/190524/mapping-computed-properties-in-linq-to-sql-to-actuall-sql-statements">previous question</a> I asked how to make "Computed properties" in a linq to sql object. The answer supplied there was sufficient for that specific case but now I've hit a similar snag in another case.</p> <p>I have a database with <strong>Items</strong> that have to pass through a number of <strong>Steps</strong>. I want to have a function in my database that retrieves the Current step of the item that I can then build on. For example:</p> <pre><code>var x = db.Items.Where(item =&gt; item.Steps.CurrentStep().Completed == null); </code></pre> <p>The code to get the current step is:</p> <pre><code>Steps.OrderByDescending(step =&gt; step.Created).First(); </code></pre> <p>So I tried to add an extension method to the <strong>EntitySet&lt;Step&gt;</strong> that returned a single <strong>Step</strong> like so:</p> <pre><code>public static OrderFlowItemStep CurrentStep(this EntitySet&lt;OrderFlowItemStep&gt; steps) { return steps.OrderByDescending(o =&gt; o.Created).First(); } </code></pre> <p>But when I try to execute the query at the top I get an error saying that the <em>CurrentStep()</em> function has no translation to SQL. Is there a way to add this functionality to Linq-to-SQL in any way or do I have to manually write the query every time? I tried to write the entire query out first but it's very long and if I ever change the way to get the active step of an item I have to go over all the code again.</p> <p>I'm guessing that the CurrentStep() method has to return a Linq expression of some kind but I'm stuck as to how to implement it.</p>
[ { "answer_id": 216733, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 2, "selected": true, "text": "using System;\nusing System.Linq;\nusing System.Linq.Expressions;\n\nclass Program {\n static void Main(string[] args) {\n Console.WriteLine(StringPredicate(c => Char.IsDigit(c)));\n var func = StringPredicate(c => Char.IsDigit(c)).Compile();\n Console.WriteLine(func(\"h2ello\"));\n Console.WriteLine(func(\"2ello\"));\n }\n\n public static Expression<Func<string,bool>> StringPredicate(Expression<Func<char,bool>> pred) {\n Expression<Func<string, char>> get = s => s.First();\n var p = Expression.Parameter(typeof(string), \"s\");\n return Expression.Lambda<Func<string, bool>>(\n Expression.Invoke(pred, Expression.Invoke(get, p)),\n p);\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26746/" ]
207,838
<p>There has been a lot of press about IPv6 and the impending switch over to IPv6 from IPv4. I have some understanding of IPv6, but I've often wondered how much impact IPv6 has on application development &amp; design (specifically)?</p> <p>Are there some tangible/well known benefits IPv6 provides which we don't already have today?</p> <p>I know Windows Vista and Server 2008 support IPv6 out-of-the-box, is anyone using (or designing with IPv6 in mind) today, and if so, what are the benefits? Should we be considering IPv6 in current and future projects?</p> <p>Are there any <em>good</em> examples of IPv6-aware applications? </p>
[ { "answer_id": 378212, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": false, "text": "AF_INET struct sockaddr_in getaddrinfo() AF_INET6 getaddrinfo memset(&hints, 0, sizeof(struct addrinfo));\n hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */\n hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */\n hints.ai_flags = 0;\n hints.ai_protocol = 0; /* Any protocol */\n\n s = getaddrinfo(hostname, service, &hints, &result);\n if (s != 0) {\n fprintf(stderr, \"getaddrinfo: %s\\n\", gai_strerror(s));\n exit(EXIT_FAILURE);\n }\n\n /* getaddrinfo() returns a list of address structures.\n Try each address until we successfully connect(2).\n If socket(2) (or connect(2)) fails, we (close the socket\n and) try the next address. */\n\n for (rp = result; rp != NULL; rp = rp->ai_next) {\n sfd = socket(rp->ai_family, rp->ai_socktype,\n rp->ai_protocol);\n if (sfd == -1)\n continue;\n\n if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)\n break; /* Success */\n\n close(sfd);\n }\n\n if (rp == NULL) { /* No address succeeded */\n fprintf(stderr, \"Could not connect\\n\");\n exit(EXIT_FAILURE);\n }\n\n freeaddrinfo(result); /* No longer needed */\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18471/" ]
207,843
<p>I am using Eclipse 3.3 ("Europa"). Periodically, Eclipse takes an inordinately long time (perhaps forever) to start up. The only thing I can see in the Eclipse log is:</p> <pre> !ENTRY org.eclipse.core.resources 2 10035 2008-10-16 09:47:34.801 !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes. </pre> <p>Googling reveals <a href="http://dev.zhourenjian.com/blog/2007/11/07/eclipse-freezing-on-start.html" rel="noreferrer">someone's suggestion</a> that I remove the folder:</p> <pre><code>workspace\.metadata\.plugins\org.eclipse.core.resources\.root\.indexes </code></pre> <p>This does not appear to have helped.</p> <p>Short of starting with a new workspace (something which I am not keen to do, as it takes me hours to set up all my projects again properly), is there a way to make Eclipse start up properly?</p>
[ { "answer_id": 208148, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 5, "selected": false, "text": "Eclipse -clean -clean Linux Eclipse" }, { "answer_id": 209834, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "Refresh workspace on startup" }, { "answer_id": 752274, "author": "Jason", "author_id": 91158, "author_profile": "https://Stackoverflow.com/users/91158", "pm_score": 9, "selected": true, "text": "<workspace>\\.metadata\\.plugins\\org.eclipse.core.resources\\.projects\\<project>\\.markers.snap\n" }, { "answer_id": 4113654, "author": "Daniel", "author_id": 435938, "author_profile": "https://Stackoverflow.com/users/435938", "pm_score": 4, "selected": false, "text": "Windows Preferences General eclipse" }, { "answer_id": 4540122, "author": "user555135", "author_id": 555135, "author_profile": "https://Stackoverflow.com/users/555135", "pm_score": 4, "selected": false, "text": "<eclipse workspace>/.metadata/.plugins/org.eclipse.core.resources/.projects\n find <eclipse_workspace>/.metadata/.plugins/org.eclipse.core.resources/.projects -name \"*.snap\" -exec rm -f {} \\;\n" }, { "answer_id": 5018562, "author": "User1", "author_id": 125380, "author_profile": "https://Stackoverflow.com/users/125380", "pm_score": 2, "selected": false, "text": "-refresh -clean" }, { "answer_id": 5504530, "author": "Hendy Irawan", "author_id": 122441, "author_profile": "https://Stackoverflow.com/users/122441", "pm_score": 5, "selected": false, "text": "Eclipse Eclipse Eclipse" }, { "answer_id": 12528785, "author": "Rafa", "author_id": 898376, "author_profile": "https://Stackoverflow.com/users/898376", "pm_score": 6, "selected": false, "text": "find $WORKSPACE_DIR/.metadata/.plugins/org.eclipse.core.resources/.projects \\\n-name .indexes -exec rm -fr {} \\;\n rm $WORKSPACE_DIR/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi\n" }, { "answer_id": 16307087, "author": "Zoccadoum", "author_id": 1316393, "author_profile": "https://Stackoverflow.com/users/1316393", "pm_score": 0, "selected": false, "text": "# adb devices\nList of devices attached \nXXXXXX offline\n # adb kill-server\n # adb start-server\n" }, { "answer_id": 18810283, "author": "user742102", "author_id": 742102, "author_profile": "https://Stackoverflow.com/users/742102", "pm_score": 0, "selected": false, "text": "ex. E:\\workspaceFolder\\.metadata\\.plugins\\org.eclipse.core.resources\n" }, { "answer_id": 22558338, "author": "persianLife", "author_id": 1424585, "author_profile": "https://Stackoverflow.com/users/1424585", "pm_score": 5, "selected": false, "text": "eclipse -clean -clearPersistedState" }, { "answer_id": 26348445, "author": "Oded Breiner", "author_id": 710284, "author_profile": "https://Stackoverflow.com/users/710284", "pm_score": 2, "selected": false, "text": "-clean\n-refresh\n-startup\n../../../plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar\n--launcher.library\n" }, { "answer_id": 33338170, "author": "Kaidul", "author_id": 1162233, "author_profile": "https://Stackoverflow.com/users/1162233", "pm_score": 0, "selected": false, "text": "eclipse -clean -refresh" }, { "answer_id": 48264045, "author": "tibi", "author_id": 390436, "author_profile": "https://Stackoverflow.com/users/390436", "pm_score": 0, "selected": false, "text": "workspace/.metadata/.plugins/org.eclipse.e4.workbench\n" }, { "answer_id": 49366506, "author": "Mark F Guerra", "author_id": 238328, "author_profile": "https://Stackoverflow.com/users/238328", "pm_score": 0, "selected": false, "text": "Window --> Preferences --> General --> Network Connections \"Requires Authentication\"" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4728/" ]
207,848
<p>How do I get the full width result for the *nix command "<strong>ps</strong>"?<br /> I know we can specify something like <code>--cols 1000</code> but is there anyway I can the columns and just print out everything?</p>
[ { "answer_id": 207864, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 4, "selected": true, "text": "ps -w -w aux" }, { "answer_id": 207893, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "w ps ps auwwx ps" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4037/" ]
207,851
<p>I want to create a Silverlight 2 control that has two content areas. A Title and a MainContent. So the control would be:</p> <pre><code>&lt;StackPanel&gt; &lt;TextBlock Text=" CONTENT1 "/&gt; &lt;Content with CONTENT2 "/&gt; &lt;/StackPanel&gt; </code></pre> <p>When I use the control I should just be able to use:</p> <pre><code>&lt;MyControl Text="somecontent"&gt;main content &lt;/MyControl&gt; </code></pre> <p>How can I create such a control?</p>
[ { "answer_id": 207897, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": true, "text": "[ContentProperty(\"Child\")]\npublic partial class MyControl: UserControl\n{\n public static readonly DependencyProperty ChildProperty = DependencyProperty.Register(\"Child\", typeof(UIElement), typeof(MyControl), null);\n\n public UIElement Child\n {\n get { return (UIElement)this.GetValue(ChildProperty); }\n set\n {\n this.SetValue(ChildProperty, value);\n this.content.Content = value;\n }\n }\n <MyControl Text=\"somecontent\">main content </MyControl> <MyControl>\n <MyControl.Content1>Hello World</MyControl.Content1>\n <MyControl.Content2>Goodbye World</MyControl.Content2>\n</MyControl>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
207,867
<p>Is it less efficient to use TEXT than varchar in an SQL database?</p> <p>If so why?</p> <p>If not why would you not just always use TEXT?</p> <p>I'm not targetting a specific database here but oracle is probably the most relevant, although I'm testing on MySQL for the time being as part of a proof of concept.</p>
[ { "answer_id": 207874, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 3, "selected": true, "text": "varchar(max) WHERE varchar,nvarchar and varbinary" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
207,871
<p>I need to use utf-8 characters in my perl-documentation. If I use:</p> <pre><code>perldoc MyMod.pm </code></pre> <p>I see strange characters. If I use:</p> <pre><code>pod2text MyMod.pm </code></pre> <p>everything is fine.</p> <p>I use Ubuntu/Debian.</p> <pre><code>$ locale LANG=de_DE.UTF-8 LC_CTYPE="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" LC_COLLATE="de_DE.UTF-8" LC_MONETARY="de_DE.UTF-8" LC_MESSAGES="de_DE.UTF-8" LC_PAPER="de_DE.UTF-8" LC_NAME="de_DE.UTF-8" LC_ADDRESS="de_DE.UTF-8" LC_TELEPHONE="de_DE.UTF-8" LC_MEASUREMENT="de_DE.UTF-8" LC_IDENTIFICATION="de_DE.UTF-8" LC_ALL=de_DE.UTF-8 </code></pre> <p>Is there a HowTo about using special characters in Pod?</p> <p>Here is a small example using german umlauts "Just a Test: äöüßÄÖ":</p> <pre><code>$ perldoc perl/MyMod.pm &lt;standard input&gt;:72: warning: can't find character with input code 159 &lt;standard input&gt;:72: warning: can't find character with input code 150 MyMod(3) User Contributed Perl Documentation MyMod(3) NAME MyMod.pm - Just a Test: äöüÃÃà perl v5.10.0 2008-10-16 MyMod(3) </code></pre>
[ { "answer_id": 208699, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 5, "selected": true, "text": "=encoding utf-8 perldoc" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27239/" ]
207,878
<p>I have the following code that sets a cookie:</p> <pre><code> string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue; HttpCookie cookie = new HttpCookie("localization",locale); cookie.Expires= DateTime.Now.AddYears(1); Response.Cookies.Set(cookie); </code></pre> <p>However, when I try to read the cookie, the Value is Null. The cookie exists. I never get past the following if check:</p> <pre><code> if (Request.Cookies["localization"] != null &amp;&amp; !string.IsNullOrEmpty(Request.Cookies["localization"].Value)) </code></pre> <p>Help?</p>
[ { "answer_id": 208159, "author": "aunlead", "author_id": 28321, "author_profile": "https://Stackoverflow.com/users/28321", "pm_score": 0, "selected": false, "text": "string locale = ((DropDownList)this.LoginUser.FindControl(\"locale\"))\n .SelectedValue; \nHttpCookie myCookie = new HttpCookie(\"localization\");\nResponse.Cookies.Add(myCookie);\nmyCookie.Values.Add(\"locale\", locale);\nResponse.Cookies[\"localization\"].Expires = DateTime.Now.AddYears(1);\n if (Request.Cookies[\"localization\"] != null)\n{\n HttpCookie cookie = Request.Cookies[\"localization\"];\n string locale = cookie.Values[\"locale\"].ToString();\n}\n" }, { "answer_id": 7573094, "author": "Jeriboy Flaga", "author_id": 967583, "author_profile": "https://Stackoverflow.com/users/967583", "pm_score": 1, "selected": false, "text": "<form> <form id=\"form1\" runat=\"server\"> <form id=\"form1\" action=\"DisplayName.aspx\" runat=\"server\"> Response.Redirect(\"DisplayName.aspx\");" }, { "answer_id": 15535022, "author": "Simon Molloy", "author_id": 942604, "author_profile": "https://Stackoverflow.com/users/942604", "pm_score": 0, "selected": false, "text": "Private Sub SetPageSize(ByVal pageSize As Integer)\n\n ' Set cookie value to pageSize\n Dim pageSizeCookie As HttpCookie = New HttpCookie(pageSizeCookieName)\n With pageSizeCookie\n .Expires = Now.AddYears(100)\n .Value = pageSize.ToString\n End With\n\n ' Add to response to save it\n Me.Response.Cookies.Add(pageSizeCookie)\n\n ' Add to request so available for postback\n Me.Request.Cookies.Remove(pageSizeCookieName)\n Me.Request.Cookies.Add(pageSizeCookie)\n\nEnd Sub\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090/" ]
207,881
<p>I've a dialog which contains a Qt TabWidget with a number of tabs added. </p> <p>I'd like to hide one of the tabs. </p> <pre><code>_mytab-&gt;hide() </code></pre> <p>doesn't work. I don't want to just delete the tab and all its widgets from the .ui file because other code relies on the widgets within the tab. However, it would be fine to generate the tab code but somehow not ::insertTab in the generated uic_mydialog.cpp. Setting the hidden property in the ui file does not work either.</p> <p>I'm using Qt 3.3</p>
[ { "answer_id": 208425, "author": "Jérôme", "author_id": 2796, "author_profile": "https://Stackoverflow.com/users/2796", "pm_score": 4, "selected": true, "text": "_myTabDlg->removePage(_mytab);\n" }, { "answer_id": 208441, "author": "AMM", "author_id": 11212, "author_profile": "https://Stackoverflow.com/users/11212", "pm_score": 3, "selected": false, "text": "ui.genTab->removeTab(1); // removes the tab at the index 1 which is the second tab from left\n\n\nui.genTab->insertTab(1, ui.tabX, \"<Name of TabX>\"); // The tab is added back.\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23434/" ]
207,889
<p>I want this method to work for any given number of arguments, i can do that with code generation(with a lot of ugly code), can it be done with recursion? if so how? I understand recursion, but i dont know how to write this.</p> <pre><code>private static void allCombinations(List&lt;String&gt;... lists) { if (lists.length == 3) { for (String s3 : lists[0]) { for (String s1 : lists[1]) { for (String s2 : lists[2]) { System.out.println(s1 + "-" + s2 + "-" + s3); } } } } if (lists.length == 2) { for (String s3 : lists[0]) { for (String s1 : lists[1]) { System.out.println(s1 + "-" + s3); } } } } </code></pre>
[ { "answer_id": 207912, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "public static void allCombinations(List<String>... lists) {\n int[] indexes = new int[lists.length];\n\n while (incrementIndexes(lists, indexes)) {\n StringBuilder builder = new StringBuilder();\n for (int i=0; i < indexes.length; i++) {\n if (i != 0) {\n builder.append(\"-\");\n }\n builder.append(lists[i].get(indexes[i]));\n }\n System.out.println(builder);\n }\n}\n\nprivate static boolean incrementIndexes(List<String>[] lists, int[] indexes) {\n for (int depth = indexes.length-1; depth >= 0; depth--) {\n indexes[depth]++;\n if (indexes[depth] != lists[depth].size()) {\n return true;\n }\n // Overflowed this index. Reset to 0 and backtrack\n indexes[depth] = 0;\n }\n // Everything is back to 0. Finished!\n return false;\n}\n" }, { "answer_id": 207933, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 2, "selected": false, "text": "private static void allCombinations(List<String>... lists) {\n allCombinations(lists, 0, \"\");\n}\n\nprivate static void allCombinations(List<String>[] lists, int index, String pre) {\n for (String s : lists[index]) {\n if (index < lists.length - 1) {\n allCombinations(lists, index + 1, pre + s + \"-\");\n }else{\n System.out.println(pre + s);\n }\n }\n}\n" }, { "answer_id": 208014, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "import java.util.*;\n\npublic class Test\n{\n public interface Action<T> {\n void execute(Iterable<T> values);\n }\n\n public static void main(String[] args) {\n List<String> first = Arrays.asList(new String[]{\"1\", \"2\", \"3\"});\n List<String> second = Arrays.asList(new String[]{\"a\", \"b\", \"c\"});\n List<String> third = Arrays.asList(new String[]{\"x\", \"y\"});\n Action<String> action = new Action<String>() {\n @Override public void execute(Iterable<String> values) {\n StringBuilder builder = new StringBuilder();\n for (String value : values) {\n if (builder.length() != 0) {\n builder.append(\"-\");\n }\n builder.append(value);\n }\n System.out.println(builder);\n }\n };\n permute(action, first, second, third);\n }\n\n public static <T> void permute(Action<T> action, Iterable<T>... lists) {\n Stack<T> current = new Stack<T>();\n permute(action, lists, 0, current);\n }\n\n public static <T> void permute(Action<T> action, Iterable<T>[] lists,\n int index, Stack<T> current) {\n for (T element : lists[index]) {\n current.push(element);\n if (index == lists.length-1) {\n action.execute(current);\n } else {\n permute(action, lists, index+1, current);\n }\n current.pop();\n }\n }\n}\n" }, { "answer_id": 208082, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 0, "selected": false, "text": "import java.util.Arrays;\nimport java.util.List;\n\n\npublic class Test {\n\n public static void main(String[] args) {\n List<String> first = Arrays.asList(new String[]{\"1\", \"2\", \"3\"});\n List<String> second = Arrays.asList(new String[]{\"a\", \"b\", \"c\"});\n List<String> third = Arrays.asList(new String[]{\"x\", \"y\", \"z\"});\n allCombinations (first, second, third);\n }\n\n private static void allCombinations(List<String>... lists) {\n allCombinations(lists, 1, \"\");\n }\n\n private static void allCombinations(List<String>[] lists, int index, String pre) {\n int nextHop = hop(index, lists.length-1);\n for (String s : lists[index]) {\n if (index != 0) {\n allCombinations(lists, nextHop, pre + s + \"-\");\n } else System.out.println(pre + s);\n }\n }\n private static int hop(int prevIndex, int maxResult){\n if (prevIndex%2 == 0){\n return prevIndex-2;\n } else {\n if (prevIndex == maxResult) \n return prevIndex-1;\n int nextHop = prevIndex+2;\n if (nextHop > maxResult){\n return maxResult;\n } else return nextHop;\n }\n }\n\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,896
<p>I have a C#/.NET program that can run both as a console application and as a service. Currently I give it a command-line option to start as a console application, but I would like to avoid that.</p> <p>Is it possible to programmatically detect whether my program is being started as a service? </p> <p>If it was pure Win32, I could try starting as a service with StartServiceCtrlDispatcher and fall back to console if it returned ERROR_FAILED_SERVICE_CONTROLLER_CONNECT, but System.ServiceProcess.ServiceBase.Run() pops up an errordialog if it fails and then just returns without signaling an error to the program.</p> <p>Any ideas?</p>
[ { "answer_id": 6202990, "author": "Chin Siang", "author_id": 779622, "author_profile": "https://Stackoverflow.com/users/779622", "pm_score": 2, "selected": false, "text": "[DllImport(\"kernel32.dll\", SetLastError = true)]\nstatic extern IntPtr GetStdHandle(int nStdHandle);\nconst int STD_OUTPUT_HANDLE = -11;\n\nIntPtr iStdOut = GetStdHandle(STD_OUTPUT_HANDLE);\n\nif (iStdOut == IntPtr.Zero)\n\n{ \n app.RunAsWindowsService = true;\n\n}\n\n// Run as Service\nif (runAsWindowsService) \n{\n // .....\n ServiceBase.Run(myService);\n}\nelse \n{\n // Run as Console\n // Register Ctrl+C Handler...\n}\n" }, { "answer_id": 16237507, "author": "Dylan Nissley", "author_id": 620178, "author_profile": "https://Stackoverflow.com/users/620178", "pm_score": 2, "selected": false, "text": "static bool RunningAsService() {\n var p = ParentProcessUtilities.GetParentProcess();\n return ( p != null && p.ProcessName == \"services\" );\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5542/" ]
207,899
<p>I have a database that contains a table that looks a bit like this:</p> <p>PropertyId, EntityId, Value</p> <p>PropertyId and EntityId are a combined primary key. Every Entity is spread over a couple of rows where every row contains a single property of the entity. I have no control over this database so I'll have to work with it.</p> <p>Is it possible to use NHibernate to map entities from this table to single objects? I only have to read from this table, this might make things a bit easier. Or would I be better off just using DataReaders and do the mapping myself?</p>
[ { "answer_id": 212838, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "map <map name='Values' table='EntityPropertyValue'>\n <key column='EntityId' />\n <index-many-to-many class='Person' column='PersonId' />\n <element column='Value' type='object' />\n</map>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3320/" ]
207,901
<p>I have a databound <code>DataGridView</code>. When a new row is added and the user presses <kbd>Esc</kbd> I want to delete the entire row. How can I do this?</p>
[ { "answer_id": 207970, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 3, "selected": false, "text": "private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)\n{\n if (e.KeyChar == (char)27)\n {\n if (dataGridView1.Rows.Count > 0)\n {\n dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);\n MessageBox.Show(\"Last row deleted!\");\n }\n e.Handled = true;\n }\n}\n" }, { "answer_id": 681591, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "DataGridView IBindingList" }, { "answer_id": 1393880, "author": "andrecarlucci", "author_id": 22693, "author_profile": "https://Stackoverflow.com/users/22693", "pm_score": 3, "selected": false, "text": "public partial class YourForm : Form {\n\n private BindingSource _source = new BindingSource();\n\n public YourForm() {\n List<Model> list = _service.GetList();\n _source.DataSource = list;\n _grid.DataSource = _source;\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
207,938
<p>I'm not sure what the best api for simple 2d graphics with Java is. I know <code>java.awt.Graphics2D</code> was the standard but has it been replaced? Swing is the new API for Java GUI apps but it seems a bit heavy for what I want. What I really want is something like the C <a href="http://libsdl.org/" rel="noreferrer">SDL library</a>.</p>
[ { "answer_id": 207982, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "Graphics2D" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3165/" ]
207,939
<p>I was wondering if anybody could point me towards a free ftps module for python.</p> <p>I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.</p> <p>thanks,</p> <p>David.</p>
[ { "answer_id": 208256, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 3, "selected": false, "text": "FTPClient.connectFactory connectSSL connectTCP" }, { "answer_id": 215529, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 2, "selected": false, "text": ">>> from M2Crypto import ftpslib\n>>> f = ftpslib.FTP_TLS()\n>>> f.connect('', 9021)\n'220 spinnaker.dyndns.org M2Crypto (Medusa) FTP/TLS server v0.07 ready.'\n>>> f.auth_tls()\n>>> f.set_pasv(0)\n>>> f.login('ftp', 'ngps@')\n'230 Ok.'\n>>> f.retrlines('LIST')\n-rw-rw-r-- 1 0 198 2326 Jul 3 1996 apache_pb.gif\ndrwxrwxr-x 7 0 198 1536 Oct 10 2000 manual\ndrwxrwxr-x 2 0 198 512 Oct 31 2000 modpy\ndrwxrwxr-x 2 0 198 512 Oct 31 2000 bobo\ndrwxr-xr-x 2 0 198 14336 May 28 15:54 postgresql\ndrwxr-xr-x 4 100 198 512 May 16 17:19 home\ndrwxr-xr-x 7 100 100 3584 Sep 23 2000 openacs\ndrwxr-xr-x 10 0 0 512 Aug 5 2000 python1.5\n-rw-r--r-- 1 100 198 326 Jul 29 03:29 index.html\ndrwxr-xr-x 12 0 0 512 May 31 17:08 python2.1\n'226 Transfer complete'\n>>> f.quit()\n'221 Goodbye.'\n>>>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10171/" ]
207,947
<p>How do I get a platform-dependent newline in Java? I can’t use <code>"\n"</code> everywhere.</p>
[ { "answer_id": 207950, "author": "abahgat", "author_id": 27565, "author_profile": "https://Stackoverflow.com/users/27565", "pm_score": 9, "selected": false, "text": "System.getProperty(\"line.separator\");\n" }, { "answer_id": 209771, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 10, "selected": true, "text": "%n Calendar c = ...;\nString s = String.format(\"Duke's Birthday: %1$tm %1$te,%1$tY%n\", c); \n//Note `%n` at end of line ^^\n\nString s2 = String.format(\"Use %%n as a platform independent newline.%n\"); \n// %% becomes % ^^\n// and `%n` becomes newline ^^\n" }, { "answer_id": 8941436, "author": "Damaji kalunge", "author_id": 1160607, "author_profile": "https://Stackoverflow.com/users/1160607", "pm_score": 4, "selected": false, "text": "BufferedWriter newLine()" }, { "answer_id": 10937340, "author": "StriplingWarrior", "author_id": 120955, "author_profile": "https://Stackoverflow.com/users/120955", "pm_score": 10, "selected": false, "text": "System.lineSeparator()" }, { "answer_id": 13719364, "author": "Gary Davies", "author_id": 458065, "author_profile": "https://Stackoverflow.com/users/458065", "pm_score": -1, "selected": false, "text": "String separator = System.getProperty( \"line.separator\" );\nStringBuilder lines = new StringBuilder( line1 );\nlines.append( separator );\nlines.append( line2 );\nlines.append( separator );\nString result = lines.toString( );\n" }, { "answer_id": 16217976, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 5, "selected": false, "text": "String.format(\"%n\") String.format(\"%n\").intern()" }, { "answer_id": 32842574, "author": "Sathesh", "author_id": 2873923, "author_profile": "https://Stackoverflow.com/users/2873923", "pm_score": 4, "selected": false, "text": "StringBuilder newLine=new StringBuilder();\nnewLine.append(\"abc\");\nnewline.append(System.getProperty(\"line.separator\"));\nnewline.append(\"def\");\nString output=newline.toString();\n" }, { "answer_id": 73991121, "author": "sahlaysta", "author_id": 15456485, "author_profile": "https://Stackoverflow.com/users/15456485", "pm_score": 0, "selected": false, "text": "public static String getSystemNewLine() {\n try {\n StringWriter sw = new StringWriter();\n BufferedWriter bw = new BufferedWriter(sw);\n bw.newLine();\n bw.flush();\n String s = sw.toString();\n bw.close();\n return s;\n } catch (Exception e) {\n throw new Error(e);\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]