qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
365,868
<p>I have a fairly standard rails app and would like to be able to access the basic CRUD (Create, Update, Delete) operations as well as queries I have added, from an iPhone app. Rails provides the REST API for these operations more or less out of the box. </p> <p>What is the best approach to deal with the REST/XML part on the iphone, and are there any good objective-C libraries that do this kind of thing already? The operations will also need to be associated with a particular user (i.e. authenticated).</p>
[ { "answer_id": 365928, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 2, "selected": false, "text": "initWithMethod:delegate:params:" }, { "answer_id": 367974, "author": "diclophis", "author_id": 32678, "author_profile": "https://Stackoverflow.com/users/32678", "pm_score": 3, "selected": false, "text": "plist = {'a' => 'b', 'c' => 'd', 'e' => {'f' => 'g', 'h' => {'i' => 'j'}}}.to_plist\nrender(:text => plist)\n NSURL *url = [NSURL URLWithString:@\"http://somewhere.com\"]; \nNSURLRequest *request = [NSURLRequest requestWithURL:url];\nNSURLResponse *response;\nNSError *error;\nNSData *plistData;\nplistData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];\nNSPropertyListFormat format;\nNSString *errorStr;\nid imagesToRate = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorStr];\nif(!imagesToRate) {\n NSLog(errorStr);\n} else {\n NSLog(@\"%@\", [imagesToRate objectForKey:@\"e\"]);\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42404/" ]
365,887
<p>I know how they are different syntactically, and that C++ uses new, and C uses malloc. But how do they work, in a high-level explanation?</p> <p>See <a href="https://stackoverflow.com/questions/240212/what-is-the-difference-between-newdelete-and-mallocfree#240308">What is the difference between new/delete and malloc/free?</a></p>
[ { "answer_id": 365891, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "new (a, b, c) TypeId;\n\n// the function called by the compiler has to have the following signature:\noperator new(std::size_t size, TypeOfA a, TypeOfB b, TypeOf C c);\n new_handler std::bad_alloc throw() no-throw nothrow_t new (std::nothrow) TypeId;\n placement new // the following function is defined implicitly in the standard library\nvoid * operator(std::size_t size, void * ptr) throw() {\n return ptr;\n}\n new (a, b, c) TypeId;\n void* int * a = new int;\n=> void * operator new(std::size_t size) throw(std::bad_alloc);\ndelete a;\n=> void operator delete(void * ptr) throw();\n\nTypeWhosCtorThrows * a = new (\"argument\") TypeWhosCtorThrows;\n=> void * operator new(std::size_t size, char const* arg1) throw(std::bad_alloc);\n=> void operator delete(void * ptr, char const* arg1) throw();\n\nTypeWhosCtorDoesntThrow * a = new (\"argument\") TypeWhosCtorDoesntThrow;\n=> void * operator new(std::size_t size, char const* arg1) throw(std::bad_alloc);\ndelete a;\n=> void operator delete(void * ptr) throw();\n new (possible_arguments) TypeId[N];\n operator new[] operator new sizeof(TypeId)*N new T[5] new[](sizeof(T)*5+x) new(2,f) T[5] new[](sizeof(T)*5+y,2,f)" }, { "answer_id": 365894, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "new malloc operator new new" }, { "answer_id": 365914, "author": "Jay Conrod", "author_id": 1891, "author_profile": "https://Stackoverflow.com/users/1891", "pm_score": 1, "selected": false, "text": "malloc free new delete new malloc malloc malloc free sbrk mmap" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25632/" ]
365,888
<p>Now, I realise the initial response to this is likely to be "you can't" or "use analytics", but I'll continue in the hope that someone has more insight than that.</p> <p>Google adwords with "autotagging" appends a "gclid" (presumably "google click id") to link that sends you to the advertised site. It appears in the web log since it's a query parameter, and it's used by analytics to tie that visit to the ad/campaign.</p> <p>What I would like to do is to extract any useful information from the gclid in order to do our own analysis on our traffic. The reasons for this are:</p> <ul> <li>Stats are imperfect, but if we are collating them, we know exactly what assumptions we have made, and how they were calculated.</li> <li>We can tie the data to the rest of our data and produce far more accurate stats wrt conversion rate.</li> <li>We don't have to rely on javascript for conversions.</li> </ul> <p>Now it is clear that the gclid is base64 encoded (or some close variant), and some parts of it vary more than others. Beyond that, I haven't been able to determine what any of it relates to.</p> <p>Does anybody have any insight into how I might approach decoding this, or has anybody already related gclids back to compaigns or even accounts?</p> <p>I have spoken to a couple of people at google, and despite their "don't be evil" motto, they were completely unwilling to discuss the possibility of divulging this information, even under an NDA. It seems they like the monopoly they have over <em>our</em> web stats.</p>
[ { "answer_id": 5887955, "author": "Jeff Wu", "author_id": 538336, "author_profile": "https://Stackoverflow.com/users/538336", "pm_score": 2, "selected": false, "text": ".*[?&]gclid=([^$&]*)\n .*[?&]q=([^$&]*).*\n" }, { "answer_id": 20616153, "author": "andre", "author_id": 3108126, "author_profile": "https://Stackoverflow.com/users/3108126", "pm_score": 4, "selected": false, "text": "gclid ei ei" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26334/" ]
365,892
<p>Duplicate Of : <a href="https://stackoverflow.com/questions/2527/c-treeview-context-menus">Find node clicked under context menu</a></p> <p>I've got a context menu on a Treeview, when the user right clicks it supposed to change based on the currently right clicked node's tag object.</p> <p>Currently I'm updating the context menu in after_select event, however this doesn't work when user right clicks to another node without selecting it.</p> <p>How can I detect which node right clicked and change the context menu? Or am I doing it wrong?</p>
[ { "answer_id": 5887955, "author": "Jeff Wu", "author_id": 538336, "author_profile": "https://Stackoverflow.com/users/538336", "pm_score": 2, "selected": false, "text": ".*[?&]gclid=([^$&]*)\n .*[?&]q=([^$&]*).*\n" }, { "answer_id": 20616153, "author": "andre", "author_id": 3108126, "author_profile": "https://Stackoverflow.com/users/3108126", "pm_score": 4, "selected": false, "text": "gclid ei ei" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40322/" ]
365,898
<p>I'm familiar with .NET and with SQL. Now I'm looking at the new LINQ and it looks to me just like a cursor. I understand the ease of use, etc., but if I do a LINQ-to-SQL query with a foreach loop, am I just using a DB cursor? Or is there some sort of magic behind the scenes where LINQ collects all the data at once and feeds it to my program one row at a time?</p>
[ { "answer_id": 365916, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "IDataReader IDataReader .ToArray() .ToList() IEnumerable[<T>] .ToEnumerable()" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12897/" ]
365,935
<p>All of my methods are failing me in various ways. different lighting can mess it all up too.</p> <p>has anyone every trying to return a name given a rgb value? "red" "green" "blue" would be enough to satisfy my needs for today.</p> <p>i have unsafe byte processing of images from my web cam.</p> <p><a href="https://i.stack.imgur.com/ptjtc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ptjtc.png" alt="webcam"></a> </p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Color_star-en.svg/646px-Color_star-en.svg.png" alt="colors"></p>
[ { "answer_id": 365942, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "IsNamedColor Color test = Color.FromArgb(255,0,0);\n Color known = (\n from prop in typeof(Color)\n .GetProperties(BindingFlags.Public | BindingFlags.Static)\n where prop.PropertyType == typeof(Color)\n let color = (Color)prop.GetValue(null, null)\n where color.A == test.A && color.R == test.R\n && color.G == test.G && color.B == test.B\n select color)\n .FirstOrDefault();\n\n Console.WriteLine(known.Name);\n" }, { "answer_id": 365949, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": false, "text": "let Diff (c1:Color) (c2:Color) =\n let dr = (c1.R - c2.R) |> int\n let dg = (c1.G - c2.G) |> int\n let db = (c1.B - c2.B) |> int\n dr*dr + dg*dg + db*db\n" }, { "answer_id": 12812292, "author": "satya", "author_id": 770641, "author_profile": "https://Stackoverflow.com/users/770641", "pm_score": 2, "selected": false, "text": "static char[] hexDigits = {\n '0', '1', '2', '3', '4', '5', '6', '7',\n '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};\n\n\n\npublic static string ColorToHexString(Color color)\n {\n byte[] bytes = new byte[4];\n bytes[0] = color.A;\n bytes[1] = color.R;\n bytes[2] = color.G;\n bytes[3] = color.B;\n char[] chars = new char[bytes.Length * 2];\n for (int i = 0; i < bytes.Length; i++)\n {\n int b = bytes[i];\n chars[i * 2] = hexDigits[b >> 4];\n chars[i * 2 + 1] = hexDigits[b & 0xF];\n }\n return new string(chars);\n }\n" }, { "answer_id": 39142758, "author": "TaW", "author_id": 3152130, "author_profile": "https://Stackoverflow.com/users/3152130", "pm_score": 1, "selected": false, "text": "string ColorName(Color c)\n{\n List<float> hues = new List<float>()\n { 0, 15, 35, 44, 54, 63, 80, 160, 180, 200, 244, 280, 350, 360};\n List<string> hueNames = new List<string>()\n { \"red\", \"orange-red\", \"orange\", \"yellow-orange\", \"yellow\",\n \"yellow-green\", \"green\" , \"blue-green\" , \"cyan\", \"blue\", \n \"violet\", \"purple\", \"red\" };\n\n float h = c.GetHue();\n float s = c.GetSaturation();\n float b = (c.R * 0.299f + c.G * 0.587f + c.B *0.114f) / 256f;\n\n string name = s < 0.35f ? \"pale \" : s > 0.8f ? \"vivid \" : \"\";\n name += b < 0.35f ? \"dark \" : b > 0.8f ? \"light \" : \"\";\n for (int i = 0; i < hues.Count - 1; i++)\n if (h >= hues[i] && h <= hues[i+1] )\n {\n name += hueNames[i];\n break;\n }\n return name;\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146637/" ]
365,968
<p>I am looking to add the capability for users to write plugins to the program I have developed in Delphi. The program is a single executable with no DLLs used. </p> <p>This would allow the user community to write extensions to my program to access the internal data and add capabilities that they may find useful. </p> <p>I've seen the post at: <a href="https://stackoverflow.com/questions/8140/adding-plugin-capability">Suggestions for Adding Plugin Capability?</a> but its answers don't seem transferrable to a Delphi program.</p> <p>I would like, if possible, to add this capability and keep my application as a single executable without any DLLs or additional modules required.</p> <p>Do you know of any resources, components or articles that would suggest how to best do this in Delphi, or do you have your own recommendation?</p>
[ { "answer_id": 366007, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": false, "text": "LoadLibrary GetProcAddress" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/365968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30176/" ]
365,975
<p>Namely, how does the following code:</p> <pre><code>var sup = new Array(5); sup[0] = 'z3ero'; sup[1] = 'o3ne'; sup[4] = 'f3our'; document.write(sup.length + &quot;&lt;br /&gt;&quot;); </code></pre> <p>output '5' for the length, when all you've done is set various elements?</p> <p>My 'problem' with this code is that I don't understand how <code>length</code> changes without calling a <code>getLength()</code> or a <code>setLength()</code> method. When I do any of the following:</p> <pre><code>a.length a['length'] a.length = 4 a['length'] = 5 </code></pre> <p>on a non-array object, it behaves like a dict / associative array. When I do this on the array object, it has special meaning. What mechanism in JavaScript allows this to happen? Does JavaScript have some type of property system which translates</p> <pre><code>a.length a['length'] </code></pre> <p>into &quot;get&quot; methods and</p> <pre><code>a.length = 4 a['length'] = 5 </code></pre> <p>into &quot;set&quot; methods?</p>
[ { "answer_id": 365992, "author": "finpingvin", "author_id": 46054, "author_profile": "https://Stackoverflow.com/users/46054", "pm_score": 2, "selected": false, "text": "sup['look'] = 4; sup sup.look = 4; sup['length']" }, { "answer_id": 365995, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": "Array length [] toString()" }, { "answer_id": 366029, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 1, "selected": false, "text": "Array caller constructor length name Function.prototype" }, { "answer_id": 11604738, "author": "Norguard", "author_id": 1001831, "author_profile": "https://Stackoverflow.com/users/1001831", "pm_score": 2, "selected": false, "text": "[].length var testArr = []; testArr[5000] = \"something\"; testArr.length; // 5001\n __proto__ get set" }, { "answer_id": 29177839, "author": "Niko Bellic", "author_id": 3334520, "author_profile": "https://Stackoverflow.com/users/3334520", "pm_score": 0, "selected": false, "text": "arr[5] = \"yo\"\n arr.insert(5,\"yo\")\n" }, { "answer_id": 54381996, "author": "Ajna", "author_id": 4099001, "author_profile": "https://Stackoverflow.com/users/4099001", "pm_score": 2, "selected": false, "text": "const test = [1, 2, 3, 4, 5]\ntest.length = 3\nconsole.log(test) // [1, 2, 3]\ntest.length = 5\nconsole.log(test) // Guess what happens here!\n const pippi = \"pippi\"\npippi.cat = \"cat\"\nconsole.log(pippi.cat) // Will it work? Throw an error? Guess why again\n String.prototype undefined" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/365975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
366,017
<p>I'm creating a set of enum values, but I need each enum value to be 64 bits wide. If I recall correctly, an enum is generally the same size as an int; but I thought I read somewhere that (at least in GCC) the compiler can make the enum any width they need to be to hold their values. So, is it possible to have an enum that is 64 bits wide?</p>
[ { "answer_id": 366026, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 8, "selected": true, "text": "enum int int" }, { "answer_id": 24067364, "author": "Kevin Cox", "author_id": 1166181, "author_profile": "https://Stackoverflow.com/users/1166181", "pm_score": 5, "selected": false, "text": "enum ord {\n FIRST = 1,\n SECOND,\n THIRD\n} __attribute__ ((__packed__));\nSTATIC_ASSERT( sizeof(enum ord) == 1 )\n" }, { "answer_id": 33713018, "author": "tushan", "author_id": 5068297, "author_profile": "https://Stackoverflow.com/users/5068297", "pm_score": -1, "selected": false, "text": "enum value{a,b,c,d,e,f,g,h,i,j,l,m,n};\nvalue s;\ncout << sizeof(s) << endl;\n enum" }, { "answer_id": 41803395, "author": "MIke", "author_id": 7364052, "author_profile": "https://Stackoverflow.com/users/7364052", "pm_score": -1, "selected": false, "text": "enum enum enum" }, { "answer_id": 48023759, "author": "rashok", "author_id": 596370, "author_profile": "https://Stackoverflow.com/users/596370", "pm_score": -1, "selected": false, "text": "enum int -fshort-enums" }, { "answer_id": 59742592, "author": "scirdan", "author_id": 4912539, "author_profile": "https://Stackoverflow.com/users/4912539", "pm_score": 0, "selected": false, "text": "enum value{a=0,b,c,d,e,f,g,h,i,j,l,m,n,last=0xFFFFFFFFFFFFFFFF};\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28804/" ]
366,031
<p>Is there any way to create an array-like object in JavaScript, without using the built-in array? I'm specifically concerned with behavior like this:</p> <pre><code>var sup = new Array(5); //sup.length here is 0 sup[0] = 'z3ero'; //sup.length here is 1 sup[1] = 'o3ne'; //sup.length here is 2 sup[4] = 'f3our'; //sup.length here is 5 </code></pre> <p><strong>The particular behavior I'm looking at here is that sup.length changes without any methods being called.</strong> I understand from <a href="https://stackoverflow.com/questions/365975/how-are-javascript-arrays-implemented">this question</a> that the [] operator is overloaded in the case of arrays, and this accounts for this behavior. Is there a pure-javascript way to duplicate this behavior, or is the language not flexible enough for that?</p> <p>According to the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array" rel="noreferrer">Mozilla docs</a>, values returned by regex also do funky things with this index. Is this possible with plain javascript?</p>
[ { "answer_id": 366044, "author": "finpingvin", "author_id": 46054, "author_profile": "https://Stackoverflow.com/users/46054", "pm_score": 1, "selected": false, "text": "var sup = []; //Shorthand for an empty array\n//sup.length is 0\nsup.push(1); //Adds an item to the array (You don't need to keep track of index-sizes)\n//sup.length is 1\nsup.push(2);\n//sup.length is 2\nsup.push(4);\n//sup.length is 3\n//sup is [1, 2, 4]\n" }, { "answer_id": 366045, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 5, "selected": false, "text": "MyClass.prototype.getItem = function(index)\n{\n return {\n name: 'Item' + index,\n value: 2 * index\n };\n}\n MyClass.prototype.addItem = function(item)\n{\n // Will add \"item\" in \"this\" as if it was a native array\n // it will then be accessible using the [] operator \n Array.prototype.push.call(this, item);\n}\n" }, { "answer_id": 366048, "author": "Jason Kester", "author_id": 27214, "author_profile": "https://Stackoverflow.com/users/27214", "pm_score": 1, "selected": false, "text": "var sup = [];\nsup['0'] = 'z3ero';\nsup['1'] = 'o3ne';\nsup['4'] = 'f3our'; \n//sup now contains 3 entries\n" }, { "answer_id": 366159, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 4, "selected": false, "text": "var ArrayLike = function() {};\nArrayLike.prototype = [];\nArrayLike.prototype.shuffle = // ... and so on ...\n var cards = new Arraylike;\ncards.push('ace of spades', 'two of spades', 'three of spades', ... \ncards.shuffle();\n length" }, { "answer_id": 366759, "author": "Matt Kantor", "author_id": 3625, "author_profile": "https://Stackoverflow.com/users/3625", "pm_score": 2, "selected": false, "text": "Thing = function() {};\nThing.prototype.__defineGetter__('length', function() {\n var count = 0;\n for(property in this) count++;\n return count - 1; // don't count 'length' itself!\n});\n\ninstance = new Thing;\nconsole.log(instance.length); // => 0\ninstance[0] = {};\nconsole.log(instance.length); // => 1\ninstance[1] = {};\ninstance[2] = {};\nconsole.log(instance.length); // => 3\ninstance[5] = {};\ninstance.property = {};\ninstance.property.property = {}; // this shouldn't count\nconsole.log(instance.length); // => 5\n" }, { "answer_id": 11234502, "author": "olleicua", "author_id": 977408, "author_profile": "https://Stackoverflow.com/users/977408", "pm_score": 1, "selected": false, "text": "Array.prototype.mylength = function() {\n var result = 0;\n for (var i = 0; i < this.length; i++) {\n if (this[i] !== undefined) {\n result++;\n }\n }\n return result;\n}\n" }, { "answer_id": 37758381, "author": "gsnedders", "author_id": 478176, "author_profile": "https://Stackoverflow.com/users/478176", "pm_score": 4, "selected": true, "text": "Array function FakeArray() {\n const target = {};\n\n Object.defineProperties(target, {\n \"length\": {\n value: 0,\n writable: true\n },\n [Symbol.iterator]: {\n // http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype-@@iterator\n value: () => {\n let index = 0;\n\n return {\n next: () => ({\n done: index >= target.length,\n value: target[index++]\n })\n };\n }\n }\n });\n\n const isArrayIndex = function(p) {\n /* an array index is a property such that\n ToString(ToUint32(p)) === p and ToUint(p) !== 2^32 - 1 */\n const uint = p >>> 0;\n const s = uint + \"\";\n return p === s && uint !== 0xffffffff;\n };\n\n const p = new Proxy(target, {\n set: function(target, property, value, receiver) {\n // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array-exotic-objects-defineownproperty-p-desc\n if (property === \"length\") {\n // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-arraysetlength\n const newLen = value >>> 0;\n const numberLen = +value;\n if (newLen !== numberLen) {\n throw RangeError();\n }\n const oldLen = target.length;\n if (newLen >= oldLen) {\n target.length = newLen;\n return true;\n } else {\n // this case gets more complex, so it's left as an exercise to the reader\n return false; // should be changed when implemented!\n }\n } else if (isArrayIndex(property)) {\n const oldLenDesc = Object.getOwnPropertyDescriptor(target, \"length\");\n const oldLen = oldLenDesc.value;\n const index = property >>> 0;\n if (index > oldLen && oldLenDesc.writable === false) {\n return false;\n }\n target[property] = value;\n if (index > oldLen) {\n target.length = index + 1;\n }\n return true;\n } else {\n target[property] = value;\n return true;\n }\n }\n });\n\n return p;\n}\n length Array length length length newLen - oldLen" }, { "answer_id": 64871214, "author": "DasonCheng", "author_id": 7068666, "author_profile": "https://Stackoverflow.com/users/7068666", "pm_score": 1, "selected": false, "text": "export type IComparer<T> = (a: T, b: T) => number;\n\nexport interface IListBase<T> {\n readonly Count: number;\n [index: number]: T;\n [Symbol.iterator](): IterableIterator<T>;\n Add(item: T): void;\n Insert(index: number, item: T): void;\n Remove(item: T): boolean;\n RemoveAt(index: number): void;\n Clear(): void;\n IndexOf(item: T): number;\n Sort(): void;\n Sort(compareFn: IComparer<T>): void;\n Reverse(): void;\n}\n\n\nexport class ListBase<T> implements IListBase<T> {\n protected list: T[] = new Array();\n [index: number]: T;\n get Count(): number {\n return this.list.length;\n }\n [Symbol.iterator](): IterableIterator<T> {\n let index = 0;\n const next = (): IteratorResult<T> => {\n if (index < this.Count) {\n return {\n value: this[index++],\n done: false,\n };\n } else {\n return {\n value: undefined,\n done: true,\n };\n }\n };\n\n const iterator: IterableIterator<T> = {\n next,\n [Symbol.iterator]() {\n return iterator;\n },\n };\n\n return iterator;\n }\n constructor() {\n return new Proxy(this, {\n get: (target, propKey, receiver) => {\n if (typeof propKey === \"string\" && this.isSafeArrayIndex(propKey)) {\n return Reflect.get(this.list, propKey);\n }\n return Reflect.get(target, propKey, receiver);\n },\n set: (target, propKey, value, receiver) => {\n if (typeof propKey === \"string\" && this.isSafeArrayIndex(propKey)) {\n return Reflect.set(this.list, propKey, value);\n }\n return Reflect.set(target, propKey, value, receiver);\n },\n });\n }\n Reverse(): void {\n throw new Error(\"Method not implemented.\");\n }\n Insert(index: number, item: T): void {\n this.list.splice(index, 0, item);\n }\n Add(item: T): void {\n this.list.push(item);\n }\n Remove(item: T): boolean {\n const index = this.IndexOf(item);\n if (index >= 0) {\n this.RemoveAt(index);\n return true;\n }\n return false;\n }\n RemoveAt(index: number): void {\n if (index >= this.Count) {\n throw new RangeError();\n }\n this.list.splice(index, 1);\n }\n Clear(): void {\n this.list = [];\n }\n IndexOf(item: T): number {\n return this.list.indexOf(item);\n }\n Sort(): void;\n Sort(compareFn: IComparer<T>): void;\n Sort(compareFn?: IComparer<T>) {\n if (typeof compareFn !== \"undefined\") {\n this.list.sort(compareFn);\n }\n }\n private isSafeArrayIndex(propKey: string): boolean {\n const uint = Number.parseInt(propKey, 10);\n const s = uint + \"\";\n return propKey === s && uint !== 0xffffffff && uint < this.Count;\n }\n}\n const list = new List<string>([\"b\", \"c\", \"d\"]);\nconst item = list[0];\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
366,047
<p>Looking at the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array" rel="noreferrer">mozilla documentation</a>, looking at the regular expression example (headed &quot;Creating an array using the result of a match&quot;), we have statements like:</p> <blockquote> <p>input: A read-only property that reflects the original string against which the regular expression was matched.</p> <p>index: A read-only property that is the zero-based index of the match in the string.</p> </blockquote> <p>etc... is it possible to create your own object in JavaScript which will have read-only properties, or is this a privilege reserved to built-in types implemented by particular browsers?</p>
[ { "answer_id": 366082, "author": "Ryan Doherty", "author_id": 956, "author_profile": "https://Stackoverflow.com/users/956", "pm_score": 3, "selected": false, "text": "YAHOO.myProject.myModule = function () {\n\n//\"private\" variables:\nvar myPrivateVar = \"I can be accessed only from within YAHOO.myProject.myModule.\";\n\n//\"private\" method:\nvar myPrivateMethod = function () {\n YAHOO.log(\"I can be accessed only from within YAHOO.myProject.myModule\");\n}\n\nreturn {\n myPublicProperty: \"I'm accessible as YAHOO.myProject.myModule.myPublicProperty.\"\n myPublicMethod: function () {\n YAHOO.log(\"I'm accessible as YAHOO.myProject.myModule.myPublicMethod.\");\n\n //Within myProject, I can access \"private\" vars and methods:\n YAHOO.log(myPrivateVar);\n YAHOO.log(myPrivateMethod());\n\n //The native scope of myPublicMethod is myProject; we can\n //access public members using \"this\":\n YAHOO.log(this.myPublicProperty);\n }\n};\n\n}(); // the parens here cause the anonymous function to execute and return\n" }, { "answer_id": 366086, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 7, "selected": true, "text": "Object.defineProperty var myObject = {\n get readOnlyProperty() { return 42; }\n};\n\nalert(myObject.readOnlyProperty); // 42\nmyObject.readOnlyProperty = 5; // Assignment is allowed, but doesn't do anything\nalert(myObject.readOnlyProperty); // 42\n __defineGetter__ __defineSetter__ var myObject = {};\nmyObject.__defineGetter__(\"readOnlyProperty\", function() { return 42; });\n" }, { "answer_id": 2964881, "author": "Aidamina", "author_id": 227955, "author_profile": "https://Stackoverflow.com/users/227955", "pm_score": 6, "selected": false, "text": "var obj = {};\nObject.defineProperty( obj, \"<yourPropertyNameHere>\", {\n value: \"<yourPropertyValueHere>\",\n writable: false,\n enumerable: true,\n configurable: true\n});\n" }, { "answer_id": 16288162, "author": "Tengiz", "author_id": 523949, "author_profile": "https://Stackoverflow.com/users/523949", "pm_score": 0, "selected": false, "text": "Property var Person = function(name, age) { \n this.name = new bob.prop.Property(name, true); \n var setName = this.name.get_setter(); \n this.age = new bob.prop.Property(age, true); \n var setAge = this.age.get_setter(); \n this.parent = new bob.prop.Property(null, false, true); \n}; \nvar p = new Person('Bob', 20); \np.parent.set_value(new Person('Martin', 50)); \nconsole.log('name: ' + p.name.get_value()); \nconsole.log('age: ' + p.age.get_value()); \nconsole.log('parent: ' + (p.parent.get_value ? p.parent.get_value().name.get_value() : 'N/A')); \n// Output: \n// name: Bob \n// age: 20 \n// parent: N/A \n p.name.set_value" }, { "answer_id": 16683019, "author": "Avenida Gez", "author_id": 2338481, "author_profile": "https://Stackoverflow.com/users/2338481", "pm_score": 3, "selected": false, "text": "<script>\nObject.defineProperties(window, {\n \"selector\": { value: 'window', writable: false }\n});\n\nalert (window.selector); // outputs window\n\nselector ='ddd'; // testing because it belong to the global object\nalert (window.selector); // outputs window\nalert (selector); // outputs window\n\nwindow.selector='abc';\nalert (window.selector); // outputs window\nalert (selector); // outputs window\n</script>\n" }, { "answer_id": 31283054, "author": "Vincent Charette", "author_id": 5091872, "author_profile": "https://Stackoverflow.com/users/5091872", "pm_score": 1, "selected": false, "text": " function Car(brand, color) {\n brand = brand || 'Porche'; // Private variable - Not accessible directly and cannot be frozen\n color = color || 'Red'; // Private variable - Not accessible directly and cannot be frozen\n this.color = function() { return color; }; // Getter for color\n this.setColor = function(x) { color = x; }; // Setter for color\n this.brand = function() { return brand; }; // Getter for brand\n Object.freeze(this); // Makes your object's public methods and properties read-only\n }\n\n function w(str) {\n /*************************/\n /*choose a logging method*/\n /*************************/\n console.log(str);\n // document.write(str + \"<br>\");\n }\n\n var myCar = new Car;\n var myCar2 = new Car('BMW','White');\n var myCar3 = new Car('Mercedes', 'Black');\n\n w(myCar.brand()); // returns Porche\n w(myCar.color()); // returns Red\n\n w(myCar2.brand()); // returns BMW\n w(myCar2.color()); // returns White\n\n w(myCar3.brand()); // returns Mercedes\n w(myCar3.color()); // returns Black\n\n // This works even when the Object is frozen\n myCar.setColor('Green');\n w(myCar.color()); // returns Green\n\n // This will have no effect\n myCar.color = 'Purple';\n w(myCar.color()); // returns Green\n w(myCar.color); // returns the method\n\n // This following will not work as the object is frozen\n myCar.color = function (x) {\n alert(x);\n };\n\n myCar.setColor('Black');\n w(\n myCar.color(\n 'This will not work. Object is frozen! The method has not been updated'\n )\n ); // returns Black since the method is unchanged\n Porche\n Red\n BMW\n White\n Mercedes\n Black\n Green\n Green\n function () { return color; }\n Black\n" }, { "answer_id": 32672132, "author": "Mohammed Safeer", "author_id": 2293686, "author_profile": "https://Stackoverflow.com/users/2293686", "pm_score": 2, "selected": false, "text": "object.defineProperty() function Employee(name,age){\n var _name = name;\n var _age = age;\n\n Object.defineProperty(this,'name',{\n get:function(){\n return _name;\n }\n })\n}\n\nvar emp = new Employee('safeer',25);\nconsole.log(emp.name); //return 'safeer'\nemp.name='abc';\nconsole.log(emp.name); //again return 'safeer', since name is read-only property\n" }, { "answer_id": 73081052, "author": "JBaczuk", "author_id": 3499115, "author_profile": "https://Stackoverflow.com/users/3499115", "pm_score": 0, "selected": false, "text": "Object.defineProperty(Fake.prototype, 'props', {\n set: function() {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n },\n});\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
366,054
<p>i have a string that looks like</p> <pre><code>"&lt;input id=a/&gt;"&lt;input id=b/&gt;"&lt;input id=c/&gt;etc. </code></pre> <p>I need to change it to</p> <pre><code>"&lt;input id='a'/&gt;"&lt;input id='b'/&gt;"&lt;input id='c'/&gt;etc, </code></pre> <p>any ideas how? </p>
[ { "answer_id": 366090, "author": "foxdonut", "author_id": 26353, "author_profile": "https://Stackoverflow.com/users/26353", "pm_score": 1, "selected": false, "text": "%s/\"<input id=\\(.\\)\\/>/\"<input id='\\1'\\/>/g\n %s/\\(\"<input id=\\)\\(.\\)\\/>/\\1'\\2'\\/>/g\n" }, { "answer_id": 366099, "author": "Renaud Bompuis", "author_id": 3811, "author_profile": "https://Stackoverflow.com/users/3811", "pm_score": 2, "selected": false, "text": "resultString = Regex.Replace(subjectString, @\"(<.*?id\\s*=\\s*)(\\w+)(.*?>)\", \"$1'$2'$3\", RegexOptions.Multiline);\n ResultString = Regex.Replace(SubjectString, \"(<.*?id\\s*=\\s*)(\\w+)(.*?>)\", \"$1'$2'$3\", RegexOptions.Multiline)\n $subject =~ s/(<.*?id\\s*=\\s*)(\\w+)(.*?>)/$1'$2'$3/mg;\n $result = preg_replace('/(<.*?id\\s*=\\s*)(\\w+)(.*?>)/m', '$1\\'$2\\'$3', $subject);\n resultString = subjectString.replaceAll(\"(?m)(<.*?id\\\\s*=\\\\s*)(\\\\w+)(.*?>)\", \"$1'$2'$3\");\n result = subject.replace(/(<.*?id\\s*=\\s*)(\\w+)(.*?>)/mg, \"$1'$2'$3\");\n" }, { "answer_id": 366542, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 0, "selected": false, "text": "=(\\w)\n ='$1'\n ='\\1'\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,088
<p>If you create a pure ActionScript project in Flex Builder 3 and want to do unit testing using flexunit, what is the best option?</p> <p>The built-in Flex builder will refuse to build the mxml file containing the TestRunnerBase component as it is a pure ActionScript project (no Flex allowed). It is impossible to add the mxml file to the "ActionScript Applications" list in the project settings.</p> <p>Right now I can see two options, both undesirable.</p> <ol> <li>Add the unit testing mxml file to the project and create an external tool setup to build and run it. This is the approach I'm taking now, and it works fine, except that interactive debugging is impossible.</li> <li>Create a new Flex project just for the test mxml file and add the main project's src directory as an additional source directory in the build options. I don't like this approach because it requires that I keep the mxml file in a separate directory tree from all the other source files in addition to the ugliness of maintaining two projects.</li> </ol>
[ { "answer_id": 367871, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 1, "selected": false, "text": "// import mx.core.Application;\n// import flexunit.framework.*;\n\n// class AutomatedTestHarness extends Application implements TestListener\n\nprivate function creationCompleteHandler(event : Event) : void\n{\n this._result = new TestResult();\n this._result.addListener(this);\n\n var testSuite : TestSuite = new TestSuite();\n this.addUnitTests(testSuite);\n\n testSuite.runWithResult(_result);\n}\n\n/**\n * Implement these as part of TestResult.addListener\n * If you want to output xml after the tests run, do so here\n * (Tip: Count tests in endTest and compare the count to testSuite.countTestCases()\n * to find out when all tests have completed)\n */\nfunction startTest(test : Test) : void {}\nfunction endTest(test : Test) : void {}\nfunction addError(test : Test, error : Error) : void {}\nfunction addFailure(test : Test, error : AssertionFailedError) : void {}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45084/" ]
366,093
<p>If I check out a tagged version of my source code without creating a branch, Git indicates that I'm not associated with any branch at all. It's happy to let me make changes and check them in though. Where do those changes go? If I switch back to 'master' they disappear (overwritten by what was in master) and I can't seem to find them again. What gives? If Git lets me commit changes against what's essentially an anonymous branch, surely I can get them back?</p>
[ { "answer_id": 366103, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 3, "selected": false, "text": "git checkout -b my-branch-name\n" }, { "answer_id": 366147, "author": "Paul", "author_id": 23356, "author_profile": "https://Stackoverflow.com/users/23356", "pm_score": 7, "selected": true, "text": "reflog XXX $ git reflog\n7a30fd7... HEAD@{0}: checkout: moving from master to XXX\nddf751d... HEAD@{1}: checkout: moving from 96c3b0300ccf16b64efc260c21c85ba9030f2e3a to master\n96c3b03... HEAD@{2}: commit: example commit on tag XXX, not on any branch\n7a30fd7... HEAD@{3}: checkout: moving from master to XXX\n checkout $ git checkout 96c3b03\nNote: moving to \"96c3b03\" which isn't a local branch\nIf you want to create a new branch from this checkout, you may do so\n(now or later) by using -b with the checkout command again. Example:\n git checkout -b <new_branch_name>\nHEAD is now at 96c3b03... example commit on tag XXX, not on any branch\n$ git checkout -b newbranch\n$ git branch #lists all branches\n feature1\n master\n * newbranch\n checkout" }, { "answer_id": 8760749, "author": "gjvis", "author_id": 256642, "author_profile": "https://Stackoverflow.com/users/256642", "pm_score": 3, "selected": false, "text": "git checkout master\ngit merge SHA1\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/826/" ]
366,104
<p>Make a <strong>new AS3 Document</strong> in Flash, <strong>paste</strong> in the following code and <strong>run it:</strong></p> <pre><code>var a:Number=0; trace(a) // 0 a+=0.3; trace(a) // 0.3 a+=0.3; trace(a) // 0.6 a+=0.3; trace(a) // 0.8999999999999999 a+=0.3; trace(a) // 1.2 a+=0.3; trace(a) // 1.5 a+=0.3; trace(a) // 1.8 a+=0.3; trace(a) // 2.1 a+=0.3; // ^ This is the output. Notice the inaccuracy starting from 0.9 / 0.89 </code></pre> <p><strong>Why the error?</strong> I'm just doing an ordinary hi resolution addition.</p> <p>Any <strong>workarounds?</strong></p>
[ { "answer_id": 366108, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": true, "text": "trace (round (a, 1))\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41021/" ]
366,109
<p>I have a VB6 legacy program which I need to change. I am unable to run the program from the IDE. When I activate one of the forms in the IDE I get an error which refers me to an error log file. The log file has the following in it</p> <p>"Cannot load control SSPanel; license not found"</p> <p>The SSPanel is part the Sheridan 3D controls (THREED32.ocx) and the component is selected.</p> <p>How can I fix the error?</p>
[ { "answer_id": 22933989, "author": "Bob Tway", "author_id": 271907, "author_profile": "https://Stackoverflow.com/users/271907", "pm_score": 2, "selected": false, "text": "regtlibv12.exe C:\\Windows\\Microsoft.NET\\Framework\\[version] C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319 regtlibv12.exe C:\\Windows\\SysWOW64\\msdatsrc.tlb regtlibv12.exe C:\\Windows\\System32\\msdatsrc.tlb" }, { "answer_id": 38057467, "author": "Julian", "author_id": 5202466, "author_profile": "https://Stackoverflow.com/users/5202466", "pm_score": 0, "selected": false, "text": "[HKEY_CLASSES_ROOT\\Licenses\\E32E2733-1BC5-11d0-B8C3-00A0C90DCA10]\n@=\"kmhfimlflmmfpffmsgfmhmimngtghmoflhsg\"\n" }, { "answer_id": 52205182, "author": "Feeble", "author_id": 8071633, "author_profile": "https://Stackoverflow.com/users/8071633", "pm_score": 0, "selected": false, "text": "%systemroot%\\SysWow64\\regsvr32 threed32.ocx\n (\\Visual Basic 6\\en_vb6_ent_cd1\\Common\\Tools\\VB\\controls)\n vbctrls.reg" }, { "answer_id": 53734594, "author": "StayOnTarget", "author_id": 3195477, "author_profile": "https://Stackoverflow.com/users/3195477", "pm_score": 0, "selected": false, "text": "License information for this component not found. You do not have an\n appropriate license to use this functionality in the design\n environment. <Path to RegSvr32>\\REGSVR32.EXE /u <Path to OCX>\\OCXFILE.OCX C:\\Devstudio\\VB\\REGSVR32.EXE /u C:\\Winnt\\System32\\COMCTL32.OCX" }, { "answer_id": 53734630, "author": "StayOnTarget", "author_id": 3195477, "author_profile": "https://Stackoverflow.com/users/3195477", "pm_score": 0, "selected": false, "text": "FILE: VBUSC.EXE Provides Licensing for Discontinued Controls SUMMARY\n=======\n\nVBUSC.EXE is a file that installs the Design-Time Licenses for ActiveX controls\nthat shipped with earlier versions of Visual Basic, but are no longer supported\nand have been discontinued with the current version.\n\nMORE INFORMATION\n================\n\nThe following file is available for download from the Microsoft Download\nCenter:\n\n VBUSC.exe\n (http://download.microsoft.com/download/VB60Pro/Install/2/Win98/En-US/VBUSC.exe)\n\nRelease Date: August 15, 2000\n\nFor additional information about how to download Microsoft Support files, click\nthe following article number to view the article in the Microsoft Knowledge\nBase:\n\n Q119591 How to Obtain Microsoft Support Files from Online Services\n\nMicrosoft scanned this file for viruses. Microsoft used the most current\nvirus-detection software that was available on the date that the file was\nposted. The file is stored on secure servers that prevent any unauthorized\nchanges to the file.\n\n FileName Size\n ---------------------------------------------------------\n VBUSC.EXE 88k\n\nThe following controls are no longer supported by Microsoft Visual Basic:\n\nActiveX Control Name Filename\n------------------------------------------------\nDesaware Animated Button Control ANIBTN32.OCX\nMicrohelp Gauge Control GAUGE32.OCX\nPinnacle-BPS Graph Control GRAPH32.EXE\nMicrosoft Grid Control GRID32.OCX\nMicrohelp Key State Control KEYSTA32.OCX\nMicrosoft Outline Control MSOUTL32.OCX\nOutrider SpinButton Control SPIN32.OCX\nSheridan 3D Controls THREED32.OCX\n\nThe ActiveX controls listed above are no longer supported, but ship with the\nProfessional and Enterprise Editions of Microsoft Visual Basic for backward\ncompatibility when upgrading existing projects.\n\nThese controls do not ship with the Learning Edition of Microsoft Visual Basic.\n\nFor the Professional and Enterprise Editions, the controls are located on the\ninstallation CDs at the following locations:\n\nMicrosoft Visual Basic Edition Location\n----------------------------------------------------------------------\nProfessional 6.0 \\Common\\Tools\\VB\\Controls\nEnterprise 6.0 \\Common\\Tools\\VB\\Controls\nVisual Studio Professional 6.0 \\Common\\Tools\\VB\\Controls (CD2)\nVisual Studio Enterprise 6.0 \\Common\\Tools\\VB\\Controls (CD3)\n\n\nEach of these directories contain a README.TXT with instructions on how to\ninstall the controls for design-time use.\n\nNOTE: Using the Learning Edition to upgrade a project developed in an earlier\nversion of Microsoft Visual Basic might result in licensing problems for these\ncontrols.\n\nThe VBUSC.EXE installs the design-time licenses for the controls listed above if\nVisual Basic is detected on the computer.\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
366,115
<p>I found the following code to create a tinyurl.com url:</p> <pre><code>http://tinyurl.com/api-create.php?url=http://myurl.com </code></pre> <p>This will automatically create a tinyurl url. Is there a way to do this using code, specifically C# in ASP.NET?</p>
[ { "answer_id": 366135, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 4, "selected": false, "text": " public static string MakeTinyUrl(string url)\n {\n try\n {\n if (url.Length <= 30)\n {\n return url;\n }\n if (!url.ToLower().StartsWith(\"http\") && !Url.ToLower().StartsWith(\"ftp\"))\n {\n url = \"http://\" + url;\n }\n var request = WebRequest.Create(\"http://tinyurl.com/api-create.php?url=\" + url);\n var res = request.GetResponse();\n string text;\n using (var reader = new StreamReader(res.GetResponseStream()))\n {\n text = reader.ReadToEnd();\n }\n return text;\n }\n catch (Exception)\n {\n return url;\n }\n }\n" }, { "answer_id": 366149, "author": "mcrumley", "author_id": 17287, "author_profile": "https://Stackoverflow.com/users/17287", "pm_score": 6, "selected": true, "text": "System.Uri address = new System.Uri(\"http://tinyurl.com/api-create.php?url=\" + YOUR ADDRESS GOES HERE);\nSystem.Net.WebClient client = new System.Net.WebClient();\nstring tinyUrl = client.DownloadString(address);\nConsole.WriteLine(tinyUrl);\n" }, { "answer_id": 57216477, "author": "Mselmi Ali", "author_id": 9091039, "author_profile": "https://Stackoverflow.com/users/9091039", "pm_score": 0, "selected": false, "text": "static void Main()\n{\n var tinyUrl = MakeTinyUrl(\"https://stackoverflow.com/questions/366115/using-tinyurl-com-in-a-net-application-possible\");\n\n Console.WriteLine(tinyUrl);\n\n Console.ReadLine();\n}\n\npublic static string MakeTinyUrl(string url)\n{\n string tinyUrl = url;\n string api = \" the api's url goes here \";\n try\n {\n var request = WebRequest.Create(api + url);\n var res = request.GetResponse();\n using (var reader = new StreamReader(res.GetResponseStream()))\n {\n tinyUrl = reader.ReadToEnd();\n }\n }\n catch (Exception exp)\n {\n Console.WriteLine(exp);\n }\n return tinyUrl;\n}\n" }, { "answer_id": 57217375, "author": "Mani", "author_id": 1735151, "author_profile": "https://Stackoverflow.com/users/1735151", "pm_score": 1, "selected": false, "text": "public class TinyUrlController : ControllerBase\n{\n Dictionary dicShortLohgUrls = new Dictionary();\n\n private readonly IMemoryCache memoryCache;\n\n public TinyUrlController(IMemoryCache memoryCache)\n {\n this.memoryCache = memoryCache;\n }\n\n [HttpGet(\"short/{url}\")]\n public string GetShortUrl(string url)\n {\n using (MD5 md5Hash = MD5.Create())\n {\n string shortUrl = UrlHelper.GetMd5Hash(md5Hash, url);\n shortUrl = shortUrl.Replace('/', '-').Replace('+', '_').Substring(0, 6);\n\n Console.WriteLine(\"The MD5 hash of \" + url + \" is: \" + shortUrl + \".\");\n\n var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(604800));\n memoryCache.Set(shortUrl, url, cacheEntryOptions);\n\n return shortUrl;\n }\n }\n\n [HttpGet(\"long/{url}\")]\n public string GetLongUrl(string url)\n {\n if (memoryCache.TryGetValue(url, out string longUrl))\n {\n return longUrl;\n }\n\n return url;\n }\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
366,124
<p>I'm building an application where I should capture several values and build a text with them: <code>Name</code>, <code>Age</code>, etc.</p> <p>The output will be a plain text into a <code>TextBox</code>.</p> <p>I am trying to make those information appear in kind of <code>columns</code>, therefore I am trying to separate them with <code>tab</code> to make it clearer.</p> <p>For example, instead of having:</p> <pre><code>Ann 26 Sarah 29 Paul 45 </code></pre> <p>I would like it to show as:</p> <pre><code>Ann 26 Sarah 29 Paul 45 </code></pre> <p>Any tip on how to <code>insert</code> the tabs into my text?</p>
[ { "answer_id": 366126, "author": "DShook", "author_id": 370, "author_profile": "https://Stackoverflow.com/users/370", "pm_score": 10, "selected": true, "text": "\\t" }, { "answer_id": 366131, "author": "Dan R", "author_id": 24222, "author_profile": "https://Stackoverflow.com/users/24222", "pm_score": 9, "selected": false, "text": "\\t \\' \\\" \\\\ \\0 \\a \\b \\f \\n \\r \\t \\v \\uxxxx \\u0020 \\x \\u \\x20 \\Uxxxxxxxx" }, { "answer_id": 366207, "author": "david valentine", "author_id": 36627, "author_profile": "https://Stackoverflow.com/users/36627", "pm_score": 6, "selected": false, "text": "String.Format String.Format(\"{0}\\t{1}\", FirstName,Count);\n" }, { "answer_id": 17336167, "author": "Amin Saqi", "author_id": 1814343, "author_profile": "https://Stackoverflow.com/users/1814343", "pm_score": 2, "selected": false, "text": "\\t \\t PdfReport" }, { "answer_id": 30165628, "author": "MafazR", "author_id": 2143712, "author_profile": "https://Stackoverflow.com/users/2143712", "pm_score": 2, "selected": false, "text": "var text = \"Ann@26\"\n\nvar editedText = text.Replace(\"@\", \"\\t\");\n" }, { "answer_id": 42250007, "author": "CERI", "author_id": 7568916, "author_profile": "https://Stackoverflow.com/users/7568916", "pm_score": 1, "selected": false, "text": "string St = String.Format(\"{0,-20} {1,5:N1}\\r\", names[ctr], hours[ctr]);\nrichTextBox1.Text += St;\n" }, { "answer_id": 52068326, "author": "Hecatonchires", "author_id": 2081568, "author_profile": "https://Stackoverflow.com/users/2081568", "pm_score": 2, "selected": false, "text": "char tab = '\\u0009';\nstring A = \"Apple\";\nstring B = \"Bob\";\nstring myStr = String.Format(@\"{0}:{1}{2}\", A, tab, B);\n Apple:<tab>Bob" }, { "answer_id": 52474661, "author": "Heersert", "author_id": 8324091, "author_profile": "https://Stackoverflow.com/users/8324091", "pm_score": 1, "selected": false, "text": "string name = \"John\";\nstring surname = \"Smith\";\n\nConsole.WriteLine(\"Name:\".PadRight(15)+\"Surname:\".PadRight(15));\nConsole.WriteLine( name.PadRight(15) + surname.PadRight(15));\n" }, { "answer_id": 54434864, "author": "schlebe", "author_id": 948359, "author_profile": "https://Stackoverflow.com/users/948359", "pm_score": 3, "selected": false, "text": "Microsoft Winform controls \"\\t\" vbTab \"\\t\" vbTab Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n TextBox1.Text = \"Bernard\" + vbTab + \"32\"\n TextBox2.Text = \"Luc\" + vbTab + \"47\"\n TextBox3.Text = \"François-Victor\" + vbTab + \"12\"\nEnd Sub\n age François-Victor age SendMessage() Public Class Form1\n\n Public Declare Function SendMessage _\n Lib \"user32\" Alias \"SendMessageA\" _\n ( ByVal hWnd As IntPtr _\n , ByVal wMsg As Integer _\n , ByVal wParam As Integer _\n , ByVal lParam() As Integer _\n ) As Integer\n\n Private Const EM_SETTABSTOPS As Integer = &HCB\n\n Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n Dim tabs() As Integer = {4 * 25}\n\n TextBox1.Text = \"Bernard\" + vbTab + \"32\"\n SendMessage(TextBox1.Handle, EM_SETTABSTOPS, 1, tabs)\n TextBox2.Text = \"Luc\" + vbTab + \"47\"\n SendMessage(TextBox2.Handle, EM_SETTABSTOPS, 1, tabs)\n TextBox3.Text = \"François-Victor\" + vbTab + \"12\"\n SendMessage(TextBox3.Handle, EM_SETTABSTOPS, 1, tabs)\n End Sub\n\nEnd Class\n Multiline AcceptsTab using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nnamespace WindowsFormsApp1\n{\n public partial class Form1 : Form\n {\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, uint[] lParam);\n private const int EM_SETTABSTOPS = 0x00CB;\n private const char vbTab = '\\t';\n\n public Form1()\n {\n InitializeComponent();\n\n var tabs = new uint[] { 25 * 4 };\n\n textBox1.Text = \"Bernard\" + vbTab + \"32\";\n SendMessage(textBox1.Handle, EM_SETTABSTOPS, 1, tabs);\n textBox2.Text = \"Luc\" + vbTab + \"47\";\n SendMessage(textBox2.Handle, EM_SETTABSTOPS, 1, tabs);\n textBox3.Text = \"François-Victor\" + vbTab + \"12\";\n SendMessage(textBox3.Handle, EM_SETTABSTOPS, 1, tabs);\n }\n }\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19159/" ]
366,137
<pre><code>&lt;?php function data_info($data) { if ($data) { while (!feof($data)) { $buffer = fgets($data); if (file_exists($buffer)) { $bufferArray[$buffer]['Exists'] = (file_exists($buffer)); $bufferArray[$buffer]['Readable'] = (is_readable($buffer)); $bufferArray[$buffer]['Writable'] = (is_writable($buffer)); $bufferArray[$buffer]['Size'] = (filesize($buffer)); } else { $bufferArray[$buffer]['Exists'] = "No"; } } print_r($bufferArray); } else { echo "The file could not be opened"; } } $data = fopen("D:/xampp/htdocs/Practice/ficheros.txt", "r"); data_info($data); ?&gt; </code></pre> <p>If I have this: ficheros.txt: ExistingFile.txt ExistingFile2.txt ExistingFile3.txt... ... It works, but If I have at least 1 NON EXISTING FILE then It will take every file as a non existing one too.</p> <p>What's wrong? I believe someting in the inner if condition.</p> <hr> <p>I mean, what is wrong with the entire code.</p> <p>I just need to make an array with arrays in it, a good result would be:</p> <pre><code> array ( 'text.txt' =&gt; array ( 'exists' =&gt; true, 'readable' =&gt; true, 'writable' =&gt; true, 'Size' =&gt; 64 ), 'document.doc' =&gt; array ( 'exists' =&gt; false ), 'photo.jpg' =&gt; array ( 'exists' =&gt; true, 'readable' =&gt; true, 'writable' =&gt; false, 'size' =&gt; 354915 ) ) </code></pre>
[ { "answer_id": 366150, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 3, "selected": true, "text": "$buffer" }, { "answer_id": 366157, "author": "matta", "author_id": 46071, "author_profile": "https://Stackoverflow.com/users/46071", "pm_score": 0, "selected": false, "text": "Existingfile.txt\nAnotherExistingfile.txt\n FakeFile.txt\nFakeFile2.txt\n Fakefile.txt\nExistingfile.txt\n" }, { "answer_id": 366179, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "<?php\n\nfunction data_info($data)\n{\n if (!$data){return \"The file could not be opened\";}\n while (!feof($data))\n {\n $buffer = implode('',fgetcsv($data));//fgetcsv will only return an array with 1 item so impload it\n if(file_exists($buffer))\n {\n $bufferArray[$buffer]['Exists'] = (file_exists($buffer));\n $bufferArray[$buffer]['Readable'] = (is_readable($buffer));\n $bufferArray[$buffer]['Writable'] = (is_writable($buffer));\n $bufferArray[$buffer]['Size'] = (filesize($buffer));\n }\n else\n {\n $bufferArray[$buffer]['Exists'] = \"No\";\n }\n }\n print_r($bufferArray);\n}\n\n$data = fopen(\"c:/file.txt\", \"r\");\ndata_info($data);\n\n?>\n Array\n(\n [c:/messageService.log] => Array\n (\n [Exists] => 1\n [Readable] => 1\n [Writable] => 1\n [Size] => 0\n )\n\n [c:/setup.log] => Array\n (\n [Exists] => 1\n [Readable] => 1\n [Writable] => 1\n [Size] => 169\n )\n\n [c:/fake1.txt] => Array\n (\n [Exists] => No\n )\n\n [c:/fake2.txt] => Array\n (\n [Exists] => No\n )\n\n)\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46071/" ]
366,145
<p>I'm trying to write a greasemonkey script, and it would be preferable for it to be able to work with images (specifically, find the darkest pixel in an image). Is there a way to do this or must I embed flash?</p>
[ { "answer_id": 366165, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 4, "selected": true, "text": "// Create the canvas element\nvar canvas = document.createElement(\"canvas\");\ncanvas.width = image.width;\ncanvas.height = image.height;\n\n// Draw the image onto the canvas\nvar ctx = canvas.getContext(\"2d\");\nctx.drawImage(image, 0, 0);\n\n// Get the pixel data\nvar imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n\n// Loop through imageData.data - an array with 4 values per pixel: red, green, blue, and alpha\nfor (int x = 0; x < imageData.width; x++) {\n for (int y = 0; y < imageData.height; y++) {\n var index = 4 * (y * imageData.width + x);\n var r = imageData.data[index];\n var g = imageData.data[index + 1];\n var b = imageData.data[index + 2];\n var a = imageData.data[index + 3];\n\n // Do whatever you need to do with the rgba values\n }\n}\n" }, { "answer_id": 1117558, "author": "hcalves", "author_id": 128942, "author_profile": "https://Stackoverflow.com/users/128942", "pm_score": 1, "selected": false, "text": "var r = imageData.data[index];\nvar g = imageData.data[index + 1];\nvar b = imageData.data[index + 2];\nvar a = imageData.data[index + 3];\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29595/" ]
366,160
<p>First, let me explain what I am doing. I need to take an order, which is split up into different databases, and print out this very large order. What I need from the orders is about 100 or so columns from different databases. The way I was doing in was querying with a join and assigning all of the column values to a variable in my one large Order class. This has started to become troublesome. I am wondering of instead of having one class that is comprised of 100 or so members that make up the order. Should I have just one class for every database I use, and then work with that?</p> <p>Let me add to this. Basically, is it better to map you objects to the original database tables, or the result set. Because I have my object mapped to the result set and not the individual tables.</p>
[ { "answer_id": 366177, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "Method New Order(orderId) {\n Get Database 1 Details\n Load Details into appropriate Variables\n Get Database 2 Details \n Load Details into appropriate Variables\n Get Database **N** Details \n Load Details into appropriate Variables\n}\n" }, { "answer_id": 366774, "author": "Ian Varley", "author_id": 37539, "author_profile": "https://Stackoverflow.com/users/37539", "pm_score": 1, "selected": true, "text": "private object GetOrderAttribute(string attributeName){\n // use a data structure (like a hash table) to store and access internally\n}\n...\noutput(\"Quantity: \" + GetOrderAttribute(\"quantity\"));\n// etc.\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45429/" ]
366,183
<p>I've got a website (currently in development for a third party, I'm sorry I can't show) that requires users to confirm their contact information by, clicking on a link sent to their email address, upon registration for the website.</p> <p>It's a pretty standard practice, not very technical or unique, which is why I was surprised to find that Hotmail and Yahoo (and maybe others, I'm not sure) are blocking any email messages that are generated dynamically via the PHP code that runs the website.</p> <p>I'm using the PHP framework CodeIgniter, and making use of their email library. I've checked my code and everything looks great, and I've also looked over the email class and it looks tip-top as well. </p> <p>Not to mention, the message sent are delivered to every other mail service I've tried, including gmail, and several POP accounts. This leads me to believe that the problem is on the Hotmail/Yahoo end. </p> <p>I suspect they are purposefully rejecting/bouncing the message due to formatting, subject content, or some other arbitrary issue. </p> <p>The HTML email design is minimal, only really utilizing HTML for header tags a link. The subject of the message simply states "Welcome to ____", and is addressed from "support@______.com".</p> <p>My question is, are there any articles relating to what could be causing this that I could read to better understand why the messages are being rejected, so I can fix the issue? </p> <p>Preferably the article or document would be from Hotmail and Yahoo (with inside info), or from somebody who has experienced the same issue, and has come to a solution. </p> <p>Also, are there any available utilities to test what is actually happening with the message once it hits their servers (i.e. Is it being bounced, or something else?)</p> <p>Thank you very much! :)</p>
[ { "answer_id": 368380, "author": "Riho", "author_id": 44715, "author_profile": "https://Stackoverflow.com/users/44715", "pm_score": 0, "selected": false, "text": " $headers = \"MIME-Version: 1.0\\r\\n\";\n $headers .= \"Content-type: text/plain; charset=iso-8859-1\\r\\n\";\n $headers .= \"X-Priority: 1\\r\\n\";\n $headers .= \"X-MSMail-Priority: High\\r\\n\";\n $headers .= \"X-Mailer: Company name\\r\\n\";\n $headers .= \"From: \\\"Company name\\\" <info@company.ee>\";\n mail($email, \"title\", $message, $headers,\"-finfo@company.ee\");\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1198507/" ]
366,186
<p>I've got a column in a table (eg. UserName) which I want to make sure is unique. So I create a unique key for that column and call it IX_Users_UserName.</p> <p>Now, if I do lots of searching for users based on their username I want to make sure there is an index for that field.</p> <p>Do I need to create a separate index, or is the unique key also considered an index, just like the primary key is a clustered unique key?</p>
[ { "answer_id": 366200, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": "IX_" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
366,187
<p>I'm looking for help getting started working programmatically with audio.</p> <p>Specifically, the platform I'm working with exposes APIs to extract audio data from a resource (like an MP3), or to play back arbitrary data as audio. In both cases the actual data is byte arrays of 32bit floats representing 44.1 KHz stereo. What I'm looking for is help understanding what those floats represent, and what kinds of things can be done with them to dynamically analyze or modify the sound they represent.</p> <p>What sort of concepts do I need to learn about to work with audio this way?</p>
[ { "answer_id": 366246, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 8, "selected": true, "text": "float original_samples = [0, 0.5, 0, -0.5, 0]\n\ndef amplify(samples):\n foreach s in samples:\n s = s * 2\n\namplified_samples = amplify(original_samples)\n\n// result: amplified_samples == [0, 1, 0, -1, 0]\n original_samples = [0, 0.5, 0, -0.5, 0]\n\ndef silence(samples):\n foreach s in samples:\n s = 0\n\nsilent_samples = silence(original_samples)\n\n// result: silent_samples == [0, 0, 0, 0, 0]\n original_samples = [0, 0.1, 0.2, 0.3, 0.4, 0.5]\n\ndef faster(samples):\n new_samples = []\n for i = 0 to samples.length:\n if i is even:\n new_samples.add(samples[i])\n return new_samples\n\nfaster_samples = faster(original_samples)\n\n// result: silent_samples == [0, 0.2, 0.4]\n original_samples = [0, 0.1, 0.2, 0.3]\n\ndef slower(samples):\n new_samples = []\n for i = 0 to samples.length:\n new_samples.add(samples[i])\n new_samples.add(interpolate(s[i], s[i + 1]))\n return new_samples\n\nslower_samples = slower(original_samples)\n\n// result: silent_samples == [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3]\n interpolation data = fft(orignal_samples)\n\nfor i = (data.length / 2) to data.length:\n data[i] = 0\n\nnew_samples = inverse_fft(data)\n data = fft(orignal_samples)\n\nfor i = 0 to (data.length / 4):\n increase(data[i])\n\nnew_samples = inverse_fft(data)\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10651/" ]
366,189
<p>i've got a commenting system in our database. Just like stackoverflow -> each post has a list of comments. kewl.</p> <p>Anonymous people can add a comment or registered users also.</p> <p>In my table, i'm thinking of having the following:</p> <ul> <li>Userid int NULLABLE</li> <li>AnonymousNickname varchar(100) NULLABLE</li> <li>AnonymousEmail varchar(200) NULLABLE</li> </ul> <p>now it can only be one or the other. You're either registered or your not. </p> <p>So should i enforce some type of constraint that says <em>one or the other</em> .. and if so, how?</p> <p>NOTE: Database is Microsoft Sql Server 2008.</p> <p>cheers!</p>
[ { "answer_id": 366199, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "(Userid is not null and AnonymousNickname is null and AnonymousEmail is null)\nor (Userid is null and AnonymousNickname is not null and AnonymousEmail is not null)\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
366,202
<p>I'm new to regular expressions and would appreciate your help. I'm trying to put together an expression that will split the example string using all spaces that are not surrounded by single or double quotes. My last attempt looks like this: <code>(?!")</code> and isn't quite working. It's splitting on the space before the quote.</p> <p>Example input: </p> <pre><code>This is a string that "will be" highlighted when your 'regular expression' matches something. </code></pre> <p>Desired output:</p> <pre><code>This is a string that will be highlighted when your regular expression matches something. </code></pre> <p>Note that <code>"will be"</code> and <code>'regular expression'</code> retain the space between the words.</p>
[ { "answer_id": 366216, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 1, "selected": false, "text": "\"will be\" string = \"This is a string that \\\"will be\\\" highlighted when your 'regular expression' matches something.\";\n\nregex = \"\\\"(\\\\\\\"|(?!\\\\\\\").)+\\\"|[^ ]+\"; // search for a quoted or non-spaced group\nfinal = new Array();\n\nwhile (string.length > 0) {\n string = string.trim();\n if (Regex(regex).test(string)) {\n final.push(Regex(regex).match(string)[0]);\n string = string.replace(regex, \"\"); // progress to next \"word\"\n }\n}\n \"Foo's Bar 'n Grill\"\n\n//=>\n\n\"Foo\"\n\"s Bar \"\n\"n\"\n\"Grill\"\n" }, { "answer_id": 366222, "author": "Zach Scrivena", "author_id": 20029, "author_profile": "https://Stackoverflow.com/users/20029", "pm_score": 1, "selected": false, "text": "String.split() Matcher.lookingAt() String str = \"This is a string that \\\"will be\\\" highlighted when your 'regular expression' matches something.\";\nstr = str + \" \"; // add trailing space\nint len = str.length();\nMatcher m = Pattern.compile(\"((\\\"[^\\\"]+?\\\")|('[^']+?')|([^\\\\s]+?))\\\\s++\").matcher(str);\n\nfor (int i = 0; i < len; i++)\n{\n m.region(i, len);\n\n if (m.lookingAt())\n {\n String s = m.group(1);\n\n if ((s.startsWith(\"\\\"\") && s.endsWith(\"\\\"\")) ||\n (s.startsWith(\"'\") && s.endsWith(\"'\")))\n {\n s = s.substring(1, s.length() - 1);\n }\n\n System.out.println(i + \": \\\"\" + s + \"\\\"\");\n i += (m.group(0).length() - 1);\n }\n}\n 0: \"This\"\n5: \"is\"\n8: \"a\"\n10: \"string\"\n17: \"that\"\n22: \"will be\"\n32: \"highlighted\"\n44: \"when\"\n49: \"your\"\n54: \"regular expression\"\n75: \"matches\"\n83: \"something.\"\n" }, { "answer_id": 366229, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "m/('.*?'|\".*?\"|\\S+)/g \n This\nis\na\nstring\nthat\n\"will be\"\nhighlighted\nwhen\nyour\n'regular expression'\nmatches\nsomething.\n" }, { "answer_id": 366239, "author": "mcrumley", "author_id": 17287, "author_profile": "https://Stackoverflow.com/users/17287", "pm_score": 3, "selected": false, "text": "(?:(['\"])(.*?)(?<!\\\\)(?>\\\\\\\\)*\\1|([^\\s]+))\n" }, { "answer_id": 366532, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 9, "selected": true, "text": "[^\\s\"']+|\"([^\"]*)\"|'([^']*)'\n List<String> matchList = new ArrayList<String>();\nPattern regex = Pattern.compile(\"[^\\\\s\\\"']+|\\\"([^\\\"]*)\\\"|'([^']*)'\");\nMatcher regexMatcher = regex.matcher(subjectString);\nwhile (regexMatcher.find()) {\n if (regexMatcher.group(1) != null) {\n // Add double-quoted string without the quotes\n matchList.add(regexMatcher.group(1));\n } else if (regexMatcher.group(2) != null) {\n // Add single-quoted string without the quotes\n matchList.add(regexMatcher.group(2));\n } else {\n // Add unquoted word\n matchList.add(regexMatcher.group());\n }\n} \n List<String> matchList = new ArrayList<String>();\nPattern regex = Pattern.compile(\"[^\\\\s\\\"']+|\\\"[^\\\"]*\\\"|'[^']*'\");\nMatcher regexMatcher = regex.matcher(subjectString);\nwhile (regexMatcher.find()) {\n matchList.add(regexMatcher.group());\n} \n" }, { "answer_id": 3714474, "author": "Marcus Andromeda", "author_id": 447978, "author_profile": "https://Stackoverflow.com/users/447978", "pm_score": 2, "selected": false, "text": "(?<!\\G\".{0,99999})\\s|(?<=\\G\".{0,99999}\")\\s\n" }, { "answer_id": 15011583, "author": "Eric Woodruff", "author_id": 1139784, "author_profile": "https://Stackoverflow.com/users/1139784", "pm_score": 1, "selected": false, "text": "(?<!\\\\G\\\\S{0,99999}[\\\"'].{0,99999})\\\\s|(?<=\\\\G\\\\S{0,99999}\\\".{0,99999}\\\"\\\\S{0,99999})\\\\s|(?<=\\\\G\\\\S{0,99999}'.{0,99999}'\\\\S{0,99999})\\\\s\"\n" }, { "answer_id": 15350753, "author": "pascals", "author_id": 2158829, "author_profile": "https://Stackoverflow.com/users/2158829", "pm_score": 0, "selected": false, "text": "(['\"])((?:\\\\\\1|.)+?)\\1|([^\\s\"']+)\n" }, { "answer_id": 20539344, "author": "iRon", "author_id": 1701026, "author_profile": "https://Stackoverflow.com/users/1701026", "pm_score": 2, "selected": false, "text": "(\"[^\"]*\"|'[^']*'|[\\S]+)+\n" }, { "answer_id": 23879905, "author": "zx81", "author_id": 1078583, "author_profile": "https://Stackoverflow.com/users/1078583", "pm_score": 1, "selected": false, "text": "\"will be\" 'regular expression' '[^']*'|\\\"[^\\\"]*\\\"|( )\n 'quoted strings' \"double-quoted strings\" SplitHere SplitHere \"will be\" will be import java.util.*;\nimport java.io.*;\nimport java.util.regex.*;\nimport java.util.List;\n\nclass Program {\npublic static void main (String[] args) throws java.lang.Exception {\n\nString subject = \"This is a string that \\\"will be\\\" highlighted when your 'regular expression' matches something.\";\nPattern regex = Pattern.compile(\"\\'[^']*'|\\\"[^\\\"]*\\\"|( )\");\nMatcher m = regex.matcher(subject);\nStringBuffer b= new StringBuffer();\nwhile (m.find()) {\n if(m.group(1) != null) m.appendReplacement(b, \"SplitHere\");\n else m.appendReplacement(b, m.group(0));\n}\nm.appendTail(b);\nString replaced = b.toString();\nString[] splits = replaced.split(\"SplitHere\");\nfor (String split : splits) System.out.println(split);\n} // end main\n} // end Program\n" }, { "answer_id": 39452156, "author": "Rakesh Sosa", "author_id": 5951283, "author_profile": "https://Stackoverflow.com/users/5951283", "pm_score": 0, "selected": false, "text": " String str = \"This is a string that \\\"will be\\\" highlighted when your 'regular expression' matches something\";\n String ss[] = str.split(\"\\\"|\\'\");\n for (int i = 0; i < ss.length; i++) {\n if ((i % 2) == 0) {//even\n String[] part1 = ss[i].split(\" \");\n for (String pp1 : part1) {\n System.out.println(\"\" + pp1);\n }\n } else {//odd\n System.out.println(\"\" + ss[i]);\n }\n }\n" }, { "answer_id": 47454129, "author": "Praveen Singh", "author_id": 5405129, "author_profile": "https://Stackoverflow.com/users/5405129", "pm_score": 1, "selected": false, "text": "string input= \"This is a string that \\\"will be\\\" highlighted when your 'regular expression' matches <something random>\";\n\nList<string> list1 = \n Regex.Matches(input, @\"(?<match>\\w+)|\\\"\"(?<match>[\\w\\s]*)\"\"|'(?<match>[\\w\\s]*)'|<(?<match>[\\w\\s]*)>\").Cast<Match>().Select(m => m.Groups[\"match\"].Value).ToList();\n\nforeach(var v in list1)\n Console.WriteLine(v);\n This\nis\na\nstring\nthat\nwill be\nhighlighted\nwhen\nyour\nregular expression \nmatches\nsomething random\n" }, { "answer_id": 57151834, "author": "Rudi Jansen van Vuuren", "author_id": 6692685, "author_profile": "https://Stackoverflow.com/users/6692685", "pm_score": 0, "selected": false, "text": "using System.Text.RegularExpressions;\n\nvar args = Regex.Matches(command, \"[^\\\\s\\\"']+|\\\"([^\\\"]*)\\\"|'([^']*)'\").Cast<Match>\n().Select(iMatch => iMatch.Value.Replace(\"\\\"\", \"\").Replace(\"'\", \"\")).ToArray();\n" }, { "answer_id": 61120643, "author": "Kaplan", "author_id": 11199879, "author_profile": "https://Stackoverflow.com/users/11199879", "pm_score": 2, "selected": false, "text": "String s = \"This is a string that \\\"will be\\\" highlighted when your 'regular expression' matches something.\";\nString[] split = s.split( \"(?<!(\\\"|').{0,255}) | (?!.*\\\\1.*)\" );\n [This, is, a, string, that, \"will be\", highlighted, when, your, 'regular expression', matches, something.]" }, { "answer_id": 74514305, "author": "Alferd Nobel", "author_id": 4005379, "author_profile": "https://Stackoverflow.com/users/4005379", "pm_score": 0, "selected": false, "text": "String str = \"2022-11-10 08:35:00,470 RAV=REQ YIP=02.8.5.1 CMID=caonaustr CMN=\\\"Some Value Pyt Ltd\\\"\";\n//this helped\nString[] str1= str.split(\"\\\\s(?=(([^\\\"]*\\\"){2})*[^\\\"]*$)\\\\s*\");\nSystem.out.println(\"Value of split string is \"+ Arrays.toString(str1));\n [2022-11-10, 08:35:00,470, PLV=REQ, YIP=02.8.5.1, CMID=caonaustr, CMN=\"Some Value Pyt Ltd\"]" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46077/" ]
366,211
<p><strong>Problem:</strong> EmacsW32 is a version of Emacs that allows the user to make Emacs treat the "Windows" key as the "Meta" key (instead of treating the Alt key as the "Meta" key). Although this works as advertised, the question is what happens when you want to create an Emacs keybinding for the "Alt" key?</p> <p><strong>Question:</strong> Is there a way in this case to allow Emacs to capture and create keybindings to the "Alt" key also, even though it now considers "Windows" key to be the new Meta?</p>
[ { "answer_id": 366394, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 1, "selected": false, "text": "Meta Shift Control Meta Hyper Super man xmodmap" }, { "answer_id": 366636, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 3, "selected": true, "text": "C-h c M-f runs the command forward-word Hyper f is undefined Super f is undefined xmodmap" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42223/" ]
366,228
<p>I am not understanding the point of using .def files with DLLs.</p> <p>It seems that it replaces the need to use explicit exports within your DLL code (ie. explicit __declspec(dllexport)) however I am unable to generate a lib file when not using these which then creates linker issues later when using the DLL. </p> <p>So how do you use .defs when linking with the client application, do they replace the need to use a header or .lib file?</p>
[ { "answer_id": 376784, "author": "cweston", "author_id": 37966, "author_profile": "https://Stackoverflow.com/users/37966", "pm_score": 4, "selected": false, "text": "lib /machine:i386 /def:sqlite3.def\n" }, { "answer_id": 597573, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "void foo(int i);\n HANDLE dllHandle = LoadLibrary(\"mydll.dll\");\nvoid* fooFcnPtr = GetProcAddress(dllHandle, \"foo\");\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37966/" ]
366,232
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/517915/when-to-use-strictfp-keyword-in-java">When to use &ldquo;strictfp&rdquo; keyword in java?</a> </p> </blockquote> <p>What is the use of Strictfp method in java?</p>
[ { "answer_id": 366269, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 4, "selected": true, "text": "strictfp" }, { "answer_id": 366270, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 1, "selected": false, "text": "strictfp" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40945/" ]
366,237
<p>Here's an example:</p> <pre><code>Double d = (1/3); System.out.println(d); </code></pre> <p>This returns 0, not 0.33333... as it should.</p> <p>Does anyone know?</p>
[ { "answer_id": 366240, "author": "Firas Assaad", "author_id": 23153, "author_profile": "https://Stackoverflow.com/users/23153", "pm_score": 6, "selected": true, "text": "1 3 integers 1/3 integer 0 double 0 (1.0/3) 1D/3" }, { "answer_id": 366253, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 4, "selected": false, "text": "int int double double d = (double)intValue1 / (double)intValue2\n intValue2 intValue1 double" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46084/" ]
366,245
<p>I'd like to make a simple html form where a person can upvote or downvote an item. However I don't like the default look of a <code>&lt;input type="submit"&gt;</code> . What other options do I have to send a POST request than a bulky, default button?</p>
[ { "answer_id": 366252, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 3, "selected": false, "text": "document.myform.submit();\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25680/" ]
366,251
<p>I'm trying to use prototype and scriptaculous to hide and display a div element but the function (below) to take advantage of the prototype setStyle property isn't working and I'm not sure what the problem is.</p> <pre><code>&lt;script type="text/javascript" language="javascript"&gt; function bodyOnload() { $('content1').setStyle({ display: 'none' }); $('content2').setStyle({ display: 'none' }); } &lt;/script&gt; &lt;script type="text/javascript" language="javascript"&gt; var currentId = null; Effect.Accordion = function (contentId) { var slideDown = 0.5; var slideUp = 0.5; contentId = $(contentId); if (currentId != contentId) { if (currentId == null) { new Effect.SlideDown(contentId, {duration: slideDown}); } else { new Effect.SlideUp(currentId, {duration: slideUp}); new Effect.SlideDown(contentId, {duration: slideDown}); } currentId = contentId; } else { new Effect.SlideUp(currentId, {duration: slideUp}); currentId = null; } }; &lt;/script&gt; </code></pre> <p>The preceding function is called as such:</p> <pre><code>&lt;div id="accordion"&gt; &lt;div id="part1"&gt; &lt;div id="nav1" onclick="new Effect.Accordion('content1');"&gt; Post a comment 1 &lt;/div&gt; &lt;div id="content1"&gt; &lt;form id="form" name="form" action="post.php" method="post"&gt; &lt;textarea name="commentbody" cols="20" rows="10"&gt;&lt;/textarea&gt; &lt;button type="submit"&gt;Post Comment&lt;/button&gt; &lt;input type="hidden" name="blogID" value="1" /&gt; &lt;input type="hidden" name="userID" value="3" /&gt; &lt;input type="hidden" name="parentID" value="7" /&gt; &lt;div class="spacer"&gt;&lt;/div&gt;&lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="part2"&gt; &lt;div id="nav2" onclick="new Effect.Accordion('content2');"&gt; Post a comment 2 &lt;/div&gt; &lt;div id="content2"&gt; &lt;form id="form" name="form" action="post.php" method="post"&gt; &lt;textarea name="commentbody" cols="20" rows="10"&gt;&lt;/textarea&gt; &lt;button type="submit"&gt;Post Comment&lt;/button&gt; &lt;input type="hidden" name="blogID" value="1" /&gt; &lt;input type="hidden" name="userID" value="3" /&gt; &lt;input type="hidden" name="parentID" value="7" /&gt; &lt;div class="spacer"&gt;&lt;/div&gt;&lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Here's what happens with the code.</p> <ul> <li>In both ie and firefox it does nothing but when you click on the link that calls the effect.accordion method the method works as expected. The problem is with the prototype function which doesn't hide the elements. Any help with be greatly appreciated. </li> </ul>
[ { "answer_id": 366297, "author": "maxnk", "author_id": 45862, "author_profile": "https://Stackoverflow.com/users/45862", "pm_score": 1, "selected": false, "text": "window.onload = bodyOnload;\n" }, { "answer_id": 366304, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 4, "selected": true, "text": "dom:loaded window.onload document.observe(\"dom:loaded\", bodyOnload);\n Element#toggle Element#hide Element#setStyle function bodyOnload() {\n $('content1').hide();\n $('content2').hide();\n}\n" }, { "answer_id": 366333, "author": "hoyt.dev", "author_id": 40376, "author_profile": "https://Stackoverflow.com/users/40376", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\" src=\"javascripts/prototype.js\"></script>\n<script type=\"text/javascript\" src=\"javascripts/scriptaculous.js?load=effects\"></script>\n <script type=\"text/javascript\" src=\"javascripts/prototype.js\"></script>\n<script type=\"text/javascript\" src=\"javascripts/effects.js\"></script>\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40376/" ]
366,255
<p>MSIE v7 does not (in my hands) open a Modeless Dialog or trigger an onLoad event if there is a Javascript alert in the target page. The following fails in MSIE v7 but is OK in v6 (zip file of full source available if required). </p> <p>Would appreciate others confirming this and discussing why this should be so.</p> <p>index.htm (only javascript function shown here)</p> <pre><code>function openDialog(n) { if (typeof(window.showModalDialog) == 'object') { /* Ensure of browser support */ var sURL = 'modeless.htm'; /* Set the URL */ var oWin = window.showModelessDialog(sURL); /* Create new modeless window */ } else { alert('"showModlessDialog" not supported!'); } } </code></pre> <p>modeless.htm</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Modeless dialog&lt;/title&gt; &lt;/head&gt; &lt;body bgcolor="#ff0000" text="#ffffff" onLoad="alert('Modeless is now loaded')"&gt; &lt;center&gt; &lt;h1&gt;Modeless&lt;/h1&gt; &lt;/center&gt; &lt;script type="text/javascript" language="JavaScript"&gt; /* If the next line is included, it prevents the onLoad event occurring in MSIE v7 */ alert('This alert stops the onLoad event in MSIE v7!'); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 372300, "author": "w4g3n3r", "author_id": 36745, "author_profile": "https://Stackoverflow.com/users/36745", "pm_score": 0, "selected": false, "text": "<html>\n <head>\n <title>Index</title>\n <script type=\"text/javascript\" language=\"JavaScript\">\n\n function openDialog() {\n if (window.showModalDialog) { \n var sURL = 'Modeless.htm'; \n var oWin = window.showModelessDialog(sURL); \n }\n else\n {\n alert('\"showModlessDialog\" not supported!');\n }\n }\n\n function addEventSimple(obj,evt,fn) {\n if (obj.addEventListener)\n obj.addEventListener(evt,fn,false);\n else if (obj.attachEvent)\n obj.attachEvent('on'+evt,fn);\n }\n\n function removeEventSimple(obj,evt,fn) {\n if (obj.removeEventListener)\n obj.removeEventListener(evt,fn,false);\n else if (obj.detachEvent)\n obj.detachEvent('on'+evt,fn);\n }\n\n addEventSimple(window, \"load\", openDialog);\n </script>\n </head>\n <body text=\"#ffffff\">\n <h1 align=\"center\">Index</h1>\n </body>\n</html>\n <html>\n<head>\n <title>Modeless dialog</title>\n <script type=\"text/javascript\" language=\"JavaScript\">\n addEventSimple(window, \"load\", showAlert);\n\n function showAlert() {\n alert('Modeless is now Loaded');\n }\n\n function addEventSimple(obj,evt,fn) {\n if (obj.addEventListener)\n obj.addEventListener(evt,fn,false);\n else if (obj.attachEvent)\n obj.attachEvent('on'+evt,fn);\n }\n\n function removeEventSimple(obj,evt,fn) {\n if (obj.removeEventListener)\n obj.removeEventListener(evt,fn,false);\n else if (obj.detachEvent)\n obj.detachEvent('on'+evt,fn);\n }\n </script>\n</head>\n<body text=\"#ffffff\" >\n <h1 align=\"center\">Modeless</h1>\n <script type=\"text/javascript\" language=\"JavaScript\">\n /* If the next line is included, it prevents the onLoad event occurring in MSIE v7 */\n alert('This alert stops the onLoad event in MSIE v7!');\n </script>\n</body>\n</html>\n" }, { "answer_id": 387002, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 1, "selected": false, "text": "window.onload = function() {\n //do stuff here\n}\n $(document).ready(function() {\n //do stuff here\n});\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46085/" ]
366,262
<p>I need to know how I can search an array for some literal text and have it used as a condition whether to continue.</p> <p>Here's why: Each time I execute a function I am pushing the ID of the property it acts upon into an array. I need my function to check if that ID is in the array already and if it is, remove it and execute my other function (the opposite).</p> <p>Here's an example array:</p> <pre><code>var myArray = new Array(); myArray.push([1.000,1.000,"test1"]); myArray.push([2.000,2.000,"test2"]); myArray.push([3.000,3.000,"test3"]); </code></pre> <p>I know the Grep function can search but I can't get it to evaluate true or false if it finds something.</p> <p>Heres my ideal use of the search evaluation.</p> <pre><code>function searcher(id){ if(myArray.grep(id);){ oppositeFunction(id); }else{ function(id); } } </code></pre>
[ { "answer_id": 366271, "author": "Supernovah", "author_id": 36076, "author_profile": "https://Stackoverflow.com/users/36076", "pm_score": 1, "selected": false, "text": "function arraytest(){\n var myArray = new Array(); \n myArray.push([\"test1\"]); \n myArray.push([\"test2\"]); \n myArray.push([\"test3\"]); \n for(i=0;i<myArray.length;i++){\n if(myArray[i]==\"test1\"){\n successFunction(\"Celebration\\!\");\n }\n }\n}\n" }, { "answer_id": 366272, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": " function superContains(aray,id)\n {\n var contains = false;\n for (var i=0, len = aray.length; !contains && i < len; ++i)\n {\n var elem = aray[i];\n if (elem.constructor && elem.constructor == Array)\n {\n contains = superContains(elem,id);\n }\n else\n {\n contains = elem == id; // or elem.match(id)\n }\n }\n return contains;\n }\n" }, { "answer_id": 366343, "author": "some", "author_id": 36866, "author_profile": "https://Stackoverflow.com/users/36866", "pm_score": 2, "selected": false, "text": "var myhash = {};\n\nmyhash[\"test1\"] = [1.000,1.000];\nmyhash[\"test2\"] = [2.000,2.000];\nmyhash[\"test3\"] = [3.000,3.000];\n\nfunction searcher(id){\n if (myhash[id]) {\n delete myhash[id];\n oppositeFunction(id);\n }else{\n normalFunction(id);\n }\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36076/" ]
366,273
<p>Can anyone send me a c code to divide 2 64bit numbers. My compiler only supports 32/32 division.</p> <p>Thanx &amp; Regards</p> <p>Mani</p>
[ { "answer_id": 366300, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 4, "selected": false, "text": "#include <stdint.h>\n#include <stdio.h>\nint main(void)\n{\n int64_t numerator = 123;\n int64_t denominator = 10;\n int64_t quotient = numerator / denominator\n printf(\"%\" PRId64 \" / %\" PRId64 \" = %\" PRId64 \"\\n\",\n numerator, denominator, quotient);\n return 0;\n}\n" }, { "answer_id": 366319, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "void mpf_div (mpf_t rop, mpf_t op1, mpf_t op2)" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,311
<p>I'm pretty happy with <a href="http://whatcodecraves.com/posts/2008/12/13/rails-flash-with-ajax.html" rel="noreferrer">the solution</a> that I came up with. Basically, I have a helper method that reloads the flash inline, and then I have an after_filter that clear out the flash if the request is xhr. Does anyone have a simpler solution than that?</p> <p><strong>Update:</strong> The solution above was written back in Rails 1.x and is no longer supported.</p>
[ { "answer_id": 405290, "author": "nakajima", "author_id": 39589, "author_profile": "https://Stackoverflow.com/users/39589", "pm_score": 3, "selected": false, "text": "flash.now[:notice]" }, { "answer_id": 423957, "author": "Silviu Postavaru", "author_id": 3718, "author_profile": "https://Stackoverflow.com/users/3718", "pm_score": 4, "selected": false, "text": "page.replace_html :notice, flash[:notice]\nflash.discard\n $(\"#flash_notice\").html(<%=escape_javascript(flash.delete(:notice)) %>');\n" }, { "answer_id": 2729454, "author": "gudleik", "author_id": 291939, "author_profile": "https://Stackoverflow.com/users/291939", "pm_score": 6, "selected": false, "text": "class ApplicationController < ActionController::Base\nafter_filter :flash_to_headers\n\ndef flash_to_headers\n return unless request.xhr?\n response.headers['X-Message'] = flash[:error] unless flash[:error].blank?\n # repeat for other flash types...\n\n flash.discard # don't want the flash to appear when you reload page\nend\n $(document).ajaxError(function(event, request) {\n var msg = request.getResponseHeader('X-Message');\n if (msg) alert(msg);\n});\n" }, { "answer_id": 5007619, "author": "empz", "author_id": 105937, "author_profile": "https://Stackoverflow.com/users/105937", "pm_score": 2, "selected": false, "text": "class ApplicationController < ActionController::Base\n after_filter :flash_to_headers\n\ndef flash_to_headers\n return unless request.xhr?\n response.headers['X-Message'] = flash_message\n response.headers[\"X-Message-Type\"] = flash_type\n\n flash.discard # don't want the flash to appear when you reload page\nend\n\nprivate\n\ndef flash_message\n [:error, :warning, :notice].each do |type|\n return flash[type] unless flash[type].blank?\n end\nend\n\ndef flash_type\n [:error, :warning, :notice].each do |type|\n return type unless flash[type].blank?\n end\nend\n Ajax.Responders.register({\nonComplete: function(event, request) {\n var msg = request.getResponseHeader('X-Message');\n var type = request.getResponseHeader('X-Message-Type');\n showAjaxMessage(msg, type); //use whatever popup, notification or whatever plugin you want\n }\n});\n" }, { "answer_id": 6955306, "author": "Arun Kumar Arjunan", "author_id": 427606, "author_profile": "https://Stackoverflow.com/users/427606", "pm_score": 3, "selected": false, "text": " flash.now[:notice] = 'Your message'\n <%= yield %>\n alert('<%= escape_javascript(flash.now[:notice]) %>'); \n <%= yield %>\n <% if flash.now[:notice] %>\n $.gritter.add({\n title: '--',\n text: '<%= escape_javascript(flash.now[:notice]) %>'\n });\n <% end %>\n" }, { "answer_id": 7414578, "author": "Vikrant Chaudhary", "author_id": 89744, "author_profile": "https://Stackoverflow.com/users/89744", "pm_score": 3, "selected": false, "text": "#application_controller.rb\nclass ApplicationController < ActionController::Base\n after_filter :flash_to_headers\n\n def flash_to_headers\n if request.xhr?\n #avoiding XSS injections via flash\n flash_json = Hash[flash.map{|k,v| [k,ERB::Util.h(v)] }].to_json\n response.headers['X-Flash-Messages'] = flash_json\n flash.discard\n end\n end\nend\n //application.js\n$(document).ajaxComplete(function(event, request){\n var flash = $.parseJSON(request.getResponseHeader('X-Flash-Messages'));\n if(!flash) return;\n if(flash.notice) { /* code to display the 'notice' flash */ $('.flash.notice').html(flash.notice); }\n if(flash.error) { /* code to display the 'error' flash */ alert(flash.error); }\n //so forth\n}\n" }, { "answer_id": 8873592, "author": "dbKooper", "author_id": 714092, "author_profile": "https://Stackoverflow.com/users/714092", "pm_score": 4, "selected": false, "text": "respond_to do |format|\n flash.now[:notice] = @msg / 'blah blah...'\n format.html \n format.js\n end\n <div id='notice'>\n <%= render :partial => 'layouts/flash' , :locals => { :flash => flash } %>\n</div> \n <% flash.each do |name, msg| %>\n <div class=\"alert-message info\"> \n <a class=\"close dismiss\" href=\"#\">x</a> \n <p><%= msg %></p>\n </div>\n<% end %>\n $(\"#notice\").html(\"<%= escape_javascript(render :partial => 'layouts/flash' , :locals => { :flash => flash }).html_safe %>\");\n" }, { "answer_id": 10167659, "author": "Victor S", "author_id": 407615, "author_profile": "https://Stackoverflow.com/users/407615", "pm_score": 5, "selected": false, "text": "class ApplicationController < ActionController::Base\n protect_from_forgery\n\n after_filter :flash_to_headers\n\n def flash_to_headers\n return unless request.xhr?\n response.headers['X-Message'] = flash_message\n response.headers[\"X-Message-Type\"] = flash_type.to_s\n\n flash.discard # don't want the flash to appear when you reload page\n end\n\n private\n\n def flash_message\n [:error, :warning, :notice].each do |type|\n return flash[type] unless flash[type].blank?\n end\n end\n\n def flash_type\n [:error, :warning, :notice].each do |type|\n return type unless flash[type].blank?\n end\n end\nend\n // FLASH NOTICE ANIMATION\nvar fade_flash = function() {\n $(\"#flash_notice\").delay(5000).fadeOut(\"slow\");\n $(\"#flash_alert\").delay(5000).fadeOut(\"slow\");\n $(\"#flash_error\").delay(5000).fadeOut(\"slow\");\n};\nfade_flash();\n\nvar show_ajax_message = function(msg, type) {\n $(\"#flash-message\").html('<div id=\"flash_'+type+'\">'+msg+'</div>');\n fade_flash();\n};\n\n$(document).ajaxComplete(function(event, request) {\n var msg = request.getResponseHeader('X-Message');\n var type = request.getResponseHeader('X-Message-Type');\n show_ajax_message(msg, type); //use whatever popup, notification or whatever plugin you want\n});\n #flash-message\n - flash.each do |name, msg|\n = content_tag :div, msg, :id => \"flash_#{name}\"\n" }, { "answer_id": 17434302, "author": "Vadym Tyemirov", "author_id": 1318367, "author_profile": "https://Stackoverflow.com/users/1318367", "pm_score": 0, "selected": false, "text": "respond_to :js\n\ndef your_ajax_method\n flash[:notice] = 'Your message!'\nend\n :plain\n $(\"form[data-remote]\")\n .on(\"ajax:success\", function(e, data, status, xhr) {\n $('.messages').html(\"#{escape_javascript(render 'layouts/messages')}\");\n setTimeout(function(){ $(\".alert\").alert('close') }, 5000);\n })\n $('.messages').html(\"<%= j(render 'layouts/messages') %>\"); your_ajax_method_in_the_controller.js.coffee $(\".alert\").alert('close') - flash.each do |name, msg|\n - if msg.is_a?(String)\n .alert-messages\n %div{class: \"alert alert-#{name == :notice ? \"success\" : \"error\"} fade in\"}\n %a.close{\"data-dismiss\" => \"alert\"} \n %i.icon-remove-circle\n = content_tag :div, msg, id: \"flash_#{name}\"\n .alert-messages {\n position: fixed;\n top: 37px;\n left: 30%;\n right: 30%;\n z-index: 7000;\n}\n" }, { "answer_id": 18678966, "author": "Ricky Gu", "author_id": 852955, "author_profile": "https://Stackoverflow.com/users/852955", "pm_score": 2, "selected": false, "text": "flash[type].blank? after_filter :flash_to_headers\n\ndef flash_to_headers\n return unless request.xhr?\n response.headers['X-Message'] = flash_message\n response.headers[\"X-Message-Type\"] = flash_type.to_s\n\n flash.discard # don't want the flash to appear when you reload page\nend\n\nprivate\n\ndef flash_message\n [:error, :warning, :notice, nil].each do |type|\n return \"\" if type.nil?\n return flash[type] unless flash[type].blank?\n end\nend\n\ndef flash_type\n [:error, :warning, :notice, nil].each do |type|\n return \"\" if type.nil?\n return type unless flash[type].blank?\n end\nend\n // FLASH NOTICE ANIMATION\n\nvar fade_flash = function() {\n $(\".flash_notice\").delay(5000).fadeOut(\"slow\");\n $(\".flash_alert\").delay(5000).fadeOut(\"slow\");\n $(\".flash_error\").delay(5000).fadeOut(\"slow\");\n};\n\nvar show_ajax_message = function(msg, type) {\n $(\".flash_message\").html('<div class=\"flash_'+type+'\">'+msg+'</div>');\n fade_flash();\n};\n\n$( document ).ajaxComplete(function(event, request) {\n var msg = request.getResponseHeader('X-Message');\n var type = request.getResponseHeader('X-Message-Type');\n show_ajax_message(msg, type); //use whatever popup, notification or whatever plugin you want\n\n});\n" }, { "answer_id": 18766826, "author": "Luc Boissaye", "author_id": 1607015, "author_profile": "https://Stackoverflow.com/users/1607015", "pm_score": 2, "selected": false, "text": "after_filter :flash_to_headers\ndef flash_to_headers\n return unless request.xhr?\n [:error, :warning, :notice].each do |type|\n if flash[type]\n response.headers[\"X-Ajax-#{type.to_s.humanize}\"] = flash[type]\n end\n end\n flash.discard\nend\n css_class = {\n Notice: 'success',\n Warning: 'warning',\n Error: 'error'\n}\n$(document).ajaxComplete (event, request) ->\n for type in [\"Notice\", \"Warning\", \"Error\"]\n msg = request.getResponseHeader(\"X-Ajax-#{type}\")\n if msg?\n $('#notices').append(\"<div class=\\\"alert #{css_class[type]}\\\">#{decodeURIComponent(escape(msg))}</div>\")\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25024/" ]
366,324
<p>Just for the sake of experimentation, I've been trying to determine different ways to non-destructively chain <code>window.onload</code> functions in a web browser. This is the idea of what I have so far:</p> <pre><code>var load = window.onload; var newFunction = function(){ alert("ha!"); } window.onload = function(){ load(); newFunction(); } </code></pre> <p>The problem I see with this is that every time you chain a function, it adds another level of function calls to the stack. Is there a better way to go about this that doesn't add unnecessary depth to the call stack?</p>
[ { "answer_id": 366335, "author": "Kit Sunde", "author_id": 29347, "author_profile": "https://Stackoverflow.com/users/29347", "pm_score": 0, "selected": false, "text": "var addEvent = function( obj, type, fn ) {\n if (obj.addEventListener)\n obj.addEventListener(type, fn, false);\n else if (obj.attachEvent) \n obj.attachEvent('on' + type, function() { return fn.apply(obj, new Array(window.event));});\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1370/" ]
366,326
<p>We all know and love Process.WaitForExit().</p> <p>Given a pid of a process on a remote machine (created by WMI/psexec), how do I wait for it to end?</p>
[ { "answer_id": 366385, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 1, "selected": true, "text": "Process.GetProcessById(processId, machineName).WaitForExit();\n" }, { "answer_id": 366472, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 2, "selected": false, "text": "public static bool WaitForProcess(int pid, string machine, TimeSpan timeout)\n{\n // busy wait\n DateTime start = DateTime.Now;\n while (IsAlive(pid, machine))\n {\n if (start.Add(timeout).CompareTo(DateTime.Now) <= 0)\n return false;\n\n Thread.Sleep(1000);\n }\n return true;\n}\n\npublic static bool IsAlive(int pid, string machine)\n{\n // doesn't work for me (throws \"The network path was not found\" exception)\n //return Process.GetProcessById(pid, @\"\\\\\" + machine) != null;\n string user;\n string domain;\n GetProcessInfoByPID(pid, machine, out user, out domain);\n return !string.IsNullOrEmpty(user);\n}\n\npublic static string GetProcessInfoByPID(int PID, string machine, out string User, out string Domain)\n{\n // copied from http://www.codeproject.com/KB/cs/processownersid.aspx?fid=323674&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2076667\n // with slight modifications\n ConnectionOptions connOptions = new ConnectionOptions();\n connOptions.Impersonation = ImpersonationLevel.Impersonate;\n connOptions.EnablePrivileges = true;\n ManagementScope manScope = new ManagementScope(String.Format(@\"\\\\{0}\\ROOT\\CIMV2\", machine), connOptions);\n manScope.Connect();\n\n User = String.Empty;\n Domain = String.Empty;\n string OwnerSID = String.Empty;\n string processname = String.Empty;\n try\n {\n ObjectQuery sq = new ObjectQuery\n (\"Select * from Win32_Process Where ProcessID = '\" + PID + \"'\");\n ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, sq);\n if (searcher.Get().Count == 0)\n return OwnerSID;\n foreach (ManagementObject oReturn in searcher.Get())\n {\n string[] o = new String[2];\n //Invoke the method and populate the o var with the user name and domain\n oReturn.InvokeMethod(\"GetOwner\", o);\n\n //int pid = (int)oReturn[\"ProcessID\"];\n processname = (string)oReturn[\"Name\"];\n //dr[2] = oReturn[\"Description\"];\n User = o[0];\n if (User == null)\n User = String.Empty;\n Domain = o[1];\n if (Domain == null)\n Domain = String.Empty;\n string[] sid = new String[1];\n oReturn.InvokeMethod(\"GetOwnerSid\", sid);\n OwnerSID = sid[0];\n return OwnerSID;\n }\n }\n catch\n {\n return OwnerSID;\n }\n return OwnerSID;\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
366,329
<p>Why can't Delphi variants hold objects? More importantly, what's the reason behind this limitation? </p>
[ { "answer_id": 366363, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 5, "selected": false, "text": "obj := TObject.Create;\nv := NativeUInt(obj);\nobj := TSomeObject(NativeUInt(v));\n" }, { "answer_id": 366615, "author": "Cesar Romero", "author_id": 36875, "author_profile": "https://Stackoverflow.com/users/36875", "pm_score": 3, "selected": false, "text": "var\n MyObject: TMyObject;\n Value: Variant;\nbegin\n MyObject:= TMyObject.Create;\n TVarData(Value).VType:= VarByRef or VarUnknown;\n TVarData(Value).VPointer:= MyObject;\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14716/" ]
366,332
<pre><code>public class Address { public string ZipCode {get; set;} } public class Customer { public Address Address {get; set;} } </code></pre> <p>how can I access eitther "ZipCode" or "Address.ZipCode" with reflection? For example: </p> <pre><code>Typeof(Customer).GetProperty("ZipCode")? </code></pre>
[ { "answer_id": 366337, "author": "maxnk", "author_id": 45862, "author_profile": "https://Stackoverflow.com/users/45862", "pm_score": 2, "selected": false, "text": "typeof (Customer).GetProperty(\"Address\").PropertyType.GetProperty(\"ZipCode\")\n" }, { "answer_id": 366339, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "PropertyInfo addressProperty = typeof(Customer).GetProperty(\"Address\");\nProportyInfo zipCodeProperty = addressProperty.PropertyType.GetProperty(\"ZipCode\");\n\nobject address = addressProperty.GetValue(customer, null);\nobject zipCode = zipCodeProperty.GetValue(address, null);\n public static object FollowPropertyPath(object value, string path)\n{\n Type currentType = value.GetType();\n\n foreach (string propertyName in path.Split('.'))\n {\n PropertyInfo property = currentType.GetProperty(propertyName);\n value = property.GetValue(value, null);\n currentType = property.PropertyType;\n }\n return value;\n}\n object zipCode = FollowPropertyPath(customer, \"Address.ZipCode\");\n property.PropertyType property.GetType()" }, { "answer_id": 366357, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "static void Main()\n{\n object obj = new Customer { Address = new Address { ZipCode = \"abcdef\" } };\n\n object address = GetValue(obj, \"Address\");\n object zip = GetValue(address, \"ZipCode\");\n\n Console.WriteLine(zip);\n}\nstatic object GetValue(object component, string propertyName)\n{\n return TypeDescriptor.GetProperties(component)[propertyName].GetValue(component);\n}\n static object ResolveValue(object component, string path) {\n foreach(string segment in path.Split('.')) {\n if (component == null) return null;\n if(component is IListSource) {\n component = ((IListSource)component).GetList();\n }\n if (component is IList) {\n component = ((IList)component)[0];\n }\n component = GetValue(component, segment);\n }\n return component;\n}\n" }, { "answer_id": 4990851, "author": "Mike Fuchs", "author_id": 385995, "author_profile": "https://Stackoverflow.com/users/385995", "pm_score": 3, "selected": false, "text": "public static class ReflectorUtil\n{\n public static object FollowPropertyPath(object value, string path)\n {\n if (value == null) throw new ArgumentNullException(\"value\");\n if (path == null) throw new ArgumentNullException(\"path\");\n\n Type currentType = value.GetType();\n\n object obj = value;\n foreach (string propertyName in path.Split('.'))\n {\n if (currentType != null)\n {\n PropertyInfo property = null;\n int brackStart = propertyName.IndexOf(\"[\");\n int brackEnd = propertyName.IndexOf(\"]\");\n\n property = currentType.GetProperty(brackStart > 0 ? propertyName.Substring(0, brackStart) : propertyName);\n obj = property.GetValue(obj, null);\n\n if (brackStart > 0)\n {\n string index = propertyName.Substring(brackStart + 1, brackEnd - brackStart - 1);\n foreach (Type iType in obj.GetType().GetInterfaces())\n {\n if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof(IDictionary<,>))\n {\n obj = typeof(ReflectorUtil).GetMethod(\"GetDictionaryElement\")\n .MakeGenericMethod(iType.GetGenericArguments())\n .Invoke(null, new object[] { obj, index });\n break;\n }\n if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof(IList<>))\n {\n obj = typeof(ReflectorUtil).GetMethod(\"GetListElement\")\n .MakeGenericMethod(iType.GetGenericArguments())\n .Invoke(null, new object[] { obj, index });\n break;\n }\n }\n }\n\n currentType = obj != null ? obj.GetType() : null; //property.PropertyType;\n }\n else return null;\n }\n return obj;\n }\n\n public static TValue GetDictionaryElement<TKey, TValue>(IDictionary<TKey, TValue> dict, object index)\n {\n TKey key = (TKey)Convert.ChangeType(index, typeof(TKey), null);\n return dict[key];\n }\n\n public static T GetListElement<T>(IList<T> list, object index)\n {\n return list[Convert.ToInt32(index)];\n }\n\n}\n" }, { "answer_id": 22817172, "author": "EmbraceUnity", "author_id": 1739938, "author_profile": "https://Stackoverflow.com/users/1739938", "pm_score": 1, "selected": false, "text": " public static Type FollowPropertyPath<T>(string path)\n {\n if (path == null) throw new ArgumentNullException(\"path\");\n\n Type currentType = typeof(T);\n\n foreach (string propertyName in path.Split('.'))\n {\n int brackStart = propertyName.IndexOf(\"[\");\n\n var property = currentType.GetProperty(brackStart > 0 ? propertyName.Substring(0, brackStart) : propertyName);\n\n if (property == null)\n return null;\n\n currentType = property.PropertyType;\n\n if (brackStart > 0)\n {\n foreach (Type iType in currentType.GetInterfaces())\n {\n if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof (IDictionary<,>))\n {\n currentType = iType.GetGenericArguments()[1];\n break;\n }\n if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof (ICollection<>))\n {\n currentType = iType.GetGenericArguments()[0];\n break;\n }\n }\n }\n }\n\n return currentType;\n }\n" }, { "answer_id": 52361678, "author": "Eric McLachlan", "author_id": 4093278, "author_profile": "https://Stackoverflow.com/users/4093278", "pm_score": 1, "selected": false, "text": "currentType = property.PropertyType public static object FollowPropertyPath(object value, string path)\n{\n Type currentType = value.GetType();\n\n foreach (string propertyName in path.Split('.'))\n {\n PropertyInfo property = currentType.GetProperty(propertyName);\n value = property.GetValue(value, null);\n currentType = value.GetType(); // <-- Change\n }\n return value;\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31624/" ]
366,345
<p>I have an external DLL whose source code is C#. From the documentation for the DLL, I determined that it writes its debug messages to the console using <code>Console.WriteLine</code>.</p> <p>I'd like to use this DLL within a WinForms application. However, what I have discovered is that I cannot see the debug messages emitted by the DLL since a WinForms application does not have a console.</p> <p>is there a way to capture those debug messages, perhaps even to a simple log file? Of course, using <code>ProcessInfo.RedirectStandartOutput</code> will not work as I do not use the DLL as a process.</p>
[ { "answer_id": 366434, "author": "user46119", "author_id": 46119, "author_profile": "https://Stackoverflow.com/users/46119", "pm_score": 2, "selected": false, "text": " Debug.Listeners.Add(new ConsoleTraceListener())\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33030/" ]
366,364
<p>I just got a weird idea about how to configure environment-dependent parameters. Sort of like parameters you can find in Rails' config/database.yml</p> <p>In my current project I use PHP and Litespeed Web Server (though the same technique applies to PHP + Apache), and I thought... 'why not use mod_rewrite for this?'. I have separate virtual hosts configs for each env (development/production at the moment)</p> <p>What I have now is:</p> <pre> <code> RewriteRule (.*) $1 [env=development:1] </pre> <p></code></p> <p>for the development environment vhost. But what if it will be something like this?</p> <pre> <code> RewriteRule (.*) $1 [env=development:1,env=mysql_host:localhost,env=mysql_port:3306,env=mysql_user:root,env=mysql_pass:,env=mysql_db:mydbname] </pre> <p></code></p> <p>Would it make sense or will cause some problems? What do you think?</p>
[ { "answer_id": 384187, "author": "ejunker", "author_id": 796, "author_profile": "https://Stackoverflow.com/users/796", "pm_score": 0, "selected": false, "text": "php_value ENV \"development\"\n $_SERVER" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45652/" ]
366,375
<p>Can someone explain to or link to an article that explains how the parameters passed into the action of a controller are populated? I understand the basic mapping when you have the Controller/Action/ID and the ID is passed in as a variable, if it doesn't convert to the type that you are asking for then it won't be passed in to that action.</p> <p>However I have been looking at the MVCContrib sub controller code and there was the following example:</p> <pre><code>public ActionResult Index(FirstLevelSubController firstLevel) </code></pre> <p>I want to know how this parameter is being populated because as far as I know nothing is being passed in to populate this?</p> <p>Let's say I created the following action which is the only action in the controller:</p> <pre><code>[AcceptVerbs(HttpVerbs.Get)] public ActionResult Index(Task task, ToDoList list) </code></pre> <p>What would I be passed back and why? (I know I could do a quick test to find out if they did come back but that would make me non the wiser as to why.</p> <p>Thanks</p>
[ { "answer_id": 366695, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 2, "selected": false, "text": "http://localhost/Task/Index/?task=mytask&todolist=a,b,c,d\n public ActionResult Index(int id, FormCollection form)\n{\n\n}\n form[\"name\"] = \"bob\"\nform[\"city\"] = \"LA\"\nform[\"state\"] = \"CA\"\nform[\"zip\"] = \"90210\"\n public class User\n{\n string string Name {get; set;}\n string string City {get; set;}\n string string State {get; set;}\n string string Zip {get; set;}\n}\n public ActionResult Index(int id, User user)\n user.Name = form[\"name\"]\nuser.City = form[\"city\"]\nuser.State = form[\"state\"]\nuser.Zip = int.Parse(form[\"zip\"])\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26081/" ]
366,379
<p>I want to show first element that is hidden by jquery. my html code is:</p> <pre><code>&lt;ol&gt; &lt;li&gt;1&lt;/li&gt; &lt;li style="display:none"&gt;2&lt;/li&gt; &lt;li style="display:none"&gt;3&lt;/li&gt; &lt;li style="display:none"&gt;4&lt;/li&gt; &lt;li style="display:none"&gt;5&lt;/li&gt; &lt;li&gt;&lt;a class="add"&gt;Add More ...&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>I want to show first hidden LI, each time that "a" element was clicked. My solution is below. but I think better way exists.</p> <pre><code>$("a.add").click(function(){ var hiddens=$(":hidden",$(this).parent().parent()); if (hiddens.length&gt;0) { hiddens.each(function(index,el){ if(index==0) { $(this).slideToggle("fast"); } }); } if (hiddens.length==1) { $(this).parent().hide(); } </code></pre> <p>Tanx</p>
[ { "answer_id": 366395, "author": "user38526", "author_id": 38526, "author_profile": "https://Stackoverflow.com/users/38526", "pm_score": 2, "selected": false, "text": "$(\"a.add\").click(function(){\n $(\":hidden:first\").show();\n});\n" }, { "answer_id": 366400, "author": "æther", "author_id": 39899, "author_profile": "https://Stackoverflow.com/users/39899", "pm_score": 5, "selected": true, "text": "$(\"a.add\").click(function(){\n $(\":hidden:first\").slideToggle(\"fast\");\n});\n" }, { "answer_id": 367810, "author": "Ata", "author_id": 46110, "author_profile": "https://Stackoverflow.com/users/46110", "pm_score": 0, "selected": false, "text": "$(\":hidden:eq(0)\",$(this).parent().parent())\n $(\":hidden:lt(1)\",$(this).parent().parent())\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46110/" ]
366,380
<p>I write this tiny C++ example in Eclipse 3.4.1 (CDT 5.0.1):</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;boost/foreach.hpp&gt; int foo() { std::vector&lt;int&gt; numbers; BOOST_FOREACH(int n, numbers) { std::cout &lt;&lt; n &lt;&lt; std::endl; } std::cout &lt;&lt; numbers.size &lt;&lt; std::endl; } </code></pre> <p>Then I hit Shift+Ctrl+F to format my code, and it becomes:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;boost/foreach.hpp&gt; int foo() { std::vector&lt;int&gt; numbers; BOOST_FOREACH(int n, numbers) { std::cout &lt;&lt; n &lt;&lt; std::endl; } std::cout &lt;&lt; numbers.size &lt;&lt; std::endl; } </code></pre> <p>This is with the BSD/Allman Code Style. Other styles obviously vary the look of the formatted code, but none give correct indentation.</p> <p>When I use the format feature on a larger piece of code, subsequent functions or methods are also affected by too little indentation, making the formatting help pretty unhelpful.</p> <p>Is there something I can do to make the indentation work properly with BOOST_FOREACH?</p>
[ { "answer_id": 9135228, "author": "Pescuma", "author_id": 802685, "author_profile": "https://Stackoverflow.com/users/802685", "pm_score": 2, "selected": false, "text": "#ifdef __CDT_PARSER__\n #undef BOOST_FOREACH\n #define BOOST_FOREACH(a, b) for(a; ; )\n#endif\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444/" ]
366,422
<p>Sometimes it seems natural to have a default parameter which is an empty list. Yet <a href="https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument">Python produces unexpected behavior in these situations</a>.</p> <p>If for example, I have a function:</p> <pre><code>def my_func(working_list=[]): working_list.append(&quot;a&quot;) print(working_list) </code></pre> <p>The first time it is called, the default will work, but calls after that will update the existing list (with one <code>&quot;a&quot;</code> each call) and print the updated version.</p> <p>So, what is the Pythonic way to get the behavior I desire (a fresh list on each call)?</p>
[ { "answer_id": 366430, "author": "HenryR", "author_id": 2827, "author_profile": "https://Stackoverflow.com/users/2827", "pm_score": 9, "selected": true, "text": "def my_func(working_list=None):\n if working_list is None: \n working_list = []\n\n # alternative:\n # working_list = [] if working_list is None else working_list\n\n working_list.append(\"a\")\n print(working_list)\n None" }, { "answer_id": 366446, "author": "bendin", "author_id": 33412, "author_profile": "https://Stackoverflow.com/users/33412", "pm_score": 4, "selected": false, "text": "if working_list is None: working_list = []\n working_list = working_list or []\n" }, { "answer_id": 367774, "author": "Mapad", "author_id": 28165, "author_profile": "https://Stackoverflow.com/users/28165", "pm_score": 2, "selected": false, "text": "*args **kargs myFunc([1, 2, 3]) def myFunc(arg1, *args):\n print args\n w = []\n w += args\n print w\n>>>myFunc(1, 2, 3, 4, 5, 6, 7)\n(2, 3, 4, 5, 6, 7)\n[2, 3, 4, 5, 6, 7]\n def myFunc(arg1, **kargs):\n print kargs\n>>>myFunc(1, option1=2, option2=3)\n{'option2' : 2, 'option1' : 3}\n" }, { "answer_id": 2021717, "author": "Beni Cherniavsky-Paskin", "author_id": 239657, "author_profile": "https://Stackoverflow.com/users/239657", "pm_score": 4, "selected": false, "text": "working_list def myFunc(starting_list = []):\n starting_list = list(starting_list)\n starting_list.append(\"a\")\n print starting_list\n print starting_list + [\"a\"] result_list.extend(myFunc()) def depth_first_walk_graph(graph, node, _visited=None):\n if _visited is None:\n _visited = set() # create memo once in top-level call\n\n if node in _visited:\n return\n _visited.add(node)\n for neighbour in graph[node]:\n depth_first_walk_graph(graph, neighbour, _visited)\n" }, { "answer_id": 45503780, "author": "drssdinblck", "author_id": 5646040, "author_profile": "https://Stackoverflow.com/users/5646040", "pm_score": 0, "selected": false, "text": "class Node(object):\n def __init__(self, _id, val, parents=None, children=None):\n self.id = _id\n self.val = val\n self.parents = parents if parents is not None else []\n self.children = children if children is not None else []\n def myFunc(working_list=None):\n working_list = [] if working_list is None else working_list\n working_list.append(\"a\")\n print working_list\n" }, { "answer_id": 56823024, "author": "Peter Chen", "author_id": 10336411, "author_profile": "https://Stackoverflow.com/users/10336411", "pm_score": -1, "selected": false, "text": "Python for programmer" }, { "answer_id": 63923760, "author": "Norman", "author_id": 5020325, "author_profile": "https://Stackoverflow.com/users/5020325", "pm_score": 1, "selected": false, "text": "def whats_on_the_telly(penguin=None):\n if penguin is None:\n penguin = []\n penguin.append(\"property of the zoo\")\n return penguin\n" }, { "answer_id": 63969205, "author": "24b4Jeff", "author_id": 5082664, "author_profile": "https://Stackoverflow.com/users/5082664", "pm_score": 1, "selected": false, "text": " def my_funct(params, lst = []):\n liste = lst.copy()\n . . \n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2242/" ]
366,432
<p>I need to use lists for my program and needed to decide if I use std::vector or std::list. The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.</p> <p>My code looks like this:</p> <pre><code>#include &lt;list&gt; template &lt;class T &gt; class myList : public std::list&lt;T&gt; { public: T operator[](int index); T operator[](int &amp; index); myList(void); ~myList(void); }; #include "myList.h" template&lt;class T&gt; myList&lt;T&gt;::myList(void): std::list&lt;T&gt;() {} template&lt;class T&gt; myList&lt;T&gt;::~myList(void) { std::list&lt;T&gt;::~list(); } template&lt;class T&gt; T myList&lt;T&gt;::operator[](int index) { int count = 0; std::list&lt;T&gt;::iterator itr = this-&gt;begin(); while(count != index)itr++; return *itr; } template&lt;class T&gt; T myList&lt;T&gt;::operator[](int &amp; index) { int count = 0; std::list&lt;T&gt;::iterator itr = this-&gt;begin(); while(count != index)itr++; return *itr; } </code></pre> <p>I can compile it but I get a linker error if I try to use it. Any ideas?</p>
[ { "answer_id": 366465, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 4, "selected": false, "text": "std::list std::vector std::remove v std::vector<T> value #include <vector>\n#include <algorithm>\nT value = ...; // whatever\nv.erase(std::remove(v.begin(), v.end(), value), v.end());\n" }, { "answer_id": 366605, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 3, "selected": false, "text": "std::string" }, { "answer_id": 366710, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": false, "text": "std::vector std::deque" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450/" ]
366,485
<p>I am very interested in streaming data for web-applications. I have tried out some javascript libraries, but the hacks and browser-incompatibilities drive me crazy ! HTML5 will hopefully standardize streaming data, but until then, hopefully I can resort to Flash to make this work in all browsers. Unfortunately, I'm not very familiar with all the functionality that Flash offers.</p> <p>I have tried loadVariables.onData in Flash 8, but it doesn't support streaming data. The data is only available after the request has been finished. Is there any way to call a function every time new data is returned ?</p>
[ { "answer_id": 373690, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 0, "selected": false, "text": "URLStream XMLSocket Socket" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6388/" ]
366,507
<p>A lot of times in code on the internet or code from my co-workers I see them creating an Object with just one method which only gets used once in the whole application. Like this:</p> <pre><code> class iOnlyHaveOneMethod{ public function theOneMethod(){ //loads and loads of code, say 100's of lines // but it only gets used once in the whole application } } if($foo){ $bar = new iOnlyHaveOneMEthod; $bar-&gt;theOneMethod(); } </code></pre> <p>Is that really better then:</p> <pre><code>if($foo){ //loads and loads of code which only gets used here and nowhere else } </code></pre> <p>?<br> For readability it makes sense to move the loads and loads of code away, but shouldn't it just be in a function?</p> <pre><code>function loadsAndLoadsOfCode(){ //Loads and loads of code } if($foo){ loadsAndLoadsOfCode(); } </code></pre> <p>Is moving the code to a new object really better then just creating a function or putting the code in there directly?<br> To me the function part makes more sense and seems more readible then creating an object which hardly is of any use since it just holds one method.</p>
[ { "answer_id": 366546, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 2, "selected": false, "text": "// let's instead assume that $bar was set earlier using a setter\nif($foo){ \n $bar = getMyBar();\n $bar->theOneMethod();\n}\n $bar theOneMethod() $bar->theOneMethod() $bar" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35197/" ]
366,533
<p>How to run the first process from a list of processes stored in a file and immediately delete the first line as if the file was a queue and I called "pop"?</p> <p>I'd like to call the first command listed in a simple text file with \n as the separator in a pop-like fashion:</p> <p><em>Figure 1:</em></p> <pre><code>cmdqueue.lst : proc_C1 proc_C2 proc_C3 . . </code></pre> <p><em>Figure 2:</em></p> <p>Pop the first command via <code>popcmd</code>:</p> <pre><code>proc_A | proc_B | popcmd cmdqueue.lst | proc_D </code></pre> <p><em>Figure 3:</em></p> <pre><code>cmdqueue.lst : proc_C2 proc_C3 proc_C4 . . </code></pre>
[ { "answer_id": 366553, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": true, "text": "#!/usr/bin/env python\nimport os, shlex, sys\nfrom subprocess import call\nfilename = sys.argv[1]\nlines = open(filename).readlines()\nif lines:\n command = lines[0].rstrip()\n open(filename, \"w\").writelines(lines[1:])\n if command:\n sys.exit(call(shlex.split(command) + sys.argv[2:]))\n proc_A | proc_B | python pop-cmd.py cmdstack.lst | proc_D\n" }, { "answer_id": 366604, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 3, "selected": false, "text": "proc_A | proc_B | `(head -1 cmdstack.lst; sed -i -e '1d' cmdstack.lst)` | proc_D\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4085/" ]
366,541
<p>I want to serialize a Dictionary that has a custom <code>IEqualityComparer</code>.</p> <p>I've tried using <code>DataContractSerializer</code> but I can't get the <code>Comparer</code> to be serialized.</p> <p>I can't use <code>BinaryFormatter</code> because of <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=303278&amp;wa=wsignin1.0" rel="nofollow noreferrer">this</a>.</p> <p>I can always do something like:</p> <pre><code>var myDictionary = new MyDictionary(deserializedDictionary, myComparer); </code></pre> <p>But that means I'd need twice the memory the dictionary uses.</p>
[ { "answer_id": 366553, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": true, "text": "#!/usr/bin/env python\nimport os, shlex, sys\nfrom subprocess import call\nfilename = sys.argv[1]\nlines = open(filename).readlines()\nif lines:\n command = lines[0].rstrip()\n open(filename, \"w\").writelines(lines[1:])\n if command:\n sys.exit(call(shlex.split(command) + sys.argv[2:]))\n proc_A | proc_B | python pop-cmd.py cmdstack.lst | proc_D\n" }, { "answer_id": 366604, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 3, "selected": false, "text": "proc_A | proc_B | `(head -1 cmdstack.lst; sed -i -e '1d' cmdstack.lst)` | proc_D\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19956/" ]
366,550
<p>I am currently reading "Beginning CakePHP:From Novice to Professional" by David Golding. At one point I have to use the CLI-command "cake bake", I get the welcome-screen but when I try to bake e.g. a Controller I get the following error messages:</p> <pre><code>Warning: mysql_connect(): Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2) in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 117 Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 122 Warning: mysql_get_server_info(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 130 Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 154 Error: Your database does not have any tables. </code></pre> <p>I suspect that the error-messages has to do with php trying to access the wrong mysql-socket, namely the default osx mysql-socket - instead of the one that MAMP uses. Hence I change my database configurations to connect to the UNIX mysql-socket (:/Applications/MAMP/tmp/mysql/mysql.sock):</p> <pre><code>class DATABASE_CONFIG { var $default = array( 'driver' =&gt; 'mysql', 'connect' =&gt; 'mysql_connect', 'persistent' =&gt; false, 'host' =&gt;':/Applications/MAMP/tmp/mysql/mysql.sock', // UNIX MySQL-socket 'login' =&gt; 'my_user', 'password' =&gt; 'my_pass', 'database' =&gt; 'blog', 'prefix' =&gt; '', ); } </code></pre> <p>But I get the same error-messages with the new socket:</p> <pre><code>Warning: mysql_connect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock:3306' (2) in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 117 Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 122 Warning: mysql_get_server_info(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 130 Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /Applications/MAMP/htdocs/blog/cake/libs/model/datasources/dbo/dbo_mysql.php on line 154 Error: Your database does not have any tables. </code></pre> <p>Also, even though I use the UNIX-socket that MAMP show on it's welcome-screen, CakePHP loses the database-connection, when using this socket instead of localhost.</p> <p>Any ideas on how I can get bake to work?</p> <p><strong>-- Edit 1 --</strong></p> <p>Thank you guys for helping me out! :)</p> <p>I have a problem figuring out where in my.cnf to edit to get MySQL to listen to TCP/IP request. The only paragraph I can find where TCP/IP is mentioned is the following: </p> <pre><code># Don't listen on a TCP/IP port at all. This can be a security enhancement, # if all processes that need to connect to mysqld run on the same host. # All interaction with mysqld must be made via Unix sockets or named pipes. # Note that using this option without enabling named pipes on Windows # (via the "enable-named-pipe" option) will render mysqld useless! # #skip-networking </code></pre> <p>That allows me to turn off TCP/IP completely, which is the opposite of my intention. I don't know how to go about what you suggest, if you could be more elaborate it would be great. I am a total n00b on these matters :S</p> <p>Reg. connecting to a local socket: I removed the leading colon in the host-parameter, same result.</p>
[ { "answer_id": 373504, "author": "user42801", "author_id": 42801, "author_profile": "https://Stackoverflow.com/users/42801", "pm_score": 1, "selected": false, "text": "my-macbook:~ chris$ php -i | grep mysql.default_socket\nmysql.default_socket => no value => no value\nmy-macbook:~ chris$ php -i -c /Applications/MAMP/conf/php5 | grep mysql.default_socket\nmysql.default_socket => /Applications/MAMP/tmp/mysql/mysql.sock => /Applications/MAMP/tmp/mysql/mysql.sock\n" }, { "answer_id": 407544, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " class DATABASE_CONFIG\n{\n public $default = array(\n 'driver' => 'mysql',\n 'persistent' => false,\n 'host' => 'localhost',\n 'login' => 'account',\n 'password' => 'password',\n 'database' => 'database',\n 'prefix' => '',\n 'port' => '/var/mysql/mysql.sock'\n );\n}\n" }, { "answer_id": 617697, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "class DATABASE_CONFIG\n{\n public $default = array(\n 'driver' => 'mysql',\n 'persistent' => false,\n 'host' => 'localhost',\n 'login' => 'account',\n 'password' => 'password',\n 'database' => 'database',\n 'prefix' => '',\n 'port' => '/Applications/MAMP/tmp/mysql/mysql.sock'\n );\n}\n" }, { "answer_id": 642979, "author": "jimiyash", "author_id": 458496, "author_profile": "https://Stackoverflow.com/users/458496", "pm_score": 1, "selected": false, "text": "sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock\n" }, { "answer_id": 1318934, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "class DATABASE_CONFIG {\n\nvar $default = array(\n 'driver' => 'mysql',\n 'persistent' => false,\n 'host' => 'localhost',\n 'port' => '/Applications/MAMP/tmp/mysql/mysql.sock', // here is the key !\n 'login' => 'you',\n 'password' => 'yourpass',\n 'database' => 'yourdb',\n 'prefix' => '',\n\n);\n" }, { "answer_id": 8614575, "author": "Jeroen den Haan", "author_id": 1113195, "author_profile": "https://Stackoverflow.com/users/1113195", "pm_score": 3, "selected": false, "text": "<?php\nclass DATABASE_CONFIG {\n\n public $default = array(\n 'datasource' => 'Database/Mysql',\n 'driver' => 'mysql',\n 'persistent' => false,\n 'host' => 'localhost',\n 'unix_socket' => '/tmp/mysql.sock',\n 'login' => 'xxx',\n 'password' => 'xxx',\n 'database' => 'xxx',\n 'encoding' => 'UTF8',\n 'prefix' => ''\n );\n\n}\n" }, { "answer_id": 8994662, "author": "Andre Sugai", "author_id": 1168039, "author_profile": "https://Stackoverflow.com/users/1168039", "pm_score": 1, "selected": false, "text": "host localhost:8889" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24218/" ]
366,586
<p>I use codeigniter as my main install on the main domain. I have created a subdomain and a folder called live e.g. live.domain.com maps to public/live . However in public I use codeigniter.</p> <p>I now have the dynamic codeigniter url: </p> <pre>http://domain.com/api/</pre> <p>which I want to map to my subdomain: </p> <pre>https://live.domain.com</pre> <p>So going to:</p> <pre>https://live.domain.com/api/functioname</pre> <p>would be using the script: </p> <pre>http://domain.com/api/apifunctioname</pre> <p>and possibly:</p> <pre>http://domain.com/api/apifunctioname/parameter1/parameter</pre> <p>Everything is on the same server so no redirects are needed.</p> <p>Anyone have any ideas on which rewrite rules to use?</p> <pre><code>Options +FollowSymLinks RewriteEngine On RewriteCond %{HTTP_HOST} ^live\.domain\.com [NC] RewriteRule (.+)$ "http://domain.com/api/$1" [L] </code></pre> <p>The above works great as a rewrite but redirects to <a href="http://domain.com/api/functionname" rel="noreferrer">http://domain.com/api/functionname</a> instead I want it to route; so that when going to:</p> <pre>https://live.domain.com/api/functioname</pre> <p>It stays at that url but uses the script of </p> <pre>http://domain.com/api/functionname</pre> <p>Thank you very much,</p> <p>Ice</p>
[ { "answer_id": 5423470, "author": "Muhammad Hamizi Jaminan", "author_id": 1045240, "author_profile": "https://Stackoverflow.com/users/1045240", "pm_score": 2, "selected": false, "text": "RewriteEngine On\nRewriteCond %{HTTP_HOST} ^live\\.domain\\.com$ [NC]\nRewriteRule (.+)$ \"https://domain.com/index.php/api/$1\" [L,P]\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,588
<p>I am a hobbyist programmer (started with VBA to make excel quicker) and have been working with VB.NET / C#.NET and am trying to learn ADO.NET.</p> <p>A facet of programming that has always frustrated me is what does 'good' look like? I am not a professional so have little to compare against. What makes a better programmer? Is it:</p> <ul> <li>They have a better understanding of all the objects / classes / methods in a given language?</li> <li>Their programs are more efficient?</li> <li>The design of their programs are much better in terms of better documentation, good choice of names for functions etc.?</li> </ul> <p>Put another way, if I were to look at the code of a professional programmer, what is the first thing that I would notice about their code relative to mine? For example, I read books like 'Professional ASP.NET' by Wrox press. Are the code examples in that book 'world class'? Is that the pinnacle? Would any top-gun programmer look at that code and think it was good code?</p>
[ { "answer_id": 367150, "author": "Filip Ekberg", "author_id": 39106, "author_profile": "https://Stackoverflow.com/users/39106", "pm_score": 1, "selected": false, "text": "Communication issues when adapting outsourcing" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235442/" ]
366,595
<p>I'm trying to use <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">Jeditable</a> as an inline editing solution.</p> <p>The default behavior (click on the element to edit it) works quite well, but I would like to activate an element by clicking on another element.</p> <p>For example clicking on a.activateEdit will activate the next div.edit (obviously should be done using jQuery selectors).</p> <p>I've looked into Jeditable docs for this, but couldn't find the right syntax</p> <p>FYI, the default Jeditable syntax is something along the lines of:</p> <pre><code> $(document).ready(function() { $('.edit').editable('http://www.example.com/save.php'); }); </code></pre> <p><strong>*Edit: found <a href="http://groups.google.com/group/jquery-en/browse_thread/thread/33c18dcf32276c89/7711363c7496fcb3?hide_quotes=no" rel="nofollow noreferrer">a better solution</a> *</strong></p>
[ { "answer_id": 366704, "author": "Ata", "author_id": 46110, "author_profile": "https://Stackoverflow.com/users/46110", "pm_score": 2, "selected": false, "text": "<a class=\"clickme\">Click me to edit</a>\n<div class=\"edit\">Edit Me!</div>\n $(document).ready(function() {\n$(\"a.clickme\").click(function(){\n $('.edit').editable('http://www.example.com/save.php');\n});\n});\n" }, { "answer_id": 367054, "author": "yoavf", "author_id": 1011, "author_profile": "https://Stackoverflow.com/users/1011", "pm_score": 2, "selected": false, "text": "$(document).ready(function() {\n $('.edit').editable('http://www.example.com/save.php');\n $(\"a.clickme\").click(function(){\n $('.edit').click();\n });\n});\n" }, { "answer_id": 1108917, "author": "Mika Tuupola", "author_id": 24433, "author_profile": "https://Stackoverflow.com/users/24433", "pm_score": 6, "selected": true, "text": "<div class=\"edit\" id=\"unique_id\">Editable text</div> \n<a href=\"#\" class=\"edit_trigger\">Edit me!!</a>\n /* Bind Jeditable instances to \"edit\" event. */\n$(\".edit\").editable(\"http://www.example.com/save.php\", {\n event : \"edit\"\n});\n/* Find and trigger \"edit\" event on correct Jeditable instance. */\n$(\".edit_trigger\").bind(\"click\", function() {\n $(this).prev().trigger(\"edit\");\n}); \n" }, { "answer_id": 1685890, "author": "David", "author_id": 204559, "author_profile": "https://Stackoverflow.com/users/204559", "pm_score": 1, "selected": false, "text": "\n/* Find and trigger \"edit\" event on next Jeditable instance. */\n $(\".edit_trigger\").livequery( 'click', function() {\n $(this).next().click();\n });\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1011/" ]
366,601
<p>I'm having issues getting Firefox to update a webpage when its class is changed dynamically.</p> <p>I'm using an HTML <code>table</code> element. When the user clicks a cell in the table header, my script toggles the class back and forth between <code>sorted_asc</code> and <code>sorted_des</code>. I have pseudo element which adds an arrow glyph (pointing up or down) depending on which class the cell currently is.</p> <pre><code>.thead .tr .sorted_asc .cell:after { content: ' \25B2'; } </code></pre> <p>The problem is, that when you click the cell header a second time, the page doesn't update the arrow... until the user mouses away from the element. I think it's a bug as it works fine in Safari, and as I don't see any <code>:hover</code> tags in my CSS or other entries that might interfere.</p> <p>Anyone seen this before, or know how to work around the issue?</p>
[ { "answer_id": 366646, "author": "I.devries", "author_id": 6388, "author_profile": "https://Stackoverflow.com/users/6388", "pm_score": 3, "selected": true, "text": "document.body.style.display = 'none';\ndocument.body.style.display = 'block';\n" }, { "answer_id": 366954, "author": "msingleton", "author_id": 46184, "author_profile": "https://Stackoverflow.com/users/46184", "pm_score": 0, "selected": false, "text": ".thead .tr .sorted_asc .sorted_asc {\n background: url(images/down_arrow.png) no-repeat right;\n}\n\n.thead .tr .sorted_asc .sorted_des {\n background: url(images/up_arrow.png) no-repeat right;\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4939/" ]
366,602
<p>In my C++ program (on Windows), I'm allocating a block of memory and can make sure it stays locked (unswapped and contiguous) in physical memory (i.e. using VirtualAllocEx(), MapUserPhysicalPages() etc). </p> <p>In the context of my process, I can get the VIRTUAL memory address of that block, <b> but I need to find out the PHYSICAL memory address of it </b> in order to pass it to some external device. </p> <p><br> <b>1.</b> Is there any way I can translate the virtual address to the physical one within my program, in USER mode? <br> <br><b>2.</b> If not, I can find out this virtual to physical mapping only in KERNEL mode. I guess it means I have to write a driver to do it...? Do you know of any readily available driver/DLL/API which I can use, that my application (program) will interface with to do the translation? <br><br> <b>3.</b> In case I'll have to write the driver myself, how do I do this translation? which functions do I use? Is it <b>mmGetPhysicalAddress()</b>? How do I use it? <br><br><b>4.</b> Also, if I understand correctly, mmGetPhysicalAddress() returns the physical address of a virtual base address that is in the context of the calling process. But if the calling process is the driver, and I'm using my application to call the driver for that function, I'm changing contexts and I am no longer in the context of the app when the mmGetPhysicalAddress routine is called... so how do I translate the virtual address in the application (user-mode) memory space, not the driver?</p> <p>Any answers, tips and code excerpts will be much appreciated!!</p> <p>Thanks</p>
[ { "answer_id": 366725, "author": "Christopher", "author_id": 3186, "author_profile": "https://Stackoverflow.com/users/3186", "pm_score": 3, "selected": false, "text": "MmGetPhysicalAddress MmProbeAndLockPages PVOID p = ExAllocatePoolWithTag( NonPagedPool, POOL_TAG );\nPHYSICAL_ADDRESS realAddr = MmGetPhysicalAddress( p );\n\n// use realAddr\n" }, { "answer_id": 366858, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 4, "selected": false, "text": "MapUserPhysicalPages DeviceIoControl METHOD_IN_DIRECT METHOD_OUT_DIRECT" }, { "answer_id": 5358446, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 3, "selected": false, "text": "1: kd> .formats 0xf9a10054\nBinary: 11111001 10100001 00000000 01010100\n\nPage Directory Pointer Index(PDPI) 11 Index into\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,603
<p>Having a table with a column like: <code>mydate DATETIME</code> ...</p> <p>I have a query such as:</p> <pre><code>SELECT SUM(foo), mydate FROM a_table GROUP BY a_table.mydate; </code></pre> <p>This will group by the full <code>datetime</code>, including hours and minutes. I wish to make the group by, only by the date <code>YYYY/MM/DD</code> not by the <code>YYYY/MM/DD/HH/mm</code>.</p> <p>How to do this?</p>
[ { "answer_id": 366610, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 9, "selected": true, "text": "SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);\n SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;\n" }, { "answer_id": 366645, "author": "moo", "author_id": 23107, "author_profile": "https://Stackoverflow.com/users/23107", "pm_score": 4, "selected": false, "text": "SELECT SUM(foo), DATE(mydate) mydate FROM a_table GROUP BY mydate;\n" }, { "answer_id": 6883887, "author": "RaK Chowdary", "author_id": 870766, "author_profile": "https://Stackoverflow.com/users/870766", "pm_score": 3, "selected": false, "text": "SELECT SUM(No), HOUR(dateofissue) \nFROM tablename \nWHERE dateofissue>='2011-07-30' \nGROUP BY HOUR(dateofissue)\n" }, { "answer_id": 9907010, "author": "Richard Merchant", "author_id": 965536, "author_profile": "https://Stackoverflow.com/users/965536", "pm_score": 5, "selected": false, "text": "SELECT date\nFROM blog \nGROUP BY DATE_FORMAT(date, \"%m-%y\")\nORDER BY YEAR(date) DESC, MONTH(date) DESC \n" }, { "answer_id": 69730237, "author": "Cristian Ariel Ab", "author_id": 8005138, "author_profile": "https://Stackoverflow.com/users/8005138", "pm_score": 0, "selected": false, "text": "select \n CONVERT(date, CONVERT(VARCHAR(10),sd.Date,112)) as Date, \n sd.CodId as CodId,\n p.Description ,\n sum(sd.Quantity)as Quantity,\n sum(sd.TotalQuantityXPriceWithIva) as TotalWithIva \nfrom \n SaleDetails sd \n join Sales s on sd.SaleId = s.SaleId \n join Products p on sd.ProductId = p.ProductId \nWhere \n (\n sd.Date >=' 1/1/2021 00:00:00' \n and sd.Date <= '26/10/2021 23:59:59' \n and p.BarCode = '7790628000034'\n and ((s.VoucherTypeId >= 16 and s.VoucherTypeId <= 18) \n or s.VoucherTypeId = 32 )) \ngroup by \n CONVERT(VARCHAR(10),sd.Date,112), \n sd.CodId , \n p.Description \norder by CONVERT(VARCHAR(10),sd.Date,112) desc\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
366,629
<p>This is the code I wrote:</p> <pre><code> MailMessage mail = new MailMessage("test@gmail.com", "me@myurl.com"); mail.Subject = "This is a test!!"; mail.Body = "testing..."; SmtpPermission connectAccess = new SmtpPermission(SmtpAccess.Connect); System.Console.WriteLine("Access? " + connectAccess.Access); SmtpClient client = new SmtpClient("mail.myurl.com", 2525); client.Send(mail); </code></pre> <p>It's not working. I get an exception at the line "client.Send(mail)" that says "Mailbox unavailable. The server response was (MYLOCALCOMPUTERNAME) [MY LOCAL IP]:3045 is currently not permitted to relay through."</p> <p>connectAccess.Access does return "Connect" (I'm not sure if this was necessary... I added it in to start the troubleshooting process.)</p> <p>Does this mean that my local machine has to be configured in some way? What about when I deploy my app to other peoples machines? Will there need to be local configuration there? I'm just looking to create a "Send Feedback" type of link from my application.</p> <p>(Note: in my real application I am using my real email addresses in both the "to" and "from" and my smtp is really my smtp address at the place that hosts my url/website)</p> <p>thanks!</p> <p>-Adeena</p>
[ { "answer_id": 366690, "author": "adeena", "author_id": 44004, "author_profile": "https://Stackoverflow.com/users/44004", "pm_score": 3, "selected": false, "text": " client.Credentials = new System.Net.NetworkCredential(\"myloginat+myurl.com\", \"mypassword\");\n" }, { "answer_id": 16939011, "author": "Shaik Raffi", "author_id": 2455399, "author_profile": "https://Stackoverflow.com/users/2455399", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Net;\nusing System.Net.Mail;\n\nnamespace SendMail\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n try\n {\n SmtpClient client = new SmtpClient(\"smtp.gmail.com\", 25);\n MailMessage msg = new MailMessage();\n\n NetworkCredential cred = new NetworkCredential(\"x@gmail.com\", \"password\");\n msg.From = new MailAddress(\"x@gmail.com\");\n msg.To.Add(\"y@gmail.com\");\n msg.Subject = \"A subject\";\n msg.Body = \"Hello,Raffi\";\n\n client.Credentials = cred;\n client.EnableSsl = true;\n label1.Text = \"Mail Sended Succesfully\";\n client.Send(msg);\n\n\n }\n catch\n {\n label1.Text = \"Error\";\n }\n }\n\n\n\n }\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44004/" ]
366,631
<p>I am working on a ASP.NET app and i have a need to post back to the server after a file is chosen in a FileUpload control without having to have the user explicitly click a 'submit' button. Is this possible? and if so, how?</p>
[ { "answer_id": 366644, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": true, "text": "change <!-- HTML code --->\n<input \n type=\"file\" \n onchange=\"if (confirm('Upload ' + this.value + '?')) this.form.submit();\"\n>\n" }, { "answer_id": 367138, "author": "Abram Simon", "author_id": 46204, "author_profile": "https://Stackoverflow.com/users/46204", "pm_score": 4, "selected": false, "text": "<asp:FileUpload ID=\"myFileUpload\" onchange=\"if (confirm('Upload ' + this.value + '?')) this.form.submit();\" runat=\"server\" />\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
366,658
<p>Does Java 6 consume more memory than you expect for largish applications?</p> <p>I have an application I have been developing for years, which has, until now taken about 30-40 MB in my particular test configuration; now with Java 6u10 and 11 it is taking several hundred while active. It bounces around a lot, anywhere between 50M and 200M, and when it idles, it <em>does</em> GC and drop the memory right down. In addition it generates millions of page faults. All of this is observed via Windows Task Manager.</p> <p>So, I ran it up under my profiler (jProfiler) and using jVisualVM, and both of them indicate the usual moderate heap and perm-gen usages of around 30M combined, even when fully active doing my load-test cycle.</p> <p>So I am mystified! And it not just requesting more memory from the Windows Virtual Memory pool - this is showing up as 200M "Mem Usage".</p> <p>CLARIFICATION: I want to be perfectly clear on this - observed over an 18 hour period with Java VisualVM the class heap and perm gen heap have been perfectly stable. The allocated volatile heap (eden and tenured) sits unmoved at 16MB (which it reaches in the first few minutes), and the use of this memory fluctuates in a perfect pattern of growing evenly from 8MB to 16MB, at which point GC kicks in an drops it back to 8MB. Over this 18 hour period, the system was under constant maximum load since I was running a stress test. This behavior is <em>perfectly</em> and <em>consistently</em> reproducible, seen over numerous runs. The only anomaly is that while this is going on the memory taken from Windows, observed via Task Manager, fluctuates all over the place from 64MB up to 900+MB.</p> <p>UPDATE 2008-12-18: I have run the program with -Xms16M -Xmx16M without any apparent adverse affect - performance is fine, total run time is about the same. But memory use in a short run still peaked at about 180M.</p> <p>Update 2009-01-21: It seems the answer may be in the number of threads - see my answer below.</p> <hr> <p>EDIT: And I mean millions of page faults literally - in the region of 30M+.</p> <p>EDIT: I have a 4G machine, so the 200M is not significant in that regard.</p>
[ { "answer_id": 367933, "author": "Michael Borgwardt", "author_id": 16883, "author_profile": "https://Stackoverflow.com/users/16883", "pm_score": 4, "selected": false, "text": "public class FreeTest\n{\n public static void main(String[] args) throws Exception\n {\n byte[][] blob = new byte[60][1024*1024];\n for(int i=0; i<blob.length; i++)\n {\n Thread.sleep(500);\n System.out.println(\"freeing block \"+i);\n blob[i] = null;\n System.gc();\n }\n }\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8946/" ]
366,682
<p>There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.</p>
[ { "answer_id": 366763, "author": "rik.the.vik", "author_id": 45570, "author_profile": "https://Stackoverflow.com/users/45570", "pm_score": 7, "selected": true, "text": "import signal\n\ndef signal_handler(signum, frame):\n raise Exception(\"Timed out!\")\n\nsignal.signal(signal.SIGALRM, signal_handler)\nsignal.alarm(10) # Ten seconds\ntry:\n long_function_call()\nexcept Exception, msg:\n print \"Timed out!\"\n" }, { "answer_id": 367490, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 0, "selected": false, "text": "def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):\n '''This function will spwan a thread and run the given function using the args, kwargs and \n return the given default value if the timeout_duration is exceeded \n ''' \n import threading\n class InterruptableThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.result = default\n def run(self):\n try:\n self.result = func(*args, **kwargs)\n except:\n self.result = default\n it = InterruptableThread()\n it.start()\n it.join(timeout_duration)\n if it.isAlive():\n return it.result\n else:\n return it.result \n" }, { "answer_id": 601168, "author": "Josh Lee", "author_id": 19750, "author_profile": "https://Stackoverflow.com/users/19750", "pm_score": 7, "selected": false, "text": "with import signal\nfrom contextlib import contextmanager\n\nclass TimeoutException(Exception): pass\n\n@contextmanager\ndef time_limit(seconds):\n def signal_handler(signum, frame):\n raise TimeoutException(\"Timed out!\")\n signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(seconds)\n try:\n yield\n finally:\n signal.alarm(0)\n\n\ntry:\n with time_limit(10):\n long_function_call()\nexcept TimeoutException as e:\n print(\"Timed out!\")\n" }, { "answer_id": 1114567, "author": "Glenn Maynard", "author_id": 136829, "author_profile": "https://Stackoverflow.com/users/136829", "pm_score": 3, "selected": false, "text": "def function_with_enforced_timeout():\n f = open_temporary_file()\n try:\n ...\n finally:\n here()\n unlink(f.filename)\n" }, { "answer_id": 26664130, "author": "Ariel Cabib", "author_id": 1994542, "author_profile": "https://Stackoverflow.com/users/1994542", "pm_score": 5, "selected": false, "text": "from multiprocessing import Process\nfrom time import sleep\n\ndef f(time):\n sleep(time)\n\n\ndef run_with_limited_time(func, args, kwargs, time):\n \"\"\"Runs a function with time limit\n\n :param func: The function to run\n :param args: The functions args, given as tuple\n :param kwargs: The functions keywords, given as dict\n :param time: The time limit in seconds\n :return: True if the function ended successfully. False if it was terminated.\n \"\"\"\n p = Process(target=func, args=args, kwargs=kwargs)\n p.start()\n p.join(time)\n if p.is_alive():\n p.terminate()\n return False\n\n return True\n\n\nif __name__ == '__main__':\n print run_with_limited_time(f, (1.5, ), {}, 2.5) # True\n print run_with_limited_time(f, (3.5, ), {}, 2.5) # False\n" }, { "answer_id": 35038906, "author": "Seba", "author_id": 1827660, "author_profile": "https://Stackoverflow.com/users/1827660", "pm_score": 2, "selected": false, "text": "import time\nfrom timeout import timeout\n\nclass Test(object):\n @timeout(2)\n def test_a(self, foo, bar):\n print foo\n time.sleep(1)\n print bar\n return 'A Done'\n\n @timeout(2)\n def test_b(self, foo, bar):\n print foo\n time.sleep(3)\n print bar\n return 'B Done'\n\nt = Test()\nprint t.test_a('python', 'rocks')\nprint t.test_b('timing', 'out')\n timeout.py import threading\n\nclass TimeoutError(Exception):\n pass\n\nclass InterruptableThread(threading.Thread):\n def __init__(self, func, *args, **kwargs):\n threading.Thread.__init__(self)\n self._func = func\n self._args = args\n self._kwargs = kwargs\n self._result = None\n\n def run(self):\n self._result = self._func(*self._args, **self._kwargs)\n\n @property\n def result(self):\n return self._result\n\n\nclass timeout(object):\n def __init__(self, sec):\n self._sec = sec\n\n def __call__(self, f):\n def wrapped_f(*args, **kwargs):\n it = InterruptableThread(f, *args, **kwargs)\n it.start()\n it.join(self._sec)\n if not it.is_alive():\n return it.result\n raise TimeoutError('execution expired')\n return wrapped_f\n python\nrocks\nA Done\ntiming\nTraceback (most recent call last):\n ...\ntimeout.TimeoutError: execution expired\nout\n TimeoutError" }, { "answer_id": 37648512, "author": "user2283347", "author_id": 2283347, "author_profile": "https://Stackoverflow.com/users/2283347", "pm_score": 4, "selected": false, "text": "with time_limit SIGALARM Timer from contextlib import contextmanager\nimport threading\nimport _thread\n\nclass TimeoutException(Exception):\n def __init__(self, msg=''):\n self.msg = msg\n\n@contextmanager\ndef time_limit(seconds, msg=''):\n timer = threading.Timer(seconds, lambda: _thread.interrupt_main())\n timer.start()\n try:\n yield\n except KeyboardInterrupt:\n raise TimeoutException(\"Timed out for operation {}\".format(msg))\n finally:\n # if the action ends in specified time, timer is canceled\n timer.cancel()\n\nimport time\n# ends after 5 seconds\nwith time_limit(5, 'sleep'):\n for i in range(10):\n time.sleep(1)\n\n# this will actually end after 10 seconds\nwith time_limit(5, 'sleep'):\n time.sleep(10)\n _thread.interrupt_main KeyboardInterrupt Timer time.sleep() KeyboardInterrupt sleep" }, { "answer_id": 63855138, "author": "Frank", "author_id": 2324547, "author_profile": "https://Stackoverflow.com/users/2324547", "pm_score": 0, "selected": false, "text": "from contextlib import contextmanager\nimport threading\nimport _thread\n\nclass TimeoutException(Exception): pass\n\n@contextmanager\ndef time_limit(seconds):\n timer = threading.Timer(seconds, lambda: _thread.interrupt_main())\n timer.start()\n try:\n yield\n except KeyboardInterrupt:\n pass \n finally:\n # if the action ends in specified time, timer is canceled\n timer.cancel()\n\ndef timeout_svm_score(i):\n #from sklearn import svm\n #import numpy as np\n #from IPython.core.display import display\n #%store -r names X Y\n clf = svm.SVC(kernel='linear', C=1).fit(np.nan_to_num(X[[names[i]]]), Y)\n score = clf.score(np.nan_to_num(X[[names[i]]]),Y)\n #scoressvm.append((score, names[i]))\n display((score, names[i])) \n \n%%time\nwith time_limit(5):\n i=0\n timeout_svm_score(i)\n#Wall time: 14.2 s\n\n%%time\nwith time_limit(20):\n i=0\n timeout_svm_score(i)\n#(0.04541284403669725, '计划飞行时间')\n#Wall time: 16.1 s\n\n%%time\nwith time_limit(5):\n i=14\n timeout_svm_score(i)\n#Wall time: 5h 43min 41s\n" }, { "answer_id": 66143888, "author": "erickfis", "author_id": 6622571, "author_profile": "https://Stackoverflow.com/users/6622571", "pm_score": 4, "selected": false, "text": "import time\nimport func_timeout\n\n\ndef my_function(n):\n \"\"\"Sleep for n seconds and return n squared.\"\"\"\n print(f'Processing {n}')\n time.sleep(n)\n return n**2\n\n\ndef main_controller(max_wait_time, all_data):\n \"\"\"\n Feed my_function with a list of itens to process (all_data).\n\n However, if max_wait_time is exceeded, return the item and a fail info.\n \"\"\"\n res = []\n for data in all_data:\n try:\n my_square = func_timeout.func_timeout(\n max_wait_time, my_function, args=[data]\n )\n res.append((my_square, 'processed'))\n except func_timeout.FunctionTimedOut:\n print('error')\n res.append((data, 'fail'))\n continue\n\n return res\n\n\ntimeout_time = 2.1 # my time limit\nall_data = range(1, 10) # the data to be processed\n\nres = main_controller(timeout_time, all_data)\nprint(res)\n" }, { "answer_id": 71959502, "author": "Ali Sajjad", "author_id": 12065150, "author_profile": "https://Stackoverflow.com/users/12065150", "pm_score": 1, "selected": false, "text": "def function_timeout(seconds: int):\n \"\"\"Wrapper of Decorator to pass arguments\"\"\"\n\n def decorator(func):\n @contextmanager\n def time_limit(seconds_):\n def signal_handler(signum, frame): # noqa\n raise TimeoutException(f\"Timed out in {seconds_} seconds!\")\n\n signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(seconds_)\n try:\n yield\n finally:\n signal.alarm(0)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n with time_limit(seconds):\n return func(*args, **kwargs)\n\n return wrapper\n\n return decorator\n @function_timeout(seconds=5)\ndef my_naughty_function():\n while True:\n print(\"Try to stop me ;-p\")\n" }, { "answer_id": 72112902, "author": "Rafael Marques", "author_id": 8132960, "author_profile": "https://Stackoverflow.com/users/8132960", "pm_score": 0, "selected": false, "text": "from multiprocessing import Process, Lock\nimport time\nimport os\n\ndef f(lock,id,sleepTime):\n lock.acquire()\n print(\"I'm P\"+str(id)+\" Process ID: \"+str(os.getpid()))\n lock.release()\n time.sleep(sleepTime) #sleeps for some time\n print(\"Process: \"+str(id)+\" took this much time:\"+str(sleepTime))\n time.sleep(sleepTime)\n print(\"Process: \"+str(id)+\" took this much time:\"+str(sleepTime*2))\n\nif __name__ == '__main__':\n timeout_function=float(9) # 9 seconds for max function time\n print(\"Main Process ID: \"+str(os.getpid()))\n lock=Lock()\n p1=Process(target=f, args=(lock,1,6,)) #Here you can change from 6 to 3 for instance, so you can watch the behavior\n start=time.time()\n print(type(start))\n p1.start()\n if p1.is_alive():\n print(\"process running a\")\n else:\n print(\"process not running a\")\n while p1.is_alive():\n timeout=time.time()\n if timeout-start > timeout_function:\n p1.terminate()\n print(\"process terminated\")\n print(\"watching, time passed: \"+str(timeout-start) )\n time.sleep(1)\n if p1.is_alive():\n print(\"process running b\")\n else:\n print(\"process not running b\")\n p1.join()\n if p1.is_alive():\n print(\"process running c\")\n else:\n print(\"process not running c\")\n end=time.time()\n print(\"I am the main process, the two processes are done\")\n print(\"Time taken:- \"+str(end-start)+\" secs\") #MainProcess terminates at approx ~ 5 secs.\n time.sleep(5) # To see if on Task Manager the child process is really being terminated, and it is\n print(\"finishing\")\n .terminate()" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925263/" ]
366,696
<p>Im trying to do a dialog box with jquery. In this dialog box Im going to have terms and conditions. The problem is that the dialog box is only displayed for the FIRST TIME.</p> <p>This is the code.</p> <p>JavaScript:</p> <pre><code>function showTOC() { $("#TOC").dialog({ modal: true, overlay: { opacity: 0.7, background: "black" } }) } </code></pre> <p>HTML (a href):</p> <pre><code>&lt;a class="TOClink" href="javascript:showTOC();"&gt;View Terms &amp; Conditions&lt;/a&gt; &lt;div id="example" title="Terms &amp; Conditions"&gt;1..2..&lt;/div&gt; </code></pre> <p>The problem I think is that when you close the dialog box the DIV is destroyed from the html code therfore it can never be displayed again on screen.</p> <p>Can you please help!</p> <p>Thanks</p>
[ { "answer_id": 366730, "author": "carlsz", "author_id": 46077, "author_profile": "https://Stackoverflow.com/users/46077", "pm_score": 6, "selected": true, "text": "$(document).ready({\n $('a.TOClink').click(function(){\n showTOC();\n });\n});\n\nfunction showTOC() {\n $('#example').dialog({modal:true});\n}\n <div id=\"terms\" style=\"display:none;\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n <a id=\"showTerms\" href=\"#\">Show Terms &amp; Conditions</a> \n <script type=\"text/javascript\">\n $(document).ready(function(){\n $('#showTerms').click(function(){\n $('#terms').dialog({modal:true}); \n });\n });\n </script>\n" }, { "answer_id": 416900, "author": "RaeLehman", "author_id": 47096, "author_profile": "https://Stackoverflow.com/users/47096", "pm_score": 6, "selected": false, "text": "<script type=\"text/javascript\"> \n jQuery(document).ready( function(){ \n jQuery(\"#myButton\").click( showDialog );\n\n //variable to reference window\n $myWindow = jQuery('#myDiv');\n\n //instantiate the dialog\n $myWindow.dialog({ height: 350,\n width: 400,\n modal: true,\n position: 'center',\n autoOpen:false,\n title:'Hello World',\n overlay: { opacity: 0.5, background: 'black'}\n });\n }\n\n );\n //function to show dialog \n var showDialog = function() {\n //if the contents have been hidden with css, you need this\n $myWindow.show(); \n //open the dialog\n $myWindow.dialog(\"open\");\n }\n\n //function to close dialog, probably called by a button in the dialog\n var closeDialog = function() {\n $myWindow.dialog(\"close\");\n }\n\n\n</script>\n</head>\n\n<body>\n\n<input id=\"myButton\" name=\"myButton\" value=\"Click Me\" type=\"button\" />\n<div id=\"myDiv\" style=\"display:none\">\n <p>I am a modal dialog</p>\n</div>\n" }, { "answer_id": 914560, "author": "Rickster", "author_id": 112980, "author_profile": "https://Stackoverflow.com/users/112980", "pm_score": 4, "selected": false, "text": "$(document).ready(function(){\n\n // Initialize my dialog\n $(\"#dialog\").dialog({\n autoOpen: false,\n modal: true,\n buttons: {\n \"OK\":function() { // do something },\n \"Cancel\": function() { $(this).dialog(\"close\"); }\n }\n });\n\n // Bind to the click event for my button and execute my function\n $(\"#x-button\").click(function(){\n Foo.DoSomething();\n });\n});\n var Foo = {\n DoSomething: function(){\n $(\"#dialog\").dialog(\"open\");\n }\n}\n" }, { "answer_id": 2066758, "author": "Jon", "author_id": 250991, "author_profile": "https://Stackoverflow.com/users/250991", "pm_score": 2, "selected": false, "text": " JS CODE:\n $(\".sectionHelp\").click(function(){\n $(\"#dialog_\"+$(this).attr('id')).dialog({autoOpen: false});\n $(\"#dialog_\"+$(this).attr('id')).dialog(\"open\");\n });\n\n HTML: \n <div class=\"dialog\" id=\"dialog_help1\" title=\"Dialog Title 1\">\n <p>Dialog 1</p>\n </div>\n <div class=\"dialog\" id=\"dialog_help2\" title=\"Dialog Title 2\">\n <p>Dialog 2 </p>\n </div>\n\n <a href=\"#\" id=\"help1\" class=\"sectionHelp\"></a>\n <a href=\"#\" id=\"help2\" class=\"sectionHelp\"></a>\n\n CSS:\n div.dialog{\n display:none;\n }\n" }, { "answer_id": 2568394, "author": "Upali", "author_id": 307869, "author_profile": "https://Stackoverflow.com/users/307869", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\">\n// Increase the default animation speed to exaggerate the effect\n$.fx.speeds._default = 1000;\n$(function() {\n $('#dialog1').dialog({\n autoOpen: false,\n show: 'blind',\n hide: 'explode'\n });\n\n $('#Wizard1_txtEmailID').click(function() {\n $('#dialog1').dialog('open');\n return false;\n });\n $('#Wizard1_txtEmailID').click(function() {\n $('#dialog2').dialog('close');\n return false;\n });\n //mouseover\n $('#Wizard1_txtPassword').click(function() {\n $('#dialog1').dialog('close');\n return false;\n });\n\n});\n\n\n\n/////////////////////////////////////////////////////\n <div id=\"dialog1\" title=\"Email ID\">\n <p>\n (Enter your Email ID here.)\n <br />\n </p>\n </div>\n ////////////////////////////////////////////////////////\n\n<div id=\"dialog2\" title=\"Password\">\n <p>\n (Enter your Passowrd here.)\n <br />\n </p>\n </div>\n" }, { "answer_id": 2604266, "author": "djburdick", "author_id": 181585, "author_profile": "https://Stackoverflow.com/users/181585", "pm_score": 0, "selected": false, "text": "$('#click_link').live(\"click\",function() {\n $(\"#popup\").dialog({modal:true, width:500, height:800});\n\n $(\"#popup\").dialog(\"open\");\n\n return false;\n});\n" }, { "answer_id": 11168565, "author": "Michal - wereda-net", "author_id": 1440818, "author_profile": "https://Stackoverflow.com/users/1440818", "pm_score": 0, "selected": false, "text": "function ySearch(){ console.log('ysearch');\n $( \"#aaa\" ).dialog({autoOpen: true,closeOnEscape: true, dialogClass: \"ysearch-dialog\",modal: false,height: 510, width:860\n });\n $('#aaa').dialog(\"open\");\n\n console.log($('#aaa').dialog(\"isOpen\"));\n return false;\n}\n" }, { "answer_id": 12069211, "author": "Vishnoo Rath", "author_id": 827225, "author_profile": "https://Stackoverflow.com/users/827225", "pm_score": 0, "selected": false, "text": " $(\"#lnkDetails\").live('click', function (e) {\n\n //Create dynamic element after the element that raised the event. In my case a <a id=\"lnkDetails\" href=\"/Attendance/Details/2012-07-01\" />\n $(this).after('<div id=\\\"dialog-confirm\\\" />');\n\n //Optional : Load data from an external URL. The attr('href') is the href of the <a> tag.\n $('#dialog-confirm').load($(this).attr('href'));\n\n //Copied from jQueryUI site . Do we need this?\n $(\"#dialog:ui-dialog\").dialog(\"destroy\");\n\n //Transform the dynamic DOM element into a dialog\n $('#dialog-confirm').dialog({\n modal: true,\n title: 'Details'\n });\n\n //Prevent Bubbling up to other elements.\n return false;\n });\n" }, { "answer_id": 13209329, "author": "Rikin Patel", "author_id": 672891, "author_profile": "https://Stackoverflow.com/users/672891", "pm_score": 0, "selected": false, "text": "/* Overlays */\n.ui-widget-overlay\n{\n background: #5c5c5c url(images/ui-bg_flat_50_5c5c5c_40x100.png) 50% 50% repeat-x;\n opacity: .50;\n filter: Alpha(Opacity=80);\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44973/" ]
366,697
<p>I have the following code which adapts linq entities to my Domain objects:</p> <pre><code>return from g in DBContext.Gigs select new DO.Gig { ID = g.ID, Name = g.Name, Description = g.Description, StartDate = g.Date, EndDate = g.EndDate, IsDeleted = g.IsDeleted, Created = g.Created, TicketPrice = g.TicketPrice }; </code></pre> <p>This works very nicely.</p> <p>However I now want to populate a domain object Venue object and add it to the gig in the same statement. Heres my attempt....</p> <pre><code>return from g in DBContext.Gigs join venue in DBContext.Venues on g.VenueID equals venue.ID select new DO.Gig { ID = g.ID, Name = g.Name, Description = g.Description, StartDate = g.Date, EndDate = g.EndDate, IsDeleted = g.IsDeleted, Created = g.Created, TicketPrice = g.TicketPrice, Venue = from v in DBContext.Venues where v.ID == g.VenueID select new DO.Venue { ID = v.ID, Name = v.Name, Address = v.Address, Telephone = v.Telephone, URL = v.Website } }; </code></pre> <p>However this doesnt compile!!!</p> <p>Is it possible to adapt children objects using the "select new" approach?</p> <p>What am I doing so very very wrong?</p>
[ { "answer_id": 366721, "author": "Mike Two", "author_id": 23659, "author_profile": "https://Stackoverflow.com/users/23659", "pm_score": 1, "selected": false, "text": "return from g in DBContext.Gigs \n join venue in DBContext.Venues on g.VenueID equals venue.ID \n select new DO.Gig { ID = g.ID, Name = g.Name, Description = g.Description,\n StartDate = g.Date, EndDate = g.EndDate, IsDeleted = g.IsDeleted, \n Created = g.Created, TicketPrice = g.TicketPrice, \n Venue = new DO.Venue { ID = venue.ID, Name = venue.Name, \n Address = venue.Address, Telephone = v.Telephone, \n URL = v.Website }\n" }, { "answer_id": 366843, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 2, "selected": false, "text": "Venue = (from v in DBContext.Venues\n where v.ID == g.VenueID\n select new DO.Venue\n {\n ID = v.ID,\n Name = v.Name,\n Address = v.Address,\n Telephone = v.Telephone,\n URL = v.Website \n }).SingleOrDefault()\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,706
<p>This is a follow-up to <a href="https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator">my question yesterday</a>:</p> <p>CMS kindly provided this example of using bitwise operators to add two numbers in C:</p> <pre><code>#include&lt;stdio.h&gt; int add(int x, int y) { int a, b; do { a = x &amp; y; b = x ^ y; x = a &lt;&lt; 1; y = b; } while (a); return b; } int main( void ){ printf( "6 + 3 = %d", add(6,3)); printf( "6 - 3 = %d", add(6,-3)); return 0; } </code></pre> <p>It works great and I then ported it to Python as follows:</p> <pre><code>def add(x, y): while True: a = x &amp; y b = x ^ y x = a &lt;&lt; 1 y = b if a == 0: break return b print "6 + 3 = %d" % add(6,3) print "6 - 3 = %d" % add(6,-3) </code></pre> <p>They both work for addition and the C program works for subtraction as well. However, the Python program enters an infinite loop for subtraction. I am trying to get to the bottom of this and have posted the program here for further experimentation: <a href="http://codepad.org/pb8IuLnY" rel="nofollow noreferrer">http://codepad.org/pb8IuLnY</a></p> <p>Can anyone advise why there would be a difference between the way C handles this and the way CPython handles this?</p>
[ { "answer_id": 366735, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": false, "text": ">>> 1 << 100\n1267650600228229401496703205376L\n x = (a << 1) & 0xffffffff\n" }, { "answer_id": 3487601, "author": "nithin", "author_id": 420980, "author_profile": "https://Stackoverflow.com/users/420980", "pm_score": 1, "selected": false, "text": "i j printf(\"%d\",(i^j)|((i&j)<<1));\n" }, { "answer_id": 30786721, "author": "DuniC", "author_id": 2302272, "author_profile": "https://Stackoverflow.com/users/2302272", "pm_score": 0, "selected": false, "text": "000 001 010 011 100 101 110 111 000 001 010 011 100 101 110 111 1-3=1+(-3) 101 1+5=6 110 1-3=-2 -4 + -1 = 3 3 + 1 = -4" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23126/" ]
366,718
<p>So I am sold on the concept of attempting to collect data automatically from a program - i.e., popping up a dialog box that asks the user to send the report when something goes wrong.</p> <p>I'm working in MS Visual Studio C#.</p> <p>From an implementation point of view, does it make sense to put a try/catch loop in my main program.cs file, around where the application is run? Like this:</p> <pre><code> try { Application.Run(new myMainForm()); } catch (Exception ex) { //the code to build the report I want to send and to //pop up the Problem Report form and ask the user to send } </code></pre> <p>or does it make sense to put try/catch loops throughout pieces of the code to catch more specific exception types? (I'm thinking not because this is a new application, and putting in more specific exception catches means I have an idea of what's going to go wrong... I don't, which is why the above seems to make sense to me.)</p> <p>-Adeena</p>
[ { "answer_id": 366731, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 3, "selected": false, "text": "[STAThread]\nstatic void Main() \n{\n System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler(ReportError);\n System.Windows.Forms.Application.Run(new MainForm());\n}\n\nprivate static void ReportError(object sender, ThreadExceptionEventArgs e)\n{\n using (ReportErrorDialog errorDlg = new ReportErrorDialog(e.Exception))\n {\n errorDlg.ShowDialog();\n }\n}\n" }, { "answer_id": 366760, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 1, "selected": false, "text": "try\n {\n //Code that could error here\n }\n catch (FormatException ex)\n {\n //Code to tell user of their error\n //all other errors will be handled \n //by the global error handler\n }\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44004/" ]
366,719
<h1>Premise</h1> <p>I believe that there is a way to objectively define &quot;Good&quot; and &quot;Bad&quot; Object-Oriented design techniques and that, as a community we can determine what these are. This is an academic exercise. If done with seriousness and resolve, I believe it can be of great benefit to the community as a whole. The community will benefit by having a place we can all point to to say, &quot;This technique is 'Good' or 'Bad' and we should or should not use it unless there are special circumstances.&quot;</p> <h1>Plan</h1> <p>For this effort, we should focus on Object-Oriented principles (as opposed to Functional, Set-based, or other type of languages).</p> <p>I'm not planning on accepting one answer, instead I'd like the answers to contribute to the final collection or be a rational debate of the issues.</p> <p>I realize that this may controversial, but I believe we can iron something out. There are exceptions to most every rule and I believe this is where the disagreement will fall. We should make declarations and then note relevant exceptions and objections from dissenters.</p> <h1>Basis</h1> <p>I'd like to take a stab at defining &quot;Good&quot; and &quot;Bad&quot;:</p> <ul> <li><p>&quot;Good&quot; - This technique will work the first time and be a lasting solution. It will be easy to change later and will pay the time investment of its implementation quickly. It can be consistently applied and easily recognized by maintenance programmers in the future. Overall, it contributes to the good function and lowers cost of maintenance over the life of the product.</p> </li> <li><p>&quot;Bad&quot; - This technique may work in the short term, but soon becomes a liability. It is immediately difficult to change or becomes more difficult over time. The initial investment may be small or large, but it quickly becomes a growing cost, eventually becoming a sunk cost and must be removed or worked around constantly. It is subjectively applied and inconsistent and may be a surprise or not easily recognizable by maintenance programmers in the future. Overall, it contributes to the ultimate increasing cost of maintaining and/or operating the product and inhibits or prevents changes to the product. By inhibiting or preventing change, it becomes not just a direct cost, but an opportunity cost and a significant liability.</p> </li> </ul> <h1>Starter</h1> <p>As an example of what I think a good contribution would look like, I'd like to propose a &quot;Good&quot; principle:</p> <h2>Separation of Concerns</h2> <p>[Short description]</p> <h3>Example</h3> <p>[Code or some other type of example]</p> <h3>Goals</h3> <p>[Explanation of what problems this principle prevents]</p> <h3>Applicability</h3> <p>[Why, where, and when would I use this principle?]</p> <h3>Exceptions</h3> <p>[When wouldn't I use this principle, or where might it actually be harmful?]</p> <h3>Objections</h3> <p>[Note any dissenting opinions or objections from the community here]</p>
[ { "answer_id": 366791, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 2, "selected": true, "text": "class Foo : private boost::noncopyable { ... };\n class Foo {\n ...\nprivate:\n boost::noncopyable noncopyable_;\n};\n synchronized class ThreadsafeVector<T> : public Vector<T>, public Mutex { ... };\n struct ThreadsafeVector<T> {\n Vector<T> vector;\n Mutex mutex;\n}\n MyThreadSafeDataStructure Mutex" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10862/" ]
366,720
<p>Currently my code is organized in the following tree structure:</p> <pre><code>src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py </code></pre> <p>Where the <code>module*.py</code> files contains the source code and the <code>test_module*.py</code> contains the <code>TestCase</code>s for the relevant module.</p> <p>With the following comands I can run the tests contained in a single file, for example:</p> <pre><code>$ cd src $ nosetests test_filesystem.py .................. ---------------------------------------------------------------------- Ran 18 tests in 0.390s OK </code></pre> <p>How can I run all tests? I tried with <code>nosetests -m 'test_.*'</code> but it doesn't work.</p> <pre><code>$cd src $ nosetests -m 'test_.*' ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>Thanks</p>
[ { "answer_id": 366770, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 2, "selected": false, "text": "setup.py foo/\n module1.py\n module2.py\n subpackage1/\n __init__.py\n moduleA.py\n moduleB.py\n tests/\n test_module1.py\n test_module2.py\n test_subpackage1_moduleA,py\n test_subpackage2_moduleB.py\n nosetests bash #!/bin/bash\ncd tests/\nfor TEST_SCRIPT in test_*.py ; do\n nosetests -m $TEST_SCRIPT\ndone\n" }, { "answer_id": 366819, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 0, "selected": false, "text": "testoob test_foo.py\n # src/subpackage?/__init__.py\ndef suite():\n import testoob\n return testoob.collecting.collect_from_files(\"test_*.py\")\n # src/alltests.py\ntest_modules = [\n 'subpackage1.suite',\n 'subpackage2.suite',\n]\n\ndef suite():\n import unittest\n return unittest.TestLoader().loadTestsFromNames(test_modules)\n\nif __name__ == \"__main__\":\n import testoob\n testoob.main(defaultTest=\"suite\")\n" }, { "answer_id": 366828, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 4, "selected": false, "text": "src/\n module1.py\n module2.py\n subpackage1/\n __init__.py\n moduleA.py\n moduleB.py\ntests/\n __init__.py\n test_module1.py\n test_module2.py\n subpackage1/\n __init__.py\n test_moduleA.py\n test_moduleB.py\n nosetests src/ PYTHONPATH" }, { "answer_id": 367748, "author": "Mapad", "author_id": 28165, "author_profile": "https://Stackoverflow.com/users/28165", "pm_score": 3, "selected": false, "text": "test_all.py import unittest\nimport test_module1\nimport test_module2\nimport subpackage1\nif __name__ == \"__main__\":\n allsuites = unittest.TestSuite([test_module1.suite(), \\\n test_module2.suite(), \\\n subpackage1.test_moduleA.suite(), \\\n subpackage1.test_moduleB.suite()])\n Class1 Class2 def suite():\n \"\"\" This defines all the tests of a module\"\"\"\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(Class1))\n suite.addTest(unittest.makeSuite(Class2))\n return suite\nif __name__ == '__main__':\n unittest.TextTestRunner(verbosity=2).run(suite())\n" }, { "answer_id": 373150, "author": "Singletoned", "author_id": 46715, "author_profile": "https://Stackoverflow.com/users/46715", "pm_score": 4, "selected": true, "text": "test nosetest" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36131/" ]
366,758
<p>I would like to access the contacts field on an email message (Email options) in outlook. Normally this field ties an email to a contact. Since it is a freeform text field available from the options dialog box, I am trying to use it to store a "next action" for my email message. I would like to set the next action based on the subject but I can't figure out how to access thas field from the outlook.mailitem object</p> <p>Thanks Jim</p>
[ { "answer_id": 380413, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 0, "selected": false, "text": "UserProperties" }, { "answer_id": 453860, "author": "Geoff", "author_id": 55487, "author_profile": "https://Stackoverflow.com/users/55487", "pm_score": 1, "selected": false, "text": "Sub ShowContactsField()\n Dim objApp As Outlook.Application\n Dim ActiveMailItem As Inspector\n Dim currLink As Link\n\nSet objApp = CreateObject(\"Outlook.Application\")\n If TypeName(objApp.ActiveWindow) = \"Inspector\" Then\n If objApp.ActiveInspector.CurrentItem.Class = olMail Then\n For Each currLink In objApp.ActiveInspector.CurrentItem.Links\n If currLink.Type = olContact Then\n MsgBox currLink.Name\n End If\n Next\n End If\n End If\n Set objApp = Nothing\nEnd Sub\n\n" }, { "answer_id": 1127756, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " For i = 1 To mailItem.Links.Count\n If mailItem.Links.item(i).Type = olContact Then\n Debug.Print mailItem.Links.item(i).Name\n End If\nNext i\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,768
<p>Can I convert a bitmap to PNG in memory (i.e. without writing to a file) using only the Platform SDK? (i.e. no libpng, etc.).</p> <p>I also want to be able to define a transparent color (not alpha channel) for this image.</p> <p><strong>The GdiPlus solution seems to be limited to images of width divisible by 4</strong>. Anything else fails during the call to Save(). Does anyone know the reason for this limitation and how/whether I can work around it?</p> <p><strong>Update: Bounty</strong></p> <p>I'm starting a bounty (I really want this to work). I implemented the GDI+ solution, but as I said, it's limited to images with quad width. The bounty will go to anyone who can solve this width issue (without changing the image dimensions), or can offer an alternative non-GDI+ solution that works.</p>
[ { "answer_id": 366785, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "Save IStream CreateStreamOnHGlobal" }, { "answer_id": 538497, "author": "Aardvark", "author_id": 3655, "author_profile": "https://Stackoverflow.com/users/3655", "pm_score": 3, "selected": false, "text": "GetDIBits BITMAPINFOHEADER::biCompression BI_PNG GetDIBits" }, { "answer_id": 538742, "author": "timday", "author_id": 24283, "author_profile": "https://Stackoverflow.com/users/24283", "pm_score": 5, "selected": true, "text": "png_set_write_fn char* png_writer file_mgr FILE*" }, { "answer_id": 540786, "author": "djeidot", "author_id": 4880, "author_profile": "https://Stackoverflow.com/users/4880", "pm_score": 3, "selected": false, "text": "CByteArray baPicture;\nIStream *pStream = NULL;\nif (CreateStreamOnHGlobal(NULL, TRUE, &pStream) == S_OK)\n{\n if (image.Save(pStream, Gdiplus::ImageFormatPNG) == S_OK)\n {\n ULARGE_INTEGER ulnSize;\n LARGE_INTEGER lnOffset;\n lnOffset.QuadPart = 0;\n if (pStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize) == S_OK)\n {\n if (pStream->Seek(lnOffset, STREAM_SEEK_SET, NULL) == S_OK)\n { \n baPicture.SetSize(ulnSize.QuadPart);\n ULONG ulBytesRead;\n pStream->Read(baPicture.GetData(), ulnSize.QuadPart, &ulBytesRead);\n }\n }\n }\n}\npStream->Release();\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11208/" ]
366,772
<p>I'm using windbg to examine some crash dumps sent in by an app. There seems to be some correlation between a crash I'm seeing and having a certain 3rd party DLL loaded into the process (a flaky Winsock LSP, I suspect). To make this sort of analysis easier in the future, is there a windbg script that would just show me a list of modules that are non-Microsoft? This would make patterns between crashes more obvious to me. I'm using "lm D sm", but going through the list manually right now is a pain.</p> <p>Thanks!</p>
[ { "answer_id": 573827, "author": "AaronBa", "author_id": 69370, "author_profile": "https://Stackoverflow.com/users/69370", "pm_score": 0, "selected": false, "text": ".load clr10\\sos\n!sam c:\\temp\\modules\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23524/" ]
366,775
<p>Im trying to add a connection to a database in SQL Server 2008 using Visual Studio 2008. When testing the connection, it says that it is successful. However, once I said okay, it complains and say: "Cannot add data connection. Object reference not set to an instance of an object."</p> <p>How do I go about adding a data connection to a SQL Server 2008 using Visual Studio 2008?</p>
[ { "answer_id": 366811, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 1, "selected": false, "text": "var conn = new SqlConnection([connectionString]);\nconn.Open();\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,794
<pre><code>&lt;?php $string = 'The quick brown fox jumped over the lazy dog.'; $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements[0] = 'slow'; $replacements[1] = 'black'; $replacements[2] = 'bear'; echo preg_replace($patterns, $replacements, $string); ?&gt; </code></pre> <p>Ok guys, Now I have the above code. It just works well. Now for example I'd like to also replace "lazy" and "dog" with "slow" What I have to do now is would look like this, right?</p> <pre><code>&lt;?php $string = 'The quick brown fox jumped over the lazy dog.'; $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $patterns[3] = '/lazy/'; $patterns[4] = '/dog/'; $replacements[0] = 'slow'; $replacements[1] = 'black'; $replacements[2] = 'bear'; $replacements[3] = 'slow'; $replacements[4] = 'slow'; echo preg_replace($patterns, $replacements, $string); ?&gt; </code></pre> <p>Ok.</p> <p>So my question is, is there any way I can do like this</p> <pre><code>$patterns[0] = '/quick/', '/lazy/', '/dog/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements[0] = 'slow'; $replacements[1] = 'black'; $replacements[2] = 'bear'; </code></pre> <p>Thanks</p>
[ { "answer_id": 366797, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": true, "text": "$patterns[0] = '/quick|lazy|dog/';\n" }, { "answer_id": 366884, "author": "TravisO", "author_id": 35116, "author_profile": "https://Stackoverflow.com/users/35116", "pm_score": 0, "selected": false, "text": "$patterns = array('/quick/','/brown/','/fox/','lazy/',/dog/');\n" }, { "answer_id": 366963, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 2, "selected": false, "text": "$output = str_replace(array('quick', 'brown', 'fox'), array('lazy', 'white', 'rabbit'), $input)\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,805
<p>How can I change <code>CSS</code> from <code>javascript</code>. </p> <p>I'm using <code>jQuery-ui Dialog</code> and I want to change the style of a <code>DIV</code> from javascript.</p> <p>Thanks</p>
[ { "answer_id": 366809, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 4, "selected": true, "text": "css $(selector).css(properties); // option 1\n$(selector).css(name, value); // option 2\n $(\"div#mydiv\").css({'background-color' : 'red'}); // option 1\n$(\"div#mydiv\").css('background-color','red'); // option 2\n var color = $(\"div#mydiv\").css('background-color');\n color red $(selector).addClass(class_name);\n$(selector).removeClass(class_name);\n" }, { "answer_id": 366818, "author": "Tuminoid", "author_id": 40657, "author_profile": "https://Stackoverflow.com/users/40657", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\">\n .foo { color: Red; }\n .bar { color: Blue; }\n</style>\n<div class=\"foo\" id=\"redtext\"> some red text here </div>\n var div = document.getElementById('redtext');\n div.style.color = 'Green';\n div.className = 'bar';\n" }, { "answer_id": 44239953, "author": "Abhijit", "author_id": 6913738, "author_profile": "https://Stackoverflow.com/users/6913738", "pm_score": 0, "selected": false, "text": " $(\"myDiv\").css({\"color\":\"red\",\"display\":\"block\"})\n var myDiv = document,getElementById(\"myDiv\");\n\nmyDiv.style.display = \"block\";\n\nmyDiv.style.color = \"red\";\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44973/" ]
366,822
<p>I have always written regexes like this</p> <pre><code>&lt;A HREF="([^"]*)" TARGET="_blank"&gt;([^&lt;]*)&lt;/A&gt; </code></pre> <p>but I just learned about this <a href="http://www.regular-expressions.info/examples.html" rel="nofollow noreferrer">lazy thing</a> and that I can write it like this</p> <pre><code>&lt;A HREF="(.*?)" TARGET="_blank"&gt;(.*?)&lt;/A&gt; </code></pre> <p>is there any disadvantage to using this second approach? The regex is definitely more compact (even SO parses it better).</p> <p><strong>Edit</strong>: There are two best answers here, which point out two important differences between the expressions. ysth's answer points to a weakness in the non-greedy/lazy one, in which the hyperlink itself could possibly include other attributes of the A tag (definitely not good). Rob Kennedy points out a weakness in the greedy example, in that anchor texts cannot include other tags (definitely not okay, because it wouldn't grab all the anchor text either)... so the answer is that, regular expressions being what they are, lazy and non-lazy solutions that seem the same are probably not semantically equivalent.</p> <p><strong>Edit</strong>: Third best answer is by Alan M about relative speed of the expressions. For the time being, I'll mark his as best answer so people give him more points :) </p>
[ { "answer_id": 366868, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": false, "text": "img b" }, { "answer_id": 366907, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 3, "selected": false, "text": "<A HREF=\"foo\" NAME=\"foo\" TARGET=\"_blank\">foo</A>\n foo\" NAME=\"foo\n" }, { "answer_id": 367304, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 5, "selected": true, "text": "/<BODY>.*?<\\/BODY>/is\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
366,834
<p>Does anyone have any suggestions as to how I can clean the body of incoming emails? I want to strip out disclaimers, images and maybe any previous email text that may be also be present so that I am left with just the body text content. My guess is it isn't going to be possible in any reliable way, but has anyone tried it? Are there any libraries geared towards this sort of thing?</p>
[ { "answer_id": 59001867, "author": "Paul Mendoza", "author_id": 29277, "author_profile": "https://Stackoverflow.com/users/29277", "pm_score": 0, "selected": false, "text": "var parser = new SigParser.EmailParsing.EmailParser();\nvar result = await parser.GetCleanedBodyAsync(new SigParser.EmailParsing.Models.CleanedBodyInput {\n FromEmailAddress = \"john.smith@example.com\",\n FromName = \"John Smith\",\n TextBody = @\"Hi Mark,\nThis is my message.\n\nThanks\nJohn Smith\n888-333-4434\"\n });\n\n// This would print \"Hi Mark,\\r\\nThis is my message.\"\nConsole.WriteLine(result.CleanedBodyPlain); \n\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
366,838
<p>Hey, i am currently working on a django app for my studies, and came to the point of l18n. Localizing the site itself was very easy, but now i have to allow users, to translate the dynamic content of the application. Users can save "products" in the database and give them names and descriptions, but since the whole site should be localized, i must provide a way of translating theses names and descriptions to the users.</p> <p>Is there a natural way in django to do this? Or do i have to realize it as part of the application (by representing the translations in the datamodel)</p> <p>Thanks, Janosch</p>
[ { "answer_id": 12482331, "author": "Kostyantyn", "author_id": 1176671, "author_profile": "https://Stackoverflow.com/users/1176671", "pm_score": 1, "selected": false, "text": "class Product(models.Model):\n name=models.CharField(max_length=100)\n name_ar=models.CharField(max_length=100, default='')\n\n def __unicode__(self):\n return self.name\n\nclass Product_ar(Product):\n def __unicode__(self):\n return self.name_ar\n class Meta:\n proxy=True\n class CollectionEditForm_en(forms.Form):\n name = forms.CharField(label=_('Name'), max_length=100, widget=forms.TextInput(attrs={'size':'50'}))\n product = forms.ModelChoiceField(label=_('product'), queryset=Product.objects.filter(enabled=True), empty_label=None)\n\nclass CollectionEditForm_ar(forms.Form):\n name = forms.CharField(label=_('Name'), max_length=100, widget=forms.TextInput(attrs={'size':'50'}))\n product = forms.ModelChoiceField(label=_('product'), queryset=Product_ar.objects.filter(enabled=True), empty_label=None)\n if request.LANGUAGE_CODE=='ar':\n CollectionEditForm=CollectionEditForm_ar\nelse:\n CollectionEditForm=CollectionEditForm_en\n {% if LANGUAGE_CODE == \"ar\" %}\n <a href=\"/product/{{product.alias}}/\">{{product.name_ar}}</a>\n{% else %}\n <a href=\"/product/{{product.alias}}/\">{{product.name}}</a>\n{% endif %}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46172/" ]
366,849
<p>Lets say my alphabet contains X letters and my language supports only Y letter words (Y &lt; X ofcourse). I need to generate all the words possible in random order.</p> <p>E.g. Alphabet=a,b,c,d,e,f,g Y=3</p> <p>So the words would be: aaa aab aac aba .. bbb ccc .. (the above should be generated in random order)</p> <p>The trivial way to do it would be to generate the words and then randomize the list. I DONT want to do that. I want to generate the words in random order.</p> <p>rondom(n)=letter[x].random(n-1) will not work because then you'll have a list of words starting with letter[x].. which will make the list not so random.</p> <p>Any code/pseudocode appreciated.</p>
[ { "answer_id": 366870, "author": "Jennifer", "author_id": 22360, "author_profile": "https://Stackoverflow.com/users/22360", "pm_score": 0, "selected": false, "text": " char[] alphabet = {'a', 'b', 'c', 'd'};\n int wordLength = 3;\n\n Random rand = new Random();\n\n for (int i = 0; i < 5; i++)\n {\n char[] word = new char[wordLength];\n for (int j = 0; j < wordLength; j++)\n {\n word[j] = alphabet[rand.Next(alphabet.Length)];\n }\n Console.WriteLine(new string(word));\n }\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13820/" ]
366,852
<p>I'm writing a financial application in C# where performance (i.e. speed) is critical. Because it's a financial app I have to use the Decimal datatype intensively. </p> <p>I've optimized the code as much as I could with the help of a profiler. Before using Decimal, everything was done with the Double datatype and the speed was several times faster. However, Double is not an option because of its binary nature, causing a lot of precision errors over the course of multiple operations.</p> <p>Is there any decimal library that I can interface with C# that could give me a performance improvement over the native Decimal datatype in .NET?</p> <p>Based on the answers I already got, I noticed I was not clear enough, so here are some additional details:</p> <ul> <li>The app has to be as fast as it can possibly go (i.e. as fast as it was when using Double instead of Decimal would be a dream). Double was about 15x faster than Decimal, as the operations are hardware based.</li> <li>The hardware is already top-notch (I'm running on a Dual Xenon Quad-Core) and the application uses threads, so CPU utilization is always 100% on the machine. Additionally, the app is running in 64bit mode, which gives it a mensurable performance advantage over 32bit.</li> <li>I've optimized past the point of sanity (more than one month and a half optimizing; believe it or not, it now takes approx. 1/5000 of what it took to do the same calculations I used as a reference initially); this optimization involved everything: string processing, I/O, database access and indexes, memory, loops, changing the way some things were made, and even using "switch" over "if" everywhere it made a difference. The profiler is now clearly showing that the remaining performance culprit is on the Decimal datatype operators. Nothing else is adding up a considerable amount of time.</li> <li>You have to believe me here: I've gone as far as I could possibly go in the realm of C#.NET to optimize the application, and I'm really amazed at its current performance. I'm now looking for a good idea in order to improve Decimal performance to something close to Double. I know it's only a dream, but just wanted to check I thought of everything possible. :)</li> </ul> <p>Thanks!</p>
[ { "answer_id": 1221409, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#include <emmintrin.h>\n#include <tmmintrin.h>\n\nextern \"C\" DllExport __int32* sse2_add(__int32* arr1, __int32* arr2);\n\nextern \"C\" DllExport __int32* sse2_add(__int32* arr1, __int32* arr2)\n{\n __m128i mi1 = _mm_setr_epi32(arr1[0], arr1[1], arr1[2], arr1[3]);\n __m128i mi2 = _mm_setr_epi32(arr2[0], arr2[1], arr2[2], arr2[3]);\n\n __m128i mi3 = _mm_add_epi32(mi1, mi2);\n __int32 rarr[4] = { mi3.m128i_i32[0], mi3.m128i_i32[1], mi3.m128i_i32[2], mi3.m128i_i32[3] };\n return rarr;\n}\n [DllImport(\"sse2.dll\")]\nprivate unsafe static extern int[] sse2_add(int[] arr1, int[] arr2);\n\npublic unsafe static decimal addDec(decimal d1, decimal d2)\n{\n int[] arr1 = decimal.GetBits(d1);\n int[] arr2 = decimal.GetBits(d2);\n\n int[] resultArr = sse2_add(arr1, arr2);\n\n return new decimal(resultArr);\n}\n" }, { "answer_id": 16585129, "author": "smirkingman", "author_id": 338101, "author_profile": "https://Stackoverflow.com/users/338101", "pm_score": 2, "selected": false, "text": "Long 231 mS\nDouble 286 mS\nDecimal 2010 mS\n Sub Main()\n Const TESTS = 100000000\n Dim sw As Stopwatch\n\n Dim l As Long = 0\n Dim a As Long = 123456\n sw = Stopwatch.StartNew()\n For x As Integer = 1 To TESTS\n l += a\n Next\n Console.WriteLine(String.Format(\"Long {0} mS\", sw.ElapsedMilliseconds))\n\n Dim d As Double = 0\n Dim b As Double = 123456\n sw = Stopwatch.StartNew()\n For x As Integer = 1 To TESTS\n d += b\n Next\n Console.WriteLine(String.Format(\"Double {0} mS\", sw.ElapsedMilliseconds))\n\n Dim m As Decimal = 0\n Dim c As Decimal = 123456\n sw = Stopwatch.StartNew()\n For x As Integer = 1 To TESTS\n m += c\n Next\n Console.WriteLine(String.Format(\"Decimal {0} mS\", sw.ElapsedMilliseconds))\n\n Console.WriteLine(\"Press a key\")\n Console.ReadKey()\nEnd Sub\n" }, { "answer_id": 34332452, "author": "user1921819", "author_id": 1921819, "author_profile": "https://Stackoverflow.com/users/1921819", "pm_score": 4, "selected": false, "text": "Int64 Money public struct Money : IComparable\n{\n private readonly long _value;\n\n public const long Multiplier = 1000000;\n private const decimal ReverseMultiplier = 0.000001m;\n\n public Money(long value)\n {\n _value = value;\n }\n\n public static explicit operator Money(decimal d)\n {\n return new Money(Decimal.ToInt64(d * Multiplier));\n }\n\n public static implicit operator decimal (Money m)\n {\n return m._value * ReverseMultiplier;\n }\n\n public static explicit operator Money(double d)\n {\n return new Money(Convert.ToInt64(d * Multiplier));\n }\n\n public static explicit operator double (Money m)\n {\n return Convert.ToDouble(m._value * ReverseMultiplier);\n }\n\n public static bool operator ==(Money m1, Money m2)\n {\n return m1._value == m2._value;\n }\n\n public static bool operator !=(Money m1, Money m2)\n {\n return m1._value != m2._value;\n }\n\n public static Money operator +(Money d1, Money d2)\n {\n return new Money(d1._value + d2._value);\n }\n\n public static Money operator -(Money d1, Money d2)\n {\n return new Money(d1._value - d2._value);\n }\n\n public static Money operator *(Money d1, Money d2)\n {\n return new Money(d1._value * d2._value / Multiplier);\n }\n\n public static Money operator /(Money d1, Money d2)\n {\n return new Money(d1._value / d2._value * Multiplier);\n }\n\n public static bool operator <(Money d1, Money d2)\n {\n return d1._value < d2._value;\n }\n\n public static bool operator <=(Money d1, Money d2)\n {\n return d1._value <= d2._value;\n }\n\n public static bool operator >(Money d1, Money d2)\n {\n return d1._value > d2._value;\n }\n\n public static bool operator >=(Money d1, Money d2)\n {\n return d1._value >= d2._value;\n }\n\n public override bool Equals(object o)\n {\n if (!(o is Money))\n return false;\n\n return this == (Money)o;\n }\n\n public override int GetHashCode()\n {\n return _value.GetHashCode();\n }\n\n public int CompareTo(object obj)\n {\n if (obj == null)\n return 1;\n\n if (!(obj is Money))\n throw new ArgumentException(\"Cannot compare money.\");\n\n Money other = (Money)obj;\n return _value.CompareTo(other._value);\n }\n\n public override string ToString()\n {\n return ((decimal) this).ToString(CultureInfo.InvariantCulture);\n }\n}\n double long decimal Money decimal Money Added moneys in 5.445 ms\nAdded decimals in 26.23 ms\nAdded doubles in 2.3925 ms\nAdded longs in 1.6494 ms\n\nSubtracted moneys in 5.6425 ms\nSubtracted decimals in 31.5431 ms\nSubtracted doubles in 1.7022 ms\nSubtracted longs in 1.7008 ms\n\nMultiplied moneys in 20.4474 ms\nMultiplied decimals in 24.9457 ms\nMultiplied doubles in 1.6997 ms\nMultiplied longs in 1.699 ms\n\nDivided moneys in 15.2841 ms\nDivided decimals in 229.7391 ms\nDivided doubles in 7.2264 ms\nDivided longs in 8.6903 ms\n\nEquility compared moneys in 5.3652 ms\nEquility compared decimals in 29.003 ms\nEquility compared doubles in 1.727 ms\nEquility compared longs in 1.7547 ms\n\nRelationally compared moneys in 9.0285 ms\nRelationally compared decimals in 29.2716 ms\nRelationally compared doubles in 1.7186 ms\nRelationally compared longs in 1.7321 ms\n decimal long double Decimal Decimal double long Decimal Decimal Decimal double Decimal long Decimal" }, { "answer_id": 57498706, "author": "user1921819", "author_id": 1921819, "author_profile": "https://Stackoverflow.com/users/1921819", "pm_score": 3, "selected": false, "text": "Decimal Decimal Double Double Decimal IEEE 754-2008 Decimal Floating-Point Arithmetic specification Decimals Double C# java java java" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46178/" ]
366,854
<p>I have a problem with the <a href="https://jqueryui.com/dialog/" rel="nofollow noreferrer"><code>jquery-ui dialog box</code></a>. </p> <p><strong>The problem is that when I close the dialog box and then I click on the link that triggers it, it does not pop-up again unless I refresh the page.</strong> </p> <p>How can I call the dialog box back without refreshing the actual page. </p> <p>Below is my code:</p> <pre><code>$(document).ready(function() { $('#showTerms').click(function() { $('#terms').css('display','inline'); $('#terms').dialog({ resizable: false, modal: true, width: 400, height: 450, overlay: { backgroundColor: "#000", opacity: 0.5 }, buttons:{ "Close": function() { $(this).dialog("close"); } }, close: function(ev, ui) { $(this).remove(); }, }); }); </code></pre> <p>Thanks</p>
[ { "answer_id": 366893, "author": "Darko", "author_id": 32943, "author_profile": "https://Stackoverflow.com/users/32943", "pm_score": 4, "selected": false, "text": "$(this).remove() $(this).hide() #terms" }, { "answer_id": 366898, "author": "David Bonnici", "author_id": 44973, "author_profile": "https://Stackoverflow.com/users/44973", "pm_score": 5, "selected": true, "text": "$(document).ready(function() {\n$('#showTerms').click(function()\n{\n $('#terms').css('display','inline');\n $('#terms').dialog({resizable: false,\n modal: true,\n width: 400,\n height: 450,\n overlay: { backgroundColor: \"#000\", opacity: 0.5 },\n buttons:{ \"Close\": function() { $(this).dialog('**destroy**'); } },\n close: function(ev, ui) { $(this).close(); },\n }); \n}); \n$('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });\n});\n" }, { "answer_id": 745635, "author": "Benedikt", "author_id": 90432, "author_profile": "https://Stackoverflow.com/users/90432", "pm_score": 2, "selected": false, "text": "$(this).dialog('destroy');\n" }, { "answer_id": 745662, "author": "Shane Fulmer", "author_id": 63477, "author_profile": "https://Stackoverflow.com/users/63477", "pm_score": 7, "selected": false, "text": "$(\"#terms\").dialog({ autoOpen: false }); $('#terms').dialog('open'); $('#terms').dialog('close');" }, { "answer_id": 1634351, "author": "26design", "author_id": 197730, "author_profile": "https://Stackoverflow.com/users/197730", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n // dialog init\n $('#terms').dialog({\n autoOpen: false,\n resizable: false,\n modal: true,\n width: 400,\n height: 450,\n overlay: { backgroundColor: \"#000\", opacity: 0.5 },\n buttons: { \"Close\": function() { $(this).dialog('close'); } },\n close: function(ev, ui) { $(this).close(); }\n });\n // click event\n $('#showTerms').click(function(){\n $('#terms').dialog('open').css('display','inline'); \n });\n // date picker\n $('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });\n});\n" }, { "answer_id": 2903551, "author": "Zilverdistel", "author_id": 2057028, "author_profile": "https://Stackoverflow.com/users/2057028", "pm_score": 2, "selected": false, "text": "$('<div id=\"dossier_edit_form_tmp_id\">').html(data.form)\n.data('dossier_id',dossier_id)\n.dialog({\n title: 'Opdracht wijzigen',\n show: 'clip',\n hide: 'clip',\n minWidth: 520,\n width: 520,\n modal: true,\n buttons: { 'Bewaren': dossier_edit_form_opslaan },\n close: function(event, ui){ \n $(this).dialog('destroy'); \n $('#dossier_edit_form_tmp_id').remove();\n }\n});\n" }, { "answer_id": 3804357, "author": "edib", "author_id": 250296, "author_profile": "https://Stackoverflow.com/users/250296", "pm_score": 1, "selected": false, "text": "var dialog1 = $(\"#dialog\").dialog({ \n autoOpen: false, \n height: 480, \n width: 640 \n}); \n$('#tikla').click(function() { \n dialog1.load('./browser.php').dialog('open');\n}); \n" }, { "answer_id": 6255055, "author": "Oleg Ivanov", "author_id": 347266, "author_profile": "https://Stackoverflow.com/users/347266", "pm_score": 1, "selected": false, "text": "oneInstance: false\n $(document).ready(function() {\n\n var overlays = null;\n\n overlays = jQuery(\"a[rel]\");\n\n for (var n = 0; n < overlays.length; n++) {\n\n $(overlays[n]).overlay({\n oneInstance: false, \n mask: '#669966',\n effect: 'apple',\n onBeforeLoad: function() {\n overlay_before_load(this);\n }\n });\n\n }\n\n}\n" }, { "answer_id": 13762097, "author": "Joanna Avalos", "author_id": 1885261, "author_profile": "https://Stackoverflow.com/users/1885261", "pm_score": 2, "selected": false, "text": " <button onClick=\"abrirOpen()\">Open Dialog</button>\n\n<script type=\"text/javascript\">\nvar $dialogo = $(\"<div></div>\").html(\"Aqui tu contenido(here your content)\").dialog({\n title: \"Dialogo de UI\",\n autoOpen: false,\n close: function(ev, ui){\n $(this).dialog(\"destroy\");\n }\n function abrirOpen(){\n $dialogo.dialog(\"open\");\n }\n});\n\n//**Esto funciona para mi... (this works for me)**\n</script>\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44973/" ]
366,856
<p>I'm about to put my head thru this sliding glass door. I can't figure out how to execute the following code in VB.NET to save my life. </p> <pre><code>private static void InitStructureMap() { ObjectFactory.Initialize(x =&gt; { x.AddRegistry(new DataAccessRegistry()); x.AddRegistry(new CoreRegistry()); x.AddRegistry(new WebUIRegistry()); x.Scan(scanner =&gt; { scanner.Assembly("RPMWare.Core"); scanner.Assembly("RPMWare.Core.DataAccess"); scanner.WithDefaultConventions(); }); }); } </code></pre>
[ { "answer_id": 366894, "author": "Kyle West", "author_id": 34133, "author_profile": "https://Stackoverflow.com/users/34133", "pm_score": 0, "selected": false, "text": "Private Shared Sub InitStructureMap()\nObjectFactory.Initialize(Function (ByVal x As IInitializationExpression) \n x.AddRegistry(New DataAccessRegistry)\n x.AddRegistry(New CoreRegistry)\n x.AddRegistry(New WebUIRegistry)\n x.Scan(Function (ByVal scanner As IAssemblyScanner) \n scanner.Assembly(\"RPMWare.Core\")\n scanner.Assembly(\"RPMWare.Core.DataAccess\")\n scanner.WithDefaultConventions\n End Function)\nEnd Function)\nEnd Sub\n Private Shared Sub InitStructureMap()\nObjectFactory.Initialize(Function (ByVal x As IInitializationExpression) _\n x.AddRegistry(New DataAccessRegistry) _\n x.AddRegistry(New CoreRegistry) _\n x.AddRegistry(New WebUIRegistry) _\n x.Scan(Function (ByVal scanner As IAssemblyScanner) _\n scanner.Assembly(\"RPMWare.Core\") _\n scanner.Assembly(\"RPMWare.Core.DataAccess\") _\n scanner.WithDefaultConventions() _\n End Function) _\nEnd Function) \nEnd Sub\n" }, { "answer_id": 366932, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "Private Shared Sub Foobar(x As IInitializationExpression)\n x.AddRegistry(New DataAccessRegistry)\n x.AddRegistry(New CoreRegistry)\n x.AddRegistry(New WebUIRegistry)\n x.Scan(AddressOf Barfoo)\nEnd Sub\n\nPrivate Shared Sub Barfoo(ByVal scanner As IAssemblyScanner) \n scanner.Assembly(\"RPMWare.Core\")\n scanner.Assembly(\"RPMWare.Core.DataAccess\")\n scanner.WithDefaultConventions\nEnd Sub\n\n' … '\nObjectFactory.Initialize(AddressOf Foobar)\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
366,857
<p>Remember the little div that shows up at the top of the page to notify us of things (like new badges)?</p> <p>I would like to implement something like that as well and am looking for some best practices or patterns.</p> <p>My site is an ASP.NET MVC app as well. Ideally the answers would include specifics like "put <em>this</em> in the master page" and "do <em>this</em> in the controllers".</p> <p>Just to save you from having to look yourself, this is the code I see from the welcome message you get when not logged in at stackoverflow.</p> <pre><code>&lt;div class="notify" style=""&gt; &lt;span&gt; First time at Stack Overflow? Check out the &lt;a href="/messages/mark-as-read?returnurl=%2ffaq"&gt;FAQ&lt;/a&gt;! &lt;/span&gt; &lt;a class="close-notify" onclick="notify.close(true)" title="dismiss this notification"&gt;×&lt;/a&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; $().ready(function() { notify.show(); }); &lt;/script&gt; </code></pre> <p>I'd like to add that I understand this perfectly and also understand the jquery involvement. I'm just interested in who puts the code into the markup and when ("who" as in which entities within an ASP.NET MVC app).</p> <p>Thanks!</p>
[ { "answer_id": 366864, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 2, "selected": false, "text": "onclick" }, { "answer_id": 878056, "author": "itsadok", "author_id": 7581, "author_profile": "https://Stackoverflow.com/users/7581", "pm_score": 4, "selected": false, "text": "<div id='message' style=\"display: none;\">\n <span>Hey, This is my Message.</span>\n <a href=\"#\" class=\"close-notify\">X</a>\n</div>\n #message {\n font-family:Arial,Helvetica,sans-serif;\n position:fixed;\n top:0px;\n left:0px;\n width:100%;\n z-index:105;\n text-align:center;\n font-weight:bold;\n font-size:100%;\n color:white;\n padding:10px 0px 10px 0px;\n background-color:#8E1609;\n}\n\n#message span {\n text-align: center;\n width: 95%;\n float:left;\n}\n\n.close-notify {\n white-space: nowrap;\n float:right;\n margin-right:10px;\n color:#fff;\n text-decoration:none;\n border:2px #fff solid;\n padding-left:3px;\n padding-right:3px\n}\n\n.close-notify a {\n color: #fff;\n}\n $(document).ready(function() {\n $(\"#message\").fadeIn(\"slow\");\n $(\"#message a.close-notify\").click(function() {\n $(\"#message\").fadeOut(\"slow\");\n return false;\n });\n});\n" }, { "answer_id": 1369953, "author": "Picflight", "author_id": 59941, "author_profile": "https://Stackoverflow.com/users/59941", "pm_score": 2, "selected": false, "text": "var notify = function() {\nvar d = false;\nvar e = 0;\nvar c = -1;\nvar f = \"m\";\nvar a = function(h) {\n if (!d) {\n $(\"#notify-container\").append('<table id=\"notify-table\"></table>');\n d = true\n }\n var g = \"<tr\" + (h.messageTypeId ? ' id=\"notify-' + h.messageTypeId + '\"' : \"\");\n g += ' class=\"notify\" style=\"display:none\"><td class=\"notify\">' + h.text;\n if (h.showProfile) {\n var i = escape(\"/users/\" + h.userId);\n g += ' See your <a href=\"/messages/mark-as-read?messagetypeid=' + h.messageTypeId + \"&returnurl=\" + i + '\">profile</a>.'\n }\n g += '</td><td class=\"notify-close\"><a title=\"dismiss this notification\" onclick=\"notify.close(';\n g += (h.messageTypeId ? h.messageTypeId : \"\") + ')\">&times;</a></td></tr>';\n $(\"#notify-table\").append(g)\n};\nvar b = function() {\n $.cookie(\"m\", \"-1\", {\n expires: 90,\n path: \"/\"\n })\n};\nreturn {\n showFirstTime: function() {\n if ($.cookie(\"new\")) {\n $.cookie(\"new\", \"0\", {\n expires: -1,\n path: \"/\"\n });\n b()\n }\n if ($.cookie(\"m\")) {\n return\n }\n $(\"body\").css(\"margin-top\", \"2.5em\");\n a({\n messageTypeId: c,\n text: 'First time here? Check out the <a onclick=\"notify.closeFirstTime()\">FAQ</a>!'\n });\n $(\".notify\").fadeIn(\"slow\")\n },\n showMessages: function(g) {\n for (var h = 0; h < g.length; h++) {\n a(g[h])\n }\n $(\".notify\").fadeIn(\"slow\");\n e = g.length\n },\n show: function(g) {\n $(\"body\").css(\"margin-top\", \"2.5em\");\n a({\n text: g\n });\n $(\".notify\").fadeIn(\"slow\")\n },\n close: function(g) {\n var i;\n var h = 0;\n if (g && g != c) {\n $.post(\"/messages/mark-as-read\", {\n messagetypeid: g\n });\n i = $(\"#notify-\" + g);\n if (e > 1) {\n h = parseInt($(\"body\").css(\"margin-top\").match(/\\d+/));\n h = h - (h / e)\n }\n } else {\n if (g && g == c) {\n b()\n }\n i = $(\".notify\")\n }\n i.children(\"td\").css(\"border-bottom\", \"none\").end().fadeOut(\"fast\", function() {\n $(\"body\").css(\"margin-top\", h + \"px\");\n i.remove()\n })\n },\n closeFirstTime: function() {\n b();\n document.location = \"/faq\"\n }\n }\n} ();\n" }, { "answer_id": 1441839, "author": "ckarbass", "author_id": 67719, "author_profile": "https://Stackoverflow.com/users/67719", "pm_score": 5, "selected": true, "text": "<div id=\"notify-container\"> </div>\n <script type=\"text/javascript\">\n $(function() { notify.showFirstTime(); });\n</script>\n <script type=\"text/javascript\">\n1\n2 var msgArray = [{\"id\":49611,\"messageTypeId\":8,\"text\":\"Welcome to Super User! Visit your \\u003ca href=\\\"/users/00000?tab=accounts\\\"\\u003eaccounts tab\\u003c/a\\u003e to associate with our other websites!\",\"userId\":00000,\"showProfile\":false}];\n3 $(function() { notify.showMessages(msgArray); });\n4\n</script>\n" }, { "answer_id": 4998208, "author": "Paul Mendoza", "author_id": 29277, "author_profile": "https://Stackoverflow.com/users/29277", "pm_score": 0, "selected": false, "text": "// Show a message bar at the top of the screen to tell the user that something is going on.\n// hideAfterMS - Optional argument. When supplied it hides the bar after a set number of milliseconds.\n function AdvancedMessageBar(hideAfterMS) {\n // Add an element to the top of the page to hold all of these bars.\n if ($('#barNotificationContainer').length == 0) \n { \n\n var barContainer = $('<div id=\"barNotificationContainer\" style=\"width: 100%; margin: 0px; padding: 0px;\"></div>');\n barContainer.prependTo('body');\n\n var barContainerFixed = $('<div id=\"barNotificationContainerFixed\" style=\"width: 100%; position: fixed; top: 0; left: 0;\"></div>');\n barContainerFixed.prependTo('body');\n }\n\n this.barTopOfPage = $('<div style=\"margin: 0px; background: orange; width: 100%; text-align: center; display: none; font-size: 15px; font-weight: bold; border-bottom-style: solid; border-bottom-color: darkorange;\"><table style=\"width: 100%; padding: 5px;\" cellpadding=\"0\" cellspacing=\"0\"><tr><td style=\"width: 20%; font-size: 10px; font-weight: normal;\" class=\"leftMessage\" ></td><td style=\"width: 60%; text-align: center;\" class=\"messageCell\"></td><td class=\"rightMessage\" style=\"width: 20%; font-size: 10px; font-weight: normal;\"></td></tr></table></div>');\n this.barTopOfScreen = this.barTopOfPage.clone();\n\n this.barTopOfPage.css(\"background\", \"transparent\");\n this.barTopOfPage.css(\"border-bottom-color\", \"transparent\");\n this.barTopOfPage.css(\"color\", \"transparent\");\n\n this.barTopOfPage.prependTo('#barNotificationContainer');\n this.barTopOfScreen.appendTo('#barNotificationContainerFixed');\n\n\n this.setBarColor = function (backgroundColor, borderColor) { \n\n this.barTopOfScreen.css(\"background\", backgroundColor);\n this.barTopOfScreen.css(\"border-bottom-color\", borderColor);\n };\n\n // Sets the message in the center of the screen.\n // leftMesage - optional\n // rightMessage - optional\n this.setMessage = function (message, leftMessage, rightMessage) {\n this.barTopOfPage.find('.messageCell').html(message);\n this.barTopOfPage.find('.leftMessage').html(leftMessage);\n this.barTopOfPage.find('.rightMessage').html(rightMessage);\n\n this.barTopOfScreen.find('.messageCell').html(message);\n this.barTopOfScreen.find('.leftMessage').html(leftMessage);\n this.barTopOfScreen.find('.rightMessage').html(rightMessage);\n };\n\n\n this.show = function() {\n this.barTopOfPage.slideDown(1000);\n this.barTopOfScreen.slideDown(1000);\n };\n\n this.hide = function () {\n this.barTopOfPage.slideUp(1000);\n this.barTopOfScreen.slideUp(1000);\n };\n\n var self = this; \n\n\n if (hideAfterMS != undefined) {\n setTimeout(function () { self.hide(); }, hideAfterMS);\n } \n}\n var mBar = new AdvancedMessageBar(10000);\nmBar.setMessage('This is my message', 'Left Message', 'Right Message');\nmBar.show();\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595/" ]
366,860
<p>From the man page on git-merge, there are a number of merge strategies you can use. </p> <ul> <li><p><em>resolve</em> - This can only resolve two heads (i.e. the current branch and another branch you pulled from) using 3-way merge algorithm. It tries to carefully detect criss-cross merge ambiguities and is considered generally safe and fast.</p></li> <li><p><em>recursive</em> - This can only resolve two heads using 3-way merge algorithm. When there are more than one common ancestors that can be used for 3-way merge, it creates a merged tree of the common ancestors and uses that as the reference tree for the 3-way merge. This has been reported to result in fewer merge conflicts without causing mis-merges by tests done on actual merge commits taken from Linux 2.6 kernel development history. Additionally this can detect and handle merges involving renames. This is the default merge strategy when pulling or merging one branch.</p></li> <li><p><em>octopus</em> - This resolves more than two-head case, but refuses to do complex merge that needs manual resolution. It is primarily meant to be used for bundling topic branch heads together. This is the default merge strategy when pulling or merging more than one branches.</p></li> <li><p><em>ours</em> - This resolves any number of heads, but the result of the merge is always the current branch head. It is meant to be used to supersede old development history of side branches.</p></li> <li><p><em>subtree</em> - This is a modified recursive strategy. When merging trees A and B, if B corresponds to a subtree of A, B is first adjusted to match the tree structure of A, instead of reading the trees at the same level. This adjustment is also done to the common ancestor tree.</p></li> </ul> <p>When should I specify something different than the default? What scenarios are each best for?</p>
[ { "answer_id": 366940, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 9, "selected": true, "text": "commit ae632e99ba0ccd0e9e06d09e8647659220d043b9\nMerge: f51262e... c9ce629... aa0f25d...\n git merge -X ours" }, { "answer_id": 10636464, "author": "thaddeusmt", "author_id": 164439, "author_profile": "https://Stackoverflow.com/users/164439", "pm_score": 5, "selected": false, "text": "fatal: git write-tree failed to write a tree" }, { "answer_id": 64950077, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "git merge -s ort\n $GIT_WORK_TREE $GIT_INDEX_FILE unpack_trees() read-tree -m -u newren gitster merge-ort merge-recursive.c newren gitster t6423, t6436 unpack_trees() unpack_trees() t6423 :FILENAME :FILENAME t6404, t6423 git rm git add recursive ort newren gitster merge tests merge-recursive.c unpack_trees() unpack_trees() merge-recursive.c git merge --abort git rebase --abort merge-recursive.c gitster newren gitster merge-ort record_conflicted_index_entries() checkout() CE_REMOVE CE_REMOVED-marked newren gitster merge-ort merge-recurisve.c RENAME_NORMAL process_renames() RENAME_NORMAL process_entry() merge-recursive.c handle_rename_normal() setup_rename_conflict_info() process_renames() conflict_info opt->priv->paths process_entry() merge_switch_to_result() newren gitster merge-ort call_depth > 0" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9594/" ]
366,861
<p>Pretty straightforward stuff, here -- I'm just not good enough with mysql to understand what it wants from me.</p> <p>I've got a short java test-case that opens a connection on mysql on my dev system but, when I try to put it to my server, it fails.</p> <p>Any help in tracking this down would be most appreciated.</p> <p>Thanks!</p> <p><strong>Test Code</strong></p> <pre><code>import java.util.*; import java.sql.*; public class mysqltest { static public void getDBConnection() { System.out.println ("Start of getDBConnection."); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "magnets_development"; String driver = "com.mysql.jdbc.Driver"; String userName = "*****"; // blanked for publication String password = "*****"; try { Class.forName (driver).newInstance(); System.out.println ("driver.newInstance gotten."); conn = DriverManager.getConnection (url+dbName, userName, password); System.out.println ("Connection gotten: " + conn + "."); Statement sql = conn.createStatement (); ResultSet results = sql.executeQuery ("use " + dbName + ";"); } catch (Exception ex) { System.out.println ("*** Got exception."); ex.printStackTrace(); } } public static void main(String args[]) { System.out.println ("Main started."); mysqltest.getDBConnection(); } } </code></pre> <p><strong>Dev System Output</strong> <em>(Expected/correct response)</em></p> <pre><code>olie$ java mysqltest Main started. Start of getDBConnection. Properties set. driver.newInstance gotten. Connection gotten: com.mysql.jdbc.Connection@c980c9. olie$ </code></pre> <p><strong>Server Output</strong> <em>(Error I'm trying to track-down)</em> (Some blank lines removed.)</p> <pre><code>mini$ java mysqltest Main started. Start of getDBConnection. Properties set. driver.newInstance gotten. *** Got exception. com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.net.ConnectException MESSAGE: Connection refused STACKTRACE: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432) at java.net.Socket.connect(Socket.java:520) at java.net.Socket.connect(Socket.java:470) at java.net.Socket.&lt;init&gt;(Socket.java:367) at java.net.Socket.&lt;init&gt;(Socket.java:209) at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256) at com.mysql.jdbc.MysqlIO.&lt;init&gt;(MysqlIO.java:271) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771) at com.mysql.jdbc.Connection.&lt;init&gt;(Connection.java:1555) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at java.sql.DriverManager.getConnection(DriverManager.java:525) at java.sql.DriverManager.getConnection(DriverManager.java:140) at mysqltest.getDBConnection(mysqltest.java:34) at mysqltest.main(mysqltest.java:49) ** END NESTED EXCEPTION ** Last packet sent to the server was 3 ms ago. at com.mysql.jdbc.Connection.createNewIO(Connection.java:2847) at com.mysql.jdbc.Connection.&lt;init&gt;(Connection.java:1555) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at java.sql.DriverManager.getConnection(DriverManager.java:525) at java.sql.DriverManager.getConnection(DriverManager.java:140) at mysqltest.getDBConnection(mysqltest.java:34) at mysqltest.main(mysqltest.java:49) mini$ </code></pre>
[ { "answer_id": 366869, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 0, "selected": false, "text": "properties.setProperty(\"socket\", \"/Applications/MAMP/tmp/mysql/mysql.sock\");\n" }, { "answer_id": 367455, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": -1, "selected": false, "text": "public SQL(String host, String port, String database, String userid, String password)\n {\n queryType = QUERYTYPE.Single;\n String driver = \"org.gjt.mm.mysql.Driver\";\n String url = \"jdbc:mysql://\" + host;\n if (port != null)\n {\n url += \":\" + port;\n }\n else\n {\n url += \":\" + defaultPort;\n }\n url += \"/\" + database;\n try\n {\n Class.forName(driver);\n\n connection = DriverManager.getConnection(url, userid, password);\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n" }, { "answer_id": 5576462, "author": "Patrick Smith", "author_id": 696133, "author_profile": "https://Stackoverflow.com/users/696133", "pm_score": 4, "selected": false, "text": "127.0.0.1 0.0.0.0 0.0.0.0 netstat -an | grep 3306" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34820/" ]
366,883
<p>Is there a way to avoid row deletion on an specific table using constrains?</p> <p>I'd like to (for example) deny row deletion if the id is 0,1 or 2</p> <p>This is in order to avoid users deleting master accounts for an application, and I'd like to avoid it even if someone tries it (by mistake) using sql directly.</p> <p>Thanks!</p> <p><strong>EDIT:</strong></p> <p>The whole idea of this question is not to touch the application. It's not a matter of security, I just need to know if It's possible to do what I asked with constrains or any other thing that SQL Server has (It does not need to be an standard db solution).</p> <p><strong>EDIT 2:</strong></p> <p>Code samples are very, very appreciated :D</p>
[ { "answer_id": 366918, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "CREATE TABLE NoKillI (\n id INT NOT NULL, FOREIGN KEY (id) REFERENCES Accounts(id) ON DELETE RESTRICT\n);\nINSERT INTO NoKillI (id) VALUES (0);\nINSERT INTO NoKillI (id) VALUES (1);\nINSERT INTO NoKillI (id) VALUES (2);\n Accounts NoKillI" }, { "answer_id": 367059, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 1, "selected": false, "text": "CREATE TRIGGER [dbo].[mytable_trd] ON [dbo].[mytable]\nWITH EXECUTE AS CALLER\nINSTEAD OF DELETE\nAS\nBEGIN\nSET NOCOUNT ON\nDECLARE @tn varchar(255)\nSELECT @tn = object_name(parent_obj)\nFROM sysobjects\nWHERE id = @@procid;\n\nSET @tn = 'Deletes not allowed for this table: ' + @tn;\n-- Add your code for checking the values from deleted\nIF EXISTS(select * from deleted where mycolumn = 1)\n RAISERROR (@tn, 16, 1) \nEND\nGO\n" }, { "answer_id": 367094, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "Tbl_Account Tbl_AccountMaster Tbl_Account.id_Account Tbl_AccountMaster Tbl_Account Tbl_AccountMaster" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
366,887
<p>On Stackers' recommendation, I have been reading Crockford's excellent <em>Javascript: The Good Parts</em>.</p> <p>It's a great book, but since so much of it is devoted to describing the best way to use Javascript's basic functionality, I'm not sure how I can put his advice into practice without duplicating the efforts of many other Javascript programmers.</p> <p>Take this passage, for example:</p> <blockquote> <p>When you make a new object, you can select the object that should be its prototype. The mechanism that Javascript provides to do this is messy and complex, but it can be significantly simplified. We will add a <code>create</code> method to the <code>Object</code> function. The <code>create</code> method creates a new object that uses an old object as its prototype.</p> <pre><code>if (typeof Object.create !== 'function') { Object.create = function(o) { var F = function () {}; F.prototype = o; return new F(); } </code></pre> </blockquote> <p>I could manually add this code to all my Javascript projects, but keeping track of everything would be a huge pain.</p> <p><strong>Are there any libraries that implement <em>The Good Part</em>'s recommendations and thereby save me the trouble of having to keep track of them (/ physically type them all out)?</strong></p>
[ { "answer_id": 367112, "author": "pottedmeat", "author_id": 2120, "author_profile": "https://Stackoverflow.com/users/2120", "pm_score": 1, "selected": false, "text": "dojo.delegate" }, { "answer_id": 11798237, "author": "feklee", "author_id": 282729, "author_profile": "https://Stackoverflow.com/users/282729", "pm_score": 0, "selected": false, "text": "Object.create()" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25068/" ]
366,889
<p>Does the SDK provide any way to change the brightness of the backlight, or turn it off temporarily? </p>
[ { "answer_id": 467029, "author": "Rhubarb", "author_id": 20479, "author_profile": "https://Stackoverflow.com/users/20479", "pm_score": 3, "selected": false, "text": "GSEventSetBacklightLevel();\n #import <GraphicsServices/GraphicsServices.h>\n" }, { "answer_id": 6938088, "author": "Raj", "author_id": 596503, "author_profile": "https://Stackoverflow.com/users/596503", "pm_score": 0, "selected": false, "text": "-(void)changeLight{\n\n GSEventSetBacklightLevel(float number);//number between 0.0 - 1.0\n}\n [self performSelector:@selector(changeLight) withObject:nil afterDelay:0.0];\n" }, { "answer_id": 9602515, "author": "hlynbech", "author_id": 1254760, "author_profile": "https://Stackoverflow.com/users/1254760", "pm_score": 0, "selected": false, "text": "void GSEventSetBacklightLevel(float level);\n GSEventSetBacklightLevel(-INFINITY);\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
366,896
<p>I've got a custom TObjectList descendant in Delphi 2009, and I'd like to play with its enumerator a bit and add some filtering functionality to the MoveNext method, to cause it to skip certain objects. MoveNext is called by DoMoveNext, which is a virtual method, so this shouldn't be difficult to override... except for one thing. The TEnumerator for TObjectList isn't its own class; it's declared as a nested type within the TObjectList declaration.</p> <p>Is there any simple way to override TEnumerator.DoMoveNext in my descendant class, or do I have to reimplement the whole TEnumerator? It's not a very big class, but I'd prefer to keep redundancies to a minimum if I can...</p>
[ { "answer_id": 366935, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": false, "text": "type\n TMasonEnumerator = class(TObjectList.TEnumerator)\n protected\n function DoMoveNext: Boolean; override;\n end;\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
366,897
<p>I've got a big file on which I'm opening a FileInputStream. This file contains some files each having an offset from the beginning and a size. Furthermore, I've got a parser that should evaluate such a contained file.</p> <pre><code>File file = ...; // the big file long offset = 1734; // a contained file's offset long size = 256; // a contained file's size FileInputStream fis = new FileInputStream(file ); fis.skip(offset); parse(fis, size); public void parse(InputStream is, long size) { // parse stream data and insure we don't read more than size bytes is.close(); } </code></pre> <p>I feel like this is no good practice. Is there a better way to do this, maybe using buffering?</p> <p>Furthermore, I feel like the skip() method slows the reading process a lot.</p>
[ { "answer_id": 366903, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 2, "selected": false, "text": "List<InputStream> getStreams(File inputFile)\n" }, { "answer_id": 366914, "author": "Esko", "author_id": 44523, "author_profile": "https://Stackoverflow.com/users/44523", "pm_score": 2, "selected": false, "text": "public void parse(File in, long size) {\n try {\n FileInputStream fis = new FileInputStream(in);\n // do file content handling here\n } finally {\n fis.close();\n }\n // do parsing here\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12463/" ]
366,913
<p>I'm learning Rails and it's going well so far. My biggest question at the moment is: how do I go about manually inserting a row into my database? I've got the scaffolding in place for creating rows of DataTypeOne, but I want a row for DataTypeTwo to be created when the form for DataTypeOne is submitted (and have it reference the id of DataTypeOne...but I think I can work this out on my own).</p> <p>Thanks in advance.</p>
[ { "answer_id": 366921, "author": "TonyLa", "author_id": 1295, "author_profile": "https://Stackoverflow.com/users/1295", "pm_score": 4, "selected": true, "text": "new_record = DataTypeTwo.new\nnew_record.save!\n" }, { "answer_id": 366930, "author": "Yaser Sulaiman", "author_id": 1173, "author_profile": "https://Stackoverflow.com/users/1173", "pm_score": 1, "selected": false, "text": "DataTypeTwo.create\n" }, { "answer_id": 366943, "author": "Cody Caughlan", "author_id": 25398, "author_profile": "https://Stackoverflow.com/users/25398", "pm_score": 2, "selected": false, "text": "class DataTypeTwo < ActiveRecord::Base\n belongs_to :data_type_one\nend\n\n\nclass DataTypeOne < ActiveRecord::Base\n has_one :data_type_two\nend\n one = DataTypeOne.create(...)\ntwo = DataTypeTwo.create(...)\ntwo.data_type_one = one\ntwo.save\n" }, { "answer_id": 367654, "author": "Ed Ruder", "author_id": 46093, "author_profile": "https://Stackoverflow.com/users/46093", "pm_score": 1, "selected": false, "text": "before_create after_create" }, { "answer_id": 383451, "author": "krishashok", "author_id": 47051, "author_profile": "https://Stackoverflow.com/users/47051", "pm_score": 1, "selected": false, "text": "./script/console (from your project folder)\n record = DataTypeTwo.new(:field1 => value1, :field2 => value2)\nrecord.save\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34795/" ]
366,915
<p>I have an articles table and a categories table. I want to fetch 7 articles for each category. Currently I have this but it's terrible slow on large tables so it's not really a solution:</p> <pre><code>SELECT id, title, categories_id, body, DATE_FORMAT(pubdate, "%d/%m/%y %H:%i") as pubdate FROM articles AS t WHERE ( SELECT COUNT(*) FROM articles WHERE t.categories_id = categories_id AND id&lt; t.id AND publish = 1 AND expires &gt; '2008-12-14 18:38:02' AND pubdate &lt;= '2008-12-14 18:38:02' ) &lt; 7 ORDER BY categories_id DESC </code></pre> <p>Using explain, it shows me it's doing a join type ALL &amp; REF. The select types are PRIMARY and DEPENDENT SUBQUERY .</p> <p>Is there a better solution?</p>
[ { "answer_id": 366939, "author": "Jennifer", "author_id": 22360, "author_profile": "https://Stackoverflow.com/users/22360", "pm_score": 0, "selected": false, "text": "SELECT categories_id FROM Categories\n SELECT \n id, \n title, \n ...etc.\nFROM articles\nwhere categories_id = 1 \n" }, { "answer_id": 366950, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 0, "selected": false, "text": "SELECT id, \n title, \n categories_id, \n body, \n DATE_FORMAT(pubdate, \"%d/%m/%y %H:%i\") as pubdate \nFROM articles A INNER JOIN articles B ON B.categories_ID = A.Categories_ID\nWHERE A.ID IN ( \n SELECT ID\n FROM Articles \n WHERE categories_id = A.categories_id \n AND publish = 1 \n AND expires > '2008-12-14 18:38:02' \n AND pubdate <= '2008-12-14 18:38:02' \n LIMIT 7\n ORDER BY Categories_ID DESC) \nORDER BY B.Categories_ID DESC\n" }, { "answer_id": 367013, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 1, "selected": false, "text": "SELECT categories_id, COUNT(1) \nFROM articles \nWHERE publish = 1 \n AND expires > '2008-12-14 18:38:02' \n AND pubdate <= '2008-12-14 18:38:02'\nGROUP BY categories_id\nHAVING COUNT(1) < 7\n SELECT \n c.id, c.title, c.id, a.body, \n DATEFORMAT(a.pubdate, \"%d/%m/%y %H:%i\") as pubdate \nFROM categories c \nJOIN articles a ON c.id = a.categories_id \nJOIN \n( \n SELECT DISTINCT categories_id \n FROM articles \n WHERE publish = 1 \n AND expires > '2008-12-14 18:38:02' \n AND pubdate <= '2008-12-14 18:38:02' \n GROUP BY categories_id \n HAVING COUNT(1) <= 7 \n) AS j ON c.id = j.categories_id \nORDER BY whatever \n" }, { "answer_id": 367111, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "SELECT a1.id, \n a1.title, \n a1.categories_id, \n a1.body, \n DATE_FORMAT(a1.pubdate, \"%d/%m/%y %H:%i\") as pubdate \nFROM articles AS a1\n LEFT OUTER JOIN articles AS a2\n ON (a1.categories_id = a2.categories_id AND \n (a1.pubdate < a2.pubdate OR (a1.pubdate = a2.pubdate AND a1.id < a2.id)))\nGROUP BY a1.id\nHAVING COUNT(*) < 7;\n id id pubdate ON (a1.categories_id = a2.categories_id AND a1.id < a2.id)\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46183/" ]
366,928
<p>I'm heavily using Cygwin (with <a href="http://en.wikipedia.org/wiki/PuTTY" rel="noreferrer">PuTTY </a> shell). But, it's quite tricky to invoke <code>cl.exe</code> (that is, the Visual C++ compiler toolchain) in the Cygwin Bash shell. Running <code>vcvars*.bat</code> in the Bash shell doesn't work obviously. I tried to migrate VC++'s environment variables to Cygwin, but it's not that easy.</p> <p>How do I run the VC++ compiler in Cygwin's Bash shell?</p>
[ { "answer_id": 366934, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 4, "selected": false, "text": "sh-3.2$ cl\nMicrosoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nusage: cl [ option... ] filename... [ /link linkoption... ]\n" }, { "answer_id": 374355, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "vsvars32.bat visual_studio.env sh \\ ; sh cygpath -au cygpath -aup commands .env cygpath -aw cygpath -aup commands visual_studio.env VS80COMNTOOLS=$(cygpath -aw '/cygdrive/c/Programmi/Microsoft Visual Studio 8/Common7/Tools/'); export VS80COMNTOOLS\nVSINSTALLDIR=$(cygpath -aw '/cygdrive/c/Programmi/Microsoft Visual Studio 8'); export VSINSTALLDIR\nVCINSTALLDIR=$(cygpath -aw '/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC'); export VCINSTALLDIR\nFrameworkDir=$(cygpath -aw '/cygdrive/c/WINDOWS/Microsoft.NET/Framework'); export FrameworkDir\nFrameworkVersion='v2.0.50727'; export FrameworkVersion\nFrameworkSDKDir=$(cygpath -aw '/cygdrive/c/Programmi/Microsoft Visual Studio 8/SDK/v2.0'); export FrameworkSDKDir\n\necho Setting environment for using Microsoft Visual Studio 2005 x86 tools.\n\nDevEnvDir=$(cygpath -aw '/cygdrive/c/Programmi/Microsoft Visual Studio 8/Common7/IDE'); export DevEnvDir\n\nPATH='/cygdrive/c/Programmi/Microsoft Visual Studio 8/Common7/IDE:/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/BIN:/cygdrive/c/Programmi/Microsoft Visual Studio 8/Common7/Tools:/cygdrive/c/Programmi/Microsoft Visual Studio 8/Common7/Tools/bin:/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/PlatformSDK/bin:/cygdrive/c/Programmi/Microsoft Visual Studio 8/SDK/v2.0/bin:/cygdrive/c/WINDOWS/Microsoft.NET/Framework/v2.0.50727:/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/VCPackages':$PATH\nINCLUDE=$(cygpath -awp '/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/ATLMFC/INCLUDE:/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/INCLUDE:/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/PlatformSDK/include:/cygdrive/c/Programmi/Microsoft Visual Studio 8/SDK/v2.0/include'); export INCLUDE\nLIB=$(cygpath -awp '/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/ATLMFC/LIB:/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/LIB:/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/PlatformSDK/lib:/cygdrive/c/Programmi/Microsoft Visual Studio 8/SDK/v2.0/lib'); export LIB\nLIBPATH=$(cygpath -awp '/cygdrive/c/WINDOWS/Microsoft.NET/Framework/v2.0.50727:/cygdrive/c/Programmi/Microsoft Visual Studio 8/VC/ATLMFC/LIB'); export LIBPATH\n" }, { "answer_id": 374411, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 5, "selected": false, "text": "call \"%VS80COMNTOOLS%vsvars32.bat\" >NUL:\n function run_with_bat()\n{\n batfile=$1; shift\n tmpfile=\"$TMP/tmp$$.bat\"\n echo \"@echo off\" > $tmpfile\n echo \"call \\\"%$batfile%vsvars32.bat\\\" >NUL:\" >> $tmpfile\n echo \"bash -c \\\"%*\\\"\" >> $tmpfile\n cmd /c `cygpath -m \"$tmpfile\"` \"$@\"\n status=$?\n rm -f $tmpfile\n return $status\n}\n\nfunction run_vs9()\n{\n run_with_bat VS90COMNTOOLS \"$@\"\n}\n\nfunction run_vs8()\n{\n run_with_bat VS80COMNTOOLS \"$@\"\n}\n $ run_vs8 cl\nMicrosoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86\nCopyright (C) Microsoft Corporation. All rights reserved. \n\nusage: cl [ option... ] filename... [ /link linkoption... ]\n$ run_vs9 cl\nMicrosoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nusage: cl [ option... ] filename... [ /link linkoption... ]\n" }, { "answer_id": 1005379, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "vcvars32.bat Cygwin.bat @echo off\nD:\nchdir D:\\cygwin\\bin\n\"%VS71COMNTOOLS%\\vsvars32.bat\" && bash --login -i\n" }, { "answer_id": 1097153, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "\"`cygpath -ua \"$VS80COMNTOOLS/vsvars32.bat\"`\" > NUL" }, { "answer_id": 3272301, "author": "Brooks Moses", "author_id": 102916, "author_profile": "https://Stackoverflow.com/users/102916", "pm_score": 4, "selected": false, "text": "# These lines will be installation-dependent.\nexport VSINSTALLDIR='C:\\Program Files\\Microsoft Visual Studio 10.0\\'\nexport WindowsSdkDir='C:\\Program Files\\Microsoft SDKs\\Windows\\v7.0A\\'\nexport FrameworkDir='C:\\WINDOWS\\Microsoft.NET\\Framework\\'\nexport FrameworkVersion=v4.0.30319\nexport Framework35Version=v3.5\n\n# The following should be largely installation-independent.\nexport VCINSTALLDIR=\"$VSINSTALLDIR\"'VC\\'\nexport DevEnvDir=\"$VSINSTALLDIR\"'Common7\\IDE\\'\n\nexport FrameworkDIR32=\"$FrameworkDir\"\nexport FrameworkVersion32=\"$FrameworkVersion\"\n\nexport INCLUDE=\"${VCINSTALLDIR}INCLUDE;${WindowsSdkDir}include;\"\nexport LIB=\"${VCINSTALLDIR}LIB;${WindowsSdkDir}lib;\"\nexport LIBPATH=\"${FrameworkDir}${FrameworkVersion};\"\nexport LIBPATH=\"${LIBPATH}${FrameworkDir}${Framework35Version};\"\nexport LIBPATH=\"${LIBPATH}${VCINSTALLDIR}LIB;\"\n\nc_VSINSTALLDIR=`cygpath -ua \"$VSINSTALLDIR\\\\\\\\\"`\nc_WindowsSdkDir=`cygpath -ua \"$WindowsSdkDir\\\\\\\\\"`\nc_FrameworkDir=`cygpath -ua \"$FrameworkDir\\\\\\\\\"`\n\nexport PATH=\"${c_WindowsSdkDir}bin:$PATH\"\nexport PATH=\"${c_WindowsSdkDir}bin/NETFX 4.0 Tools:$PATH\"\nexport PATH=\"${c_VSINSTALLDIR}VC/VCPackages:$PATH\"\nexport PATH=\"${c_FrameworkDir}${Framework35Version}:$PATH\"\nexport PATH=\"${c_FrameworkDir}${FrameworkVersion}:$PATH\"\nexport PATH=\"${c_VSINSTALLDIR}Common7/Tools:$PATH\"\nexport PATH=\"${c_VSINSTALLDIR}VC/BIN:$PATH\"\nexport PATH=\"${c_VSINSTALLDIR}Common7/IDE/:$PATH\"\n" }, { "answer_id": 8797390, "author": "Charles Grunwald", "author_id": 1017636, "author_profile": "https://Stackoverflow.com/users/1017636", "pm_score": 0, "selected": false, "text": "(void)cygwin_conv_to_posix_path(s.c_str(), buf);\n (void)cygwin_conv_path(CCP_WIN_A_TO_POSIX, (const void *)s.c_str(), (void *)buf, (size_t)MAX_PATH);\n (void)cygwin_conv_to_win32_path(s.c_str(), buf);\n (void)cygwin_conv_path(CCP_POSIX_TO_WIN_A, (const void *)s.c_str(), (void *)buf, (size_t)MAX_PATH);\n" }, { "answer_id": 15335686, "author": "Igor Mikushkin", "author_id": 380247, "author_profile": "https://Stackoverflow.com/users/380247", "pm_score": 3, "selected": false, "text": "function run_in_vs_env\n{\n eval vssetup=\"\\$$1\\\\vsvars32.bat\"\n cmd /Q /C call \"$vssetup\" \"&&\" \"${@:2}\"\n}\n\nfunction run_vs11\n{\n run_in_vs_env VS110COMNTOOLS \"$@\"\n}\n\nfunction run_vs10\n{\n run_in_vs_env VS100COMNTOOLS \"$@\"\n}\n export -f run_in_vs_env\nexport -f run_vs11\nexport -f run_vs10\n run_vs11 cl\n" }, { "answer_id": 53236894, "author": "truthadjustr", "author_id": 2856202, "author_profile": "https://Stackoverflow.com/users/2856202", "pm_score": 1, "selected": false, "text": "msbuild g++ visual studio cl msbuild *.vcxproj ls -l ~/bin/msbuild\nlrwxrwxrwx 1 johnny Domain Users 102 Sep 4 04:25 /home/johnny/bin/msbuild -> /cygdrive/c/Program Files (x86)/Microsoft Visual Studio/2017/Professional/MSBuild/15.0/Bin/MSBuild.exe\n builddebug (){\n [ $# -eq 0 ] && return 1;\n msbuild /m /p:Configuration=Debug /p:Platform=Win32 \"$1\"\n}\n g++ Visual Studio 2017 msbuild cl" }, { "answer_id": 57796999, "author": "mwag", "author_id": 3160967, "author_profile": "https://Stackoverflow.com/users/3160967", "pm_score": 0, "selected": false, "text": "set > c:\\temp\\cl.env source awk < /cygdrive/c/temp/cl.env -F= '{ if($1 !~ \")\") print \"export \" $1 \"=\\x27\" $2 \"\\x27\" }' > cl.source\n TEMP='C:\\Temp' source cl.source" }, { "answer_id": 58519502, "author": "ericcurtin", "author_id": 2682012, "author_profile": "https://Stackoverflow.com/users/2682012", "pm_score": 0, "selected": false, "text": "cl() {\n tmpfile=\"/tmp/tmp$$.bat\"\n echo \"@echo off\" > $tmpfile\n echo \"call \\\"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Auxiliary\\Build\\vcvars64.bat\\\" >NUL:\" >> $tmpfile\n echo \"bash -c \\\"cl %*\\\"\" >> $tmpfile\n cmd /c `cygpath -m \"$tmpfile\"` \"$@\"\n status=$?\n rm -f $tmpfile\n return $status\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46185/" ]
366,938
<p>I have an NSView subclass which has property which I want to be bindable. I've implemented the following in the subclass:</p> <p>myView.h:</p> <pre><code>@property (readwrite, retain) NSArray *representedObjects; </code></pre> <p>myView.m:</p> <pre><code>@synthesize representedObjects; +(void)initialize { [self exposeBinding: @&quot;representedObjects&quot;]; } -(void)bind:(NSString *)binding toObject:(id)observableController withKeyPath:(NSString *)keyPath options:(NSDictionary *)options { if ([binding isEqualToString:@&quot;representedObjects&quot;]) { [observableController addObserver: self forKeyPath:@&quot;arrangedObjects&quot; options:NSKeyValueChangeNewKey context:nil]; } else { [super bind: binding toObject:observableController withKeyPath:keyPath options: options]; } } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@&quot;arrangedObjects&quot;]) { [self setRepresentedObjects: [object arrangedObjects]]; } } </code></pre> <p>I then create the binding to an arrayController in <code>-[AppController awakeFromNib]</code>:</p> <pre><code>[myView bind:@&quot;representedObjects&quot; toObject:arrayController withKeyPath:@&quot;arrangedObjects&quot; options: nil]; </code></pre> <p>Is this the correct way of implementing binding? It involves a lot of boiler plate code which makes me think that I'm doing something wrong.</p> <p>I thought that NSObject would automagically implement what I have done manually in <code>-bind:toObject:withKeyPath:options:</code> but this doesn't seem to be the case. If I comment out my <code>-bind:toObject:withKeyPath:options:</code> the setRepresentedObjects method is never called.</p> <p>Additional info: I've done some more investigating and have reached the conclusion that my original approach is correct and you do have to over ride <code>-bind:toObject:withKeyPath:options:</code>. Here's a quote from <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/HowDoBindingsWork.html#//apple_ref/doc/uid/20002373" rel="nofollow noreferrer">Cocoa Bindings Programming Topics: How Do Bindings Work?</a>:</p> <blockquote> <p>In its bind:toObject:withKeyPath:options: method an object must as a minimum do the following:</p> <ul> <li>Determine which binding is being set</li> <li>Record what object it is being bound to using what keypath and with what options</li> <li>Register as an observer of the keypath of the object to which it is bound so that it receives notification of changes</li> </ul> <p>The code sample in Listing 2 shows a partial implementation of Joystick’s bind:toObject:withKeyPath:options: method dealing with just the angle binding.</p> <p>Listing 2 Partial implementation of the bind:toObject:withKeyPath:options method for the Joystick class:</p> <blockquote> <pre><code>static void *AngleBindingContext = (void *)@&quot;JoystickAngle&quot;; - (void)bind:(NSString *)binding toObject:(id)observableObject withKeyPath:(NSString *)keyPath options:(NSDictionary *)options { // Observe the observableObject for changes -- note, pass binding identifier // as the context, so you get that back in observeValueForKeyPath:... // This way you can easily determine what needs to be updated. if ([binding isEqualToString:@&quot;angle&quot;]) { [observableObject addObserver:self forKeyPath:keyPath options:0 context:AngleBindingContext]; // Register what object and what keypath are // associated with this binding observedObjectForAngle = [observableObject retain]; observedKeyPathForAngle = [keyPath copy]; // Record the value transformer, if there is one angleValueTransformer = nil; NSString *vtName = [options objectForKey:@&quot;NSValueTransformerName&quot;]; if (vtName != nil) { angleValueTransformer = [NSValueTransformer valueTransformerForName:vtName]; } } // Implementation continues... </code></pre> </blockquote> </blockquote> <p>This clearly shows that the Joystick class (which is an NSView subclass) needs to override <code>-bind:toObject:withKeyPath:options:</code>.</p> <p>I find this surprising. I was skeptical of this conclusion as I have found no other code samples that do this. However, as the offical Apple documentation says I should over ride <code>-bind:toObject:withKeyPath:options:</code> I conclude that it is the correct approach.</p> <p>I would be very happy if someone could prove me wrong!</p>
[ { "answer_id": 423175, "author": "Rob Keniger", "author_id": 50122, "author_profile": "https://Stackoverflow.com/users/50122", "pm_score": 0, "selected": false, "text": "-bind:toObject:withKeyPath:options:" }, { "answer_id": 7394273, "author": "paulmelnikow", "author_id": 893113, "author_profile": "https://Stackoverflow.com/users/893113", "pm_score": 1, "selected": false, "text": "bind: exposeBinding: @interface MyView : NSView {\n NSArray *_representedObjects;\n}\n\n// IBOutlet is not required for bindings, but by adding it you can ALSO use\n// an outlet\n@property (readonly, retain) IBOutlet NSArray *representedObjects;\n\n@end\n + (void)initialize {\n [self exposeBinding:@\"representedObjects\"];\n}\n\n// Use a custom setter, because presumably, the view needs to re-draw\n- (void)setRepresentedObjects:(NSArray *)representedObjects {\n [self willChangeValueForKey:@\"representedObjects\"];\n // Based on automatic garbage collection\n _representedObjects = representedObjects;\n [self didChangeValueForKey:@\"representedObjects\"];\n\n [self setNeedsDisplayInRect:[self visibleRect]];\n}\n [myView bind:@\"representedObjects\" toObject:arrayController withKeyPath:@\"arrangedObjects\" options: nil];\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,955
<p>how do I bind a <code>std::ostream</code> to either <code>std::cout</code> or to an <code>std::ofstream</code> object, depending on a certain program condition? Although this invalid for many reasons, I would like to achieve something that is semantically equivalent to the following:</p> <pre><code>std::ostream out = condition ? &amp;std::cout : std::ofstream(filename); </code></pre> <p>I've seen some examples that are not exception-safe, such as one from <a href="http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html" rel="noreferrer">http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html</a>:</p> <pre><code>int main(int argc, char *argv[]) { std::ostream* fp; //1 if (argc &gt; 1) fp = new std::ofstream(argv[1]); //2 else fp = &amp;std::cout //3 *fp &lt;&lt; "Hello world!" &lt;&lt; std::endl; //4 if (fp!=&amp;std::cout) delete fp; } </code></pre> <p>Does anyone know a better, exception-safe solution?</p>
[ { "answer_id": 366967, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 5, "selected": false, "text": "void process(std::ostream &os);\n\nint main(int argc, char *argv[]) {\n std::ostream* fp = &cout;\n std::ofstream fout;\n if (argc > 1) {\n fout.open(argv[1]);\n fp = &fout;\n }\n process(*fp);\n}\n" }, { "answer_id": 366969, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": true, "text": "std::streambuf * buf;\nstd::ofstream of;\n\nif(!condition) {\n of.open(\"file.txt\");\n buf = of.rdbuf();\n} else {\n buf = std::cout.rdbuf();\n}\n\nstd::ostream out(buf);\n std::cout std::ofstream file(\"file.txt\");\nstd::streambuf * old = std::cout.rdbuf(file.rdbuf());\n// do here output to std::cout\nstd::cout.rdbuf(old); // restore\n struct opiped {\n opiped(std::streambuf * buf, std::ostream & os)\n :os(os), old_buf(os.rdbuf(buf)) { }\n ~opiped() { os.rdbuf(old_buf); }\n\n std::ostream& os;\n std::streambuf * old_buf;\n};\n\nint main() {\n // or: std::filebuf of; \n // of.open(\"file.txt\", std::ios_base::out);\n std::ofstream of(\"file.txt\");\n {\n // or: opiped raii(&of, std::cout);\n opiped raii(of.rdbuf(), std::cout);\n std::cout << \"going into file\" << std::endl;\n }\n std::cout << \"going on screen\" << std::endl;\n}\n" }, { "answer_id": 5521331, "author": "Tony Clifton", "author_id": 688630, "author_profile": "https://Stackoverflow.com/users/688630", "pm_score": 3, "selected": false, "text": "std::ofstream of;\nstd::ostream& out = condition ? std::cout : of.open(filename);\n" }, { "answer_id": 47557687, "author": "user32849", "author_id": 4028182, "author_profile": "https://Stackoverflow.com/users/4028182", "pm_score": -1, "selected": false, "text": "std::ostream& output = (condition)?*(new std::ofstream(filename)):std::cout;\n" }, { "answer_id": 56299446, "author": "levir chianca", "author_id": 11552490, "author_profile": "https://Stackoverflow.com/users/11552490", "pm_score": -1, "selected": false, "text": "int main(int argc, char const *argv[]){ \n\n std::ofstream outF;\n if (argc > 1)\n {\n outF = std::ofstream(argv[1], std::ofstream::out); \n }\n\n std::ostream& os = (argc > 1)? outF : std::cout;\n}\n" }, { "answer_id": 62491762, "author": "Kaan Sancak", "author_id": 12202733, "author_profile": "https://Stackoverflow.com/users/12202733", "pm_score": 2, "selected": false, "text": "struct noop {\n void operator()(...) const {}\n};\n std::shared_ptr<std::ostream> of;\nif (condition) {\n of.reset(new std::ofstream(filename, std::ofstream::out));\n} else {\n of.reset(&std::cout, noop());\n}\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1170277/" ]
366,968
<p>I have been searching for a way to insert linebreaks in my code for when I view my source. I am not looking for <code>&lt;br /&gt;</code></p> <p>Something like the PHP equiv to <code>\n</code></p> <p>Any ideas on how to do this in ASP? I will be placing this inside a string.</p>
[ { "answer_id": 366979, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 6, "selected": true, "text": "Response.Write \"hello\" & vbCrLf & \"world\"\n output = \"hello\\nworld\"\noutput = Replace(output, \"\\n\", vbCrLf)\nResponse.Write output\n" }, { "answer_id": 367023, "author": "Taptronic", "author_id": 14728, "author_profile": "https://Stackoverflow.com/users/14728", "pm_score": 2, "selected": false, "text": "\\n <BR> Response.Write \"First Line Of Text<br>Second Line Of Text<br>Third line Of Text\"\n" }, { "answer_id": 31428097, "author": "Programster", "author_id": 1385833, "author_profile": "https://Stackoverflow.com/users/1385833", "pm_score": 1, "selected": false, "text": "\"\\n\" \\n chr(10) CrLf" }, { "answer_id": 42564108, "author": "Amin", "author_id": 6327541, "author_profile": "https://Stackoverflow.com/users/6327541", "pm_score": 0, "selected": false, "text": "Response.Write \"<BR>\"" }, { "answer_id": 52109493, "author": "user1939189", "author_id": 1939189, "author_profile": "https://Stackoverflow.com/users/1939189", "pm_score": 0, "selected": false, "text": "<br/> <%@ Language=\"VBScript\" %>\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <title></title>\n\n </head>\n<body>\n <%\n dim i\n for i=0 to 10\n response.write(i & \"<br/>\")\n next \n %>\n</body>\n" }, { "answer_id": 73013937, "author": "Rafael F.", "author_id": 5370166, "author_profile": "https://Stackoverflow.com/users/5370166", "pm_score": 0, "selected": false, "text": "vbCrLf vbCr vbLf vbCrLf = char(13) & char(10) 'Same as PHP \\r\\n\nvbCr = char(13) 'Same as PHP \\r\nvbLf = char(10) 'Same as PHP \\n\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
366,980
<p>What are the main differences among them? And in which typical scenarios is it better to use each language?</p>
[ { "answer_id": 367014, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 10, "selected": true, "text": "sed awk perl python sed ed awk sed awk a2p s2p awk sed awk sed" }, { "answer_id": 367082, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": false, "text": "subprocess" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44100/" ]
366,998
<p><em>Javascript: The Good Parts</em> is a great book. Often I find myself reading passages like the following from the perspective of a language designer:</p> <blockquote> <p><code>undefined</code> and <code>NaN</code> are not constants. They are global variables, and you can change their values. This should not be possible, and yet it is. Don't do it.</p> </blockquote> <p>Takeaways:</p> <ol> <li>Don't change the value of <code>undefined</code> in my Javascript code.</li> <li>When designing a language, make its equivalent of <code>undefined</code> immutable.</li> </ol> <p>A different more subtle example would be "<code>for in</code> shouldn't enumerate over prototype properties".</p> <p>I want a book at talks about these issues of language design outside of the context of a particular language.</p> <p><strong>If you were trying to design the "perfect" OO language, what books would you read for guidance?</strong></p>
[ { "answer_id": 367472, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "Perl6 Perl6 infix:<+> infix:«+» infix:<<+>> infix:{'+'} infix:{\"+\"} sub postfix:<!> ($n) { [*] 1..$n }\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/366998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25068/" ]
367,007
<p>On the page <a href="http://tesselaar.com/gallery/" rel="nofollow noreferrer">http://tesselaar.com/gallery/</a> I have a heading (level 1) at the top of the page "Photo Gallery" that doesn't display in IE7 and I can't work out why.</p> <p>It follows the same CSS and page-structure as the rest of the site, the only difference being there is an element being floated to the right immediately after.</p> <p>Any insight would be appreciated.</p>
[ { "answer_id": 367790, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 2, "selected": true, "text": "text-align: right;" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/367007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14979/" ]
367,020
<p>What's the best way to animate a background image sliding to the left, and looping it? Say I've got a progress bar with a background I want to animate when it's active (like in Gnome or OS X).</p> <p>I've been playing with the <code>$(...).animate()</code> function and trying to modify the relevant CSS property, but I keep hitting a brick wall when trying to figure out how to modify the <code>background-position</code> property. I can't just increment its value, and I'm not sure if this is even the best approach.</p> <p>Any help appreciated!</p>
[ { "answer_id": 367028, "author": "Wilco", "author_id": 5291, "author_profile": "https://Stackoverflow.com/users/5291", "pm_score": 5, "selected": true, "text": "function animateBar(self) {\n // Setup\n var bar = self.element.find('.ui-progress-bar');\n\n bar.css('background-position', '0px 0px');\n\n bar.animate({\n backgroundPosition: '-20px 0px'\n }, 1000, 'linear', function() {\n animateBar(self);\n });\n}\n" }, { "answer_id": 4708792, "author": "Markus Amalthea Magnuson", "author_id": 11403, "author_profile": "https://Stackoverflow.com/users/11403", "pm_score": 1, "selected": false, "text": "$(\"#progress\").css(\"background-image\", \"progress.gif\");\n" }, { "answer_id": 6118394, "author": "Fresheyeball", "author_id": 501187, "author_profile": "https://Stackoverflow.com/users/501187", "pm_score": 2, "selected": false, "text": "$.fn.extend({\n animateBar: function(){\n $(this).find('.ui-progress-bar').css('background-position', '0px 0px');\n $(this).find('.ui-progress-bar').animate({\n backgroundPosition: '-20px 0px'\n }, 1000, 'linear', function() {\n animateBar(self);\n });\n }\n});\n $(this).animateBar(); \n animateBar( $(this) );\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/367020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
367,029
<p>Most of the time, the errors you get from your model properties will happen when you're saving data. For instance, if you try saving a string as an IntegerProperty, that will result in an error.</p> <p>The one exception (no pun intended) is ReferenceProperty. If you have lots of references and you're not completely careful about leaving in bad references, it's common to be greeted with an error like "TemplateSyntaxError: Caught an exception while rendering: ReferenceProperty failed to be resolved".</p> <p>And this is if there's only one bad reference in the view. D'oh. </p> <p>I could write a try/except block to try to access all the reference properties and delete them if an exception is raised, but this functionality could surely be useful to many other developers if there was a more generic method than the one I'd be capable of writing. I imagine it would take a list of model types and try to access each reference property of each entity in each model, setting the property to None if an exception is raised.</p> <p>I'll see if I can do this myself, but it would definitely help to have some suggestions/snippets to get me started.</p>
[ { "answer_id": 2152183, "author": "Mehmet", "author_id": 565109, "author_profile": "https://Stackoverflow.com/users/565109", "pm_score": 0, "selected": false, "text": "obj1 = db.get(obj2.reference)\n\nif not obj1:\n # Referenced entity was deleted.\n" } ]
2008/12/14
[ "https://Stackoverflow.com/questions/367029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9106/" ]