qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
212,271
<p>A person uses their cell phone multiple times per day, and the length of their calls vary. I am tracking the length of the calls in a table:</p> <pre><code>Calls [callID, memberID, startTime, duration] </code></pre> <p>I need to a query to return the average call length for users <strong>per day</strong>. Per day means, if a user used the phone 3 times, first time for 5 minutes, second for 10 minutes and the last time for 7 minutes, the calculation is: <code>5 + 10 + 7 / 3 = ...</code></p> <p>Note:</p> <ol> <li><p>People don't use the phone everyday, so we have to get the latest day's average per person and use this to get the overall average call duration.</p></li> <li><p>we don't want to count anyone twice in the average, so only 1 row per user will go into calculating the average daily call duration.</p></li> </ol> <p>Some clarifications...</p> <p>I need a overall per day average, based on the per-user per-day average, using the users latest days numbers (since we are only counting a given user ONCE in the query), so it will mean we will be using different days avg. since people might not use the phone each day or on the same day even.</p>
[ { "answer_id": 212284, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "select average(duration) from calls group by date(startTime);\n" }, { "answer_id": 212285, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "SELECT\n memberId,\n CONVERT(VARCHAR, startTime, 102) Day,\n AVG(Duration) AvgDuration\nFROM\n Calls\nWHERE\n CONVERT(VARCHAR, startTime, 102) = \n (\n SELECT \n CONVERT(VARCHAR, MAX(startTime), 102) \n FROM \n Calls i WHERE i.memberId = Calls.memberId\n )\nGROUP BY\n memberId,\n CONVERT(VARCHAR, startTime, 102)\n LEFT(CONVERT(VARCHAR, startTime, 120), 10)" }, { "answer_id": 212500, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "SELECT AVG(rt.UserDuration) AS AveragePerDay\nFROM\n(\n SELECT\n c1.MemberId,\n AVG(c1.Duration) AS \"UserDuration\"\n FROM Calls c1\n WHERE CONVERT(VARCHAR, c1.StartTime, 102) =\n (SELECT CONVERT(VARCHAR, MAX(c2.StartTime), 102)\n FROM Calls c2\n WHERE c2.MemberId = c1.MemberId)\n GROUP By MemberId\n) AS rt\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,321
<p>Anyone know a simple way using Java calendar to subtract X days from a date?</p> <p>I have not been able to find any function which allows me to directly subtract X days from a date in Java. Can someone point me to the right direction?</p>
[ { "answer_id": 212334, "author": "Anson Smith", "author_id": 28685, "author_profile": "https://Stackoverflow.com/users/28685", "pm_score": 9, "selected": true, "text": "Calendar calendar = Calendar.getInstance(); // this would default to now\ncalendar.add(Calendar.DAY_OF_MONTH, -5).\n" }, { "answer_id": 212337, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "int x = -1;\nCalendar cal = ...;\ncal.add(Calendar.DATE, x);\n java.util.Calendar#add(int,int)" }, { "answer_id": 212353, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 5, "selected": false, "text": "add Calendar public static void addDays(Date d, int days)\n{\n d.setTime( d.getTime() + (long)days*1000*60*60*24 );\n}\n public static void addDays(Date d, int days)\n{\n Calendar c = Calendar.getInstance();\n c.setTime(d);\n c.add(Calendar.DATE, days);\n d.setTime( c.getTime().getTime() );\n}\n Date Date" }, { "answer_id": 212363, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 5, "selected": false, "text": "DateTime dt = new DateTime();\nDateTime fiveDaysEarlier = dt.minusDays(5);\n" }, { "answer_id": 1476346, "author": "user178973", "author_id": 178973, "author_profile": "https://Stackoverflow.com/users/178973", "pm_score": 0, "selected": false, "text": "Calendar c = Calendar.getInstance();\nc.setTime(date);\nc.add(Calendar.DATE, -days);\ndate.setTime(c.getTime().getTime());\n" }, { "answer_id": 7922011, "author": "Michael K", "author_id": 620054, "author_profile": "https://Stackoverflow.com/users/620054", "pm_score": 1, "selected": false, "text": "CalendarDate someDay = new CalendarDate(2011, 10, 27);\nCalendarDate someLaterDay = today.addDays(77);\n //print 4 previous days of the week and today\nString dayLabel = \"\";\nCalendarDate today = new CalendarDate(TimeZone.getDefault());\nCalendarDateFormat cdf = new CalendarDateFormat(\"EEE\");//day of the week like \"Mon\"\nCalendarDate currDay = today.addDays(-4);\nwhile(!currDay.isAfter(today)) {\n dayLabel = cdf.format(currDay);\n if (currDay.equals(today))\n dayLabel = \"Today\";//print \"Today\" instead of the weekday name\n System.out.println(dayLabel);\n currDay = currDay.addDays(1);//go to next day\n}\n" }, { "answer_id": 11934301, "author": "Risav Karna", "author_id": 1187246, "author_profile": "https://Stackoverflow.com/users/1187246", "pm_score": 3, "selected": false, "text": "addDays DateUtils addDays(Date date, int amount) Date" }, { "answer_id": 33530885, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 5, "selected": false, "text": "LocalDate.now().minusDays( 10 )\n LocalDate.now( ZoneId.of( \"America/Montreal\" ) ).minusDays( 10 )\n java.util.Date .Calendar LocalDate LocalDate LocalDate today = LocalDate.now( ZoneId.of( \"America/Montreal\" ) );\nLocalDate tenDaysAgo = today.minusDays( 10 );\n ZonedDateTime Instant ZonedDateTime Instant now = Instant.now(); // UTC.\nZoneId zoneId = ZoneId.of( \"America/Montreal\" );\nZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );\nZonedDateTime tenDaysAgo = zdt.minusDays( 10 );\n java.util.Date Calendar SimpleDateFormat java.sql.* Interval YearWeek YearQuarter" }, { "answer_id": 47881277, "author": "rab", "author_id": 2564329, "author_profile": "https://Stackoverflow.com/users/2564329", "pm_score": 2, "selected": false, "text": "Calendar calendar = Calendar.getInstance();\n // from current time\n long curTimeInMills = new Date().getTime();\n long timeInMills = curTimeInMills - 5 * (24*60*60*1000); // `enter code here`subtract like 5 days\n calendar.setTimeInMillis(timeInMills);\n System.out.println(calendar.getTime());\n\n // from specific time like (08 05 2015)\n calendar.set(Calendar.DAY_OF_MONTH, 8);\n calendar.set(Calendar.MONTH, (5-1));\n calendar.set(Calendar.YEAR, 2015);\n timeInMills = calendar.getTimeInMillis() - 5 * (24*60*60*1000);\n calendar.setTimeInMillis(timeInMills);\n System.out.println(calendar.getTime());\n" }, { "answer_id": 59249667, "author": "Yordan Boev", "author_id": 2715285, "author_profile": "https://Stackoverflow.com/users/2715285", "pm_score": 2, "selected": false, "text": "new Date(Instant.now().minus(5, ChronoUnit.DAYS).toEpochMilli());\n Date.from(Instant.now().minus(Duration.ofHours(1)).plus(Duration.ofMinutes(15)));\n minusNano()\nplusNano()\ngetNano()\n" }, { "answer_id": 69708511, "author": "shashi ranjan", "author_id": 8132714, "author_profile": "https://Stackoverflow.com/users/8132714", "pm_score": 2, "selected": false, "text": "GregorianCalendar cal = new GregorianCalendar();\n cal.set(Calendar.YEAR, 2021);\n cal.set(Calendar.MONTH, 0);\n cal.set(Calendar.DATE, 1);\n System.out.println(\"Original: \" + cal.getTime());\n cal.add(Calendar.DATE, -1);\n System.out.println(\"After adding DATE: \" + cal.getTime());\n Original: Fri Jan 01 15:08:33 CET 2021\nAfter adding DATE: Thu Dec 31 15:08:33 CET 2020\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
212,350
<p>The <code>JPA</code> (Java Persistence API) specification has 2 different ways to specify entity composite keys: <code>@IdClass</code> and <code>@EmbeddedId</code>. </p> <p>I'm using both annotations on my mapped entities, but it turns out to be a big mess to people who aren't very familiar with <code>JPA</code>. </p> <p>I want to adopt only one way to specify composite keys. Which one is really the best? Why?</p>
[ { "answer_id": 212371, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 8, "selected": true, "text": "@EmbeddedId @IdClass @EmbeddedId @Embeddable class EmployeeId { name, dataOfBirth }\n@Entity class Employee {\n @EmbeddedId EmployeeId employeeId;\n ...\n}\n @IdClass @EmbeddedId @IdClass @EmbeddedId IdClass" }, { "answer_id": 4672983, "author": "Bertie", "author_id": 500451, "author_profile": "https://Stackoverflow.com/users/500451", "pm_score": 3, "selected": false, "text": "@GeneratedValue @IdClass @GeneratedValue @EmbeddedId" }, { "answer_id": 18890592, "author": "Ondrej Bozek", "author_id": 668417, "author_profile": "https://Stackoverflow.com/users/668417", "pm_score": 4, "selected": false, "text": "@IdClass @EmbeddedId @Embeddedable @ManyToOne @ManyToOne @PrimaryKeyJoinColumn @Embeddedable @IdClass ...\n@Entity\n@IdClass(PhonePK.class)\npublic class Phone {\n \n @Id\n private String type;\n \n @ManyToOne\n @Id\n @JoinColumn(name=\"OWNER_ID\", referencedColumnName=\"EMP_ID\")\n private Employee owner;\n ...\n}\n ...\npublic class PhonePK {\n private String type;\n private long owner;\n \n public PhonePK() {}\n \n public PhonePK(String type, long owner) {\n this.type = type;\n this.owner = owner;\n }\n \n public boolean equals(Object object) {\n if (object instanceof PhonePK) {\n PhonePK pk = (PhonePK)object;\n return type.equals(pk.type) && owner == pk.owner;\n } else {\n return false;\n }\n }\n \n public int hashCode() {\n return type.hashCode() + owner;\n }\n}\n" }, { "answer_id": 25579661, "author": "bkuriach", "author_id": 3972704, "author_profile": "https://Stackoverflow.com/users/3972704", "pm_score": 3, "selected": false, "text": "@Id @EmbeddedId" }, { "answer_id": 42214032, "author": "Adelin", "author_id": 1170677, "author_profile": "https://Stackoverflow.com/users/1170677", "pm_score": 5, "selected": false, "text": "@Embeddable @Id @EmbeddedId @Id @IdClass @Id @Embeddable @Embeddable @Embeddable @EmbeddedId @Embeddable @IdClass @Id @IdClass @Id" }, { "answer_id": 49615687, "author": "Aleks Ben Maza", "author_id": 6626501, "author_profile": "https://Stackoverflow.com/users/6626501", "pm_score": 2, "selected": false, "text": "FROM Entity WHERE id IN :ids FROM Entity WHERE idPartA = :idPartA0 AND idPartB = :idPartB0 .... OR idPartA = :idPartAN AND idPartB = :idPartBN" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28921/" ]
212,358
<p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p> <p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html" rel="noreferrer">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p> <p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p> <p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p> <p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p> <p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
[ { "answer_id": 212413, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 6, "selected": false, "text": "def binary_search(a, x, lo=0, hi=None):\n if hi is None:\n hi = len(a)\n while lo < hi:\n mid = (lo+hi)//2\n midval = a[mid]\n if midval < x:\n lo = mid+1\n elif midval > x: \n hi = mid\n else:\n return mid\n return -1\n" }, { "answer_id": 212541, "author": "jrb", "author_id": 27437, "author_profile": "https://Stackoverflow.com/users/27437", "pm_score": 2, "selected": false, "text": "# Generate a list\nl = [n*n for n in range(1000)]\n\n# Convert to dict - doesn't matter what you map values to\nd = dict((x, 1) for x in l)\n\ncount = 0\nfor n in range(1000000):\n # Compare with \"if n in l\"\n if n in d:\n count += 1\n" }, { "answer_id": 212971, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 5, "selected": false, "text": "set() set()" }, { "answer_id": 213834, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 1, "selected": false, "text": ">>> a = 'foo'\n>>> b = [a]\n>>> c = [a]\n>>> b[0] is c[0]\nTrue\n" }, { "answer_id": 530397, "author": "Imran", "author_id": 58866, "author_profile": "https://Stackoverflow.com/users/58866", "pm_score": 4, "selected": false, "text": "def binary_search(a,x,lo=0,hi=-1):\n i = bisect(a,x,lo,hi)\n if i == 0:\n return -1\n elif a[i-1] == x:\n return i-1\n else:\n return -1\n" }, { "answer_id": 2233940, "author": "Dave Abrahams", "author_id": 125349, "author_profile": "https://Stackoverflow.com/users/125349", "pm_score": 9, "selected": true, "text": "bisect_left p x x p x x x from bisect import bisect_left\n\ndef binary_search(a, x, lo=0, hi=None):\n if hi is None: hi = len(a)\n pos = bisect_left(a, x, lo, hi) # find insertion position\n return pos if pos != hi and a[pos] == x else -1 # don't walk off the end\n" }, { "answer_id": 10555553, "author": "iraycd", "author_id": 1097972, "author_profile": "https://Stackoverflow.com/users/1097972", "pm_score": 0, "selected": false, "text": "'''\nOnly used if set your position as global\n'''\nposition #set global \n\ndef bst(array,taget): # just pass the array and target\n global position\n low = 0\n high = len(array)\n while low <= high:\n mid = (lo+hi)//2\n if a[mid] == target:\n position = mid\n return -1\n elif a[mid] < target: \n high = mid+1\n else:\n low = mid-1\n return -1\n" }, { "answer_id": 10578346, "author": "jdsantiagojr", "author_id": 817423, "author_profile": "https://Stackoverflow.com/users/817423", "pm_score": 2, "selected": false, "text": "def binary_search(a, key, imin=0, imax=None):\n if imax is None:\n # if max amount not set, get the total\n imax = len(a) - 1\n\n while imin <= imax:\n # calculate the midpoint\n mid = (imin + imax)//2\n midval = a[mid]\n\n # determine which subarray to search\n if midval < key:\n # change min index to search upper subarray\n imin = mid + 1\n elif midval > key:\n # change max index to search lower subarray\n imax = mid - 1\n else:\n # return index number \n return mid\n raise ValueError\n" }, { "answer_id": 18678361, "author": "Florent", "author_id": 1908102, "author_profile": "https://Stackoverflow.com/users/1908102", "pm_score": 2, "selected": false, "text": "def binary_search(L, x):\n i = bisect.bisect_left(L, x)\n if i == len(L) or L[i] != x:\n return -1\n return i\n" }, { "answer_id": 18681876, "author": "paulluap", "author_id": 2484194, "author_profile": "https://Stackoverflow.com/users/2484194", "pm_score": 3, "selected": false, "text": "bisect.bisect_left(a, x, lo=0, hi=len(a)) bisect.bisect_left 0 len(a) __getitem__ a import bisect\n\nclass sqrt_array(object):\n def __init__(self, digits):\n self.precision = float(10**(digits))\n def __getitem__(self, key):\n return (key/self.precision)**2.0\n\nsa = sqrt_array(4)\n\n# \"search\" in the range of 0 to 10 with a \"precision\" of 0.0001\nindex = bisect.bisect_left(sa, 7, 0, 10*10**4)\nprint 7**0.5\nprint index/(10**4.0)\n" }, { "answer_id": 20007672, "author": "stephenfin", "author_id": 613428, "author_profile": "https://Stackoverflow.com/users/613428", "pm_score": 2, "selected": false, "text": "bisect bisect >>> import bisect\n>>> names = ['bender', 'fry', 'leela', 'nibbler', 'zoidberg']\n>>> bisect.bisect_left(names, 'fry')\n1\n>>> keyword = 'fry'\n>>> x = bisect.bisect_left(names, keyword)\n>>> names[x] == keyword\nTrue\n>>> keyword = 'arnie'\n>>> x = bisect.bisect_left(names, keyword)\n>>> names[x] == keyword\nFalse\n ...\n>>> names = ['bender', 'fry', 'fry', 'fry', 'leela', 'nibbler', 'zoidberg']\n>>> keyword = 'fry'\n>>> leftIndex = bisect.bisect_left(names, keyword)\n>>> rightIndex = bisect.bisect_right(names, keyword)\n>>> names[leftIndex:rightIndex]\n['fry', 'fry', 'fry']\n >>> import bisect\n>>> class Tag(object): # a simple wrapper around strings\n... def __init__(self, tag):\n... self.tag = tag\n... def __lt__(self, other):\n... return self.tag < other.tag\n... def __gt__(self, other):\n... return self.tag > other.tag\n...\n>>> tags = [Tag('bender'), Tag('fry'), Tag('leela'), Tag('nibbler'), Tag('zoidbe\nrg')]\n>>> key = Tag('fry')\n>>> leftIndex = bisect.bisect_left(tags, key)\n>>> rightIndex = bisect.bisect_right(tags, key)\n>>> print([tag.tag for tag in tags[leftIndex:rightIndex]])\n['fry']\n" }, { "answer_id": 20827948, "author": "arainchi", "author_id": 1730644, "author_profile": "https://Stackoverflow.com/users/1730644", "pm_score": 3, "selected": false, "text": "def index(a, x):\n 'Locate the leftmost value exactly equal to x'\n i = bisect_left(a, x)\n if i != len(a) and a[i] == x:\n return i\n raise ValueError\n def index(a, x):\n 'Locate the leftmost value exactly equal to x'\n i = bisect_left(a, x)\n if i != len(a) and a[i] == x:\n return i\n return -1\n" }, { "answer_id": 27843077, "author": "AV94", "author_id": 3721259, "author_profile": "https://Stackoverflow.com/users/3721259", "pm_score": 1, "selected": false, "text": "s binary(s, 0, len(s) - 1, find) -1 def binary(s,p,q,find):\n if find==s[(p+q)/2]:\n return (p+q)/2\n elif p==q-1 or p==q:\n if find==s[q]:\n return q\n else:\n return -1\n elif find < s[(p+q)/2]:\n return binary(s,p,(p+q)/2,find)\n elif find > s[(p+q)/2]:\n return binary(s,(p+q)/2+1,q,find)\n" }, { "answer_id": 30385777, "author": "Mateusz Piotrowski", "author_id": 4694621, "author_profile": "https://Stackoverflow.com/users/4694621", "pm_score": 3, "selected": false, "text": "def binsearch(t, key, low = 0, high = len(t) - 1):\n # bisecting the range\n while low < high:\n mid = (low + high)//2\n if t[mid] < key:\n low = mid + 1\n else:\n high = mid\n # at this point 'low' should point at the place\n # where the value of 'key' is possibly stored.\n return low if t[low] == key else -1\n" }, { "answer_id": 42416906, "author": "sonus21", "author_id": 4255107, "author_profile": "https://Stackoverflow.com/users/4255107", "pm_score": 0, "selected": false, "text": "def binary_search(values, key, lo=0, hi=None, length=None, cmp=None):\n \"\"\"\n This is a binary search function which search for given key in values.\n This is very generic since values and key can be of different type.\n If they are of different type then caller must specify `cmp` function to\n perform a comparison between key and values' item.\n :param values: List of items in which key has to be search\n :param key: search key\n :param lo: start index to begin search\n :param hi: end index where search will be performed\n :param length: length of values\n :param cmp: a comparator function which can be used to compare key and values\n :return: -1 if key is not found else index\n \"\"\"\n assert type(values[0]) == type(key) or cmp, \"can't be compared\"\n assert not (hi and length), \"`hi`, `length` both can't be specified at the same time\"\n\n lo = lo\n if not lo:\n lo = 0\n if hi:\n hi = hi\n elif length:\n hi = length - 1\n else:\n hi = len(values) - 1\n\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n if not cmp:\n if values[mid] == key:\n return mid\n if values[mid] < key:\n lo = mid + 1\n else:\n hi = mid - 1\n else:\n val = cmp(values[mid], key)\n # 0 -> a == b\n # > 0 -> a > b\n # < 0 -> a < b\n if val == 0:\n return mid\n if val < 0:\n lo = mid + 1\n else:\n hi = mid - 1\n return -1\n" }, { "answer_id": 44033742, "author": "user3412550", "author_id": 3412550, "author_profile": "https://Stackoverflow.com/users/3412550", "pm_score": 0, "selected": false, "text": "def binary_search_length_of_a_list(single_method_list):\n index = 0\n first = 0\n last = 1\n\n while True:\n mid = ((first + last) // 2)\n if not single_method_list.get(index):\n break\n index = mid + 1\n first = index\n last = index + 1\n return mid\n" }, { "answer_id": 44761213, "author": "Jitesh Mohite", "author_id": 5106574, "author_profile": "https://Stackoverflow.com/users/5106574", "pm_score": 0, "selected": false, "text": "// List - values inside list\n// searchItem - Item to search\n// size - Size of list\n// upperBound - higher index of list\n// lowerBound - lower index of list\ndef binarySearch(list, searchItem, size, upperBound, lowerBound):\n print(list)\n print(upperBound)\n print(lowerBound)\n mid = ((upperBound + lowerBound)) // 2\n print(mid)\n if int(list[int(mid)]) == value:\n return \"value exist\"\n elif int(list[int(mid)]) < value:\n return searchItem(list, value, size, upperBound, mid + 1)\n elif int(list[int(mid)]) > value:\n return searchItem(list, value, size, mid - 1, lowerBound)\n list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nsearchItem = 1 \nprint(searchItem(list[0], item, len(list[0]) -1, len(list[0]) - 1, 0))\n" }, { "answer_id": 49907291, "author": "Bob", "author_id": 9666157, "author_profile": "https://Stackoverflow.com/users/9666157", "pm_score": 0, "selected": false, "text": "#Code\nfrom bisect import bisect_left\nnames=[\"Adam\",\"Donny\",\"Jalan\",\"Zach\",\"Zayed\"]\nsearch=\"\"\nlenNames = len(names)\nwhile search !=\"none\":\n search =input(\"Enter name to search for or 'none' to terminate program:\")\n if search == \"none\":\n break\n i = bisect_left(names,search)\n print(i) # show index returned by Python bisect_left\n if i < (lenNames) and names[i] == search:\n print(names[i],\"found\") #return True - if function\n else:\n print(search,\"not found\") #return False – if function\n##Exhaustive test cases:\n##Enter name to search for or 'none' to terminate program:Zayed\n##4\n##Zayed found\n##Enter name to search for or 'none' to terminate program:Zach\n##3\n##Zach found\n##Enter name to search for or 'none' to terminate program:Jalan\n##2\n##Jalan found\n##Enter name to search for or 'none' to terminate program:Donny\n##1\n##Donny found\n##Enter name to search for or 'none' to terminate program:Adam\n##0\n##Adam found\n##Enter name to search for or 'none' to terminate program:Abie\n##0\n##Abie not found\n##Enter name to search for or 'none' to terminate program:Carla\n##1\n##Carla not found\n##Enter name to search for or 'none' to terminate program:Ed\n##2\n##Ed not found\n##Enter name to search for or 'none' to terminate program:Roger\n##3\n##Roger not found\n##Enter name to search for or 'none' to terminate program:Zap\n##4\n##Zap not found\n##Enter name to search for or 'none' to terminate program:Zyss\n##5\n##Zyss not found\n" }, { "answer_id": 66909852, "author": "me6", "author_id": 6150460, "author_profile": "https://Stackoverflow.com/users/6150460", "pm_score": 0, "selected": false, "text": "def bisectLeft(a, t):\n lo = 0\n hi = len(a) - 1\n ans = None\n # print(\"------lower------\")\n # print(a, t)\n while lo <= hi:\n mid = (lo + hi) // 2\n # print(a[lo:mid], [a[mid]], a[mid:hi])\n if a[mid] < t:\n lo = mid + 1\n elif a[mid] > t:\n hi = mid - 1\n elif a[mid] == t:\n if mid == 0: return 0\n if a[mid-1] != t: return mid\n hi = mid - 1\n \n return ans\n\ndef bisectRight(a, t):\n lo = 0\n hi = len(a) - 1\n ans = None\n # print(\"------upper------\")\n # print(a, t)\n while lo <= hi:\n mid = (lo + hi) // 2\n # print(a[lo:mid], [a[mid]], a[mid:hi])\n if a[mid] == t:\n ans = mid\n if a[mid] <= t:\n lo = mid + 1\n else:\n hi = mid - 1\n return ans\n\n" }, { "answer_id": 72413103, "author": "Raymond Hettinger", "author_id": 424499, "author_profile": "https://Stackoverflow.com/users/424499", "pm_score": 2, "selected": false, "text": "def find(data, target):\n start = bisect_left(data, target)\n end = bisect_right(data, target)\n return -1 if start == end else start\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15682/" ]
212,378
<p>I have an embedded webserver that has a total of 2 Megs of space on it. Normally you gzip files for the clients benefit, but this would save us space on the server. I read that you can just gzip the js file and save it on the server. I tested that on IIS and I didn't have any luck at all. What exactly do I need to do on every step of the process to make this work?</p> <p>This is what I imagine it will be like:</p> <ol> <li>gzip foo.js</li> <li>change link in html to point to foo.js.gz instead of just .js</li> <li>Add some kind of header to the response?</li> </ol> <p>Thanks for any help at all.</p> <p>-fREW</p> <p><strong>EDIT</strong>: My webserver can't do anything on the fly. It's not Apache or IIS; it's a binary on a ZiLog processor. I know that you can compress streams; I just heard that you can also compress the files once and leave them compressed.</p>
[ { "answer_id": 212684, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 4, "selected": true, "text": "Content-Encoding: gzip\n Accept-Encoding: gzip\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
212,381
<p>I am trying to create a multi dimensional array using this syntax:</p> <pre><code>$x[1] = 'parent'; $x[1][] = 'child'; </code></pre> <p>I get the error: <code>[] operator not supported for strings</code> because it is evaluating the <code>$x[1]</code> as a string as opposed to returning the array so I can append to it.</p> <p>What is the correct syntax for doing it this way? The overall goal is to create this multidimensional array in an iteration that will append elements to a known index.</p> <p>The syntax <code>${$x[1]}[]</code> does not work either.</p>
[ { "answer_id": 212396, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 3, "selected": false, "text": "$x = array();\n$x[1] = array();\n$x[1][] = 'child';\n" }, { "answer_id": 212399, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 6, "selected": true, "text": "$x[1] = array();\n$x[1][] = 'child';\n" }, { "answer_id": 216358, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 1, "selected": false, "text": "$x = array('parent' => array());\n$x['parent'][] = 'child';\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,401
<p>From Wikipedia, the free encyclopedia: <strong>Closure (computer science)</strong></p> <blockquote> <p>In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Constructs such as objects in other languages can also be modeled with closures.</p> </blockquote> <p>To use this inside of JavaScript, can someone point me to an example of how this applies?</p>
[ { "answer_id": 212431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "function SetClassOnHover(className){\n $(\"td\").hover(\n function () {\n $(this).addClass(className);\n },\n function () {\n $(this).removeClass(className);\n }\n );\n}\n" }, { "answer_id": 5084991, "author": "invisible bob", "author_id": 462266, "author_profile": "https://Stackoverflow.com/users/462266", "pm_score": 1, "selected": false, "text": "function incrementer(){\n var i=0;\n this.increment=function(){\n i++;\n }\n this.get=function(){\n return i;\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,407
<p>Is the singleton class in Ruby a class in and of itself? Is it the reason why all objects belong to "class?" The concept is <strong>fuzzy</strong>, but I believe it has something to do with why I can define a class method at all (<code>class foo; def foo.bar ...</code>).</p> <p>What is the singleton class in Ruby?</p>
[ { "answer_id": 213177, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 8, "selected": true, "text": "irb(main):001:0> class Foo; def method1; puts 1; end; end\n=> nil\nirb(main):002:0> foo = Foo.new\n=> #<Foo:0xb79fa724>\nirb(main):003:0> def foo.method2; puts 2; end\n=> nil\nirb(main):004:0> foo.method1\n1\n=> nil\nirb(main):005:0> foo.method2\n2\n=> nil\nirb(main):006:0> other_foo = Foo.new\n=> #<Foo:0xb79f0ef4>\nirb(main):007:0> other_foo.method1\n1\n=> nil\nirb(main):008:0> other_foo.method2\nNoMethodError: undefined method `method2' for #<Foo:0xb79f0ef4>\n from (irb):8\n Class irb(main):009:0> Foo.method_defined? :method1\n=> true\nirb(main):010:0> Foo.method_defined? :method2\n=> false\n class << obj irb(main):012:0> singleton_class = ( class << foo; self; end )\n=> #<Class:#<Foo:0xb79fa724>>\nirb(main):013:0> singleton_class.method_defined? :method1\n=> true\nirb(main):014:0> singleton_class.method_defined? :method2\n=> true\nirb(main):015:0> other_singleton_class = ( class << other_foo; self; end )\n=> #<Class:#<Foo:0xb79f0ef4>>\nirb(main):016:0> other_singleton_class.method_defined? :method1\n=> true\nirb(main):017:0> other_singleton_class.method_defined? :method2\n=> false\n irb(main):018:0> class << foo; def method3; puts 3; end; end\n=> nil\nirb(main):019:0> foo.method3\n3\n=> nil\nirb(main):022:0> Foo.method_defined? :method3\n=> false\n Class" }, { "answer_id": 8932711, "author": "Bedasso", "author_id": 325589, "author_profile": "https://Stackoverflow.com/users/325589", "pm_score": 5, "selected": false, "text": "\n foo = Array.new\n def foo.size\n \"Hello World!\"\n end\n foo.size # => \"Hello World!\"\n foo.class # => Array\n #Create another instance of Array Class and call size method on it\n bar = Array.new\n bar.size # => 0\n singleton_methods foo.singleton_methods # => [:size]\n bar.singleton_methods # => []\n" }, { "answer_id": 46916846, "author": "Piotr Galas", "author_id": 2482094, "author_profile": "https://Stackoverflow.com/users/2482094", "pm_score": 3, "selected": false, "text": " singleton_class = ( class << foo; self; end )\n singleton_class = foo.singleton_class\n" }, { "answer_id": 60468299, "author": "Paa Yaw", "author_id": 5552374, "author_profile": "https://Stackoverflow.com/users/5552374", "pm_score": 2, "selected": false, "text": "class User; end\nuser = User.new\ndef user.age\n \"i'm a unique method\"\nend\nuser1 = User.new \nuser.age #\"i'm a unique method\"\nuser1.age # NoMethodError (undefined method `age' for #<User:0x0000559c66ab7338>)\n user.singleton_class # #<Class:#<User:0x0000559c66b47c58>>\n user_singleton_class = user.method(:age).owner # #<Class:#<User:0x0000559c66b47c58>>\nuser.method(:age).owner == user.singleton_class # true\nuser_singleton_class.instance_methods(false) # [:age]\n user.singleton_methods == user_singleton_class.instance_methods(false) # true\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28914/" ]
212,425
<p>How can I go about making my routes recognise an optional prefix parameter as follows:</p> <pre><code>/*lang/controller/id </code></pre> <p>In that the lang part is optional, and has a default value if it's not specified in the URL:</p> <pre><code>/en/posts/1 =&gt; lang = en /fr/posts/1 =&gt; lang = fr /posts/1 =&gt; lang = en </code></pre> <p><em>EDIT</em></p> <p>Ideally, I'm looking to do this across many controllers and actions by mapping a namespace:</p> <pre><code>map.namespace "*lang" do |lang| lang.resources :posts lang.resources :stories end </code></pre>
[ { "answer_id": 212895, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 1, "selected": false, "text": "map.connect ':language/posts/:id', :controller => 'posts', :action => 'show'\nmap.connect 'posts/:id', :controller => 'posts', :action => 'show'\n" }, { "answer_id": 213111, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": ":defaults map.connect ':lang/posts/:id', :controller => 'posts', :action => 'show',\n :defaults => { :lang => 'en' }\n" }, { "answer_id": 213865, "author": "Collin", "author_id": 29104, "author_profile": "https://Stackoverflow.com/users/29104", "pm_score": 1, "selected": false, "text": "map.connect ':lang/posts/:id', :controller => 'posts', :action => 'show', :lang => nil\n" }, { "answer_id": 221125, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 5, "selected": true, "text": "require 'routing_filter/base'\n\nmodule RoutingFilter\n class Locale < Base\n\n # remove the locale from the beginning of the path, pass the path\n # to the given block and set it to the resulting params hash\n def around_recognize(path, env, &block)\n locale = nil\n path.sub! %r(^/([a-zA-Z]{2})(?=/|$)) do locale = $1; '' end\n returning yield do |params|\n params[:locale] = locale || 'en'\n end\n end\n\n def around_generate(*args, &block)\n locale = args.extract_options!.delete(:locale) || 'en'\n returning yield do |result|\n if locale != 'en'\n result.sub!(%r(^(http.?://[^/]*)?(.*))){ \"#{$1}/#{locale}#{$2}\" }\n end \n end\n end\n\n end\nend\n map.filter 'locale'\n / => :locale => 'en'\n/en => :locale => 'en'\n/fr => :locale => 'fr'\n home_path => /\nhome_path(:locale => 'en') => /\nhome_path(:locale => 'fr') => /fr\n" }, { "answer_id": 2167394, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " map.with_options(:path_prefix => \":locale\") do |m|\n m.resources :posts\n m.resources :stories \n end\n before_filter :define_locale\n\ndef define_locale\n if params[:locale] == nil\n I18n.locale = 'en'\n else\n I18n.locale = params[:locale]\n end\nend\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12037/" ]
212,429
<p>Scenario:</p> <p>I'm currently writing a layer to abstract 3 similar webservices into one useable class. Each webservice exposes a set of objects that share commonality. I have created a set of intermediary objects which exploit the commonality. However in my layer I need to convert between the web service objects and my objects.</p> <p>I've used reflection to create the appropriate type at run time before I make the call to the web service like so:</p> <pre><code> public static object[] CreateProperties(Type type, IProperty[] properties) { //Empty so return null if (properties==null || properties.Length == 0) return null; //Check the type is allowed CheckPropertyTypes("CreateProperties(Type,IProperty[])",type); //Convert the array of intermediary IProperty objects into // the passed service type e.g. Service1.Property object[] result = new object[properties.Length]; for (int i = 0; i &lt; properties.Length; i++) { IProperty fromProp = properties[i]; object toProp = ReflectionUtility.CreateInstance(type, null); ServiceUtils.CopyProperties(fromProp, toProp); result[i] = toProp; } return result; } </code></pre> <p>Here's my calling code, from one of my service implementations:</p> <pre><code>Property[] props = (Property[])ObjectFactory.CreateProperties(typeof(Property), properties); _service.SetProperties(folderItem.Path, props); </code></pre> <p>So each service exposes a different "Property" object which I hide behind my own implementation of my IProperty interface.</p> <p>The reflection code works in unit tests producing an array of objects whose elements are of the appropriate type. But the calling code fails:</p> <blockquote> <p>System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'MyProject.Property[]</p> </blockquote> <p>Any ideas?</p> <p>I was under the impression that any cast from Object will work as long as the contained object is convertable?</p>
[ { "answer_id": 212443, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "Property[] props = Array.ConvertAll(source, prop => (Property)prop);\n Property[] props = Array.ConvertAll<object,Property>(\n source, delegate(object prop) { return (Property)prop; });\n Array.Copy Property[] props = new Property[2];\nprops[0] = new Property();\nprops[1] = new Property();\n\nobject[] asObj = (object[])props;\n Property[] object[]" }, { "answer_id": 212447, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "object[] result = (object[]) Array.CreateInstance(type, properties.Length);\n type object[]" }, { "answer_id": 212512, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "public static T[] CreateProperties<T>(IProperty[] properties)\n where T : class, new()\n{\n //Empty so return null\n if (properties==null || properties.Length == 0)\n return null;\n\n //Check the type is allowed\n CheckPropertyTypes(\"CreateProperties(Type,IProperty[])\",typeof(T));\n\n //Convert the array of intermediary IProperty objects into\n // the passed service type e.g. Service1.Property\n T[] result = new T[properties.Length];\n for (int i = 0; i < properties.Length; i++)\n {\n T[i] = new T();\n ServiceUtils.CopyProperties(properties[i], t[i]);\n }\n return result;\n}\n Property[] props = ObjectFactory.CreateProperties<Property>(properties);\n_service.SetProperties(folderItem.Path, props);\n" }, { "answer_id": 3291110, "author": "Mr. Graves", "author_id": 171518, "author_profile": "https://Stackoverflow.com/users/171518", "pm_score": 1, "selected": false, "text": "//get the data from the object factory\nobject[] newDataArray = AppObjectFactory.BuildInstances(Type.GetType(\"OutputData\"));\nif (newDataArray != null)\n{\n SomeComplexObject result = new SomeComplexObject();\n //find the source\n Type resultTypeRef = result.GetType();\n //get a reference to the property\n PropertyInfo pi = resultTypeRef.GetProperty(\"TargetPropertyName\");\n if (pi != null)\n {\n //create an array of the correct type with the correct number of items\n pi.SetValue(result, Array.CreateInstance(Type.GetType(\"OutputData\"), newDataArray.Length), null);\n //copy the data and leverage Array.Copy's built in type casting\n Array.Copy(newDataArray, pi.GetValue(result, null) as Array, newDataArray.Length);\n }\n}\n T result = new T();\nType resultTypeRef = result.GetType();\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950/" ]
212,434
<p>As the title states, is there a way to prevent extra elements from showing up in VBA dynamic arrays when they are non-zero based? </p> <p>For example, when using code similar to the following:</p> <pre><code>While Cells(ndx, 1).Value &lt;&gt; vbNullString ReDim Preserve data(1 To (UBound(data) + 1)) ndx = ndx + 1 Wend </code></pre> <p>You have an extra empty array element at the end of processing. While this can be eliminated with the following:</p> <pre><code>ReDim Preserve data(1 To (UBound(data) - 1)) </code></pre> <p>This doesn't seem like the best way of resolving this problem. </p> <p>As such, is there a way to prevent that extra element from being created in the first place? Preferably something that doesn't require additional logic inside of the loop.</p>
[ { "answer_id": 212497, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "Option Base UBound() + 1 ReDim Preserve For Each ... In ... ' creation ' \nDim anyValue as Variant\nDim c as New Collection\n\n' and adding values '\nc.Add anyValue, strKey\n\n' iteration '\nFor Each anyValue in c\n Debug.Print anyValue\nNext c\n\n' count values '\nDebug.Print c.Count\n\n' element deletion '\nc.Delete strKey\n" }, { "answer_id": 212615, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "ReDim Preserve ReDim Dim a()\n With Sheet1\n a = .Range(.Range(\"A1\"), .Range(\"A1\").End(xlDown)).Value\n End With\n Debug.Print a(1, 1)\n" }, { "answer_id": 213115, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "ReDim data(1 To 1) \nWhile Cells(ndx, 1).Value <> vbNullString \n ReDim Preserve data(1 To (UBound(data) + 1)) \n ndx = ndx + 1\nWend\n ReDim data(1 To 1) \nnStartIndex = ndx\nWhile Cells(ndx, 1).Value <> vbNullString \n ' On the first iteration this does nothing because\n ' the array already has one element\n ReDim Preserve data(1 To ndx - nStartIndex + 1) \n ndx = ndx + 1\nWend\n" }, { "answer_id": 9774185, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 1, "selected": false, "text": "Dim data()\nDim i as Long\n\nReDim data(-1 To -1) ' Empty array. We never use data(-1).\n\nFor i = 0 To UBound(data)\n ...\nNext i\n ReDim data(0 To 0) ' Empty array. We never use data(0).\n\nFor i = 1 To UBound(data)\n ...\nNext i\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
212,442
<p>I want to do something very simple in C++ but i can't find how. I want to create a function like a for loop where i will ideally enter a variable for the times the iteration should happen and some functions inside brackets my function will execute. I hope i was clear enough. Thanks...</p> <p>Example</p> <pre><code>superFor (1) { //commands to be executed here add(1+2); } </code></pre>
[ { "answer_id": 212460, "author": "FOR", "author_id": 27826, "author_profile": "https://Stackoverflow.com/users/27826", "pm_score": 0, "selected": false, "text": "void DoSomethingRepeatedly(int numTimesTo Loop)\n{\n for(int i=0; i<numTimesToLoop; i++)\n { \n //do whatever; \n }\n}\n" }, { "answer_id": 212462, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "void out(int x) {\n cout << x << ' ';\n}\n\nvector<int> xs;\nxs.push_back(42);\nxs.push_back(23);\n\nfor_each(xs.begin(), xs.end(), out);\n out for_each" }, { "answer_id": 212464, "author": "user9282", "author_id": 9282, "author_profile": "https://Stackoverflow.com/users/9282", "pm_score": 3, "selected": false, "text": "#define superFor(n) for(int i = 0; i < (n); i++)\n" }, { "answer_id": 212480, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 1, "selected": false, "text": "#define superFor(v,i) for(int v=0; v<(i); v++)\n superFor(i,10) {\n printf(\"Doing something ten times\");\n}\n" }, { "answer_id": 212491, "author": "Keith Twombley", "author_id": 23866, "author_profile": "https://Stackoverflow.com/users/23866", "pm_score": 2, "selected": false, "text": " for(variable; condition; increment) {\n //stuff goes here\n }\n for(int i = 0; i < how_many_times_to_loop; i++) {\n //stuff goes here\n }\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28954/" ]
212,446
<p>I need to return only the facet counts from solr. So I basically want to search over all documents and return the facet counts, but I don't want to return any search results. Is this possible?</p> <p>Thanks</p>
[ { "answer_id": 2740207, "author": "nialloc", "author_id": 187419, "author_profile": "https://Stackoverflow.com/users/187419", "pm_score": 7, "selected": true, "text": "facet=true rows=0 numFound" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93743/" ]
212,466
<p>What does the &quot;bus error&quot; message mean, and how does it differ from a <a href="https://en.wikipedia.org/wiki/Segmentation_fault" rel="noreferrer">segmentation fault</a>?</p>
[ { "answer_id": 212519, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "unsigned char data[6];\n(unsigned int *) (data + 2) = 0xdeadf00d;\n 0xdeadf00d" }, { "answer_id": 11203800, "author": "Vinaya Sagar", "author_id": 1482148, "author_profile": "https://Stackoverflow.com/users/1482148", "pm_score": -1, "selected": false, "text": "{\n char buf[255];\n sprintf(buf,\"%s:%s\\n\", ifname, message);\n}\n" }, { "answer_id": 21610131, "author": "stuxnetting", "author_id": 2742584, "author_profile": "https://Stackoverflow.com/users/2742584", "pm_score": -1, "selected": false, "text": "for (j = 0; i < n; j++) {\n for (i =0; i < m; i++) {\n a[n+1][j] += a[i][j];\n }\n}\n" }, { "answer_id": 26261457, "author": "Erik Vesteraas", "author_id": 3347227, "author_profile": "https://Stackoverflow.com/users/3347227", "pm_score": 3, "selected": false, "text": "#include <string.h>\n#include <stdio.h>\n\nint main(void)\n{\n char buffer[120];\n fgets(buffer, sizeof buffer, stdin);\n strcat(\"foo\", buffer);\n return 0;\n}\n strcat" }, { "answer_id": 31877230, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "mmap SIGBUS ftruncate #include <fcntl.h> /* O_ constants */\n#include <unistd.h> /* ftruncate */\n#include <sys/mman.h> /* mmap */\n\nint main() {\n int fd;\n int *map;\n int size = sizeof(int);\n char *name = \"/a\";\n\n shm_unlink(name);\n fd = shm_open(name, O_RDWR | O_CREAT, (mode_t)0600);\n /* THIS is the cause of the problem. */\n /*ftruncate(fd, size);*/\n map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n /* This is what generates the SIGBUS. */\n *map = 0;\n}\n gcc -std=c99 main.c -lrt\n./a.out\n SIGBUS shm_open *map = 0 .global _start\n_start:\nasm_main_after_prologue:\n /* misalign the stack out of 16-bit boundary */\n add sp, sp, #-4\n /* access the stack */\n ldr w0, [sp]\n\n /* exit syscall in case SIGBUS does not happen */\n mov x0, 0\n mov x8, 93\n svc 0\n SCTLR_ELx.SA SCTLR_EL1.SA0" }, { "answer_id": 53068841, "author": "Aditya Vikas Devarapalli", "author_id": 2498327, "author_profile": "https://Stackoverflow.com/users/2498327", "pm_score": 3, "selected": false, "text": "SIGBUS" }, { "answer_id": 68074627, "author": "deeBo", "author_id": 7674702, "author_profile": "https://Stackoverflow.com/users/7674702", "pm_score": 0, "selected": false, "text": ".text .globl _myGlobal # Allocate a 64-bit global with the value 2\n.data\n.align 3\n_myGlobal:\n.quad 2\n.globl _main # Main function code\n_main:\npush %rbp\n _myGlobal:\n.quad 2\n.text # <- This\n.globl _main\n_main:\n" }, { "answer_id": 68245694, "author": "John Kearney", "author_id": 977365, "author_profile": "https://Stackoverflow.com/users/977365", "pm_score": 2, "selected": false, "text": "/*\n * SIGSEGV si_codes\n */\n#define SEGV_MAPERR 1 /* address not mapped to object */\n#define SEGV_ACCERR 2 /* invalid permissions for mapped object */\n#define SEGV_BNDERR 3 /* failed address bound checks */\n#ifdef __ia64__\n# define __SEGV_PSTKOVF 4 /* paragraph stack overflow */\n#else\n# define SEGV_PKUERR 4 /* failed protection key checks */\n#endif\n#define SEGV_ACCADI 5 /* ADI not enabled for mapped object */\n#define SEGV_ADIDERR 6 /* Disrupting MCD error */\n#define SEGV_ADIPERR 7 /* Precise MCD exception */\n#define SEGV_MTEAERR 8 /* Asynchronous ARM MTE error */\n#define SEGV_MTESERR 9 /* Synchronous ARM MTE exception */\n#define NSIGSEGV 9\n\n/*\n * SIGBUS si_codes\n */\n#define BUS_ADRALN 1 /* invalid address alignment */\n#define BUS_ADRERR 2 /* non-existent physical address */\n#define BUS_OBJERR 3 /* object specific hardware error */\n/* hardware memory error consumed on a machine check: action required */\n#define BUS_MCEERR_AR 4\n/* hardware memory error detected in process but not consumed: action optional*/\n#define BUS_MCEERR_AO 5\n#define NSIGBUS 5\n /*\n * si_code values\n * Digital reserves positive values for kernel-generated signals.\n */\n#define SI_USER 0 /* sent by kill, sigsend, raise */\n#define SI_KERNEL 0x80 /* sent by the kernel from somewhere */\n#define SI_QUEUE -1 /* sent by sigqueue */\n#define SI_TIMER -2 /* sent by timer expiration */\n#define SI_MESGQ -3 /* sent by real time mesq state change */\n#define SI_ASYNCIO -4 /* sent by AIO completion */\n#define SI_SIGIO -5 /* sent by queued SIGIO */\n#define SI_TKILL -6 /* sent by tkill system call */\n#define SI_DETHREAD -7 /* sent by execve() killing subsidiary threads */\n#define SI_ASYNCNL -60 /* sent by glibc async name lookup completion */\n\n#define SI_FROMUSER(siptr) ((siptr)->si_code <= 0)\n#define SI_FROMKERNEL(siptr) ((siptr)->si_code > 0)\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
212,481
<p>I have a header file like this:</p> <pre><code>#ifndef __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ #define __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ #ifdef _DEBUG // macros for turning a number into a string #define STRING2(x) #x #define STRING(x) STRING2(x) #ifdef TRIAGE_MESG_AS_WARNING #define TRIAGE_TODO_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : warning : TRIAGE TO-DO: " STRING(description) )) #define TRIAGE_FIXTHIS_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : warning : TRIAGE FIXTHIS: " STRING(description) )) #else #define TRIAGE_TODO_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : message : TRIAGE TO-DO: " STRING(description) )) #define TRIAGE_FIXTHIS_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : message : TRIAGE FIXTHIS: " STRING(description) )) #endif #else #define TRIAGE_TODO_TAG(description) #define TRIAGE_FIXTHIS_TAG(description) #endif #endif // __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__ </code></pre> <p>Which outputs notes to the output pane in Visual Studio 2005. When 'TRIAGE_MESG_AS_WARNING' is defined, Visual Studio will harvest these messages and list them as warnings in the Error List. It does this because the text format matches a warning. However, I don't want them to show up as warnings all the time, I would rather they show up in the Messages pane of the Error List.</p> <blockquote> <p>How do you format lines you put in the "Output Window" so that Visual Studio will auto-magically show them in the "Messages" tab of the "Error List" window?</p> </blockquote> <p>The format I have setup for messages in the above code looks like a message from other output, but does not get harvested in the same way.</p> <p>A co-worker suggested to me that I might need to write a 'custom automation object' to write to the Messages pane. That seems like a pain, especially since it is trivial to end-up with entries in the Error pane and Warning pane simply by proper formating. Is this a possible avenue?</p> <p>We're using unmanaged C++, so we can't rely on managed (.NET) only tooling. We do not want to extend VS with hooks.</p>
[ { "answer_id": 888396, "author": "ChrisBD", "author_id": 102238, "author_profile": "https://Stackoverflow.com/users/102238", "pm_score": 2, "selected": false, "text": "//Get the \"Error List Window\"\n\nErrorListProvider errorProvider = new ErrorListProvider(this);\nTask newError = new Task();\nnewError.ErrorCategory = TaskErrorCategory.Error; // or TaskErrorCategory.Warning for warnings\nnewError.Category = TaskCategory.BuildCompile;\nnewError.Text = \"Some Error Text\";\nerrorProvider.Tasks.Add(newError);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28950/" ]
212,492
<p>I've worked with a couple of Visual C++ compilers (VC97, VC2005, VC2008) and I haven't really found a clearcut way of adding external libraries to my builds. I come from a Java background, and in Java libraries are everything! </p> <p>I understand from compiling open-source projects on my Linux box that all the source code for the library seems to need to be included, with the exception of those .so files.</p> <p>Also I've heard of the .lib static libraries and .dll dynamic libraries, but I'm still not entirely sure how to add them to a build and make them work. How does one go about this?</p>
[ { "answer_id": 213204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "include lib bin" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18149/" ]
212,494
<p>I use an XML file in App_Data in conjunction with a Repeater on the main page of an intranet application allow me to display messages to users when they logon about application status, maintenance, etc. To test the functionality, it would be nice to have the file in the App_Data folder under development, but if I do this it copies it over the file on the production server when I publish the application. Is there anyway I can prevent this from happening short of going to a Web Deployment project (and will that solve my problem)?</p>
[ { "answer_id": 248958, "author": "Andrew Theken", "author_id": 32238, "author_profile": "https://Stackoverflow.com/users/32238", "pm_score": 1, "selected": false, "text": "Stream xml;\n#if DEBUG\nxml = File.Open(\"debug.xml\");\n#else\nxml = File.Open(\"release.xml\");\n#endif\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12950/" ]
212,510
<p>Currently I'm writing it in clear text <em>oops!</em>, it's an in house program so it's not that bad but I'd like to do it right. How should I go about encrypting this when writing to the registry and how do I decrypt it?</p> <pre><code>OurKey.SetValue("Password", textBoxPassword.Text); </code></pre>
[ { "answer_id": 212526, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 7, "selected": false, "text": "byte[] data = System.Text.Encoding.ASCII.GetBytes(inputString);\ndata = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);\nString hash = System.Text.Encoding.ASCII.GetString(data);\n" }, { "answer_id": 212589, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 5, "selected": false, "text": "byte[] salt = new byte[32];\nSystem.Security.Cryptography.RNGCryptoServiceProvider.Create().GetBytes(salt);\n // Convert the plain string pwd into bytes\nbyte[] plainTextBytes = System.Text UnicodeEncoding.Unicode.GetBytes(plainText);\n// Append salt to pwd before hashing\nbyte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length];\nSystem.Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length);\nSystem.Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length);\n // Create hash for the pwd+salt\nSystem.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();\nbyte[] hash = hashAlgo.ComputeHash(combinedBytes);\n // Append the salt to the hash\nbyte[] hashPlusSalt = new byte[hash.Length + salt.Length];\nSystem.Buffer.BlockCopy(hash, 0, hashPlusSalt, 0, hash.Length);\nSystem.Buffer.BlockCopy(salt, 0, hashPlusSalt, hash.Length, salt.Length);\n" }, { "answer_id": 272235, "author": "Jamie Wright", "author_id": 2779, "author_profile": "https://Stackoverflow.com/users/2779", "pm_score": 4, "selected": false, "text": "OurKey.SetValue(\"Password\", StringEncryptor.EncryptString(textBoxPassword.Text));\nOurKey.GetValue(\"Password\", StringEncryptor.DecryptString(textBoxPassword.Text));\n public class StringEncryptor\n{\n private static IKernel _kernel;\n\n static StringEncryptor()\n {\n _kernel = new StandardKernel(new EncryptionModule());\n }\n\n public static string EncryptString(string plainText)\n {\n return _kernel.Get<IStringEncryptor>().EncryptString(plainText);\n }\n\n public static string DecryptString(string encryptedText)\n {\n return _kernel.Get<IStringEncryptor>().DecryptString(encryptedText);\n }\n}\n public class EncryptionModule : StandardModule\n{\n public override void Load()\n {\n Bind<IStringEncryptor>().To<TripleDESStringEncryptor>();\n }\n}\n public interface IStringEncryptor\n{\n string EncryptString(string plainText);\n string DecryptString(string encryptedText);\n}\n public class TripleDESStringEncryptor : IStringEncryptor\n{\n private byte[] _key;\n private byte[] _iv;\n private TripleDESCryptoServiceProvider _provider;\n\n public TripleDESStringEncryptor()\n {\n _key = System.Text.ASCIIEncoding.ASCII.GetBytes(\"GSYAHAGCBDUUADIADKOPAAAW\");\n _iv = System.Text.ASCIIEncoding.ASCII.GetBytes(\"USAZBGAW\");\n _provider = new TripleDESCryptoServiceProvider();\n }\n\n #region IStringEncryptor Members\n\n public string EncryptString(string plainText)\n {\n return Transform(plainText, _provider.CreateEncryptor(_key, _iv));\n }\n\n public string DecryptString(string encryptedText)\n {\n return Transform(encryptedText, _provider.CreateDecryptor(_key, _iv));\n }\n\n #endregion\n\n private string Transform(string text, ICryptoTransform transform)\n {\n if (text == null)\n {\n return null;\n }\n using (MemoryStream stream = new MemoryStream())\n {\n using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))\n {\n byte[] input = Encoding.Default.GetBytes(text);\n cryptoStream.Write(input, 0, input.Length);\n cryptoStream.FlushFinalBlock();\n\n return Encoding.Default.GetString(stream.ToArray());\n }\n }\n }\n}\n" }, { "answer_id": 6157302, "author": "Deathstalker", "author_id": 773704, "author_profile": "https://Stackoverflow.com/users/773704", "pm_score": 3, "selected": false, "text": "public string GenerateAPassKey(string passphrase)\n {\n // Pass Phrase can be any string\n string passPhrase = passphrase;\n // Salt Value can be any string(for simplicity use the same value as used for the pass phrase)\n string saltValue = passphrase;\n // Hash Algorithm can be \"SHA1 or MD5\"\n string hashAlgorithm = \"SHA1\";\n // Password Iterations can be any number\n int passwordIterations = 2;\n // Key Size can be 128,192 or 256\n int keySize = 256;\n // Convert Salt passphrase string to a Byte Array\n byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);\n // Using System.Security.Cryptography.PasswordDeriveBytes to create the Key\n PasswordDeriveBytes pdb = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);\n //When creating a Key Byte array from the base64 string the Key must have 32 dimensions.\n byte[] Key = pdb.GetBytes(keySize / 11);\n String KeyString = Convert.ToBase64String(Key);\n\n return KeyString;\n }\n\n //Save the keystring some place like your database and use it to decrypt and encrypt\n//any text string or text file etc. Make sure you dont lose it though.\n\n private static string Encrypt(string plainStr, string KeyString) \n { \n RijndaelManaged aesEncryption = new RijndaelManaged();\n aesEncryption.KeySize = 256;\n aesEncryption.BlockSize = 128;\n aesEncryption.Mode = CipherMode.ECB;\n aesEncryption.Padding = PaddingMode.ISO10126;\n byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);\n aesEncryption.Key = KeyInBytes;\n byte[] plainText = ASCIIEncoding.UTF8.GetBytes(plainStr);\n ICryptoTransform crypto = aesEncryption.CreateEncryptor();\n byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);\n return Convert.ToBase64String(cipherText);\n }\n\n private static string Decrypt(string encryptedText, string KeyString) \n {\n RijndaelManaged aesEncryption = new RijndaelManaged(); \n aesEncryption.KeySize = 256;\n aesEncryption.BlockSize = 128; \n aesEncryption.Mode = CipherMode.ECB;\n aesEncryption.Padding = PaddingMode.ISO10126;\n byte[] KeyInBytes = Encoding.UTF8.GetBytes(KeyString);\n aesEncryption.Key = KeyInBytes;\n ICryptoTransform decrypto = aesEncryption.CreateDecryptor(); \n byte[] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(), 0, encryptedText.Length); \n return ASCIIEncoding.UTF8.GetString(decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length)); \n }\n\n String KeyString = GenerateAPassKey(\"PassKey\");\n String EncryptedPassword = Encrypt(\"25Characterlengthpassword!\", KeyString);\n String DecryptedPassword = Decrypt(EncryptedPassword, KeyString);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,528
<p>This Question is almost the same as the previously asked <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer">How can I get the IP Address of a local computer?</a> -Question. However I need to find the IP address(es) of a <strong>Linux Machine</strong>.</p> <p>So: How do I - programmatically in <strong>C++</strong> - detect the IP addresses of the linux server my application is running on. The servers will have at least two IP addresses and I need a specific one (the one in a given network (the public one)).</p> <p>I'm sure there is a simple function to do that - but where?</p> <hr /> <p>To make things a bit clearer:</p> <ul> <li>The server will obviously have the &quot;localhost&quot;: 127.0.0.1</li> <li>The server will have an internal (management) IP address: 172.16.x.x</li> <li>The server will have an external (public) IP address: 80.190.x.x</li> </ul> <p>I need to find the external IP address to bind my application to it. Obviously I can also bind to INADDR_ANY (and actually that's what I do at the moment). I would prefer to detect the public address, though.</p>
[ { "answer_id": 212688, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 5, "selected": false, "text": "ioctl(<socketfd>, SIOCGIFCONF, (struct ifconf)&buffer); /usr/include/linux/if.h ifconf ifreq /usr/include/linux/sockios.h" }, { "answer_id": 213223, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "curl www.whatismyip.org" }, { "answer_id": 265978, "author": "Twelve47", "author_id": 26961, "author_profile": "https://Stackoverflow.com/users/26961", "pm_score": 7, "selected": false, "text": "#include <stdio.h> \n#include <sys/types.h>\n#include <ifaddrs.h>\n#include <netinet/in.h> \n#include <string.h> \n#include <arpa/inet.h>\n\nint main (int argc, const char * argv[]) {\n struct ifaddrs * ifAddrStruct=NULL;\n struct ifaddrs * ifa=NULL;\n void * tmpAddrPtr=NULL;\n\n getifaddrs(&ifAddrStruct);\n\n for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {\n if (!ifa->ifa_addr) {\n continue;\n }\n if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4\n // is a valid IP4 Address\n tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n char addressBuffer[INET_ADDRSTRLEN];\n inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n printf(\"%s IP Address %s\\n\", ifa->ifa_name, addressBuffer); \n } else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6\n // is a valid IP6 Address\n tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;\n char addressBuffer[INET6_ADDRSTRLEN];\n inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);\n printf(\"%s IP Address %s\\n\", ifa->ifa_name, addressBuffer); \n } \n }\n if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);\n return 0;\n}\n" }, { "answer_id": 3120382, "author": "4dan", "author_id": 376518, "author_profile": "https://Stackoverflow.com/users/376518", "pm_score": 5, "selected": false, "text": "void GetPrimaryIp(char* buffer, size_t buflen) \n{\n assert(buflen >= 16);\n\n int sock = socket(AF_INET, SOCK_DGRAM, 0);\n assert(sock != -1);\n\n const char* kGoogleDnsIp = \"8.8.8.8\";\n uint16_t kDnsPort = 53;\n struct sockaddr_in serv;\n memset(&serv, 0, sizeof(serv));\n serv.sin_family = AF_INET;\n serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);\n serv.sin_port = htons(kDnsPort);\n\n int err = connect(sock, (const sockaddr*) &serv, sizeof(serv));\n assert(err != -1);\n\n sockaddr_in name;\n socklen_t namelen = sizeof(name);\n err = getsockname(sock, (sockaddr*) &name, &namelen);\n assert(err != -1);\n\n const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, buflen);\n assert(p);\n\n close(sock);\n}\n" }, { "answer_id": 5452793, "author": "Chaza", "author_id": 679398, "author_profile": "https://Stackoverflow.com/users/679398", "pm_score": -1, "selected": false, "text": "// Use a HTTP request to a well known server that echo's back the public IP address\nvoid GetPublicIP(CString & csIP)\n{\n // Initialize COM\n bool bInit = false;\n if (SUCCEEDED(CoInitialize(NULL)))\n {\n // COM was initialized\n bInit = true;\n\n // Create a HTTP request object\n MSXML2::IXMLHTTPRequestPtr HTTPRequest;\n HRESULT hr = HTTPRequest.CreateInstance(\"MSXML2.XMLHTTP\");\n if (SUCCEEDED(hr))\n {\n // Build a request to a web site that returns the public IP address\n VARIANT Async;\n Async.vt = VT_BOOL;\n Async.boolVal = VARIANT_FALSE;\n CComBSTR ccbRequest = L\"http://whatismyipaddress.com/\";\n\n // Open the request\n if (SUCCEEDED(HTTPRequest->raw_open(L\"GET\",ccbRequest,Async)))\n {\n // Send the request\n if (SUCCEEDED(HTTPRequest->raw_send()))\n {\n // Get the response\n CString csRequest = HTTPRequest->GetresponseText();\n\n // Parse the IP address\n CString csMarker = \"<!-- contact us before using a script to get your IP address -->\";\n int iPos = csRequest.Find(csMarker);\n if (iPos == -1)\n return;\n iPos += csMarker.GetLength();\n int iPos2 = csRequest.Find(csMarker,iPos);\n if (iPos2 == -1)\n return;\n\n // Build the IP address\n int nCount = iPos2 - iPos;\n csIP = csRequest.Mid(iPos,nCount);\n }\n }\n }\n }\n\n // Unitialize COM\n if (bInit)\n CoUninitialize();\n}\n\n" }, { "answer_id": 6045426, "author": "Erik Aronesty", "author_id": 627042, "author_profile": "https://Stackoverflow.com/users/627042", "pm_score": 3, "selected": false, "text": "// ifconfig | perl -ne 'print \"$1\\n\" if /inet addr:([\\d.]+)/'\n\n#include <stdlib.h>\n\nint main() {\n setenv(\"LANG\",\"C\",1);\n FILE * fp = popen(\"ifconfig\", \"r\");\n if (fp) {\n char *p=NULL, *e; size_t n;\n while ((getline(&p, &n, fp) > 0) && p) {\n if (p = strstr(p, \"inet \")) {\n p+=5;\n if (p = strchr(p, ':')) {\n ++p;\n if (e = strchr(p, ' ')) {\n *e='\\0';\n printf(\"%s\\n\", p);\n }\n }\n }\n }\n }\n pclose(fp);\n return 0;\n}\n" }, { "answer_id": 33872296, "author": "Tino", "author_id": 490291, "author_profile": "https://Stackoverflow.com/users/490291", "pm_score": 3, "selected": false, "text": "lo ip r get 1.1.1.1 strace ip r get 1.1.1.1 /etc/hosts /etc/hosts 80.190.1.3 publicinterfaceip\n publicinterfaceip haproxy /etc/hosts root /etc/hosts /etc/profile ~/.profile MYPUBLICIP #define MYPUBLICIPENVVAR \"MYPUBLICIP\"\n\nconst char *mypublicip = getenv(MYPUBLICIPENVVAR);\n\nif (!mypublicip) { fprintf(stderr, \"please set environment variable %s\\n\", MYPUBLICIPENVVAR); exit(3); }\n /path/to/your/script MYPUBLICIP=80.190.1.3 /path/to/your/script crontab ip" }, { "answer_id": 66467436, "author": "PYK", "author_id": 3233722, "author_profile": "https://Stackoverflow.com/users/3233722", "pm_score": 1, "selected": false, "text": "stdio.h #include <stdio.h>\nint main()\n{\n static char ip[32];\n FILE *f = popen(\"ip a | grep 'scope global' | grep -v ':' | awk '{print $2}' | cut -d '/' -f1\", \"r\");\n int c, i = 0;\n while ((c = getc(f)) != EOF) i += sprintf(ip+i, \"%c\", c);\n pclose(f);\n printf(ip);\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999/" ]
212,534
<p>I use a custom-built asp.net control that renders to a DIV and has "height='0'" hard-coded into the element (I know.. stupid). But I need to reset it - get rid of the height assignment somehow. Is this doable with CSS?</p> <p>I can set the height to 100px for example, and it works. But that's not what I want - I want the height assignment removed pretty much.</p> <p>UPDATE: Using FireBug, I can see that CSS's height gets overridden by the hard-coded one:</p> <p><em>removed dead ImageShack link</em></p> <p>I guess there's no way for me to resolve this besides removing the hard-coded height=0. Anyone else see an alternative?</p>
[ { "answer_id": 212635, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 7, "selected": true, "text": "height:auto !important" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22303/" ]
212,539
<p>Is there a Java equivalent to .NET's App.Config?</p> <p>If not is there a standard way to keep you application settings, so that they can be changed after an app has been distributed?</p>
[ { "answer_id": 212605, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 5, "selected": true, "text": "userNodeForPackage(ClassName.class) systemNodeForPackage(ClassName.class)" }, { "answer_id": 19040876, "author": "Pursuit", "author_id": 931379, "author_profile": "https://Stackoverflow.com/users/931379", "pm_score": 4, "selected": false, "text": "Properties public class SomeClass {\n public static void main(String[] args){\n String dbUrl = \"\";\n String dbLogin = \"\";\n String dbPassword = \"\"; \n if (args.length<3) {\n //If no inputs passed in, look for a configuration file\n URL configFile = SomeClass.class.getClass().getResource(\"/Configuration.cnf\");\n try {\n InputStream configFileStream = configFile.openStream();\n Properties p = new Properties();\n p.load(configFileStream);\n configFileStream.close();\n\n dbUrl = (String)p.get(\"dbUrl\");\n dbLogin = (String)p.get(\"dbUser\");\n dbPassword = (String)p.get(\"dbPassword\"); \n } catch (Exception e) { //IO or NullPointer exceptions possible in block above\n System.out.println(\"Useful message\");\n System.exit(1);\n }\n } else {\n //Read required inputs from \"args\"\n dbUrl = args[0];\n dbLogin = args[1];\n dbPassword = args[2]; \n }\n //Input checking one three items here\n //Real work here.\n }\n}\n Configuration.cnf #Comments describing the file\n#more comments\ndbUser=username\ndbPassword=password\ndbUrl=jdbc\\:mysql\\://servername/databasename\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
212,550
<p>The problem is in the title - IE is misbehaving and is saying that there is a script running slowly - FF and Chrome don't have this problem.</p> <p>How can I find the problem . .there's a lot of JS on that page. Checking by hand is not a good ideea</p> <p><strong>EDIT :</strong> It's a page from a project i'm working on... but I need a tool to find the problem.</p> <p><strong>End :</strong> It turned out to be the UpdatePanel - somehow it would get "confused" and would take too long to process something. I just threw it out the window - will only use JQuery from now on :D.</p> <p>And I'm selecting Remy Sharp's answere because I really didn't know about the tool and it seems pretty cool.</p>
[ { "answer_id": 9475927, "author": "dude_id", "author_id": 1236988, "author_profile": "https://Stackoverflow.com/users/1236988", "pm_score": 1, "selected": false, "text": "Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(win_onload);\n win_onload()" }, { "answer_id": 24812408, "author": "LCJ", "author_id": 696627, "author_profile": "https://Stackoverflow.com/users/696627", "pm_score": 0, "selected": false, "text": "dropdown list for" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
212,562
<p>Is there a good way to have a <code>Map&lt;String, ?&gt;</code> get and put ignoring case?</p>
[ { "answer_id": 212629, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 5, "selected": false, "text": "public class CaseInsensitiveMap extends HashMap<String, String> {\n ...\n put(String key, String value) {\n super.put(key.toLowerCase(), value);\n }\n\n get(String key) {\n super.get(key.toLowercase());\n }\n}\n" }, { "answer_id": 1876820, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 7, "selected": true, "text": "final Map<String, ...> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013/" ]
212,569
<p>I'm using Spring's support for JDBC. I'd like to use <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html" rel="noreferrer">JdbcTemplate</a> (or SimpleJdbcTemplate) to execute a query and obtain the result as an instance of ResultSet.</p> <p>The only way that I can see of achieving this is using:</p> <pre><code>String sql = "select * from...."; SqlRowSet results = jdbcTemplate.queryForRowSet(sql); ((ResultSetWrappingSqlRowSet) results).getResultSet(); </code></pre> <p>An obvious shortcoming of this approach is that it requires me to make an assumption (by casting) about the implementation type of SqlRowSet, but is there a better way?</p> <p><strong>Background info...</strong></p> <p>The reason I want to obtain the results as a ResultSet, rather than a collection of beans, is because the results will be passed straight to a Jasper report for display. In other words, the Java bean would be used for nothing other than temporarily storing each row in the ResultSet, and I'd like to avoid creating such a bean for every Jasper report if possible.</p> <p>Cheers, Don</p>
[ { "answer_id": 212632, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 3, "selected": true, "text": " Connection c = ...\n c.prepareCall(\"select ...\").getResultSet();\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
212,577
<p>At the moment, I'm creating an XML file in Java and displaying it in a JSP page by transforming it with XSL/XSLT. Now I need to take that XML file and display the same information in a PDF. Is there a way I can do this by using some kind of XSL file?</p> <p>I've seen the <a href="http://www.lowagie.com/iText/" rel="noreferrer">iText</a> Java-PDF library, but I can't find any way to use it with XML and a stylesheet.</p> <p>Any assistance would be much appreciated. Thanks in advance!</p>
[ { "answer_id": 9477362, "author": "Shriram Kalpathy Mohan", "author_id": 898726, "author_profile": "https://Stackoverflow.com/users/898726", "pm_score": 0, "selected": false, "text": "'Section 9.4.2 Parsing XML' 'iText in Action : Edition 2' '15.2.3 Adding structure' 'iText in Action : Edition 2'" }, { "answer_id": 9622759, "author": "Yaroslav", "author_id": 1254552, "author_profile": "https://Stackoverflow.com/users/1254552", "pm_score": 1, "selected": false, "text": "File xmlfile = new File(baseDir, xml);\nFile xsltfile = new File(baseDir, xsl);\nFile pdffile = new File(outDir, \"ResultXMLPDF.pdf\");\n\nFopFactory fopFactory = FopFactory.newInstance();\nFOUserAgent foUserAgent = fopFactory.newFOUserAgent();\n\nOutputStream out = new java.io.FileOutputStream(pdffile);\nout = new java.io.BufferedOutputStream(out);\n\ntry\n{\n Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);\n // Setup XSLT\n TransformerFactory factory = TransformerFactory.newInstance();\n Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));\n\n transformer.setParameter(\"versionParam\", \"1.0\");\n\n Source src = new StreamSource(xmlfile);\n\n Result res = new SAXResult(fop.getDefaultHandler());\n\n transformer.transform(src, res);\n\n} finally {\n out.close();\n}\n\nSystem.out.println(\"Success!\");\n" }, { "answer_id": 41049405, "author": "Levent Divilioglu", "author_id": 3128926, "author_profile": "https://Stackoverflow.com/users/3128926", "pm_score": 5, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-stylesheet type=\"application/xml\"?>\n<users-data>\n <header-section>\n <data-type id=\"019\">User Bill Data</data-type>\n <process-date>Thursday December 9 2016 00:04:29</process-date>\n </header-section>\n <user-bill-data>\n <full-name>John Doe</full-name>\n <postal-code>34239</postal-code>\n <national-id>123AD329248</national-id>\n <price>17.84</price>\n </user-bill-data>\n <user-bill-data>\n <full-name>Michael Doe</full-name>\n <postal-code>54823</postal-code>\n <national-id>942KFDSCW322</national-id>\n <price>34.50</price>\n </user-bill-data>\n <user-bill-data>\n <full-name>Jane Brown</full-name>\n <postal-code>66742</postal-code>\n <national-id>ABDD324KKD8</national-id>\n <price>69.36</price>\n </user-bill-data>\n</users-data>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:fo=\"http://www.w3.org/1999/XSL/Format\" version=\"1.0\">\n <xsl:output encoding=\"UTF-8\" indent=\"yes\" method=\"xml\" standalone=\"no\" omit-xml-declaration=\"no\"/>\n <xsl:template match=\"users-data\">\n <fo:root language=\"EN\">\n <fo:layout-master-set>\n <fo:simple-page-master master-name=\"A4-portrail\" page-height=\"297mm\" page-width=\"210mm\" margin-top=\"5mm\" margin-bottom=\"5mm\" margin-left=\"5mm\" margin-right=\"5mm\">\n <fo:region-body margin-top=\"25mm\" margin-bottom=\"20mm\"/>\n <fo:region-before region-name=\"xsl-region-before\" extent=\"25mm\" display-align=\"before\" precedence=\"true\"/>\n </fo:simple-page-master>\n </fo:layout-master-set>\n <fo:page-sequence master-reference=\"A4-portrail\">\n <fo:static-content flow-name=\"xsl-region-before\">\n <fo:table table-layout=\"fixed\" width=\"100%\" font-size=\"10pt\" border-color=\"black\" border-width=\"0.4mm\" border-style=\"solid\">\n <fo:table-column column-width=\"proportional-column-width(20)\"/>\n <fo:table-column column-width=\"proportional-column-width(45)\"/>\n <fo:table-column column-width=\"proportional-column-width(20)\"/>\n <fo:table-body>\n <fo:table-row>\n <fo:table-cell text-align=\"left\" display-align=\"center\" padding-left=\"2mm\">\n <fo:block>\n Bill Id:<xsl:value-of select=\"header-section/data-type/@id\"/>\n , Date: <xsl:value-of select=\"header-section/process-date\"/>\n </fo:block>\n </fo:table-cell>\n <fo:table-cell text-align=\"center\" display-align=\"center\">\n <fo:block font-size=\"150%\">\n <fo:basic-link external-destination=\"http://www.example.com\">XXX COMPANY</fo:basic-link>\n </fo:block>\n <fo:block space-before=\"3mm\"/>\n </fo:table-cell>\n <fo:table-cell text-align=\"right\" display-align=\"center\" padding-right=\"2mm\">\n <fo:block>\n <xsl:value-of select=\"data-type\"/>\n </fo:block>\n <fo:block display-align=\"before\" space-before=\"6mm\">Page <fo:page-number/> of <fo:page-number-citation ref-id=\"end-of-document\"/>\n </fo:block>\n </fo:table-cell>\n </fo:table-row>\n </fo:table-body>\n </fo:table>\n </fo:static-content>\n <fo:flow flow-name=\"xsl-region-body\" border-collapse=\"collapse\" reference-orientation=\"0\">\n <fo:block>MONTHLY BILL REPORT</fo:block>\n <fo:table table-layout=\"fixed\" width=\"100%\" font-size=\"10pt\" border-color=\"black\" border-width=\"0.35mm\" border-style=\"solid\" text-align=\"center\" display-align=\"center\" space-after=\"5mm\">\n <fo:table-column column-width=\"proportional-column-width(20)\"/>\n <fo:table-column column-width=\"proportional-column-width(30)\"/>\n <fo:table-column column-width=\"proportional-column-width(25)\"/>\n <fo:table-column column-width=\"proportional-column-width(50)\"/>\n <fo:table-body font-size=\"95%\">\n <fo:table-row height=\"8mm\">\n <fo:table-cell>\n <fo:block>Full Name</fo:block>\n </fo:table-cell>\n <fo:table-cell>\n <fo:block>Postal Code</fo:block>\n </fo:table-cell>\n <fo:table-cell>\n <fo:block>National ID</fo:block>\n </fo:table-cell>\n <fo:table-cell>\n <fo:block>Payment</fo:block>\n </fo:table-cell>\n </fo:table-row>\n <xsl:for-each select=\"user-bill-data\">\n <fo:table-row>\n <fo:table-cell>\n <fo:block>\n <xsl:value-of select=\"full-name\"/>\n </fo:block>\n </fo:table-cell>\n <fo:table-cell>\n <fo:block>\n <xsl:value-of select=\"postal-code\"/>\n </fo:block>\n </fo:table-cell>\n <fo:table-cell>\n <fo:block>\n <xsl:value-of select=\"national-id\"/>\n </fo:block>\n </fo:table-cell>\n <fo:table-cell>\n <fo:block>\n <xsl:value-of select=\"price\"/>\n </fo:block>\n </fo:table-cell>\n </fo:table-row>\n </xsl:for-each>\n </fo:table-body>\n </fo:table>\n <fo:block id=\"end-of-document\">\n <fo:instream-foreign-object>\n <svg width=\"200mm\" height=\"150mm\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M153 334\nC153 334 151 334 151 334\nC151 339 153 344 156 344\nC164 344 171 339 171 334\nC171 322 164 314 156 314\nC142 314 131 322 131 334\nC131 350 142 364 156 364\nC175 364 191 350 191 334\nC191 311 175 294 156 294\nC131 294 111 311 111 334\nC111 361 131 384 156 384\nC186 384 211 361 211 334\nC211 300 186 274 156 274\" style=\"fill:yellow;stroke:red;stroke-width:2\"/>\n </svg>\n </fo:instream-foreign-object>\n </fo:block>\n </fo:flow>\n </fo:page-sequence>\n </fo:root>\n </xsl:template>\n</xsl:stylesheet>\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.levent.fopdemo</groupId>\n <artifactId>apache-fop-demo</artifactId>\n <packaging>jar</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>apache-fop-demo</name>\n <url>http://maven.apache.org</url>\n\n <properties>\n <fop.version>2.1</fop.version>\n </properties>\n\n <dependencies> \n <!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/fop -->\n <dependency>\n <groupId>org.apache.xmlgraphics</groupId>\n <artifactId>fop</artifactId>\n <version>${fop.version}</version>\n </dependency>\n </dependencies>\n\n <build>\n <finalName>Apache Fop Demo</finalName>\n\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.5.1</version>\n <configuration>\n <source>1.8</source>\n <target>1.8</target>\n </configuration>\n </plugin>\n </plugins>\n </build>\n</project>\n package com.levent.fopdemo;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.OutputStream;\n\nimport javax.xml.transform.Result;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.sax.SAXResult;\nimport javax.xml.transform.stream.StreamSource;\n\nimport org.apache.fop.apps.FOPException;\nimport org.apache.fop.apps.FOUserAgent;\nimport org.apache.fop.apps.Fop;\nimport org.apache.fop.apps.FopFactory;\nimport org.apache.fop.apps.MimeConstants;\n\npublic class PdfGenerationDemo \n{\n public static final String RESOURCES_DIR;\n public static final String OUTPUT_DIR;\n\n static {\n RESOURCES_DIR = \"src//main//resources//\";\n OUTPUT_DIR = \"src//main//resources//output//\";\n }\n\n public static void main( String[] args )\n {\n try {\n convertToPDF();\n } catch (FOPException | IOException | TransformerException e) {\n e.printStackTrace();\n }\n }\n\n public static void convertToPDF() throws IOException, FOPException, TransformerException {\n // the XSL FO file\n File xsltFile = new File(RESOURCES_DIR + \"//template.xsl\");\n // the XML file which provides the input\n StreamSource xmlSource = new StreamSource(new File(RESOURCES_DIR + \"//data.xml\"));\n // create an instance of fop factory\n FopFactory fopFactory = FopFactory.newInstance(new File(\".\").toURI());\n // a user agent is needed for transformation\n FOUserAgent foUserAgent = fopFactory.newFOUserAgent();\n // Setup output\n OutputStream out;\n out = new java.io.FileOutputStream(OUTPUT_DIR + \"//output.pdf\");\n\n try {\n // Construct fop with desired output format\n Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);\n\n // Setup XSLT\n TransformerFactory factory = TransformerFactory.newInstance();\n Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));\n\n // Resulting SAX events (the generated FO) must be piped through to\n // FOP\n Result res = new SAXResult(fop.getDefaultHandler());\n\n // Start XSLT transformation and FOP processing\n // That's where the XML is first transformed to XSL-FO and then\n // PDF is created\n transformer.transform(xmlSource, res);\n } finally {\n out.close();\n }\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
212,587
<p>I’m having an issue where a drop down list in IE 6/7 is behaving as such:</p> <p><img src="https://i488.photobucket.com/albums/rr249/djfloetic/ie7.jpg" alt="alt text"></p> <p>You can see that the drop down <code>width</code> is not wide enough to display the whole text without expanding the overall drop down list.</p> <p>However in Firefox, there is no issue as it <code>expands the width</code> accordingly. This is the behaviour we want in IE 6/7:</p> <p><img src="https://i488.photobucket.com/albums/rr249/djfloetic/firefox.jpg" alt="alt text"></p> <p>We’ve looked at various ways to utilize the <code>onfocus, onblur, onchange, keyboard and mouse events</code> to attempt to solve the problem but still some issues.</p> <p>I was wondering if anyone has solved this issue in IE 6/7 without using any toolkits/frameworks (YUI, Ext-JS, jQuery, etc…).</p>
[ { "answer_id": 212637, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": -1, "selected": false, "text": "private void BindData()\n {\n List<Foo> list = new List<Foo>();\n list.Add(new Foo(\"Hello\"));\n list.Add(new Foo(\"bye bye\"));\n list.Add(new Foo(\"this is a reall asd a s das d asd as da sf gfa sda sd asdasd a\"));\n\n ddl1.DataSource = list;\n ddl1.DataTextField = \"Text\"; \n ddl1.DataBind(); \n }\n" }, { "answer_id": 213936, "author": "Jack", "author_id": 24998, "author_profile": "https://Stackoverflow.com/users/24998", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n var MAX_WIDTH = 500; //the biggest width the select is allowed to be\n\n function biggestOption(elem) {\n var biggest = 0;\n for (var i=0;i<elem.options.length;i++) {\n if ( elem.options[i].innerHTML.length > biggest ) {\n biggest = elem.options[i].innerHTML.length;\n }\n }\n return roughPixelSize(biggest);\n }\n\n function roughPixelSize(charLength) {\n //this is far from perfect charLength to pixel\n //but it works for proof of concept\n roughSize = 30 + (charLength * 6);\n if (roughSize > MAX_WIDTH) {\n return MAX_WIDTH;\n } else {\n return roughSize;\n }\n }\n\n function resizeToBiggest(elem) {\n elem.style.width = biggestOption(elem);\n }\n\n function resizeToSelected(elem) {\n elem.style.width = roughPixelSize(elem.options[elem.selectedIndex].innerHTML.length);\n }\n\n</script>\n\n<select onmouseover=\"resizeToBiggest(this)\" style=\"width:70px\" onchange=\"resizeToSelected(this)\" onblur=\"resizeToSelected(this)\" >\n <option>test 1</option>\n <option>test 2</option>\n <option>test 3</option>\n <option>this is some really really realy long text</option>\n <option>test 4</option>\n <option>test 5</option>\n</select>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5853/" ]
212,596
<p>I'm currently doing some GUI testing on a ASP.net 2.0 application. The RDBMS is SQL Server 2005. The host is Win Server 2003 / IIS 6.0.</p> <p>I do not have the source code of the application because it was programmed by an external company who's not releasing the code.</p> <p>I've noticed that the application performs well when I restart IIS but after some testing, after I have opened and closed my browser for a couple of hours, the application starts to get slower and slower. I was wondering if this behaviour was due to a bad closing connection practice from the programmers : I'm suspecting an open connection leak on the database here.</p> <p>I guess the .Net garbage collector will eventually close them but... that can take a while, no?</p> <p>I've got SQL Server Management Studio and I do notice from the activity monitor that there are quite a few connections opened on the database.</p> <p>From all that's being said above, here are some questions related to the main question : </p> <ol> <li><p>Is there any way to know in SQL Server 2005 if connections are open because they're waiting to be used in a connection pool or if they're open because they are used by an application?</p></li> <li><p>Does somone know of good online/paper resources where I could learn how to use performance counters or some other kind of tools to help track down these kind of issues?</p></li> <li><p>If performance counters are the best solution, what are the variables that I should watch?</p></li> </ol>
[ { "answer_id": 12428235, "author": "user1617425", "author_id": 1617425, "author_profile": "https://Stackoverflow.com/users/1617425", "pm_score": 6, "selected": false, "text": "SELECT S.spid, login_time, last_batch, status, hostname, program_name, cmd,\n(\n select text from sys.dm_exec_sql_text(S.sql_handle)\n) as last_sql\nFROM sys.sysprocesses S\nwhere dbid > 0\nand DB_NAME(dbid) = '<my_database_name>'\nand loginame = '<my_application_login>'\norder by last_batch asc\n sys.sysprocesses" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2046272/" ]
212,603
<p>I'm trying to write some SQL that will delete files of type '.7z' that are older than 7 days.</p> <p>Here's what I've got that's not working:</p> <pre><code>DECLARE @DateString CHAR(8) SET @DateString = CONVERT(CHAR(8), DATEADD(d, -7, GETDATE()), 1) EXECUTE master.dbo.xp_delete_file 0, N'e:\Database Backups',N'7z', @DateString, 1 </code></pre> <p>I've also tried changing the '1' at the end to a '0'.</p> <p>This returns 'success', but the files aren't getting deleted.</p> <p>I'm using SQL Server 2005, Standard, w/SP2.</p>
[ { "answer_id": 212757, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "xp_delete_file" }, { "answer_id": 212834, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "xp_delete_file" }, { "answer_id": 212931, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 2, "selected": false, "text": "xp_cmdshell 'del <filename>'\n" }, { "answer_id": 529770, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "DECLARE @DeleteDate datetime\nSET @DeleteDate = DateAdd(day, -7, GetDate())\n\nEXECUTE master.sys.xp_delete_file\n0, -- FileTypeSelected (0 = FileBackup, 1 = FileReport)\nN'D:\\SQLbackups\\', -- folder path (trailing slash)\nN'bak', -- file extension which needs to be deleted (no dot)\n@DeleteDate, -- date prior which to delete\n1 -- subfolder flag (1 = include files in first subfolder level, 0 = not)\n" }, { "answer_id": 26486818, "author": "Jivomir Yovkov", "author_id": 4165882, "author_profile": "https://Stackoverflow.com/users/4165882", "pm_score": 0, "selected": false, "text": "EXECUTE master.sys.xp_delete_file 0, -- FileTypeSelected (0 = FileBackup, 1 = FileReport)\n" }, { "answer_id": 35384431, "author": "user5923365", "author_id": 5923365, "author_profile": "https://Stackoverflow.com/users/5923365", "pm_score": 2, "selected": false, "text": "RESTORE HEADERONLY FROM DISK = N'<file path\\filename>.Bak'\nRESTORE VERIFYONLY FROM DISK = N'<file path\\filename>.bak'\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6624/" ]
212,604
<p>I have a function that is effectively a replacement for print, and I want to call it without parentheses, just like calling print.</p> <pre><code># Replace print $foo, $bar, "\n"; # with myprint $foo, $bar, "\n"; </code></pre> <p>In Perl, you can create subroutines with parameter templates and it allows exactly this behavior if you define a subroutine as</p> <pre><code>sub myprint(@) { ... } </code></pre> <p>Anything similar in PHP?</p>
[ { "answer_id": 5452710, "author": "Marcelo", "author_id": 679386, "author_profile": "https://Stackoverflow.com/users/679386", "pm_score": 2, "selected": false, "text": "echoh \"hello\";\n 'hello<br>\\n'.\n <?php\nconst PHP_BR_EOL = \"<br>\\n\";\necho \"Hello\" . PHP_BR_EOL;\n?>\n Hello<br>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8454/" ]
212,614
<p>Should a method that implements an interface method be annotated with <code>@Override</code>?</p> <p>The <a href="http://java.sun.com/javase/6/docs/api/java/lang/Override.html" rel="noreferrer">javadoc of the <code>Override</code> annotation</a> says: </p> <blockquote> <p>Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.</p> </blockquote> <p>I don't think that an interface is technically a superclass. Or is it?</p> <p><kbd><a href="https://stackoverflow.com/revisions/212614/5">Question Elaboration</a></kbd></p>
[ { "answer_id": 212624, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 9, "selected": true, "text": "class C {\n @Override\n public boolean equals(SomeClass obj){\n // code ...\n }\n}\n public boolean equals(Object obj)" }, { "answer_id": 213896, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 1, "selected": false, "text": "@Override" }, { "answer_id": 964567, "author": "Silent Warrior", "author_id": 87582, "author_profile": "https://Stackoverflow.com/users/87582", "pm_score": 4, "selected": false, "text": "@Override" }, { "answer_id": 8266820, "author": "GKelly", "author_id": 18744, "author_profile": "https://Stackoverflow.com/users/18744", "pm_score": 6, "selected": false, "text": "@Override equals(Object) equals(YourObject) @Override @Implements" }, { "answer_id": 22517730, "author": "spujia", "author_id": 4339042, "author_profile": "https://Stackoverflow.com/users/4339042", "pm_score": 2, "selected": false, "text": "@Override super.theOverridenMethod() @Interface" }, { "answer_id": 34366091, "author": "juanchito", "author_id": 2019874, "author_profile": "https://Stackoverflow.com/users/2019874", "pm_score": 3, "selected": false, "text": "@Override @Override @Implement" }, { "answer_id": 39740106, "author": "ZhaoGang", "author_id": 2830167, "author_profile": "https://Stackoverflow.com/users/2830167", "pm_score": 2, "selected": false, "text": "@Override @Implement @Override" }, { "answer_id": 54490813, "author": "Madhu", "author_id": 1981792, "author_profile": "https://Stackoverflow.com/users/1981792", "pm_score": 2, "selected": false, "text": "interface abstract @Override interface @Override abstract interface interface abstract interface @Override interface" }, { "answer_id": 70855508, "author": "smilyface", "author_id": 2086966, "author_profile": "https://Stackoverflow.com/users/2086966", "pm_score": 1, "selected": false, "text": "@override public interface Restaurant(){\n public boolean getBill();\n public BigDecimal payAmount();\n}\n\npublic interface Food() extends Restaurant{\n public boolean haveSomeFood();\n public boolean drinkWater();\n}\n\npublic class Hungry() implements Food{\n public boolean haveSomeFood(){}\n public boolean drinkWater(){}\n public boolean getBill(){}\n public BigDecimal payAmount(){}\n}\n Hungry Food Restaurant Food extends Restaurant @override @override @override" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565/" ]
212,645
<p>I have found an interesting issue in windows which allows me to cause the Windows clock (but not the hardware clocks) to run fast - as much as 8 seconds every minute. I am doing some background research to work out how Windows calculates and updates it's internal time (not how it syncs with an NTP servers). Any information anyone has or any documents you can point me to would be greatly appreciated!</p> <p>Also, if anyone knows how _ftime works please let me know.</p>
[ { "answer_id": 214347, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "_ftime() _ftime() %ProgramFiles%\\Microsoft Visual Studio <version>\\VC\\crt\\src\\ftime.c ftime64.c" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
212,657
<p>Within a stored procedure, another stored procedure is being called within a cursor. For every call, the SQL Management Studio results window is showing a result. The cursor loops over 100 times and at that point the results window gives up with an error. Is there a way I can stop the stored procedure within the cursor from outputting any results?</p> <pre><code> WHILE @@FETCH_STATUS = 0 BEGIN EXEC @RC = dbo.NoisyProc SELECT @RValue2 = 1 WHERE @@ROWCOUNT = 0 FETCH NEXT FROM RCursor INTO @RValue1, @RValue2 END </code></pre> <p>Thanks!</p>
[ { "answer_id": 212670, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 0, "selected": false, "text": "SET ROWCOUNT OFF\n/* the internal SP */\nSET ROWCOUNT ON\n" }, { "answer_id": 212833, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 5, "selected": true, "text": "create table #tmp (columns)\n\nwhile\n ...\n insert into #tmp exec @RC=dbo.NoisyProc\n ...\nend\ndrop table #tmp\n" }, { "answer_id": 213011, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 5, "selected": false, "text": "DECLARE @i int\nSET @i = 1\nWHILE (@i <= 100)\n BEGIN\n SELECT @i as Iteration\n SET @i = @i + 1\n END\n" }, { "answer_id": 213328, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 1, "selected": false, "text": "DECLARE @I INT\nSET @I=0\nWHILE @I<200 BEGIN\n SELECT * FROM INFORMATION_SCHEMA.TABLES\n SET @I = @I + 1\nEND\n" }, { "answer_id": 4994183, "author": "Estanislao", "author_id": 444920, "author_profile": "https://Stackoverflow.com/users/444920", "pm_score": 4, "selected": false, "text": "SET NOCOUNT ON" }, { "answer_id": 62730206, "author": "Todd Albers", "author_id": 13508595, "author_profile": "https://Stackoverflow.com/users/13508595", "pm_score": 1, "selected": false, "text": "DROP TABLE IF EXISTS TestTable\nGO\nCREATE TABLE TestTable (ID INT, TestText VARCHAR (40))\nGO\n\n-- Get the Original NOCOUNT setting and save it to @OriginalNoCountSettingIsOn\nDECLARE @options INT\nSET @options = @@OPTIONS\nDECLARE @OriginalNoCountSettingIsOn AS bit\nSET @OriginalNoCountSettingIsOn = IIF(( (512 & @@OPTIONS) = 512 ),1,0)\n\n-- Now set NOCOUNT ON to suppress result output returned from INSERTS \n-- Note - this does not affect @@ROWCOUNT values from being set \nSET NOCOUNT ON -- <---- Try running script with SET NOCOUNT ON and SET NOCOUNT OFF to See difference\n\nINSERT INTO TestTable (ID, TestText)\nVALUES (0, 'Test Row 1')\n\nINSERT INTO TestTable (ID, TestText)\nVALUES (0, 'Test Row 2'),\n (0, 'Test Row 3'),\n (0, 'Test Row 4')\n\nINSERT INTO TestTable (ID, TestText)\nVALUES (0, 'Test Row 5')\n\n/*Now set NOCOUNT back to original setting*/\nIF @OriginalNoCountSettingIsOn = 1 \nBEGIN\n SET NOCOUNT ON\nEND\nELSE\nBEGIN\n SET NOCOUNT OFF\nEND \n\nDROP TABLE IF EXISTS TestTable\nGO\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
212,689
<p>I have implemented a pretty simple picture viewer that will allow the user to browse through a collection of images. They are loaded from the Internet, and displayed on the device through a <code>UIImageView</code> object. Something like this:</p> <pre><code>UIImage *image = [[UIImage alloc] initWithData:imageData]; [img setImage:image]; </code></pre> <p><code>imageData</code> is an instance of <code>NSData</code> that I use to load the contents of the image from an URL, and <code>img</code> is the <code>UIImageView</code> instance.</p> <p>It all works well, but the new image replaces the one being displayed before without any transitions, and I was wondering if there is an easy way to do a good animation transition to improve the user experience.</p> <p>Any idea how to do this? Code samples would be very appreciated.</p>
[ { "answer_id": 223423, "author": "Jamey McElveen", "author_id": 30099, "author_profile": "https://Stackoverflow.com/users/30099", "pm_score": 1, "selected": false, "text": "RootViewController.m UIViewAnimationTransitionFlipFromLeft UIViewAnimationTransitionFlipFromRight UIViewAnimationTransitionCurlUp UIViewAnimationTransitionCurlDown" }, { "answer_id": 353724, "author": "Rob", "author_id": 386102, "author_profile": "https://Stackoverflow.com/users/386102", "pm_score": 2, "selected": false, "text": "typedef enum {\n UIViewAnimationTransitionNone,\n UIViewAnimationTransitionFlipFromLeft,\n UIViewAnimationTransitionFlipFromRight,\n UIViewAnimationTransitionCurlUp,\n UIViewAnimationTransitionCurlDown,\n } UIViewAnimationTransition;\n CGContextRef context = UIGraphicsGetCurrentContext();\n[UIView beginAnimations:nil context:context];\n\n[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:[self superview] cache:YES];\n\n// -- These don't work on the simulator and the curl up will turn into a fade -- //\n//[UIView setAnimationTransition: UIViewAnimationTransitionCurlUp forView:[self superview] cache:YES];\n//[UIView setAnimationTransition: UIViewAnimationTransitionCurlDown forView:[self superview] cache:YES];\n\n[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];\n[UIView setAnimationDuration:1.0];\n\n// Below assumes you have two subviews that you're trying to transition between\n[[self superview] exchangeSubviewAtIndex:0 withSubviewAtIndex:1];\n[UIView commitAnimations];\n" }, { "answer_id": 967816, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " UIImage *img = [params objectAtIndex:0]; // the right image\nUIImageView *view = [params objectAtIndex:1]; // the base\n\nUIImageView *tmp = [[UIImageView alloc] initWithImage:view.image]; // the one which will use to fade\ntmp.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);\n[view addSubview:tmp];\n\nview.image = img;\nfloat r = img.size.width / img.size.height;\nfloat h = view.frame.size.height;\nfloat w = h * r;\nfloat x = view.center.x - w/2;\nfloat y = view.frame.origin.y;\n\n[UIView beginAnimations:nil context:nil];\n[UIView setAnimationDuration:1.0];\n\ntmp.alpha = 0;\nview.frame = CGRectMake(x, y, w, h);\n\n[UIView commitAnimations];\n\n[tmp performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:1.5];\n[tmp performSelector:@selector(release) withObject:nil afterDelay:2];\n" }, { "answer_id": 3545591, "author": "Raj Pawan Gumdal", "author_id": 260665, "author_profile": "https://Stackoverflow.com/users/260665", "pm_score": 4, "selected": false, "text": "#import <UIKit/UIKit.h>\n\n\n@interface TransitionImageView : UIImageView \n{\n UIImageView *mOriginalImageViewContainerView;\n UIImageView *mIntermediateTransitionView;\n}\n@property (nonatomic, retain) UIImageView *originalImageViewContainerView;\n@property (nonatomic, retain) UIImageView *intermediateTransitionView;\n\n#pragma mark -\n#pragma mark Animation methods\n-(void)setImage:(UIImage *)inNewImage withTransitionAnimation:(BOOL)inAnimation;\n\n@end\n #import \"TransitionImageView.h\"\n\n#define TRANSITION_DURATION 1.0\n\n@implementation TransitionImageView\n@synthesize intermediateTransitionView = mIntermediateTransitionView;\n@synthesize originalImageViewContainerView = mOriginalImageViewContainerView;\n\n- (id)initWithFrame:(CGRect)frame {\n if ((self = [super initWithFrame:frame])) {\n // Initialization code\n }\n return self;\n}\n\n/*\n// Only override drawRect: if you perform custom drawing.\n// An empty implementation adversely affects performance during animation.\n- (void)drawRect:(CGRect)rect {\n // Drawing code\n}\n*/\n\n- (void)dealloc \n{\n [self setOriginalImageViewContainerView:nil];\n [self setIntermediateTransitionView:nil];\n [super dealloc];\n}\n\n#pragma mark -\n#pragma mark Animation methods\n-(void)setImage:(UIImage *)inNewImage withTransitionAnimation:(BOOL)inAnimation\n{\n if (!inAnimation)\n {\n [self setImage:inNewImage];\n }\n else\n {\n // Create a transparent imageView which will display the transition image.\n CGRect rectForNewView = [self frame];\n rectForNewView.origin = CGPointZero;\n UIImageView *intermediateView = [[UIImageView alloc] initWithFrame:rectForNewView];\n [intermediateView setBackgroundColor:[UIColor clearColor]];\n [intermediateView setContentMode:[self contentMode]];\n [intermediateView setClipsToBounds:[self clipsToBounds]];\n [intermediateView setImage:inNewImage];\n\n // Create the image view which will contain original imageView's contents:\n UIImageView *originalView = [[UIImageView alloc] initWithFrame:rectForNewView];\n [originalView setBackgroundColor:[UIColor clearColor]];\n [originalView setContentMode:[self contentMode]];\n [originalView setClipsToBounds:[self clipsToBounds]];\n [originalView setImage:[self image]];\n\n // Remove image from the main imageView and add the originalView as subView to mainView:\n [self setImage:nil];\n [self addSubview:originalView];\n\n // Add the transparent imageView as subview whose dimensions are same as the view which holds it.\n [self addSubview:intermediateView];\n\n // Set alpha value to 0 initially:\n [intermediateView setAlpha:0.0];\n [originalView setAlpha:1.0];\n [self setIntermediateTransitionView:intermediateView];\n [self setOriginalImageViewContainerView:originalView];\n [intermediateView release];\n [originalView release];\n\n // Begin animations:\n [UIView beginAnimations:@\"ImageViewTransitions\" context:nil];\n [UIView setAnimationDuration:(double)TRANSITION_DURATION];\n [UIView setAnimationDelegate:self];\n [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];\n [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];\n [[self intermediateTransitionView] setAlpha:1.0];\n [[self originalImageViewContainerView] setAlpha:0.0];\n [UIView commitAnimations];\n }\n}\n\n-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context\n{\n // Reset the alpha of the main imageView\n [self setAlpha:1.0];\n\n // Set the image to the main imageView:\n [self setImage:[[self intermediateTransitionView] image]];\n\n [[self intermediateTransitionView] removeFromSuperview];\n [self setIntermediateTransitionView:nil];\n\n [[self originalImageViewContainerView] removeFromSuperview];\n [self setOriginalImageViewContainerView:nil];\n}\n\n@end\n -setImage -setImage:withTransitionAnimation: [super setImage:] [self setImage:] -setImage:withTransitionAnimation:" }, { "answer_id": 5689021, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 3, "selected": false, "text": "[UIView \n animateWithDuration:0.2 \n delay:0 \n options:UIViewAnimationCurveEaseOut\n animations:^{\n self.view0.alpha = 0;\n self.view1.alpha = 1;\n }\n completion:^(BOOL finished){\n view0.hidden = YES;\n }\n];\n" }, { "answer_id": 24158507, "author": "Manab Kumar Mal", "author_id": 2905967, "author_profile": "https://Stackoverflow.com/users/2905967", "pm_score": 2, "selected": false, "text": "imgvw.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@\"Your Image name as string\"]]];\nCATransition *transition = [CATransition animation];\ntransition.duration = 1.0f;\ntransition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];\ntransition.type = kCATransitionFade;\n[imgvw.layer addAnimation:transition forKey:nil];\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,697
<p>Every class that wants to use java.util.logging generally needs to declare a logger like this:</p> <pre><code>public class MyClass { private static Logger _log = Logger.getLogger(MyClass.class.getName()); } </code></pre> <p>How do you avoid this MyClass.class.getName() boilerplate code?</p>
[ { "answer_id": 212750, "author": "Ogre Psalm33", "author_id": 13140, "author_profile": "https://Stackoverflow.com/users/13140", "pm_score": 0, "selected": false, "text": "public class MyClass {\n private static Logger _log = Logger.getLogger(MyClass.class);\n}\n public class MyBase {\n protected static Logger _log = Logger.getLogger(MyClass.class);\n}\n\npublic class MyClass extends MyBase {\n ....\n _log.info(\"Stuff....\");\n}\n" }, { "answer_id": 212753, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": -1, "selected": false, "text": "public class SomeBaseClass\n{\n protected Logger logger = Logger.getLogger(getClass());\n}\n\npublic class SubClass extends SomeBaseClass\n{\n public void doit() { logger.debug(\"doit!!!!\"); }\n}\n" }, { "answer_id": 212754, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "private static final Logger log = Logs.log;\n" }, { "answer_id": 212904, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": true, "text": "${:import(org.apache.log4j.Logger)}\nprivate final static Logger log = Logger.getLogger(${enclosing_type}.class);\n${cursor}\n logger Ctrl+Space Enter" }, { "answer_id": 213144, "author": "Snowtoad", "author_id": 13068, "author_profile": "https://Stackoverflow.com/users/13068", "pm_score": 2, "selected": false, "text": "public class LoggingService {\n\n/**\n * A log for informational messages.\n */\nstatic private Logger infoLog;\n\n/**\n * A log for data access messages.\n */\nstatic private Logger dataAccessLog;\n\n/**\n * A log for debug messages.\n */\nstatic private Logger debugLog;\n\n/**\n * A log for error messages.\n */\nstatic private Logger errorLog;\n\n/**\n * A log for all XML related messages.\n */\nstatic private Logger xmlLog;\n\n/**\n * A log for all trace messages.\n */\nstatic private Logger traceLog;\n\n/**\n * A log for all warning messages.\n */\nstatic private Logger warnLog;\n\nstatic {\n\n //This is the bootstrap for the logging service.\n //Setup each logger\n infoLog = Logger.getLogger(\"com.company.logging.info\");\n dataAccessLog = Logger.getLogger(\"com.company.logging.dataaccess\");\n debugLog = Logger.getLogger(\"com.company.logging.debug\");\n errorLog = Logger.getLogger(\"com.company.logging.error\");\n xmlLog = Logger.getLogger(\"com.company.logging.xml\");\n traceLog = Logger.getLogger(\"com.company.logging.trace\");\n warnLog = Logger.getLogger(\"com.company.logging.warn\");\n\n // This must be set so isErrorEnabled() will work.\n errorLog.setLevel(Level.ERROR);\n warnLog.setLevel(Level.WARN);\n}\nstatic public void logDataAccess(String pMessage) {\n dataAccessLog.info(pMessage);\n}\n\nstatic public void logInfo(String pMessage) {\n infoLog.info(pMessage);\n}\n\nstatic public void logDebug(String pMessage) {\n debugLog.debug(pMessage);\n}\n\nstatic public void logTrace(String pMessage) {\n traceLog.debug(pMessage);\n}\n\nstatic public void logWarn(String pMessage) {\n warnLog.warn(pMessage);\n}\n\nstatic public void logError(String pMessage) {\n errorLog.error(pMessage);\n}\n\nstatic public void logError(String pMessage, Throwable pThrowable) {\n errorLog.error(pMessage, pThrowable);\n}\n\nstatic public void logXml(String pMessage, XmlBean pContainer) {\n\n if (!xmlLog.isInfoEnabled()) return;\n\n xmlLog.info(pMessage + \" : \" + JAXBHelper.marshal(pContainer));\n}\n\nstatic public boolean isInfoEnabled() {\n return infoLog.isInfoEnabled();\n}\n\nstatic public boolean isDataAccessEnabled() {\n return dataAccessLog.isInfoEnabled();\n}\n\nstatic public boolean isDebugEnabled() {\n return debugLog.isDebugEnabled();\n}\n\nstatic public boolean isErrorEnabled() {\n if (errorLog.getLevel().toInt() >= Level.ERROR_INT) {\n return true;\n }\n return false;\n}\n\nstatic public boolean isTraceEnabled() {\n return traceLog.isDebugEnabled();\n}\n\nstatic public boolean isXmlEnabled() {\n return xmlLog.isInfoEnabled();\n}\n\nstatic public boolean isWarnEnabled() {\n return warnLog.isEnabledFor(Level.WARN);\n}\n" }, { "answer_id": 23865539, "author": "Alireza Fattahi", "author_id": 2648077, "author_profile": "https://Stackoverflow.com/users/2648077", "pm_score": 1, "selected": false, "text": " @Slf4j\n public class LogExample {\n }\n public class LogExample {\n private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);\n }\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28604/" ]
212,705
<p>I have a <code>&lt;div&gt;</code> that I want to be on a line by itself. According to <a href="http://www.w3schools.com/Css/pr_class_clear.asp" rel="nofollow noreferrer">W3Schools</a>, this rule:</p> <pre><code>div.foo { clear: both; } </code></pre> <p>...should mean this:</p> <blockquote> <p>"No floating elements allowed on either the left or the right side."</p> </blockquote> <p>However, if I float two <code>&lt;div&gt;</code> elements left, and apply the rule above to the first one, the second one does not budge.</p> <p>On the other hand, if I apply <code>"clear: left"</code> to the second <code>&lt;div&gt;</code>, it moves down to the next line. This is my normal approach, but I don't understand why I have to do it like this.</p> <p>Is the W3Schools description above poorly stated, or am I missing something? <strong>Is a clearing rule only able to move the element to which it is applied?</strong></p> <h2>Answer</h2> <p>Thanks Michael S and John D for the good explanations. Warren pointed to <a href="http://www.w3.org/TR/REC-CSS2" rel="nofollow noreferrer">the CSS2 spec</a>, and that's where I found this answer (emphasis mine):</p> <blockquote> <p>This property indicates which sides of an element's box(es) may not be adjacent to an <strong>earlier</strong> floating box.</p> </blockquote> <p>So: <code>clear</code> only affects the position of the element to which it is applied, relative to elements that appear before it the code.</p> <p>Disappointing that I can't tell my <code>&lt;div&gt;</code> to make other divs move down, but them's the breaks. :)</p>
[ { "answer_id": 212721, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "float: left;\nclear: right;\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ]
212,706
<p>What is the best way to reset a PIC18 using C code with the HiTech Pic18 C compiler?</p> <p>Edit:</p> <p>I am currenlty using</p> <pre><code>void reset() { #asm reset #endasm } </code></pre> <p>but there must be a better way</p>
[ { "answer_id": 59441046, "author": "Dan1138", "author_id": 10085080, "author_profile": "https://Stackoverflow.com/users/10085080", "pm_score": 1, "selected": false, "text": "/*\n * File: main.c\n * Author: dan1138\n * Target: PIC18F45K20\n * Compiler: XC8 v2.05\n *\n * PIC18F46K20\n * +---------+ +---------+ +----------+ +----------+\n * <> 1 : RC7/RX : -- 12 : NC : <> 23 : RA4 : -- 34 : NC :\n * LED4 <> 2 : RD4 : -- 13 : NC : <> 24 : RA5 : 32.768KHz -> 35 : RC1/SOSI :\n * LED5 <> 3 : RD5 : <> 14 : RB4 : <> 25 : RE0 : <> 36 : RC2 :\n * LED6 <> 4 : RD6 : <> 15 : RB5/PGM : <> 26 : RE1 : <> 37 : RC3 :\n * GND -> 5 : VSS : PGC <> 16 : RB6/PGC : <> 27 : RE2 : LED0 <> 38 : RD0 :\n * 3v3 -> 6 : VDD : PGD <> 17 : RB7/PGD : 3v3 -> 28 : VDD : LED1 <> 39 : RD1 :\n * SW1 <> 7 : RB0/INT : VPP -> 18 : RE3/VPP : GND -> 29 : VSS : LED2 <> 40 : RD2 :\n * <> 8 : RB1 : POT <> 19 : RA0/AN0 : 4MHz -> 30 : RA7/OSC1 : LED3 <> 41 : RD3 :\n * <> 9 : RB2 : <> 20 : RA1 : 4MHz <- 31 : RA6/OSC2 : <> 42 : RC4 :\n * <> 10 : RB3 : <> 21 : RA2 : 32.767KHz <- 32 : RC0/SOSO : <> 43 : RC5 :\n * LED7 <> 11 : RD7 : <> 22 : RA3 : -- 33 : NC : <> 44 : RC6/TX :\n * +---------+ +---------+ +----------+ +----------+\n * TQFP-44\n *\n *\n * Created on December 21, 2019, 2:26 PM\n */\n\n/* Target specific configuration words */\n#pragma config FOSC = INTIO67, FCMEN = OFF\n#pragma config IESO = OFF, PWRT = OFF, BOREN = SBORDIS, BORV = 18\n#pragma config WDTEN = OFF, WDTPS = 32768, CCP2MX = PORTC, PBADEN = OFF\n#pragma config LPT1OSC = ON, HFOFST = ON\n#pragma config MCLRE = ON, STVREN = ON, LVP = OFF, XINST = OFF\n#pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF\n#pragma config CPB = OFF, CPD = OFF\n#pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF\n#pragma config WRTC = OFF, WRTB = OFF, WRTD = OFF\n#pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF\n#pragma config EBTRB = OFF\n\n/* Target specific definitions for special function registers */\n#include <xc.h>\n\n/* Declare the system oscillator frequency setup by the code */\n#define _XTAL_FREQ (4000000UL)\n\n/* reset instruction */\nvoid ResetMethod_1(void)\n{\n asm(\" reset\");\n}\n\n/* long jump to absolute address zero */\nvoid ResetMethod_2(void)\n{\n INTCON = 0;\n asm(\" pop\\n ljmp 0\");\n}\n\n/* return to absolute address zero */\nvoid ResetMethod_3(void)\n{\n INTCON = 0;\n asm(\" clrf TOSU\\n clrf TOSH\\n clrf TOSL\\n\");\n}\n\n/* provoke stackoverflow reset */\nvoid ResetMethod_4(void)\n{\n INTCON = 0;\n while (1) \n {\n asm(\" push\\n\");\n }\n}\n\n/* provoke stackunderflow reset */\nvoid ResetMethod_5(void)\n{\n INTCON = 0;\n STKPTR = 0;\n}\n\n/* clear the program counter */\nvoid ResetMethod_6(void)\n{\n INTCON = 0;\n asm(\" clrf PCLATU\\n clrf PCLATH\\n clrf PCL\\n\");\n}\n\nvoid main(void)\n{\n INTCON = 0; /* Disable all interrupt sources */\n PIE1 = 0;\n PIE2 = 0;\n INTCON3bits.INT1IE = 0;\n INTCON3bits.INT2IE = 0;\n\n OSCCON = 0x50; /* set internal oscillator to 4MHz */\n OSCTUNEbits.TUN = 0; /* use factory calibration of internal oscillator */\n ANSEL = 0;\n ANSELH = 0;\n \n if(!RCONbits.nPOR)\n {\n RCONbits.nPOR = 1;\n LATD = 0;\n }\n \n TRISD = 0;\n /*\n * Application loop\n */\n while(1)\n {\n __delay_ms(500);\n if (LATDbits.LD0 == 0)\n {\n LATDbits.LD0 = 1;\n ResetMethod_1();\n }\n \n if (LATDbits.LD1 == 0)\n {\n LATDbits.LD1 = 1;\n ResetMethod_2();\n }\n\n if (LATDbits.LD2 == 0)\n {\n LATDbits.LD2 = 1;\n ResetMethod_3();\n }\n \n if (LATDbits.LD3 == 0)\n {\n LATDbits.LD3 = 1;\n ResetMethod_4();\n }\n\n if (LATDbits.LD4 == 0)\n {\n LATDbits.LD4 = 1;\n ResetMethod_5();\n }\n\n if (LATDbits.LD5 == 0)\n {\n LATDbits.LD5 = 1;\n ResetMethod_6();\n }\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ]
212,713
<p>Using subversion 1.5 I have branch B which was branched off of branch A. After doing work in both branches I go to merge changes from A into B (using <code>svn merge http://path/to/A</code> in the working directory of B) and get <code>svn: Target path does not exist</code>. What does this mean?</p>
[ { "answer_id": 15531404, "author": "dankuck", "author_id": 146786, "author_profile": "https://Stackoverflow.com/users/146786", "pm_score": 1, "selected": false, "text": " /---------\\\ntrunk -------+---+ +---\\\n \\-----------BOOM!\n /---------\\\ntrunk -------+---+ +---+-----\n \\---------/\n /---------\\\ntrunk -------+---+ +---+-------\n \\ \\---+--\n \\-------------/\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14481/" ]
212,715
<p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p> <pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); </code></pre> <p>but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both</p> <pre><code>f = os.open("\\\\.\\giveio", os.O_RDONLY) </code></pre> <p>and </p> <pre><code>f = os.open("//./giveio", os.O_RDONLY) </code></pre> <p>Why doesn't this do the same thing?</p> <p><strong>Edited</strong> to hopefully reduce confusion of ideas (thanks Will). I did verify that the device driver is running via the batch files that come with AVRdude.</p> <p><strong>Further edited</strong> to clarify SamB's bounty.</p>
[ { "answer_id": 214066, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "\\\\.\\DRIVERNAME\n" }, { "answer_id": 5870770, "author": "Grim", "author_id": 561323, "author_profile": "https://Stackoverflow.com/users/561323", "pm_score": 1, "selected": false, "text": "h = win32file.CreateFile\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28984/" ]
212,718
<p>The NUnit documentation doesn't tell me when to use a method with a <code>TestFixtureSetup</code> and when to do the setup in the constructor.</p> <pre><code>public class MyTest { private MyClass myClass; public MyTest() { myClass = new MyClass(); } [TestFixtureSetUp] public void Init() { myClass = new MyClass(); } } </code></pre> <p>Are there any good/bad practices about the <code>TestFixtureSetup</code> versus default constructor or isn't there any difference?</p>
[ { "answer_id": 212769, "author": "Sam Wessel", "author_id": 4734, "author_profile": "https://Stackoverflow.com/users/4734", "pm_score": 6, "selected": false, "text": "[SetUp] [TearDown] [TestFixtureSetUp] [TestFixtureTearDown] [TestFixtureSetUp]" }, { "answer_id": 213172, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 5, "selected": true, "text": "TestFixtureSetUp TestFixtureTearDown SetUp TearDown" }, { "answer_id": 830473, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "[TestFixtureSetUp]" }, { "answer_id": 1181456, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 2, "selected": false, "text": "[TestFixtureSetup]" }, { "answer_id": 3580745, "author": "Ergwun", "author_id": 177018, "author_profile": "https://Stackoverflow.com/users/177018", "pm_score": 4, "selected": false, "text": "[TestFixtureSetup] [TestFixture] [TestFixture(\"System.Data.SqlClient\",\n \"Server=(local)\\\\SQLEXPRESS;Initial Catalog=MyTestDatabase;Integrated Security=True;Pooling=False\"))]\n[TestFixture(\"System.Data.SQLite\", \"Data Source=MyTestDatabase.s3db\")])]\ninternal class MyDataAccessLayerIntegrationTests\n{\n MyDataAccessLayerIntegrationTests(\n string dataProvider,\n string connectionString)\n {\n ...\n }\n}\n" }, { "answer_id": 8817850, "author": "oderibas", "author_id": 470325, "author_profile": "https://Stackoverflow.com/users/470325", "pm_score": 4, "selected": false, "text": "[TestFixtureSetUp] TestFixtureSetUp" }, { "answer_id": 11011682, "author": "nonexistent myth", "author_id": 1453240, "author_profile": "https://Stackoverflow.com/users/1453240", "pm_score": -1, "selected": false, "text": "SetUp SetUp" }, { "answer_id": 35290105, "author": "Shankar S", "author_id": 2584363, "author_profile": "https://Stackoverflow.com/users/2584363", "pm_score": 2, "selected": false, "text": "[TestFixtureSetUp] [TestFixtureTearDown] [SetUp] [TearDown]" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376/" ]
212,734
<p>How do you automatically start a service after running an install from a Visual Studio Setup Project?</p> <p>I just figured this one out and thought I would share the answer for the general good. Answer to follow. I am open to other and better ways of doing this.</p>
[ { "answer_id": 212736, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 7, "selected": true, "text": "using System.ServiceProcess; \n\nclass ServInstaller : ServiceInstaller\n{\n protected override void OnCommitted(System.Collections.IDictionary savedState)\n {\n ServiceController sc = new ServiceController(\"YourServiceNameGoesHere\");\n sc.Start();\n }\n}\n" }, { "answer_id": 732740, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "private System.ServiceProcess.ServiceInstaller serviceInstaller1;\n\nprivate void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)\n{\n ServiceController sc = new ServiceController(\"YourServiceName\");\n sc.Start();\n}\n" }, { "answer_id": 769445, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 5, "selected": false, "text": "protected override void OnCommitted(System.Collections.IDictionary savedState)\n{\n new ServiceController(serviceInstaller1.ServiceName).Start();\n}\n" }, { "answer_id": 10531267, "author": "HeWillem", "author_id": 558133, "author_profile": "https://Stackoverflow.com/users/558133", "pm_score": 3, "selected": false, "text": "private void serviceInstallerService1_Committed(object sender, InstallEventArgs e)\n{\n var serviceInstaller = sender as ServiceInstaller;\n // Start the service after it is installed.\n if (serviceInstaller != null && serviceInstaller.StartType == ServiceStartMode.Automatic)\n {\n var serviceController = new ServiceController(serviceInstaller.ServiceName);\n serviceController.Start();\n }\n}\n" }, { "answer_id": 10661276, "author": "Jeffrey Roughgarden", "author_id": 381465, "author_profile": "https://Stackoverflow.com/users/381465", "pm_score": 2, "selected": false, "text": "using System.ComponentModel;\nusing System.Configuration.Install;\nusing System.ServiceProcess;\n\nnamespace FSWManager {\n [RunInstaller(true)]\n public partial class ProjectInstaller : Installer {\n public ProjectInstaller() {\n InitializeComponent();\n this.FSWServiceMgr.AfterInstall += FSWServiceMgr_AfterInstall;\n }\n\n static void FSWServiceMgr_AfterInstall(object sender, InstallEventArgs e) {\n new ServiceController(\"FSWServiceMgr\").Start();\n }\n }\n}\n" }, { "answer_id": 10762880, "author": "Keith", "author_id": 65775, "author_profile": "https://Stackoverflow.com/users/65775", "pm_score": 5, "selected": false, "text": "using System.ComponentModel;\nusing System.Configuration.Install;\nusing System.ServiceProcess;\n\nnamespace MyProject\n{\n [RunInstaller(true)]\n public partial class ProjectInstaller : Installer\n {\n public ProjectInstaller()\n {\n InitializeComponent();\n serviceInstaller1.AfterInstall += (sender, args) => new ServiceController(serviceInstaller1.ServiceName).Start();\n }\n }\n}\n serviceInstaller1 ServiceName" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
212,745
<p>I'm on OS X 10.5.5 (though it does not matter much I guess)</p> <p>I have a set of text files with fancy characters like double backquotes, ellipsises ("...") in one character etc. </p> <p>I need to convert these files to good old plain 7-bit ASCII, preferably without losing character meaning (that is, convert those ellipses to three periods, backquotes to usual "s etc.).</p> <p>Please advise some smart command-line (bash) tool/script to do that.</p>
[ { "answer_id": 212955, "author": "Josh Lee", "author_id": 19750, "author_profile": "https://Stackoverflow.com/users/19750", "pm_score": 3, "selected": true, "text": "#!/usr/bin/env python\nimport elinks\nimport sys\nfor line in sys.stdin:\n line = line.decode('utf-8')\n sys.stdout.write(line.encode('ASCII', 'elinks'))\n" }, { "answer_id": 212969, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "rename.pl" }, { "answer_id": 354969, "author": "glennkentwell", "author_id": 32795, "author_profile": "https://Stackoverflow.com/users/32795", "pm_score": 1, "selected": false, "text": " cat utf16file.txt |iconv -f UTF-16LE -t ASCII > asciifile.txt\n cat utf16file.txt | iconv -f UTF-16LE -t ASCII | hexdump -C \n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6236/" ]
212,748
<p>I wrote a savefile method to save an object to xml. But I am not sure how to test the method in NUnit. Do I need create a sample file manually and compare the string between the files? Are there any better ways to test the method?</p> <p>Thanks for your answer.</p>
[ { "answer_id": 212781, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 1, "selected": false, "text": "XmlDocument XmlDocument <FileList> <Cups> <Rifles>" }, { "answer_id": 212789, "author": "Krzysztof Kozmic", "author_id": 13163, "author_profile": "https://Stackoverflow.com/users/13163", "pm_score": 1, "selected": false, "text": "void Persist(XmlWriter writer);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28989/" ]
212,762
<p>I need generate <a href="https://stackoverflow.com/questions/27921/what-is-the-best-way-to-create-a-thumbnail-using-aspnet">thumbnails</a> for a bunch of jpegs (200,000+) but I want to make sure all of my thumbs have a equal height and width. However, I don't want to change the proportions of the image so I need to add empty space to the shorter dimension to "square it up". The empty space's background color is variable. </p> <p>Here's the code snippet I'm using to generate the thumbs. What's the best way to do the squaring?</p> <pre><code> Dim imgDest As System.Drawing.Bitmap = New Bitmap(ScaleWidth, ScaleHeight) imgDest.SetResolution(TARGET_RESOLUTION, TARGET_RESOLUTION) Dim grDest As Graphics = Graphics.FromImage(imgDest) grDest.DrawImage(SourceImage, 0, 0, imgDest.Width, imgDest.Height) </code></pre>
[ { "answer_id": 216042, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "imageWidth imageHeight thumbWidth thumbHeight imageRatio = imageWidth / imageHeight;\nthumbRatio = thumbWidth / thumbHeight;\n\nzoomFactor = imageRatio >= thumbRatio\n ? thumbWidth / imageWidth \n : thumbHeight / imageHeight;\n\ndestWidth = imageWidth * zoomFactor;\ndestHeight = imageHeight * zoomFactor;\n\ndrawImage(\n (thumbWidth - destWidth) >> 1,\n (thumbHeight - destHeight) >> 1,\n destWidth,\n destHeight);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796/" ]
212,763
<p>My Win form app doesn't seem to like FormsAuthentication, I'm totally new to hashing so any help to convert this would be very welcome. Thanks.</p> <pre><code>//Write hash protected TextBox tbPassword; protected Literal liHashedPassword; { string strHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(tbPassword.Text, "sha1"); liHashedPassword.Text = "Hashed Password is: " + strHashedPassword; } //read hash string strUserInputtedHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile( tbPassword.Text, "sha1"); if(strUserInputtedHashedPassword == GetUsersHashedPasswordUsingUserName(tbUserName.Text)) { // sign-in successful } else { // sign-in failed } </code></pre>
[ { "answer_id": 212822, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": false, "text": "using System.Security.Cryptography;\n\npublic static string EncodePasswordToBase64(string password)\n{ byte[] bytes = Encoding.Unicode.GetBytes(password);\n byte[] inArray = HashAlgorithm.Create(\"SHA1\").ComputeHash(bytes);\n return Convert.ToBase64String(inArray);\n} \n" }, { "answer_id": 212846, "author": "user28636", "author_id": 28636, "author_profile": "https://Stackoverflow.com/users/28636", "pm_score": 1, "selected": false, "text": "//step 1 and 2\nbyte[] data = System.Text.Encoding.Unicode.GetBytes(tbPassword.Text,);\nbyte[] result; \n\n//step 3\nSHA1 sha = new SHA1CryptoServiceProvider(); \nresult = sha.ComputeHash(data);\n\n//step 4\nstring storableHashResult = System.Text.Encoding.Unicode.ToString(result);\n\n//step 5\n // add your code here\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,797
<p>It seems</p> <pre><code>import Queue Queue.Queue().get(timeout=10) </code></pre> <p>is keyboard interruptible (ctrl-c) whereas</p> <pre><code>import Queue Queue.Queue().get() </code></pre> <p>is not. I could always create a loop;</p> <pre><code>import Queue q = Queue() while True: try: q.get(timeout=1000) except Queue.Empty: pass </code></pre> <p>but this seems like a strange thing to do.</p> <p>So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()?</p>
[ { "answer_id": 212975, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": true, "text": "Queue Condition threading Queue Queue def interruptable_get(self):\n while True:\n try:\n return self.get(timeout=1000)\n except Queue.Empty:\n pass\nQueue.interruptable_get = interruptable_get\n q.interruptable_get()\n interruptable_get(q)\n" }, { "answer_id": 216719, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 2, "selected": false, "text": "STOP = object()\n\ndef consumer(q):\n while True:\n x = q.get()\n if x is STOP:\n return\n consume(x)\n\ndef main()\n q = Queue()\n c=threading.Thread(target=consumer,args=[q])\n\n try:\n run_producer(q)\n except KeybordInterrupt:\n q.enqueue(STOP)\n c.join()\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2010/" ]
212,805
<pre><code>Object o = new Long[0] System.out.println( o.getClass().isArray() ) System.out.println( o.getClass().getName() ) Class ofArray = ??? </code></pre> <p>Running the first 3 lines emits;</p> <pre><code>true [Ljava.lang.Long; </code></pre> <p>How do I get ??? to be type long? I could parse the string and do a Class.forname(), but thats grotty. What's the easy way?</p>
[ { "answer_id": 212816, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 5, "selected": false, "text": "public Class<?> getComponentType()\n Class" }, { "answer_id": 212817, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 7, "selected": true, "text": "Class ofArray = o.getClass().getComponentType();\n public Class<?> getComponentType() Class null" }, { "answer_id": 212855, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 3, "selected": false, "text": "public <T> Class<T> testArray(T[] array) {\n return array.getClass().getComponentType();\n}\n Object maybeArray = ...\nClass<?> clazz = maybeArray.getClass();\nif (clazz.isArray()) {\n System.out.printf(\"Array of type %s\", clazz.getComponentType());\n} else {\n System.out.println(\"Not an array\");\n}\n String[] arr = {\"Daniel\", \"Chris\", \"Joseph\"};\narr.getClass().getComponentType(); // => java.lang.String\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
212,808
<p>I'm trying to find an efficient C++ interval tree implementation (mostly likely based on red black trees) without a viral or restrictive license. Any pointers to a clean lightweight standalone implementation? For the use case I have in mind, the set of intervals is known at the outset (there would be say a million) and I want to be able to quickly obtain a list of intervals that overlap a given interval. Thus the tree once built will not change -- just needs rapid queries.</p>
[ { "answer_id": 213308, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 2, "selected": false, "text": "std::map std::multimap std::set std::multiset std::map upper_bound() lower_bound()" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,821
<p>In this class for example, I want to force a limit of characters the first/last name can allow.</p> <pre><code>public class Person { public string FirstName { get; set; } public string LastName { get; set; } } </code></pre> <p>Is there a way to force the string limit restriction for the first or last name, so <strong>when the client serializes this</strong> before sending it to me, it would throw an error on their side if it violates the lenght restriction?</p> <p>Update: this needs to be identified and forced in the WSDL itself, and not after I've recieved the invalid data.</p>
[ { "answer_id": 212917, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "[ValidationSchema(\"person.xsd\")]\npublic class Person { /* ... */ }\n\n<!-- person.xsd -->\n\n<?xml version=\"1.0\"?>\n<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n\n <xsd:element name=\"Person\" type=\"PersonType\" />\n\n <xsd:simpleType name=\"NameString\">\n <xsd:restriction base=\"xsd:string\">\n <xsd:maxLength value=\"255\"/>\n </xsd:restriction>\n </xsd:simpleType>\n\n <xsd:complexType name=\"PersonType\">\n <xsd:sequence>\n <xsd:element name=\"FirstName\" type=\"NameString\" maxOccurs=\"1\"/>\n <xsd:element name=\"LastName\" type=\"NameString\" maxOccurs=\"1\"/>\n </xsd:sequence>\n </xsd:complexType>\n</xsd:schema>\n" }, { "answer_id": 5469051, "author": "Jason", "author_id": 681540, "author_profile": "https://Stackoverflow.com/users/681540", "pm_score": 4, "selected": false, "text": "using System.ComponentModel.DataAnnotations;\npublic class Person\n{\n [StringLength(255, ErrorMessage = \"Error\")]\n public string FirstName { get; set; }\n [StringLength(255, ErrorMessage = \"Error\")]\n public string LastName { get; set; }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/820/" ]
212,827
<p>I've been using Pydev/Eclipse to develop Google App Engine (GAE) applications but I've been unable to get the response/request objects from WebOb to have auto-completion. I used a <a href="http://code.google.com/appengine/articles/eclipse.html" rel="nofollow noreferrer">widely recommended tutorial</a> to get everything configured; auto-completion is working for everything else I've run into.</p> <p>As an example: if I type in "self." I get auto-completion for response and request; if I select one of those, say "response", and add a "." (bringing the full line to "self.response." thus far) I don't get any options - since the WebOb library is included, I would expect to get things like "out.write()" as an option.</p> <p>I'm including the following libraries into my Pydev project:</p> <ul> <li>C:\Program Files\Google\google_appengine </li> <li>C:\Program Files\Google\google_appengine\lib\django </li> <li>C:\Program Files\Google\google_appengine\lib\webob </li> <li>C:\Program Files\Google\google_appengine\lib\yaml\lib</li> </ul> <p>Any help would be much appreciated, thanks.</p>
[ { "answer_id": 2321588, "author": "Goyuix", "author_id": 243, "author_profile": "https://Stackoverflow.com/users/243", "pm_score": 0, "selected": false, "text": "os.pathsep.join(EXTRA_PATHS)\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/312043/" ]
212,839
<p>The test form generated by ASMX is pretty handy for testing operations. However, there is no apparent way to include SOAP headers.</p> <p>How can you test your headers without programming a client to use the service?</p>
[ { "answer_id": 276501, "author": "Austin", "author_id": 32854, "author_profile": "https://Stackoverflow.com/users/32854", "pm_score": 1, "selected": false, "text": "// Set SOAP Message\nstring msg = \"<?xml version='1.0' encoding='UTF-8'?><soap:Envelope>\";\n...\n...\n\n// Make http request\nHttpWebRequest req = (HttpWebRequest)WebRequest.Create(\"http://linktoyour/service.asmx\");\n\nreq.Headers.Add(\"SOAPAction\", \"http://linktoyour/NameOfFuntion\");\n\nreq.ContentType = \"text/xml;charset=\\\"utf-8\\\"\";\nreq.Accept = \"text/xml\";\nreq.Method = \"POST\";\nbyte[] bytes = System.Text.Encoding.UTF8.GetBytes(msg);\n\nreq.ContentLength = bytes.Length;\n\nSystem.IO.Stream st = req.GetRequestStream();\nst.Write(bytes,0,bytes.Length);\nst.Close();\n\n// Read response\nHttpWebResponse res = (HttpWebResponse)req.GetResponse();\nSystem.IO.Stream st1 = res.GetResponseStream();\n\nSystem.IO.StreamReader sr = new System.IO.StreamReader(st1, System.Text.Encoding.UTF8);\n\nstring txt = sr.ReadToEnd();\n\n// Display response\nResponse.Write(txt);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
212,842
<p>In short, how can I search, view, and modify in-memory values in linux, preferably as easily/simply as possible.</p> <p><a href="http://www.raymond.cc/blog/archives/2007/02/27/how-to-cheat-and-hack-flash-based-games/" rel="nofollow noreferrer">Like this</a>.</p>
[ { "answer_id": 72671768, "author": "Devon", "author_id": 7944912, "author_profile": "https://Stackoverflow.com/users/7944912", "pm_score": 0, "selected": false, "text": "ceserver localhost" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,847
<p>I am mentoring the programming group of a high school robotics team. I would like to set up a source control repository to avoid the mess of manually copying directories for sharing/backups and merging these by hand. The build location will not usually have network access, so this has led me to distributed version control systems (DVCS), which I am not familiar with.</p> <p>The largest requirements are the following:</p> <ol> <li>Works in Windows XP and Vista. (absolute must)</li> <li>Changes can be committed locally. (Seems to be the case with all DVCS's)</li> <li>Repositories from multiple machines can be merged without network access. (Possibly by storing the repository on a USB drive and swapping the drive to another machine, then merging from there) </li> </ol> <p>It should also be easy to learn and use, preferably through a graphical UI, as I am working with high school students who have never used a version control system.</p> <p>Any suggestions as to which DVCS fits this the best.</p> <p>EDIT:</p> <p>Thanks for the answers. Mercurial looks pretty good, but does it support merging repositories from one directory to another, or do I have to set up a local network to merge across?</p>
[ { "answer_id": 213345, "author": "quark", "author_id": 29057, "author_profile": "https://Stackoverflow.com/users/29057", "pm_score": 2, "selected": false, "text": "cd C:\\Project hg pull F:\\Project cd C:\\Project hg pull C:\\Project1 hg merge added 1 changesets with 1 changes to 1 files (+1 heads) (run 'hg heads' to see heads, 'hg merge' to merge)" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5233/" ]
212,851
<p>I've got a <code>DataGridViewCobmoboxColumn</code> that has to be on the far right side of the screen. The items in the cell are wider that the cell width, so the dropdown list is also wider than the cell, so the user can see what top select. When the list drops down, the right side of the dropdown is not visible, and thus the scroll bar is also not visible. The users think there are only 7 items to choose from, when there are actually many.</p> <p>Since this has to be on the right side, is there any way to anchor the dropdown to the right of the cell and expand to the left?</p> <p>We're using .Net 2.0 for this project. Since we're coding in both VB and C#, I'm not too concerned about an answer being language specific. I'll take anything...</p>
[ { "answer_id": 42065719, "author": "Taras Kozubski", "author_id": 1259074, "author_profile": "https://Stackoverflow.com/users/1259074", "pm_score": 0, "selected": false, "text": "ToolStripDropDownDirection.AboveLeft" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,858
<p>I'm working on a web app project (in java; not that it matters) and we have a form with drop down lists and input fields. </p> <p>Obviously drop down lists are provided because we expect a specific value from a set of values. </p> <p>So my question is this: does it make sense to ensure the submitted value is in the set of expected values? Or is it acceptable to just assume the correct value is coming across?</p> <p>There aren't any "errors" that would arise from different values being submitted, but the data store would not be consistent with the business rules/requirements.</p>
[ { "answer_id": 42065719, "author": "Taras Kozubski", "author_id": 1259074, "author_profile": "https://Stackoverflow.com/users/1259074", "pm_score": 0, "selected": false, "text": "ToolStripDropDownDirection.AboveLeft" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17337/" ]
212,863
<p>My current project uses NUnit for unit tests and to drive UATs written with Selenium. Developers normally run tests using ReSharper's test runner in VS.Net 2003 and our build box kicks them off via NAnt.</p> <p>We would like to run the UAT tests in parallel so that we can take advantage of Selenium Grid/RCs so that they will be able to run much faster.</p> <p>Does anyone have any thoughts on how this might be achieved? and/or best practices for testing Selenium tests against multiple browsers environments without writing duplicate tests automatically?</p> <p>Thank you.</p>
[ { "answer_id": 32245312, "author": "Peter", "author_id": 707458, "author_profile": "https://Stackoverflow.com/users/707458", "pm_score": 1, "selected": false, "text": "[Parallelizable(ParallelScope.Self)]" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29009/" ]
212,900
<p>I've used lex and yacc (more usually bison) in the past for various projects, usually translators (such as a subset of EDIF streamed into an EDA app). Additionally, I've had to support code based on lex/yacc grammars dating back decades. So I know my way around the tools, though I'm no expert.</p> <p>I've seen positive comments about Antlr in various fora in the past, and I'm curious as to what I may be missing. So if you've used both, please tell me what's better or more advanced in Antlr. My current constraints are that I work in a C++ shop, and any product we ship will not include Java, so the resulting parsers would have to follow that rule.</p>
[ { "answer_id": 212930, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 8, "selected": true, "text": "expr ::= expr '+' expr\n | expr '-' expr\n | '(' expr ')'\n | NUM ;\n expr ::= expr '.' ID '(' actuals ')' ;\n\nactuals ::= actuals ',' expr | expr ;\n expr actuals" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778/" ]
212,902
<p>I'm trying to find about ALL the possible options that I can set in <code>web.config</code>. Surprisingly, I can't find this at all. I expected it to be somewhere inside <a href="http://msdn.microsoft.com" rel="noreferrer">MSDN</a>.</p> <p>I know I can technically add "anything" to <code>web.config</code>, what I'm looking for is the things that the .NET Framework "as shipped" uses.</p> <p>In particular, right now I'm interested in the <code>&lt;mailsettings&gt;</code> section.<br> For example, in many examples I've found, I noticed that they set <code>DeliveryMethod="Network"</code>. I'm really curious what other values this attribute can take.</p> <p>Is there any document on all the attributes and all their values, and all the effects those have?</p>
[ { "answer_id": 212933, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "<system.web> <system.web.extensions> <appSettings> <configSections> <connectionStrings>" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
212,906
<p>My customer is replacing MS Office with OpenOffice in some workstations. My program export a file to Excel using the .xml extension (using open format) and opens it using the current associated program (using ShellExecute)</p> <p>The problem is that OpenOffice does not register the .xml extension associated with it.</p> <p>Manually association works fine, but I want to make a .reg or something to easily change the setting.</p> <p>I'm looking in the registry in a PC with the change already made, but the </p> <pre><code>"HKEY_CLASSES_ROOT\.xml" </code></pre> <p>key does not have anything referencing OpenOffice.</p> <p>Where is the association stored? How can I make a script to do the work?</p>
[ { "answer_id": 212921, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "\"HKEY_CLASSES_ROOT\\.xml\" \"xmlfile\" \"HKEY_CLASSES_ROOT\\xmlfile\" HKEY_CLASSES_ROOT\\xmlfile\\shell\\open\\command\n \"HKEY_CLASSES_ROOT\\xmlfile\\shell\" \"shell\" \"open\" regedit /s new_xml_association.reg\n reg add \"HKEY_CLASSES_ROOT\\xmlfile\\shell\\open\\command\" /ve /d \"path\\to\\program %1\"\n reg add/?" }, { "answer_id": 212984, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "assoc" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ]
212,919
<p>I need to change the permissions of a directory to be owned by the Everyone user with all access rights on this directory. I'm a bit new to the Win32 API, so I'm somewhat lost in the SetSecurity* functions.</p>
[ { "answer_id": 213716, "author": "Jason", "author_id": 26302, "author_profile": "https://Stackoverflow.com/users/26302", "pm_score": 2, "selected": false, "text": "SetSecurityInfo(hDir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26302/" ]
212,939
<p>MySQL 5.0.45</p> <p>What is the syntax to alter a table to allow a column to be null, alternately what's wrong with this:</p> <pre><code>ALTER mytable MODIFY mycolumn varchar(255) null; </code></pre> <p>I interpreted the manual as just run the above and it would recreate the column, this time allowing null. The server is telling me I have syntactical errors. I just don't see them.</p>
[ { "answer_id": 212947, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 11, "selected": true, "text": "ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);\n UNIQUE NOT NULL" }, { "answer_id": 212966, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 8, "selected": false, "text": "ALTER TABLE mytable MODIFY mycolumn varchar(255) null;\n" }, { "answer_id": 1368689, "author": "Gerald Senarclens de Grancy", "author_id": 104659, "author_profile": "https://Stackoverflow.com/users/104659", "pm_score": 3, "selected": false, "text": "ALTER TABLE mytable MODIFY mytable.mycolumn varchar(255);\n" }, { "answer_id": 8254845, "author": "Krishnrohit", "author_id": 1063633, "author_profile": "https://Stackoverflow.com/users/1063633", "pm_score": 5, "selected": false, "text": "ALTER TABLE table_name CHANGE column_name column_name type DEFAULT NULL\n ALTER TABLE SCHEDULE CHANGE date date DATETIME DEFAULT NULL;\n" }, { "answer_id": 31966476, "author": "Jan Nejedly", "author_id": 2947740, "author_profile": "https://Stackoverflow.com/users/2947740", "pm_score": -1, "selected": false, "text": "ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);" }, { "answer_id": 55777515, "author": "Hmerman6006", "author_id": 10177977, "author_profile": "https://Stackoverflow.com/users/10177977", "pm_score": 3, "selected": false, "text": "ALTER TABLE `table` CHANGE `column_current_name` `new_column_name` DATETIME NULL;\n NOT NULL NULL CHANGE" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13285/" ]
212,941
<p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/" rel="noreferrer">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go about limiting what people can view and manipulate through the rest interface? Normally I'd put this kind of logic in my views. Is this the right place or should I be moving some more logic down into the model? Alternatively is there a better library out there or do I need to roll my own?</p>
[ { "answer_id": 214383, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 2, "selected": false, "text": "authentication Collection login_required permission_required" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2351/" ]
212,965
<p>What I want to do is the following:</p> <ol> <li>read in multiple line input from <code>stdin</code> into variable <code>A</code></li> <li>make various operations on <code>A</code></li> <li>pipe <code>A</code> without losing delimiter symbols (<code>\n</code>,<code>\r</code>,<code>\t</code>,etc) to another command</li> </ol> <p>The current problem is that, I can't read it in with <code>read</code> command, because it stops reading at newline.</p> <p>I can read stdin with <code>cat</code>, like this:</p> <pre><code>my_var=`cat /dev/stdin` </code></pre> <p>, but then I don't know how to print it. So that the newline, tab, and other delimiters are still there.</p> <p>My sample script looks like this:</p> <pre><code>#!/usr/local/bin/bash A=`cat /dev/stdin` if [ ${#A} -eq 0 ]; then exit 0 else cat ${A} | /usr/local/sbin/nextcommand fi </code></pre>
[ { "answer_id": 212987, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 7, "selected": true, "text": "myvar=`cat`\n\necho \"$myvar\"\n $myvar" }, { "answer_id": 213007, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "myvar=`cat`\n myvar=`cat /dev/stdin`\n bash" }, { "answer_id": 15269128, "author": "Ingo Karkat", "author_id": 813602, "author_profile": "https://Stackoverflow.com/users/813602", "pm_score": 5, "selected": false, "text": "man bash $(cat file) $(< file) $ myVar=$(</dev/stdin)\nhello\nthis is test\n$ echo \"$myVar\"\nhello\nthis is test\n" }, { "answer_id": 22064369, "author": "Sergey Grigoriev", "author_id": 1921113, "author_profile": "https://Stackoverflow.com/users/1921113", "pm_score": 4, "selected": false, "text": "#!/bin/bash\nmyVar=$(tee)\n" }, { "answer_id": 25738463, "author": "Ingo Karkat", "author_id": 813602, "author_profile": "https://Stackoverflow.com/users/813602", "pm_score": 3, "selected": false, "text": "myVar=$(cat; echo x)\nmyVar=${myVar%x}\nprintf %s \"$myVar\"\n" }, { "answer_id": 47343371, "author": "DocSalvager", "author_id": 470211, "author_profile": "https://Stackoverflow.com/users/470211", "pm_score": 4, "selected": false, "text": "var=\"$(< /dev/stdin)\"\n read /dev/stdin IFS read -r -d '' __=\"\"\n_stdin=\"\"\n\nread -N1 -t1 __ && {\n (( $? <= 128 )) && {\n IFS= read -rd '' _stdin\n _stdin=\"$__$_stdin\"\n }\n}\n var=\"$(command ...)\" $() $(parens) ${braces} _stdin=\"$(awk '{print}; END {print \"|||\"}' /dev/stdin)\"\n_stdin=\"${_stdin%|||}\"\n" }, { "answer_id": 69184102, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "-read d '' read -d'' myvar\necho \"$myvar\"\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
212,968
<p>I have a scenario in a system which I've tried to simplify as best as I can. We have a table of (lets call them) artefacts, artefacts can be accessed by any number of security roles and security roles can access any number of artefacts. As such, we have 3 tables in the database - one describing artefacts, one describing roles and a many-to-many association table linking artefact ID to Role ID.</p> <p>Domain wise, we have two classes - one for a role and one for an artefact. the artefact class has an IList property that returns a list of roles that can access it. (Roles however do not offer a property to get artefacts that can be accessed).</p> <p>As such, the nhibernate mapping for artefact contains the following;</p> <pre class="lang-xml prettyprint-override"><code>&lt;bag name="AccessRoles" table="ArtefactAccess" order-by="RoleID" lazy="true" access="field.camelcase-underscore" optimistic-lock="false"&gt; &lt;key column="ArtefactID"/&gt; &lt;many-to-many class="Role" column="RoleID"/&gt; &lt;/bag&gt; </code></pre> <p>This all works fine and if I delete an artefact, the association table is cleaned up appropriately and all references between the removed artefact and roles are removed (the role isn't deleted though, correctly - as we don't want orphans deleted).</p> <p>The problem is - how to delete a role and have it clear up the association table automatically. If I presently try to delete a role, I get a reference constraint as there are still entries in the association table for the role. The only way to successfully delete a role is to query for all artefacts that link to that role, remove the role from the artefact's role collection, update the artefacts and then delete the role - not very efficient or nice, especially when in the un-simplified system, roles can be associated with any number of other tables/objects.</p> <p>I need to be able to hint to NHibernate that I want this association table cleared whenever I delete a role - is this possible, and if so - how do I do it?</p> <p>Thanks for any help.</p>
[ { "answer_id": 214138, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 0, "selected": false, "text": "Artifact ArtefactAccess" }, { "answer_id": 407171, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<bag name=\"Roles\" table=\"RolesToAccess\" cascade=\"none\" lazy=\"false\">\n <key column=\"AccessId\" />\n <many-to-many column=\"AccessId\" class=\"Domain.Compound,Domain\" />\n </bag>\n\n<bag name=\"RolesToAccess\" cascade=\"save-update\" inverse=\"true\" lazy=\"false\">\n <key column=\"AccessId\" on-delete=\"cascade\" />\n <one-to-many class=\"Domain.RolesToAccess,Domain\" />\n </bag>\n <bag name=\"Accesses\" table=\"RolesToAccess\" cascade=\"none\" lazy=\"false\">\n <key column=\"RoleId\" />\n <many-to-many column=\"RoleId\" class=\"Domain.Compound,Domain\" />\n </bag>\n\n<bag name=\"RolesToAccess\" cascade=\"save-update\" inverse=\"true\" lazy=\"false\">\n <key column=\"RoleId\" on-delete=\"cascade\" />\n <one-to-many class=\"Domain.RolesToAccess,Domain\" />\n </bag>\n" }, { "answer_id": 4421934, "author": "pvolders", "author_id": 480421, "author_profile": "https://Stackoverflow.com/users/480421", "pm_score": 1, "selected": false, "text": " <bag name=\"Artifacts\" table=\"[ArtifactAccess]\" schema=\"[Dbo]\" lazy=\"true\"\n inverse=\"false\" cascade=\"none\" generic=\"true\">\n <key column=\"[ArtifactID]\"/>\n\n <many-to-many column=\"[RoleID]\" class=\"Role\" />\n </bag>\n <bag name=\"Roles\" table=\"[ArtifactAccess]\" schema=\"[Dbo]\" lazy=\"true\"\n inverse=\"false\" cascade=\"none\" generic=\"true\">\n <key column=\"[RoleID]\"/>\n\n <many-to-many column=\"[ArtifactID]\" class=\"Role\" />\n </bag>\n foreach(var artifact in role.Artifacts)\n foreach(var role in artifact.Roles)\n if(role == roleToDelete)\n artifact.Roles.Remove(role)\n artifact.Save();\nroleToDelete.Delete();\n roleToDelete.Artifacts.Clear(); //removes the association record\nroleToDelete.Delete(); // removes the artifact record\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524/" ]
212,988
<p>I have created an item swapper control consisting in two listboxes and some buttons that allow me to swap items between the two lists. The swapping is done using javascript. I also move items up and down in the list. Basically when I move the items to the list box on the right I store the datakeys of the elements (GUIDs) in a hiddenfield. On postback I simply read the GUIDs from the field. Everything works great but on postback, I get the following exception:</p> <blockquote> <p>Invalid postback or callback argument. Event validation is enabled using in configuration or &lt;%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. </p> </blockquote> <p>I've prepared a test application. All you have to do is download the archive and run the project. On the web page select the 3 items, press Add all, then move the third element up one level and then hit "Button". The error will show up. Turning event validation off is by no means acceptable. Can anyone help me, I've spent two already days without finding a solution.</p> <p><a href="http://cid-c9672af9b84b07ef.skydrive.live.com/self.aspx/TestApp/TestProject.zip" rel="noreferrer">TEST APPLICATION</a></p>
[ { "answer_id": 213535, "author": "kjv", "author_id": 1360, "author_profile": "https://Stackoverflow.com/users/1360", "pm_score": 1, "selected": true, "text": "public class CustomListBox : ListBox\n{\n protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)\n {\n return true;\n }\n}\n" }, { "answer_id": 215583, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 0, "selected": false, "text": "document.getElementById(\"listbox\").selectedIndex = -1;\n" }, { "answer_id": 8222376, "author": "Tom", "author_id": 882436, "author_profile": "https://Stackoverflow.com/users/882436", "pm_score": 0, "selected": false, "text": "<select runat=\"server\" id=\"myList\" multiple=\"true\" />\n" }, { "answer_id": 33810783, "author": "Gerbus", "author_id": 303659, "author_profile": "https://Stackoverflow.com/users/303659", "pm_score": 0, "selected": false, "text": "protected override void Render(HtmlTextWriter writer)\n{\n foreach (DictionaryEntry entry in ColumnConfig) { \n Page.ClientScript.RegisterForEventValidation(lstbxColumnsToExport.UniqueID,(string)entry.Key);\n Page.ClientScript.RegisterForEventValidation(lstbxNonExportColumns.UniqueID,(string)entry.Key);\n }\n base.Render(writer);\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
212,989
<p>I have G729 encoded audio files. I need to programmatically convert them to WAV PCM (16bit 8kHz mono) in the flow of a tool that is doing other thing too. I have an executable that will do that for me. But spawning that external process every time I convert is too heavy on resources. Especially if I need many of them being done in parallel. Looking for a .NET library or code that will let me call this inside my process.</p>
[ { "answer_id": 12105360, "author": "AndroidLearner", "author_id": 1479075, "author_profile": "https://Stackoverflow.com/users/1479075", "pm_score": 0, "selected": false, "text": "EXE browse dialogue box All Files(*.*) browse file dialogue" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363/" ]
212,994
<p>How can I get tab completion to work for selecting CVS modules under Linux (preferably using bash) ?</p> <p>For example, "cvs co " + tab would list the modules I can checkout. I've heard it's easy to do using zsh, but still I didn't manage to get it working either. </p> <p>Also, how can I list all available modules (or repositories?) available in the CVSROOT?</p>
[ { "answer_id": 213025, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 2, "selected": false, "text": "cvs -d \"$the_cvsroot\" checkout -c" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2907/" ]
212,999
<p>After using Hudson for continuous integration with a prior project, I want to set up a continuous integration server for the iPhone projects I'm working on now. After doing some research it looks like there aren't any CI engines designed specifically for Xcode, but one guy has had success <a href="http://www.pragmaticautomation.com/cgi-bin/pragauto.cgi/Build/XcodeOnCC.rdoc" rel="noreferrer">using Cruise Control combined with the xcodebuild CLI tool</a>. Has anyone here tried this? Are there any CI engines that work well with Xcode projects?</p> <p>I'm probably going to give Cruise Control a try. I'll post an answer with my findings.</p>
[ { "answer_id": 1182726, "author": "Silentcode", "author_id": 145054, "author_profile": "https://Stackoverflow.com/users/145054", "pm_score": 6, "selected": true, "text": "xcodebuild -target \"myAppAppStore\" -configuration \"DistributionAppStore\" -sdk iphoneos2.1\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/212999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17188/" ]
213,002
<p>I have some data grouped in a table by a certain criteria, and for each group it is computed an average —well, the real case is a bit more tricky— of the values from each of the detail rows that belong to that group. This average is shown in each group footer rows. Let's see this simple example:</p> <p><img src="https://farm4.static.flickr.com/3008/2958165686_088405e1ef_o.jpg" alt="Report table"></p> <p>What I want now is to show a grand total on the <strong>table footer</strong>. The grand total should be computed by <em>adding</em> each group's average (for instance, in this example the grand total should be 20 + 15 = 35). However, I can't nest aggregate functions. How can I do?</p>
[ { "answer_id": 305766, "author": "user33675", "author_id": 33675, "author_profile": "https://Stackoverflow.com/users/33675", "pm_score": 3, "selected": true, "text": "Public Sub New()\n\n m_valueTable = New DataTable(tableName:=\"DoubleValueList\")\n\n 'Type reference to System.Double\n Dim doubleType = Type.GetType(typeName:=\"System.Double\")\n\n ' Add a single Double column to hold values\n m_valueTable.Columns.Add(columnName:=\"Value\", type:=doubleType)\n\n ' Add aggregation column\n m_sumColumn = m_valueTable.Columns.Add(columnName:=\"Sum\", type:=doubleType, expression:=\"Sum(Value)\")\nEnd Sub\nPublic Function Aggregate(ByVal value As Double) As Double\n\n ' Appends a row using a 1-element object array. \n ' If there will be more than 1 column, more values need to be supplied respectively.\n m_valueTable.Rows.Add(value)\n\n Aggregate = value\nEnd Function\nPublic ReadOnly Property Sum() As Double\n Get\n\n If 0 = m_valueTable.Rows.Count Then\n Sum = 0\n Else\n Sum = CDbl(m_valueTable.Rows(0)(m_sumColumn))\n End If\n End Get\nEnd Property\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679/" ]
213,015
<p>I have over a TB of home movies with horrible file names. Finding what you want is impossible. I would like to rename all files to the time they were originally recorded (not the file time they were placed on my computer). Some applications (like Ulead Video Studio) can access this information, which I believe is embedded in the CODEC.</p> <p>I would LOVE to find how how either I can write a .Net app to extract this information to rename my files so I can easily organize them OR find an application that will do this for me. Thank you very much in advanced.</p> <p>additional information:: home movies were captured on miniDV and DVD camcorders.</p>
[ { "answer_id": 6050589, "author": "PhilT", "author_id": 759912, "author_profile": "https://Stackoverflow.com/users/759912", "pm_score": 3, "selected": false, "text": "mplayer -vo null -ao null -frames 0 -identify myfile.MOV 2>/dev/null|grep creation_time:\n for m in MVI*.MOV; do\n t=$(mplayer -vo null -ao null -frames 0 -identify $m 2>/dev/null|grep creation_time:|sed 's/.*creation_time: *//;s/[-:]//g;s/ /-/')\n mv ${m} ${t}_${m}\ndone\n" }, { "answer_id": 16814606, "author": "Robert Siemer", "author_id": 825924, "author_profile": "https://Stackoverflow.com/users/825924", "pm_score": 1, "selected": false, "text": "dvgrab" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29027/" ]
213,027
<p>The following code was produced by a consultant working for my group. I'm not a C++ developer (worked in many languages, though) but would like some independent opinions on the following code. This is in Visual Studio C++ 6.0. I've got a gut reaction (not a good one, obviously), but I'd like some "gut reactions" from seasoned (or even not so unseasoned) C++ developers out there. Thanks in advance!</p> <pre><code>// Example call strColHeader = insert_escape(strColHeader, ',', '\\'); //Get rid of the commas and make it an escape character </code></pre> <p>...snip...</p> <pre><code>CString insert_escape ( CString originalString, char charFind, char charInsert ) { bool continueLoop = true; int currentInd = 0; do { int occurenceInd = originalString.Find(charFind, currentInd); if(occurenceInd&gt;0) { originalString.Insert(occurenceInd, charInsert); currentInd = occurenceInd + 2; } else { continueLoop = false; } } while(continueLoop); return(originalString); } </code></pre>
[ { "answer_id": 213041, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 4, "selected": false, "text": "CString strColHeader;\nstrColHeader.Replace(\",\", \"\\\\,\") \n while (occurenceInd != 0)" }, { "answer_id": 213398, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "int occurenceInd = originalString.Find(charFind, currentInd);\n if(occurenceInd>0) \n if(occurrenceInd >= 0)\n CString insert_escape ( const CString &originalString, char charFind, char charInsert ) {\n std::string escaped;\n // Reserve enough space for each character to be escaped\n escaped.reserve(originalString.GetLength() * 2); \n for (int iOriginal = 0; iOriginal < originalString.GetLength(); ++iOriginal) {\n if (originalString[iOriginal] == charFind)\n escaped += charInsert;\n escaped += originalString[iOriginal];\n }\n return CString(escaped.c_str());\n}\n" }, { "answer_id": 213526, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "// Example call\nstrColHeader = insert_escape(strColHeader, ',', '\\\\'); //Get rid of the commas and make it an escape character\n\nCString insert_escape ( CString originalString, char charFind, char charInsert )\n strColHeader originalString & strColHeader void insert_escape(CString &originalString, char charFind, char charInsert)\n CString insert_escape(const CString &originalString, char charFind, char charInsert)\n CString Replace" }, { "answer_id": 256410, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "CString CString CString CString" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
213,042
<p>I tried "x = y ** e", but that didn't work.</p>
[ { "answer_id": 213043, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 8, "selected": true, "text": "pow float double man pow #include <math.h>\n\n double pow(double x, double y);\n float powf(float x, float y);\n long double powl(long double x, long double y);\n 2 (1 << x) 2 x" }, { "answer_id": 213064, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": false, "text": "exp(double) expf(float) expl(long double) ^" }, { "answer_id": 213260, "author": "None", "author_id": 25012, "author_profile": "https://Stackoverflow.com/users/25012", "pm_score": 2, "selected": false, "text": "int power(int x, int y){\n if(y == 0)\n return 1;\n return (x * power(x,y-1) );\n }\n" }, { "answer_id": 213322, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": false, "text": "pow double 2 int power(int base, unsigned int exp) {\n int i, result = 1;\n for (i = 0; i < exp; i++)\n result *= base;\n return result;\n }\n O(log n) O(1) O(n) int power(int base, int exp) {\n if (exp == 0)\n return 1;\n else if (exp % 2)\n return base * power(base, exp - 1);\n else {\n int temp = power(base, exp / 2);\n return temp * temp;\n }\n}\n" }, { "answer_id": 213897, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "long powi(long x, unsigned n)\n{\n long p = x;\n long r = 1;\n\n while (n > 0)\n {\n if (n % 2 == 1)\n r *= p;\n p *= p;\n n /= 2;\n }\n\n return(r);\n}\n" }, { "answer_id": 4641585, "author": "Anonymous", "author_id": 504056, "author_profile": "https://Stackoverflow.com/users/504056", "pm_score": 2, "selected": false, "text": "int power(int x,int y){\n int r=1;\n do{\n r*=r;\n if(y%2)\n r*=x;\n }while(y>>=1);\n return r;\n};\n int power(int x,int y){\n return y?(y%2?x:1)*power(x*x,y>>1):1;\n};\n" }, { "answer_id": 11552955, "author": "kallikak", "author_id": 966208, "author_profile": "https://Stackoverflow.com/users/966208", "pm_score": 3, "selected": false, "text": "double intpow(double a, int b)\n{\n double r = 1.0;\n if (b < 0)\n {\n a = 1.0 / a;\n b = -b;\n }\n while (b)\n {\n if (b & 1)\n r *= a;\n a *= a;\n b >>= 1;\n }\n return r;\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
213,045
<p>I have a class library with some extension methods written in C# and an old website written in VB.</p> <p>I want to call my extension methods from the VB code but they don't appear in intelisense and I get compile errors when I visit the site.</p> <p>I have got all the required <em>Import</em>s because other classes contained in the same namespaces are appearing fine in Intelisense.</p> <p>Any suggestions</p> <p><strong>EDIT:</strong> More info to help with some comments.</p> <p>my implementation looks like this </p> <pre><code>//C# code compiled as DLL namespace x.y { public static class z { public static string q (this string s){ return s + " " + s; } } } </code></pre> <p>and my usage like this </p> <pre><code>Imports x.y '...' Dim r as string = "greg" Dim s as string = r.q() ' does not show in intelisense ' and throws error : Compiler Error Message: BC30203: Identifier expected. </code></pre>
[ { "answer_id": 213066, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 2, "selected": false, "text": "public static string MyExtMethod(this string s)\n MyExtMethod(\"myArgument\")\n" }, { "answer_id": 213070, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 0, "selected": false, "text": "StaticClass.ExtensionMethod(theString, arg1, ..., argN)\n theString.ExtensionMethod(arg1, ..., argN);\n" }, { "answer_id": 213318, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "Shared Import x.y x x.y Import Imports x\nDim x As New y.SomeClass()\n" }, { "answer_id": 213338, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "Imports x.y\n\n'...'\nDim r As String = \"greg\"\nDim s As String = r.q() 'same as z.q(r) \n" }, { "answer_id": 213450, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "using System;\n\nnamespace ExtensionLibrary\n{\n public static class Extensions\n {\n public static string CustomExtension(this string text)\n {\n char[] chars = text.ToCharArray();\n Array.Reverse(chars);\n return new string(chars);\n }\n }\n}\n Imports ExtensionLibrary\n\nModule Test\n\n Sub Main()\n Console.WriteLine(\"Hello\".CustomExtension())\n End Sub\n\nEnd Module\n Object" }, { "answer_id": 3742072, "author": "NagyBandi", "author_id": 451429, "author_profile": "https://Stackoverflow.com/users/451429", "pm_score": 0, "selected": false, "text": "x.y.r.q()\n using x.y;\n...\nr.q()\n" }, { "answer_id": 12211281, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "Option Strict Object namespace NS\n...\n\npublic static class Utility {\n\n public static void Something(this object input) { ...\n\n public static void Something(this string input) { ...\n\n}\n\n// Works fine, resolves to 2nd method\n\"test\".Something();\n\n// At compile time C# converts the above to:\nUtility.Something(\"test\");\n Option Infer On\nOption Explicit On\nOption Strict Off\nImports NS\n...\n\n Dim r as String = \"test\" \n r.Something()\n Something String Utility.Something Object Object String Integer Option Infer VBCodeProvider Object" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1741868/" ]
213,078
<p>Alright so I'm essentialyl trying to code something that will combine two files together in VB and output a single file that when run, runs both of them. I've grabbed this source from several places online and am just trying to get it to work. We have the main program that combines them with a GUI</p> <pre><code>Const FileSplit = "@&lt;&gt;#&lt;&gt;#&lt;&gt;@" Private Sub cmdAdd_Click() With Dlg .Filter = "All Files(*.*) | *.*" .DialogTitle = "Please Select a File..." .ShowOpen End With lsFiles.AddItem (Dlg.FileName) End Sub Private Sub cmdBuild_Click() Dim sStub As String, sFiles As String, i As Integer Open App.Path &amp; "\stub.exe" For Binary As #1 sStub = Space(LOF(1)) Get #1, , sStub Close #1 Open App.Path &amp; "\boundfile.exe" For Binary As #1 Put #1, , sStub &amp; FileSplit For i = 0 To lsFiles.ListCount - 1 Open lsFiles.List(i) For Binary As #2 sFiles = Space(LOF(2)) Get #2, , sFiles Close #2 Put #1, , sFiles &amp; FileSplit Next i Close #1 MsgBox "Files Successfully Combined" End Sub </code></pre> <p>And then we have a second App that acts as a stub</p> <pre><code>Const FileSplit = "@&lt;&gt;#&lt;&gt;#&lt;&gt;@" Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Private Sub Form_Load() Dim sStub As String, sFiles() As String, i As Integer Open App.Path &amp; "\" &amp; App.EXEName &amp; ".exe" For Binary As #1 sStub = Input(LOF(1), 1) Get #1, , stub Close #1 sFiles = Split(sStub, FileSplit) For i = 1 To UBound(sFiles()) Open Environ("tmp") &amp; "\tmp" &amp; i &amp; ".exe" For Binary As #1 Put #1, , sFiles(i) Close #1 Call ShellExecute(0, vbNullString, Environ("tmp") &amp; "\tmp" &amp; i &amp; ".exe", vbNullString, vbNullString, vbNormalFocus) Next i End End Sub </code></pre> <p>however when the files are combined and run all I get is a dosbox opening and closing. Any ideas?</p>
[ { "answer_id": 235586, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 0, "selected": false, "text": "Const FileSplit = \"@<>#<>#<>@\"\n\nPrivate Sub cmdAdd_Click()\n With Dlg\n .Filter = \"All Files(*.*) | *.*\"\n .DialogTitle = \"Please Select a File...\"\n .ShowOpen\n End With\n lsFiles.AddItem (Dlg.FileName)\nEnd Sub\n\nPrivate Sub cmdBuild_Click()\n Dim sStub As String, sFiles As String, i As Integer\n Open App.Path & \"\\stub.exe\" For Binary As #1\n sStub = Space(LOF(1))\n Get #1, , sStub\n Close #1\n Open App.Path & \"\\boundfile.exe\" For Output As #1\n Print #1, sStub & FileSplit;\n For i = 0 To lsFiles.ListCount - 1\n Open lsFiles.List(i) For Binary As #2\n sFiles = Space(LOF(2))\n Get #2, , sFiles\n Close #2\n Print #1, sFiles & FileSplit;\n Next i\n Close #1\n MsgBox \"Files Successfully Combined\"\nEnd Sub\n Const FileSplit = \"@<>#<>#<>@\"\nPrivate Declare Function ShellExecute Lib \"shell32.dll\" Alias \"ShellExecuteA\" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long\n\nPrivate Sub Form_Load()\n Dim sStub As String, sFiles() As String, i As Integer\n Open App.Path & \"\\\" & App.EXEName & \".exe\" For Binary As #1\n sStub = Space(LOF(1))\n Get #1, , sStub\n Close #1\n sFiles = Split(sStub, FileSplit)\n For i = 1 To UBound(sFiles())\n Open Environ(\"tmp\") & \"\\tmp\" & i & \".exe\" For Output As #1\n Print #1, sFiles(i);\n Close #1\n Call ShellExecute(0, vbNullString, Environ(\"tmp\") & \"\\tmp\" & i & \".exe\", vbNullString, vbNullString, vbNormalFocus)\n Next i \n End\nEnd Sub\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
213,085
<p>I'm working on a forums system. I'm trying to allow users to see the posts they've made. In order for this link to work, I'd need to jump to the <strong>page</strong> on the particular topic they posted in that contained their post, so the bookmarks could work, etc. Since this is a new feature on an old forum, I'd like to code it so that the forum system doesn't have to keep track of every post, but can simply populate this list automatically.</p> <p>I know how to populate the list, but I need to do this: </p> <p>Given a query, where will X row within the query (guaranteed to be unique by some combination of identifiers) appear? As in, how many rows would I have to offset to get to it? This would be in a sorted query.</p> <p>Ideally, I'd like to do this with SQL and not PHP, but if it can't be done in SQL I guess that's an answer too. ^_^</p> <p>Thanks</p>
[ { "answer_id": 213186, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "SELECT count(post_id) FROM posts\n WHERE thread_id = '{$thread_id}' AND date_posted <= '{$date_posted}'\n // dig around forum code for number of items per page\n$itemsPerPage = 10; // let's say\n$ourCount = getQueryResultFromAbove(); \n\n// this is the page that post will be on\n$page = ceil($ourCount / $itemsPerPage);\n\n// for example\n$link = '/thread.php?thread_id='.$thread_id.'&page='.$page;\n" }, { "answer_id": 213189, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": " select row_number() OVER(ORDER BY MessageDate DESC) \n AS 'RowNum', * from MESSAGES\n select RowNum, Title, Body, Author from (\n select row_number() OVER(ORDER BY MessageDate DESC) \n AS 'RowNum', * from MESSAGES)\n where AuthorID = @User\n" }, { "answer_id": 213200, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "SET @i=0;\nSELECT number FROM (SELECT *,@i:=@i+1 as number FROM Posts \nORDER BY <order_clause>) as a WHERE <unique_condition_over_a>\n CREATE TEMPORARY SEQUENCE counter;\nSELECT number FROM (SELECT *,nextval('sequence') as number FROM Posts \nORDER BY <order_clause>) as a WHERE <unique_condition_over_a>\n" }, { "answer_id": 213217, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 0, "selected": false, "text": "START TRANSACTION;\n\nSET @rows_count = 0;\nSET @user_id = ...;\nSET @page_size = ...;\n\nSELECT \n @rows_count := @rows_count + 1 AS RowNumber\n ,CEIL( @rows_count / @page_size ) AS PageNumber\nFROM ForumPost P\nWHERE \n P.PosterId = @user_id;\n\nROLLBACK;\n" }, { "answer_id": 213315, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 0, "selected": false, "text": "CREATE TABLE OF QUERY RESULTS WITH IDENTITY COLUMN\n\nINSERT INTO TABLE \nQUERY \nORDER BY something\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
213,118
<p>In MFC I'm trying to set a null handler timer (ie. no windows). But I'm unable to process the WM_TIMER event in the CWinApp MESSAGE_MAP. Is this possible? If so, how?</p>
[ { "answer_id": 213776, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 5, "selected": true, "text": "SetTimer() CWinApp UINT_PTR uTimerId = SetTimer(NULL, 0, 2000, NULL);\nTRACE(_T(\"Timer created - ID=%x\\n\"), uTimerId);\n CWinApp::PreTranslateMessage() BOOL CMyFunkyApp::PreTranslateMessage(MSG* pMsg)\n{\n if (pMsg->message == WM_TIMER)\n {\n TRACE(_T(\"Timer fired - ID=%x\\n\"), pMsg->wParam);\n }\n\n return CWinApp::PreTranslateMessage(pMsg);\n}\n CWinApp ON_WM_*() void CALLBACK TimerCallback(HWND, UINT, UINT_PTR id, DWORD dwTime)\n{\n TRACE(_T(\"Timer fired - ID=%x\\n\"), id);\n}\n\n//...\n\nUINT_PTR uTimerId = SetTimer(NULL, 0, 2000, &TimerCallback);\nTRACE(_T(\"Timer created - ID=%x\\n\"), uTimerId);\n CWinApp" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
213,121
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2023977/c-difference-of-keywords-typename-and-class-in-templates">C++ difference of keywords ‘typename’ and ‘class’ in templates</a> </p> </blockquote> <p>When defining a function template or class template in C++, one can write this:</p> <pre><code>template &lt;class T&gt; ... </code></pre> <p>or one can write this:</p> <pre><code>template &lt;typename T&gt; ... </code></pre> <p>Is there a good reason to prefer one over the other?</p> <hr> <p>I accepted the most popular (and interesting) answer, but the real answer seems to be "No, there is no good reason to prefer one over the other."</p> <ul> <li>They are equivalent (except as noted below).</li> <li>Some people have reasons to always use <code>typename</code>.</li> <li>Some people have reasons to always use <code>class</code>.</li> <li>Some people have reasons to use both.</li> <li>Some people don't care which one they use.</li> </ul> <p>Note, however, that before C++17 in the case of <em>template template</em> parameters, use of <code>class</code> instead of <code>typename</code> was required. See <a href="https://stackoverflow.com/a/11311432/3964522">user1428839's answer</a> below. (But this particular case is not a matter of preference, it was a requirement of the language.)</p>
[ { "answer_id": 213135, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 10, "selected": true, "text": "class typename class" }, { "answer_id": 213149, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 6, "selected": false, "text": "static" }, { "answer_id": 213708, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 3, "selected": false, "text": "template <class IntegerType>\nclass smart_integer {\npublic: \n typedef integer_traits<Integer> traits;\n IntegerType operator+=(IntegerType value){\n typedef typename traits::larger_integer_t larger_t;\n larger_t interm = larger_t(myValue) + larger_t(value); \n if(interm > traits::max() || interm < traits::min())\n throw overflow();\n myValue = IntegerType(interm);\n }\n}\n larger_integer_t larger_integer_t" }, { "answer_id": 2558958, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "template <class T>\nclass Demonstration { \npublic:\nvoid method() {\n T::A *aObj; // oops ...\n};\n" }, { "answer_id": 11311432, "author": "JorenHeit", "author_id": 1428839, "author_profile": "https://Stackoverflow.com/users/1428839", "pm_score": 7, "selected": false, "text": "class template <template <typename, typename> class Container, typename Type>\nclass MyContainer: public Container<Type, std::allocator<Type>>\n{ /*...*/ };\n typename Container error: expected 'class' before 'Container'\n" }, { "answer_id": 11616000, "author": "user541686", "author_id": 541686, "author_profile": "https://Stackoverflow.com/users/541686", "pm_score": 4, "selected": false, "text": "class typename typename class template<template<class> typename MyTemplate, class Bar> class Foo { }; // :(\ntemplate<template<class> class MyTemplate, class Bar> class Foo { }; // :)\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
213,128
<p>We're running into issues with how we specify font sizes. If we specify the font sizes using pt, they don't always look the same across browsers/platforms. If we specify font sizes using px, IE6 users can't resize the text.</p>
[ { "answer_id": 213407, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 3, "selected": true, "text": "<style type=\"text/css\">`\nbody {\n font-size:100%;\n line-height:1.125em;\n}\n\n.bodytext p {\n font-size:0.875em;\n}\n\n.sidenote {\n font-size:0.75em;\n}\n</style>\n\n<!--[if !IE]>-->\n\n<style type=\"text/css\">\nbody {\n font-size:16px;\n}\n</style>\n\n<!--<[endif]-->\n" }, { "answer_id": 214768, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 2, "selected": false, "text": "<body> html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{border:0;outline:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;margin:0;padding:0;}\n:focus{outline:0;}\nbody{line-height:1;font-family:verdana, arial, helvetica, sans-serif;font-size:76%;}\nol,ul{list-style:none;}\ntable{border-collapse:separate;border-spacing:0;}\ncaption,th,td{text-align:left;font-weight:400;}\nblockquote:before,blockquote:after,q:before,q:after{content:\"\";}\nblockquote,q{quotes:\"\" \"\";}\na{text-decoration:none;font-weight:700;color:#000;}\na:hover{text-decoration:underline;}\nh1{font-size:2em;font-weight:400;margin-top:0;margin-bottom:0;}\nh2{font-size:1.7em;font-weight:400;margin:1.2em 0;}\nh3{font-size:1.4em;font-weight:400;margin:1.2em 0;}\nh4{font-size:1.2em;font-weight:700;margin:1.2em 0;}\nh5{font-size:1em;font-weight:700;margin:1.2em 0;}\nh6{font-size:.8em;font-weight:700;margin:1.2em 0;}\nimg{border:0;}\nol,ul,li{font-size:1em;line-height:1.8em;margin-top:.2em;margin-bottom:.1em;}\np{font-size:1em;line-height:1.8em;margin:1.2em 0;}\nli > p{margin-top:.2em;}\npre{font-family:monospace;font-size:1em;}\nstrong,b{font-weight:700;}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538/" ]
213,148
<p>Can anyone tell the function to sort the columns of a gridview in c# asp.net.</p> <p>The databound to gridview is from datacontext created using linq. I wanted to click the header of the column to sort the data.</p> <p>Thanks!</p>
[ { "answer_id": 213306, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 0, "selected": false, "text": " AllowSorting=\"true\"\n <asp:GridView />" }, { "answer_id": 213541, "author": "Daniel Schaffer", "author_id": 2596, "author_profile": "https://Stackoverflow.com/users/2596", "pm_score": 0, "selected": false, "text": "<asp:LinqDataSource ID=\"dsMyDataSource\" runat=\"server\"\nDataContextTypeName=\"MyDataContext\"\nTableName=\"MyTable\"\nAllowSort=\"true\" />\n <asp:GridView ID=\"gvMyGridView\" runat=\"server\" DataSourceID=\"dsMyDataSource\" ... />\n" }, { "answer_id": 233569, "author": "Georg", "author_id": 30776, "author_profile": "https://Stackoverflow.com/users/30776", "pm_score": 0, "selected": false, "text": "string Query= string.Empty;\nstring SortExpression = string.Empty;\n\n// HDFSort is an HiddenField !!!\n\nprotected void SortCommand_OnClick(object sender, GridViewSortEventArgs e)\n{\n SortExpression = e.SortExpression; \n Query = YourQuery + \" ORDER BY \"+SortExpression +\" \"+ HDFSort.Value ;\n HDFSort.Value = HDFSort.Value== \"ASC\" ? \"DESC\" : \"ASC\";\n RefreshGridView();\n}\n\nprotected void RefreshGridView()\n{\n GridView1.DataSource = DBObject.GetData(Query);\n GridView1.DataBind();\n}\n" }, { "answer_id": 357276, "author": "davidfowl", "author_id": 45091, "author_profile": "https://Stackoverflow.com/users/45091", "pm_score": 3, "selected": false, "text": "public static IQueryable<T> SortBy<T>(IQueryable<T> source, string sortExpression, SortDirection direction) {\n if (source == null) {\n throw new ArgumentNullException(\"source\");\n }\n\n string methodName = \"OrderBy\";\n if (direction == SortDirection.Descending) {\n methodName += \"Descending\";\n }\n\n var paramExp = Expression.Parameter(typeof(T), String.Empty);\n var propExp = Expression.PropertyOrField(paramExp, sortExpression);\n\n // p => p.sortExpression\n var sortLambda = Expression.Lambda(propExp, paramExp);\n\n var methodCallExp = Expression.Call(\n typeof(Queryable),\n methodName,\n new[] { typeof(T), propExp.Type },\n source.Expression,\n Expression.Quote(sortLambda)\n );\n\n return (IQueryable<T>)source.Provider.CreateQuery(methodCallExp);\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
213,151
<p>EDIT: It seems to be something with having the two queues in the same schema.</p> <p>I’m trying to experiment with queue propagation but I’m not seeing records in the destination queue. But that could easily be because I don’t have all the pieces in place.</p> <p>Does anyone have a test case they could post? I’ll include what I tried below. I found the troubleshooting in the docs a little light and the propagation is such a black box, it’s hard to know why this isn’t moving.</p> <p>Here’s what I have; no laughing.</p> <hr> <pre><code>CREATE OR REPLACE TYPE test_payload AS OBJECT( test_id NUMBER, test_dt DATE); DECLARE subscriber SYS.aq$_agent; BEGIN --- Create Originating Queue and start it DBMS_AQADM.create_queue_table( queue_table =&gt; 'Test_MQT', queue_payload_type =&gt; 'Test_Payload', multiple_consumers =&gt; TRUE ); --- multiple subscriber DBMS_AQADM.create_queue( 'Test_Q', 'Test_MQT' ); DBMS_AQADM.start_queue( queue_name =&gt; 'Test_Q' ); --- Create Destination Queue and start it DBMS_AQADM.create_queue_table( queue_table =&gt; 'Dest_MQT', queue_payload_type =&gt; 'Test_Payload', multiple_consumers =&gt; TRUE ); DBMS_AQADM.create_queue( 'Dest_Q', 'Dest_MQT' ); DBMS_AQADM.start_queue( queue_name =&gt; 'Dest_Q' ); --- Add Subscriber and schedule propagation subscriber := SYS.aq$_agent( 'test_local_sub', 'Dest_Q', NULL ); DBMS_AQADM.add_subscriber( queue_name =&gt; 'Test_Q', subscriber =&gt; subscriber ); DBMS_AQADM.schedule_propagation( queue_name =&gt; 'Test_Q', destination_queue =&gt; 'Dest_Q' ); END; DECLARE enqueue_options DBMS_AQ.enqueue_options_t; message_properties DBMS_AQ.message_properties_t; message_handle RAW( 16 ); MESSAGE test_payload; BEGIN MESSAGE := test_payload( 2, SYSDATE ); DBMS_AQ.enqueue( queue_name =&gt; 'Test_Q', enqueue_options =&gt; enqueue_options, message_properties =&gt; message_properties, payload =&gt; MESSAGE, msgid =&gt; message_handle ); COMMIT; END; DECLARE dequeue_options DBMS_AQ.dequeue_options_t; message_properties DBMS_AQ.message_properties_t; message_handle RAW( 16 ); MESSAGE test_payload; BEGIN dequeue_options.navigation := DBMS_AQ.first_message; DBMS_AQ.dequeue( queue_name =&gt; 'Dest_Q', dequeue_options =&gt; dequeue_options, message_properties =&gt; message_properties, payload =&gt; MESSAGE, msgid =&gt; message_handle ); DBMS_OUTPUT.put_line( 'Test_ID: ' || MESSAGE.test_id ); DBMS_OUTPUT.put_line( 'Test_Date: ' || MESSAGE.test_dt ); COMMIT; END; </code></pre>
[ { "answer_id": 215092, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 1, "selected": false, "text": "DBMS_AQADM.ENABLE_PROPAGATION_SCHEDULE(queue_name => 'Test_Q'); \n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
213,153
<p>The general problem:</p> <p>We have urls coming to our IIS web servers formatted like: </p> <blockquote> <p><strong><a href="http://www.server.com/page.aspx" rel="nofollow noreferrer">http://www.server.com/page.aspx</a></strong></p> </blockquote> <p>We are also seeing that urls like this are coming in: </p> <blockquote> <p><strong><a href="http://www.server.com//page.aspx" rel="nofollow noreferrer">http://www.server.com//page.aspx</a></strong></p> </blockquote> <p>We would like to get rid of that extra path character because when the user agent is Internet Explorer, this is resolving as 2 different pages, and thus, downloading the content twice when it should be resolved from a cache.</p> <p>I am not sure if this is a problem to be solved with something like a url-rewriting module, or if there is a configuration setting.</p>
[ { "answer_id": 215092, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 1, "selected": false, "text": "DBMS_AQADM.ENABLE_PROPAGATION_SCHEDULE(queue_name => 'Test_Q'); \n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ]
213,167
<p>I'm looking at the code for a phase accumulator, and I must be a simpleton because I don't get it. The code is simple enough:</p> <pre> Every Clock Tick do: accum = accum + NCO_param; return accum; </pre> <p>accum is a 32-bit register. Obviously, at some point it will roll-over.</p> <p>My question really is: How does this relate to the phase?</p>
[ { "answer_id": 27747391, "author": "LifeInTheTrees", "author_id": 2040877, "author_profile": "https://Stackoverflow.com/users/2040877", "pm_score": 0, "selected": false, "text": " var accadd = 1.0/( sampleRate / p2freq( note ) ) ;\n acc+= accadd;\n acc = acc%1.0;// not sure to do this as accurately using if statement. can reset acc every noteOn\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
213,173
<p>I have a single image with 9 different states and the appropriate background-position rules set up as classes to show the different states. I can't use the :hover pseudo-selector because the background image being changed is not the same element that is being hovered over. I have defined the classes this way:</p> <pre><code>#chooser_nav {width:580px; height:38px; background:transparent url(/assets/images/chooser-tabs.jpg) 0 0 no-repeat; margin-left:34px;} #chooser_nav.feat {background-position:0 0;} #chooser_nav.inv {background-position:0 -114px;} #chooser_nav.bts {background-position:0 -228px;} #chooser_nav.featinv {background-position:0 -38px;} #chooser_nav.featbts {background-position:0 -76px;} #chooser_nav.invfeat {background-position:0 -152px;} #chooser_nav.invbts {background-position:0 -190px;} #chooser_nav.btsfeat {background-position:0 -266px;} #chooser_nav.btsinv {background-position:0 -304px;} </code></pre> <p>Then, using jQuery, I have a series of hover rules based on a previous click event (the here-undeclared "cur" variable is properly declared elsewhere):</p> <pre><code> $("#featured_races a").hover(function(){ cur == "feat" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"feat"); }, function(){ $("#chooser_nav").attr("class", cur); }); $("#invitational_races a").hover(function(){ cur == "inv" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"inv"); }, function(){ $("#chooser_nav").attr("class", cur); }); $("#behind_the_scenes a").hover(function(){ cur == "bts" ? $("#chooser_nav").attr("class", cur) : $("#chooser_nav").attr("class", cur+"bts"); }, function(){ $("#chooser_nav").attr("class", cur); }); </code></pre> <p>So, in Moz and WebKit browsers, this works fine. The classes are applied and the background image changes accordingly. Works in IE7 as well. However, in IE6, the background image never changes. The classes get applied appropriately, I verified this with the DOM viewer in MS's web dev tool. So, the jQuery is working. The class is getting applied, but no change is visibly occurring.</p> <p>I'm kinda stumped here... Help me, Crackoverflow... you're my only hope...</p> <p>EDIT: As far as className vs. setAttribute... the class is changing. attr("class", cur) is working. However, once the class is changed, the resulting rules are not applied visually... but the change of class is occurring.</p> <p>EDIT 2: As for jQuery's class-specific methods: I originally had them in the code, and the result was the same. Again, the problem is not with the class not getting applied to the element... this has been verified to be happening. it's that once the class is on the element, for some reason, the element is not following the CSS rules set for that class...</p>
[ { "answer_id": 213213, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 0, "selected": false, "text": "className setAttribute()" }, { "answer_id": 215156, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 2, "selected": false, "text": "/* fix hasLayout bug for IE */\ndiv#id {\n _height : 0;\n min-height : 0;\n}\n document.body.className += '';\n div.class1.class2 {\n border : 1px solid red; /* this will normally not work in IE6 */\n}\n .inv#chooser_nav { background-position : 0 -114px; }\n #someparent .inv { background-position : 0 -114px; }\n" }, { "answer_id": 610648, "author": "Magnar", "author_id": 1123, "author_profile": "https://Stackoverflow.com/users/1123", "pm_score": 1, "selected": false, "text": "#chooser_nav.bts {background-position:0 -228px;}\n chooser_nav bts .bts {background-position:0 -228px;}\n #chooser_nav_parent .bts {background-position:0 -228px;}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9414/" ]
213,181
<p>Umm, I guess my questions in the title:</p> <p>How do I turn on Option Strict / Infer in a VB.NET aspx page without a code behind file?</p> <pre><code>&lt;%@ Page Language="VB" %&gt; &lt;script runat="server"&gt; Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) End Sub &lt;/script&gt; </code></pre>
[ { "answer_id": 213190, "author": "IAmCodeMonkey", "author_id": 27613, "author_profile": "https://Stackoverflow.com/users/27613", "pm_score": 5, "selected": true, "text": "<%@ Page Language=\"VB\" Strict=\"true\" %>\n" }, { "answer_id": 213198, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "<%@ Page Language=\"VB\" strict=\"True\" %>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
213,192
<p>In my ideal world, what I'm looking for would exist as something along the lines of this:</p> <pre><code>public string UserDefinedField { get { return _userDefinedField; } internal set { _userDefinedField = value; } set { _userDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); } } </code></pre> <p>Where one statement is executed regardless of the access modifier, and another statement is executed if it's called from an external assembly or class.</p> <p>I'm sure I could code something by using reflection and checking up the current call stack to see if the caller is in the same assembly, but I'm looking to see if there's a more elegant approach than that.</p>
[ { "answer_id": 213207, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": true, "text": "public string UserDefinedField\n{\n get { return _userDefinedField; }\n set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); }\n}\n\n// Call this from internal methods and use the public property for other cases\ninternal string SetField(string userValue)\n{\n _userDefinedField = userValue;\n}\n" }, { "answer_id": 213211, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 0, "selected": false, "text": "...\ninternal void SetUserDefinedField(string val) {\n _userDefinedField = val;\n}\n...\n" }, { "answer_id": 213296, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "public string UserDefinedField\n{\n get { return InternalUserDefinedField; }\n set { InternalUserDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); }\n}\n\ninternal string InternalUserDefinedField \n{\n get { return _userDefinedField; }\n set { _userDefinedField= value; }\n}\n" }, { "answer_id": 222095, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 0, "selected": false, "text": "// assumes callers know where they're located at in the current stack trace.\nprivate Boolean IsExternallyCalled(int methodDepth)\n{\n System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();\n\n System.Type callingType = trace.GetFrame(methodDepth).GetMethod().ReflectedType;\n System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(callingType);\n\n return !(a.Equals(System.Reflection.Assembly.GetCallingAssembly()));\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13412/" ]
213,195
<p>When I try to login to this site using my yahoo openid, it takes me to the yahoo site, I click "continue" meaning that i <em>want</em> to send my authentication details to stackoverflow.com and stackoverflow.com gives me the following error underneath the login text field:</p> <p>Unable to log in with your OpenID provider:</p> <p>failed to authenticate, returning Failed. Please ensure your identifier is correct and try again. </p>
[ { "answer_id": 213207, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": true, "text": "public string UserDefinedField\n{\n get { return _userDefinedField; }\n set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); }\n}\n\n// Call this from internal methods and use the public property for other cases\ninternal string SetField(string userValue)\n{\n _userDefinedField = userValue;\n}\n" }, { "answer_id": 213211, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 0, "selected": false, "text": "...\ninternal void SetUserDefinedField(string val) {\n _userDefinedField = val;\n}\n...\n" }, { "answer_id": 213296, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "public string UserDefinedField\n{\n get { return InternalUserDefinedField; }\n set { InternalUserDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); }\n}\n\ninternal string InternalUserDefinedField \n{\n get { return _userDefinedField; }\n set { _userDefinedField= value; }\n}\n" }, { "answer_id": 222095, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 0, "selected": false, "text": "// assumes callers know where they're located at in the current stack trace.\nprivate Boolean IsExternallyCalled(int methodDepth)\n{\n System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();\n\n System.Type callingType = trace.GetFrame(methodDepth).GetMethod().ReflectedType;\n System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(callingType);\n\n return !(a.Equals(System.Reflection.Assembly.GetCallingAssembly()));\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29049/" ]
213,214
<p>I'm in a 10 person team working on a large legacy code base with a less than ideal product owner. Our backlog is in pretty bad shape and large epics have frequently been breaking our sprints. The team also struggles with its definition of done - some members write unit test religiously, others don't, sometimes depending on time available.</p> <p>So, I've been seeing some interesting burndown patterns, and I'm wondering which patterns others are seeing and what they mean.</p> <p>Pattern 1:</p> <pre><code># # # # # # # # # # # # # # # # # # # # # # # # # # # # </code></pre> <ul> <li>Positive explanation: "All good."</li> <li>Negative explanation: "Too good to be true. What's <strong>really</strong> going on?"</li> </ul> <p>Pattern 2:</p> <pre><code># # # # # # # # # # # # # # # # # # # # # # </code></pre> <ul> <li>Positive explanation: "This was way easier than we thought, let's pull in more stories."</li> <li>Negative explanation: ??</li> </ul> <p>Pattern 3:</p> <pre><code># # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # </code></pre> <ul> <li>Positive explanation: "Not sure about this work at first, then turns out easier than we thought."</li> <li>Negative explanation: "Not enough progress, let's stop writing unit tests to get 'done' on time."</li> </ul>
[ { "answer_id": 213289, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 3, "selected": true, "text": " # # #\n # # # #\n # # # # #\n # # # # # #\n# # # # # # #\n# # # # # # # #\n# # # # # # # #\n" }, { "answer_id": 222134, "author": "Fabian Buch", "author_id": 28968, "author_profile": "https://Stackoverflow.com/users/28968", "pm_score": 0, "selected": false, "text": "#####\n#######\n########\n#########\n#########\n#########\n##########\n" }, { "answer_id": 318760, "author": "joshua.ewer", "author_id": 28664, "author_profile": "https://Stackoverflow.com/users/28664", "pm_score": 0, "selected": false, "text": "#\n##\n###\n#####\n#############\n##################\n###################\n####################\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13041/" ]
213,237
<p>In Django, given excerpts from an application <em>animals</em> likeso:</p> <p>A <em>animals/models.py</em> with: </p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType class Animal(models.Model): content_type = models.ForeignKey(ContentType,editable=False,null=True) name = models.CharField() class Dog(Animal): is_lucky = models.BooleanField() class Cat(Animal): lives_left = models.IntegerField() </code></pre> <p>And an <em>animals/urls.py</em>:</p> <pre><code>from django.conf.urls.default import * from animals.models import Animal, Dog, Cat dict = { 'model' : Animal } urlpatterns = ( url(r'^edit/(?P&lt;object_id&gt;\d+)$', 'create_update.update_object', dict), ) </code></pre> <p>How can one use generic views to edit Dog and/or Cat using the same form?</p> <p>I.e. The <em>form</em> object that is passed to <em>animals/animal_form.html</em> will be Animal, and thus won't contain any of the specifics for the derived classes Dog and Cat. How could I have Django automatically pass a form for the child class to <em>animal/animals_form.html</em>?</p> <p>Incidentally, I'm using <a href="http://www.djangosnippets.org/snippets/1031/" rel="nofollow noreferrer">Djangosnippets #1031</a> for ContentType management, so Animal would have a method named <em>as_leaf_class</em> that returns the derived class.</p> <p>Clearly, one could create forms for each derived class, but that's quite a lot of unnecessary duplication (as the templates will all be generic -- essentially {{ form.as_p }}).</p> <p>Incidentally, it's best to assume that Animal will probably be one of several unrelated base classes with the same problem, so an ideal solution would be generic.</p> <p>Thank you in advance for the help.</p>
[ { "answer_id": 213393, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 0, "selected": false, "text": "'create_update.update_object' dict 'model':Dog 'model':Cat" }, { "answer_id": 215488, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 2, "selected": true, "text": "from django.contrib.contenttypes.models import ContentType\nfrom django.views.generic import create_update\n\ndef update_object_as_child(parent_model_class):\n \"\"\"\n Given a base models.Model class, decorate a function to return \n create_update.update_object, on the child class.\n\n e.g.\n @update_object(Animal)\n def update_object(request, object_id):\n pass\n\n kwargs should have an object_id defined.\n \"\"\"\n\n def decorator(function):\n def wrapper(request, **kwargs):\n # may raise KeyError\n id = kwargs['object_id']\n\n parent_obj = parent_model_class.objects.get( pk=id )\n\n # following http://www.djangosnippets.org/snippets/1031/\n child_class = parent_obj.content_type.model_class()\n\n kwargs['model'] = child_class\n\n # rely on the generic code for testing/validation/404\n return create_update.update_object(request, **kwargs)\n return wrapper\n\n return decorator\n from mysite.core.views.create_update import update_object_as_child\n\n@update_object_as_child(Animal)\ndef edit_animal(request, object_id):\n pass\n urlpatterns += patterns('animals.views',\n url(r'^edit/(?P<object_id>\\d+)$', 'edit_animal', name=\"edit_animal\"),\n)\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
213,238
<p>Just playing around with the now released Silverlight 2.0. I'm trying to put a simple Calendar in a control. However the project doesn't seem to know what I'm talking about:-</p> <pre><code>&lt;UserControl x:Class="MyFirstSL2.Test" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" &gt; &lt;Grid Background="#FF5C7590"&gt; &lt;Calendar /&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>Visual Studio 2008 just puts blue line under the Calendar saying the type Calendar not found. Do I need to add an assembly? Which one? Do I need to add another namespace to the Xaml?</p>
[ { "answer_id": 213592, "author": "Tim Heuer", "author_id": 705, "author_profile": "https://Stackoverflow.com/users/705", "pm_score": 5, "selected": true, "text": "xmlns:basics=\"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls\"\n <basics:Calendar />\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17516/" ]
213,249
<p>I am wondering - What's the most effective way of parsing something like:</p> <pre><code>{{HEADER}} Hello my name is {{NAME}} {{#CONTENT}} This is the content ... {{#PERSONS}} &lt;p&gt;My name is {{NAME}}.&lt;/p&gt; {{/PERSONS}} {{/CONTENT}} {{FOOTER}} </code></pre> <p>Of course this is intended to be somewhat of a templating system in the end, so my plan is to create a hashmap to "lay over" the template, as something like this</p> <pre><code>$hash = array( 'HEADER' =&gt; 'This is a header', 'NAME' =&gt; 'David', 'CONTENT' =&gt; array('PERSONS' =&gt; array(array('NAME' =&gt; 'Heino'), array('NAME' =&gt; 'Sebastian')), 'FOOTER' =&gt; 'This is the footer' ); </code></pre> <p>It's worth noticing that the "sections" (the tags that start with #), can be repeated more than once, and i think this is what trips me up ...</p> <p>Also, any section can contain any number of other sections, and regular tags...</p> <p>So.. how'd you do it?</p>
[ { "answer_id": 213344, "author": "Troy Howard", "author_id": 19258, "author_profile": "https://Stackoverflow.com/users/19258", "pm_score": 2, "selected": true, "text": "This is the content ...\n\nMy name is Heino.\n\nMy name is Sebastian.\n" }, { "answer_id": 213589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<?php echo $HEADER ?>\n\nHello my name is <?php echo $NAME?>\n\n<div id=\"CONTENT\">\n This is the content ...\n\n <?php foreach ($PERSONS as $PERSON) : ?>\n\n <p>My name is <?php echo $PERSON['NAME']?>.</p>\n\n <?php endforeach ?>\n\n</div>\n\n<?php echo $FOOTER ?>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538/" ]
213,251
<p>I've been reading that Adobe has made crossdomain.xml stricter in flash 9-10 and I'm wondering of someone can paste me a copy of one that they know works. Having some trouble finding a recent sample on Adobe's site.</p>
[ { "answer_id": 213272, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 8, "selected": true, "text": "<?xml version=\"1.0\" ?>\n<cross-domain-policy>\n<allow-access-from domain=\"*\" />\n</cross-domain-policy>\n" }, { "answer_id": 215346, "author": "ThePants", "author_id": 29260, "author_profile": "https://Stackoverflow.com/users/29260", "pm_score": 5, "selected": false, "text": "<?xml version=\"1.0\" ?>\n<cross-domain-policy>\n <site-control permitted-cross-domain-policies=\"master-only\"/>\n <allow-access-from domain=\"*\"/>\n <allow-http-request-headers-from domain=\"*\" headers=\"*\"/>\n</cross-domain-policy>\n" }, { "answer_id": 5472417, "author": "Zhami", "author_id": 65934, "author_profile": "https://Stackoverflow.com/users/65934", "pm_score": 5, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<cross-domain-policy xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://www.adobe.com/xml/schemas/PolicyFile.xsd\">\n <allow-access-from domain=\"twitter.com\" />\n <allow-access-from domain=\"api.twitter.com\" />\n <allow-access-from domain=\"search.twitter.com\" />\n <allow-access-from domain=\"static.twitter.com\" />\n <site-control permitted-cross-domain-policies=\"master-only\"/>\n <allow-http-request-headers-from domain=\"*.twitter.com\" headers=\"*\" secure=\"true\"/>\n</cross-domain-policy>\n" }, { "answer_id": 10259429, "author": "trante", "author_id": 429938, "author_profile": "https://Stackoverflow.com/users/429938", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\"?>\n<cross-domain-policy>\n<allow-access-from domain=\"www.mysite.com\" />\n<allow-access-from domain=\"mysite.com\" />\n</cross-domain-policy>\n" }, { "answer_id": 31488228, "author": "ThisClark", "author_id": 1161948, "author_profile": "https://Stackoverflow.com/users/1161948", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\"?>\n<!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">\n<cross-domain-policy>\n <!-- Read this: https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->\n\n <!-- Most restrictive policy: -->\n <site-control permitted-cross-domain-policies=\"none\"/>\n\n <!-- Least restrictive policy: -->\n <!--\n <site-control permitted-cross-domain-policies=\"all\"/>\n <allow-access-from domain=\"*\" to-ports=\"*\" secure=\"false\"/>\n <allow-http-request-headers-from domain=\"*\" headers=\"*\" secure=\"false\"/>\n -->\n</cross-domain-policy>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
213,256
<p>I am trying to debug a strange issue with users that have <a href="https://secure.logmein.com/home.asp" rel="nofollow noreferrer">LogMeIn</a> installed. After a few days, some of my dialogs that my app opens can end up offscreen. If I could reliable detect that, I could programmatically move the dialogs back where they are visible again.</p> <p>Note: this has to work for multiple monitors and use the win32 API. However, if you know how to do it from .NET I can probably extrapolate from there...</p> <p><strong>Update:</strong> For the curious, the bug mentioned above has to do with wxWidgets. If you run a wxWidgets application, then walk away and let your screen saver go, then log in remotely with LogMeIn, then try to open a dialog from your app, you will have trouble if you use wxDisplay::GetFromPoint(pos) or wxWindowBase::Center() to position the dialog.</p>
[ { "answer_id": 5454407, "author": "CAD bloke", "author_id": 492, "author_profile": "https://Stackoverflow.com/users/492", "pm_score": 1, "selected": false, "text": "if (!Screen.FromControl(this).Bounds.Contains(this.Location))\n {\n this.DesktopLocation = new Point(100,100);\n }\n" }, { "answer_id": 64193144, "author": "Ben Thompson", "author_id": 4669174, "author_profile": "https://Stackoverflow.com/users/4669174", "pm_score": 0, "selected": false, "text": "public static class WindowLocation\n{\n public static Boolean VisibleOnScreen(this Form form)\n {\n foreach (Screen screen in Screen.AllScreens)\n {\n if (screen.Bounds.Contains(form.Bounds)) return true;\n }\n\n return false;\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ]
213,266
<p>How do I go about positioning a JDialog at the center of the screen?</p>
[ { "answer_id": 213291, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 8, "selected": true, "text": "final JDialog d = new JDialog();\nd.setSize(200,200);\nd.setLocationRelativeTo(null);\nd.setVisible(true);\n final JDialog d = new JDialog();\nd.setSize(200, 200);\nfinal Toolkit toolkit = Toolkit.getDefaultToolkit();\nfinal Dimension screenSize = toolkit.getScreenSize();\nfinal int x = (screenSize.width - d.getWidth()) / 2;\nfinal int y = (screenSize.height - d.getHeight()) / 2;\nd.setLocation(x, y);\nd.setVisible(true);\n" }, { "answer_id": 582346, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "import java.awt.*;\nimport javax.swing.JFrame;\n\n/**\n * Méthodes statiques pour récupérer les informations d'un écran.\n *\n * @author Jean-Claude Stritt\n * @version 1.0 / 24.2.2009\n */\npublic class ScreenInfo {\n\n /**\n * Permet de récupérer le numéro de l'écran par rapport à la fenêtre affichée.\n * @return le numéro 1, 2, ... (ID) de l'écran\n */\n public static int getScreenID( JFrame jf ) {\n int scrID = 1;\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n GraphicsDevice[] gd = ge.getScreenDevices();\n for (int i = 0; i < gd.length; i++) {\n GraphicsConfiguration gc = gd[i].getDefaultConfiguration();\n Rectangle r = gc.getBounds();\n if (r.contains(jf.getLocation())) {\n scrID = i+1;\n }\n }\n return scrID;\n }\n\n /**\n * Permet de récupérer la dimension (largeur, hauteur) en px d'un écran spécifié.\n * @param scrID --> le n° d'écran\n * @return la dimension (largeur, hauteur) en pixels de l'écran spécifié\n */\n public static Dimension getScreenDimension( int scrID ) {\n Dimension d = new Dimension(0, 0);\n if (scrID > 0) {\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n DisplayMode mode = ge.getScreenDevices()[scrID - 1].getDisplayMode();\n d.setSize(mode.getWidth(), mode.getHeight());\n }\n return d;\n }\n\n /**\n * Permet de récupérer la largeur en pixels d'un écran spécifié.\n * @param scrID --> le n° d'écran\n * @return la largeur en px de l'écran spécifié\n */\n public static int getScreenWidth( int scrID ) {\n Dimension d = getScreenDimension(scrID);\n return d.width;\n }\n\n /**\n * Permet de récupérer la hauteur en pixels d'un écran spécifié.\n * @param scrID --> le n° d'écran\n * @return la hauteur en px de l'écran spécifié\n */\n public static int getScreenHeight( int scrID ) {\n Dimension d = getScreenDimension(scrID);\n return d.height;\n }\n\n}\n" }, { "answer_id": 9577907, "author": "Java42", "author_id": 1250303, "author_profile": "https://Stackoverflow.com/users/1250303", "pm_score": 3, "selected": false, "text": "// Center on screen ( absolute true/false (exact center or 25% upper left) )\npublic void centerOnScreen(final Component c, final boolean absolute) {\n final int width = c.getWidth();\n final int height = c.getHeight();\n final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n int x = (screenSize.width / 2) - (width / 2);\n int y = (screenSize.height / 2) - (height / 2);\n if (!absolute) {\n x /= 2;\n y /= 2;\n }\n c.setLocation(x, y);\n}\n\n// Center on parent ( absolute true/false (exact center or 25% upper left) )\npublic void centerOnParent(final Window child, final boolean absolute) {\n child.pack();\n boolean useChildsOwner = child.getOwner() != null ? ((child.getOwner() instanceof JFrame) || (child.getOwner() instanceof JDialog)) : false;\n final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n final Dimension parentSize = useChildsOwner ? child.getOwner().getSize() : screenSize ;\n final Point parentLocationOnScreen = useChildsOwner ? child.getOwner().getLocationOnScreen() : new Point(0,0) ;\n final Dimension childSize = child.getSize();\n childSize.width = Math.min(childSize.width, screenSize.width);\n childSize.height = Math.min(childSize.height, screenSize.height);\n child.setSize(childSize); \n int x;\n int y;\n if ((child.getOwner() != null) && child.getOwner().isShowing()) {\n x = (parentSize.width - childSize.width) / 2;\n y = (parentSize.height - childSize.height) / 2;\n x += parentLocationOnScreen.x;\n y += parentLocationOnScreen.y;\n } else {\n x = (screenSize.width - childSize.width) / 2;\n y = (screenSize.height - childSize.height) / 2;\n }\n if (!absolute) {\n x /= 2;\n y /= 2;\n }\n child.setLocation(x, y);\n}\n" }, { "answer_id": 15926711, "author": "Kunax", "author_id": 2266196, "author_profile": "https://Stackoverflow.com/users/2266196", "pm_score": 4, "selected": false, "text": "pack() setLocation((Toolkit.getDefaultToolkit().getScreenSize().width)/2 - getWidth()/2, (Toolkit.getDefaultToolkit().getScreenSize().height)/2 - getHeight()/2);\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
213,267
<p>I'm trying to pass one method to another in elisp, and then have that method execute it. Here is an example:</p> <pre><code>(defun t1 () "t1") (defun t2 () "t1") (defun call-t (t) ; how do I execute "t"? (t)) ; How do I pass in method reference? (call-t 't1) </code></pre>
[ { "answer_id": 213511, "author": "Timo Geusch", "author_id": 29068, "author_profile": "https://Stackoverflow.com/users/29068", "pm_score": 6, "selected": true, "text": "t (defun test-func-1 () \"test-func-1\"\n (interactive \"*\")\n (insert-string \"testing callers\"))\n\n(defun func-caller (callee)\n \"Execute callee\"\n (funcall callee))\n\n(func-caller 'test-func-1)\n" }, { "answer_id": 226770, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 3, "selected": false, "text": "#' '" }, { "answer_id": 63721766, "author": "Víctor Ponce", "author_id": 13667103, "author_profile": "https://Stackoverflow.com/users/13667103", "pm_score": 0, "selected": false, "text": "(defun n1 ()\n \"n1\")\n\n(defmacro call-n (n)\n (apply n))\n\n(call-n (n1))\n (defmacro for (i &optional i++ &rest body)\n \"c-like for-loop\"\n (unless (numberp i++) (push i++ body) (setq i++ 1))\n\n (while (/= i 0)\n (let ((args 0))\n (while (nth args body)\n (apply (car (nth args body))\n (cdr (nth args body)))\n (setq args (1+ args))))\n (setq i (- i i++))\n )\n )\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9435/" ]
213,271
<p>window.scrollMaxY can be set via that property in IE and older versions of Firefox, but when trying in FF3 it says "Cannot set this property as it only has a getter".</p> <p>What is my alternative?</p> <p>EDIT:</p> <p>The reason why I'm asking is that I'm fixing some very horrible JS written by someone else, it has a function to keep a div centered on the page while scrolling, and has this line:</p> <pre><code>// Fixes Firefox incrementing page height while scrolling window.scrollMaxY = scrollMaxY </code></pre> <p>Obviously this doesn't work, but the main issue is that when the page is scrolled, it grows in length.</p>
[ { "answer_id": 213511, "author": "Timo Geusch", "author_id": 29068, "author_profile": "https://Stackoverflow.com/users/29068", "pm_score": 6, "selected": true, "text": "t (defun test-func-1 () \"test-func-1\"\n (interactive \"*\")\n (insert-string \"testing callers\"))\n\n(defun func-caller (callee)\n \"Execute callee\"\n (funcall callee))\n\n(func-caller 'test-func-1)\n" }, { "answer_id": 226770, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 3, "selected": false, "text": "#' '" }, { "answer_id": 63721766, "author": "Víctor Ponce", "author_id": 13667103, "author_profile": "https://Stackoverflow.com/users/13667103", "pm_score": 0, "selected": false, "text": "(defun n1 ()\n \"n1\")\n\n(defmacro call-n (n)\n (apply n))\n\n(call-n (n1))\n (defmacro for (i &optional i++ &rest body)\n \"c-like for-loop\"\n (unless (numberp i++) (push i++ body) (setq i++ 1))\n\n (while (/= i 0)\n (let ((args 0))\n (while (nth args body)\n (apply (car (nth args body))\n (cdr (nth args body)))\n (setq args (1+ args))))\n (setq i (- i i++))\n )\n )\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
213,295
<p>I'm storing an ArrayList of Ids in a processing script that I want to spit out as a comma delimited list for output to the debug log. Is there a way I can get this easily without looping through things?</p> <p>EDIT: Thanks to Joel for pointing out the List(Of T) that is available in .net 2.0 and above. That makes things TONS easier if you have it available.</p>
[ { "answer_id": 213305, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 8, "selected": true, "text": "String.Join(\",\", CType(TargetArrayList.ToArray(Type.GetType(\"System.String\")), String()))\n string.Join(\",\", (string[])TargetArrayList.ToArray(Type.GetType(\"System.String\")))\n String.Join(\",\", TargetList.ToArray())\n" }, { "answer_id": 213320, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 4, "selected": false, "text": "String.Join(\",\", myArrayList.toArray(string.GetType()) );\n string.Join(\",\", Array.ConvertAll<object, string>(a.ToArray(), Convert.ToString));\n" }, { "answer_id": 213367, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 2, "selected": false, "text": "foo.ToArray().Aggregate((a, b) => (a + \",\" + b)).ToString()\n string.Concat(foo.ToArray().Select(a => a += \",\").ToArray())\n" }, { "answer_id": 213448, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "String.Join(\",\", x.Cast(Of String)().ToArray())\n Console.WriteLine(String.Join(\",\", CType(x.ToArray(GetType(String)), String())))\n AddressOf Convert.ToString Convert" }, { "answer_id": 10191829, "author": "Jim Lahman", "author_id": 584962, "author_profile": "https://Stackoverflow.com/users/584962", "pm_score": 2, "selected": false, "text": "List<string> histList = new List<string>();\nhistList.Add(dt.ToString(\"MM/dd/yyyy::HH:mm:ss.ffff\"));\nhistList.Add(Index.ToString());\n/*arValue is array of Singles */\nforeach (Single s in arValue)\n{\n histList.Add(s.ToString());\n}\nString HistLine = String.Join(\",\", histList.ToArray());\n" }, { "answer_id": 35198293, "author": "bashburak", "author_id": 5882534, "author_profile": "https://Stackoverflow.com/users/5882534", "pm_score": 3, "selected": false, "text": "string.Join(\" ,\", myArrayList.ToArray());" }, { "answer_id": 65640025, "author": "Monzur", "author_id": 1331294, "author_profile": "https://Stackoverflow.com/users/1331294", "pm_score": 0, "selected": false, "text": "//CPID[] is the array\nstring cps = \"\";\nif (CPID.Length > 0)\n{ \n foreach (var item in CPID)\n {\n cps += item.Trim() + \",\";\n }\n}\n//Use the string cps\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
213,299
<p>I've implemented a .NET Web control that uses the callback structure implemented in ASP.Net 2.0. It's an autodropdown control, and it works correctly in IE 6.0/7.0 and Google Chrome. Here's the relevant callback function:</p> <pre><code>function ReceiveServerData(args, context) { document.getElementById(context).style.zIndex = 300; document.getElementById(context).style.visibility = 'visible'; document.getElementById(context).innerHTML = args; fixHover(context); } </code></pre> <p>In Firefox, "args" is always the same data, so the innerHTML of the <code>&lt;div&gt;</code> that is the display for my dropdown always shows the same items. I've doublechecked my client-side code, and the right information is being sent client->server and in return server-> client.</p> <p>Of note, in the "WebForm_DoCallback" function created by the .NET framework, the following snippet is getting called:</p> <pre><code>if (setRequestHeaderMethodExists) { xmlRequest.onreadystatechange = WebForm_CallbackComplete; callback.xmlRequest = xmlRequest; xmlRequest.open("POST", theForm.action, true); xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlRequest.send(postData); return; } </code></pre> <p>and the callback function ReceiveServerData is called both on <code>xmlRequest.open("POST", theForm.action, true);</code> and <code>xmlRequest.send(postData);</code>. I wonder if this is causing an error, but I'm at the end of my debugging skills.</p> <p>Edited to add -- ReceiveServerData is not being called twice the very first time I use the dropdown -- in fact, the dropdown works correctly for the very first keystroke. It stops working, and doubles the callback with old return data, after the first keystroke.</p>
[ { "answer_id": 220090, "author": "Atanas Korchev", "author_id": 10141, "author_profile": "https://Stackoverflow.com/users/10141", "pm_score": 0, "selected": false, "text": "function WebForm_CallbackComplete()\n{\n for(var i=0; i< __pendingCallbacks.length;i++)\n {\n var _f3=__pendingCallbacks[i];\n if(_f3 && _f3.xmlRequest && (_f3.xmlRequest.readyState==4))\n {\n __pendingCallbacks[i]=null;\n WebForm_ExecuteCallback(_f3);\n if(!_f3.async)\n {\n __synchronousCallBackIndex=-1;\n }\n var _f4=\"__CALLBACKFRAME\"+i;\n var _f5=document.getElementById(_f4);\n if(_f5)\n {\n _f5.parentNode.removeChild(_f5);\n }\n }\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11947/" ]
213,303
<p>There are many tools out there for writing and managing requirements, but are there any good ones for reviewing them? </p> <p>I'm not talking about <strong><em>managing</em></strong> reviews, but automation tools that look for common requirement blunders (such as using negative requirements, or ones that are worded in a way that makes testing difficult).<br> More of a screening tool that someone writing requirements can use to screen their document before distributing to a group of reviewers so that the review process need not be slowed down by everyone commenting on the same easily recognizable issues.</p> <p>I'm curious if anyone's used anything like this in the past.</p>
[ { "answer_id": 213452, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ReqCheck>\n <Categories name=\"Reconsider wording\">\n <Keyword>may</Keyword>\n <Keyword>should</Keyword>\n </Categories>\n <Categories name=\"Potential logic problem\" format=\"{0}: consider both then and else conditions.\">\n <Keyword>not</Keyword>\n </Categories>\n</ReqCheck>\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2382102/" ]
213,309
<p>Is it possible to create, for instance, a box model hack while using in-line CSS?</p> <p>For example:</p> <p><code>&lt;div id="blah" style="padding: 5px; margin: 5px; width: 30px; /*IE5-6 Equivalent here*/"&gt;</code></p> <p>Thanks! </p>
[ { "answer_id": 213342, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<div id=\"blah\" style=\"padding: 5px; margin: 5px; width: 30px; <!--[if lte IE 6]> ... <![endif]-->\">\n" }, { "answer_id": 213351, "author": "alexp206", "author_id": 666, "author_profile": "https://Stackoverflow.com/users/666", "pm_score": 2, "selected": false, "text": "<!--[if lt IE 7]>\n<style>\n#blah {\npadding: 5px;\nmargin: 5px;\nwidth: 30px;\n}\n</style>\n<![endif]-->\n" }, { "answer_id": 213458, "author": "John Dunagan", "author_id": 28939, "author_profile": "https://Stackoverflow.com/users/28939", "pm_score": 3, "selected": false, "text": ".foo {\npadding: 5px;\n^padding: 4px; /* this targets all IE, including 7. It must go first, or it overrides the following hack */\n_padding: 3px; /* this targets >= IE6 */\nwidth: 30px;\n}\n" }, { "answer_id": 213612, "author": "Atanas Korchev", "author_id": 10141, "author_profile": "https://Stackoverflow.com/users/10141", "pm_score": 4, "selected": false, "text": "<div style=\"*background:red\"></div>\n" }, { "answer_id": 213673, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 0, "selected": false, "text": "voice-family" }, { "answer_id": 214048, "author": "Paul M", "author_id": 28241, "author_profile": "https://Stackoverflow.com/users/28241", "pm_score": 0, "selected": false, "text": "print(\"code sample\");\n\n style=\"position:relative;padding:5px; _position:absolute; _padding:10px;\" \n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
213,312
<p>Can Ruby really be used as a functional language? What are some good tutorials to teach this facet of the language? Note: I really want to use and stick with Ruby as my primary language so I am not interested at this point in being converted to YAFL (yet another functional language). I am really interested in how well Ruby's functional facets perform against the standard functional language baseline. Thanks.</p>
[ { "answer_id": 213336, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 4, "selected": false, "text": "Object#freeze Array Hash String gsub! map zip" }, { "answer_id": 214330, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 0, "selected": false, "text": "def foo(n)\n puts n\n foo(n + 1)\nend\n\nfoo(1)\n SystemStackError: stack level too deep\n from (irb):2:in `puts'\n from (irb):2:in `foo'\n from (irb):3:in `foo'\n from (irb):5\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20714/" ]
213,333
<p>I have a generic class in C# with 2 constructors:</p> <pre><code>public Houses(params T[] InitialiseElements) {} public Houses(int Num, T DefaultValue) {} </code></pre> <p>Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view).</p> <p>E.g. <code>Houses&lt;int&gt; houses = new Houses&lt;int&gt;(1,2)</code> - calls the 2nd construtor. Passing in any other number of ints into the constructor will call the 1st constructor.</p> <p>Is there any way around this other than removing the params keyword and forcing users to pass an array of T when using the first constructor?</p>
[ { "answer_id": 213354, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 2, "selected": false, "text": "public Houses(IEnumerable<T> InitialiseElements){}\n" }, { "answer_id": 213403, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "public static class Houses\n{\n public static Houses<T> CreateFromElements<T>(params T[] initialElements)\n {\n return new Houses<T>(initialElements);\n }\n\n public Houses<T> CreateFromDefault<T>(int count, T defaultValue)\n {\n return new Houses<T>(count, defaultValue);\n }\n}\n Houses<string> x = Houses.CreateFromDefault(10, \"hi\");\nHouses<int> y = Houses.CreateFromElements(20, 30, 40);\n" }, { "answer_id": 213807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace GenericTest\n{\n public class House<T>\n {\n public House(params T[] values)\n {\n System.Console.WriteLine(\"Params T[]\");\n }\n public House(int num, T defaultVal)\n {\n System.Console.WriteLine(\"int, T\");\n }\n\n public static House<T> CreateFromDefault<T>(int count, T defaultVal)\n {\n return new House<T>(count, defaultVal);\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n House<int> test = new House<int>(1, 2); // prints int, t\n House<int> test1 = new House<int>(new int[] {1, 2}); // prints parms\n House<string> test2 = new House<string>(1, \"string\"); // print int, t\n House<string> test3 = new House<string>(\"string\", \"string\"); // print parms\n House<int> test4 = House<int>.CreateFromDefault<int>(1, 2); // print int, t\n }\n }\n}\n" } ]
2008/10/17
[ "https://Stackoverflow.com/questions/213333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29059/" ]