qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
256,255
<p>I read all over the place about how Spring encourages you to use interfaces in your code. I don't see it. There is no notion of interface in your spring xml configuration. What part of Spring actually encourages you to use interfaces (other than the docs)?</p>
[ { "answer_id": 256274, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 2, "selected": false, "text": "org.springframework.core.io.Resource org.springframework.core.io.ClassPathResource org.springframework.core.io.FileSystemResource org.springframework.core.io.UrlResource" }, { "answer_id": 256329, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 5, "selected": false, "text": "public class Copy {\n private Keyboard keyboard = new Keyboard(); // concrete dependency\n private Printer printer = new Printer(); // concrete dependency\n public void copy() {\n for (int c = keyboard.read(); c != KeyBoard.EOF) {\n printer.print(c);\n }\n }\n}\n public class Copy {\n private Reader reader; // any dependency satisfying the reader interface will work\n private Writer writer; // any dependency satisfying the writer interface will work\n public void copy() {\n for (int c = reader.read(); c != Reader.EOF) {\n writer.write(c);\n }\n }\n public Copy(Reader reader, Writer writer) {\n this.reader = reader;\n this.writer = writer;\n }\n}\n Copy Reader Writer <bean id=\"copy\" class=\"Copy\">\n <constructor-arg ref=\"reader\" />\n <constructor-arg ref=\"writer\" />\n</bean>\n\n<bean id=\"reader\" class=\"KeyboardReader\" />\n<bean id=\"writer\" class=\"PrinterWriter\" />\n <bean id=\"reader\" class=\"RemoteDeviceReader\" />\n<bean id=\"writer\" class=\"DatabaseWriter\" />\n" }, { "answer_id": 256540, "author": "Sean Schulte", "author_id": 33380, "author_profile": "https://Stackoverflow.com/users/33380", "pm_score": 6, "selected": true, "text": "Analyzer DefaultAnalyzer DummyAnalyzer PageByPageAnalyzer" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22063/" ]
256,264
<p>The symptom of the problem looks like "[0m[27m[24m[J[34;1" which on a terminal translates into the color blue.</p> <p>-A </p>
[ { "answer_id": 256393, "author": "cefstat", "author_id": 19155, "author_profile": "https://Stackoverflow.com/users/19155", "pm_score": 0, "selected": false, "text": "case $TERM in\nxterm-color)\nexport PS1='\\[\\e]0;\\W\\007\\]\\[\\e[34;1m\\]\\W\\[\\e[0m\\]\\$ '\n;;\n*)\nexport PS1='\\W\\$ '\n;;\nesac\n" }, { "answer_id": 256399, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 5, "selected": false, "text": ".emacs (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)\n" }, { "answer_id": 256894, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "alias ls=ls unset LS_COLORS ~/.emacs_{bash,tsch,whatever-your-shell-is-called} ~/.emacs_shellname shellname ~/.emacs_bash ~/.emacs.d/init_shellname.sh" }, { "answer_id": 264241, "author": "Setjmp", "author_id": 30636, "author_profile": "https://Stackoverflow.com/users/30636", "pm_score": 3, "selected": true, "text": ";; shell-mode\n(defun sh ()\n (interactive)\n (ansi-term \"/bin/zsh\"))\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30636/" ]
256,267
<p>I have a windows service connecting to a SqlServer database on the local box. This works fine most all the time. At a large customer, however, the database connectivity gets corrupted for some rare and unknown reason. When this happens, calls to DbDataAdapter.Fill return a DataSet with a different number of columns than in the select command passed in (validated by trace logs showing the sql expected, and the number of columns returned). For the first few errored DataSets it appears the adapter instance is returning results from the previous query. This is happening even though the adapter objects are unique instances, and the connection/adapter creation calls are thread protected (as DbProviderFactory is not thread safe).</p> <p>Has anyone experience this or something similar? Does anyone know what could cause this? At this moment in time, I'm having a hard time thinking up new ideas for a cause of this.</p>
[ { "answer_id": 256393, "author": "cefstat", "author_id": 19155, "author_profile": "https://Stackoverflow.com/users/19155", "pm_score": 0, "selected": false, "text": "case $TERM in\nxterm-color)\nexport PS1='\\[\\e]0;\\W\\007\\]\\[\\e[34;1m\\]\\W\\[\\e[0m\\]\\$ '\n;;\n*)\nexport PS1='\\W\\$ '\n;;\nesac\n" }, { "answer_id": 256399, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 5, "selected": false, "text": ".emacs (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)\n" }, { "answer_id": 256894, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "alias ls=ls unset LS_COLORS ~/.emacs_{bash,tsch,whatever-your-shell-is-called} ~/.emacs_shellname shellname ~/.emacs_bash ~/.emacs.d/init_shellname.sh" }, { "answer_id": 264241, "author": "Setjmp", "author_id": 30636, "author_profile": "https://Stackoverflow.com/users/30636", "pm_score": 3, "selected": true, "text": ";; shell-mode\n(defun sh ()\n (interactive)\n (ansi-term \"/bin/zsh\"))\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18313/" ]
256,277
<p>"C Interfaces and Implementations" shows some interesting usage patterns for data structures, but I am sure there are others out there.</p> <p><a href="https://rads.stackoverflow.com/amzn/click/com/0201498413" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Interfaces-Implementations-Techniques-Addison-Wesley-Professional/dp/0201498413</a></p>
[ { "answer_id": 256440, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "#include \"header.h\"\n #ifndef HEADER_H_INCLUDED\n#define HEADER_H_INCLUDED\n...operational body of header.h...\n#endif /* HEADER_H_INCLUDED */\n #ifndef HEADER_H_INCLUDED\n#include \"header.h\"\n#endif /* HEADER_H_INCLUDED */\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30636/" ]
256,282
<p>On <a href="http://andrew.hedges.name/blog/" rel="nofollow noreferrer">my blog</a>, I display in the right nav the 10 most popular articles in terms of page hits. Here's how I get that:</p> <pre><code>SELECT * FROM entries WHERE is_published = 1 ORDER BY hits DESC, created DESC LIMIT 10 </code></pre> <p>What I would like to do is show the top 10 in terms of page hits <em>per day.</em> I'm using MySQL. Is there a way I can do this in the database?</p> <p>BTW, The <code>created</code> field is a datetime.</p> <p>UPDATE: I think I haven't made myself clear. What I want is for the blog post with 10,000 hits that was posted 1,000 days ago to have the same popularity as the blog post with 10 hits that was posted 1 day ago. In pseudo-code:</p> <pre><code>ORDER BY hits / days since posting </code></pre> <p>...where <code>hits</code> is just an int that is incremented each time the blog post is viewed.</p> <p>OK, here's what I'm going to use:</p> <pre><code>SELECT *, AVG( hits / DATEDIFF(NOW(), created) ) AS avg_hits FROM entries WHERE is_published = 1 GROUP BY id ORDER BY avg_hits DESC, hits DESC, created DESC LIMIT 10 </code></pre> <p>Thanks, Stephen! (I love this site...)</p>
[ { "answer_id": 256302, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 4, "selected": true, "text": "SELECT *, AVG(hits / DATEDIFF(NOW(), created)) as avg_hits\nFROM entries\nWHERE is_published = 1\nGROUP BY id\nORDER BY avg_hits DESC\nLIMIT 10\n" }, { "answer_id": 256326, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": false, "text": "if article_data['hits_day_current'] == datetime.now():\n article_data['hits_day_count'] ++\nelse:\n article_data['hits_day'] = 0\n\narticle_data['hits_day_current'] = datetime.now()\n" } ]
2008/11/01
[ "https://Stackoverflow.com/questions/256282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
256,291
<p>What tools do you know, other than those in Visual Studio, to analyze performance bottlenecks in a Windows CE/Mobile application? I'm looking for something like AQTime for CE/Mobile, to profile C/C++ applications compiled to native code.</p>
[ { "answer_id": 256502, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 4, "selected": true, "text": "// File: callcaphooks.c\n\n#include <stdio.h>\nint main();\n\nvoid _CAP_Enter_Function(void *p) \n{\n if (p != main) \n printf(\"Enter function (at address %p) at %d\\n\", \n p, GetTickCount());\n return;\n}\nvoid _CAP_Exit_Function(void *p) \n{\n if (p != main) \n printf(\"Leaving function (at address %p) at %d\\n\", \n p, GetTickCount());\n return;\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8999/" ]
256,297
<p>In C++ I'd like to do something like:</p> <pre><code>int n = get_int_from_user(); char* matrix = new char[n][n]; matrix[0][0] = 'c'; //... matrix[n][n] = 'a'; delete [][] matrix; </code></pre> <p>but of course this doesn't work. What is the best way to do something similar? I've seen some solutions to this but they seem pretty messy.</p>
[ { "answer_id": 256303, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "int n = get_int_from_user();\n\nchar** matrix = new char*[n];\nfor (int i = 0; i < n; i++) {\n matrix[i] = new char[n];\n}\n\n// Operations on matrix.\n\nfor (int i = 0; i < n; i++) {\n delete [] matrix[i];\n}\ndelete matrix;\n" }, { "answer_id": 256304, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "char *matrix = new char [width * height];\n\nmatrix[i + j * width] = 'c'; // same as matrix[i][j] = 'c';\n\ndelete [] matrix;\n" }, { "answer_id": 256305, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 6, "selected": true, "text": "char *matrix = new char[width*height];\n delete[] matrix;\n char getArrayValue(char *matrix, int row, int col)\n{\n return matrix[row + col*width];\n}\n void setArrayValue(char *matrix, int row, int col, char val)\n{\n matrix[row + col*width] = val;\n}\n #include <boost/numeric/ublas/matrix.hpp>\nusing namespace boost::numeric::ublas;\nmatrix<char> m (3, 3);\nfor (unsigned i = 0; i < m.size1 (); ++ i)\n for (unsigned j = 0; j < m.size2 (); ++ j)\n m (i, j) = 3 * i + j;\n int width = 10;\nint height = 10; \nint matrix[width][height];\n" }, { "answer_id": 256686, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "std::vector< std::vector<int> > array2d;" }, { "answer_id": 260341, "author": "John", "author_id": 13895, "author_profile": "https://Stackoverflow.com/users/13895", "pm_score": 2, "selected": false, "text": "class Matrix\n{\n int width;\n int height;\n char* data;\npublic:\n Matrix();\n Matrix(int width, int height);\n ~Matrix();\n\n char getArrayValue(int row, int col);\n void setArrayValue(int row, int col, char val);\n}\n" }, { "answer_id": 4236413, "author": "Sridarshan", "author_id": 434354, "author_profile": "https://Stackoverflow.com/users/434354", "pm_score": 0, "selected": false, "text": "int n = get_int_from_user();\n\nchar **matrix=new (char*)[n];\n\nfor(int i=0;i<n;i++)\n matrix[i]=new char[n];\n\nmatrix[0][0] = 'c';\n//...\nmatrix[n][n] = 'a';\n\nfor(int i=0;i<n;i++)\n delete []matrix;\ndelete []matrix;\n" }, { "answer_id": 28756741, "author": "Pavel", "author_id": 4142152, "author_profile": "https://Stackoverflow.com/users/4142152", "pm_score": 0, "selected": false, "text": "std::vector<int> m;\n int* matrix = new int[w*h];\n int** matrix = new int*[h];\nfor(size_t i(0); i < h; ++i)\n matrix[i] = new int[w];\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30529/" ]
256,306
<p>I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file.</p> <p>I added a static method to my class CallRate that returns a <code>List&lt;CallRate&gt;</code>. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do.</p> <pre><code>List&lt;CallRates&gt; cr = CallRates.ProcessCallsFile(file); </code></pre>
[ { "answer_id": 256308, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 5, "selected": true, "text": "XmlReadrer reader = XmlReader.Create(filepathString);\n" }, { "answer_id": 256323, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 1, "selected": false, "text": "new MyClass()\n MyClass.New()\n class MyClass\n{\n public static MyClass New()\n {\n return new MyClass();\n }\n}\n null MyClass" }, { "answer_id": 256772, "author": "user33416", "author_id": 33416, "author_profile": "https://Stackoverflow.com/users/33416", "pm_score": 1, "selected": false, "text": " public class Car\n {\n public static Car RedExpensiveCar = new Car(\"Red\", 250000);\n\n public Car()\n {\n\n }\n\n public Car(string color, int price)\n {\n Color = color;\n Price = price;\n }\n\n public string Color { get; set; }\n public int Price { get; set; }\n }\n Car car = Car.RedExpensiveCar;\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10178/" ]
256,325
<p>For my Django app I have Events, Ratings, and Users. Ratings are related to Events and Users through a foreign keys. When displaying a list of Events I want to filter the ratings of the Event by a user_id so I know if an event has been rated by the user. </p> <p>If I do:</p> <pre><code>event_list = Event.objects.filter(rating__user=request.user.id) </code></pre> <p>(request.user.id gives the user_id of the current logged in user) ...then I only get the events that are rated by the user and not the entire list of events.</p> <p>What I need can be generated through the custom SQL:</p> <pre><code>SELECT * FROM `events_event` LEFT OUTER JOIN ( SELECT * FROM `events_rating` WHERE user_id = ## ) AS temp ON events_event.id = temp.user_id </code></pre> <p>Is there an easier way so I don't have to use custom SQL?</p>
[ { "answer_id": 256342, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "Event.objects.all() {% for e in event_list %}\n {{ e }}\n {% if e.rating_set.all %}{{ e.rating_set }}{% endif %}\n{% endfor %}\n" }, { "answer_id": 256400, "author": "Daniel Naab", "author_id": 32638, "author_profile": "https://Stackoverflow.com/users/32638", "pm_score": 3, "selected": false, "text": "Event.objects.all().select_related(depth=1)\n" }, { "answer_id": 256782, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": true, "text": "filter Event User import collections\n\nfrom django.db import models\n\nclass RatingManager(models.Manager):\n def get_for_user(self, events, user):\n ratings = self.filter(event__in=[event.id for event in events],\n user=user)\n rating_dict = collections.defaultdict(lambda: None)\n for rating in ratings:\n rating_dict[rating.event_id] = rating\n return rating_dict\n\nclass Rating(models.Model):\n # ...\n objects = RatingManager()\n events = Event.objects.all()\nuser_ratings = Rating.objects.get_for_user(events, request.user)\ncontext = {\n 'events': [(event, user_ratings[event.id]) for event in events],\n}\n {% for event, user_rating in events %}\n {% if user_rating %} ... {% endif %}\n{% endfor %}\n" }, { "answer_id": 3341185, "author": "fastmultiplication", "author_id": 51115, "author_profile": "https://Stackoverflow.com/users/51115", "pm_score": -1, "selected": false, "text": "events=Event.objects.filter(rating__user=request.user.id)\nratings='(select rating from ratings where user_id=%d and event_id=event_events.id '%request.user.id\nevents=events.extra(select={'rating':ratings})\n" }, { "answer_id": 66053973, "author": "alper", "author_id": 11074329, "author_profile": "https://Stackoverflow.com/users/11074329", "pm_score": 2, "selected": false, "text": "from django.db.models import Prefetch\n\n\nevent_list = Event.objects.all().prefetch_related(Prefetch(<related_name>, queryset=Rating.objects.filter(<criteria>)))\n class Rating(models.Model):\n event = models.ForeignKey(Event, related_name='ratings')\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5112/" ]
256,345
<p>Could you write a function that takes one argument (a positive integer) and</p> <ul> <li>divides it by two if it's even, or</li> <li>multiplies it by three and adds one if it's odd</li> </ul> <p>and then returns the resulting number.</p> <p>And then a separate function that takes one argument (a positive integer) and repeatedly passes it to the previous function until it reaches 1 (at which point it stops). The function would return the number of steps it took to reduce it to 1.</p> <p>And then another function which takes two arguments a and b (both positive integers with a &lt;= b) and returns the largest number of repeated Collatz steps it takes to reduce any single number in the range to 1 (including the endpoints). (Collatz steps refers to the previous function).</p> <p>And finally, another function that takes two arguments a and b (both positive integers with a &lt;= b) and returns the number between a and b (including the endpoints) that takes the largest number of Collatz steps to be reduced to 1.</p> <p>These functions are related to the Collatz problem, and I find it very interesting. The subsequent functions will obviously borrow other function that were defined previously.</p> <p>Any idea how we could show this in Scheme code?</p>
[ { "answer_id": 256352, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 0, "selected": false, "text": "(define (collatz x)\n (if (even? x)\n (/ x 2)\n (+ (* x 3) 1)))\n (define (collatz-loop x)\n (if (= x 1) 1\n (+ (collatz-loop (collatz x)) 1)))\n (define (collatz-loop x)\n (define (internal x counter)\n (if (= x 1) counter\n (internal (collatz x) (+ counter 1))))\n (internal x 1))\n (define (collatz-range a b)\n (if (= a b)\n (cons a (collatz-loop a))\n (let ((this (collatz-loop a))\n (rest (collatz-range (+ a 1) b)))\n (if (< this (cdr rest)) rest\n (cons a this)))))\n\n(collatz-range 1 20) ; returns (18 . 21), which means that (collatz-loop 18) returns 21\n (define (collatz-range a b)\n (define (internal a best)\n (if (< b a) best\n (internal (+ a 1)\n (let ((x (collatz-loop a)))\n (if (< x (cdr best))\n best\n (cons a x))))))\n (internal a (cons -1 -1)))\n" }, { "answer_id": 256369, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 1, "selected": false, "text": "(define (listfrom a b)\n (if (= a b)\n (cons a empty)\n (cons a (listfrom (+ 1 a) b))))\n\n(define (max-collatz a b)\n (foldl max 0 (map collatz-loop (listfrom a b))))\n\n(define (max-collatz-num a b)\n (foldl (lambda (c r)\n (if (> (collatz-loop c) (collatz-loop r)) c r))\n a\n (listfrom a b))) \n" }, { "answer_id": 256377, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 2, "selected": false, "text": "inline unsigned int step(unsigned int i)\n{\n return (i&0x1)*(i*3+1)+((i+1)&0x1)*(i>>1);\n}\n unsigned int collatz(unsigned int i)\n{\n unsigned int cur = i;\n unsigned steps = 0;\n while((cur=step(cur))!=1) steps++;\n return steps;\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
256,349
<p>I'm trying to find some info on the best and most common RESTful url actions.</p> <p>for example, what url do you use for displaying the details of an item, for editing the item, updating, etc.</p> <pre><code>/question/show/&lt;whatever&gt; /question/edit/&lt;whatever&gt; /question/update/&lt;whatever&gt; (this is the post back url) /question/list (lists the questions) </code></pre> <p>hmm. thanks to anyone helping out :)</p>
[ { "answer_id": 256355, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 4, "selected": false, "text": "/questions/10" }, { "answer_id": 256359, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 8, "selected": true, "text": "/questions/show/<whatever>\n /questions/<question>\n GET /questions/<question> HTTP/1.1\nHost: whateverblahblah.com\n GET /questions HTTP/1.1\nHost: whateverblahblah.com\n POST /questions/<new_question> HTTP/1.1\nHost: whateverblahblah.com\n POST /questions HTTP/1.1\nHost: whateverblahblah.com\n DELETE /questions/<question> HTTP/1.1\nHost: whateverblahblah.com\n PUT /questions/<new_question> HTTP/1.1\nHost: whateverblahblah.com\n PUT /questions/<existing_question> HTTP/1.1\nHost: whateverblahblah.com\n PATCH /questions/<new_question> HTTP/1.1\nHost: whateverblahblah.com\n" }, { "answer_id": 256374, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "http://application.com/controller/<action>/<id>\n" }, { "answer_id": 263885, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 1, "selected": false, "text": "/question/show/<whatever>\n GET /question/<whatever>\n /question/edit/<whatever>\n GET /question/<whatever>;edit\n /question/update/<whatever> (this is the post back url)\n PUT /question/<whatever>\n /question/list (lists the questions)\n GET /question\n POST /question (create a new question and returns its URL)\nDELETE /question/<whatever> (deletes a question if this is relevant)\n" }, { "answer_id": 1081730, "author": "pbreitenbach", "author_id": 42048, "author_profile": "https://Stackoverflow.com/users/42048", "pm_score": -1, "selected": false, "text": "GET /questions/123\nPOST (or PUT) /questions/123 q=What+is+the+meaning+of+life\nPOST (or PUT) /questions/123 q=What+is+the+meaning+of+life\nGET /questions\n POST /questions q=What+is+the+meaning+of+life\n 200 OK (or 201 Created)\nLocation: /questions/456\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
256,354
<p>In some my project I notice that during executing unit tests under VSTS2008 its VSTestHost's memory consuming grows. As I have very many tests in my solution it leads to OutOfMemroyException eventually. That looks very strange for me as I was sure that MSTest creates a new AppDomain for each unit test. Otherwise how would it reset static fields? But if AppDomain is being created for each test than memory shouldn't leak. But it does.</p> <p>So the question is: Should VS create AppDomain for each test class or not? If yes than how can I check that it does it. I tried tracing through ProcessExpolorer and Performance snap-in. A value of "Total appdomain unloaded" is always 0 during test run.</p>
[ { "answer_id": 256865, "author": "Shrike", "author_id": 27703, "author_profile": "https://Stackoverflow.com/users/27703", "pm_score": 3, "selected": false, "text": "public class Singleton\n{\n public static Singleton Instance = new Singleton();\n\n private Guid _token;\n private Singleton()\n {\n _token = Guid.NewGuid();\n }\n\n public Guid Token\n {\n get { return _token; }\n }\n}\n [TestClass]\npublic class UnitTest2\n{\n [TestMethod]\n public void TestMethod1()\n {\n Console.WriteLine(Singleton.Instance.Token);\n }\n}\n[TestClass]\npublic class UnitTest1\n{\n [TestMethod]\n public void TestMethod1()\n {\n Console.WriteLine(Singleton.Instance.Token);\n }\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27703/" ]
256,387
<p>When using copy-on-write semantics to share memory among processes, how can you test if a memory page is writable or if it is marked as read-only? Can this be done by calling a specific assembler code, or reading a certain spot in memory, or through the OS's API?</p>
[ { "answer_id": 256409, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": true, "text": "$ cat /proc/self/maps\n\n002b3000-002cc000 r-xp 00000000 68:01 143009 /lib/ld-2.5.so\n002cc000-002cd000 r-xp 00018000 68:01 143009 /lib/ld-2.5.so\n002cd000-002ce000 rwxp 00019000 68:01 143009 /lib/ld-2.5.so\n002d0000-00407000 r-xp 00000000 68:01 143010 /lib/libc-2.5.so\n00407000-00409000 r-xp 00137000 68:01 143010 /lib/libc-2.5.so\n00409000-0040a000 rwxp 00139000 68:01 143010 /lib/libc-2.5.so\n0040a000-0040d000 rwxp 0040a000 00:00 0\n00c6f000-00c70000 r-xp 00c6f000 00:00 0 [vdso]\n08048000-0804d000 r-xp 00000000 68:01 379298 /bin/cat\n0804d000-0804e000 rw-p 00004000 68:01 379298 /bin/cat\n08326000-08347000 rw-p 08326000 00:00 0\nb7d1b000-b7f1b000 r--p 00000000 68:01 226705 /usr/lib/locale/locale-archive\nb7f1b000-b7f1c000 rw-p b7f1b000 00:00 0\nb7f28000-b7f29000 rw-p b7f28000 00:00 0\nbfe37000-bfe4d000 rw-p bfe37000 00:00 0 [stack]\n" }, { "answer_id": 256427, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 1, "selected": false, "text": "int shmget(key_t, size_t, int);\n int shmctl(int, int, struct shmid_ds *);\n key_t key = /* your choice of memory api */\nint flag = /* set of flags for your app */\nint shmid = shmget(key, 4096, flag);\n\nstruct shmid_ds buf;\nint result = shmctl(shmid, IPC_STAT, &buf);\n/* buf.ipc_perm.mode contains the permissions for the memory segment */\n" }, { "answer_id": 256479, "author": "Chris Smith", "author_id": 9073, "author_profile": "https://Stackoverflow.com/users/9073", "pm_score": 2, "selected": false, "text": "MEMORY_BASIC_INFORMATION Protect" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33364/" ]
256,405
<p>I have a C/C++ application and I need to create a X509 pem certificate containing both a public and private key. The certificate can be self signed, or unsigned, doesn't matter.</p> <p>I want to do this inside an app, not from command line.</p> <p>What OpenSSL functions will do this for me? Any sample code is a bonus!</p>
[ { "answer_id": 256436, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "system openssl openssl-dev" }, { "answer_id": 15082282, "author": "Nathan Osman", "author_id": 193619, "author_profile": "https://Stackoverflow.com/users/193619", "pm_score": 8, "selected": false, "text": "EVP_PKEY openssl/evp.h openssl/x509.h EVP_PKEY EVP_PKEY_new EVP_PKEY * pkey;\npkey = EVP_PKEY_new();\n EVP_PKEY_free EVP_PKEY RSA_generate_key openssl/rsa.h RSA RSA * rsa;\nrsa = RSA_generate_key(\n 2048, /* number of bits for the key - 2048 is a sensible value */\n RSA_F4, /* exponent - RSA_F4 is defined as 0x10001L */\n NULL, /* callback - can be NULL if we aren't displaying progress */\n NULL /* callback argument - not needed in this case */\n);\n RSA_generate_key NULL EVP_PKEY EVP_PKEY_assign_RSA(pkey, rsa);\n RSA EVP_PKEY X509 openssl/x509.h X509_new X509 * x509;\nx509 = X509_new();\n EVP_PKEY X509_free X509_* ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);\n X509_gmtime_adj(X509_get_notBefore(x509), 0);\nX509_gmtime_adj(X509_get_notAfter(x509), 31536000L);\n notBefore X509_gmtime_adj notAfter X509_set_pubkey(x509, pkey);\n X509_NAME * name;\nname = X509_get_subject_name(x509);\n X509_NAME_add_entry_by_txt(name, \"C\", MBSTRING_ASC,\n (unsigned char *)\"CA\", -1, -1, 0);\nX509_NAME_add_entry_by_txt(name, \"O\", MBSTRING_ASC,\n (unsigned char *)\"MyCompany Inc.\", -1, -1, 0);\nX509_NAME_add_entry_by_txt(name, \"CN\", MBSTRING_ASC,\n (unsigned char *)\"localhost\", -1, -1, 0);\n unsigned char * X509_set_issuer_name(x509, name);\n X509_sign X509_sign(x509, pkey, EVP_sha1());\n mkcert.c PEM_* openssl/pem.h PEM_write_PrivateKey FILE * f;\nf = fopen(\"key.pem\", \"wb\");\nPEM_write_PrivateKey(\n f, /* write the key to the file we've opened */\n pkey, /* our key from earlier */\n EVP_des_ede3_cbc(), /* default cipher for encrypting the key on disk */\n \"replace_me\", /* passphrase required for decrypting the key on disk */\n 10, /* length of the passphrase string */\n NULL, /* callback for requesting a password */\n NULL /* data to pass to the callback */\n);\n NULL chmod 600 key.pem PEM_write_X509 FILE * f;\nf = fopen(\"cert.pem\", \"wb\");\nPEM_write_X509(\n f, /* write the certificate to the file we've opened */\n x509 /* our certificate */\n);\n" }, { "answer_id": 57478849, "author": "MasterAler", "author_id": 2846068, "author_profile": "https://Stackoverflow.com/users/2846068", "pm_score": 3, "selected": false, "text": "bool generateX509(const std::string& certFileName, const std::string& keyFileName, long daysValid)\n{\n bool result = false;\n\n std::unique_ptr<BIO, void (*)(BIO *)> certFile { BIO_new_file(certFileName.data(), \"wb\"), BIO_free_all };\n std::unique_ptr<BIO, void (*)(BIO *)> keyFile { BIO_new_file(keyFileName.data(), \"wb\"), BIO_free_all };\n\n if (certFile && keyFile)\n {\n std::unique_ptr<RSA, void (*)(RSA *)> rsa { RSA_new(), RSA_free };\n std::unique_ptr<BIGNUM, void (*)(BIGNUM *)> bn { BN_new(), BN_free };\n\n BN_set_word(bn.get(), RSA_F4);\n int rsa_ok = RSA_generate_key_ex(rsa.get(), RSA_KEY_LENGTH, bn.get(), nullptr);\n\n if (rsa_ok == 1)\n {\n // --- cert generation ---\n std::unique_ptr<X509, void (*)(X509 *)> cert { X509_new(), X509_free };\n std::unique_ptr<EVP_PKEY, void (*)(EVP_PKEY *)> pkey { EVP_PKEY_new(), EVP_PKEY_free};\n\n // The RSA structure will be automatically freed when the EVP_PKEY structure is freed.\n EVP_PKEY_assign(pkey.get(), EVP_PKEY_RSA, reinterpret_cast<char*>(rsa.release()));\n ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), 1); // serial number\n\n X509_gmtime_adj(X509_get_notBefore(cert.get()), 0); // now\n X509_gmtime_adj(X509_get_notAfter(cert.get()), daysValid * 24 * 3600); // accepts secs\n\n X509_set_pubkey(cert.get(), pkey.get());\n\n // 1 -- X509_NAME may disambig with wincrypt.h\n // 2 -- DO NO FREE the name internal pointer\n X509_name_st* name = X509_get_subject_name(cert.get());\n\n const uchar country[] = \"RU\";\n const uchar company[] = \"MyCompany, PLC\";\n const uchar common_name[] = \"localhost\";\n\n X509_NAME_add_entry_by_txt(name, \"C\", MBSTRING_ASC, country, -1, -1, 0);\n X509_NAME_add_entry_by_txt(name, \"O\", MBSTRING_ASC, company, -1, -1, 0);\n X509_NAME_add_entry_by_txt(name, \"CN\", MBSTRING_ASC, common_name, -1, -1, 0);\n\n X509_set_issuer_name(cert.get(), name);\n X509_sign(cert.get(), pkey.get(), EVP_sha256()); // some hash type here\n\n\n int ret = PEM_write_bio_PrivateKey(keyFile.get(), pkey.get(), nullptr, nullptr, 0, nullptr, nullptr);\n int ret2 = PEM_write_bio_X509(certFile.get(), cert.get());\n\n result = (ret == 1) && (ret2 == 1); // OpenSSL return codes\n }\n }\n\n return result;\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
256,451
<p>I've written a VB.NET application that uses SQL CE 3.5. I'm curious if anyone has any best practice or code to help check if A) SQL CE is installed and B) If so, what version. </p> <p>I searched msdn and google for anything but I didn't find anything helpful. I was poking around the registry and found this key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server Compact Edition\v3.5 with a string value "Version" and the data was 3.5.5692.0. </p> <p>So off the bat my assumption is to check for the presence of this key but it bothers me because the "3.5" key sure sounds like it's tied to the 3.5 DLL. What I'm trying to say is I'd hate to force someone to install SQL 3.5 if they have SQL CE (insert some future version of CE here).</p> <p>Misc info: Target Framework: .NET 2.0 Minimum Target OS: Windows XP SP2</p>
[ { "answer_id": 17834938, "author": "noelicus", "author_id": 865643, "author_profile": "https://Stackoverflow.com/users/865643", "pm_score": 0, "selected": false, "text": "<Fragment>\n <util:RegistrySearch\n Id='SearchForSQLCE'\n Variable=\"SQLCEInstalled\"\n Result=\"exists\"\n Root=\"HKLM\"\n Key=\"SOFTWARE\\Classes\\Microsoft SQL Server Compact Edition Database File\"\n Win64=\"yes\"\n />\n </Fragment>\n" }, { "answer_id": 31324173, "author": "Bluebaron", "author_id": 511273, "author_profile": "https://Stackoverflow.com/users/511273", "pm_score": 1, "selected": false, "text": " DownloadUrl=\"http://download.microsoft.com/download/0/5/D/05DCCDB5-57E0-4314-A016-874F228A8FAD/SSCERuntime_x86-ENU.exe\"\n SourceFile=\"SSCERuntime_x86-ENU.exe\"\n Compressed=\"no\"\n <PackageGroup Id=\"SQLExpressCE\">\n <ExePackage\n Vital=\"yes\"\n SourceFile=\"SSCERuntime_x86-ENU.exe\"\n InstallCondition=\"NOT VersionNT64\"\n\n //Include the exes(only about 2.5 megs each)\n //Setting this to no causes your bootstrapper to download on installation but since this will always be trying to install, it is probably best to include it\n Compressed=\"yes\"\n\n //install quietly without an interface\n InstallCommand=\"/i /quiet /n\"\n />\n <ExePackage\n Vital=\"yes\"\n InstallCondition=\"VersionNT64\" \n SourceFile=\"SSCERuntime_x64-ENU.exe\"\n Compressed=\"yes\"\n InstallCommand=\"/i /quiet /n\"\n />\n</PackageGroup>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33371/" ]
256,456
<p>My application has a WCF service tier between the front-end and the database. Since we currently host in IIS6 we are using SOAP over HTTP. How can I find out how much real world time I am spending doing serialization activities in my application?</p>
[ { "answer_id": 256602, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "AfterReceiveRequest\n{\n DateTime start = datetime.now;\n return start;\n}\nBeforeSendReply\n{\n // start will be passed in as state in the parameter. \n TimeSpan period = datetime.now - start \n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32992/" ]
256,460
<p>Is there anything similar to an <code>indexOf</code> function in the NSString objects?</p>
[ { "answer_id": 256464, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 8, "selected": true, "text": "-[NSString rangeOfString:] - (NSRange)rangeOfString:(NSString *)aString;\n" }, { "answer_id": 7329792, "author": "firestoke", "author_id": 555796, "author_profile": "https://Stackoverflow.com/users/555796", "pm_score": 4, "selected": false, "text": "#import <Foundation/Foundation.h>\n\n@interface NSString (util)\n\n- (int) indexOf:(NSString *)text;\n\n@end\n #import \"ExtendNSString.h\"\n\n@implementation NSString (util)\n\n- (int) indexOf:(NSString *)text {\n NSRange range = [self rangeOfString:text];\n if ( range.length > 0 ) {\n return range.location;\n } else {\n return -1;\n }\n}\n\n@end\n" }, { "answer_id": 8036303, "author": "orafaelreis", "author_id": 798430, "author_profile": "https://Stackoverflow.com/users/798430", "pm_score": 5, "selected": false, "text": "#define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound)\n\n//using \nNSString a = @\"PUC MINAS - BRAZIL\";\n\nNSString b = @\"BRAZIL\";\n\nif( contains(a,b) ){\n //TO DO HERE\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
256,490
<p>I'm trying to go deep into Dictionary ADT and Skip List for Java. My textbook doesn't cover a lot about this and whatever it has covered is very complicated. Which is the best online site to get more information on Dictionary ADT and Skip List for Java. I'm looking for the one which talks visually and gives a lot of examples.</p>
[ { "answer_id": 256498, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 3, "selected": true, "text": "ConcurrentSkipListSet ConcurrentSkipListMap Map" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33203/" ]
256,495
<p>Are there compilers for high-level languages (such as C) which can be targeted to various architectures by specifying the hardware resources of the target?</p> <p>I'm wondering if there are compilers which can target an architecture by specifying features such as the available registers and instruction set of the processor (i.e. how each instruction changes the state of the processor), and memory layout of the architecture.</p> <p>I am aware that compilers such as <a href="http://gcc.gnu.org/" rel="nofollow noreferrer">gcc</a> can target for multiple archtectures, but I'd like to know if there are compilers that can compile for new architectures by swapping out, say, configuration files, in order to target a new architecture.</p>
[ { "answer_id": 256555, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": true, "text": ".md" }, { "answer_id": 256639, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 2, "selected": false, "text": "Phoenix:X86 louis$ ls -al | grep cpp \n-rw-r--r-- 1 louis louis 27627 Nov 1 03:32 X86CodeEmitter.cpp\n-rw-r--r-- 1 louis louis 661 Oct 29 18:56 X86ELFWriterInfo.cpp\n-rw-r--r-- 1 louis louis 46558 Oct 29 18:56 X86FastISel.cpp\n-rw-r--r-- 1 louis louis 43660 Oct 29 18:56 X86FloatingPoint.cpp\n-rw-r--r-- 1 louis louis 59915 Oct 29 18:56 X86ISelDAGToDAG.cpp\n-rw-r--r-- 1 louis louis 312709 Nov 1 03:32 X86ISelLowering.cpp\n-rw-r--r-- 1 louis louis 109229 Oct 29 18:56 X86InstrInfo.cpp\n-rw-r--r-- 1 louis louis 17396 Oct 29 18:56 X86JITInfo.cpp\n-rw-r--r-- 1 louis louis 44111 Nov 1 03:32 X86RegisterInfo.cpp\n-rw-r--r-- 1 louis louis 10369 Oct 29 18:56 X86Subtarget.cpp\n-rw-r--r-- 1 louis louis 15265 Oct 29 18:56 X86TargetAsmInfo.cpp\n-rw-r--r-- 1 louis louis 9365 Oct 29 18:56 X86TargetMachine.cpp\nPhoenix:X86 louis$ ls -al | grep td \n-rw-r--r-- 1 louis louis 6870 Oct 29 18:56 X86.td\n-rw-r--r-- 1 louis louis 13480 Oct 29 18:56 X86CallingConv.td\n-rw-r--r-- 1 louis louis 77361 Nov 1 03:32 X86Instr64bit.td\n-rw-r--r-- 1 louis louis 31517 Oct 29 18:56 X86InstrFPStack.td\n-rw-r--r-- 1 louis louis 11690 Oct 29 18:56 X86InstrFormats.td\n-rw-r--r-- 1 louis louis 156188 Oct 29 18:56 X86InstrInfo.td\n-rw-r--r-- 1 louis louis 32971 Oct 29 18:56 X86InstrMMX.td\n-rw-r--r-- 1 louis louis 183502 Oct 29 18:56 X86InstrSSE.td\n-rw-r--r-- 1 louis louis 23653 Nov 1 03:32 X86RegisterInfo.td\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17172/" ]
256,507
<p>I'm a Lisp beginner. I'm trying to memoize a recursive function for calculating the number of terms in a <a href="http://en.wikipedia.org/wiki/Collatz_conjecture" rel="noreferrer">Collatz sequence</a> (for problem 14 in <a href="http://projecteuler.net/index.php?section=problems&amp;id=14" rel="noreferrer">Project Euler</a>). My code as of yet is:</p> <pre><code>(defun collatz-steps (n) (if (= 1 n) 0 (if (evenp n) (1+ (collatz-steps (/ n 2))) (1+ (collatz-steps (1+ (* 3 n))))))) (defun p14 () (defvar m-collatz-steps (memoize #'collatz-steps)) (let ((maxsteps (funcall m-collatz-steps 2)) (n 2) (steps)) (loop for i from 1 to 1000000 do (setq steps (funcall m-collatz-steps i)) (cond ((&gt; steps maxsteps) (setq maxsteps steps) (setq n i)) (t ()))) n)) (defun memoize (fn) (let ((cache (make-hash-table :test #'equal))) #'(lambda (&amp;rest args) (multiple-value-bind (result exists) (gethash args cache) (if exists result (setf (gethash args cache) (apply fn args))))))) </code></pre> <p>The memoize function is the same as the one given in the <a href="http://lib.store.yahoo.net/lib/paulgraham/onlisp.pdf" rel="noreferrer">On Lisp</a> book. </p> <p>This code doesn't actually give any speedup compared to the non-memoized version. I believe it's due to the recursive calls calling the non-memoized version of the function, which sort of defeats the purpose. In that case, what is the correct way to do the memoization here? Is there any way to have all calls to the original function call the memoized version itself, removing the need for the special m-collatz-steps symbol?</p> <p>EDIT: Corrected the code to have </p> <pre><code>(defvar m-collatz-steps (memoize #'collatz-steps)) </code></pre> <p>which is what I had in my code. Before the edit I had erroneously put:</p> <pre><code>(defvar collatz-steps (memoize #'collatz-steps)) </code></pre> <p>Seeing that error gave me another idea, and I tried using this last defvar itself and changing the recursive calls to </p> <pre><code> (1+ (funcall collatz-steps (/ n 2))) (1+ (funcall collatz-steps (1+ (* 3 n)))) </code></pre> <p>This does seem to perform the memoization (speedup from about 60 seconds to 1.5 seconds), but requires changing the original function. Is there a cleaner solution which doesn't involve changing the original function? </p>
[ { "answer_id": 256552, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "(setf collatz-steps (memoize lambda (n)\n (if (= 1 n) 0\n (if (evenp n) \n (1+ (collatz-steps (/ n 2)))\n (1+ (collatz-steps (1+ (* 3 n))))))))\n" }, { "answer_id": 257224, "author": "huaiyuan", "author_id": 16240, "author_profile": "https://Stackoverflow.com/users/16240", "pm_score": 5, "selected": true, "text": "(setf (fdefinition 'collatz-steps) (memoize #'collatz-steps))\n\n(defun p14 ()\n (let ((mx 0) (my 0))\n (loop for x from 1 to 1000000\n for y = (collatz-steps x)\n when (< my y) do (setf my y mx x))\n mx))\n" }, { "answer_id": 259704, "author": "Eric Normand", "author_id": 7492, "author_profile": "https://Stackoverflow.com/users/7492", "pm_score": 2, "selected": false, "text": "(defun memoize-function (function-name)\n (setf (symbol-function function-name)\n (let ((cache (make-hash-table :test #'equal)))\n #'(lambda (&rest args)\n (multiple-value-bind \n (result exists)\n (gethash args cache)\n (if exists\n result\n (setf (gethash args cache)\n (apply fn args)))))))\n (defun collatz-steps (n)\n (if (= 1 n) 0\n (if (evenp n) \n (1+ (collatz-steps (/ n 2)))\n (1+ (collatz-steps (1+ (* 3 n)))))))\n\n(memoize-function 'collatz-steps)\n" }, { "answer_id": 307912, "author": "jonrock", "author_id": 39526, "author_profile": "https://Stackoverflow.com/users/39526", "pm_score": 1, "selected": false, "text": "(setf (fdefinition 'collatz-steps) (memoize #'collatz-steps))\n" }, { "answer_id": 307938, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 0, "selected": false, "text": "(define (memoize op)\n (letrec ((get (lambda (key) (list #f)))\n (set (lambda (key item)\n (let ((old-get get))\n (set! get (lambda (new-key)\n (if (equal? key new-key) (cons #t item)\n (old-get new-key))))))))\n (lambda args\n (let ((ans (get args)))\n (if (car ans) (cdr ans)\n (let ((new-ans (apply op args)))\n (set args new-ans)\n new-ans))))))\n (define fib (memoize (lambda (x)\n (if (< x 2) x\n (+ (fib (- x 1)) (fib (- x 2)))))))\n" }, { "answer_id": 2393414, "author": "Vatine", "author_id": 34771, "author_profile": "https://Stackoverflow.com/users/34771", "pm_score": 0, "selected": false, "text": "(let ((memo (make-hash-table :test #'equal)))\n (defun collatz-steps (n)\n (or (gethash n memo)\n (setf (gethash n memo)\n (cond ((= n 1) 0)\n ((oddp n) (1+ (collatz-steps (+ 1 n n n))))\n (t (1+ (collatz-steps (/ n 2)))))))))\n" }, { "answer_id": 2393650, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 2, "selected": false, "text": "(defun foo (bar)\n ... (foo 3) ...)\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8127/" ]
256,517
<p>When I was learning Java coming from a background of some 20 years of procedural programming with basic, Pascal, COBOL and C, I thought at the time that the hardest thing about it was wrapping my head around the OOP jargon and concepts. Now with about 8 years of solid Java under my belt, I have come to the conclusion that the single hardest thing about programming in Java and similar languages like C# is the multithreaded/concurrent aspects.</p> <p>Coding reliable and scalable multi-threaded applications is just plain hard! And with the trend for processors to grow "wider" rather than faster, it is rapidly becoming just plain critical.</p> <p>The hardest area is, of course, controlling interactions between threads and the resulting bugs: deadlocks, race conditions, stale data and latency.</p> <p>So my question to you is this: what approach or methodology do <em>you</em> employ for producing safe concurrent code while mitigating the potential for deadlocks, latency, and other problems? I have come up with an approach which is a little unconventional but has worked very well in several large applications, which I will share in a detailed answer to this question.</p>
[ { "answer_id": 256591, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 0, "selected": false, "text": "Object processIocMessage(Object msgsdr, int msgidn, Object msgdta)\n Object iocMessage(int mid, Object dta)\nvoid iocSignal (int mid, Object dta)\n" }, { "answer_id": 256675, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 0, "selected": false, "text": "thread1_proc() {\n\nmsg = get_queue1_msg(); // block until message is put to queue1\nthreat1_msg(msg);\n\n}\n\nthread2_proc() {\nmsg = create_msg_for_thread1();\nsend_to_queue1(msg);\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8946/" ]
256,546
<p>Anyone know if there is already a validator for "type" strings?</p> <p>I want to make sure that the type attributes in my custom config are one of the following:</p> <pre> type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly" type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089" </pre> <p>Writing one is easy enough, I just don't want to reinvent the wheel.</p>
[ { "answer_id": 258944, "author": "jon without an h", "author_id": 27578, "author_profile": "https://Stackoverflow.com/users/27578", "pm_score": 0, "selected": false, "text": "List<>\n\"System.Collections.Generic.List`1\"\n\nList<string>\n\"System.Collections.Generic.List`1[[System.String]]\"\n\nDictionary<string, string>\n\"System.Collections.Generic.Dictionary`2[[System.String],[System.String]]\"\n\nDictionary<string, List<string>>\n\"System.Collections.Generic.Dictionary`2[[System.String],[System.Collections.Generic.List`1[[System.String]]]]\"\n" }, { "answer_id": 293190, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 0, "selected": false, "text": "Type.GetType(...)" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91911/" ]
256,554
<p>In particular, I'm editing the AutoCompletion.plist file for CSSEdit (if that even matters).</p> <p>My question is, are there any characters withing the STRING elements that need to be escaped? spaces? quotes?</p> <p>EDIT: Just to be clear, I'm not using CSSEdit to edit the file - rather the file is part of the CSSEdit package. I'm using TextMate to edit the file (although "Property List Editor.app" is another option) and it is in XML format. Here's a snippet from the AutoCompletion.plist file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;font-family&lt;/key&gt; &lt;array&gt; &lt;string&gt;Arial&lt;/string&gt; &lt;string&gt;Helvetica&lt;/string&gt; &lt;string&gt;Georgia&lt;/string&gt; &lt;string&gt;serif&lt;/string&gt; &lt;string&gt;sans-serif&lt;/string&gt; &lt;string&gt;cursive&lt;/string&gt; etc... </code></pre> <p>I'd like to add STRINGs with spaces and single quotes such as:</p> <pre><code>&lt;string&gt;Georgia, Times, 'Times New Roman', serif&lt;/string&gt; </code></pre> <p>But CSSEdit goes haywire when I edit the file as such</p>
[ { "answer_id": 257149, "author": "Brian Webster", "author_id": 23324, "author_profile": "https://Stackoverflow.com/users/23324", "pm_score": 5, "selected": true, "text": "<string>Georgia, Times, &apos;Times New Roman&apos;, serif</string>" }, { "answer_id": 257185, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 2, "selected": false, "text": "plutil" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17252/" ]
256,557
<p>One of the things that seems to be necessary with use of STL is a way to specify local functions. Many of the functions that I would normally provide cannot be created using STL function object creation tools ( eg bind ), I have to hand roll my function object.</p> <p>Since the C++ standard forbids local types to be used as arguments in template instantiations the best I was able to use was to create a small library, ( just showing relevant parts )</p> <pre><code>// library header class MyFunctionBase&lt;R,T&gt; { public: virtual ~MyFunctionBase(); virtual R operator()(const T &amp;) const=0; }; class MyFunction&lt;R,T&gt; { MyFunctionBase&lt;R,T&gt; *b; public: ~MyFunction() { delete b; } virtual R operator()(const T &amp;) const { return (*b)(T); } }; // source file .... class func: public MyFunctionBase ... std::stl_alg(.... MyFunction(new funct)); </code></pre> <p>This has always seemed unwieldly to me. I guess to the people on the ISO committee believe so too and added a lambda to C++.</p> <p>In the meantime how have compilers addressed this problem? ( Especially Windows compilers. )</p> <p>A correction which might clarify a bit. Changelog: Nov 2 replaced to clarify Since the C++ standard forbids local classes as function objects</p>
[ { "answer_id": 256567, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "struct operator() struct MyMinFunctor {\n bool operator()(const int& a, const int& b) { return a > b; }\n};\n\nvector<int> v;\nsort(v.begin(), v.end(), MyMinFunctor());\n" }, { "answer_id": 257299, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 1, "selected": false, "text": "for_each(container.begin(), container.end(),\n [](auto item) {\n // do something with item\n }\n );\n bind function" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29178/" ]
256,564
<p>I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (<a href="http://twitpic.com/api.do" rel="nofollow noreferrer">http://twitpic.com/api.do</a>). For reference purposes, check out the code (<a href="http://pastebin.com/f4c498b6e" rel="nofollow noreferrer">http://pastebin.com/f4c498b6e</a>) and the error I'm getting (<a href="http://pastebin.com/mff11d31" rel="nofollow noreferrer">http://pastebin.com/mff11d31</a>).</p> <p>Pay special attention to line 27 of the code, which contains "xml = server.perform()". After researching my problem, I discovered that unlike I had previously thought, .perform() does not return the xml response from twitpic.com, but None, when the upload succeeds (duh!).</p> <p>After looking at the error output further, it seems to me like the xml input that I want stuffed into the "xml" variable is instead being printed to ether standard output or standard error (not sure which). I'm sure there is an easy way to do this, but I cannot seem to think of it at the moment. If you have any tips that could point me in the right direction, I'd be very appreciative. Thanks in advance.</p>
[ { "answer_id": 256610, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 3, "selected": true, "text": "import sys\nimport pycurl\n\nclass Test:\n def __init__(self):\n self.contents = ''\n\n def body_callback(self, buf):\n self.contents = self.contents + buf\n\nprint >>sys.stderr, 'Testing', pycurl.version\n\nt = Test()\nc = pycurl.Curl()\nc.setopt(c.URL, 'http://curl.haxx.se/dev/')\nc.setopt(c.WRITEFUNCTION, t.body_callback)\nc.perform()\nc.close()\n\nprint t.contents\n Test() c.setopt(c.WRITEFUNCTION, t.body_callback) buf print t.contents\n" }, { "answer_id": 2351363, "author": "Alon Swartz", "author_id": 283106, "author_profile": "https://Stackoverflow.com/users/283106", "pm_score": 4, "selected": false, "text": "import pycurl\nimport cStringIO\n\nresponse = cStringIO.StringIO()\n\nc = pycurl.Curl()\nc.setopt(c.URL, 'http://www.turnkeylinux.org')\nc.setopt(c.WRITEFUNCTION, response.write)\nc.perform()\nc.close()\n\nprint response.getvalue()\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33383/" ]
256,566
<p>I'm trying to create a function in C# which will allow me to, when called, return a reference to a given class type. The only types of functions like this that I have seen are in UnrealScript and even then the functionality is hard coded into its compiler. I'm wondering if I can do this in C#. Here's what I mean (code snippet from UnrealScript source):</p> <pre><code>native(278) final function actor Spawn ( class&lt;actor&gt; SpawnClass, optional actor SpawnOwner, optional name SpawnTag, optional vector SpawnLocation, optional rotator SpawnRotation ); </code></pre> <p>Now in UScript you would call it like this...</p> <pre><code>local ActorChild myChildRef; //Ref to ActorChild which Extends 'actor' myChildRef = Spawn(class'ActorChild' ...); //rest of parameters taken out myChildRef.ChildMethod(); //method call to method existing inside class 'ActorChild' </code></pre> <p>Which will return a reference to an object of class 'ActorChild' and set it to variable 'myChildRef.' I need to do something similar within C#.</p> <p>I've looked into Generics but it seems that to use them, I need create an instace of the class where my function lies and pass the 'generic' parameter to it. This isn't very desirable however as I won't need to use the 'Spawn' function for certain classes but I would still need to add the generic parameter to the class whenever I use it.</p> <p>I guess a simplified question would be, how can I return a type that I do not know at compile time and when the different classes could be far too many to trap.</p> <p>Pseudo-Code (sticking to UScript class names, i.e. Actor):</p> <pre><code>//Function Sig public class&lt;Actor&gt; Create(class&lt;Actor&gt; CreatedClass) { return new CreatedClass; } //Function call ActorChild myChild = Create(class'ActorChild'); </code></pre> <p>Any ideas?</p> <p>EDIT: I would like to avoid explicit typecasts that would occur from the class calling Created. If I can typecast to the desired object within the Created method and return the 'unknown type' whatever that may be, I would be extremely happy.</p> <p>EDIT 2: Thanks for your answers.</p>
[ { "answer_id": 256586, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 0, "selected": false, "text": "System.Type t = typeof(ActorChild);\n System.Type t = Type.GetType(\"NamespaceFoo.ActorChild\");\n public object Create(System.Type ClassToCreate)\n{\n return ClassToCreate.GetConstructor(Type.EmptyTypes).Invoke(null);\n}\n" }, { "answer_id": 256633, "author": "Alon L", "author_id": 30884, "author_profile": "https://Stackoverflow.com/users/30884", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nnamespace Reflection\n{\n class SomeClass\n {\n private string StringPrimer = \"The parameter text is: \";\n public SomeClass(string text)\n {\n Console.WriteLine(StringPrimer + text);\n }\n public string getPrimer() //supplies the Primer in upper case, just for kicks\n {\n return StringPrimer.ToUpper();\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n SomeClass s = new SomeClass(\"this is an example of the classes normal hard-coded function.\\nNow try feeding in some text\");\n string t = Console.ReadLine();\n\n Console.WriteLine(\"Now feed in the class name (SomeClass in this case)\");\n Type myType = Type.GetType(\"Reflection.\"+Console.ReadLine()); //Stores info about the class.\n object myClass = Activator.CreateInstance(myType, new object[] { t }); //This dynamically calls SomeClass and sends in the text you enter as a parameter\n\n //Now lets get the string primer, using the getPrimer function, dynamically\n string primer = (string)myType.InvokeMember(\"getPrimer\",\n BindingFlags.InvokeMethod | BindingFlags.Default,\n null,\n myClass,\n null); //This method takes the name of the method, some Binding flags,\n //a binder object that I left null,\n //the object that the method will be called from (would have been null if the method was static)\n //and an object array of parameters, just like in the CreateInstance method.\n Console.WriteLine(primer);\n }\n }\n}\n" }, { "answer_id": 256636, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": true, "text": "public T Spawn<T>() where T : new()\n{\n return new T();\n}\n new MyClass()" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
256,579
<p>I'm working on an application developed by another mob and am confounded by the use of a char field instead of bit for all the boolean columns in the database. It uses "Y" for true and "N" for false (these have to be uppercase). The type name itself is then aliased with some obscure name like <em>ybln</em>.</p> <p>This is very annoying to work with for a lot of reasons, not the least of which is that it just looks downright aesthetically unpleasing.</p> <p>But maybe its me that's stupid - why would anyone do this? Is it a database compatibility issue or some design pattern that I am not aware of?</p> <p>Can anyone enlighten me?</p>
[ { "answer_id": 259176, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "WHERE BooleanColumn WHERE BitColumn = 1 IF @BitFlag = 1 IF @BooleanFlag NULL" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21966/" ]
256,625
<p>I have seen samples of closure from - <a href="https://stackoverflow.com/questions/36636/what-is-a-closure">What is a &#39;Closure&#39;?</a></p> <p>Can anyone provide simple example of when to use closure?<br></p> <p><b>Specifically, scenarios in which closure makes sense?</b><Br></p> <p>Lets assume that the language doesn't have closure support, how would one still achieve similar thing?</p> <p>Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc. <br>I am sorry, I do not understand functional languages yet.</p>
[ { "answer_id": 256630, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": 4, "selected": false, "text": "(defun make-adder (how-much)\n (lambda (x)\n (+ x how-much)))\n cl-user(2): (make-adder 5)\n#<Interpreted Closure (:internal make-adder) @ #x10009ef272>\ncl-user(3): (funcall * 3) ; calls the function you just made with the argument '3'.\n8\n public class Adder {\n private int howMuch;\n\n public Adder(int h) {\n howMuch = h;\n }\n\n public int doAdd(int x) {\n return x + howMuch;\n }\n}\n Adder addFive = new Adder(5);\nint addedFive = addFive.doAdd(3);\n// addedFive is now 8.\n" }, { "answer_id": 256663, "author": "zvoase", "author_id": 31600, "author_profile": "https://Stackoverflow.com/users/31600", "pm_score": 4, "selected": false, "text": "f() a b def f(a, b):\n return a + b\n f() f(2, 3) f(2)(3) def f(a):\n def g(b): # Function-within-a-function\n return a + b # The value of a is present in the scope of g()\n return g # f() returns a one-argument function g()\n f(2) g() f() g(3) a f g() 2 + 3 => 5 def many_arguments(a, b, c, d, e, f, g, h, i):\n return # SOMETHING\n\ndef curry(function, **curry_args):\n # call is a closure which closes over the environment of curry.\n def call(*call_args):\n # Call the function with both the curry args and the call args, returning\n # the result.\n return function(*call_args, **curry_args)\n # Return the closure.\n return call\n\nuseful_function = curry(many_arguments, a=1, b=2, c=3, d=4, e=5, f=6)\n useful_function curry" }, { "answer_id": 256666, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "string name = // blah\nint value = // blah\nnew Thread((ThreadStart)delegate { DoWork(name, value);}); // or inline if short\n Person person = list.Find(x=>x.Age > minAge && x.Region == region);\n internal sealed class PersonFinder\n{\n public PersonFinder(int minAge, string region)\n {\n this.minAge = minAge;\n this.region = region;\n }\n private readonly int minAge;\n private readonly string region;\n public bool IsMatch(Person person)\n {\n return person.Age > minAge && person.Region == region;\n }\n}\n...\nPerson person = list.Find(new PersonFinder(minAge,region).IsMatch);\n for(int i = 0 ; i < 10 ; i++) {\n ThreadPool.QueueUserWorkItem(delegate\n {\n Console.WriteLine(i);\n });\n }\n for(int i = 0 ; i < 10 ; i++) {\n int j = i;\n ThreadPool.QueueUserWorkItem(delegate\n {\n Console.WriteLine(j);\n });\n }\n" }, { "answer_id": 256682, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 2, "selected": false, "text": "def strseq(object, convert, join=joinseq):\n \"\"\"Recursively walk a sequence, stringifying each element.\"\"\"\n if type(object) in (list, tuple):\n return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))\n else:\n return convert(object)\n def strseq(object, convert, join=joinseq):\n \"\"\"Recursively walk a sequence, stringifying each element.\"\"\"\n if type(object) in (list, tuple):\n return join(map(lambda o: strseq(o, convert, join), object))\n else:\n return convert(object)\n class ClassBrowser: # shortened\n def close(self, event=None):\n self.top.destroy()\n self.node.destroy()\n def init(self, flist):\n top.bind(\"<Escape>\", self.close)\n class ClassBrowser:\n def close(self, event=None):\n self.top.destroy()\n self.node.destroy()\n def init(self, flist):\n top.bind(\"<Escape>\", lambda:self.close())\n" }, { "answer_id": 19550098, "author": "BitMask777", "author_id": 509891, "author_profile": "https://Stackoverflow.com/users/509891", "pm_score": 1, "selected": false, "text": "button color setColor() function setColor(button, color) {\n\n button.addEventListener(\"click\", function()\n {\n button.style.backgroundColor = color;\n }, false);\n}\n\nwindow.onload = function() {\n setColor(document.getElementById(\"StartButton\"), \"green\");\n setColor(document.getElementById(\"StopButton\"), \"red\");\n}\n setColor()" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23574/" ]
256,628
<p>I'm trying to set up a loop where an animation runs a certain number of times, and a function is run before each iteration of the animation. The timing ends up being off, though -- it runs the callback n times, then runs the animation n times. For example:</p> <pre><code>for (var i=0;i&lt;3;i++) { console.log(i); $('#blerg').animate({top:'+=50px'},75,'linear', function(){log('animated')}); } </code></pre> <p>outputs</p> <pre><code>0 1 2 animated animated animated </code></pre> <p>I ran into this problem with scriptaculous before I switched to jquery, and discovered a "beforeSetup" animation callback. Is there a jquery equivalent?</p>
[ { "answer_id": 256645, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 2, "selected": false, "text": "do_animation(max_runs, total_runs) {\n log();\n if (total_runs < max_runs) {\n $(foo).animate(..., do_animation(max_runs, ++total_runs));\n }\n}\n" }, { "answer_id": 256688, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "/* Safe Namespace + Onload : I do this everywhere */\njQuery(function($){ \n /* Calling this once instead of many times will save \n a lot of wasted calls to document.getElementById + processing garbage \n */\n var blerg = $('#blerg');\n var addStep = function( i )\n {\n blerg.queue(function(){ \n console.log(i);\n $(this).dequeue();\n }); \n blerg.animate({top:'+=50px'},75,'linear'); \n /* In theory, this works like the callback does */\n blerg.queue(function(){\n log('animated');\n $(this).dequeue();\n });\n };\n\n for (var i=0;i<3;i++) \n {\n /* I call a function here, because that way you don't need to worry \n about the fact 'i' will reference the last value of 'i' when the code \n gets around to executing. */\n addStep(i); \n }\n});\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33391/" ]
256,647
<p>I want to see how long a function takes to run. What's the easiest way to do this in PLT-Scheme? Ideally I'd want to be able to do something like this:</p> <pre><code>&gt; (define (loopy times) (if (zero? times) 0 (loopy (sub1 times)))) &gt; (loopy 5000000) 0 ;(after about a second) &gt; (timed (loopy 5000000)) Took: 0.93 seconds 0 &gt; </code></pre> <p>It doesn't matter if I'd have to use some other syntax like <code>(timed loopy 5000000)</code> or <code>(timed '(loopy 5000000))</code>, or if it returns the time taken in a cons or something.</p>
[ { "answer_id": 256652, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "(time-apply proc arg-list) > (time-apply loopy '(5000000))\n(0)\n621\n887\n0\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
256,700
<p>What is a view in Oracle?</p>
[ { "answer_id": 256703, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 7, "selected": false, "text": "SELECT customerid, customername FROM customers WHERE countryid='US';\n CREATE VIEW view_uscustomers\nAS\nSELECT customerid, customername FROM customers WHERE countryid='US';\n SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200;\n SELECT * \nFROM (select customerid, customername from customers WHERE countryid='US') \nWHERE customerid BETWEEN 100 AND 200\n" }, { "answer_id": 5867837, "author": "shubham", "author_id": 735896, "author_profile": "https://Stackoverflow.com/users/735896", "pm_score": 2, "selected": false, "text": "SELECT CREATE OR REPLACE VIEW <view_name> AS\n SELECT <any valid select query>;\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
256,702
<p>I have used something like the following to compose policies for my application:</p> <p>The policy classes look like this:</p> <pre><code>struct Policy { static void init(); static void cleanup(); //... }; template &lt;class CarT, class CdrT&gt; struct Cons { static void init() { CarT::init(); CdrT::init(); } static void cleanup() { CdrT::cleanup(); CarT::cleanup(); } //... }; </code></pre> <p>To compose policies:</p> <pre><code>typedef Cons&lt;Policy1, Cons&lt;Policy2, Cons&lt;Policy3, Policy4&gt; &gt; &gt; MyPolicy; </code></pre> <p>To use MyPolicy:</p> <pre><code>init_with&lt;MyPolicy&gt;(...); //... cleanup_with&lt;MyPolicy&gt;(...); </code></pre> <p>where they'd call:</p> <pre><code>MyPolicy::init_options(); // calls Policy1 to 4's init in order </code></pre> <p>and</p> <pre><code>MyPolicy::cleanup(); // calls Policy1 to 4's cleanup in reverse order </code></pre> <p>Essentially, Cons constructs a type list here. It's pretty straight forward. However the typedef cons line is kinda ugly. It'll be ideal to have policy combiner that can do this:</p> <pre><code>typedef CombinePolicy&lt;Policy1, Policy2, Policy3, Policy4&gt; MyPolicy; </code></pre> <p>Since we can have arbitrary number of policies, the CombinePolicy would need variadic template support in C++0x, which is only available experimentally in cutting edge compilers. However, it seems that boost:mpl library solved/worked around the problem by using a bunch preprocessing tricks. I <em>guess</em> I could use something like:</p> <pre><code>typedef mpl::list&lt;Policy, Policy2, Policy3, Policy4&gt; Policies; </code></pre> <p>and then calls:</p> <pre><code>init_with&lt;Policies&gt;(...); </code></pre> <p>which would then use:</p> <pre><code>typedef iter_fold&lt;Policies, begin&lt;Policies&gt;::type, some_magic_lambda_expression&gt;::type MyPolicy; </code></pre> <p>Obviously, I have a little trouble figuring out <em>some_magic_lambda_expression</em> here. I'm sure it's quite trivial for mpl experts here.</p> <p>Thanks in advance.</p>
[ { "answer_id": 256860, "author": "tabdamage", "author_id": 28022, "author_profile": "https://Stackoverflow.com/users/28022", "pm_score": 1, "selected": false, "text": "for_each<Policies>(InitPolicy());\n struct InitPolicy() {\n template<class Policy>\n void operator() (Policy& p) { p.init_options(); }\n};\n" }, { "answer_id": 257270, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 1, "selected": false, "text": "typedef \n iter_fold<\n Policies,\n begin<Policies>::type,\n Cons<_1,_2>\n >::type\n MyType;\n" }, { "answer_id": 260750, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 3, "selected": false, "text": "typedef fold<Policies, Null, Cons<_1, _2> >::type MyPolicy;\n struct Null { };\n\ntemplate<class PolicyT>\nstruct Cons<Null, PolicyT> {\n static void init() { PolicyT::init(); }\n static void cleanup() { PolicyT::cleanup(); }\n};\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28888/" ]
256,719
<p>In most versions of windows, you can get to the menu by pressing the F10 key, thus avoiding having to use the mouse. This behaviour does not appear to be present in Windows Mobile 5.0, but is desirable as the device I am using will be more keyboard than touch screen driven. </p> <p>Is there a way of programmatically activating and using the menu on Windows Mobile 5.0, under C++ using either MFC or Windows API calls. I have tried setting the focus of the CFrameWnd and CCeCommandBar classes to no avail.</p>
[ { "answer_id": 256777, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": true, "text": "void CMyFrame::OnFocusMenu()\n{\n PostMessage(WM_SYSCOMMAND,SC_KEYMENU,0);\n}\n ::SetActiveWindow(m_wndCommandBar.m_hWnd);\nm_wndCommandBar.PostMessage(WM_ACTIVATE,WA_ACTIVE,0);\nm_wndCommandBar.PostMessage(WM_LBUTTONDOWN,0,0);\nm_wndCommandBar.PostMessage(WM_LBUTTONUP,0,0);\nm_wndCommandBar.OnActivate(WA_ACTIVE, NULL, FALSE);\nm_wndCommandBar.SetFocus();\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22564/" ]
256,723
<p>We are using Subversion. We would like to </p> <pre><code>1. search across all commit messages ? 2. monitor the commits on certain important files ? 3. identify files that are never/rarely used ? 4. identify files that are most frequently changed ? 5. identify files that most developers have accessed ? 6. identify files that have been committed together many number of times ? </code></pre> <p>The usage of these data could be to weed out messages like <a href="https://stackoverflow.com/questions/216876/what-is-the-best-commit-message-you-have-ever-encountered#255762">these</a>, to refactor code and clean up the project of unused files. </p> <p>Please suggest tools to achieve the same.. </p> <p><b>EDIT:</b> We run SVN on Windows 2003.</p>
[ { "answer_id": 256727, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "sed" }, { "answer_id": 257141, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 1, "selected": false, "text": "1. search across all commit messages ?\n 2. monitor the commits on certain important files ?\n 3. identify files that are never/rarely used ?\n4. identify files that are most frequently changed ? \n5. identify files that most developers have accessed ?\n6. identify files that have been committed together many number of times ?\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27474/" ]
256,724
<p>In C++, is it safe to extend scope via a reference?</p> <p>In code, what I mean is: </p> <pre><code>MyCLass&amp; function badIdea() { MyClass obj1; ... return obj1; } </code></pre>
[ { "answer_id": 256741, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 1, "selected": false, "text": "int * p = NULL;\n{\n int y = 22;\n p = &y;\n}\n*p = 77; // BOOM!\n" }, { "answer_id": 256748, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 4, "selected": false, "text": "const namespace const int & cir = 1+1; // OK to use cir = 2 after this line \n const" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
256,728
<pre><code>function AddTheatres() { Services.AdminWebServices.AddTheatresSVC(oTheatres, OnSuccessTheatres, OnError, OnTimeOut); } function OnSuccessTheatres(result1) { Services.AdminWebServices.AddTicketPricesSVC(oTicketPrices, OnSuccessTicketPrices, OnError, OnTimeOut); //working } function OnSuccessTicketPrices(result2) { alert(result2); //not working } </code></pre> <p>Why is the alert not working? On Debugging the function calling <code>AddTicketPricesSVC</code> is returning correct value.</p>
[ { "answer_id": 256747, "author": "naveen", "author_id": 17447, "author_profile": "https://Stackoverflow.com/users/17447", "pm_score": 0, "selected": false, "text": "function OnError(error)\n{\n alert(error.get_message());\n}\nfunction OnTimeOut()\n{\n alert('System Time Out');\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
256,729
<p>I have a regular expression to match a persons name.</p> <p>So far I have ^([a-zA-Z\'\s]+)$ but id like to add a check to allow for a maximum of 4 spaces. How do I amend it to do this?</p> <p><strong>Edit:</strong> what i meant was 4 spaces anywhere in the string</p>
[ { "answer_id": 256735, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "1: Get Input \n2: Trim White Space\n3: If this makes sence, trim out any 'bad' characters. \n4: Use the \"split\" utility provided by your language to break it into words\n5: Return the first 5 Words. \n sub getNames{\n my @args = @_;\n my $text = shift @args;\n my $num = shift @args;\n\n # Trim Whitespace from Head/End\n $text =~ s/^\\s*//;\n $text =~ s/\\s*$//;\n\n # Trim Bad Characters (??)\n $text =~ s/[^a-zA-Z\\'\\s]//g;\n\n # Tokenise By Space \n my @words = split( /\\s+/, $text );\n\n #return 0..n \n return @words[ 0 .. $num - 1 ];\n} ## end sub getNames\n\nprint join \",\", getNames \" Hello world this is a good test\", 5;\n>> Hello,world,this,is,a\n /([^\\s]+\n (\\s[^\\s]+\n (\\s[^\\s]+\n (\\s[^\\s]+\n (\\s[^\\s]+|)\n |)\n |)\n |)\n )/ \n /([^\\s]+(\\s[^\\s]+(\\s[^\\s]+(\\s[^\\s]+|)|)|))/ \n [^\\s]+ (Hello( this( is( example))))\n(Hello( this( is( example( two)))))\n(Hello( this( is( better( example))))) three\n(Hello( this( is()))))\n(Hello( this()))\n(Hello())\n $word = '[^\\s]+'; \n $regex = \"/($word(\\s$word(\\s$word(\\s$word(\\s$word|)|)|)|)|)/\"; \n" }, { "answer_id": 256737, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "^([a-zA-Z']+\\s){0,4}[a-zA-Z']+$ substr_count" }, { "answer_id": 256789, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": false, "text": "^ # Start of string\n(?!\\S*(?:\\s\\S*){5}) # Negative look-ahead for five spaces.\n([a-zA-Z\\'\\s]+)$ # Original regex\n ^(?!(?:\\S*\\s){5})([a-zA-Z\\'\\s]+)$\n" }, { "answer_id": 256805, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "^[a-zA-Z']+(\\s[a-zA-Z']+){0,4}$\n" }, { "answer_id": 17335836, "author": "Ketan.G", "author_id": 2526806, "author_profile": "https://Stackoverflow.com/users/2526806", "pm_score": -1, "selected": false, "text": "select 'This is a long string with 2 chars at the end AB' as \"C1\", regexp_replace('This is a long string with 2 chars at the end AB',\n '[[[:space:]][a-zA-Z][a-zA-Z]]*$') as \"C2\" from dual; C1 This is a long string with 2 chars at the end AB C2 This is a long string with 2 chars at the end" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
256,754
<p>The situation is somewhat like-</p> <pre><code>var someVar = some_other_function(); someObj.addEventListener("click", function(){ some_function(someVar); }, false); </code></pre> <p>The problem is that the value of <code>someVar</code> is not visible inside the listener function of the <code>addEventListener</code>, where it is probably being treated as a new variable.</p>
[ { "answer_id": 256763, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 9, "selected": true, "text": "some_function someVar function() { some_function(someVar); } \n someVar addEventListener var someVar; \nsomeVar = some_other_function();\nalert(someVar);\nsomeObj.addEventListener(\"click\", function(){\n some_function(someVar);\n}, false);\n" }, { "answer_id": 256945, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 3, "selected": false, "text": "someVar some_function() someObj.addEventListener(\"click\",\n function(){\n var newVar = someVar;\n some_function(someVar);\n },\n false);\n newVar someVar some_function() var someVar = some_function(someVar);\n" }, { "answer_id": 3696345, "author": "Ganesh Krishnan", "author_id": 436620, "author_profile": "https://Stackoverflow.com/users/436620", "pm_score": 5, "selected": false, "text": "myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false); newSrc funcName myaudio.removeEventListener('ended',func,false);" }, { "answer_id": 8202901, "author": "DMike92", "author_id": 1056540, "author_profile": "https://Stackoverflow.com/users/1056540", "pm_score": 1, "selected": false, "text": "function addEvent(obj, type, fn) {\n eval('obj.on'+type+'=fn');\n}\n\nfunction removeEvent(obj, type) {\n eval('obj.on'+type+'=null');\n}\n\n// Use :\n\nfunction someFunction (someArg) {alert(someArg);}\n\nvar object=document.getElementById('somObject_id') ;\nvar someArg=\"Hi there !\";\nvar func=function(){someFunction (someArg)};\n\n// mouseover is inactive\naddEvent (object, 'mouseover', func);\n// mouseover is now active\naddEvent (object, 'mouseover');\n// mouseover is inactive\n" }, { "answer_id": 11515561, "author": "kta", "author_id": 539023, "author_profile": "https://Stackoverflow.com/users/539023", "pm_score": 3, "selected": false, "text": " el.addEventListener('click',\n function(){\n // this will give you the id value \n alert(this.id); \n },\nfalse);\n // this will dynamically create property a property\n // you can create anything like el.<your variable>\n el.myvalue = \"hello world\";\n el.addEventListener('click',\n function(){\n //this will show you the myvalue \n alert(el.myvalue);\n // this will give you the id value \n alert(this.id); \n },\nfalse);\n" }, { "answer_id": 11986895, "author": "Zaloz", "author_id": 1603177, "author_profile": "https://Stackoverflow.com/users/1603177", "pm_score": 9, "selected": false, "text": "const someInput = document.querySelector('button');\nsomeInput.addEventListener('click', myFunc, false);\nsomeInput.myParam = 'This is my parameter';\nfunction myFunc(evt)\n{\n window.alert(evt.currentTarget.myParam);\n} <button class=\"input\">Show parameter</button>" }, { "answer_id": 16595873, "author": "Brian Moore", "author_id": 623315, "author_profile": "https://Stackoverflow.com/users/623315", "pm_score": 7, "selected": false, "text": ".bind() function some_func(otherFunc, ev) {\n // magic happens\n}\nsomeObj.addEventListener(\"click\", some_func.bind(null, some_other_func), false);\n" }, { "answer_id": 21552207, "author": "eclos", "author_id": 3270790, "author_profile": "https://Stackoverflow.com/users/3270790", "pm_score": 4, "selected": false, "text": "this someObj.addEventListener(\"click\", some_function.bind(this), false);\n someObj.addEventListener(\"click\", some_function.bind(this, arg1, arg2), false);\n this someObj.addEventListener(\"click\", some_function.bind(null, arg1, arg2), false);\n" }, { "answer_id": 23024673, "author": "Oleksandr Tkalenko", "author_id": 1027440, "author_profile": "https://Stackoverflow.com/users/1027440", "pm_score": 5, "selected": false, "text": "root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));\n event arg1 myPrettyHandler" }, { "answer_id": 23636295, "author": "fhuertas", "author_id": 3567642, "author_profile": "https://Stackoverflow.com/users/3567642", "pm_score": -1, "selected": false, "text": "for (var key in catalog){\n document.getElementById(key).my_id = key\n document.getElementById(key).addEventListener('click', function(e) {\n editorContent.loadCatalogEntry(e.srcElement.my_id)\n }, false);\n}\n" }, { "answer_id": 24018543, "author": "Asik", "author_id": 1387002, "author_profile": "https://Stackoverflow.com/users/1387002", "pm_score": 1, "selected": false, "text": "var someVar; \nsomeVar = some_other_function();\nalert(someVar);\nsomeObj.addEventListener(\"click\",\n function(){\n some_function(someVar);\n },\n false);\n var someVar, eventListnerFunc;\nsomeVar = some_other_function();\neventListnerFunc = some_function(someVar);\nsomeObj.addEventListener(\"click\", eventListnerFunc, false);\n" }, { "answer_id": 27908041, "author": "StanE", "author_id": 1854856, "author_profile": "https://Stackoverflow.com/users/1854856", "pm_score": 2, "selected": false, "text": "var someVar = some_other_function();\nsomeObj.addEventListener(\"click\", function(someVar){\n some_function(arguments[0]);\n}, false);\n" }, { "answer_id": 28633276, "author": "Hello World", "author_id": 2347534, "author_profile": "https://Stackoverflow.com/users/2347534", "pm_score": 4, "selected": false, "text": "var someVar = some_other_function();\nsomeObj.addEventListener(\"click\", \n\nfunction(theVar){\n return function(){some_function(theVar)};\n}(someVar),\n\nfalse);\n" }, { "answer_id": 30732382, "author": "Šerg", "author_id": 4090695, "author_profile": "https://Stackoverflow.com/users/4090695", "pm_score": 0, "selected": false, "text": "for (var i=0; i<3; i++) {\n element = new ... // create your element\n element.counter = i;\n element.addEventListener('click', function(e){\n console.log(this.counter);\n ... // another code with this element\n }, false);\n}\n 0\n1\n2\n" }, { "answer_id": 31195862, "author": "bob", "author_id": 1088866, "author_profile": "https://Stackoverflow.com/users/1088866", "pm_score": 2, "selected": false, "text": "// Lambda closure chaos.\n//\n// Send an anonymous function to the listener, but execute it immediately.\n// This will cause the arguments are captured, which is useful when running \n// within loops.\n//\n// The anonymous function returns a closure, that will be executed when \n// the event triggers. And since the arguments were captured, any vars \n// that were sent in will be unique to the function.\n\nfunction addListenerWithArgs(elem, evt, func, vars){\n var f = function(ff, vv){\n return (function (){\n ff(vv);\n });\n }(func, vars);\n\n elem.addEventListener(evt, f);\n\n return f;\n}\n\n// Usage:\n\nfunction doSomething(withThis){\n console.log(\"withThis\", withThis);\n}\n\n// Capture the function so we can remove it later.\nvar storeFunc = addListenerWithArgs(someElem, \"click\", doSomething, \"foo\");\n\n// To remove the listener, use the normal routine:\nsomeElem.removeEventListener(\"click\", storeFunc);\n" }, { "answer_id": 32645073, "author": "Gennadiy Sherbakha", "author_id": 5349151, "author_profile": "https://Stackoverflow.com/users/5349151", "pm_score": 1, "selected": false, "text": " var EV = {\n ev: '',\n fn: '',\n elem: '',\n add: function () {\n this.elem.addEventListener(this.ev, this.fn, false);\n }\n };\n\n function cons() {\n console.log('some what');\n }\n\n EV.ev = 'click';\n EV.fn = cons;\n EV.elem = document.getElementById('body');\n EV.add();\n\n//If you want to add one more listener for load event then simply add this two lines of code:\n\n EV.ev = 'load';\n EV.add();\n" }, { "answer_id": 32930248, "author": "Felipe", "author_id": 4173568, "author_profile": "https://Stackoverflow.com/users/4173568", "pm_score": 3, "selected": false, "text": "elem.addEventListener('click', (function(numCopy) {\n return function() {\n alert(numCopy)\n };\n})(num));\n catimg.addEventListener('click', (function(c, i){\n return function() {\n c.meows++;\n i.textContent = c.name + '\\'s meows are: ' + c.meows;\n }\n})(cat, catmeows));\n" }, { "answer_id": 35212752, "author": "Nate", "author_id": 3549440, "author_profile": "https://Stackoverflow.com/users/3549440", "pm_score": 1, "selected": false, "text": "function callback(theVar) {\n return function() {\n theVar();\n }\n}\n\nfunction some_other_function() {\n document.body.innerHTML += \"made it.\";\n}\n\nvar someVar = some_other_function;\ndocument.getElementById('button').addEventListener('click', callback(someVar)); <!DOCTYPE html>\n<html>\n <body>\n <button type=\"button\" id=\"button\">Click Me!</button>\n </body>\n</html>" }, { "answer_id": 35290817, "author": "Suneel Kumar", "author_id": 2301402, "author_profile": "https://Stackoverflow.com/users/2301402", "pm_score": 2, "selected": false, "text": "for (var i = 0; i < states_array.length; i++) {\n var link = document.getElementById('apply_'+states_array[i].state_id);\n link.my_id = i;\n link.addEventListener('click', function(e) { \n alert(e.target.my_id); \n some_function(states_array[e.target.my_id].css_url);\n });\n}\n" }, { "answer_id": 36786630, "author": "ahuigo", "author_id": 2140757, "author_profile": "https://Stackoverflow.com/users/2140757", "pm_score": 4, "selected": false, "text": "var someVar='origin';\nfunc = function(v){\n console.log(v);\n}\ndocument.addEventListener('click',function(someVar){\n return function(){func(someVar)}\n}(someVar));\nsomeVar='changed'\n wrapEventCallback function wrapEventCallback(callback){\n var args = Array.prototype.slice.call(arguments, 1);\n return function(e){\n callback.apply(this, args)\n }\n}\nvar someVar='origin';\nfunc = function(v){\n console.log(v);\n}\ndocument.addEventListener('click',wrapEventCallback(func,someVar))\nsomeVar='changed'\n wrapEventCallback(func,var1,var2) func.bind(null, var1,var2)\n" }, { "answer_id": 45696430, "author": "tomcek112", "author_id": 6691067, "author_profile": "https://Stackoverflow.com/users/6691067", "pm_score": 6, "selected": false, "text": "someObj.addEventListener('click', some_function(someVar));\n\nvar some_function = function(someVar) {\n return function curried_func(e) {\n // do something here\n }\n}\n" }, { "answer_id": 50649380, "author": "Victor Behar", "author_id": 7768934, "author_profile": "https://Stackoverflow.com/users/7768934", "pm_score": 0, "selected": false, "text": "newElem.addEventListener('click', {\n handleEvent: function (event) {\n clickImg(parameter);\n }\n});\n" }, { "answer_id": 53179059, "author": "fnclovers", "author_id": 8145426, "author_profile": "https://Stackoverflow.com/users/8145426", "pm_score": -1, "selected": false, "text": "var some_other_function = someVar => function() {\n}\n\nsomeObj.addEventListener('click', some_other_function(someVar));\n" }, { "answer_id": 54313715, "author": "developer82", "author_id": 2652208, "author_profile": "https://Stackoverflow.com/users/2652208", "pm_score": 3, "selected": false, "text": "bind bind // Possible:\nfunction myCallback() { /* code here */ }\nsomeObject.addEventListener('event', myCallback);\nsomeObject.removeEventListener('event', myCallback);\n\n// Not Possible:\nfunction myCallback() { /* code here */ }\nsomeObject.addEventListener('event', function() { myCallback });\nsomeObject.removeEventListener('event', /* can't remove anonymous function */);\n someObject.addEventListener('event', () => myCallback(params));\n" }, { "answer_id": 54731362, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": 3, "selected": false, "text": " $form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));\n function save(data, keyword, name, comment, event) {\n" }, { "answer_id": 55859799, "author": "Gon82", "author_id": 9212067, "author_profile": "https://Stackoverflow.com/users/9212067", "pm_score": 5, "selected": false, "text": "element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));\n function onDragStart(param1, param2, param3, evt) {\n\n //some action...\n\n}\n" }, { "answer_id": 55925153, "author": "Spoo", "author_id": 2415580, "author_profile": "https://Stackoverflow.com/users/2415580", "pm_score": 0, "selected": false, "text": " function readFiles(input) {\n if (input.files) {\n for(i=0;i<input.files.length;i++) {\n\n var filename = input.files[i].name;\n\n if ( /\\.(jpe?g|jpg|png|gif|svg|bmp)$/i.test(filename) ) {\n readFile(input.files[i],filename);\n }\n }\n }\n } //end readFiles\n\n\n\n function readFile(file,filename) {\n var reader = new FileReader();\n\n reader.addEventListener(\"load\", function() { alert(filename);}, false);\n\n reader.readAsDataURL(file);\n\n } //end readFile\n" }, { "answer_id": 57889478, "author": "Bruce Tong", "author_id": 6131033, "author_profile": "https://Stackoverflow.com/users/6131033", "pm_score": 0, "selected": false, "text": "event.target this" }, { "answer_id": 59418293, "author": "hoogw", "author_id": 3521515, "author_profile": "https://Stackoverflow.com/users/3521515", "pm_score": 3, "selected": false, "text": " button_element = document.getElementById('your-button')\n\n button_element.setAttribute('your-parameter-name',your-parameter-value);\n\n button_element.addEventListener('click', your_function);\n\n\n function your_function(event)\n {\n //when click print the parameter value \n console.log(event.currentTarget.attributes.your-parameter-name.value;)\n }\n" }, { "answer_id": 61986436, "author": "AAYUSH SHAH", "author_id": 9082644, "author_profile": "https://Stackoverflow.com/users/9082644", "pm_score": -1, "selected": false, "text": "function Name()\n{\n\nthis.methodName = \"Value\"\n\n}\n" }, { "answer_id": 63320750, "author": "Michael", "author_id": 14041506, "author_profile": "https://Stackoverflow.com/users/14041506", "pm_score": 1, "selected": false, "text": "someObj.setAttribute(\"onclick\", \"function(parameter)\");\n" }, { "answer_id": 67185345, "author": "Alvaro Gabriel Gomez", "author_id": 10797766, "author_profile": "https://Stackoverflow.com/users/10797766", "pm_score": 3, "selected": false, "text": " window.addEventListener('click', (e) => functionHandler(e, ...args));\n" }, { "answer_id": 70967292, "author": "leafsAsd", "author_id": 11042072, "author_profile": "https://Stackoverflow.com/users/11042072", "pm_score": 1, "selected": false, "text": "var someVar = some_other_function();\nsomeObj.addEventListener(\"click\", (event, param1 = someVar) => {\n some_function(param1);\n}, false);\n" }, { "answer_id": 72380138, "author": "Al Po", "author_id": 1224072, "author_profile": "https://Stackoverflow.com/users/1224072", "pm_score": 1, "selected": false, "text": "function func(){\n console.log(this.dataset.someVar);\n div.removeEventListener(\"click\", func);\n}\n \nvar div = document.getElementById(\"some-div\");\ndiv.setAttribute(\"data-some-var\", \"hello\");\ndiv.addEventListener(\"click\", func);\n" }, { "answer_id": 74127970, "author": "Dejan Dozet", "author_id": 4541566, "author_profile": "https://Stackoverflow.com/users/4541566", "pm_score": 1, "selected": false, "text": "function makeSizer(size) {\n return function () {\n document.body.style.fontSize = `${size}px`;\n };\n}\n\n//pass parameters here and keep the reference in variables:\nconst size12 = makeSizer(12);\nconst size24 = makeSizer(24);\nconst size36 = makeSizer(36);\n\ndocument.getElementById('size-12').addEventListener(\"click\", size12);\ndocument.getElementById('size-24').addEventListener(\"click\", size24);\ndocument.getElementById('size-36').addEventListener(\"click\", size36);\n\ndocument.getElementById('remove-12').addEventListener(\"click\", ()=>{\n document.getElementById('size-12').removeEventListener(\"click\", size12);\n alert(\"Now click on 'size 12' button and you will see that there is no event listener any more\");\n}); test<br/>\n<button id=\"size-12\">\nsize 12\n</button>\n\n<button id=\"size-24\">\nsize 24\n</button>\n\n<button id=\"size-36\">\nsize 36\n</button>\n\n<button id=\"remove-12\">\nremove 12\n</button>" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30252/" ]
256,803
<p>A few days ago, I asked <a href="https://stackoverflow.com/questions/242577/c-what-is-string-really-good-for">why its not possible to store binary data, such as a jpg file into a string variable</a>.</p> <p>Most of the answers I got said that string is used for textual information such as what I'm writing now.</p> <p>What is considered textual data though? Bytes of a certain nature represent a jpg file and those bytes could be represented by character byte values...I think. So when we say strings are for textual information, is there some sort of range or list of characters that aren't stored?</p> <p>Sorry if the question sounds silly. Just trying to 'get it'</p>
[ { "answer_id": 256824, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "byte[] myJpegByteArray = GetBytesFromSomeImage();\n\nstring myString = Encoding.ASCII.GetString(myJpegByteArray);\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
256,804
<p>Is there a way to execute SQL custom functions with Enterpise Library? I've tried Database.ExecuteScalar() but for some reason it returns null.</p> <p>This is my function:</p> <pre><code>Database db = DatabaseFactory.CreateDatabase("ConnectionString"); DbCommand cmd = db.GetStoredProcCommand("FunctionName"); db.AddInParameter(cmd, "Value1", DbType.String, Param1Value); db.AddInParameter(cmd, "Value2", DbType.String, Param2Value); return Convert.ToBoolean(db.ExecuteScalar(cmd)); </code></pre> <p>Here the db.ExecuteScalar(cmd) method returns null. This does not happen with Stored Procedures.</p> <p>By the way, im using version 4.0</p> <p>Thanks.</p>
[ { "answer_id": 256898, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 2, "selected": false, "text": "SELECT FuncName(@Param1)\n SELECT * FROM FuncName(@Param1)\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14533/" ]
256,806
<p>A common pattern in C++ is to create a class that wraps a lock - the lock is either implicitly taken when object is created, or taken explicitly afterwards. When object goes out of scope, dtor automatically releases the lock. Is it possible to do this in C#? As far as I understand there are no guarantees on when dtor in C# will run after object goes out of scope.</p> <p>Clarification: Any lock in general, spinlock, ReaderWriterLock, whatever. Calling Dispose myself defeats the purpose of the pattern - to have the lock released as soon as we exit scope - no matter if we called return in the middle, threw exception or whatnot. Also, as far as I understand using will still only queue object for GC, not destroy it immediately...</p>
[ { "answer_id": 256818, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "lock (_myLockKey) { ... }\n" }, { "answer_id": 256842, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 4, "selected": false, "text": "lock(_lockKey)\n{\n // Code under lock\n}\n\n// is equivalent to this\nMonitor.Enter(_lockKey)\ntry\n{\n // Code under lock\n}\nfinally\n{\n Monitor.Exit(_lockKey)\n}\n" }, { "answer_id": 256844, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 4, "selected": true, "text": "using lock using" }, { "answer_id": 256917, "author": "philsquared", "author_id": 32136, "author_profile": "https://Stackoverflow.com/users/32136", "pm_score": 2, "selected": false, "text": "using IDisposable using using \nfunkyObj.InOut( delegate{ System.Console.WriteLine( \"middle bit\" ); } );\n using IDisposable lock using" }, { "answer_id": 337152, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 0, "selected": false, "text": "using public class MyLockedResource : IDisposable\n{\n private MyLockedResource()\n {\n Console.WriteLine(\"initialize\");\n }\n\n public void Dispose()\n {\n Console.WriteLine(\"dispose\");\n }\n\n public delegate void RAII(MyLockedResource resource);\n\n static public void Use(RAII raii)\n {\n using (MyLockedResource resource = new MyLockedResource())\n {\n raii(resource);\n }\n }\n\n public void test()\n {\n Console.WriteLine(\"test\");\n }\n}\n MyLockedResource.Use(delegate(MyLockedResource resource)\n{\n resource.test();\n});\n MyLockedResource res = null;\nMyLockedResource.Use(delegate(MyLockedResource resource)\n{\n resource.test();\n res = resource;\n res.test();\n});\nres.test();\n" }, { "answer_id": 55494632, "author": "Yola", "author_id": 312896, "author_profile": "https://Stackoverflow.com/users/312896", "pm_score": 1, "selected": false, "text": "lock(obj) {\n ... some logic goes here\n}\n try lock try lock" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33426/" ]
256,807
<p>Is there any way to check if a given index of an array exists? I am trying to set numerical index but something like 1, 5, 6,10. And so I want to see if these indexes already exist and if they do just increase another counter.</p> <p>I normally work with php but I am trying to do this in c++, so basically I am trying to ask if there is an isset() way to use with c++</p> <p>PS: Would this be easier with vectors? If so, can anyone point me to a good vector tutorial? Thanks</p>
[ { "answer_id": 256825, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": 4, "selected": true, "text": "int i[10];\ni[10] = 2; // Legal but very dangerous! Writing on memory you don't know about\n #include <map>\n#include <string>\n\n// Declare the map - integer keys, string values \nstd::map<int, std::string> a;\n\n// Add an item at an arbitrary location\na[2] = std::string(\"A string\");\n\n// Find a key that isn't present\nif(a.find(1) == a.end())\n{\n // This code will be run in this example\n std::cout << \"Not found\" << std::endl;\n}\nelse\n{\n std::cout << \"Found\" << std::endl;\n}\n if(a[2] == 0)\n{\n a[2] = myValueToPutIn;\n}\n" }, { "answer_id": 31472020, "author": "MukeshD", "author_id": 2679111, "author_profile": "https://Stackoverflow.com/users/2679111", "pm_score": 2, "selected": false, "text": "if(index < array_size) sizeof int arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};\nint arr_size = sizeof(arr)/sizeof(arr[0]);\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
256,811
<p>How do you create non scrolling div that looks like the MS Office 2007 ribbon on a web page without two sets of scroll bars. One for the window and one for the div.</p>
[ { "answer_id": 256830, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 3, "selected": false, "text": "<div> z-index <div> <div> <body>\n <div style=\"position: fixed; top: 0px; width:100%; height: 100px;\">\n HEader content goes here\n </div>\n <div style=\"margin-top: 100px;\">\n Main content goes here\n </div>\n</body>\n <div>" }, { "answer_id": 256870, "author": "Nikola Stjelja", "author_id": 32582, "author_profile": "https://Stackoverflow.com/users/32582", "pm_score": 0, "selected": false, "text": "\n<div style='position:absolute;top:0px:left:0px;'>Text</div>;\n" }, { "answer_id": 258404, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 0, "selected": false, "text": "<style type=\"text/css\">\n div#fixme {\n width: 100%; /* For all browsers */\n }\n body > div#fixme {\n position: fixed; /* For good browsers */\n }\n</style>\n\n<!--[if gte IE 5.5]>\n<![if lt IE 7]>\n<style type=\"text/css\">\n div#fixme {\n /* IE5.5+/Win - this is more specific than the IE 5.0 version */\n right: auto; bottom: auto;\n left: expression( ( 0 - fixme.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );\n top: expression( ( 0 - fixme.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );\n }\n</style>\n<![endif]>\n<![endif]-->\n\n<body>\n <div id=\"fixme\"> ...\n" }, { "answer_id": 258967, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <title>Fixed Header/Full Page Content</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n <style type=\"text/css\">\n body,\n div {\n margin: 0;\n padding: 0;\n }\n\n body {\n /* Disable scrollbars and ensure that the body fills the window */\n overflow: hidden;\n width: 100%;\n height: 100%;\n }\n\n #header {\n /* Provide scrollbars if needed and fix the header dimensions */\n overflow: auto;\n position: absolute;\n width: 100%;\n height: 200px;\n }\n\n #main {\n /* Provide scrollbars if needed, position below header, and derive height from top/bottom */\n overflow: auto;\n position: absolute;\n width: 100%;\n top: 200px;\n bottom: 0;\n }\n </style>\n </head>\n <body>\n <div id=\"header\">HEADER</div>\n <div id=\"main\">\n <p>FIRST</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>MAIN</p>\n <p>LAST</p>\n </div>\n<!--[if lt IE 7]>\n <script type=\"text/javascript\">\n var elMain = document.getElementById('main');\n\n setMainDims();\n document.body.onresize = setMainDims;\n\n function setMainDims() {\n elMain.style.height = (document.body.clientHeight - 200) + 'px';\n elMain.style.width = '99%'\n setTimeout(\"elMain.style.width = '100%'\", 0);\n }\n </script>\n<![endif]-->\n </body>\n</html>\n #main top bottom height #main" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
256,822
<p>In RoR,how to validate a Chinese or a Japanese word for a posting form with utf8 code.</p> <p>In GBK code, it uses [\u4e00-\u9fa5]+ to validate Chinese words. In Php, it uses /^[\x{4e00}-\x{9fa5}]+$/u for utf-8 pages.</p>
[ { "answer_id": 256855, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 3, "selected": false, "text": ">> \"acentuação\".scan(/\\xC3\\xA7/)\n=> [\"ç\"] \n /([\\x4E-\\x9E][\\x00-\\xFF])|(\\x9F[\\x00-\\xA5])/ # (untested)\n" }, { "answer_id": 1971006, "author": "Jose Barrera", "author_id": 239738, "author_profile": "https://Stackoverflow.com/users/239738", "pm_score": 2, "selected": false, "text": "%r{^[#{\"\\344\\270\\200\"}-#{\"\\351\\277\\277\"}]+$}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20191/" ]
256,823
<p>The scenario is trying to adjust font size to get a nice graphic arrangement, or trying to decide where to break a caption/subtitle. a) In XL VBA is there a way to find out whether a text on a textbox, or caption on a label, still fits the control? b) Is there a way to know where was the text/caption broken on multiline control?</p>
[ { "answer_id": 257458, "author": "jpinto3912", "author_id": 11567, "author_profile": "https://Stackoverflow.com/users/11567", "pm_score": 3, "selected": true, "text": "Function TextWidth(aText As String, Optional aFont As NewFont) As Single\n Dim theFont As New NewFont\n Dim notSeenTBox As Control\n\n On Error Resume Next 'trap for aFont=Nothing\n theFont = aFont 'try assign\n\n If Err.Number Then 'can't use aFont because it's not instantiated/set\n theFont.Name = \"Tahoma\"\n theFont.Size = 8\n theFont.Bold = False\n theFont.Italic = False\n End If\n On Error GoTo ErrHandler\n\n 'make a TextBox, fiddle with autosize et al, retrive control width\n Set notSeenTBox = UserForms(0).Controls.Add(\"Forms.TextBox.1\", \"notSeen1\", False)\n notSeenTBox.MultiLine = False\n notSeenTBox.AutoSize = True 'the trick\n notSeenTBox.Font.Name = theFont.Name\n notSeenTBox.SpecialEffect = 0\n notSeenTBox.Width = 0 ' otherwise we get an offset (a \"\"feature\"\" from MS)\n notSeenTBox.Text = aText\n TextWidth = notSeenTBox.Width\n 'done with it, to scrap I say\n UserForms(0).Controls.Remove (\"notSeen1\")\n Exit Function\n\nErrHandler:\n TextWidth = -1\n MsgBox \"TextWidth failed: \" + Err.Description\nEnd Function\n" }, { "answer_id": 68120747, "author": "Wayne Hoff", "author_id": 16309261, "author_profile": "https://Stackoverflow.com/users/16309261", "pm_score": 0, "selected": false, "text": "Public Sub ResizeTextToFit(Ctrl As MSForms.Label) 'or TextBox\n \n Const FONT_SHRINKAGE_FACTOR As Single = 0.9 'For more accuracy, use .95 or .99\n \n Dim OrigWidth As Single\n Dim OrigHeight As Single\n Dim OrigLeft As Single\n Dim OrigTop As Single\n \n With Ctrl\n If .Caption = \"\" Then Exit Sub\n .AutoSize = False\n OrigWidth = .Width\n OrigHeight = .Height\n OrigLeft = .Left\n OrigTop = .Top\n Do\n .AutoSize = True\n If .Width <= OrigWidth And .Height <= OrigHeight Then\n Exit Do 'The font is small enough now\n .Font.Size = .Font.Size * FONT_SHRINKAGE_FACTOR\n .AutoSize = False\n Loop\n .AutoSize = False\n .Width = OrigWidth\n .Height = OrigHeight\n .Left = OrigLeft\n .Top = OrigTop\n End With\n\nEnd Sub\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11567/" ]
256,832
<p>I'm used to work with Java where large amounts of examples are available. For various reasons I had to switch to C# and trying to do the following in SharpDevelop:</p> <pre><code>// Form has a menu containing a combobox added via SharpDevelop's GUI // --- Variables languages = new string[2]; languages[0] = "English"; languages[1] = "German"; DataSet myDataSet = new DataSet(); // --- Preparation DataTable lTable = new DataTable("Lang"); DataColumn lName = new DataColumn("Language", typeof(string)); lTable.Columns.Add( lName ); for( int i=0; i&lt;languages.Length; i++ ) { DataRow lLang = lTable.NewRow(); lLang["Language"] = languages[i]; lTable.Rows.Add(lLang); } myDataSet.Tables.Add(lTable); // --- Handling the combobox mnuActionLanguage.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView; mnuActionLanguage.ComboBox.DisplayMember = "Language"; </code></pre> <p>One would assume to see some values in the dropdown, but it's empty. Please tell me what I'm doing wrong ;(</p> <p><em>EDIT: mnuActionLanguage.ComboBox.DataBind() is what I also found on the net, but it doesn't work in my case.</em></p> <p><strong>SOLUTION</strong></p> <pre><code>mnuActionLanguage.ComboBox.BindingContext = this.BindingContext; </code></pre> <p>at the end solved the problem!</p>
[ { "answer_id": 256840, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 0, "selected": false, "text": "mnuActionLanguage.ComboBox.DisplayMember = \"Lang.Language\";\n mnuActionLanguage.ComboBox.DisplayMember = \"Language\";\n" }, { "answer_id": 256854, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "mnuActionLanguage.ComboBox.DataSource = languages;\n" }, { "answer_id": 256864, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": false, "text": "mnuActionLanguage.ComboBox.DataSource = lTable.DefaultView;\nmnuActionLanguage.ComboBox.DisplayMember = lName.ColumnName;" }, { "answer_id": 256871, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": 6, "selected": true, "text": "var languages = new string[2];\nlanguages[0] = \"English\";\nlanguages[1] = \"German\";\n\nDataSet myDataSet = new DataSet();\n\n// --- Preparation\nDataTable lTable = new DataTable(\"Lang\");\nDataColumn lName = new DataColumn(\"Language\", typeof(string));\nlTable.Columns.Add(lName);\n\nfor (int i = 0; i < languages.Length; i++)\n{\n DataRow lLang = lTable.NewRow();\n lLang[\"Language\"] = languages[i];\n lTable.Rows.Add(lLang);\n}\nmyDataSet.Tables.Add(lTable);\n\ntoolStripComboBox1.ComboBox.DataSource = myDataSet.Tables[\"Lang\"].DefaultView;\ntoolStripComboBox1.ComboBox.DisplayMember = \"Language\";\n\ntoolStripComboBox1.ComboBox.BindingContext = this.BindingContext;\n" }, { "answer_id": 5660011, "author": "Nidz", "author_id": 579496, "author_profile": "https://Stackoverflow.com/users/579496", "pm_score": 3, "selected": false, "text": "string strConn = \"Data Source=SEZSW08;Initial Catalog=Nidhi;Integrated Security=True\";\nSqlConnection Con = new SqlConnection(strConn);\nCon.Open();\nstring strCmd = \"select companyName from companyinfo where CompanyName='\" + cmbCompName.SelectedValue + \"';\";\nSqlDataAdapter da = new SqlDataAdapter(strCmd, Con);\nDataSet ds = new DataSet();\nCon.Close();\nda.Fill(ds);\ncmbCompName.DataSource = ds;\ncmbCompName.DisplayMember = \"CompanyName\";\ncmbCompName.ValueMember = \"CompanyName\";\n//cmbCompName.DataBind();\ncmbCompName.Enabled = true;\n" }, { "answer_id": 40449714, "author": "Masoud Siahkali", "author_id": 6687274, "author_profile": "https://Stackoverflow.com/users/6687274", "pm_score": 3, "selected": false, "text": "DataTable dt = new DataTable ();\ndt.Columns.Add(\"Title\", typeof(string));\ndt.Columns.Add(\"Value\", typeof(int));\n DataRow row = dt.NewRow();\nrow[\"Title\"] = \"Price\"\nrow[\"Value\"] = 2000;\ndt.Rows.Add(row);\n dt.Rows.Add(\"Price\",2000);\n combo.DataSource = dt;\ncombo.DisplayMember = \"Title\";\ncombo.ValueMember = \"Value\";\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33429/" ]
256,859
<p>What, if any, is the performance difference between the following two loops?</p> <pre><code>for (Object o: objectArrayList) { o.DoSomething(); } </code></pre> <p>and </p> <pre><code>for (int i=0; i&lt;objectArrayList.size(); i++) { objectArrayList.get(i).DoSomething(); } </code></pre>
[ { "answer_id": 256861, "author": "Vijay Dev", "author_id": 27474, "author_profile": "https://Stackoverflow.com/users/27474", "pm_score": 9, "selected": true, "text": "// The preferred idiom for iterating over collections and arrays\nfor (Element e : elements) {\n doSomething(e);\n}\n" }, { "answer_id": 257009, "author": "P Arrayah", "author_id": 33459, "author_profile": "https://Stackoverflow.com/users/33459", "pm_score": 5, "selected": false, "text": "for (int i=0; i < strings.size(); i++) { /* do something using strings.get(i) */ }\n for (String s : strings) { /* do something using s */ }\n int size = strings.size();\nfor (int i = -1; ++i < size;) { /* do something using strings.get(i) */ }\n" }, { "answer_id": 580210, "author": "Sarmun", "author_id": 70173, "author_profile": "https://Stackoverflow.com/users/70173", "pm_score": 4, "selected": false, "text": "RandomAccess for (int i=0, n=list.size(); i < n; i++)\n list.get(i);\n for (Iterator i=list.iterator(); i.hasNext();)\n i.next();\n ArrayList" }, { "answer_id": 12168053, "author": "Wibowit", "author_id": 492749, "author_profile": "https://Stackoverflow.com/users/492749", "pm_score": 2, "selected": false, "text": "import java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.List;\n\ninterface Function<T> {\n long perform(T parameter, long x);\n}\n\nclass MyArray<T> {\n\n T[] array;\n long x;\n\n public MyArray(int size, Class<T> type, long x) {\n array = (T[]) Array.newInstance(type, size);\n this.x = x;\n }\n\n public void forEach(Function<T> function) {\n for (T element : array) {\n x = function.perform(element, x);\n }\n }\n}\n\nclass Compute {\n int factor;\n final long constant;\n\n public Compute(int factor, long constant) {\n this.factor = factor;\n this.constant = constant;\n }\n\n public long compute(long parameter, long x) {\n return x * factor + parameter + constant;\n }\n}\n\npublic class Main {\n\n public static void main(String[] args) {\n List<Long> numbers = new ArrayList<Long>(50000000);\n for (int i = 0; i < 50000000; i++) {\n numbers.add(i * i + 5L);\n }\n\n long x = 234553523525L;\n\n long time = System.currentTimeMillis();\n for (int i = 0; i < numbers.size(); i++) {\n x += x * 7 + numbers.get(i) + 3;\n }\n System.out.println(System.currentTimeMillis() - time);\n System.out.println(x);\n x = 0;\n time = System.currentTimeMillis();\n for (long i : numbers) {\n x += x * 7 + i + 3;\n }\n System.out.println(System.currentTimeMillis() - time);\n System.out.println(x);\n x = 0;\n numbers = null;\n MyArray<Long> myArray = new MyArray<Long>(50000000, Long.class, 234553523525L);\n for (int i = 0; i < 50000000; i++) {\n myArray.array[i] = i * i + 3L;\n }\n time = System.currentTimeMillis();\n myArray.forEach(new Function<Long>() {\n\n public long perform(Long parameter, long x) {\n return x * 8 + parameter + 5L;\n }\n });\n System.out.println(System.currentTimeMillis() - time);\n System.out.println(myArray.x);\n myArray = null;\n myArray = new MyArray<Long>(50000000, Long.class, 234553523525L);\n for (int i = 0; i < 50000000; i++) {\n myArray.array[i] = i * i + 3L;\n }\n time = System.currentTimeMillis();\n myArray.forEach(new Function<Long>() {\n\n public long perform(Long parameter, long x) {\n return new Compute(8, 5).compute(parameter, x);\n }\n });\n System.out.println(System.currentTimeMillis() - time);\n System.out.println(myArray.x);\n }\n}\n 224\n-699150247503735895\n221\n-699150247503735895\n220\n-699150247503735895\n219\n-699150247503735895\n" }, { "answer_id": 19802454, "author": "Changgeng", "author_id": 2958002, "author_profile": "https://Stackoverflow.com/users/2958002", "pm_score": 2, "selected": false, "text": "objectArrayList java.util.ArrayList java.util.LinkedList List#get(int)" }, { "answer_id": 26068201, "author": "Gary Gregory", "author_id": 686368, "author_profile": "https://Stackoverflow.com/users/686368", "pm_score": 3, "selected": false, "text": " /*\n * Called from add while synchronized.\n */\n private static boolean contains(final Marker parent, final Marker... localParents) {\n //noinspection ForLoopReplaceableByForEach\n for (final Marker marker : localParents) {\n if (marker == parent) {\n return true;\n }\n }\n return false;\n }\n private static boolean contains(org.apache.logging.log4j.Marker, org.apache.logging.log4j.Marker...);\n Code:\n 0: iconst_0\n 1: istore_2\n 2: aload_1\n 3: arraylength\n 4: istore_3\n 5: iload_2\n 6: iload_3\n 7: if_icmpge 29\n 10: aload_1\n 11: iload_2\n 12: aaload\n 13: astore 4\n 15: aload 4\n 17: aload_0\n 18: if_acmpne 23\n 21: iconst_1\n 22: ireturn\n 23: iinc 2, 1\n 26: goto 5\n 29: iconst_0\n 30: ireturn\n private static boolean contains(org.apache.logging.log4j.Marker, org.apache.logging.log4j.Marker...);\n Code:\n 0: aload_1\n 1: astore_2\n 2: aload_2\n 3: arraylength\n 4: istore_3\n 5: iconst_0\n 6: istore 4\n 8: iload 4\n 10: iload_3\n 11: if_icmpge 34\n 14: aload_2\n 15: iload 4\n 17: aaload\n 18: astore 5\n 20: aload 5\n 22: aload_0\n 23: if_acmpne 28\n 26: iconst_1\n 27: ireturn\n 28: iinc 4, 1\n 31: goto 8\n 34: iconst_0\n 35: ireturn\n" }, { "answer_id": 34948680, "author": "Santosh", "author_id": 5730313, "author_profile": "https://Stackoverflow.com/users/5730313", "pm_score": 0, "selected": false, "text": "1. for(Object o: objectArrayList){\n o.DoSomthing();\n}\nand\n\n2. for(int i=0; i<objectArrayList.size(); i++){\n objectArrayList.get(i).DoSomthing();\n}\n" }, { "answer_id": 45789947, "author": "Sreekanth Karumanaghat", "author_id": 1448316, "author_profile": "https://Stackoverflow.com/users/1448316", "pm_score": 0, "selected": false, "text": "static class Foo {\n int mSplat;\n}\n\nFoo[] mArray = ...\n\npublic void zero() {\n int sum = 0;\n for (int i = 0; i < mArray.length; ++i) {\n sum += mArray[i].mSplat;\n }\n}\n\npublic void one() {\n int sum = 0;\n Foo[] localArray = mArray;\n int len = localArray.length;\n\n for (int i = 0; i < len; ++i) {\n sum += localArray[i].mSplat;\n }\n}\n\npublic void two() {\n int sum = 0;\n for (Foo a : mArray) {\n sum += a.mSplat;\n }\n}\n" }, { "answer_id": 69223378, "author": "Jerry Lundegaard", "author_id": 10656396, "author_profile": "https://Stackoverflow.com/users/10656396", "pm_score": 2, "selected": false, "text": "int localArray = this.array;\nfor (int i = 0; i < localArray.length; i++) { \n methodCall(localArray[i]); \n}\n for (int i = 0; i < this.array.length; i++) { //now java knows i < this.array.length\n methodCall(this.array[i]);// no need to check\n}\n int len = this.array.length;//len is now a local variable\nfor (int i = 0; i < len; i++) { //no reload needed\n methodCall(this.array[i]); //now java will do the check\n}\n ArrayType[] localArray = this.array;\nfor (int i = 0; i < localArray.length; i++) { \n methodCall(localArray[i]); \n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26567/" ]
256,892
<p>How do i backup a SQL database using PHP.</p> <p>Is there a vendor agnostic way to do this that conforms to ANSI SQL?</p> <p>If not maybe you can list how to do it for each of the database vendors?</p>
[ { "answer_id": 256907, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 4, "selected": true, "text": "pg_dump mysqldump system() shell_exec() test <?php\nheader('Content-type: text/plain');\nsystem('pg_dump test');\n?>\n ~/.my.cnf <?php\nheader('Content-type: text/plain');\nsystem('mysqldump test');\n?>\n <?php\nheader('Content-type: text/plain');\nsystem('mysqldump -utestuser -ptestpassword test');\n?>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
256,897
<p>I'm using <a href="http://www.codeplex.com/bizunit" rel="noreferrer" title="BizUnit">BizUnit</a> to unit-tests my Biztalk orchestrations, but some orchestrations consume a WebService,and testing these seems more like integration testing than unit testing.</p> <p>I'm familiar with using a mocking framework to mock the generated proxy objects, in order to test a web service from a Windows Forms application, but I would like to be able to do it in a more integrated way in a request-response port?</p> <p>How would you approach this problem?</p>
[ { "answer_id": 271044, "author": "David Hall", "author_id": 2660, "author_profile": "https://Stackoverflow.com/users/2660", "pm_score": 4, "selected": true, "text": "new Guid(\"\"), new Guid()" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18865/" ]
256,915
<p>I'm building small web shop with asp.net mvc and Structuremap ioc/di. My Basket class uses session object for persistence, and I want use SM to create my basket object through IBasket interface. My basket implementation need HttpSessionStateBase (session state wrapper from mvc) in constructor, which is available inside Controller/Action. How do I register my IBasket implementation for SM?<br> This is my basket interface:</p> <pre><code>public interface IBasketService { BasketContent GetBasket(); void AddItem(Product productItem); void RemoveItem(Guid guid); } </code></pre> <p>And SM registration: </p> <pre><code>ForRequestedType(typeof (IBasketService)).TheDefaultIsConcreteType(typeof (StoreBasketService)); </code></pre> <p>But my StoreBasketService implementation has constructor: </p> <pre><code>public StoreBasketService(HttpSessionStateBase sessionState) </code></pre> <p>How do I provide HttpSessionStateBase object to SM, which is available only in controller?<br> This is my first use of SM IOC/DI, and cann't find solution/example in official documentation and web site ;)</p>
[ { "answer_id": 257496, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "public interface IHttpSessionStateWrapper\n{\n HttpSessionState GetSessionState();\n}\n\npublic class HttpSessionStateWrapper : IHttpSessionStateWrapper\n{\n public virtual HttpSessionState GetSessionState()\n {\n return HttpContext.Current.Session;\n }\n}\n\nForRquestedType(typeof(IHttpSessionStateWrapper))\n .TheDefaultIsConcreteType(typeof(IHttpSessionStateWrapper));\n public class StoreBasketService\n{\n HttpSessionState session;\n public StoreBasketService( IHttpSessionstateWrapper wrapper )\n {\n session = wrapper.GetSessionState();\n }\n\n // basket implementation ...\n}\n .CacheBy(InstanceScope.HttpContext) Dictionary<Guid,Product>" }, { "answer_id": 349106, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " ObjectFactory.Initialize(x=>x.ForRequestedType<MyClass>(). CacheBy(InstanceScope.HttpContext));\n protected void btnTest_Click(object sender, EventArgs e)\n {\n MyClass c = ObjectFactory.GetInstance<MyClass>();\n System.Threading.Thread.Sleep(1000);\n MyClass b = ObjectFactory.GetInstance<MyClass>();\n\n\n\n lblResult.Text = String.Format(\"cache by httpcontext First:{0} Second:{1} session id {2} \", c.GetTimeCreated(), b.GetTimeCreated(),Session.SessionID);\n }\n public class MyClass\n{\n private DateTime _timeCreated;\n public MyClass()\n {\n _timeCreated = DateTime.Now;\n }\n\n public string GetTimeCreated()\n {\n return _timeCreated.ToString(\"dd/MM/yyyy hh:mm:ss\");\n }\n}\n" }, { "answer_id": 350447, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public class HttpSessionBuilder : CacheInterceptor\n{\n private readonly string _prefix = Guid.NewGuid().ToString();\n\n protected override CacheInterceptor clone()\n {\n return this;\n }\n\n private string getKey(string instanceKey, Type pluginType)\n {\n return string.Format(\"{0}:{1}:{2}\", pluginType.AssemblyQualifiedName, instanceKey, this._prefix);\n }\n\n public static bool HasContext()\n {\n return (HttpContext.Current.Session != null);\n }\n\n protected override bool isCached(string instanceKey, Type pluginType)\n {\n return HttpContext.Current.Session[this.getKey(instanceKey, pluginType)] != null;\n }\n\n protected override object retrieveFromCache(string instanceKey, Type pluginType)\n {\n return HttpContext.Current.Session[this.getKey(instanceKey, pluginType)];\n }\n\n protected override void storeInCache(string instanceKey, Type pluginType, object instance)\n {\n HttpContext.Current.Session.Add(this.getKey(instanceKey, pluginType), instance);\n }\n\n}\n ObjectFactory.Initialize(x=>\n x.ForRequestedType<MyClass>().InterceptConstructionWith(new HttpSessionBuilder()));\n" }, { "answer_id": 370463, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 1, "selected": false, "text": "ForRequestedType<IBasketService>()\n .TheDefault.Is.OfConcreteType<StoreBasketService>()\n .WithCtorArg(\"sessionState\").EqualTo(HttpContext.Current.Session);\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1407/" ]
256,919
<p>I am looking for suggestions on how to find the sizes (in bits) and range of floating point numbers in an architecture independent manner. The code could be built on various platforms (AIX, Linux, HPUX, VMS, maybe Windoze) using different flags - so results should vary. The sign, I've only seen as one bit, but how to measure the size of the exponent and mantissa?</p>
[ { "answer_id": 256926, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 2, "selected": false, "text": "float.h" }, { "answer_id": 256928, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": " Sign Exponent Fraction Bias\nSingle Precision 1 [31] 8 [30-23] 23 [22-00] 127\nDouble Precision 1 [63] 11 [62-52] 52 [51-00] 1023\n" }, { "answer_id": 574726, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "myfloat a = 2.0,\n b = 0.0;\n\nfor (int i=0; i<20; i++)\n b += 0.1;\n\n(a == b) => decimal, else binary\n Myfloat a = 1.0,\n b = 1.0,\n c,\n inc = 1.0;\n\nint mantissabits = 0;\n\ndo {\n mantissabits++;\n inc *= 0.5; // effectively shift to the right\n c = b+inc;\n} while (a != c);\n Myfloat a = 1.0;\nint max = 0,\n min = 0;\n\nwhile (true) {\n a *= 2.0;\n if (a != NaN && a != Infinity && whatever) // depends on system\n max++;\n else\n break;\n}\n\na = 1.0;\nwhile (true) {\n a *= 0.5;\n if (a != 0.0) \n min--;\n else\n break;\n}\n -(max+1) - max min -(max+1)" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
256,932
<p>Is there a way of getting the websites absolute URL (<a href="http://www.domain.com/" rel="nofollow noreferrer">http://www.domain.com/</a>) using Java? because I've googled a bit but I only come across with having to make 2 or 3 classes to create that function =/</p> <h3>Update:</h3> <p>The thing is I am trying to create a crawler that will give me some information and among that I'd like to get the URL of the webpage it's getting the information from. I'm developing this in JAVA and what I meant to say was that I was wondering if there was some getUrl(); or any method like that to get me the Url, because I know it can be done but I've only done it writing a whole other class to retrieve the url and then inherit it and use it further...hope it made it clearer</p>
[ { "answer_id": 256995, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 1, "selected": false, "text": "String realPath = getServletConfig().getServletContext().getRealPath(relativePath);\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28586/" ]
256,938
<p>I am writing a footer div that displays info from the database. The footer has a different background color than the rest of the page, and will have a height that depends on how much content the database throws to it. When I generate the content with php and call for a border around the footer div, the content appears and is, let's say, 400px high, but the div border appears as a 1px high rectangle at the top of the div.</p> <p>How do I get the height to auto-fit the content?</p> <pre><code>&lt;div id="footer"&gt; &lt;?php $an_array=array(); $tasks=mysql_query("select stuff from the db"); while($row=mysql_fetch_assoc($tasks)){ extract($taskrow); $an_array[]=$task; } $an_array=array_chunk($an_array,4); foreach($an_array as $dtkey=&gt;$dtval){ echo "&lt;dl&gt;"; foreach($dtval as $dtvkey=&gt;$dtvval){ echo "&lt;dt&gt;".$dtvval."&lt;/dt&gt;"; } echo "&lt;/dl&gt;"; } ?&gt; &lt;/div&gt; </code></pre> <p>This is what I get. The area below the red border should be filled with a color. <a href="http://www.kevtrout.com/tortus/div.png" rel="nofollow noreferrer">border image http://www.kevtrout.com/tortus/div.png</a></p> <p>By popular demand, here is the css:</p> <pre><code>#footer{ border-top: 10px solid #d8d8d8; background:#5b5b5b; /*overflow:auto;*///Added this after seeing your answers, it worked } dl.tr{ width: 255px; height:160px; background: #5b5b5b; margin:0px; float:left; padding: 10px; } dt.tr{ font-weight: normal; font-size: 14px; color: #d8d8d8; line-height: 28px; } </code></pre> <p>edit: I am using firefox on a mac</p>
[ { "answer_id": 256948, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 2, "selected": false, "text": "<dl> <div> clear:both; </div> <div style='clear:both;'></div>\n" }, { "answer_id": 256965, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<dl> <dd> <div style='clear:both;'></div> <dt>" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1149/" ]
256,953
<p>It seems that HTML 5 is going to be supported (partially) by Firefox 3.1 and other browsers. It is adding support for video and audio as tags, but these are new tags that XHTML 1.0 Transitional does not recognize. What is the behavior supposed to be if I use a new HTML 5 tag in a future version of Firefox but use the DTD for XHTML? And what if I mix HTML 5 markup with XHTML 1.0 Trans?</p> <p>This is getting confusing. Why didn't they just add these tags to XHTML? How do we support both XHTML and HTML 5?</p> <p>Video on HTML 5: <a href="http://www.youtube.com/watch?v=xIxDJof7xxQ" rel="noreferrer">http://www.youtube.com/watch?v=xIxDJof7xxQ</a></p>
[ { "answer_id": 256998, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 4, "selected": true, "text": "<video> <audio>" }, { "answer_id": 257053, "author": "Ms2ger", "author_id": 33466, "author_profile": "https://Stackoverflow.com/users/33466", "pm_score": 2, "selected": false, "text": "<video> <audio> text/html <!doctype html> application/xhtml+xml" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10366/" ]
256,978
<p>Is there a way to persist an enum to the DB using NHibernate? That is have a table of both the code and the name of each value in the enum.</p> <p>I want to keep the enum without an entity, but still have a foreign key (the int representation of the enum) from all other referencing entities to the enum's table.</p>
[ { "answer_id": 257073, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 3, "selected": false, "text": "private int myField;\npublic virtual MyEnum MyProperty\n{\n get { return (MyEnum)myField; }\n set { myField = value; }\n}\n" }, { "answer_id": 1530190, "author": "RhysC", "author_id": 17466, "author_profile": "https://Stackoverflow.com/users/17466", "pm_score": 2, "selected": false, "text": "[Serializable]\npublic abstract partial class TimesheetStatus : IHasIdentity<int>\n{\n public static readonly TimesheetStatus NotEntered = new NotEnteredTimesheetStatus();\n public static readonly TimesheetStatus Draft = new DraftTimesheetStatus();\n public static readonly TimesheetStatus Submitted = new SubmittedTimesheetStatus();\n //etc\n\n public abstract int Id { get; protected set; }\n public abstract string Description { get; protected set; }\n public abstract bool IsReadyForSubmission();\n\n protected class NotEnteredTimesheetStatus: TimesheetStatus\n {\n private const string DESCRIPTION = \"NotEntered\";\n private const int ID = 0;\n public override int Id\n {\n get { return ID; }\n protected set { if (value != ID)throw new InvalidOperationException(\"ID for NotEnteredTimesheetStatus must be \" + ID); }\n }\n\n public override string Description\n {\n get { return DESCRIPTION; }\n protected set { if (value != DESCRIPTION)throw new InvalidOperationException(\"The description for NotEnteredTimesheetStatus must be \" + DESCRIPTION); }\n }\n public override bool IsReadyForSubmission()\n {\n return false;\n }\n\n }\n //etc\n}\n" }, { "answer_id": 1905268, "author": "Emad", "author_id": 18132, "author_profile": "https://Stackoverflow.com/users/18132", "pm_score": 7, "selected": false, "text": "<property name=\"OrganizationType\"></property>\n public virtual OrganizationTypes OrganizationType { get; set; }\n public enum OrganizationTypes\n{\n NonProfit = 1,\n ForProfit = 2\n}\n" }, { "answer_id": 10605789, "author": "Jamie", "author_id": 1396824, "author_profile": "https://Stackoverflow.com/users/1396824", "pm_score": 2, "selected": false, "text": "type=\"NHibernate.Type.EnumStringType`1[[enum_full_type_name, enum_assembly]], NHibernate\"\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19956/" ]
256,997
<p>I have a PHP web application which uses a MySQL database for object tagging, in which I've used the tag structure accepted as the answer to <a href="https://stackoverflow.com/questions/20856/how-do-you-recommend-implementing-tags-or-tagging">this SO question</a>.</p> <p>I'd like to implement a tag hierarchy, where each tag can have a unique parent tag. Searches for a parent tag T would then match all descendants of T (i.e. T, tags whos parent is T (children of T), grandchildren of T, etc.).</p> <p>The easiest way of doing this seems to be to add a ParentID field to the tag table, which contains the ID of a tag's parent tag, or some magic number if the tag has no parent. Searching for descendants, however, then requires repeated full searches of the database to find the tags in each 'generation', which I'd like to avoid.</p> <p>A (presumably) faster, but less normalised way of doing this would be to have a table containing all the children of each tag, or even all the descendants of each tag. This however runs the risk of inconsistent data in the database (e.g. a tag being the child of more than one parent).</p> <p>Is there a good way to make queries to find descendants fast, while keeping the data as normalised as possible?</p>
[ { "answer_id": 257020, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "tag path\n--- ----\ndatabase database/\nmysql database/mysql/\nmysql4 database/mysql/mysql4/\nmysql4-1 database/mysql/mysql4-1/\noracle database/oracle/\nsqlserver database/sqlserver/\nsqlserver2005 database/sqlserver/sqlserver2005/\nsqlserver2005 database/sqlserver/sqlserver2008/\n like SELECT * FROM tags WHERE path LIKE 'database/%'\n" }, { "answer_id": 259401, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "ParentID, ChildID, Depth, Highest Flag, Lowest Flag\nA, A, 0, Y, N\nA, B, 1, N, N\nA, C, 2, N, N\nA, D, 3, N, Y\nB, B, 0, N, N\nB, C, 1, N, N\nB, D, 2, N, Y\nC, C, 0, N, N\nC, D, 1, N, Y\nD, D, 0. N, Y\n WHERE parentID = 'B' and Depth = 1\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/256997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23732/" ]
257,005
<p>I want to do this using the <code>Math.Round</code> function</p>
[ { "answer_id": 257011, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 7, "selected": false, "text": "twoDec = Math.Round(val, 2)\n" }, { "answer_id": 257017, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 10, "selected": false, "text": "decimal a = 1.994444M;\n\nMath.Round(a, 2); //returns 1.99\n\ndecimal b = 1.995555M;\n\nMath.Round(b, 2); //returns 2.00\n Math.Round(a, 2, MidpointRounding.ToEven);\n" }, { "answer_id": 9403001, "author": "sadim", "author_id": 1226874, "author_profile": "https://Stackoverflow.com/users/1226874", "pm_score": 3, "selected": false, "text": "label8.Text = valor_cuota .ToString(\"N2\") ;\n Imports System.Math\n round(label8.text,2)\n" }, { "answer_id": 9406108, "author": "Gleno", "author_id": 427673, "author_profile": "https://Stackoverflow.com/users/427673", "pm_score": 5, "selected": false, "text": "string.Format(\"{0:0.00}\", number)" }, { "answer_id": 15650246, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 5, "selected": false, "text": "> (1.7289).ToString(\"#.##\")\n\"1.73\"\n > Math.Round((Decimal)x, 2)\n1.73m\n round(x*y) != round(x) * round(y)" }, { "answer_id": 34807727, "author": "Rae Lee", "author_id": 5113582, "author_profile": "https://Stackoverflow.com/users/5113582", "pm_score": 4, "selected": false, "text": "String.Format(\"{0:0.00}\", 140.6767554); // \"140.67\"\nString.Format(\"{0:0.00}\", 140.1); // \"140.10\"\nString.Format(\"{0:0.00}\", 140); // \"140.00\"\n\nDouble d = 140.6767554;\nDouble dc = Math.Round((Double)d, 2); // 140.67\n\ndecimal d = 140.6767554M;\ndecimal dc = Math.Round(d, 2); // 140.67\n // just two decimal places\nString.Format(\"{0:0.##}\", 123.4567); // \"123.46\"\nString.Format(\"{0:0.##}\", 123.4); // \"123.4\"\nString.Format(\"{0:0.##}\", 123.0); // \"123\"\n String.Format(\"{0:0.0#}\", 123.4567) // \"123.46\"\nString.Format(\"{0:0.0#}\", 123.4) // \"123.4\"\nString.Format(\"{0:0.0#}\", 123.0) // \"123.0\"\n" }, { "answer_id": 44797890, "author": "Ruan", "author_id": 1713519, "author_profile": "https://Stackoverflow.com/users/1713519", "pm_score": 0, "selected": false, "text": " public double RoundDown(double number, int decimalPlaces)\n {\n return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);\n }\n" }, { "answer_id": 47071421, "author": "Guy P", "author_id": 1252723, "author_profile": "https://Stackoverflow.com/users/1252723", "pm_score": 3, "selected": false, "text": "decimal d1 = (decimal)1.125;\nMath.Round(d1, 2).Dump(); // returns 1.12\nd1.ToString(\"#.##\").Dump(); // returns \"1.13\"\n\ndecimal d2 = (decimal)1.1251;\nMath.Round(d2, 2).Dump(); // returns 1.13\nd2.ToString(\"#.##\").Dump(); // returns \"1.13\"\n" }, { "answer_id": 56066728, "author": "fedesanp", "author_id": 2690533, "author_profile": "https://Stackoverflow.com/users/2690533", "pm_score": 3, "selected": false, "text": "double result = 0.75d * 0.95d; // result = 0.71249999999999991\ndouble result = 0.75f * 0.95f; // result = 0.71249997615814209\n\nresult = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok\nresult = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713\n double result = -0.75 * 0.95; //result = -0.71249999999999991\nresult = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok\nresult = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713\n double Redondea(double value, int precision, bool roundUp = true)\n{\n if ((decimal)value == 0.0m)\n return 0.0;\n\n double corrector = 1 / Math.Pow(10, precision + 2);\n\n if ((decimal)value < 0.0m)\n {\n if (roundUp)\n return Math.Round(value, precision, MidpointRounding.ToEven);\n else\n return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);\n }\n else\n {\n if (roundUp)\n return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);\n else\n return Math.Round(value, precision, MidpointRounding.ToEven);\n }\n}\n" }, { "answer_id": 57889973, "author": "Riyaz Hameed", "author_id": 1570636, "author_profile": "https://Stackoverflow.com/users/1570636", "pm_score": 3, "selected": false, "text": "public static class DecimalExtensions\n{\n public static decimal WithTwoDecimalPoints(this decimal val)\n {\n return decimal.Parse(val.ToString(\"0.00\"));\n }\n}\n var sampleDecimalValueV1 = 2.5m;\nConsole.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());\n\ndecimal sampleDecimalValueV1 = 2;\nConsole.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());\n 2.50\n2.00\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
257,030
<p>Writing something like this using the <a href="http://loki-lib.sourceforge.net/" rel="nofollow noreferrer">loki library</a>,</p> <pre><code>typedef Functor&lt;void&gt; BitButtonPushHandler; </code></pre> <p>throws a compiler error, but this works</p> <pre><code>typedef Functor&lt;void,TYPELIST_1(Matrix3D*)&gt; Perspective; </code></pre> <blockquote> <p>Functor.h:530: error: '((Loki::FunctorHandler, int>*)this)->Loki::FunctorHandler, int>::f_' cannot be used as a function Functor.h:530: error: return-statement with a value, in function returning 'void'</p> </blockquote> <p>Anyone familiar with this library know how to get the first line working?</p>
[ { "answer_id": 257064, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": 3, "selected": true, "text": "template <typename R = void, class TList = NullType,\n template<class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL>\n class Functor{...};\n typedef Functor<> BitButtonPushHandler;\n" }, { "answer_id": 258156, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 0, "selected": false, "text": "using namespace Loki; \n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
257,047
<p>Where would i go to look for algorithms that take a 2d grid of values that are either 0 or 1 as input and then identifies all possible non-overlapping rectangles in it?</p> <p>In a more practical explanation: I am drawing a grid that is represented by a number of squares, and i wish to find a way to combine as many adjacent squares into rectangles as possible, in order to cut down on the time spent on cycling through each square and drawing it.</p> <p>Maximum efficiency is not needed, speed is more important.</p> <p>Addendum: Apparently what i am looking for seems to be a technique called Tesselation. Now i only need to find a good description for this specific case.</p> <p>Addendum 2: The boundary of the "1" squares will be irregular and in some cases not even connected, as the distribution of "1" squares will be completely random. I need these irregular shapes to be identified and split up into regular rectangles.</p> <p><strong>Correct answer:</strong> To get the best balance between speed and efficiency it is optimal to use the grid data to fill a quad-tree with each node having a status value of either empty/partly filled/filled.</p>
[ { "answer_id": 257075, "author": "Peter Olsson", "author_id": 2703, "author_profile": "https://Stackoverflow.com/users/2703", "pm_score": 1, "selected": false, "text": "0 0 1 1 1 0 0 0 1 1 1 1 0\n skip 2\ndraw 3\nskip 3\ndraw 4\nskip 1\n" }, { "answer_id": 257103, "author": "Daniel Rikowski", "author_id": 23368, "author_profile": "https://Stackoverflow.com/users/23368", "pm_score": 3, "selected": true, "text": "xxxx 1111\nxxxx 1111\nxxxx 1111\n\n2222 3333\n2222 3333\n2222 3333\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145119/" ]
257,050
<p>Say you have a string, but you don't know what it contains. And you want to replace all occurences of a particular word or part of a word with a formatted version of the same word. For example, I have a string that contains "lorem ipsum" and i want to replace the entire word that contains "lo" with "lorem can" so that the end result would be "lorem can ipsum" but if I put the string "loreal ipsum" through the same function, the result would now be "loreal can ipsum". Thanks</p>
[ { "answer_id": 257054, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": true, "text": "$str = preg_replace('/lo(\\w*)/', 'lo$1 can', $str); \\w* \\w+" }, { "answer_id": 257063, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "$str = preg_replace('/(\\blo[a-z]+\\b)/', '$1 can', $str);\n \\w lo lo \\b lo [a-z]+ \\b $str = preg_replace('/(\\blo[a-z\\p{L}]+\\b)/', '$1 can', $str);\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24391/" ]
257,065
<p>The reason I am asking this is that I had accidentally done a <code>git commit -a</code> that included a file I did not yet want to commit. My solution was to do the following:</p> <pre><code>git reset --soft HEAD^ git reset -- file/with/changes_not_to_committed git commit -C HEAD@{1} </code></pre> <p>Here, I’ve rewound the branch by one commit while keeping the index and working tree, then pulled <code>file/with/changes_not_to_committed</code> from a yet older revision into the index, and then I committed the index using the commit message from the previous branch head commit. Neither <code>git-reset</code> invocation touches the working copy, so my modifications to <code>file/with/changes_not_to_committed</code> persist, but are no longer recorded in the <code>HEAD</code> revision.</p> <p>However, it would have been easier if I could pull <code>file/with/changes_not_to_committed</code> from the <code>HEAD^</code> revision right into the index <em>without touching the working copy</em>. Since the index otherwise already represents the state I want, I could then just amend the <code>HEAD</code> commit, producing a sequence like this:</p> <pre><code>git magic-pony HEAD^ file/with/changes_not_to_committed git commit --amend -C HEAD </code></pre> <p>This is <em>almost</em> what I would get by replacing <code>git-magic-pony</code> with <code>git-checkout</code>, except for the requirement that the working copy be left untouched and only the index updated. It seems there is no way to make <code>git-checkout</code> not touch both.</p> <p>My question is: does <code>git-magic-pony</code> exist, and if so, under what name?</p>
[ { "answer_id": 257105, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "git update-index git update-index --cacheinfo 100644 5be7e154c284fb8de8ddca0bb18b72a73089df9b filename\n git ls-tree git commit --amend" }, { "answer_id": 257196, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "git-magic-pony #!/bin/sh\ngit ls-tree \"$@\" | while read mode type hash path ; do\n git update-index --cacheinfo $mode $hash \"$path\"\ndone" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9410/" ]
257,078
<p>I understand that using the "===" compares type, so running the following code results in "not equal" because it's comparing a number type to a string type.</p> <pre><code>var a = 20; var b = "20"; if (a === b) { alert("They are equal"); } else { alert("They are not equal"); } </code></pre> <p>But I dont understand how using the "==" to compare only the value results in the "They are equal" message.</p> <pre><code>var a = 20; var b = "20"; if (a == b) { alert("They are equal"); } else { alert("They are not equal"); } </code></pre> <p>How are the values equal? Isn't the string "20" stored as the ASCII characters 50 and 48 (0110010 and 0110000 in binary) and 20 stored as the actual binary number 0010100?</p> <p>EDIT: Thanks everyone! I think all the responses are great and have helped me understand this much better.</p>
[ { "answer_id": 257083, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 5, "selected": true, "text": "== === \"20\" !== 20" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
257,085
<p>I have a JavaScript snippet that runs very well on Firefox and Safari, but refuses to run on IE:</p> <pre><code>var drop= function(id) { if(document.getElementById("select1").value == "Ficha de pediatria"){ top.location.href = "print.jsp?id="+id+"&amp;type=2"; } else if(document.getElementById("select1").value == "Ficha normal"){ top.location.href = "print.jsp?id="+id+"&amp;type=1"; } } &lt;select id="select1" name="select1" onChange="drop(id);return false;"&gt; &lt;option&gt;Imprimir:&lt;/option&gt; &lt;option&gt;Ficha de pediatria&lt;/option&gt; &lt;option&gt;Ficha normal&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I trimed this as it had more JSP code but it' remained the same. Anyone got any idea why it's not running on IE?</p>
[ { "answer_id": 257095, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "id function drop(ctl,id)\n{\n var value = ctl.options[ctl.selectedIndex].value;\n\n if(value == \"Ficha de pediatria\"){\n window.top.location.href = \"print.jsp?id=\"+id+\"&type=2\";\n }\n else if (value == \"Ficha normal\"){\n window.top.location.href = \"print.jsp?id=\"+id+\"&type=1\";\n }\n}\n\n<select id=\"select1\" name=\"select1\" onChange=\"drop(this,id);return false;\">\n<option>Imprimir:</option>\n<option>Ficha de pediatria</option>\n<option>Ficha normal</option>\n</select>\n window.top this" }, { "answer_id": 257097, "author": "mbillard", "author_id": 810, "author_profile": "https://Stackoverflow.com/users/810", "pm_score": -1, "selected": false, "text": "function drop(id)\n{\n // same code\n}\n onChange=\"drop(id);event.returnValue=false;return false;\"\n function CrossBrowserFalse()\n{\n if(IE) // use whatever you want to detect IE\n {\n event.returnValue = false;\n }\n\n return false;\n}\n onChange=\"drop(id);return CrossBrowserFalse();\"\n" }, { "answer_id": 257279, "author": "kamens", "author_id": 1335, "author_profile": "https://Stackoverflow.com/users/1335", "pm_score": 1, "selected": false, "text": "<select ...>\n<option value=\"Imprimir\">Imprimir:</option>\n<option value=\"Ficha de pediatria\">Ficha de pediatria</option>\n<option value=\"Ficha normal\">Ficha normal</option>\n</select>\n" }, { "answer_id": 257321, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "document.getElementById(\"select1\").value\n <select id=\"select1\" name=\"select1\" onChange=\"drop(this,id);return false;\">\n <option value=\"Imprimir:\">Imprimir:</option>\n <option value=\"Ficha de pediatria\">Ficha de pediatria</option>\n <option value=\"Ficha normal\">Ficha normal</option>\n</select>\n var theSelect = document.getElementById(\"select1\");\nvar theValue = theSelect.options[theSelect.selectedIndex].text\n function foo(theSelect){\n alert(theSelect.options);\n}\n <select id=\"whatever\" onchange=\"foo(this);\">\n...\n</select>\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
257,091
<p>How do I clear the cin buffer in C++?</p>
[ { "answer_id": 257092, "author": "Gunnar Steinn", "author_id": 33468, "author_profile": "https://Stackoverflow.com/users/33468", "pm_score": 1, "selected": false, "text": "cin.flush();\n cin.ignore(INT_MAX);\n" }, { "answer_id": 257098, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 8, "selected": true, "text": "std::cin.ignore(INT_MAX);\n EOF '\\n' std::cin.clear();" }, { "answer_id": 257182, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": false, "text": "// Ignore to the end of Stream\nstd::cin.ignore(std::numeric_limits<std::streamsize>::max())\n\n// Ignore to the end of line\nstd::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n')\n" }, { "answer_id": 257203, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 2, "selected": false, "text": "cin.clear();\nfflush(stdin);\n" }, { "answer_id": 538629, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "cin.ignore(cin.rdbuf()->in_avail());\n" }, { "answer_id": 1542777, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "int i;\n cout << \"Please enter an integer value: \";\n\n // cin >> i; leaves '\\n' among possible other junk in the buffer. \n // '\\n' also happens to be the default delim character for getline() below.\n cin >> i; \n if (cin.fail()) \n {\n cout << \"\\ncin failed - substituting: i=1;\\n\\n\";\n i = 1;\n }\n cin.clear(); cin.ignore(INT_MAX,'\\n'); \n\n cout << \"The value you entered is: \" << i << \" and its double is \" << i*2 << \".\\n\\n\";\n\n string myString;\n cout << \"What's your full name? (spaces inclded) \\n\";\n getline (cin, myString);\n cout << \"\\nHello '\" << myString << \"'.\\n\\n\\n\";\n" }, { "answer_id": 23745035, "author": "jyggorath", "author_id": 2306552, "author_profile": "https://Stackoverflow.com/users/2306552", "pm_score": 5, "selected": false, "text": "cin.clear();\nfflush(stdin);\n cin.getline(temp, STRLEN);\nif (cin.fail()) {\n cin.clear();\n cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n}\n" }, { "answer_id": 26817311, "author": "techcomp", "author_id": 3921632, "author_profile": "https://Stackoverflow.com/users/3921632", "pm_score": 1, "selected": false, "text": "#include <stdio_ext.h>\n __fpurge(stdin)\n" }, { "answer_id": 29155484, "author": "GuestPerson001", "author_id": 4691763, "author_profile": "https://Stackoverflow.com/users/4691763", "pm_score": 0, "selected": false, "text": "cin.get()" }, { "answer_id": 31872811, "author": "Bobul Mentol", "author_id": 5191247, "author_profile": "https://Stackoverflow.com/users/5191247", "pm_score": 2, "selected": false, "text": "cin.clear();\nwhile (cin.get() != '\\n') \n{\n continue;\n}\n" }, { "answer_id": 34518907, "author": "Ben", "author_id": 1727729, "author_profile": "https://Stackoverflow.com/users/1727729", "pm_score": 4, "selected": false, "text": "std::getline() std::getline(std::cin, yourString);\n #include <limits>\n// Possibly some other code here\ncin.clear();\ncin.ignore(numeric_limits<streamsize>::max(), '\\n');\n" }, { "answer_id": 46411174, "author": "Chaitanya Vaishampayan", "author_id": 7105441, "author_profile": "https://Stackoverflow.com/users/7105441", "pm_score": 2, "selected": false, "text": "cin.seekg(0,ios::end);\ncin.clear();\n" }, { "answer_id": 61894774, "author": "Amrit Malla", "author_id": 10755186, "author_profile": "https://Stackoverflow.com/users/10755186", "pm_score": 2, "selected": false, "text": "cin.ignore()\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
257,093
<p>Given the following table, how does one calculate the hourly mode, or value with the highest frequency by hour?</p> <pre><code>CREATE TABLE Values ( ValueID int NOT NULL, Value int NOT NULL, LogTime datetime NOT NULL ) </code></pre> <p>So far, I've come up with the following query.</p> <pre><code>SELECT count(*) AS Frequency, DatePart(yy, LogTime) as [Year], DatePart(mm, LogTime) as [Month], DatePart(dd, LogTime) as [Day], DatePart(hh, LogTime) as [Hour] FROM Values GROUP BY Value, DatePart(yy, LogTime), DatePart(mm, LogTime), DatePart(dd, LogTime), DatePart(hh, LogTime) </code></pre> <p>However, this yields the frequency of each distinct value by hour. How do I add a constraint to only return the value with the maximum frequency by hour?</p> <p>Thanks</p>
[ { "answer_id": 257181, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 1, "selected": false, "text": "SELECT\n MAX(Frequency) AS [Mode],\n [Year],[Month],[Day],[Hour]\nFROM\n (SELECT\n COUNT(*) AS Frequency, \n DatePart(yy, LogTime) as [Year], \n DatePart(mm, LogTime) as [Month], \n DatePart(dd, LogTime) as [Day], \n DatePart(hh, LogTime) as [Hour]\n FROM \n Values \n GROUP BY \n Value, \n DatePart(yy, LogTime), \n DatePart(mm, LogTime), \n DatePart(dd, LogTime), \n DatePart(hh, LogTime)\n ) foo\nGROUP By\n [Year],[Month],[Day],[Hour]\n" }, { "answer_id": 257306, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "WITH GroupedValues (Value, Frequency, Hour) AS\n (SELECT\n Value,\n COUNT(*) AS Frequency,\n DATEPART(hh, LogTime) AS Hour\n FROM\n dbo.MyValues\n GROUP BY\n Value,\n DATEPART(hh, LogTime))\n\nSELECT\n MAX(Value) AS Value,\n a.Hour\nFROM\n GroupedValues a INNER JOIN\n (SELECT MAX(Frequency) AS MaxFrequency,\n Hour FROM GroupedValues GROUP BY Hour) b\n ON a.Frequency = b.MaxFrequency AND a.Hour = b.Hour\nGROUP BY\n a.Hour\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
257,102
<p>In other words, can <code>fn()</code> know that it is being used as <code>$var = fn();</code> rather than as <code>fn();</code>?</p> <p>A use case would be to <code>echo</code> the return value in the latter case but to <code>return</code> it in the former.</p> <p>Can this be done without passing a parameter to the function to declare which way it is being used?</p>
[ { "answer_id": 257122, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 0, "selected": false, "text": "if (namespace) {\n return $output;\n} else {\n echo $output;\n}\n" }, { "answer_id": 257184, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 2, "selected": false, "text": "echo function foo() {\n echo \"Hello World\";\n}\nfoo(); // will output \"Hello World\"\nob_start();\nfoo();\n$foo = ob_get_clean(); // will assign the string \"Hello World\" into the variable $foo\n" }, { "answer_id": 257191, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": true, "text": "function fn($return=false) {\n if ($return) {\n return 'blah';\n } else {\n echo 'blah';\n }\n}\n" }, { "answer_id": 257233, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "$var = fn();\n fn() $var" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17964/" ]
257,152
<p>If I have two things which are hex, can I someone how append their binary together to get a value?</p> <p>In C++, say I have</p> <pre><code>unsigned char t = 0xc2; // 11000010 unsigned char q = 0xa3; // 10100011 </code></pre> <p>What I want is somehow, <code>1100001010100011</code>, is this possible using bit-wise operators?</p> <p>I want to extract the binary form of t and q and append them...</p>
[ { "answer_id": 257199, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "unsigned char t = 0xc2; // 11000010 \nunsigned char q = 0xa3; // 10100011\nunsigned short s = (((unsigned short)t)<<8) | q; //// 11000010 10100011\n" }, { "answer_id": 257201, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "unsigned char t = 0xc2; // 11000010\nunsigned char q = 0xa3; // 10100011\n\nint result = t; // Put into object that can hold the fully concatenated data;\nresult <<= 8; // Shift it left\nresult |= q; // Or the bottom bits into place;\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
257,157
<p>I am attempting to build a simple method that creates an XML file from a database in ruby on rails. I feel like my code is right but I am not seeing all of the users in the XML.<br> I am a complete newbie to RoR.</p> <p>Here's my code:</p> <pre><code>def create_file @users = User.find(:all) file = File.new('dir.xml','w') doc = Document.new make = Element.new "make" @users.each do |y| make.add_element "name" make.elements["name"].text = y.name make.add_element "description" make.elements["description"].text = y.description end doc.add_element make file.puts doc file.close end </code></pre> <p>And my XML output:</p> <pre><code>&lt;make&gt; &lt;name&gt;sammy&lt;/name&gt;&lt;description&gt;samsdescription&lt;/description&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;name/&gt;&lt;description/&gt; &lt;/make&gt; </code></pre> <p>I don't get why all the fields aren't populated. Why is just one of the database entires showing up? I really appreciate the help.</p>
[ { "answer_id": 257180, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 3, "selected": true, "text": "add_element Elements#[] Elements#[] @users.each do |y|\n name_node = make.add_element \"name\"\n name_node.text = y.name\n desc_node = make.add_element \"description\"\n desc_node.text = y.description\nend\n" }, { "answer_id": 257781, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "@users.to_xml" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33344/" ]
257,188
<p>I'm looking for a free (GPL or BSD-type license) outliner library that works in a browser. </p> <p>It doesn't have to be too complicated, just allow keyboard control of collapsing and expanding items, and changing their order.</p> <p>Anyone know a good library for this? Do any of the big UI component libraries have an outliner? If not, how would I go about writing it from scratch? (Eg. would it be better to start with jQuery? Or something else?)</p>
[ { "answer_id": 6179661, "author": "Marcel", "author_id": 154877, "author_profile": "https://Stackoverflow.com/users/154877", "pm_score": 3, "selected": false, "text": "<li>" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8482/" ]
257,189
<p>I've heard a lot of people touting success using Linux based proxies to handle routing for high availability of web applications, but what are others doing with web services? I have a bank of WCF services that need to be moved to a high availability (failover) model, meaning that if a particular server hosting the WCF services goes down, the request is routed to another of the servers in the bank. I would rather stay away from implementing a Linux based solution, since there are no Linux knowledgeable people in the environment. </p>
[ { "answer_id": 6179661, "author": "Marcel", "author_id": 154877, "author_profile": "https://Stackoverflow.com/users/154877", "pm_score": 3, "selected": false, "text": "<li>" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
257,190
<p>Here is a simple scenario with table characters:</p> <pre><code>CharacterName GameTime Gold Live Foo 10 100 3 Foo 20 100 2 Foo 30 95 2 </code></pre> <p>How do I get this output for the query <code>SELECT Gold, Live FROM characters WHERE name = 'Foo' ORDER BY GameTime</code>:</p> <pre><code>Gold Live 100 3 0 -1 -5 0 </code></pre> <p>using MySQL stored procedure (or query) if it's even possible? I thought of using 2 arrays like how one would normally do in a server-side language, but MySQL doesn't have array types.</p> <p>While I'm aware it's probably easier to do in PHP (my server-side langauge), I want to know if it's possible to do in MySQL, just as a learning material.</p>
[ { "answer_id": 257213, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "GameID CharacterName GameTime Gold Live\n----------- ------------- ----------- ----------- -----------\n1 Foo 10 100 3\n2 Foo 20 100 2\n3 Foo 30 95 2\n SELECT\n c.CharacterName, \n CASE WHEN c_offset.Gold IS NOT NULL THEN c.Gold - c_offset.Gold ELSE c.Gold END AS Gold,\n CASE WHEN c_offset.Live IS NOT NULL THEN c.Live - c_offset.Live ELSE c.Live END AS Live\nFROM Characters c \n LEFT OUTER JOIN Characters c_offset\n ON c.GameID - 1 = c_offSet.GameID\nORDER BY\n c.GameTime\n CharacterName Gold Live\n------------- ----------- -----------\nFoo 100 3\nFoo 0 -1\nFoo -5 0\n" }, { "answer_id": 257217, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 2, "selected": true, "text": "CREATE TABLE characters_by_gametime (\n id INTEGER AUTO_INCREMENT PRIMARY KEY,\n gold INTEGER,\n live INTEGER);\n\nINSERT INTO characters_by_gametime (gold, live)\nSELECT gold, live\nFROM characters\nORDER BY game_time;\n\nSELECT\n c1.id,\n c1.gold - IFNULL(c2.gold, 0) AS gold,\n c1.live - IFNULL(c2.live, 0) AS live\nFROM\n characters_by_gametime c1\n LEFT JOIN characters_by_gametime c2\n ON c1.id = c2.id + 1\nORDER BY\n c1.id;\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ]
257,220
<h2>solution structure [Plain Winforms + VS 2008 Express Edition]</h2> <ul> <li>CoffeeMakerInterface (NS CoffeeMaker)</li> <li>CoffeeMakerSoftware (NS CoffeeMakerSoftware)</li> <li>TestCoffeeMaker (NS TestCoffeeMaker)</li> </ul> <p>CoffeeMakerSoftware proj references CoffeeMakerInterface. TestCoffeeMaker proj references CoffeeMakerInterface and CoffeeMakerSoftware.</p> <p>Now the thing that is driving me nuts. I can't get this to build. <strong>If I remove CoffeeMakerSoftware project reference from TestCoffeeMaker it builds (??!!).. as soon as I add the second project reference, it throws build errors</strong> claiming that types declared in first reference 'can't be found.. are you missing an assembly ref'</p> <p>At first I had the first 2 assemblies having the same namespace CoffeeMaker.. I then made them distinct (although I think having classes belonging to the same NS across assemblies should be possible) but even that doesn't seem to be it.</p> <p>Calling more eyeballs. Any pointers.. </p>
[ { "answer_id": 258076, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "1. CoffeeMaker > CoffeeMakerInterfaces\n2. [X] > CoffeeMaker > CoffeeMakerSoftware\n3. [X] > TestCoffeeMaker\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
257,229
<p>I am writing a quick application myself - first project, however I am trying to find the VBA code for writing the result of an input string to a named cell in Excel.</p> <p>For example, a input box asks the question "Which job number would you like to add to the list?"... the user would then enter a reference number such as "FX1234356". The macro then needs to write that information into a cell, which I can then use to finish the macro (basically a search in some data).</p>
[ { "answer_id": 257247, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": true, "text": "Range(\"C1\").Value = Inputbox(\"Which job number would you like to add to the list?)\n" }, { "answer_id": 257253, "author": "rbrayb", "author_id": 9922, "author_profile": "https://Stackoverflow.com/users/9922", "pm_score": 0, "selected": false, "text": "H1 ActiveSheet.Range(\"H1\").Value = txtBoxName.Text" }, { "answer_id": 257706, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 2, "selected": false, "text": "Range(\"RefNo\") = InputBox(\"....\") \n Range(\"H1\") = InputBox(\"....\") \n Range(\"Results\").Resize(10,3) = arrResults()\n Option Base 1\n" }, { "answer_id": 35447038, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " Dim returnVal As Variant\n\n returnVal = InputBox(Prompt:=\"Type a value:\", Title:=\"Test Data\")\n\n 'if the user clicked Cancel, Close or Esc the False\n 'is translated to the variant as a vbNullString\n Select Case True\n Case Len(returnVal) = 0\n 'no value but user clicked OK - clear the target cell\n Range(\"A2\").ClearContents\n Case Else\n 'returned a value with OK, save it\n Range(\"A2\") = returnVal\n End Select\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22284/" ]
257,250
<p>I'm relatively new to jQuery, but so far what I've seen I like. What I want is for a div (or any element) to be across the top of the page as if "position: fixed" worked in every browser.</p> <p>I do not want something complicated. I do not want giant CSS hacks. I would prefer if just using jQuery (version 1.2.6) is good enough, but if I need jQuery-UI-core, then that's fine too.</p> <p>I've tried $("#topBar").scrollFollow(); &lt;-- but that goes slow... I want something to appear really fixed.</p>
[ { "answer_id": 257972, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 7, "selected": true, "text": "<div id=\"myElement\" style=\"position: absolute\">This stays at the top</div>\n $(window).scroll(function() {\n $('#myElement').css('top', $(this).scrollTop() + \"px\");\n});\n" }, { "answer_id": 258331, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n $(\"#topBar\").css(\"position\", \"absolute\");\n});\n\n$(window).scroll(function() {\n $(\"#topBar\").css(\"top\", $(window).scrollTop() + \"px\");\n});\n" }, { "answer_id": 11620903, "author": "Mac Attack", "author_id": 406914, "author_profile": "https://Stackoverflow.com/users/406914", "pm_score": 2, "selected": false, "text": "<div> <div id=\"wrapper\">\n <div id=\"fixed\">\n [Fixed Content]\n </div><!-- /fixed -->\n <div id=\"scroller\">\n [Scrolling Content]\n </div><!-- /scroller -->\n</div><!-- /wrapper -->\n #wrapper { position: relative; }\n#fixed { position: fixed; top: 0; right: 0; }\n#scroller { height: 100px; overflow: auto; }\n //Compensate for the scrollbar (otherwise #fixed will be positioned over it).\n$(function() {\n //Determine the difference in widths between\n //the wrapper and the scroller. This value is\n //the width of the scroll bar (if any).\n var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;\n\n //Set the right offset\n $('#fixed').css('right', offset + 'px');​\n});\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11917/" ]
257,251
<p>I swear I've seen someone do this, but I can't find it in the various lists of shortcuts.</p> <p>Given:</p> <pre><code>String s = "A very long ............................ String"; </code></pre> <p>Is there an Eclipse shortcut to turn it into:</p> <pre><code>String s = "A very long ............................ " + "String"; </code></pre>
[ { "answer_id": 257652, "author": "John Stoneham", "author_id": 2040146, "author_profile": "https://Stackoverflow.com/users/2040146", "pm_score": 0, "selected": false, "text": "StringBuilder MessageFormat" }, { "answer_id": 26861386, "author": "Tomáš Záluský", "author_id": 653539, "author_profile": "https://Stackoverflow.com/users/653539", "pm_score": 0, "selected": false, "text": "\"\\s*?\\+\\s*?\\R(\\s*?)\" \"\\R$1\\+ \"" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
257,255
<p>I'm looking for a really generic way to "fill out" a form based on a parameter string using javascript.</p> <p>for example, if i have this form:</p> <pre><code>&lt;form id="someform"&gt; &lt;select name="option1"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;select name="option2"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p>I'd like to be able to take a param string like this: <code>option1=2&amp;option2=1</code></p> <p>And then have the correct things selected based on the options in the query string.</p> <p>I have a sort of ugly solution where I go through children of the form and check if they match the various keys, then set the values, but I really don't like it.</p> <p>I'd like a cleaner, <strong>generic</strong> way of doing it that would work for any form (assuming the param string had all the right keys).</p> <p>I'm using the prototype javascript library, so I'd welcome suggestions that take advantage of it.</p> <p>EDIT: this is what I've come up with so far (using prototype for <code>Form.getElements(form)</code>)</p> <pre><code>function setFormOptions(formId, params) { params = params.split('&amp;'); params.each(function(pair) { pair = pair.split('='); var key = pair[0]; var val = pair[1]; Form.getElements(form).each(function(element) { if(element.name == key) { element.value = val; } }); }); } </code></pre> <p>I feel that it could still be faster/cleaner however.</p>
[ { "answer_id": 257287, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 1, "selected": false, "text": "function setFormSelectValues(form, dataset) {\n var sel = form.getElementsByTagName(\"select\");\n dataset.replace(/([^=&]+)=([^&]*)/g, function(match, name, value){\n for (var i = 0; i < sel.length; ++i) {\n if (sel[i].name == name) {\n sel[i].value = value;\n }\n }\n }); \n}\n" }, { "answer_id": 257322, "author": "Stephen Walcher", "author_id": 25375, "author_profile": "https://Stackoverflow.com/users/25375", "pm_score": 2, "selected": false, "text": "Event.observe(window, 'load', function() {\n var loc = window.location.search.substr(1).split('&');\n\n loc.each(function(param) {\n param = param.split('=');\n key = param[0];\n val = param[1];\n\n $(key).value = val;\n });\n});\n Event.observe(window, 'load', function() {\n var loc = window.location.search.substr(1).split('&');\n\n loc.each(function(param) {\n param = param.split('=');\n key = param[0].split('_');\n\n type = key[0];\n key = key[1];\n val = param[1];\n\n $$(type + '[name=\"' + key + '\"]').each(function(ele) {\n ele.value = val;\n });\n});\n" }, { "answer_id": 257401, "author": "adgoudz", "author_id": 30527, "author_profile": "https://Stackoverflow.com/users/30527", "pm_score": 4, "selected": true, "text": "function populateForm(queryString) {\n var params = queryString.toQueryParams();\n Object.keys(params).each(function(key) {\n Form.Element.setValue($(\"someform\")[key], params[key]);\n });\n}\n" }, { "answer_id": 283923, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 0, "selected": false, "text": "$H(query.toQueryParams()).each(function(pair) {\n $(\"form\")[pair.key].setValue(pair.value);\n});\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12983/" ]
257,259
<pre><code>void addNewNode (struct node *head, int n) { struct node* temp = (struct node*) malloc(sizeof(struct node)); temp -&gt; data = n; temp -&gt; link = head; head = temp; } </code></pre> <p>The code give above is the popularly wrong version of a function for adding a new node at the head of a linked list. Generally the correct versions are like,</p> <pre><code>void addNewNode (struct node **head, int n); void addNewNode (struct node * &amp;head, int n); </code></pre> <p>I worked out another but simple function for the purpose which worked fine.</p> <pre><code>struct node* addNewNode (struct node *head, int n) { struct node* temp = (struct node*) malloc(sizeof(struct node)); temp -&gt; data = n; temp -&gt; link = head; return temp; } </code></pre> <p>But I haven't seen this being used or discussed in code and tutorials and thus I am curious to know if this approach has some flaw.</p>
[ { "answer_id": 257267, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 2, "selected": false, "text": "addNode list.add(element)\n list = add(list, element)\n" }, { "answer_id": 257268, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "val ls = [1, 2, 3, 4]\nval newList = 0 :: ls\n :: 0 ls 0 :: addNewNode" }, { "answer_id": 259115, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 1, "selected": false, "text": "malloc() sizeof struct node* temp = malloc(sizeof *temp);\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6561/" ]
257,286
<p>in C++ I have two chars holding hex values e.g.:</p> <pre><code>char t = 0x4; char q = 0x4; </code></pre> <p>How would i compare if the two values held in the char are the same?? I tried</p> <pre><code>if (t == q) // should give me true </code></pre> <p>but no, any help, thanks!</p>
[ { "answer_id": 257291, "author": "BobS", "author_id": 33481, "author_profile": "https://Stackoverflow.com/users/33481", "pm_score": -1, "selected": false, "text": "if (t & q)\n" }, { "answer_id": 257304, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "char t = 0x4;\nchar q = 0x4;\nif(t == q)\n{\n //They are the same\n}\n char t = 4;\nchar q = 4;\nif(t == q)\n{\n //They are the same\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
257,288
<p>Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?</p> <p>Here's a simple example of what I would want to write:</p> <pre><code>template&lt;class T&gt; std::string optionalToString(T* obj) { if (FUNCTION_EXISTS(T-&gt;toString)) return obj-&gt;toString(); else return "toString not defined"; } </code></pre> <p>So, if <code>class T</code> has <code>toString()</code> defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.</p>
[ { "answer_id": 257315, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "template <typename T>\nstruct response_trait {\n static bool const has_tostring = false;\n};\n\ntemplate <>\nstruct response_trait<your_type_with_tostring> {\n static bool const has_tostring = true;\n}\n" }, { "answer_id": 257382, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 10, "selected": true, "text": "#include <iostream>\n\nstruct Hello\n{\n int helloworld() { return 0; }\n};\n\nstruct Generic {}; \n\n// SFINAE test\ntemplate <typename T>\nclass has_helloworld\n{\n typedef char one;\n struct two { char x[2]; };\n\n template <typename C> static one test( decltype(&C::helloworld) ) ;\n template <typename C> static two test(...); \n\npublic:\n enum { value = sizeof(test<T>(0)) == sizeof(char) };\n};\n \nint main(int argc, char *argv[])\n{\n std::cout << has_helloworld<Hello>::value << std::endl;\n std::cout << has_helloworld<Generic>::value << std::endl;\n return 0;\n}\n" }, { "answer_id": 261262, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "typeof toString() T doToString() toString() #include <iostream>\n#include <string>\n\nstruct Hello\n{\n std::string toString() {\n return \"Hello\";\n }\n};\n\nstruct Generic {};\n\n\n// the following namespace keeps the toString() method out of\n// most everything - except the other stuff in this\n// compilation unit\n\nnamespace {\n std::string toString()\n {\n return \"toString not defined\";\n }\n\n template <typename T>\n class optionalToStringImpl : public T\n {\n public:\n std::string doToString() {\n\n // in theory, the name lookup for this call to \n // toString() should find the toString() in \n // the base class T if one exists, but if one \n // doesn't exist in the base class, it'll \n // find the free toString() function in \n // the private namespace.\n //\n // This theory works for MSVC (all versions\n // from VC6 to VC9) and Comeau C++, but\n // does not work with MinGW 3.4.5 or \n // Digital Mars 8.42n\n //\n // I'm honestly not sure what the standard says \n // is the correct behavior here - it's sort \n // of like ADL (Argument Dependent Lookup - \n // also known as Koenig Lookup) but without\n // arguments (except the implied \"this\" pointer)\n\n return toString();\n }\n };\n}\n\ntemplate <typename T>\nstd::string optionalToString(T & obj)\n{\n // ugly, hacky cast...\n optionalToStringImpl<T>* temp = reinterpret_cast<optionalToStringImpl<T>*>( &obj);\n\n return temp->doToString();\n}\n\n\n\nint\nmain(int argc, char *argv[])\n{\n Hello helloObj;\n Generic genericObj;\n\n std::cout << optionalToString( helloObj) << std::endl;\n std::cout << optionalToString( genericObj) << std::endl;\n return 0;\n}\n" }, { "answer_id": 264088, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": false, "text": "#define HAS_MEM_FUNC(func, name) \\\n template<typename T, typename Sign> \\\n struct name { \\\n typedef char yes[1]; \\\n typedef char no [2]; \\\n template <typename U, U> struct type_check; \\\n template <typename _1> static yes &chk(type_check<Sign, &_1::func > *); \\\n template <typename > static no &chk(...); \\\n static bool const value = sizeof(chk<T>(0)) == sizeof(yes); \\\n }\n HAS_MEM_FUNC(toString, has_to_string);\n\ntemplate<typename T> void\ndoSomething() {\n if(has_to_string<T, std::string(T::*)()>::value) {\n ...\n } else {\n ...\n }\n}\n toString if enable_if template<bool C, typename T = void>\nstruct enable_if {\n typedef T type;\n};\n\ntemplate<typename T>\nstruct enable_if<false, T> { };\n\nHAS_MEM_FUNC(toString, has_to_string);\n\ntemplate<typename T> \ntypename enable_if<has_to_string<T, \n std::string(T::*)()>::value, std::string>::type\ndoSomething(T * t) {\n /* something when T has toString ... */\n return t->toString();\n}\n\ntemplate<typename T> \ntypename enable_if<!has_to_string<T, \n std::string(T::*)()>::value, std::string>::type\ndoSomething(T * t) {\n /* something when T doesnt have toString ... */\n return \"T::toString() does not exist.\";\n}\n const std::string(T::*)() const" }, { "answer_id": 3102261, "author": "Alexandre C.", "author_id": 373025, "author_profile": "https://Stackoverflow.com/users/373025", "pm_score": 2, "selected": false, "text": "template <class T>\nstruct has_foo\n{\n struct S { void foo(...); };\n struct derived : S, T {};\n\n template <typename V, V> struct W {};\n\n template <typename X>\n char (&test(W<void (X::*)(), &X::foo> *))[1];\n\n template <typename>\n char (&test(...))[2];\n\n static const bool value = sizeof(test<derived>(0)) == 1;\n};\n" }, { "answer_id": 3627243, "author": "FireAphis", "author_id": 102834, "author_profile": "https://Stackoverflow.com/users/102834", "pm_score": 6, "selected": false, "text": "typeof template <class Type>\nclass TypeHasToString\n{\n // This type won't compile if the second template parameter isn't of type T,\n // so I can put a function pointer type in the first parameter and the function\n // itself in the second thus checking that the function has a specific signature.\n template <typename T, T> struct TypeCheck;\n\n typedef char Yes;\n typedef long No;\n\n // A helper struct to hold the declaration of the function pointer.\n // Change it if the function signature changes.\n template <typename T> struct ToString\n {\n typedef void (T::*fptr)();\n };\n\n template <typename T> static Yes HasToString(TypeCheck< typename ToString<T>::fptr, &T::toString >*);\n template <typename T> static No HasToString(...);\n\npublic:\n static bool const value = (sizeof(HasToString<Type>(0)) == sizeof(Yes));\n};\n" }, { "answer_id": 6324863, "author": "Brett Rossier", "author_id": 376331, "author_profile": "https://Stackoverflow.com/users/376331", "pm_score": 3, "selected": false, "text": "x CREATE_MEMBER_CHECK(x);\nbool has_x = has_member_x<class_to_check_for_x>::value;\n void x() //Func signature MUST have T as template variable here... simpler this way :\\\nCREATE_MEMBER_FUNC_SIG_CHECK(x, void (T::*)(), void__x);\nbool has_func_sig_void__x = has_member_func_void__x<class_to_check_for_x>::value;\n x CREATE_MEMBER_VAR_CHECK(x);\nbool has_var_x = has_member_var_x<class_to_check_for_x>::value;\n x CREATE_MEMBER_CLASS_CHECK(x);\nbool has_class_x = has_member_class_x<class_to_check_for_x>::value;\n x CREATE_MEMBER_UNION_CHECK(x);\nbool has_union_x = has_member_union_x<class_to_check_for_x>::value;\n x CREATE_MEMBER_ENUM_CHECK(x);\nbool has_enum_x = has_member_enum_x<class_to_check_for_x>::value;\n x CREATE_MEMBER_CHECK(x);\nCREATE_MEMBER_VAR_CHECK(x);\nCREATE_MEMBER_CLASS_CHECK(x);\nCREATE_MEMBER_UNION_CHECK(x);\nCREATE_MEMBER_ENUM_CHECK(x);\nCREATE_MEMBER_FUNC_CHECK(x);\nbool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;\n CREATE_MEMBER_CHECKS(x); //Just stamps out the same macro calls as above.\nbool has_any_func_x = has_member_func_x<class_to_check_for_x>::value;\n /*\n - Multiple inheritance forces ambiguity of member names.\n - SFINAE is used to make aliases to member names.\n - Expression SFINAE is used in just one generic has_member that can accept\n any alias we pass it.\n*/\n\n//Variadic to force ambiguity of class members. C++11 and up.\ntemplate <typename... Args> struct ambiguate : public Args... {};\n\n//Non-variadic version of the line above.\n//template <typename A, typename B> struct ambiguate : public A, public B {};\n\ntemplate<typename A, typename = void>\nstruct got_type : std::false_type {};\n\ntemplate<typename A>\nstruct got_type<A> : std::true_type {\n typedef A type;\n};\n\ntemplate<typename T, T>\nstruct sig_check : std::true_type {};\n\ntemplate<typename Alias, typename AmbiguitySeed>\nstruct has_member {\n template<typename C> static char ((&f(decltype(&C::value))))[1];\n template<typename C> static char ((&f(...)))[2];\n\n //Make sure the member name is consistently spelled the same.\n static_assert(\n (sizeof(f<AmbiguitySeed>(0)) == 1)\n , \"Member name specified in AmbiguitySeed is different from member name specified in Alias, or wrong Alias/AmbiguitySeed has been specified.\"\n );\n\n static bool const value = sizeof(f<Alias>(0)) == 2;\n};\n //Check for any member with given name, whether var, func, class, union, enum.\n#define CREATE_MEMBER_CHECK(member) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct Alias_##member; \\\n \\\ntemplate<typename T> \\\nstruct Alias_##member < \\\n T, std::integral_constant<bool, got_type<decltype(&T::member)>::value> \\\n> { static const decltype(&T::member) value; }; \\\n \\\nstruct AmbiguitySeed_##member { char member; }; \\\n \\\ntemplate<typename T> \\\nstruct has_member_##member { \\\n static const bool value \\\n = has_member< \\\n Alias_##member<ambiguate<T, AmbiguitySeed_##member>> \\\n , Alias_##member<AmbiguitySeed_##member> \\\n >::value \\\n ; \\\n}\n //Check for member variable with given name.\n#define CREATE_MEMBER_VAR_CHECK(var_name) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_var_##var_name : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_var_##var_name< \\\n T \\\n , std::integral_constant< \\\n bool \\\n , !std::is_member_function_pointer<decltype(&T::var_name)>::value \\\n > \\\n> : std::true_type {}\n //Check for member function with given name AND signature.\n#define CREATE_MEMBER_FUNC_SIG_CHECK(func_name, func_sig, templ_postfix) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_func_##templ_postfix : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_func_##templ_postfix< \\\n T, std::integral_constant< \\\n bool \\\n , sig_check<func_sig, &T::func_name>::value \\\n > \\\n> : std::true_type {}\n //Check for member class with given name.\n#define CREATE_MEMBER_CLASS_CHECK(class_name) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_class_##class_name : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_class_##class_name< \\\n T \\\n , std::integral_constant< \\\n bool \\\n , std::is_class< \\\n typename got_type<typename T::class_name>::type \\\n >::value \\\n > \\\n> : std::true_type {}\n //Check for member union with given name.\n#define CREATE_MEMBER_UNION_CHECK(union_name) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_union_##union_name : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_union_##union_name< \\\n T \\\n , std::integral_constant< \\\n bool \\\n , std::is_union< \\\n typename got_type<typename T::union_name>::type \\\n >::value \\\n > \\\n> : std::true_type {}\n //Check for member enum with given name.\n#define CREATE_MEMBER_ENUM_CHECK(enum_name) \\\n \\\ntemplate<typename T, typename = std::true_type> \\\nstruct has_member_enum_##enum_name : std::false_type {}; \\\n \\\ntemplate<typename T> \\\nstruct has_member_enum_##enum_name< \\\n T \\\n , std::integral_constant< \\\n bool \\\n , std::is_enum< \\\n typename got_type<typename T::enum_name>::type \\\n >::value \\\n > \\\n> : std::true_type {}\n //Check for function with given name, any signature.\n#define CREATE_MEMBER_FUNC_CHECK(func) \\\ntemplate<typename T> \\\nstruct has_member_func_##func { \\\n static const bool value \\\n = has_member_##func<T>::value \\\n && !has_member_var_##func<T>::value \\\n && !has_member_class_##func<T>::value \\\n && !has_member_union_##func<T>::value \\\n && !has_member_enum_##func<T>::value \\\n ; \\\n}\n //Create all the checks for one member. Does NOT include func sig checks.\n#define CREATE_MEMBER_CHECKS(member) \\\nCREATE_MEMBER_CHECK(member); \\\nCREATE_MEMBER_VAR_CHECK(member); \\\nCREATE_MEMBER_CLASS_CHECK(member); \\\nCREATE_MEMBER_UNION_CHECK(member); \\\nCREATE_MEMBER_ENUM_CHECK(member); \\\nCREATE_MEMBER_FUNC_CHECK(member)\n" }, { "answer_id": 8755981, "author": "kispaljr", "author_id": 667409, "author_profile": "https://Stackoverflow.com/users/667409", "pm_score": 3, "selected": false, "text": "T::const_iterator begin() const template<class T> struct has_const_begin\n{\n typedef char (&Yes)[1];\n typedef char (&No)[2];\n\n template<class U> \n static Yes test(U const * data, \n typename std::enable_if<std::is_same<\n typename U::const_iterator, \n decltype(data->begin())\n >::value>::type * = 0);\n static No test(...);\n static const bool value = sizeof(Yes) == sizeof(has_const_begin::test((typename std::remove_reference<T>::type*)0));\n};\n has_const_begin<int>::value void foo(MyClass&, unsigned) template<class T> struct has_foo\n{\n typedef char (&Yes)[1];\n typedef char (&No)[2];\n\n template<class U>\n static Yes test(U * data, MyClass* arg1 = 0,\n typename std::enable_if<std::is_void<\n decltype(data->foo(*arg1, 1u))\n >::value>::type * = 0);\n static No test(...);\n static const bool value = sizeof(Yes) == sizeof(has_foo::test((typename std::remove_reference<T>::type*)0));\n};\n" }, { "answer_id": 9154394, "author": "Xeo", "author_id": 500104, "author_profile": "https://Stackoverflow.com/users/500104", "pm_score": 8, "selected": false, "text": "template<class T>\nauto serialize_imp(std::ostream& os, T const& obj, int)\n -> decltype(os << obj, void())\n{\n os << obj;\n}\n\ntemplate<class T>\nauto serialize_imp(std::ostream& os, T const& obj, long)\n -> decltype(obj.stream(os), void())\n{\n obj.stream(os);\n}\n\ntemplate<class T>\nauto serialize(std::ostream& os, T const& obj)\n -> decltype(serialize_imp(os, obj, 0), void())\n{\n serialize_imp(os, obj, 0);\n}\n serialize(_imp) decltype void() void 0 os << obj 0 int #include <type_traits>\n\ntemplate<class>\nstruct sfinae_true : std::true_type{};\n\nnamespace detail{\n template<class T, class A0>\n static auto test_stream(int)\n -> sfinae_true<decltype(std::declval<T>().stream(std::declval<A0>()))>;\n template<class, class A0>\n static auto test_stream(long) -> std::false_type;\n} // detail::\n\ntemplate<class T, class Arg>\nstruct has_stream : decltype(detail::test_stream<T, Arg>(0)){};\n sfinae_true decltype(void(std::declval<T>().stream(a0)), std::true_type{}) struct has_stream : decltype(...) std::true_type std::false_type decltype test_stream std::declval decltype sizeof decltype sizeof decltype sizeof template<class T>\nvoid serialize_imp(std::ostream& os, T const& obj, int,\n int(*)[sizeof((os << obj),0)] = 0)\n{\n os << obj;\n}\n int long sizeof" }, { "answer_id": 17534399, "author": "user1095108", "author_id": 1095108, "author_profile": "https://Stackoverflow.com/users/1095108", "pm_score": 2, "selected": false, "text": "#include <type_traits>\n\ntemplate <typename U, typename = void> struct hasToString : std::false_type { };\n\ntemplate <typename U>\nstruct hasToString<U,\n typename std::enable_if<bool(sizeof(&U::toString))>::type\n> : std::true_type { };\n" }, { "answer_id": 19815793, "author": "Shubham", "author_id": 2712152, "author_profile": "https://Stackoverflow.com/users/2712152", "pm_score": 3, "selected": false, "text": "/** \n * @class : HAS_TYPEDEF\n * @brief : This macro will be used to check if a class has a particular\n * typedef or not.\n * @param typedef_name : Name of Typedef\n * @param name : Name of struct which is going to be run the test for\n * the given particular typedef specified in typedef_name\n */\n#define HAS_TYPEDEF(typedef_name, name) \\\n template <typename T> \\\n struct name { \\\n typedef char yes[1]; \\\n typedef char no[2]; \\\n template <typename U> \\\n struct type_check; \\\n template <typename _1> \\\n static yes& chk(type_check<typename _1::typedef_name>*); \\\n template <typename> \\\n static no& chk(...); \\\n static bool const value = sizeof(chk<T>(0)) == sizeof(yes); \\\n }\n /** \n * @class : HAS_MEM_FUNC\n * @brief : This macro will be used to check if a class has a particular\n * member function implemented in the public section or not. \n * @param func : Name of Member Function\n * @param name : Name of struct which is going to be run the test for\n * the given particular member function name specified in func\n * @param return_type: Return type of the member function\n * @param ellipsis(...) : Since this is macro should provide test case for every\n * possible member function we use variadic macros to cover all possibilities\n */\n#define HAS_MEM_FUNC(func, name, return_type, ...) \\\n template <typename T> \\\n struct name { \\\n typedef return_type (T::*Sign)(__VA_ARGS__); \\\n typedef char yes[1]; \\\n typedef char no[2]; \\\n template <typename U, U> \\\n struct type_check; \\\n template <typename _1> \\\n static yes& chk(type_check<Sign, &_1::func>*); \\\n template <typename> \\\n static no& chk(...); \\\n static bool const value = sizeof(chk<T>(0)) == sizeof(yes); \\\n }\n class A {\npublic:\n typedef int check;\n void check_function() {}\n};\n\nclass B {\npublic:\n void hello(int a, double b) {}\n void hello() {}\n};\n\nHAS_MEM_FUNC(check_function, has_check_function, void, void);\nHAS_MEM_FUNC(hello, hello_check, void, int, double);\nHAS_MEM_FUNC(hello, hello_void_check, void, void);\nHAS_TYPEDEF(check, has_typedef_check);\n\nint main() {\n std::cout << \"Check Function A:\" << has_check_function<A>::value << std::endl;\n std::cout << \"Check Function B:\" << has_check_function<B>::value << std::endl;\n std::cout << \"Hello Function A:\" << hello_check<A>::value << std::endl;\n std::cout << \"Hello Function B:\" << hello_check<B>::value << std::endl;\n std::cout << \"Hello void Function A:\" << hello_void_check<A>::value << std::endl;\n std::cout << \"Hello void Function B:\" << hello_void_check<B>::value << std::endl;\n std::cout << \"Check Typedef A:\" << has_typedef_check<A>::value << std::endl;\n std::cout << \"Check Typedef B:\" << has_typedef_check<B>::value << std::endl;\n}\n" }, { "answer_id": 21063089, "author": "Hui", "author_id": 3185134, "author_profile": "https://Stackoverflow.com/users/3185134", "pm_score": 1, "selected": false, "text": "#include <string>\n#include <vector>\n\nHAS_MEM(bar)\nHAS_MEM_FUN_CALL(bar)\n\nstruct test\n{\n void bar(int);\n void bar(double);\n void bar(int,double);\n\n template < typename T >\n typename std::enable_if< not std::is_integral<T>::value >::type\n bar(const T&, int=0){}\n\n template < typename T >\n typename std::enable_if< std::is_integral<T>::value >::type\n bar(const std::vector<T>&, T*){}\n\n template < typename T >\n int bar(const std::string&, int){}\n};\n int main(int argc, const char * argv[])\n{\n static_assert( has_mem_bar<test>::value , \"\");\n\n static_assert( has_valid_mem_fun_call_bar<test(char const*,long)>::value , \"\");\n static_assert( has_valid_mem_fun_call_bar<test(std::string&,long)>::value , \"\");\n\n static_assert( has_valid_mem_fun_call_bar<test(std::vector<int>, int*)>::value , \"\");\n static_assert( has_no_viable_mem_fun_call_bar<test(std::vector<double>, double*)>::value , \"\");\n\n static_assert( has_valid_mem_fun_call_bar<test(int)>::value , \"\");\n static_assert( std::is_same<void,result_of_mem_fun_call_bar<test(int)>::type>::value , \"\");\n\n static_assert( has_valid_mem_fun_call_bar<test(int,double)>::value , \"\");\n static_assert( not has_valid_mem_fun_call_bar<test(int,double,int)>::value , \"\");\n\n static_assert( not has_ambiguous_mem_fun_call_bar<test(double)>::value , \"\");\n static_assert( has_ambiguous_mem_fun_call_bar<test(unsigned)>::value , \"\");\n\n static_assert( has_viable_mem_fun_call_bar<test(unsigned)>::value , \"\");\n static_assert( has_viable_mem_fun_call_bar<test(int)>::value , \"\");\n\n static_assert( has_no_viable_mem_fun_call_bar<test(void)>::value , \"\");\n\n return 0;\n}\n #pragma once\n\n#if __cplusplus >= 201103\n\n#include <utility>\n#include <type_traits>\n\n#define HAS_MEM(mem) \\\n \\\ntemplate < typename T > \\\nstruct has_mem_##mem \\\n{ \\\n struct yes {}; \\\n struct no {}; \\\n \\\n struct ambiguate_seed { char mem; }; \\\n template < typename U > struct ambiguate : U, ambiguate_seed {}; \\\n \\\n template < typename U, typename = decltype(&U::mem) > static constexpr no test(int); \\\n template < typename > static constexpr yes test(...); \\\n \\\n static bool constexpr value = std::is_same<decltype(test< ambiguate<T> >(0)),yes>::value ; \\\n typedef std::integral_constant<bool,value> type; \\\n};\n\n\n#define HAS_MEM_FUN_CALL(memfun) \\\n \\\ntemplate < typename Signature > \\\nstruct has_valid_mem_fun_call_##memfun; \\\n \\\ntemplate < typename T, typename... Args > \\\nstruct has_valid_mem_fun_call_##memfun< T(Args...) > \\\n{ \\\n struct yes {}; \\\n struct no {}; \\\n \\\n template < typename U, bool = has_mem_##memfun<U>::value > \\\n struct impl \\\n { \\\n template < typename V, typename = decltype(std::declval<V>().memfun(std::declval<Args>()...)) > \\\n struct test_result { using type = yes; }; \\\n \\\n template < typename V > static constexpr typename test_result<V>::type test(int); \\\n template < typename > static constexpr no test(...); \\\n \\\n static constexpr bool value = std::is_same<decltype(test<U>(0)),yes>::value; \\\n using type = std::integral_constant<bool, value>; \\\n }; \\\n \\\n template < typename U > \\\n struct impl<U,false> : std::false_type {}; \\\n \\\n static constexpr bool value = impl<T>::value; \\\n using type = std::integral_constant<bool, value>; \\\n}; \\\n \\\ntemplate < typename Signature > \\\nstruct has_ambiguous_mem_fun_call_##memfun; \\\n \\\ntemplate < typename T, typename... Args > \\\nstruct has_ambiguous_mem_fun_call_##memfun< T(Args...) > \\\n{ \\\n struct ambiguate_seed { void memfun(...); }; \\\n \\\n template < class U, bool = has_mem_##memfun<U>::value > \\\n struct ambiguate : U, ambiguate_seed \\\n { \\\n using ambiguate_seed::memfun; \\\n using U::memfun; \\\n }; \\\n \\\n template < class U > \\\n struct ambiguate<U,false> : ambiguate_seed {}; \\\n \\\n static constexpr bool value = not has_valid_mem_fun_call_##memfun< ambiguate<T>(Args...) >::value; \\\n using type = std::integral_constant<bool, value>; \\\n}; \\\n \\\ntemplate < typename Signature > \\\nstruct has_viable_mem_fun_call_##memfun; \\\n \\\ntemplate < typename T, typename... Args > \\\nstruct has_viable_mem_fun_call_##memfun< T(Args...) > \\\n{ \\\n static constexpr bool value = has_valid_mem_fun_call_##memfun<T(Args...)>::value \\\n or has_ambiguous_mem_fun_call_##memfun<T(Args...)>::value; \\\n using type = std::integral_constant<bool, value>; \\\n}; \\\n \\\ntemplate < typename Signature > \\\nstruct has_no_viable_mem_fun_call_##memfun; \\\n \\\ntemplate < typename T, typename... Args > \\\nstruct has_no_viable_mem_fun_call_##memfun < T(Args...) > \\\n{ \\\n static constexpr bool value = not has_viable_mem_fun_call_##memfun<T(Args...)>::value; \\\n using type = std::integral_constant<bool, value>; \\\n}; \\\n \\\ntemplate < typename Signature > \\\nstruct result_of_mem_fun_call_##memfun; \\\n \\\ntemplate < typename T, typename... Args > \\\nstruct result_of_mem_fun_call_##memfun< T(Args...) > \\\n{ \\\n using type = decltype(std::declval<T>().memfun(std::declval<Args>()...)); \\\n};\n\n#endif\n" }, { "answer_id": 22014784, "author": "Morwenn", "author_id": 1364752, "author_profile": "https://Stackoverflow.com/users/1364752", "pm_score": 7, "selected": false, "text": "requires requires optionalToString template<class T>\nstd::string optionalToString(T* obj)\n{\n constexpr bool has_toString = requires(const T& t) {\n t.toString();\n };\n\n if constexpr (has_toString)\n return obj->toString();\n else\n return \"toString not defined\";\n}\n requires std::is_detected template<typename T>\nusing toString_t = decltype( std::declval<T&>().toString() );\n\ntemplate<typename T>\nconstexpr bool has_toString = std::is_detected_v<toString_t, T>;\n if constexpr template<class T>\nstd::string optionalToString(T* obj)\n{\n if constexpr (has_toString<T>)\n return obj->toString();\n else\n return \"toString not defined\";\n}\n is_valid auto has_toString = hana::is_valid([](auto&& obj) -> decltype(obj.toString()) { });\n has_toString IntegralConstant has_toString BOOST_TTI_HAS_MEMBER_FUNCTION #include <boost/tti/has_member_function.hpp>\n\n// Generate the metafunction\nBOOST_TTI_HAS_MEMBER_FUNCTION(toString)\n\n// Check whether T has a member function toString\n// which takes no parameter and returns a std::string\nconstexpr bool foo = has_member_function_toString<T, std::string>::value;\n bool BOOST_TTI_HAS_MEMBER_FUNCTION has_member_function_toString value true T std::string toString() has_member_function_toString has_member_function_toString<T, std::string>::value has_member_function_toString<std::string T::* ()>::value" }, { "answer_id": 23996349, "author": "Yakk - Adam Nevraumont", "author_id": 1774667, "author_profile": "https://Stackoverflow.com/users/1774667", "pm_score": 4, "selected": false, "text": "template<class> struct type_sink { typedef void type; }; // consumes a type, and makes it `void`\ntemplate<class T> using type_sink_t = typename type_sink<T>::type;\ntemplate<class T, class=void> struct has_to_string : std::false_type {}; \\\ntemplate<class T> struct has_to_string<\n T,\n type_sink_t< decltype( std::declval<T>().toString() ) >\n>: std::true_type {};\n has_to_string has_to_string<T>::value true T .toString namespace details {\n template<class T>\n std::string optionalToString_helper(T* obj, std::true_type /*has_to_string*/) {\n return obj->toString();\n }\n template<class T>\n std::string optionalToString_helper(T* obj, std::false_type /*has_to_string*/) {\n return \"toString not defined\";\n }\n}\ntemplate<class T>\nstd::string optionalToString(T* obj) {\n return details::optionalToString_helper( obj, has_to_string<T>{} );\n}\n #define MAKE_CODE_TRAIT( TRAIT_NAME, ... ) \\\ntemplate<class T, class=void> struct TRAIT_NAME : std::false_type {}; \\\ntemplate<class T> struct TRAIT_NAME< T, type_sink_t< decltype( __VA_ARGS__ ) > >: std::true_type {};\n MAKE_CODE_TRAIT T MAKE_CODE_TRAIT( has_to_string, std::declval<T>().toString() )\n template<class T>\nstd::string optionalToString(T* obj) {\n return compiled_if< has_to_string >(*obj, [&](auto&& obj) {\n return obj.toString();\n }) *compiled_else ([&]{ \n return \"toString not defined\";\n });\n}\n" }, { "answer_id": 30848101, "author": "akim", "author_id": 1353549, "author_profile": "https://Stackoverflow.com/users/1353549", "pm_score": 5, "selected": false, "text": "// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf.\ntemplate <typename...>\nusing void_t = void;\n\n// Primary template handles all types not supporting the operation.\ntemplate <typename, template <typename> class, typename = void_t<>>\nstruct detect : std::false_type {};\n\n// Specialization recognizes/validates only types supporting the archetype.\ntemplate <typename T, template <typename> class Op>\nstruct detect<T, Op, void_t<Op<T>>> : std::true_type {};\n template <typename T>\nusing toString_t = decltype(std::declval<T>().toString());\n\ntemplate <typename T>\nusing has_toString = detect<T, toString_t>;\n // Archetypal expression for assignment operation.\ntemplate <typename T>\nusing assign_t = decltype(std::declval<T&>() = std::declval<T const &>())\n\n// Trait corresponding to that archetype.\ntemplate <typename T>\nusing is_assignable = detect<T, assign_t>;\n void_t detect void_t void_t #if __GNUC__ < 5 && ! defined __clang__\n// https://stackoverflow.com/a/28967049/1353549\ntemplate <typename...>\nstruct voider\n{\n using type = void;\n};\ntemplate <typename...Ts>\nusing void_t = typename voider<Ts...>::type;\n#else\ntemplate <typename...>\nusing void_t = void;\n#endif\n" }, { "answer_id": 31860104, "author": "Aaron McDaid", "author_id": 146041, "author_profile": "https://Stackoverflow.com/users/146041", "pm_score": 5, "selected": false, "text": "template<class T>\nauto optionalToString(T* obj)\n -> decltype( obj->toString() )\n{\n return obj->toString();\n}\nauto optionalToString(...) -> string\n{\n return \"toString not defined\";\n}\n template<class T>\nconstexpr auto test_has_toString_method(T* obj)\n -> decltype( obj->toString() , std::true_type{} )\n{\n return obj->toString();\n}\nconstexpr auto test_has_toString_method(...) -> std::false_type\n{\n return \"toString not defined\";\n}\n" }, { "answer_id": 33328621, "author": "user3296587", "author_id": 3296587, "author_profile": "https://Stackoverflow.com/users/3296587", "pm_score": 2, "selected": false, "text": "template<typename T> T declval(void);\n\nstruct fake_void { };\ntemplate<typename T> T &operator,(T &,fake_void);\ntemplate<typename T> T const &operator,(T const &,fake_void);\ntemplate<typename T> T volatile &operator,(T volatile &,fake_void);\ntemplate<typename T> T const volatile &operator,(T const volatile &,fake_void);\n\nstruct yes { char v[1]; };\nstruct no { char v[2]; };\ntemplate<bool> struct yes_no:yes{};\ntemplate<> struct yes_no<false>:no{};\n\ntemplate<typename T>\nstruct has_awesome_member {\n template<typename U> static yes_no<(sizeof((\n declval<U>().awesome_member(),fake_void()\n ))!=0)> check(int);\n template<typename> static no check(...);\n enum{value=sizeof(check<T>(0)) == sizeof(yes)};\n};\n\n\nstruct foo { int awesome_member(void); };\nstruct bar { };\nstruct foo_void { void awesome_member(void); };\nstruct wrong_params { void awesome_member(int); };\n\nstatic_assert(has_awesome_member<foo>::value,\"\");\nstatic_assert(!has_awesome_member<bar>::value,\"\");\nstatic_assert(has_awesome_member<foo_void>::value,\"\");\nstatic_assert(!has_awesome_member<wrong_params>::value,\"\");\n" }, { "answer_id": 34801904, "author": "Paul Fultz II", "author_id": 375343, "author_profile": "https://Stackoverflow.com/users/375343", "pm_score": 1, "selected": false, "text": "fit::conditional template<class T>\nstd::string optionalToString(T* x)\n{\n return fit::conditional(\n [](auto* obj) -> decltype(obj->toString()) { return obj->toString(); },\n [](auto*) { return \"toString not defined\"; }\n )(x);\n}\n FIT_STATIC_LAMBDA_FUNCTION(optionalToString) = fit::conditional(\n [](auto* obj) -> decltype(obj->toString(), std::string()) { return obj->toString(); },\n [](auto*) -> std::string { return \"toString not defined\"; }\n);\n struct withToString\n{\n template<class T>\n auto operator()(T* obj) const -> decltype(obj->toString(), std::string())\n {\n return obj->toString();\n }\n};\n\nstruct withoutToString\n{\n template<class T>\n std::string operator()(T*) const\n {\n return \"toString not defined\";\n }\n};\n\nFIT_STATIC_FUNCTION(optionalToString) = fit::conditional(\n withToString(),\n withoutToString()\n);\n" }, { "answer_id": 37142300, "author": "anton_rh", "author_id": 5447906, "author_profile": "https://Stackoverflow.com/users/5447906", "pm_score": 2, "selected": false, "text": "#include <type_traits>\n\ntemplate <template <typename> class TypeChecker, typename Type>\nstruct is_supported\n{\n // these structs are used to recognize which version\n // of the two functions was chosen during overload resolution\n struct supported {};\n struct not_supported {};\n\n // this overload of chk will be ignored by SFINAE principle\n // if TypeChecker<Type_> is invalid type\n template <typename Type_>\n static supported chk(typename std::decay<TypeChecker<Type_>>::type *);\n\n // ellipsis has the lowest conversion rank, so this overload will be\n // chosen during overload resolution only if the template overload above is ignored\n template <typename Type_>\n static not_supported chk(...);\n\n // if the template overload of chk is chosen during\n // overload resolution then the feature is supported\n // if the ellipses overload is chosen the the feature is not supported\n static constexpr bool value = std::is_same<decltype(chk<Type>(nullptr)),supported>::value;\n};\n foo double(const char*) // if T doesn't have foo method with the signature that allows to compile the bellow\n// expression then instantiating this template is Substitution Failure (SF)\n// which Is Not An Error (INAE) if this happens during overload resolution\ntemplate <typename T>\nusing has_foo = decltype(double(std::declval<T>().foo(std::declval<const char*>())));\n // types that support has_foo\nstruct struct1 { double foo(const char*); }; // exact signature match\nstruct struct2 { int foo(const std::string &str); }; // compatible signature\nstruct struct3 { float foo(...); }; // compatible ellipsis signature\nstruct struct4 { template <typename T>\n int foo(T t); }; // compatible template signature\n\n// types that do not support has_foo\nstruct struct5 { void foo(const char*); }; // returns void\nstruct struct6 { std::string foo(const char*); }; // std::string can't be converted to double\nstruct struct7 { double foo( int *); }; // const char* can't be converted to int*\nstruct struct8 { double bar(const char*); }; // there is no foo method\n\nint main()\n{\n std::cout << std::boolalpha;\n\n std::cout << is_supported<has_foo, int >::value << std::endl; // false\n std::cout << is_supported<has_foo, double >::value << std::endl; // false\n\n std::cout << is_supported<has_foo, struct1>::value << std::endl; // true\n std::cout << is_supported<has_foo, struct2>::value << std::endl; // true\n std::cout << is_supported<has_foo, struct3>::value << std::endl; // true\n std::cout << is_supported<has_foo, struct4>::value << std::endl; // true\n\n std::cout << is_supported<has_foo, struct5>::value << std::endl; // false\n std::cout << is_supported<has_foo, struct6>::value << std::endl; // false\n std::cout << is_supported<has_foo, struct7>::value << std::endl; // false\n std::cout << is_supported<has_foo, struct8>::value << std::endl; // false\n\n return 0;\n}\n" }, { "answer_id": 47064058, "author": "tereshkd", "author_id": 2584542, "author_profile": "https://Stackoverflow.com/users/2584542", "pm_score": 0, "selected": false, "text": "template<typename T>\nusing toStringFn = decltype(std::declval<const T>().toString());\n\ntemplate <class T, toStringFn<T>* = nullptr>\nstd::string optionalToString(const T* obj, int)\n{\n return obj->toString();\n}\n\ntemplate <class T>\nstd::string optionalToString(const T* obj, long)\n{\n return \"toString not defined\";\n}\n\nint main()\n{\n A* a;\n B* b;\n\n std::cout << optionalToString(a, 0) << std::endl; // This is A\n std::cout << optionalToString(b, 0) << std::endl; // toString not defined\n}\n toStringFn<T>* = nullptr int long 0 true template <typename T>\nconstexpr bool toStringExists(long)\n{\n return false;\n}\n\ntemplate <typename T, toStringFn<T>* = nullptr>\nconstexpr bool toStringExists(int)\n{\n return true;\n}\n\n\nint main()\n{\n A* a;\n B* b;\n\n std::cout << toStringExists<A>(0) << std::endl; // true\n std::cout << toStringExists<B>(0) << std::endl; // false\n}\n" }, { "answer_id": 48384508, "author": "Paul Belanger", "author_id": 3349368, "author_profile": "https://Stackoverflow.com/users/3349368", "pm_score": 3, "selected": false, "text": "Has_foo #include <type_traits>\nstruct A{};\n\nstruct B{ int foo(int a, int b);};\n\nstruct C{void foo(int a, int b);};\n\nstruct D{int foo();};\n\nstruct E: public B{};\n\n// available in C++17 onwards as part of <type_traits>\ntemplate<typename...>\nusing void_t = void;\n\ntemplate<typename T, typename = void> struct Has_foo: std::false_type{};\n\ntemplate<typename T> \nstruct Has_foo<T, void_t<\n std::enable_if_t<\n std::is_same<\n int, \n decltype(std::declval<T>().foo((int)0, (int)0))\n >::value\n >\n>>: std::true_type{};\n\n\nstatic_assert(not Has_foo<A>::value, \"A does not have a foo\");\nstatic_assert(Has_foo<B>::value, \"B has a foo\");\nstatic_assert(not Has_foo<C>::value, \"C has a foo with the wrong return. \");\nstatic_assert(not Has_foo<D>::value, \"D has a foo with the wrong arguments. \");\nstatic_assert(Has_foo<E>::value, \"E has a foo since it inherits from B\");\n" }, { "answer_id": 53987441, "author": "Yigal Eilam", "author_id": 5925184, "author_profile": "https://Stackoverflow.com/users/5925184", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\n\nstruct Generic {}; \nstruct HasMember \n{\n HasMember() : _a(1) {};\n int _a;\n}; \n\n// SFINAE test\ntemplate <typename T>\nclass S : public T\n{\npublic:\n std::string foo (std::string b)\n {\n return foo2<T>(b,0);\n }\n\nprotected:\n template <typename T> std::string foo2 (std::string b, decltype (T::_a))\n {\n return b + std::to_string(T::_a);\n }\n template <typename T> std::string foo2 (std::string b, ...)\n {\n return b + \"No\";\n }\n};\n\nint main(int argc, char *argv[])\n{\n S<HasMember> d1;\n S<Generic> d2;\n\n std::cout << d1.foo(\"HasMember: \") << std::endl;\n std::cout << d2.foo(\"Generic: \") << std::endl;\n return 0;\n}\n" }, { "answer_id": 54867112, "author": "Abhishek", "author_id": 5321262, "author_profile": "https://Stackoverflow.com/users/5321262", "pm_score": -1, "selected": false, "text": "template<class T>\nauto optionalToString(T* obj)\n->decltype( obj->toString(), std::string() )\n{\n return obj->toString();\n}\n\ntemplate<class T>\nauto optionalToString(T* obj)\n->decltype( std::string() )\n{\n throw \"Error!\";\n}\n" }, { "answer_id": 61034367, "author": "Bernd", "author_id": 9099261, "author_profile": "https://Stackoverflow.com/users/9099261", "pm_score": 4, "selected": false, "text": "template<typename T>\nconcept has_toString = requires(const T& t) {\n t.toString();\n};\n\ntemplate<typename T>\nstd::string optionalToString(const T& obj)\n{\n if constexpr (has_toString<T>)\n return obj.toString();\n else\n return \"toString not defined\";\n}\n" }, { "answer_id": 62292282, "author": "Dmytro Ovdiienko", "author_id": 1145526, "author_profile": "https://Stackoverflow.com/users/1145526", "pm_score": 4, "selected": false, "text": "boost:hana has_something<T> ////////////////////////////////////////////\n// has_member implementation\n////////////////////////////////////////////\n\n#include <type_traits>\n\ntemplate<typename T, typename F>\nconstexpr auto has_member_impl(F&& f) -> decltype(f(std::declval<T>()), true)\n{\n return true;\n}\n\ntemplate<typename>\nconstexpr bool has_member_impl(...) { return false; }\n\n#define has_member(T, EXPR) \\\n has_member_impl<T>( [](auto&& obj)->decltype(obj.EXPR){} )\n\n ////////////////////////////////////////////\n// Test\n////////////////////////////////////////////\n\n#include <iostream>\n#include <string>\n\nstruct Example {\n int Foo;\n void Bar() {}\n std::string toString() { return \"Hello from Example::toString()!\"; }\n};\n\nstruct Example2 {\n int X;\n};\n\ntemplate<class T>\nstd::string optionalToString(T* obj)\n{\n if constexpr(has_member(T, toString()))\n return obj->toString();\n else\n return \"toString not defined\";\n}\n\nint main() {\n static_assert(has_member(Example, Foo), \n \"Example class must have Foo member\");\n static_assert(has_member(Example, Bar()), \n \"Example class must have Bar() member function\");\n static_assert(!has_member(Example, ZFoo), \n \"Example class must not have ZFoo member.\");\n static_assert(!has_member(Example, ZBar()), \n \"Example class must not have ZBar() member function\");\n\n Example e1;\n Example2 e2;\n\n std::cout << \"e1: \" << optionalToString(&e1) << \"\\n\";\n std::cout << \"e1: \" << optionalToString(&e2) << \"\\n\";\n}\n" }, { "answer_id": 63630013, "author": "Sean", "author_id": 12854372, "author_profile": "https://Stackoverflow.com/users/12854372", "pm_score": 2, "selected": false, "text": "template<typename Callable, typename... Args, typename = decltype(declval<Callable>()(declval<Args>()...))>\nstd::true_type isCallableImpl(Callable, Args...) { return {}; }\n\nstd::false_type isCallableImpl(...) { return {}; }\n\ntemplate<typename... Args, typename Callable>\nconstexpr bool isCallable(Callable callable) {\n return decltype(isCallableImpl(callable, declval<Args>()...)){};\n}\n constexpr auto TO_STRING_TEST = [](auto in) -> decltype(in.toString()) { return {}; };\nconstexpr bool TO_STRING_WORKS = isCallable<T>(TO_STRING_TEST);\n" }, { "answer_id": 63823318, "author": "TommyD", "author_id": 4602726, "author_profile": "https://Stackoverflow.com/users/4602726", "pm_score": 3, "selected": false, "text": "const std::vector<>::begin #include <iostream>\n#include <vector>\n\nclass EmptyClass{};\n\ntemplate <typename T>\nclass has_begin\n{\n private:\n has_begin() = delete;\n \n struct one { char x[1]; };\n struct two { char x[2]; };\n\n template <typename C> static one test( decltype(void(std::declval<C &>().begin())) * ) ;\n template <typename C> static two test(...); \n\npublic:\n static constexpr bool value = sizeof(test<T>(0)) == sizeof(one);\n};\n \nint main(int argc, char *argv[])\n{\n std::cout << std::boolalpha;\n std::cout << \"vector<int>::begin() exists: \" << has_begin<std::vector<int>>::value << std::endl;\n std::cout << \"EmptyClass::begin() exists: \" << has_begin<EmptyClass>::value << std::endl;\n return 0;\n}\n #include <iostream>\n#include <vector>\n\nclass EmptyClass{};\n\ntemplate <typename T, typename = void>\nstruct has_begin : std::false_type {};\n\ntemplate <typename T>\nstruct has_begin<T, decltype(void(std::declval<T &>().begin()))> : std::true_type {};\n\nint main(int argc, char *argv[])\n{\n std::cout << std::boolalpha;\n std::cout << \"vector<int>::begin() exists: \" << has_begin<std::vector<int>>::value << std::endl;\n std::cout << \"EmptyClass exists: \" << has_begin<EmptyClass>::value << std::endl;\n}\n resize resize(0) test( decltype(&C::helloworld) ) noop has_begin<T, decltype(void(std::declval<T &>().begin()))>\n std::declval<T &>() begin begin decltype begin" }, { "answer_id": 64945445, "author": "Thomas Eding", "author_id": 239916, "author_profile": "https://Stackoverflow.com/users/239916", "pm_score": 1, "selected": false, "text": "template <typename... Args>\nstruct Pack {};\n\n#define Proxy(T) ((T &)(*(int *)(nullptr)))\n\ntemplate <typename Class, typename ArgPack, typename = nullptr_t>\nstruct HasFoo\n{\n enum { value = false };\n};\n\ntemplate <typename Class, typename... Args>\nstruct HasFoo<\n Class,\n Pack<Args...>,\n decltype((void)(Proxy(Class).foo(Proxy(Args)...)), nullptr)>\n{\n enum { value = true };\n};\n struct Object\n{\n int foo(int n) { return n; }\n#if SOME_CONDITION\n int foo(int n, char c) { return n + c; }\n#endif\n};\n\ntemplate <bool has_foo_int_char>\nstruct Dispatcher;\n\ntemplate <>\nstruct Dispatcher<false>\n{\n template <typename Object>\n static int exec(Object &object, int n, char c)\n {\n return object.foo(n) + c;\n }\n};\n\ntemplate <>\nstruct Dispatcher<true>\n{\n template <typename Object>\n static int exec(Object &object, int n, char c)\n {\n return object.foo(n, c);\n }\n};\n\nint runExample()\n{\n using Args = Pack<int, char>;\n enum { has_overload = HasFoo<Object, Args>::value };\n Object object;\n return Dispatcher<has_overload>::exec(object, 100, 'a');\n}\n" }, { "answer_id": 66190295, "author": "DisplayName", "author_id": 8741818, "author_profile": "https://Stackoverflow.com/users/8741818", "pm_score": 0, "selected": false, "text": "has_member has_member<ClassName, SOME_MACRO_WITH_DECLTYPE(member_name)> #include <iostream>\n#include <list>\n#include <type_traits>\n\n#define LAMBDA_FOR_MEMBER_NAME(NAME) [](auto object_instance) -> decltype(&(decltype(object_instance)::NAME)) {}\n\ntemplate<typename T>\nstruct TypeGetter\n{\n constexpr TypeGetter() = default;\n constexpr TypeGetter(T) {}\n using type = T;\n\n constexpr auto getValue()\n {\n return std::declval<type>();\n }\n};\n\ntemplate<typename T, typename LambdaExpressionT>\nstruct has_member {\n using lambda_prototype = LambdaExpressionT;\n\n //SFINAE\n template<class ValueT, class = void>\n struct is_void_t_deducable : std::false_type {};\n\n template<class ValueT>\n struct is_void_t_deducable<ValueT,\n std::void_t<decltype(std::declval<lambda_prototype>()(std::declval<ValueT>()))>> : std::true_type {};\n\n static constexpr bool value = is_void_t_deducable<T>::value;\n};\n\nstruct SimpleClass\n{\n int field;\n void method() {}\n};\n\nint main(void)\n{ \n const auto helpful_lambda = LAMBDA_FOR_MEMBER_NAME(field);\n using member_field = decltype(helpful_lambda);\n std::cout << has_member<SimpleClass, member_field>::value;\n\n const auto lambda = LAMBDA_FOR_MEMBER_NAME(method);\n using member_method = decltype(lambda);\n std::cout << has_member<SimpleClass, member_method>::value;\n \n}\n" }, { "answer_id": 67942658, "author": "Jean-Michaël Celerier", "author_id": 1495627, "author_profile": "https://Stackoverflow.com/users/1495627", "pm_score": 3, "selected": false, "text": "template<class T>\nstd::string optionalToString(T* obj)\n{\n if constexpr (requires { obj->toString(); })\n return obj->toString();\n else\n return \"toString not defined\";\n}\n" }, { "answer_id": 69604306, "author": "Elliott", "author_id": 8658157, "author_profile": "https://Stackoverflow.com/users/8658157", "pm_score": 0, "selected": false, "text": "int foo ();\n declval template <auto v>\nstruct tag_v\n{\n constexpr static auto value = v;\n};\n\ntemplate <class, class = int>\nstruct has_foo_method : tag_v<false> {};\n\ntemplate <class T>\nstruct has_foo_method <T, decltype(T().foo())>\n : tag_v<true> {};\n int foo decltype decltype(T().foo(), int())\n int" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21482/" ]
257,324
<p>I need to add 30 minutes to values in a Oracle date column. I do this in my SELECT statement by specifying </p> <p><code>to_char(date_and_time + (.000694 * 31)</code></p> <p>which works fine most of the time. But not when the time is on the AM/PM border. For example, adding 30 minutes to <code>12:30</code> [which is PM] returns <code>1:00</code> which is AM. The answer I expect is <code>13:00</code>. What's the correct way to do this?</p>
[ { "answer_id": 257337, "author": "Camilo Díaz Repka", "author_id": 861, "author_profile": "https://Stackoverflow.com/users/861", "pm_score": 1, "selected": false, "text": "SELECT to_char((to_date('12:40 PM', 'HH:MI AM') + (1/24/60) * 30), 'HH24:MI') as time\n FROM dual\n\nTIME\n---------\n13:10\n 'AM' 'PM'" }, { "answer_id": 257341, "author": "Sidnei Andersson", "author_id": 31619, "author_profile": "https://Stackoverflow.com/users/31619", "pm_score": 2, "selected": false, "text": "select field + 0.5/24 from table;\n" }, { "answer_id": 257399, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 7, "selected": false, "text": "Oracle 9i SQL> ed\nWrote file afiedt.buf\nSELECT sysdate, sysdate + interval '30' minute FROM dual\nSQL> /\n\nSYSDATE SYSDATE+INTERVAL'30'\n-------------------- --------------------\n02-NOV-2008 16:21:40 02-NOV-2008 16:51:40\n" }, { "answer_id": 258555, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 6, "selected": true, "text": "to_char(date_and_time + (.000694 * 31))\n to_char(date_and_time + (.000694 * 31), 'DD-MON-YYYY HH24:MI')\n" }, { "answer_id": 2311033, "author": "crazy", "author_id": 278699, "author_profile": "https://Stackoverflow.com/users/278699", "pm_score": 4, "selected": false, "text": "SQL> select sysdate, sysdate+1/24, sysdate +1/1440, sysdate + 1/86400 from dual;\n\nSYSDATE SYSDATE+1/24 SYSDATE+1/1440 SYSDATE+1/86400\n-------------------- -------------------- -------------------- --------------------\n03-Jul-2002 08:32:12 03-Jul-2002 09:32:12 03-Jul-2002 08:33:12 03-Jul-2002 08:32:13\n" }, { "answer_id": 4329358, "author": "saidevakumar", "author_id": 336478, "author_profile": "https://Stackoverflow.com/users/336478", "pm_score": 2, "selected": false, "text": "SELECT date_and_time + INTERVAL '20:00' MINUTE TO SECOND FROM dual;\n" }, { "answer_id": 8814626, "author": "Chirag Mehta", "author_id": 1142418, "author_profile": "https://Stackoverflow.com/users/1142418", "pm_score": -1, "selected": false, "text": "SELECT to_char(sysdate + (1/24/60) * 30, 'dd/mm/yy HH24:MI am') from dual;\n" }, { "answer_id": 17039496, "author": "jtomaszk", "author_id": 2393509, "author_profile": "https://Stackoverflow.com/users/2393509", "pm_score": 4, "selected": false, "text": "UPDATE \"TABLE\" \nSET DATE_FIELD = CURRENT_TIMESTAMP + interval '48' minute \nWHERE (...)\n interval" }, { "answer_id": 33580076, "author": "Sam", "author_id": 5201238, "author_profile": "https://Stackoverflow.com/users/5201238", "pm_score": 0, "selected": false, "text": " select to_char(<columnName> + 5 / 24 + 30 / (24 * 60),\n 'DD/MM/RRRR hh:mi AM') AS <logicalName> from <tableName>\n" }, { "answer_id": 40459784, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 4, "selected": false, "text": "interval interval '30' minute interval '5' second 30 / (24 * 60) 5 / (24 * 60 * 69) some_date + interval '2' hour some_date + interval '30' minute some_date + interval '5' second some_date + interval '2' day some_date + interval '2 3:06' day to minute" }, { "answer_id": 53806710, "author": "Bilal", "author_id": 2016070, "author_profile": "https://Stackoverflow.com/users/2016070", "pm_score": 2, "selected": false, "text": "select to_char(sysdate + NUMTODSINTERVAL(10,'MINUTE'),'DD/MM/YYYY HH24:MI:SS') from dual;\n" }, { "answer_id": 63854245, "author": "Julius Simon", "author_id": 5993387, "author_profile": "https://Stackoverflow.com/users/5993387", "pm_score": 0, "selected": false, "text": "select systimestamp START_TIME, systimestamp + NUMTODSINTERVAL(30, 'minute') end_time from dual\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3401/" ]
257,329
<p>I'm working on writing a kernel, and I have a few friends working with me on the project. We've been using DJGPP to compile the project for a while, but we're having some cross-platform compatibility issues with compiling this way that have left my main Partnet on the project unable to compile on Windows XP. (DJGPP's GCC is having issues with argument lists longer than 127 on windows XP, but not having issues with the same argument lists on Vista. So, for once, Vista works better than XP at something. o.O)</p> <p>Anywho, rather than try to work out some dirty hack to make the darn thing compile with DJGPP, we've decided that we want to ditch DJGPP entirely and work with a different version of GCC for windows. The trouble is, MinGW (to my knowledge) doesn't let us use NASM syntax for the assembly portions of the code, and it would be a bit of a pain to convert it all to AT&amp;T syntax at this point. Possible of course, since its fairly early in the project, but a pain.</p> <p>So now you know the issue. My question is this: What GCC compiler distro for Windows will allow us to most easily port this project to itself? Ideally, we're looking for something that can do NASM assembler syntax, not have any reliance on externel dlls (this is a kernel here, it won't have access to them) and will work consistantly on multiple versions on Windows. What are your recommendations about the best way to go about doing this, and what version of GCC for windows do you recommend?</p> <p>Note that if we are going to need to convert the project to AT&amp;T syntax that's OK, I'd just like to not do that. We're actually using NASM to assemble the assembly bits of it, and that produces a valid .o file, but MinGW isn't able to link that in for some reason. I think the inline assembly bits (maybe 5 lines) are already AT&amp;T syntax, as required by GCC.</p> <p>Thanks!</p>
[ { "answer_id": 7827309, "author": "Unsigned", "author_id": 629493, "author_profile": "https://Stackoverflow.com/users/629493", "pm_score": 1, "selected": false, "text": "elf32" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
257,331
<p>What is the clearest explanation of what computer scientists mean by "the naive implementation"? I need a good clear example which will illustrate — ideally, even to non-technical people — that the naive implementation may <em>technically</em> be a functioning solution to the problem, but <em>practically</em> be utterly unusable.</p>
[ { "answer_id": 257340, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": -1, "selected": false, "text": "foreach(object o in set1)\n{\n foreach(object p in set1)\n {\n // codez\n }\n}\n public static SomeObject Instance\n{\n get\n {\n if(obj == null)\n {\n obj = new SomeObject();\n }\n\n return obj;\n }\n}\n" }, { "answer_id": 257446, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": " def naive_inverse(x):\n return 1/x\n" }, { "answer_id": 259083, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "base ** exp base * base * ... * base exp double pow(double base, int exp) {\n double result = 1;\n for (int i = 0; i < exp; i++)\n result *= base;\n return result;\n}\n base ** exp == 1 / base ** (-exp) == (1 / base) ** (-exp) double pow(double base, int exp) {\n double result = 1;\n if (exp < 0) {\n base = 1 / base;\n exp = -exp;\n }\n for (int i = 0; i < exp; i++)\n result *= base;\n return result;\n}\n base ** exp exp double pow(double base, int exp) {\n double result = 1;\n if (exp < 0) {\n base = 1 / base;\n exp = -exp;\n }\n while (exp) {\n if (exp % 2) {\n result *= base;\n exp--;\n }\n else {\n base *= base;\n exp /= 2;\n }\n }\n return result * base;\n}\n base ** exp == (base * base) ** (exp / 2) exp log2(exp)" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33904/" ]
257,339
<p>I've never done it myself, and I've never subscribed to a feed, but it seems that I'm going to have to create one, so I'm wondering. The only way that seems apparent to me is that when the system is updated with a new item (blog post, news item, whatever), a new element should be written to the rss file. Or alternatively have a script that checks for updates to the system a few times a day and writes to the rss file is there is. There's probably a better way of doing it though.</p> <p>And also, should old elements be removed as new ones are added? </p> <p><strong>Edit</strong>: I should have mentioned, I'm working in PHP, specifically using CodeIgniter, with a mySQL database.</p>
[ { "answer_id": 257366, "author": "Nick", "author_id": 14072, "author_profile": "https://Stackoverflow.com/users/14072", "pm_score": 0, "selected": false, "text": "<%@ Page Language=\"C#\" EnableViewState=\"false\" %>\n<%@ OutputCache Duration=\"300\" VaryByParam=\"none\" %>\n\n<%@ Import Namespace=\"System\" %>\n<%@ Import Namespace=\"System.Configuration\" %>\n<%@ Import Namespace=\"System.Web\" %>\n<%@ Import Namespace=\"System.Web.Security\" %>\n<%@ Import Namespace=\"System.Data\" %>\n<%@ Import Namespace=\"System.Xml\" %>\n<%@ Import Namespace=\"System.Text\" %>\n<%@ Import Namespace=\"System.DirectoryServices\" %>\n\n<script runat=\"server\">\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n System.Collections.Specialized.StringCollection HideSites = new StringCollection();\n System.Collections.Generic.List<string> Sites = new System.Collections.Generic.List<string>();\n\n HideSites.Add(@\"IISHelp\");\n HideSites.Add(@\"MSMQ\");\n HideSites.Add(@\"Printers\");\n\n DirectoryEntry entry = new DirectoryEntry(\"IIS://LocalHost/W3SVC/1/ROOT\");\n foreach (DirectoryEntry site in entry.Children)\n {\n if (site.SchemaClassName == \"IIsWebVirtualDir\" && !HideSites.Contains(site.Name))\n {\n Sites.Add(site.Name);\n }\n }\n\n Sites.Sort();\n\n Response.Clear();\n Response.ContentType = \"text/xml\";\n XmlTextWriter RSS = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);\n RSS.WriteStartDocument();\n RSS.WriteStartElement(\"rss\");\n RSS.WriteAttributeString(\"version\",\"2.0\");\n RSS.WriteStartElement(\"channel\");\n RSS.WriteElementString(\"title\", \"Localhost Websites\");\n RSS.WriteElementString(\"link\",\"http://localhost/sitelist.aspx\");\n RSS.WriteElementString(\"description\",\"localhost websites\");\n\n foreach (string s in Sites)\n {\n RSS.WriteStartElement(\"item\");\n RSS.WriteElementString(\"title\", s);\n RSS.WriteElementString(\"link\", \"http://localhost/\" + s);\n RSS.WriteEndElement();\n }\n\n RSS.WriteEndElement();\n RSS.WriteEndElement();\n RSS.WriteEndDocument();\n RSS.Flush();\n RSS.Close();\n Response.End();\n}\n\n</script>\n" }, { "answer_id": 257987, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 3, "selected": false, "text": "<?php define ('CONFIG_SYSTEM_URL','http://www.domain.tld/');\n\nrequire_once('feedcreator/feedcreator.class.php');\n\n$feedformat='RSS2.0';\n\nheader('Content-type: application/xml');\n\n$rss = new UniversalFeedCreator();\n$rss->useCached();\n$rss->title = \"Item List\";\n$rss->cssStyleSheet='';\n$rss->description = 'this feed';\n$rss->link = CONFIG_SYSTEM_URL;\n$rss->syndicationURL = CONFIG_SYSTEM_URL.'feed.php';\n\n\n$articles=new itemList(); // list of stuff\nforeach ($articles as $i) { \n $item = new FeedItem();\n $item->title = sprintf('%s',$i->title);\n $item->link = CONFIG_SYSTEM_URL.'item.php?id='.$i->dbId;\n $item->description = $i->Subject; \n $item->date = $i->ModifyDate; \n $item->source = CONFIG_SYSTEM_URL; \n $item->author = $i->User;\n $rss->addItem($item);\n}\n\nprint $rss->createFeed($feedformat);\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12765/" ]
257,343
<p>If I have a range of say <code>000080-0007FF</code> and I want to see if a char containing hex is within that range, how can I do it?</p> <p>Example</p> <pre><code>char t = 0xd790; if (t is within range of 000080-0007FF) // true </code></pre>
[ { "answer_id": 257346, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "wchar_t t = 0xd790;\n\nif (t >= 0x80 && t <= 0x7ff) ...\n wchar_t char" }, { "answer_id": 257372, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 2, "selected": false, "text": "unsigned short t = 0xd790;\n\nif (t >= 0x80 && t <= 0x7ff) ...\n" }, { "answer_id": 257386, "author": "dicroce", "author_id": 3886, "author_profile": "https://Stackoverflow.com/users/3886", "pm_score": 0, "selected": false, "text": "if( (t >= 128) && (t <= 2047) )\n{\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33481/" ]
257,350
<p>I need to create a form with, half linear view (textboxes and dropdownlists in separate line) and the other half, non linear view i.e. the textboxes will appear next to each other, like first name and last name will be next to each other. </p> <p>I am aware how to acomplish the linear view with CSS. I am using</p> <pre><code>fieldset { clear: both; font-size: 100%; border-color: #000000; border-width: 1px 0 0 0; border-style: solid none none none; padding: 10px; margin: 0 0 0 0; } label { float: left; width: 10em; text-align:right; } </code></pre> <p>How can I get the non-linear view?</p>
[ { "answer_id": 257995, "author": "Cyril Gupta", "author_id": 33052, "author_profile": "https://Stackoverflow.com/users/33052", "pm_score": 0, "selected": false, "text": "display: inline display: block float: left" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
257,353
<p>Is there a native c++ variable type that's "bigger" than a double?<br> float is 7<br> double is 15 (of course depending on the compiler)<br> Is there anything bigger that's native, or even non-native?</p>
[ { "answer_id": 257359, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "long double double double long double" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31325/" ]
257,391
<p>I have a const char arr[] parameter that I am trying to iterate over,</p> <pre><code>char *ptr; for (ptr= arr; *ptr!= '\0'; ptr++) /* some code*/ </code></pre> <p>I get an error: assignment discards qualifiers from pointer target type</p> <p>Are const char [] handled differently than non-const?</p>
[ { "answer_id": 257394, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 5, "selected": true, "text": "const char* ptr;\n" }, { "answer_id": 257420, "author": "Drew Hall", "author_id": 23934, "author_profile": "https://Stackoverflow.com/users/23934", "pm_score": 3, "selected": false, "text": "const char* ptr;\n char* ptr; // Both pointer & pointed-to value are non-const\nconst char* ptr; // Pointed-to value is const, pointer is non-const \nchar* const ptr; // Pointed-to value is non-const, pointer is const\nconst char* const ptr; // Both pointer & pointed-to value are const.\n const char* const ptr;\n" }, { "answer_id": 21558668, "author": "Paul DesRivieres", "author_id": 3271839, "author_profile": "https://Stackoverflow.com/users/3271839", "pm_score": 0, "selected": false, "text": "++ptr ptr++ ptr++ temp = *ptr;\n++ptr;\nreturn temp;`\n ++ptr ++ptr;\nreturn *ptr;\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
257,396
<p>I'm having some trouble understanding how command parameter binding works.</p> <p>When I create an instance of the widget class before the call to InitializeComponent it seems to work fine. Modifications to the parameter(Widget) in the ExecuteCommand function will be "applied" to _widget. This is the behavior I expected. </p> <p>If the instance of _widget is created after InitializeComponent, I get null reference exceptions for e.Parameter in the ExecuteCommand function.</p> <p>Why is this? How do I make this work with MVP pattern, where the bound object may get created after the view is created?</p> <pre><code>public partial class WidgetView : Window { RoutedCommand _doSomethingCommand = new RoutedCommand(); Widget _widget; public WidgetView() { _widget = new Widget(); InitializeComponent(); this.CommandBindings.Add(new CommandBinding(DoSomethingCommand, ExecuteCommand, CanExecuteCommand)); } public Widget TestWidget { get { return _widget; } set { _widget = value; } } public RoutedCommand DoSomethingCommand { get { return _doSomethingCommand; } } private static void CanExecuteCommand(object sender, CanExecuteRoutedEventArgs e) { if (e.Parameter == null) e.CanExecute = true; else { e.CanExecute = ((Widget)e.Parameter).Count &lt; 2; } } private static void ExecuteCommand(object sender, ExecutedRoutedEventArgs e) { ((Widget)e.Parameter).DoSomething(); } } &lt;Window x:Class="CommandParameterTest.WidgetView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WidgetView" Height="300" Width="300" DataContext="{Binding RelativeSource={RelativeSource Self}}"&gt; &lt;StackPanel&gt; &lt;Button Name="_Button" Command="{Binding DoSomethingCommand}" CommandParameter="{Binding TestWidget}"&gt;Do Something&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/Window&gt; public class Widget { public int Count = 0; public void DoSomething() { Count++; } } </code></pre>
[ { "answer_id": 257508, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 2, "selected": false, "text": "public static readonly DependencyProperty TestWidgetProperty =\n DependencyProperty.Register(\"TestWidget\", typeof(Widget), typeof(Window1), new UIPropertyMetadata(null));\npublic Widget TestWidget\n{\n get { return (Widget) GetValue(TestWidgetProperty); }\n set { SetValue(TestWidgetProperty, value); }\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22522/" ]
257,398
<p>Is there a UI library to create a message box or input box in python?</p>
[ { "answer_id": 8678916, "author": "akoc kanor", "author_id": 1122830, "author_profile": "https://Stackoverflow.com/users/1122830", "pm_score": 1, "selected": false, "text": "import *\nimport os\n\n class Dialog(Toplevel):\n\n def __init__(self, parent, title = None):\n\n Toplevel.__init__(self, parent)\n self.transient(parent)\n\n if title:\n self.title(title)\n\n self.parent = parent\n\n self.result = None\n\n body = Frame(self)\n self.initial_focus = self.body(body)\n body.pack(padx=5, pady=5)\n\n self.buttonbox()\n\n self.grab_set()\n\n if not self.initial_focus:\n self.initial_focus = self\n\n self.protocol(\"WM_DELETE_WINDOW\", self.cancel)\n\n self.geometry(\"+%d+%d\" % (parent.winfo_rootx()+50,\n parent.winfo_rooty()+50))\n\n self.initial_focus.focus_set()\n\n self.wait_window(self)\n\n #\n # construction hooks\n\n def body(self, master):\n # create dialog body. return widget that should have\n # initial focus. this method should be overridden\n\n pass\n\n def buttonbox(self):\n # add standard button box. override if you don't want the\n # standard buttons\n\n box = Frame(self)\n\n w = Button(box, text=\"OK\", width=10, command=self.ok, default=ACTIVE)\n w.pack(side=LEFT, padx=5, pady=5)\n w = Button(box, text=\"Cancel\", width=10, command=self.cancel)\n w.pack(side=LEFT, padx=5, pady=5)\n\n self.bind(\"<Return>\", self.ok)\n self.bind(\"<Escape>\", self.cancel)\n\n box.pack()\n\n #\n # standard button semantics\n\n def ok(self, event=None):\n\n if not self.validate():\n self.initial_focus.focus_set() # put focus back\n return\n\n self.withdraw()\n self.update_idletasks()\n\n self.apply()\n\n self.cancel()\n\n def cancel(self, event=None):\n\n # put focus back to the parent window\n self.parent.focus_set()\n self.destroy()\n\n #\n # command hooks\n\n def validate(self):\n\n return 1 # override\n\n def apply(self):\n\n pass # override\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
257,400
<p>I am trying to load <code>UIImage</code> object from <code>NSData</code>, and the sample code was to <code>NSImage</code>, I guess they should be the same. But just now loading the image, I am wondering what's the best to troubleshoot the <code>UIImage</code> loading <code>NSData</code> issue.</p>
[ { "answer_id": 257451, "author": "Noah Witherspoon", "author_id": 30618, "author_profile": "https://Stackoverflow.com/users/30618", "pm_score": 6, "selected": true, "text": "initWithData:" }, { "answer_id": 258122, "author": "leonho", "author_id": 30883, "author_profile": "https://Stackoverflow.com/users/30883", "pm_score": 2, "selected": false, "text": "NSData NSData NSLog" }, { "answer_id": 5262262, "author": "b123400", "author_id": 343065, "author_profile": "https://Stackoverflow.com/users/343065", "pm_score": 7, "selected": false, "text": "UIImageJPEGRepresentation() UIImagePNGRepresentation NSData UIImage NSData *imageData = UIImagePNGRepresentation(image);\nUIImage *image=[UIImage imageWithData:imageData];\n" }, { "answer_id": 7011337, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "UIImage *img = [UIImage imageNamed:@\"image.png\"];\nNSData *data1 = UIImagePNGRepresentation(img);\n" }, { "answer_id": 46073188, "author": "Krunal", "author_id": 5638630, "author_profile": "https://Stackoverflow.com/users/5638630", "pm_score": -1, "selected": false, "text": "if let img = UIImage(named: \"Hello.png\") {\n if let data:Data = UIImagePNGRepresentation(img) {\n // Handle operations with data here... \n }\n}\n if let img = UIImage(named: \"Hello.png\") {\n if let data:Data = UIImagePNGRepresentation(img) {\n handleOperationWithData(data: data) \n } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {\n handleOperationWithData(data: data) \n }\n}\n\n*******\nfunc handleOperationWithData(data: Data) {\n // Handle operations with data here...\n if let image = UIImage(data: data) {\n // Use image...\n }\n}\n extension UIImage {\n\n var pngRepresentationData: Data? {\n return UIImagePNGRepresentation(img)\n }\n\n var jpegRepresentationData: Data? {\n return UIImageJPEGRepresentation(self, 1.0)\n }\n}\n\n*******\nif let img = UIImage(named: \"Hello.png\") {\n if let data = img.pngRepresentationData {\n handleOperationWithData(data: data) \n } else if let data = jpegRepresentationData {\n handleOperationWithData(data: data) \n }\n}\n\n*******\nfunc handleOperationWithData(data: Data) {\n // Handle operations with data here...\n if let image = UIImage(data: data) {\n // Use image...\n }\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32096/" ]
257,409
<p>I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. All the images are part of the HTML page.</p>
[ { "answer_id": 258511, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 7, "selected": true, "text": "\"\"\"\ndumpimages.py\n Downloads all the images on the supplied URL, and saves them to the\n specified output file (\"/test/\" by default)\n\nUsage:\n python dumpimages.py http://example.com/ [output]\n\"\"\"\nfrom bs4 import BeautifulSoup as bs\nfrom urllib.request import (\n urlopen, urlparse, urlunparse, urlretrieve)\nimport os\nimport sys\n\ndef main(url, out_folder=\"/test/\"):\n \"\"\"Downloads all the images at 'url' to /test/\"\"\"\n soup = bs(urlopen(url))\n parsed = list(urlparse(url))\n\n for image in soup.findAll(\"img\"):\n print(\"Image: %(src)s\" % image)\n filename = image[\"src\"].split(\"/\")[-1]\n parsed[2] = image[\"src\"]\n outpath = os.path.join(out_folder, filename)\n if image[\"src\"].lower().startswith(\"http\"):\n urlretrieve(image[\"src\"], outpath)\n else:\n urlretrieve(urlunparse(parsed), outpath)\n\ndef _usage():\n print(\"usage: python dumpimages.py http://example.com [outpath]\")\n\nif __name__ == \"__main__\":\n url = sys.argv[-1]\n out_folder = \"/test/\"\n if not url.lower().startswith(\"http\"):\n out_folder = sys.argv[-1]\n url = sys.argv[-2]\n if not url.lower().startswith(\"http\"):\n _usage()\n sys.exit(-1)\n main(url, out_folder)\n" }, { "answer_id": 2448326, "author": "Dingo", "author_id": 291667, "author_profile": "https://Stackoverflow.com/users/291667", "pm_score": 3, "selected": false, "text": "def download_photo(self, img_url, filename):\n file_path = \"%s%s\" % (DOWNLOADED_IMAGE_PATH, filename)\n downloaded_image = file(file_path, \"wb\")\n\n image_on_web = urllib.urlopen(img_url)\n while True:\n buf = image_on_web.read(65536)\n if len(buf) == 0:\n break\n downloaded_image.write(buf)\n downloaded_image.close()\n image_on_web.close()\n\n return file_path\n" }, { "answer_id": 4200547, "author": "Catherine Devlin", "author_id": 86209, "author_profile": "https://Stackoverflow.com/users/86209", "pm_score": 4, "selected": false, "text": "for image in soup.findAll(\"img\"):\n print \"Image: %(src)s\" % image\n image_url = urlparse.urljoin(url, image['src'])\n filename = image[\"src\"].split(\"/\")[-1]\n outpath = os.path.join(out_folder, filename)\n urlretrieve(image_url, outpath)\n" }, { "answer_id": 24837891, "author": "Lerner Zhang", "author_id": 3552975, "author_profile": "https://Stackoverflow.com/users/3552975", "pm_score": 1, "selected": false, "text": "r_img = requests.get(img_url, auth=(username, password)) \nf = open('000000.jpg','wb') \nf.write(r_img.content) \nf.close()\n" }, { "answer_id": 71616051, "author": "imbr", "author_id": 1207193, "author_profile": "https://Stackoverflow.com/users/1207193", "pm_score": 1, "selected": false, "text": "img import os, sys\nimport requests\nfrom urllib import parse\nfrom bs4 import BeautifulSoup\nimport re\n def savePageImages(url, imagespath='images'):\n def soupfindnSave(pagefolder, tag2find='img', inner='src'):\n if not os.path.exists(pagefolder): # create only once\n os.mkdir(pagefolder)\n for res in soup.findAll(tag2find): \n if res.has_attr(inner): # check inner tag (file object) MUST exists\n try:\n filename, ext = os.path.splitext(os.path.basename(res[inner])) # get name and extension\n filename = re.sub('\\W+', '', filename) + ext # clean special chars from name\n fileurl = parse.urljoin(url, res.get(inner))\n filepath = os.path.join(pagefolder, filename)\n if not os.path.isfile(filepath): # was not downloaded\n with open(filepath, 'wb') as file:\n filebin = session.get(fileurl)\n file.write(filebin.content)\n except Exception as exc:\n print(exc, file=sys.stderr) \n session = requests.Session()\n #... whatever other requests config you need here\n response = session.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n soupfindnSave(imagespath, 'img', 'src')\n google.com google_images savePageImages('https://www.google.com', 'google_images')\n" }, { "answer_id": 73352797, "author": "Hassan Zamir", "author_id": 14905611, "author_profile": "https://Stackoverflow.com/users/14905611", "pm_score": 0, "selected": false, "text": "import urllib.request as req\n\nwith req.urlopen(image_link) as d, open(image_location, \"wb\") as image_object:\n data = d.read()\n image_object.write(data)\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
257,418
<p>I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)</p> <p>Is it good for anything else? Do you use it?</p>
[ { "answer_id": 257421, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 7, "selected": false, "text": "do {\n // do something\n if (error) {\n break;\n }\n // do something else\n if (error) {\n break;\n }\n // etc..\n} while (0);\n" }, { "answer_id": 257422, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": -1, "selected": false, "text": "do while while for do {\n char c = read_input();\n\n process_input(c);\n} while (c != 'Q');\n" }, { "answer_id": 257424, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 7, "selected": false, "text": "#define FOO(n) foo(n);bar(n)\n void foobar(int n) {\n if (n)\n FOO(n);\n}\n void foobar(int n) {\n if (n)\n foo(n);bar(n);\n}\n bar(n) if do { } while(0) if" }, { "answer_id": 257425, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 10, "selected": true, "text": "#define if #define FOO(x) foo(x); bar(x)\n\nif (condition)\n FOO(x);\nelse // syntax error here\n ...;\n #define FOO(x) { foo(x); bar(x); }\n if if (condition)\n FOO(x)\nelse\n ...\n #define FOO(x) do { foo(x); bar(x); } while (0)\n if (condition)\n FOO(x);\nelse\n ....\n" }, { "answer_id": 4627814, "author": "ubuntu-fanboy", "author_id": 552429, "author_profile": "https://Stackoverflow.com/users/552429", "pm_score": 4, "selected": false, "text": "\n#include <stdio.h>\n\n#define log_to_string1(str, fmt, arg...) \\\n do { \\\n sprintf(str, \"%s: \" fmt, \"myprog\", ##arg); \\\n } while (0)\n\n#define log_to_string2(str, fmt, arg...) \\\n ({ \\\n sprintf(str, \"%s: \" fmt, \"myprog\", ##arg); \\\n })\n\nint main() {\n char buf[1000];\n int n = 0;\n\n log_to_string1(buf, \"%s\\n\", \"No assignment, OK\");\n\n n += log_to_string1(buf + n, \"%s\\n\", \"NOT OK: gcc: error: expected expression before 'do'\");\n\n n += log_to_string2(buf + n, \"%s\\n\", \"This fixes it\");\n n += log_to_string2(buf + n, \"%s\\n\", \"Assignment worked!\");\n printf(\"%s\", buf);\n return 0;\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31515/" ]
257,423
<p>I've been trying to trace down why I have 100% iowait on my box. If I do something like a mysql select query, system goes to 100% iowait (on more than one cpu on my server,) which kills my watchdogs and sometimes kills httpd itself. </p> <p>In vmstat I see that every 8 seconds or so, there's a 5MB disk write. And that causes at least one cpu (out of 4) to be blocking for one or two seconds. </p> <p>I have to say that there are a few million files in my ext3 (and I tried ext2, and I have no atime and no journaling enabled.) There is a hardware raid, mirroring two 300GB ides.</p> <p>I'm missing dtrace. Is there any way to find out what causes these writes? and how do I speed my filesystem up? </p> <p>Ideas are welcome!</p> <p>Thank you!</p>
[ { "answer_id": 257434, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "strace dtrace" }, { "answer_id": 257783, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 3, "selected": false, "text": "iotop" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31515/" ]
257,433
<p>I wonder if the UNIX domain socket connections with postgresql are faster then tcp connections from localhost in high concurrency rate and if it does, by how much?</p>
[ { "answer_id": 257490, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": false, "text": "read() write()" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20955/" ]
257,462
<p>So I have this c# application that needs to ping my web server thats running linux/php stack.<br> I am having problems with the c# way of base 64 encoding bytes.</p> <p>my c# code is like:</p> <pre><code>byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("the string"); String enc = Convert.ToBase64String(encbuff); </code></pre> <p>and php side:</p> <pre><code>$data = $_REQUEST['in']; $raw = base64_decode($data); </code></pre> <p>with larger strings 100+ chars it fails. I think this is due to c# adding '+'s in the encoding but not sure. any clues</p>
[ { "answer_id": 257470, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "byte[] bytes = new byte[1000];\nConsole.WriteLine(Convert.ToBase64String(bytes));\n $data enc" }, { "answer_id": 257473, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "+ base64_decode" }, { "answer_id": 257475, "author": "w-ll", "author_id": 146637, "author_profile": "https://Stackoverflow.com/users/146637", "pm_score": 0, "selected": false, "text": "this is a <B>long</b>string. and lets make this a3214 ad0-3214 0czcx 909340 zxci 0324#$@#$%%13244513123\n dGhpcyBpcyBhIDxCPmxvbmc8L2I+c3RyaW5nLiBhbmQgbGV0cyBtYWtlIHRoaXMgYTMyMTQgYWQwLTMyMTQgMGN6Y3ggOTA5MzQwIHp4Y2kgMDMyNCMkQCMkJSUxMzI0NDUxMzEyMw==\n" }, { "answer_id": 257486, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 5, "selected": true, "text": "byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(\"the string\");\nstring enc = Convert.ToBase64String(encbuff);\nstring urlenc = Server.UrlEncode(enc);\n $data = $_REQUEST['in'];\n$decdata = urldecode($data);\n$raw = base64_decode($decdata);\n" }, { "answer_id": 8060975, "author": "cliff", "author_id": 1037006, "author_profile": "https://Stackoverflow.com/users/1037006", "pm_score": 2, "selected": false, "text": "private string HTTPPost(string URL, Dictionary<string, string> FormData)\n{\n\n UTF8Encoding UTF8encoding = new UTF8Encoding();\n string postData = \"\";\n\n foreach (KeyValuePair<String, String> entry in FormData)\n {\n postData += entry.Key + \"=\" + entry.Value + \"&\";\n }\n\n postData = postData.Remove(postData.Length - 1);\n\n //urlencode replace (+) with (%2B) so it will not be changed to space ( )\n postData = postData.Replace(\"+\", \"%2B\");\n\n byte[] data = UTF8encoding.GetBytes(postData); \n\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);\n\n request.Method = \"POST\";\n request.ContentType = \"application/x-www-form-urlencoded\";\n request.ContentLength = data.Length;\n\n Stream strm = request.GetRequestStream();\n // Send the data.\n strm.Write(data, 0, data.Length);\n strm.Close();\n\n WebResponse rsp = null;\n // Send the data to the webserver\n rsp = request.GetResponse();\n\n StreamReader rspStream = new StreamReader(rsp.GetResponseStream());\n string response = rspStream.ReadToEnd();\n\n return response;\n\n}\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146637/" ]
257,505
<p>Within an unordered list:</p> <pre><code>&lt;li&gt;&lt;span&gt;&lt;/span&gt; The lazy dog.&lt;/li&gt; &lt;li&gt;&lt;span&gt;AND&lt;/span&gt; The lazy cat.&lt;/li&gt; &lt;li&gt;&lt;span&gt;OR&lt;/span&gt; The active goldfish.&lt;/li&gt; </code></pre> <p>Adding a class or style attribute is permitted but padding the text and adding or changing tags is not allowed.</p> <p>The page is rendering with Courier New.</p> <p>Goal is to have text after span lined up.</p> <pre><code> The lazy dog. AND The lazy cat. OR The active goldfish. </code></pre> <p>Justification of the "OR" is unimportant.</p> <p>The lazy animal text may be wrapped in an additional element but I'll have to double check.</p>
[ { "answer_id": 257524, "author": "Stephen Caldwell", "author_id": 33437, "author_profile": "https://Stackoverflow.com/users/33437", "pm_score": 10, "selected": true, "text": "ul {\n list-style-type: none;\n padding-left: 0px;\n}\n\nul li span {\n float: left;\n width: 40px;\n} <ul>\n <li><span></span> The lazy dog.</li>\n <li><span>AND</span> The lazy cat.</li>\n <li><span>OR</span> The active goldfish.</li>\n</ul>" }, { "answer_id": 257531, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 4, "selected": false, "text": "<style type=\"text/css\">\ndiv.f1 { float: left; width: 20px; }\ndiv.f2 { float: left; }\ndiv.f3 { clear: both; }\n</style>\n\n<div class=\"f1\"></div><div class=\"f2\">The Lazy dog</div><div class=\"f3\"></div>\n<div class=\"f1\">AND</div><div class=\"f2\">The Lazy cat</div><div class=\"f3\"></div>\n<div class=\"f1\">OR</div><div class=\"f2\">The active goldfish</div><div class=\"f3\"></div>\n <html><head>\n<style type=\"text/css\">\n span.f1 { display: block; float: left; clear: left; width: 60px; }\n li { list-style-type: none; }\n </style>\n\n</head><body>\n<ul>\n<li><span class=\"f1\">&nbsp;</span>The lazy dog.</li>\n<li><span class=\"f1\">AND</span> The lazy cat.</li>\n<li><span class=\"f1\">OR</span> The active goldfish.</li>\n</ul>\n</body>\n</html>\n" }, { "answer_id": 257534, "author": "luiscubal", "author_id": 32775, "author_profile": "https://Stackoverflow.com/users/32775", "pm_score": 0, "selected": false, "text": "<style>\nul{\n text-indent: 40px;\n}\n\nli{\n list-style-type: none;\n padding: 0;\n}\n\nspan{\n color: #ff0000;\n position: relative;\n left: -40px;\n}\n</style>\n\n\n<ul>\n<span></span><li>The lazy dog.</li>\n<span>AND</span><li>The lazy cat.</li>\n<span>OR</span><li>The active goldfish.</li>\n</ul>\n" }, { "answer_id": 257537, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 4, "selected": false, "text": "<span> display:block <style type=\"text/css\"> span { width: 50px; display: block; } </style>\n <li><span>&nbsp;</span>something</li>\n<li><span>AND</span>something else</li>\n" }, { "answer_id": 257564, "author": "codeinthehole", "author_id": 32640, "author_profile": "https://Stackoverflow.com/users/32640", "pm_score": 9, "selected": false, "text": "<style type=\"text/css\">\n\nspan {\n display: inline-block;\n width: 50px;\n}\n\n</style>\n" }, { "answer_id": 257592, "author": "eaolson", "author_id": 23669, "author_profile": "https://Stackoverflow.com/users/23669", "pm_score": -1, "selected": false, "text": "<li><pre> The lazy dog.</pre></li>\n<li><pre>AND The lazy cat.</pre></li>\n<li><pre>OR The active goldfish.</pre></li>\n" }, { "answer_id": 2645732, "author": "Arturro", "author_id": 317548, "author_profile": "https://Stackoverflow.com/users/317548", "pm_score": 2, "selected": false, "text": "<li><span></span><strong>The</strong> lazy dog.</li>\n<li><span>AND</span> <strong>The</strong> lazy cat.</li>\n<li><span>OR</span> <strong>The</strong> active goldfish.</li>\n li {position:relative;padding-left:80px;} // 80px or something else\nli span {position:absolute;top:0;left:0;}\nli strong {color:red;} // red or else\n li top:0;left:0; padding-left padding:0px 0px 0px 80px;" }, { "answer_id": 18806385, "author": "Augustus Francis", "author_id": 2151172, "author_profile": "https://Stackoverflow.com/users/2151172", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\">\n\nspan {\n position:absolute;\n width: 50px;\n}\n\n</style>\n" }, { "answer_id": 48848233, "author": "Rahmad Saleh", "author_id": 4747007, "author_profile": "https://Stackoverflow.com/users/4747007", "pm_score": 1, "selected": false, "text": "> <span class=\"input-group-addon\" style=\"padding-left:6%;\n> padding-right:6%; width:150px; overflow: auto;\">\n" }, { "answer_id": 55517589, "author": "Pepe Unodostres", "author_id": 11208299, "author_profile": "https://Stackoverflow.com/users/11208299", "pm_score": -1, "selected": false, "text": "ul {\n list-style-type: none;\n padding-left: 0px;\n}\n\nul li span { \n float: left;\n width: 40px;\n} <ul>\n <li><span></span> The lazy dog.</li>\n <li><span>AND</span> The lazy cat.</li>\n <li><span>OR</span> The active goldfish.</li>\n</ul>" }, { "answer_id": 61549391, "author": "schlebe", "author_id": 948359, "author_profile": "https://Stackoverflow.com/users/948359", "pm_score": 3, "selected": false, "text": "<span> <div> <span> display: inline-block;\n <span> &nbsp; body\n {\n font-family: Arial;\n font-size:20px;\n }\n\ndiv\n {\n width:200px;\n font-size:80px;\n background-color: lime;\n }\ndiv span\n {\n display:block;\n width:200px;\n background-color: lime;\n }\n\nul li span\n {\n display: inline-block;\n width: 80px;\n background-color: yellow;\n }\nspan.tab\n {\n display: inline-block;\n width: 80px;\n background-color: yellow;\n } &lt;DIV&gt;\n\n<div class='test'>ABCDEF</div>\n\n&lt;SPAN&gt;\n\n<div>\n <span class='test'>ABCDEF</span>\n</div\n\n<br>\n\n<ul>\n <li><span class='tab'>&nbsp;</span> The lazy dog.</li>\n <li><span class='tab'>AND</span> The lazy cat.</li>\n <li><span class='tab'>OR</span> The active goldfish.</li>\n</ul> tab ul li span" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293/" ]
257,507
<p>I understand how the implementation of dynamic binding works and also the difference between static and dynamic binding, I am just having trouble wrapping my brain around the definition of dynamic binding. Basically other than it is a run-time binding type.</p>
[ { "answer_id": 257565, "author": "kings90", "author_id": 33269, "author_profile": "https://Stackoverflow.com/users/33269", "pm_score": 1, "selected": false, "text": "class Animal\n{\nvoid talk();\n}\n\nclass Dog extends Animal\n{\npublic void talk() { System.out.println(\"woof\"); }\n}\n\nclass Cat extends Animal\n{\npublic void talk() { System.out.println(\"meow\"); }\n}\n\n....\nAnimal zoo[2];\nzoo[0] = new Dog();\nzoo[1] = new Cat();\n\nfor(Animal animalToggle: zoo)\n{\nanimalToggle.talk();\n}\n" }, { "answer_id": 257567, "author": "dsimcha", "author_id": 23903, "author_profile": "https://Stackoverflow.com/users/23903", "pm_score": 3, "selected": true, "text": "foo(bar) //Calls a funciton\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29299/" ]
257,514
<p>I need to find out the pixel position of one element in a list that's been displayed using a <code>ListView</code>. It seems like I should get one of the <strong>TextView's</strong> and then use <code>getTop()</code>, but I can't figure out how to get a child view of a <code>ListView</code>.</p> <p><strong>Update:</strong> The children of the <code>ViewGroup</code> do not correspond 1-to-1 with the items in the list, for a <code>ListView</code>. Instead, the <code>ViewGroup</code>'s children correspond to only those views that are visible right now. So <code>getChildAt()</code> operates on an index that's internal to the <code>ViewGroup</code> and doesn't necessarily have anything to do with the position in the list that the <code>ListView</code> uses.</p>
[ { "answer_id": 340691, "author": "jasonhudgins", "author_id": 24590, "author_profile": "https://Stackoverflow.com/users/24590", "pm_score": -1, "selected": false, "text": " View element = listView.getListAdapter().getView(position, null, null);\n" }, { "answer_id": 2679284, "author": "Joe", "author_id": 231078, "author_profile": "https://Stackoverflow.com/users/231078", "pm_score": 9, "selected": true, "text": "int wantedPosition = 10; // Whatever position you're looking for\nint firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0\nint wantedChild = wantedPosition - firstPosition;\n// Say, first visible position is 8, you want position 10, wantedChild will now be 2\n// So that means your view is child #2 in the ViewGroup:\nif (wantedChild < 0 || wantedChild >= listView.getChildCount()) {\n Log.w(TAG, \"Unable to get view for desired position, because it's not being displayed on screen.\");\n return;\n}\n// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.\nView wantedView = listView.getChildAt(wantedChild);\n" }, { "answer_id": 8692373, "author": "Kalimah", "author_id": 529024, "author_profile": "https://Stackoverflow.com/users/529024", "pm_score": 4, "selected": false, "text": " View rowView = listView.getChildAt(viewIndex);//The item number in the List View\n if(rowView != null)\n {\n // Your code here\n }\n" }, { "answer_id": 17345134, "author": "Wes", "author_id": 2528371, "author_profile": "https://Stackoverflow.com/users/2528371", "pm_score": 3, "selected": false, "text": "listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n @Override\n public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {\n View v;\n int count = parent.getChildCount();\n v = parent.getChildAt(position);\n parent.requestChildFocus(v, view);\n v.setBackground(res.getDrawable(R.drawable.transparent_button));\n for (int i = 0; i < count; i++) {\n if (i != position) {\n v = parent.getChildAt(i);\n v.setBackground(res.getDrawable(R.drawable.not_clicked));\n }\n }\n }\n});\n int position ListView listview ListView TextView ArrayAdapter" }, { "answer_id": 35079680, "author": "Milaaaad", "author_id": 4923925, "author_profile": "https://Stackoverflow.com/users/4923925", "pm_score": 2, "selected": false, "text": "int position = 0;\nlistview.setItemChecked(position, true);\nView wantedView = adapter.getView(position, null, listview);\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2652/" ]
257,519
<p>I'm completely new at C# and NUnit.</p> <p>In Boost.Test there is a family of <code>BOOST_*_THROW</code> macros. In Python's test module there is <code>TestCase.assertRaises</code> method.</p> <p>As far as I understand it, in C# with NUnit (2.4.8) the only method of doing exception test is to use <code>ExpectedExceptionAttribute</code>.</p> <p>Why should I prefer <code>ExpectedExceptionAttribute</code> over - let's say - Boost.Test's approach? What reasoning can stand behind this design decision? Why is that better in case of C# and NUnit?</p> <p>Finally, if I decide to use <code>ExpectedExceptionAttribute</code>, how can I do some additional tests after exception was raised and catched? Let's say that I want to test requirement saying that object has to be valid after some setter raised <code>System.IndexOutOfRangeException</code>. How would you fix following code to compile and work as expected?</p> <pre><code>[Test] public void TestSetterException() { Sth.SomeClass obj = new SomeClass(); // Following statement won't compile. Assert.Raises( "System.IndexOutOfRangeException", obj.SetValueAt( -1, "foo" ) ); Assert.IsTrue( obj.IsValid() ); } </code></pre> <hr> <p>Edit: Thanks for your answers. Today, I've found an <em>It's the Tests</em> <a href="http://nunit.com/blogs/?p=63" rel="nofollow noreferrer">blog entry</a> where all three methods described by you are mentioned (and one more minor variation). It's shame that I couldn't find it before :-(.</p>
[ { "answer_id": 257523, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": false, "text": "Assert.That( delegate { ... }, Throws.Exception<ArgumentException>())\n" }, { "answer_id": 257526, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 2, "selected": false, "text": "bool success = true;\ntry {\n obj.SetValueAt(-1, \"foo\");\n} catch () {\n success = false;\n}\n\nassert.IsFalse(success);\n\n...\n" }, { "answer_id": 257536, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "Assert.Throws<IndexOutOfRangeException>(delegate {\n int[] nums = new int[] { 0, 1, 2 };\n nums[3] = 3;\n});\n" }, { "answer_id": 257540, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "try\n{\n obj.SetValueAt(-1, \"foo\");\n Assert.Fail(\"Expected exception\");\n}\ncatch (IndexOutOfRangeException)\n{\n // Expected\n}\nAssert.IsTrue(obj.IsValid());\n" }, { "answer_id": 257590, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "Assert.Raises( \"System.IndexOutOfRangeException\",\n obj.SetValueAt( -1, \"foo\" ) );\n void Raises<T>(Action action) where T:Exception {\n try {\n action();\n throw new ExpectedException(typeof(T));\n catch (Exception ex) {\n if (ex.GetType() != typeof(T)) {\n throw;\n }\n }\n}\n Assert.Raises<System.IndexOutOfRangeException>(() => \n obj.SetValueAt(-1, \"foo\")\n;\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26141/" ]
257,550
<p>I have put together a script which is very much like the flickr photostream feature. Two thumbnails next to each other, and when you click the next or prev links the next (or previous) two images slide in. Cool!</p> <p>Currently when the page loads it loads the two images. The first time nxt / prv is used then the next two images or previous two are loaded via ajax, with the id of the first image being passed in the url and the HTML for the two new images returned and displayed via ajax.</p> <p>simple enough, but it got me to thinking, on a slow connection, or heavy server load then the two images, although relatively small thumbnails could still take a while to load, and the nice things with sliding panes is the fact that the hidden data slides in quickly and smoothly preferbly without a loading delay.</p> <p>So I was wondering from a performance and good practice point of view which option is best, this is what I can think of for now, open to suggestions.</p> <p>1, call each set of images via JSON (its supposed to be fast?) </p> <p>2,load all the possible images into a json file and pull in the details that way - although browser will still have to load image. Plus sometimes there might be 4 images, other times there could be upto 1000!</p> <p>3, Load 10 images via php into a Json or other file, and load all 10 images into the browser hiding the 8 which are not on show, and always showing the middle two. Problem here is that each time someone clicks, the file has to reload the first and last images, which still takes up time, although i suppose the middle images will have all been cached via the browser by now though. But still there is a loading time.</p> <p>4, Is it possible to have a json image with all the image details (regardless of numbers) and use no 3 above to load 10 of those images, is it possible to use ajax to only read 10 lines and keep a pointer of the last one it read, so the json file can be loaded fast, short refresh and images either side are cached via the browser!!</p> <p>Hope thats clear, any suggestions on how you would handle this?</p>
[ { "answer_id": 257594, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "var img = new Image();\nimg.src = \"http://example.com/new/image.jpg\";\n src" }, { "answer_id": 257601, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": " <?php \n $images = array( \"foo.jpg\",\"bar.jpg\" ); \n ?>\n <script type=\"text/javascript\">\n jQuery(function($){\n var images = ( <?php echo json_encode($images); ?> ); \n /* Creating A Hidden box to preload the images into */\n var imgbox = document.createElement(\"div\"); \n $(imgbox).css({display: 'none'});\n /* Possible Alternative trick */\n /* $(imgbox).css({height:1px; width: 1px; overflow: hidden;}); */\n $('body').append(imgbox);\n\n $.each( images , function( ind, item ) \n {\n #Injecting images into the bottom hidden div. \n var img = document.createElement(\"img\"); \n $(img).src(\"/some/prefix/\" + item ); \n $(imgbox).append(img);\n });\n }); \n </script>\n" }, { "answer_id": 1073187, "author": "brianegge", "author_id": 14139, "author_profile": "https://Stackoverflow.com/users/14139", "pm_score": 0, "selected": false, "text": "<script>\nvar urls = [\n \"a.png\",\n \"b.png\",\n \"c.png\",\n \"d.png\",\n \"e.png\",\n \"f.png\"\n];\n\nvar currentStep = 0;\nfunction loadResources()\n{\n if(currentStep<urls.length){\n var url = urls[currentStep];\n var req = GetXmlHttpObject();\n update('loading ' + url);\n req.open(\"GET\", url, true);\n req.onreadystatechange = getUpdateState(req, url);\n req.send(null);\n} else {\n window.location = 'done.htm';\n}\n}\n\nfunction getUpdateState(req, url) {\n return function() {\n var state = req.readyState;\n if (state != 4) { return; }\n req = null;\n setTimeout('loadResources()', 0);\n }\n}\n</script>\n\n<!-- This will queue up to four concurrent requests. Modern browsers will request up to eight images at time -->\n<body onload=\"javascript: loadResources(); loadResources(); loadResources(); loadResources();\">\n" } ]
2008/11/02
[ "https://Stackoverflow.com/questions/257550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]