qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
189,588
|
<p>I've been led to believe that for single variable assignment in T-SQL, <code>set</code> is the best way to go about things, for two reasons:</p>
<ul>
<li>it's the ANSI standard for variable assignment</li>
<li>it's actually faster than doing a SELECT (for a single variable)</li>
</ul>
<p>So...</p>
<pre><code>SELECT @thingy = 'turnip shaped'
</code></pre>
<p>becomes</p>
<pre><code>SET @thingy = 'turnip shaped'
</code></pre>
<p>But how fast, is <em>fast</em>? Am I ever really going to notice the difference?</p>
|
[
{
"answer_id": 189727,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 4,
"selected": true,
"text": "SET NOCOUNT ON\n\nDECLARE @runs int\nDECLARE @i int, @j int\nSET @runs = 1\nSET @i = 0\nSET @j = 0\n\nDECLARE @dtStartDate datetime, @dtEndDate datetime\n\n\nWHILE @runs > 0\n BEGIN\n SET @j = 0\n SET @dtStartDate = CURRENT_TIMESTAMP\n WHILE @j < 1000000\n BEGIN\n SET @i = @j\n SET @j = @j + 1\n END\n SELECT @dtEndDate = CURRENT_TIMESTAMP\n SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SET_MILLISECONDS\n\n\n SET @j = 0\n SET @dtStartDate = CURRENT_TIMESTAMP\n WHILE @j < 1000000\n BEGIN\n SELECT @i = @j\n SET @j = @j + 1\n END\n SELECT @dtEndDate = CURRENT_TIMESTAMP\n SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SELECT_MILLISECONDS\n\n SET @runs = @runs - 1\n END\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
189,621
|
<p>I am wondering if someone can put a bit of an authoritative reference summary of when the !important declaration in CSS does <strong>not</strong> work to override inline styles.</p>
|
[
{
"answer_id": 189661,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 4,
"selected": false,
"text": "someselector {\n property: value !important;\n same-property: another-value;\n}\n"
},
{
"answer_id": 71161879,
"author": "CSSBurner",
"author_id": 9858653,
"author_profile": "https://Stackoverflow.com/users/9858653",
"pm_score": 1,
"selected": false,
"text": "!important <div id=\"bad-div\" style=\"margin-left: 5px\"></div>\n #bad-div {\n width: 100px;\n height: 100px;\n animation: marginLeftInvalid 4s infinite ease-in 1s\n}\n\n@keyframes marginLeftInvalid {\n 0% {\n margin-left: 100px!important\n }\n 100% {\n margin-left: 500px\n }\n}\n @keyframes margin-left <div> 0% <div id=\"good-div\" style=\"margin-left: 5px\"></div>\n\n#good-div {\n width: 100px;\n height: 100px;\n animation: marginLeftValid 4s infinite ease-in 1s\n}\n\n@keyframes marginLeftValid {\n 0% {\n margin-left: 100px\n }\n 100% {\n margin-left: 500px\n }\n}\n margin-left 0% margin-left !important @font-face style=\"font-family: moderna\" h1 h1 !important 'moderna' font-family @font-face src format() h1 h1 {...} font-family: 'arsenalregular' !important 'arsenalregular' font-family @font-face 'moderna' h1 !important 'moderna' h1 arsenalregular h1 {...} @counter-style !important symbols suffix !important suffix !important @supports @layer @layer"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
189,645
|
<p>Given the following code (that doesn't work):</p>
<pre><code>while True:
# Snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 # This doesn't work :(
if ok.lower() == "n": break
# Do more processing with menus and stuff
</code></pre>
<p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p>
|
[
{
"answer_id": 189664,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 7,
"selected": false,
"text": "class GetOutOfLoop( Exception ):\n pass\n\ntry:\n done= False\n while not done:\n isok= False\n while not (done or isok):\n ok = get_input(\"Is this ok? (y/n)\")\n if ok in (\"y\", \"Y\") or ok in (\"n\", \"N\") : \n done= True # probably better\n raise GetOutOfLoop\n # other stuff\nexcept GetOutOfLoop:\n pass\n"
},
{
"answer_id": 189666,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 6,
"selected": false,
"text": "#import the stuff\nfrom goto import goto, label\n\nwhile True:\n #snip: print out current state\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\": goto .breakall\n if ok == \"n\" or ok == \"N\": break\n #do more processing with menus and stuff\nlabel .breakall\n"
},
{
"answer_id": 189685,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 10,
"selected": true,
"text": "return"
},
{
"answer_id": 189696,
"author": "quick_dry",
"author_id": 3716,
"author_profile": "https://Stackoverflow.com/users/3716",
"pm_score": 4,
"selected": false,
"text": "keeplooping = True\nwhile keeplooping:\n # Do stuff\n while keeplooping:\n # Do some other stuff\n if finisheddoingstuff():\n keeplooping = False\n"
},
{
"answer_id": 189838,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 4,
"selected": false,
"text": "def loop():\n while True:\n #snip: print out current state\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\": return\n if ok == \"n\" or ok == \"N\": break\n #do more processing with menus and stuff\n"
},
{
"answer_id": 2621659,
"author": "Matt Billenstein",
"author_id": 314462,
"author_profile": "https://Stackoverflow.com/users/314462",
"pm_score": 3,
"selected": false,
"text": "def it(rows, cols, images):\n i = 0\n for r in xrange(rows):\n for c in xrange(cols):\n if i >= len(images):\n return\n yield r, c, images[i]\n i += 1 \n\nfor r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']):\n ... do something with r, c, image ...\n"
},
{
"answer_id": 3150107,
"author": "yak",
"author_id": 380157,
"author_profile": "https://Stackoverflow.com/users/380157",
"pm_score": 9,
"selected": false,
"text": "for a in xrange(10):\n for b in xrange(20):\n if something(a, b):\n # Break the inner loop...\n break\n else:\n # Continue if the inner loop wasn't broken.\n continue\n # Inner loop was broken, break the outer.\n break\n continue continue"
},
{
"answer_id": 3171971,
"author": "Mark Dickinson",
"author_id": 270986,
"author_profile": "https://Stackoverflow.com/users/270986",
"pm_score": 6,
"selected": false,
"text": "with from contextlib import contextmanager\n@contextmanager\ndef nested_break():\n class NestedBreakException(Exception):\n pass\n try:\n yield NestedBreakException\n except NestedBreakException:\n pass\n with nested_break() as mylabel:\n while True:\n print \"current state\"\n while True:\n ok = raw_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\": raise mylabel\n if ok == \"n\" or ok == \"N\": break\n print \"more processing\"\n Exception nested_break Exception"
},
{
"answer_id": 6564670,
"author": "krvolok",
"author_id": 827133,
"author_profile": "https://Stackoverflow.com/users/827133",
"pm_score": 6,
"selected": false,
"text": "breaker = False #our mighty loop exiter!\nwhile True:\n while True:\n if conditionMet:\n #insert code here...\n breaker = True \n break\n if breaker: # the interesting part!\n break # <--- !\n"
},
{
"answer_id": 10930656,
"author": "alu5",
"author_id": 1442038,
"author_profile": "https://Stackoverflow.com/users/1442038",
"pm_score": -1,
"selected": false,
"text": "breaker = False #our mighty loop exiter!\nwhile True:\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n breaker+= (ok.lower() == \"y\")\n break\n\n if breaker: # the interesting part!\n break # <--- !\n"
},
{
"answer_id": 11974716,
"author": "Nathan Garabedian",
"author_id": 546302,
"author_profile": "https://Stackoverflow.com/users/546302",
"pm_score": 1,
"selected": false,
"text": "for x in array:\n for y in dont_use_these_values:\n if x.value==y:\n array.remove(x) # fixed, was array.pop(x) in my original answer\n continue\n\n do some other stuff with x\n for x in array:\n for y in dont_use_these_values:\n if x.value==y:\n array.remove(x) # fixed, was array.pop(x) in my original answer\n continue\n\nfor x in array:\n do some other stuff with x\n"
},
{
"answer_id": 13252668,
"author": "Mauro",
"author_id": 1459120,
"author_profile": "https://Stackoverflow.com/users/1459120",
"pm_score": 4,
"selected": false,
"text": "dejaVu = True\n\nwhile dejaVu:\n while True:\n ok = raw_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\" or ok == \"n\" or ok == \"N\":\n dejaVu = False\n break\n"
},
{
"answer_id": 15559616,
"author": "Rusty Rob",
"author_id": 632088,
"author_profile": "https://Stackoverflow.com/users/632088",
"pm_score": 2,
"selected": false,
"text": "from itertools import repeat\ninputs = (get_input(\"Is this ok? (y/n)\") for _ in repeat(None))\nresponse = (i.lower()==\"y\" for i in inputs if i.lower() in (\"y\", \"n\"))\n\nwhile True:\n #snip: print out current state\n if next(response):\n break\n #do more processing with menus and stuff\n"
},
{
"answer_id": 17092776,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 2,
"selected": false,
"text": "# this version uses a level counter to choose how far to break out\n\nbreak_levels = 0\nwhile True:\n # snip: print out current state\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\":\n break_levels = 1 # how far nested, excluding this break\n break\n if ok == \"n\" or ok == \"N\":\n break # normal break\n if break_levels:\n break_levels -= 1\n break # pop another level\nif break_levels:\n break_levels -= 1\n break\n\n# ...and so on\n"
},
{
"answer_id": 17093146,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 2,
"selected": false,
"text": "# this version breaks up to a certain label\n\nbreak_label = None\nwhile True:\n # snip: print out current state\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\":\n break_label = \"outer\" # specify label to break to\n break\n if ok == \"n\" or ok == \"N\":\n break\n if break_label:\n if break_label != \"inner\":\n break # propagate up\n break_label = None # we have arrived!\nif break_label:\n if break_label != \"outer\":\n break # propagate up\n break_label = None # we have arrived!\n\n#do more processing with menus and stuff\n"
},
{
"answer_id": 32023069,
"author": "Loax",
"author_id": 1526490,
"author_profile": "https://Stackoverflow.com/users/1526490",
"pm_score": 2,
"selected": false,
"text": "def user_confirms():\n while True:\n answer = input(\"Is this OK? (y/n) \").strip().lower()\n if answer in \"yn\":\n return answer == \"y\"\n\ndef main():\n while True:\n # do stuff\n if user_confirms():\n break\n"
},
{
"answer_id": 33121569,
"author": "holroy",
"author_id": 1548472,
"author_profile": "https://Stackoverflow.com/users/1548472",
"pm_score": 2,
"selected": false,
"text": "while ... else while else continue break else while True:\n #snip: print out current state\n ok = \"\"\n while ok != \"y\" and ok != \"n\":\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"n\" or ok == \"N\":\n break # Breaks out of inner loop, skipping else\n\n else:\n break # Breaks out of outer loop\n\n #do more processing with menus and stuff\n while for else"
},
{
"answer_id": 40120729,
"author": "Skycc",
"author_id": 7031759,
"author_profile": "https://Stackoverflow.com/users/7031759",
"pm_score": 1,
"selected": false,
"text": "break_level = 0\n# while break_level < 3: # if we have another level of nested loop here\nwhile break_level < 2:\n #snip: print out current state\n while break_level < 1:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\": break_level = 2 # break 2 level\n if ok == \"n\" or ok == \"N\": break_level = 1 # break 1 level\n"
},
{
"answer_id": 40917562,
"author": "Peeyush Kushwaha",
"author_id": 1412255,
"author_profile": "https://Stackoverflow.com/users/1412255",
"pm_score": 2,
"selected": false,
"text": "for i, j in ((i, j) for i in A for j in B):\n print(i , j)\n if (some_condition):\n break\n"
},
{
"answer_id": 42946779,
"author": "helmsdeep",
"author_id": 4120359,
"author_profile": "https://Stackoverflow.com/users/4120359",
"pm_score": 1,
"selected": false,
"text": "while True:\n break_statement=0\n while True:\n ok = raw_input(\"Is this ok? (y/n)\")\n if ok == \"n\" or ok == \"N\": \n break\n if ok == \"y\" or ok == \"Y\": \n break_statement=1\n break\n if break_statement==1:\n break\n"
},
{
"answer_id": 44517453,
"author": "user",
"author_id": 3075942,
"author_profile": "https://Stackoverflow.com/users/3075942",
"pm_score": 2,
"selected": false,
"text": "nonlocal global def is_prime(number):\n\n foo = bar = number\n\n def return_here():\n nonlocal foo, bar\n init_bar = bar\n while foo > 0:\n bar = init_bar\n while bar >= foo:\n if foo*bar == number:\n return\n bar -= 1\n foo -= 1\n\n return_here()\n\n if foo == 1:\n print(number, 'is prime')\n else:\n print(number, '=', bar, '*', foo)\n >>> is_prime(67)\n67 is prime\n>>> is_prime(117)\n117 = 13 * 9\n>>> is_prime(16)\n16 = 4 * 4\n"
},
{
"answer_id": 45328126,
"author": "Daniel L.",
"author_id": 7108248,
"author_profile": "https://Stackoverflow.com/users/7108248",
"pm_score": -1,
"selected": false,
"text": "x = True\ny = True\nwhile x == True:\n while y == True:\n ok = get_input(\"Is this ok? (y/n)\") \n if ok == \"y\" or ok == \"Y\":\n x,y = False,False #breaks from both loops\n if ok == \"n\" or ok == \"N\": \n break #breaks from just one\n"
},
{
"answer_id": 46889357,
"author": "Prasad",
"author_id": 1190882,
"author_profile": "https://Stackoverflow.com/users/1190882",
"pm_score": -1,
"selected": false,
"text": "Exception class BreakLoop(Exception):\n def __init__(self, counter):\n Exception.__init__(self, 'Exception 1')\n self.counter = counter\n\nfor counter1 in range(6): # Make it 1000\n try:\n thousand = counter1 * 1000\n for counter2 in range(6): # Make it 100\n try:\n hundred = counter2 * 100\n for counter3 in range(6): # Make it 10\n try:\n ten = counter3 * 10\n for counter4 in range(6):\n try:\n unit = counter4\n value = thousand + hundred + ten + unit\n if unit == 4 :\n raise BreakLoop(4) # Don't break from loop\n if ten == 30: \n raise BreakLoop(3) # Break into loop 3\n if hundred == 500:\n raise BreakLoop(2) # Break into loop 2\n if thousand == 2000:\n raise BreakLoop(1) # Break into loop 1\n\n print('{:04d}'.format(value))\n except BreakLoop as bl:\n if bl.counter != 4:\n raise bl\n except BreakLoop as bl:\n if bl.counter != 3:\n raise bl\n except BreakLoop as bl:\n if bl.counter != 2:\n raise bl\n except BreakLoop as bl:\n pass\n BreakLoop(4) BreakLoop(3) BreakLoop(2) BreakLoop(1)"
},
{
"answer_id": 46985239,
"author": "Justas",
"author_id": 407108,
"author_profile": "https://Stackoverflow.com/users/407108",
"pm_score": 5,
"selected": false,
"text": "try:\n for outer in range(100):\n for inner in range(100):\n if break_early():\n raise StopIteration\n\nexcept StopIteration: pass\n"
},
{
"answer_id": 49136435,
"author": "Erico9001",
"author_id": 9211400,
"author_profile": "https://Stackoverflow.com/users/9211400",
"pm_score": -1,
"selected": false,
"text": "Variable_That_Counts_To_Three=1\nwhile 1==1:\n shouldbreak='no'\n Variable_That_Counts_To_Five=0\n while 2==2:\n Variable_That_Counts_To_Five+=1\n print(Variable_That_Counts_To_Five)\n if Variable_That_Counts_To_Five == 5:\n if Variable_That_Counts_To_Three == 3:\n shouldbreak='yes'\n break\n print('Three Counter = ' + str(Variable_That_Counts_To_Three))\n Variable_That_Counts_To_Three+=1\n if shouldbreak == 'yes':\n break\n\nprint('''\nThis breaks out of two loops!''')\n"
},
{
"answer_id": 49663931,
"author": "Rafiq",
"author_id": 3600487,
"author_profile": "https://Stackoverflow.com/users/3600487",
"pm_score": 2,
"selected": false,
"text": "def myloop():\n for i in range(1,6,1): # 1st loop\n print('i:',i)\n for j in range(1,11,2): # 2nd loop\n print(' i, j:' ,i, j)\n for k in range(1,21,4): # 3rd loop\n print(' i,j,k:', i,j,k)\n if i%3==0 and j%3==0 and k%3==0:\n return # getting out of all loops\n\nmyloop()\n return done = False\nfor i in range(1,6,1): # 1st loop\n print('i:', i)\n for j in range(1,11,2): # 2nd loop\n print(' i, j:' ,i, j)\n for k in range(1,21,4): # 3rd loop\n print(' i,j,k:', i,j,k)\n if i%3==0 and j%3==0 and k%3==0:\n done = True\n break # breaking from 3rd loop\n if done: break # breaking from 2nd loop\n if done: break # breaking from 1st loop\n break"
},
{
"answer_id": 50310192,
"author": "one_observation",
"author_id": 1055658,
"author_profile": "https://Stackoverflow.com/users/1055658",
"pm_score": 2,
"selected": false,
"text": "numpy.ndindex for i in range(n):\n for j in range(n):\n val = x[i, j]\n break # still inside the outer loop!\n\nfor i, j in np.ndindex(n, n):\n val = x[i, j]\n break # you left the only loop there was!\n"
},
{
"answer_id": 55002089,
"author": "Harun Altay",
"author_id": 6193320,
"author_profile": "https://Stackoverflow.com/users/6193320",
"pm_score": 2,
"selected": false,
"text": "same_matrices = True\ninner_loop_broken_once = False\nn = len(matrix1)\n\nfor i in range(n):\n for j in range(n):\n\n if matrix1[i][j] != matrix2[i][j]:\n same_matrices = False\n inner_loop_broken_once = True\n break\n\n if inner_loop_broken_once:\n break\n def are_two_matrices_the_same (matrix1, matrix2):\n n = len(matrix1)\n for i in range(n):\n for j in range(n):\n if matrix1[i][j] != matrix2[i][j]:\n return False\n return True\n"
},
{
"answer_id": 61562303,
"author": "Fateh",
"author_id": 11809159,
"author_profile": "https://Stackoverflow.com/users/11809159",
"pm_score": 2,
"selected": false,
"text": "break_ = False\nfor i in range(10):\n if break_:\n break\n for j in range(10):\n if j == 3:\n break_ = True\n break\n else:\n print(i, j)\n break_"
},
{
"answer_id": 61948529,
"author": "Muhammad Faizan Fareed",
"author_id": 7300865,
"author_profile": "https://Stackoverflow.com/users/7300865",
"pm_score": 3,
"selected": false,
"text": "def doMywork(data):\n for i in data:\n for e in i:\n return \n is_break = False\nfor i in data:\n if is_break:\n break # outer loop break\n for e in i:\n is_break = True\n break # inner loop break\n"
},
{
"answer_id": 66587485,
"author": "kcEmenike",
"author_id": 8327117,
"author_profile": "https://Stackoverflow.com/users/8327117",
"pm_score": 2,
"selected": false,
"text": "while True:\n #snip: print out current state\n quit = False\n while True:\n ok = input(\"Is this ok? (y/n)\")\n if ok.lower() == \"y\":\n quit = True\n break # this should work now :-)\n if ok.lower() == \"n\":\n quit = True\n break # This should work too :-)\n if quit:\n break\n #do more processing with menus and stuff\n"
},
{
"answer_id": 70636271,
"author": "thanos.a",
"author_id": 2110865,
"author_profile": "https://Stackoverflow.com/users/2110865",
"pm_score": 0,
"selected": false,
"text": "break_2 = False\nwhile True:\n # Snip: print out current state\n if break_2: break\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok.lower() == \"y\": break_2 = True\n if break_2: break\n if ok.lower() == \"n\": break\n # Do more processing with menus and stuff\n"
},
{
"answer_id": 72463676,
"author": "Charlie Clark",
"author_id": 2385133,
"author_profile": "https://Stackoverflow.com/users/2385133",
"pm_score": 0,
"selected": false,
"text": "b = None\nfor a in range(10):\n if something(a, b): # should never = True if b is None\n break\n for b in range(20):\n pass\n"
},
{
"answer_id": 72577907,
"author": "Wendel",
"author_id": 2057463,
"author_profile": "https://Stackoverflow.com/users/2057463",
"pm_score": 0,
"selected": false,
"text": "while True:\n # Snip: print out current state\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok.lower() == \"y\": \n break_2 = True\n if ok.lower() == \"n\": \n break\n if break_2:\n break\n"
},
{
"answer_id": 74120229,
"author": "Warlax56",
"author_id": 10818367,
"author_profile": "https://Stackoverflow.com/users/10818367",
"pm_score": 0,
"selected": false,
"text": "1/0 break for i in first_iter:\n for j in second_iter:\n for k in third_iter:\n print(i_want_to_run_this_once_and_stop_executing(i,j,k))\n 1/0\n code_that_takes_a_long_time()\n expensive_code()\n"
},
{
"answer_id": 74600459,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": -1,
"selected": false,
"text": "break while while True:\n while True:\n print('Breaks inner \"while\" loop')\n break # Here\n print('Breaks outer \"while\" loop')\n break # Here\n break while if while True:\n while True:\n if True:\n print('Breaks inner \"while\" loop')\n break # Here\n print('Breaks outer \"while\" loop')\n break # Here\n Breaks inner \"while\" loop\nBreaks outer \"while\" loop\n break for for _ in iter(int, 1):\n for _ in iter(int, 1):\n print('Breaks inner \"for\" loop')\n break # Here\n print('Breaks outer \"for\" loop')\n break # Here\n break for if for _ in iter(int, 1):\n for _ in iter(int, 1):\n if True:\n print('Breaks inner \"for\" loop')\n break # Here\n print('Breaks outer \"for\" loop')\n break # Here\n Breaks inner \"for\" loop\nBreaks outer \"for\" loop\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
189,680
|
<p>i am looking for opinions if the following problem maybe has a better/different/common solution:</p>
<hr>
<p>I have a database for products which contains the names of the products in english (the default language of this application) and i need translations of the names if available.</p>
<p>Currently i have this setup:</p>
<p>A product table</p>
<pre><code>CREATE TABLE products
(
id serial NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_pkey PRIMARY KEY (id)
)
</code></pre>
<p>and a product localization table</p>
<pre><code>CREATE TABLE products_l10n
(
product_id serial NOT NULL,
"language" character(2) NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),
CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)
REFERENCES products (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
</code></pre>
<p>and i use the following query to retrieve a list of localized products (german in this case) with fallback to the default english names:</p>
<pre><code>SELECT p.id, COALESCE(pl.name, p.name)
from products p LEFT
JOIN products_l10n pl ON p.id = pl.product_id AND language = 'de';
</code></pre>
<p>The SQL code is in postgres dialect. Data is stored as UTF-8.</p>
|
[
{
"answer_id": 189693,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 4,
"selected": true,
"text": "CREATE TABLE products_l10n\n(\n product_id serial NOT NULL,\n language_id int NOT NULL,\n \"name\" character varying(255) NOT NULL,\n CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),\n CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)\n REFERENCES products (id) MATCH SIMPLE\n ON UPDATE CASCADE ON DELETE CASCADE\n CONSTRAINT products_l10n_language_id_fkey FOREIGN KEY (language_id)\n REFERENCES languages (id) MATCH SIMPLE\n ON UPDATE CASCADE ON DELETE CASCADE\n)\n\nCREATE TABLE languages\n)\n id serial not null\n \"language\" character(2) NOT NULL\n)\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21566/"
] |
189,694
|
<p>I'm exporting data programatically from Excel to SQL Server 2005 using SqlBulkCopy. It works great, the only problem I have is that it doesn't preserve the row sequence i have in Excel file. I don't have a column to order by, I just want the records to be inserted in the same order they appear in the Excel Spreadsheet.</p>
<p>I can't modify the Excel file, and have to work with what I've got. Sorting by any of the existing columns will break the sequence.</p>
<p>Please help.</p>
<p>P.S. Ended up inserting ID column to the spreadsheet, looks like there's no way to keep the order during export/import</p>
|
[
{
"answer_id": 189728,
"author": "abarax",
"author_id": 24390,
"author_profile": "https://Stackoverflow.com/users/24390",
"pm_score": 0,
"selected": false,
"text": "def file1 = new File('c:\\\\temp\\\\yourSpreadsheet.csv')\ndef file2 = new File('c:\\\\temp\\\\yourInsertScript.sql')\n\ndef reader = new FileReader(file1)\ndef writer = new FileWriter(file2)\n\nreader.transformLine(writer) { line ->\n fields = line.split(',')\n\n text = \"\"\"INSERT INTO table1 (col1, col2, col3) VALUES ('${fields[0]}', '${fields[1]}', '${fields[2]}');\"\"\"\n\n}\n"
},
{
"answer_id": 43689731,
"author": "Dean Bell",
"author_id": 7938704,
"author_profile": "https://Stackoverflow.com/users/7938704",
"pm_score": 1,
"selected": false,
"text": "---------------------------------\nDeclare @X xml;\n---------------------------------\nSELECT @X=Cast('<X>'+Replace([BulkColumn],Char(13)+Char(10),'</X><X>')+'</X>' as XML)\nFROM OPENROWSET (BULK N'\\\\FileServer\\ImportFolder\\ImportFile_20170120.csv',SINGLE_CLOB) T\n---------------------------------\nSELECT [Record].[X].query('.').value('.','varchar(max)') [Record]\n,ROW_NUMBER() OVER (ORDER BY (SELECT 100)) [ID]\n--Into #TEMP \nFROM @X.nodes('X') [Record](X);\n---------------------------------\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] |
189,708
|
<p>Is there any way of determining whether or not a specific temp table has been created in a session without referencing the tempdb database that it was created on? Users are allocated to a specific tempdb when they log in, so I don't know which tempdb they'll be using.</p>
<p>I don't need to specify a tempdb to select data out of the temp table, so surely I can see if the table exists?</p>
|
[
{
"answer_id": 356175,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 3,
"selected": false,
"text": "SELECT object_id('#tmpTable')\n SELECT object_id('tempdb..#tmpTable')\n SELECT object_id('##tmpTable')\n IF NULLIF(object_id('#tmpTable'), 0) IS NOT NULL DROP TABLE #tmpTable\nCREATE TABLE #tmpTable (\n id int,\n col1 varchar(100)\n)\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
189,725
|
<p>During recent discussions at work, someone referred to a trampoline function.</p>
<p>I have read the description at <a href="http://en.wikipedia.org/wiki/Trampoline_(computers)" rel="noreferrer">Wikipedia</a>. It is enough to give a general idea of the functionality, but I would like something a bit more concrete.</p>
<p>Do you have a simple snippet of code that would illustrate a trampoline?</p>
|
[
{
"answer_id": 189818,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": false,
"text": "#include <stdlib.h>\n#include <string.h>\n/* sort an array, starting at address `base`,\n * containing `nmemb` members, separated by `size`,\n * comparing on the first `nbytes` only. */\nvoid sort_bytes(void *base, size_t nmemb, size_t size, size_t nbytes) {\n int compar(const void *a, const void *b) {\n return memcmp(a, b, nbytes);\n }\n qsort(base, nmemb, size, compar);\n}\n compar nbytes sort_bytes sort_bytes compar"
},
{
"answer_id": 489860,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "function fibcps(n, c) {\n if (n <= 1) {\n c(n);\n } else {\n fibcps(n - 1, function (x) {\n fibcps(n - 2, function (y) {\n c(x + y)\n })\n });\n }\n}\n n = 25 return function fibt(n, c) {\n function trampoline(x) {\n while (x && x.func) {\n x = x.func.apply(null, x.args);\n }\n }\n\n function fibtramp(n, c) {\n if (n <= 1) {\n return {func: c, args: [n]};\n } else {\n return {\n func: fibtramp,\n args: [n - 1,\n function (x) {\n return {\n func: fibtramp,\n args: [n - 2, function (y) {\n return {func: c, args: [x + y]}\n }]\n }\n }\n ]\n }\n }\n }\n\n trampoline({func: fibtramp, args: [n, c]});\n}\n"
},
{
"answer_id": 489892,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 0,
"selected": false,
"text": "size_t (*trampoline_example)(const char *, const char *);\ntrampoline_example= strcspn;\nsize_t result_1= trampoline_example(\"xyzbxz\", \"abc\");\n\ntrampoline_example= strspn;\nsize_t result_2= trampoline_example(\"xyzbxz\", \"abc\");\n"
},
{
"answer_id": 1112003,
"author": "boxofrats",
"author_id": 35591,
"author_profile": "https://Stackoverflow.com/users/35591",
"pm_score": 3,
"selected": false,
"text": "#include <stdio.h>\n\ntypedef void *(*CONTINUATION)(int);\n\nvoid trampoline(CONTINUATION cont)\n{\n int counter = 0;\n CONTINUATION currentCont = cont;\n while (currentCont != NULL) {\n currentCont = (CONTINUATION) currentCont(counter);\n counter++;\n }\n printf(\"got off the trampoline - happy happy joy joy !\\n\");\n}\n\nvoid *thunk3(int param)\n{\n printf(\"*boing* last thunk\\n\");\n return NULL;\n}\n\nvoid *thunk2(int param)\n{\n printf(\"*boing* thunk 2\\n\");\n return thunk3;\n}\n\nvoid *thunk1(int param)\n{\n printf(\"*boing* thunk 1\\n\");\n return thunk2;\n}\n\nint main(int argc, char **argv)\n{\n trampoline(thunk1);\n}\n meincompi $ ./trampoline \n*boing* thunk 1\n*boing* thunk 2\n*boing* last thunk\ngot off the trampoline - happy happy joy joy !\n"
},
{
"answer_id": 11921515,
"author": "Piotr Kukielka",
"author_id": 704905,
"author_profile": "https://Stackoverflow.com/users/704905",
"pm_score": 5,
"selected": false,
"text": "sealed trait Bounce[A]\ncase class Done[A](result: A) extends Bounce[A]\ncase class Call[A](thunk: () => Bounce[A]) extends Bounce[A]\n\ndef trampoline[A](bounce: Bounce[A]): A = bounce match {\n case Call(thunk) => trampoline(thunk())\n case Done(x) => x\n}\n\ndef factorial(n: Int, product: BigInt): Bounce[BigInt] = {\n if (n <= 2) Done(product)\n else Call(() => factorial(n - 1, n * product))\n}\n\nobject Factorial extends Application {\n println(trampoline(factorial(100000, 1)))\n}\n import java.math.BigInteger;\n\nclass Trampoline<T> \n{\n public T get() { return null; }\n public Trampoline<T> run() { return null; }\n\n T execute() {\n Trampoline<T> trampoline = this;\n\n while (trampoline.get() == null) {\n trampoline = trampoline.run();\n }\n\n return trampoline.get();\n }\n}\n\npublic class Factorial\n{\n public static Trampoline<BigInteger> factorial(final int n, final BigInteger product)\n {\n if(n <= 1) {\n return new Trampoline<BigInteger>() { public BigInteger get() { return product; } };\n } \n else {\n return new Trampoline<BigInteger>() { \n public Trampoline<BigInteger> run() { \n return factorial(n - 1, product.multiply(BigInteger.valueOf(n)));\n } \n };\n }\n }\n\n public static void main( String [ ] args )\n {\n System.out.println(factorial(100000, BigInteger.ONE).execute());\n }\n}\n #include <stdio.h>\n\ntypedef struct _trampoline_data {\n void(*callback)(struct _trampoline_data*);\n void* parameters;\n} trampoline_data;\n\nvoid trampoline(trampoline_data* data) {\n while(data->callback != NULL)\n data->callback(data);\n}\n\n//-----------------------------------------\n\ntypedef struct _factorialParameters {\n int n;\n int product;\n} factorialParameters;\n\nvoid factorial(trampoline_data* data) {\n factorialParameters* parameters = (factorialParameters*) data->parameters;\n\n if (parameters->n <= 1) {\n data->callback = NULL;\n }\n else {\n parameters->product *= parameters->n;\n parameters->n--;\n }\n}\n\nint main() {\n factorialParameters params = {5, 1};\n trampoline_data t = {&factorial, ¶ms};\n\n trampoline(&t);\n printf(\"\\n%d\\n\", params.product);\n\n return 0;\n}\n"
},
{
"answer_id": 33590722,
"author": "thenry",
"author_id": 5538451,
"author_profile": "https://Stackoverflow.com/users/5538451",
"pm_score": -1,
"selected": false,
"text": "typedef void* (*state_type)(void);\nvoid* state1();\nvoid* state2();\nvoid* state1() {\n return state2;\n}\nvoid* state2() {\n return state1;\n}\n// ...\nstate_type state = state1;\nwhile (1) {\n state = state();\n}\n// ...\n"
},
{
"answer_id": 58674093,
"author": "RandomProgrammer",
"author_id": 58864,
"author_profile": "https://Stackoverflow.com/users/58864",
"pm_score": 1,
"selected": false,
"text": "using System.Collections.Generic;\nusing System.Linq;\n\nclass Game\n{\n internal static int RollMany(params int[] rs) \n {\n return Trampoline(1, 0, rs.ToList());\n\n int Trampoline(int frame, int rsf, IEnumerable<int> rs) =>\n frame == 11 ? rsf\n : rs.Count() == 0 ? rsf\n : rs.First() == 10 ? Trampoline(frame + 1, rsf + rs.Take(3).Sum(), rs.Skip(1))\n : rs.Take(2).Sum() == 10 ? Trampoline(frame + 1, rsf + rs.Take(3).Sum(), rs.Skip(2))\n : Trampoline(frame + 1, rsf + rs.Take(2).Sum(), rs.Skip(2));\n }\n}\n Game.RollMany return Trampoline(1, 0, rs.ToList()); frame rsf"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] |
189,751
|
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p>
<pre><code>- url: (.*)/
static_files: static\1/index.html
upload: static/index.html
- url: /
static_dir: static
</code></pre>
<p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p>
<p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p>
<pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html":
[Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html'
INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 -
</code></pre>
|
[
{
"answer_id": 189935,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 6,
"selected": true,
"text": "- url: /.*\n script: main.py\n from google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass NotFoundPageHandler(webapp.RequestHandler):\n def get(self):\n self.error(404)\n self.response.out.write('<Your 404 error html page>')\n\napplication = webapp.WSGIApplication([('/.*', NotFoundPageHandler)],\n debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n <Your 404 error html page>"
},
{
"answer_id": 855877,
"author": "Zee Spencer",
"author_id": 91163,
"author_profile": "https://Stackoverflow.com/users/91163",
"pm_score": 2,
"selected": false,
"text": "- url: /.*\n static_files: views/404.html\n upload: views/404.html\n"
},
{
"answer_id": 3722135,
"author": "jonmiddleton",
"author_id": 315908,
"author_profile": "https://Stackoverflow.com/users/315908",
"pm_score": 5,
"selected": false,
"text": "error_handlers:\n\n- file: default_error.html\n\n- error_code: over_quota\n file: over_quota.html\n"
},
{
"answer_id": 4041691,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "$ wget -O - http://127.0.0.1:8080/foo\n--2010-10-28 10:54:51-- http://127.0.0.1:8080/foo\nConnecting to 127.0.0.1:8080... connected.\nHTTP request sent, awaiting response... 404 \n2010-10-28 10:54:51 ERROR 404: (no description).\n\n$ wget -O - http://127.0.0.1:8080/foo/\n--2010-10-28 10:54:54-- http://127.0.0.1:8080/foo/\nConnecting to 127.0.0.1:8080... connected.\nHTTP request sent, awaiting response... 404 \n2010-10-28 10:54:54 ERROR 404: (no description).\n"
},
{
"answer_id": 10861989,
"author": "TeknasVaruas",
"author_id": 1088579,
"author_profile": "https://Stackoverflow.com/users/1088579",
"pm_score": 2,
"selected": false,
"text": "def Handle404(request, response, exception):\n response.out.write(\"Your error message\") \n response.set_status(404)`\n response.out.write app app.error_handlers[404] = Handle404"
},
{
"answer_id": 17082291,
"author": "JackNova",
"author_id": 298022,
"author_profile": "https://Stackoverflow.com/users/298022",
"pm_score": 0,
"selected": false,
"text": "app = webapp2.WSGIApplication([\n ...\n ...\n ('/.*', ErrorsHandler)\n], debug=True)\n\n\nclass ErrorsHandler(webapp2.RequestHandler):\n def get(self):\n p = self.request.path_qs\n if p in ['/index.html', 'resources-that-I-removed']: \n return self.redirect('/and-substituted-with-this', permanent=True)\n else: \n self.error(404)\n template = jinja_environment.get_template('404.html')\n context = {\n 'page_title': '404',\n }\n self.response.out.write(template.render(context))\n"
},
{
"answer_id": 22150908,
"author": "Romain",
"author_id": 145997,
"author_profile": "https://Stackoverflow.com/users/145997",
"pm_score": 2,
"selected": false,
"text": "webapp2 error_handlers def handle_404(request, response, exception):\n logging.warn(str(exception))\n response.set_status(404)\n h = YourAppBaseHandler(request, response)\n h.render_template('notfound')\n\ndef handle_500(request, response, exception):\n logging.error(str(exception))\n response.set_status(500)\n h = YourAppBaseHandler(request, response)\n h.render_template('servererror')\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler, name='home')\n ], debug=True)\napp.error_handlers[404] = handle_404\napp.error_handlers[500] = handle_500\n webapp2"
},
{
"answer_id": 34583480,
"author": "husayt",
"author_id": 15461,
"author_profile": "https://Stackoverflow.com/users/15461",
"pm_score": 2,
"selected": false,
"text": "app.yaml - url: /(.*) \n script: 404.app\n 404.py import webapp2\nfrom google.appengine.ext.webapp import template\n\nclass NotFound(webapp2.RequestHandler):\n def get(self):\n self.error(404)\n self.response.out.write(template.render('404.html', {}))\n\napp = webapp2.WSGIApplication([\n ('/.*', NotFound)\n], debug=True)\n 404.html 404.html Custom Error Responses"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26683/"
] |
189,765
|
<p>I have a query that ran fine on SQL2005 but moving the database to SQL2008 gives me the error from the title.</p>
<p>The code that is the problem is a call to CONTAINS, CONTAINSTABLE or FREETEXT with an empty parameter. However I'm trying to only call or join when there is a value like such</p>
<pre><code>where (@search_term = '' or (FREETEXT(lst.search_text, @search_term)))
</code></pre>
<p>or</p>
<pre><code>left join containstable (listing_search_text, search_text, @search_term) ftb on l.listing_id = ftb.[key]
and len(@search_term) > 0
</code></pre>
<p>However I cannot find any workaround for this to work on SQL2008. Any ideas?</p>
<p>I know I can do dynamic SQL or have a if statement with two different cases (select with FT join, select without FT join. Any better workaround which doesn't require doing this?</p>
|
[
{
"answer_id": 347232,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 6,
"selected": false,
"text": "\"\" '' @search_term = '\"\"' declare @SearchTerm nvarchar(250)\n\nSET @SearchTerm = '\"\"'\n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE ((@SearchTerm = '\"\"') OR CONTAINS( (U.Description, U.UserName), @SearchTerm))\n"
},
{
"answer_id": 5209595,
"author": "whiplashtony",
"author_id": 477019,
"author_profile": "https://Stackoverflow.com/users/477019",
"pm_score": 4,
"selected": false,
"text": "declare @SearchTerm nvarchar(250)\n\nSET @SearchTerm = '\"\"'\n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE ((@SearchTerm = '\"\"') \n\nUNION \n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE CONTAINS( (U.Description, U.UserName), @SearchTerm)) \n"
},
{
"answer_id": 45588071,
"author": "Abhishek Chandel",
"author_id": 6889690,
"author_profile": "https://Stackoverflow.com/users/6889690",
"pm_score": 2,
"selected": false,
"text": "Set @search_term = case when @search_term = '' then '\"\"' else @Address End\n where (@search_term = '\"\"' or (FREETEXT(lst.search_text, @search_term)))\n"
},
{
"answer_id": 67170285,
"author": "FloverOwe",
"author_id": 6885037,
"author_profile": "https://Stackoverflow.com/users/6885037",
"pm_score": 1,
"selected": false,
"text": "SET @SearchPhrase = coalesce(@SearchPhrase, 'a'); /* replace with 'a' if null parameter */ \nSELECT ... WHERE \n (@SearchPhrase = 'a' OR contains(Search_Text, @SearchPhrase)) \n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084/"
] |
189,770
|
<p>How would you go about retrieving the @@IDENTITY value for each row when the SQLDataAdapater.Update is executed on a table?</p>
<p>eg. Is it possible to modify/intercept the InsertCommand, generated by the SQLCommandBuilder, to say add an output parameter, and then retrieve its value in the da.RowUpdated event???</p>
|
[
{
"answer_id": 347232,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 6,
"selected": false,
"text": "\"\" '' @search_term = '\"\"' declare @SearchTerm nvarchar(250)\n\nSET @SearchTerm = '\"\"'\n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE ((@SearchTerm = '\"\"') OR CONTAINS( (U.Description, U.UserName), @SearchTerm))\n"
},
{
"answer_id": 5209595,
"author": "whiplashtony",
"author_id": 477019,
"author_profile": "https://Stackoverflow.com/users/477019",
"pm_score": 4,
"selected": false,
"text": "declare @SearchTerm nvarchar(250)\n\nSET @SearchTerm = '\"\"'\n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE ((@SearchTerm = '\"\"') \n\nUNION \n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE CONTAINS( (U.Description, U.UserName), @SearchTerm)) \n"
},
{
"answer_id": 45588071,
"author": "Abhishek Chandel",
"author_id": 6889690,
"author_profile": "https://Stackoverflow.com/users/6889690",
"pm_score": 2,
"selected": false,
"text": "Set @search_term = case when @search_term = '' then '\"\"' else @Address End\n where (@search_term = '\"\"' or (FREETEXT(lst.search_text, @search_term)))\n"
},
{
"answer_id": 67170285,
"author": "FloverOwe",
"author_id": 6885037,
"author_profile": "https://Stackoverflow.com/users/6885037",
"pm_score": 1,
"selected": false,
"text": "SET @SearchPhrase = coalesce(@SearchPhrase, 'a'); /* replace with 'a' if null parameter */ \nSELECT ... WHERE \n (@SearchPhrase = 'a' OR contains(Search_Text, @SearchPhrase)) \n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1885/"
] |
189,780
|
<p>I have an odd problem...I'm using a documentation generator which generates a lot of output like docs/foo.php.html. It's XHTML, and thus contains <code><?xml...></code> tags at the beginning of file. The problem is, Apache has somehow decided to run it through the PHP interpreter, even though ".php" appears in the middle of the filename, and not at the end. This, in turn, triggers a PHP error, because it sees "<code><?</code>" as the command to start executing PHP code, and immediately gets confused by the "<code>xml...</code>" which follows it.</p>
<p>How do I configure Apache to ONLY execute .php files and not .php.html files? The string "php.html" does not appear explicitly anywhere in my Apache config files. There is a line "<code>AddHandler php5-script .php</code>", but I don't see how that would also include ".php.html" files.</p>
|
[
{
"answer_id": 189810,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "short_open_tag = 0\n"
},
{
"answer_id": 190221,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 5,
"selected": true,
"text": "<FilesMatch \\.cgi$> SetHandler cgi-script </FilesMatch> apache mod_mime \"multiple extensions\""
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
] |
189,787
|
<p>I have never seen a way to do this nicely, i would be interested in seeing how others do it. Currently i format it like this:</p>
<pre><code>public Booking createVehicleBooking(Long officeId,
Long start,
Long end,
String origin,
String destination,
String purpose,
String requirements,
Integer numberOfPassengers) throws ServiceException {
/*..Code..*/
}
</code></pre>
|
[
{
"answer_id": 189793,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "public Booking createVehicleBooking(\n Long officeId, \n Long start, \n Long end,\n String origin, \n String destination, \n String purpose, \n String requirements, \n Integer numberOfPassengers)\n\nthrows ServiceException {\n/*..Code..*/\n}\n"
},
{
"answer_id": 189834,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 5,
"selected": true,
"text": "create... class BuildVehicleBooking {\n Long officeId;\n Long start;\n Long end;\n String origin;\n String destination;\n String purpose; \n String requirements;\n Integer numberOfPassengers;\n\n Booking createVehicleBooking () throws ServiceException { ... }\n}\n create verifyParameters creating"
},
{
"answer_id": 189969,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 2,
"selected": false,
"text": "public Booking createVehicleBooking(Long officeId, DateRange dates, TripDetails trip)\n public Booking createVehicleBooking(BookingParameters parameters)\n"
},
{
"answer_id": 30202173,
"author": "miguel",
"author_id": 11015,
"author_profile": "https://Stackoverflow.com/users/11015",
"pm_score": 2,
"selected": false,
"text": "booking.createVehicleBooking(\n getOfficeId(), // Long officeId \n startVariable, // Long start \n 42, // Long end\n getOrigin(), // String origin \n \"destination\", // String destination \n \"purpose\", // String purpose \n \"requirements\", // String requirements\n 3 // Integer numberOfPassengers\n);\n"
},
{
"answer_id": 46275233,
"author": "Rich",
"author_id": 8261,
"author_profile": "https://Stackoverflow.com/users/8261",
"pm_score": 2,
"selected": false,
"text": "public static <F, T> Collection<T> transform(\n Collection<F> fromCollection, Function<? super F, T> function) {\n return new TransformedCollection<>(fromCollection, function);\n}\n public static <T, K extends Comparable<? super K>, V>\n Collector<T, ?, ImmutableRangeMap<K, V>> toImmutableRangeMap(\n Function<? super T, Range<K>> keyFunction,\n Function<? super T, ? extends V> valueFunction) {\n return CollectCollectors.toImmutableRangeMap(keyFunction, valueFunction);\n}\n public static Foo makeFoo(\n Foo foo,\n Bar bar,\n Baz baz)\n throws FooException {\n f();\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24390/"
] |
189,791
|
<p>Compared to most people on this site I am admittedly a novice. I wanted to get some advice from the pros on how to avoid making stupid errors in your code. </p>
<p>Is there anyone else who had the problem when they were first starting out of missing some detail that causes big problems? Are there any habits or behaviors that helped you over come this.</p>
|
[
{
"answer_id": 189866,
"author": "Skittles",
"author_id": 26300,
"author_profile": "https://Stackoverflow.com/users/26300",
"pm_score": 1,
"selected": false,
"text": " // Create local variables\n\n // Get the connection string from the config file\n\n // Create Try Catch Finally block\n\n // Create SQL parameters \n\n .... etc\n\n }\n"
},
{
"answer_id": 193147,
"author": "Richard T",
"author_id": 26976,
"author_profile": "https://Stackoverflow.com/users/26976",
"pm_score": 2,
"selected": false,
"text": "void MyMethod(String some_input)\n{\n if (some_input == null)\n {\n some_input = \"\";\n }\n}\n void MyMethod(String some_input) {\n if (some_input == null) {\n some_input = \"\";\n }\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25012/"
] |
189,850
|
<p>What is the <a href="http://en.wikipedia.org/wiki/MIME" rel="noreferrer">MIME</a> type of javascript? </p>
<p>More specifically, what is the right thing to put in the "type" attribute of a script tag? <code>application/x-javascript</code> and <code>text/javascript</code> seem to be the main contenders.</p>
|
[
{
"answer_id": 1998417,
"author": "ekerner",
"author_id": 233060,
"author_profile": "https://Stackoverflow.com/users/233060",
"pm_score": 5,
"selected": false,
"text": "text/javascript application/javascript application/x-javascript type=\"text/javascript\" application/x-javascript"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6007/"
] |
189,855
|
<p>Which would be a neat implemenation of a N-ary tree in C language?</p>
<p>Particulary, I want to implement an n-ary tree, not self-ballancing, with an unbound number of children in each node, in which each node holds an already defined struct, like this for example:</p>
<pre><code>struct task {
char command[MAX_LENGTH];
int required_time;
};
</code></pre>
|
[
{
"answer_id": 189900,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 5,
"selected": true,
"text": "struct task {\n char command[MAX_LENGTH];\n int required_time;\n};\n\nstruct TreeNode;\n\nstruct ListNode {\n struct TreeNode * child;\n struct ListNode * next;\n};\n\nstruct TreeNode {\n struct task myTask;\n struct ListNode myChildList;\n};\n"
},
{
"answer_id": 192089,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 6,
"selected": false,
"text": "struct task {\n char command[MAX_LENGTH];\n int required_time;\n};\n\nstruct node {\n struct task taskinfo;\n struct node *firstchild;\n struct node *nextsibling;\n};\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26699/"
] |
189,878
|
<p>I'm looking for a regex that will allow me to validate whether or not a string is the reference to a website address, or a specific page in that website. </p>
<p>So it would match:</p>
<pre><code>http://google.com
ftp://google.com
http://google.com/
http://lots.of.subdomains.google.com
</code></pre>
<p>But not:</p>
<pre><code>http://google.com/search.whatever
ftp://google.com/search.whatever
http://lots.of.subdomains.google.com/search.whatever
</code></pre>
<p>Any ideas? I can't quite figure out how to handle allowing the <code>/</code> at the end of the URL.</p>
|
[
{
"answer_id": 189941,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": true,
"text": "(http|ftp|https)://([a-zA-Z0-9\\-\\.]+)/?\n"
},
{
"answer_id": 190053,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 2,
"selected": false,
"text": "http://example.com/bin/cgi?returnUrl=http://google.com ^\\w+://(\\w+\\.)+\\w+/?$\n"
},
{
"answer_id": 190340,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "/^(https?|ftp):\\/\\/(?# protocol\n)(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+(?# username\n)(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?(?# password\n)@)?(?# auth requires @\n)((([a-z0-9][a-z0-9-]*[a-z0-9]\\.)*(?# domain segments AND\n)[a-z]{2}[a-z0-9-]*[a-z0-9](?# top level domain OR\n)|(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5]\\.){3}(?#\n )(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])(?# IP address\n))(:\\d+)?(?# port\n))\\/?$/i\n /^(https?|ftp):\\/\\/(?# protocol\n)(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+(?# username\n)(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?(?# password\n)@)?(?# auth requires @\n)((([a-z0-9][a-z0-9-]*[a-z0-9]\\.)*(?# domain segments AND\n)[a-z]{2}[a-z0-9-]*[a-z0-9](?# top level domain OR\n)|(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5]\\.){3}(?#\n )(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])(?# IP address\n))(:\\d+)?(?# port\n))(((\\/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*(?# path\n)(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)(?# query string\n)?)?)?(?# path and query string optional\n)(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?(?# fragment\n)$/i\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4965/"
] |
189,887
|
<p>is there an if statement when it comes to mysql query statements?</p>
<p>when i am updating a table record, i want to only update certain columns if they have a value to be updated.</p>
<p>for example, i want an update table function, and there is a table for volunteers and a table for people who just want email updates.</p>
<p>i want to use the same function (there will be a function that only deals w/ the upd queries) and is it possible to do this in theory...</p>
<p>if you are updating volunteer table, only update these columns, if mailing_list, then update these</p>
<p>i know this can by done using an if statement w/ two query statements, based on what table you're updating, but i am wondering is it possible to use only one query statement w/ the conditionals in it to update the appropriate columns in the table.</p>
<p>this may sound like something you would dream about, let me know.</p>
<p>thanks.</p>
|
[
{
"answer_id": 190011,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 3,
"selected": true,
"text": "UPDATE volunteer, people\nSET volunteer.email = 'me@email.com',\n people.email = 'other@gmail.com',\n people.first_name = 'first',\nWHERE people.id = 2 AND volunteer.id = 5;\n"
},
{
"answer_id": 190141,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "update tablereferences\n set foo.bar = if( somebooleanexpression, newbarvalue, foo.bar ),\n baz.quux = if( somebooleanexpression, newbazvalue, baz.quux )\n where ...\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
189,889
|
<p>I'm having a problem using the java.text.MessageFormat object.</p>
<p>I'm trying to create SQL insert statements. The problem is, when I do something like this:</p>
<pre><code>MessageFormat messageFormat = "insert into {0} values ( '{1}', '{2}', '{3}', {4} )";
Object[] args = { str0, str1, str2, str3, str4 };
String result = messageFormat.format(args);
</code></pre>
<p>I get this for the value of <code>result</code>:</p>
<pre><code>"insert into <str0> values ( {1}, {2}, {3}, <str4> )"
</code></pre>
<p>As you can see, the problem is that any of the target locations that are enclosed by single quotes do not get replaced by arguments. I have tried using double single quotes like this: <code>''{1}''</code> and escaped characters like this: <code>\'{1}\'</code> but it still gives the same result. </p>
<p>edit: I forgot to mention that I also tried <code>'''{1}'''</code>. The result is: <code>"insert into <str0> values ( '{1}', '{2}', '{3}', <str4> )"</code>. It is keeping the original quotes around but still not inserting the values.</p>
<p>How can I resolve this issue? For the record, I am using JDK 6u7.</p>
|
[
{
"answer_id": 189896,
"author": "Chris Boran",
"author_id": 25660,
"author_profile": "https://Stackoverflow.com/users/25660",
"pm_score": 4,
"selected": false,
"text": "\"'{0}'\" \"{0}\" '' String \"'{''}'\" '{ '' }' '{' '}' \"{'}\" \"{}\""
},
{
"answer_id": 189898,
"author": "Brian Duff",
"author_id": 3643,
"author_profile": "https://Stackoverflow.com/users/3643",
"pm_score": 2,
"selected": false,
"text": "MessageFormat messageFormat = \"insert into {0} values ( '''{1}''', '''{2}''', '''{3}''', '''{4}''' )\";\n"
},
{
"answer_id": 189955,
"author": "serg",
"author_id": 20128,
"author_profile": "https://Stackoverflow.com/users/20128",
"pm_score": 8,
"selected": true,
"text": "MessageFormat messageFormat = new MessageFormat(\"insert into {0} values ( ''{1}'', ''{2}'', ''{3}'', {4} )\");\nObject[] args = {\"000\", \"111\", \"222\",\"333\",\"444\",\"555\"};\nString result = messageFormat.format(args);\n insert into 000 values ( '111', '222', '333', 444 )\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12983/"
] |
189,892
|
<p>If I have an array of a fixed size depending on how it is defined and used, I typically use one of two ways to reference it.</p>
<p>Array type 1: Since it is a fixed size based on a define, I just use that define in all my loops referencing it.</p>
<pre><code>#define MAXPLAYERS 4
int playerscores[MAXPLAYERS];
for(i=0;i<MAXPLAYERS;++i)
{
.... do something with each player
}
</code></pre>
<p>Array type 2: Since this array can grow as items are added to it, I use the sizeof to count the number of entries in it. The size would be converted to a constant by the compiler so there shouldn't be any runtime penalty to doing it this way.</p>
<pre><code>typedef struct
{
fields....
}MYSTRUCT_DEF;
MYSTRUCT_DEF mystruct[]={
{entry 1},
{entry 2},
{entry 3...n}
};
for(i=0;i<(sizeof(mystruct)/sizeof(MYSTRUCT_DEF));++i)
{
..... do something with each entry
}
</code></pre>
<p>Is there a more elegant solution to handling processing of arrays without going past the end or stopping too early. Thoughts? Comments?</p>
|
[
{
"answer_id": 189907,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 4,
"selected": true,
"text": "#define ARRAY_COUNT(x) (sizeof(x)/sizeof((x)[0]))\n\n...\n\nstruct foo arr[100];\n...\n\nfor (i = 0; i < ARRAY_COUNT(arr); ++i) {\n /* do stuff to arr[i] */\n}\n"
},
{
"answer_id": 189922,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": false,
"text": "// crt_countof.cpp\n#define _UNICODE\n#include <stdio.h>\n#include <stdlib.h>\n#include <tchar.h>\nint main( void )\n{\n _TCHAR arr[20], *p;\n printf( \"sizeof(arr) = %d bytes\\n\", sizeof(arr) );\n printf( \"_countof(arr) = %d elements\\n\", _countof(arr) );\n // In C++, the following line would generate a compile-time error:\n // printf( \"%d\\n\", _countof(p) ); // error C2784 (because p is a pointer)\n\n _tcscpy_s( arr, _countof(arr), _T(\"a string\") );\n // unlike sizeof, _countof works here for both narrow- and wide-character strings\n}\n"
},
{
"answer_id": 189996,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "struct foo {\n ... /* fields */\n};\nstruct foo array[] = {\n { ... }, /* item 1 */\n { ... }, /* item 2 */\n ...,\n { 0 } /* terminator */\n};\nfor (i = 0; array[i].some_field; i++) {\n ...\n}\n 0 NULL ARRAY_COUNT struct array_of_stuff {\n struct stuff *array;\n int count; /* number of used elements */\n int length; /* number of elements allocated */\n};\n length"
},
{
"answer_id": 190514,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 1,
"selected": false,
"text": "// #define MAXPLAYERS 4\nconst unsigned int MAXPLAYERS = 4 ;\n\nint playerscores[MAXPLAYERS];\n\nfor(i=0;i<MAXPLAYERS;++i)\n{\n.... do something with each player\n}\n /* header.h */\nextern const unsigned int MAXPLAYERS ;\nextern int playerscores[] ;\n\n/* source.c */\nconst unsigned int MAXPLAYERS = 4\nint playerscores[MAXPLAYERS];\n\n/* another_source.c */\n#include \"header.h\"\n\nfor(i=0;i<MAXPLAYERS;++i)\n{\n.... do something with each player\n}\n"
},
{
"answer_id": 190639,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 1,
"selected": false,
"text": "_countof"
},
{
"answer_id": 191688,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "template<int N> void for_all_objects(MYSTRUCT_DEF[N] myobjects) sizeof(mystruct)/sizeof(MYSTRUCT_DEF) MYSTRUCT_DEF* sizeof(mystruct) sizeof(MYSTRUCT_DEF*) sizeof(MYSTRUCT_DEF)"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
189,903
|
<p>At the <a href="http://www.binpress.com" rel="noreferrer">startup</a> I'm working at we are now considering scaling solutions for our database. Things get somewhat confusing (for me at least) with MySQL, which has the <a href="http://dev.mysql.com/doc/refman/5.0/en/faqs-mysql-cluster.html" rel="noreferrer">MySQL cluster</a>, <a href="http://dev.mysql.com/doc/refman/5.0/en/replication.html" rel="noreferrer">replication</a> and <a href="http://dev.mysql.com/doc/refman/5.1/en/mysql-cluster-replication.html" rel="noreferrer">MySQL cluster replication</a> (from ver. 5.1.6), which is an asynchronous version of the MySQL cluster. The MySQL manual explains some of the differences in its <a href="http://dev.mysql.com/doc/refman/5.0/en/faqs-mysql-cluster.html#qandaitem-22-10-3" rel="noreferrer">cluster FAQ</a>, but it is hard to ascertain from it when to use one or the other.</p>
<p>I would appreciate any advice from people who are familiar with the differences between those solutions and what are the pros and cons, and when do you recommend to use each.</p>
|
[
{
"answer_id": 222837,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 2,
"selected": false,
"text": "#\n# Log names\n#\n\nlog-bin=binlog\nrelay-log=relaylog\nlog-error=errors.log\n\n#\n# Log tuning\n#\n\nsync_binlog = 1\nbinlog_cache_size = 1M\n\n#\n# Replication rules (what are we interested in listening for...)\n#\n# In our replicants, we are interested in ANYTHING that isn't a permission table thing\n#\n\nreplicate-ignore-db = mysql\nreplicate-wild-ignore-table=mysql.%\n\n#\n# Replication server ID\n#\n\nserver-id = 2\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585/"
] |
189,906
|
<p>I'm trying to upgrade my subversion server (I have it hosted with Dreamhost)</p>
<p>This is what I run:</p>
<ul>
<li>wget <a href="http://subversion.tigris.org/downloads/subversion-1.5.2.tar.bz2" rel="nofollow noreferrer">http://subversion.tigris.org/downloads/subversion-1.5.2.tar.bz2</a></li>
<li>wget <a href="http://subversion.tigris.org/downloads/subversion-deps-1.5.2.tar.bz2" rel="nofollow noreferrer">http://subversion.tigris.org/downloads/subversion-deps-1.5.2.tar.bz2</a></li>
<li>tar -xjf subversion-1.5.2.tar.bz2</li>
<li>tar -xjf subversion-deps-1.5.2.tar.bz2</li>
<li>cd subversion-1.5.2</li>
<li>./configure --prefix=/usr/bin --with-libs=/usr/bin/openssl --with-ssl</li>
</ul>
<p>But I'm unable to continue any further because of this error:</p>
<ul>
<li>checking for C compiler default output file name...</li>
<li><strong>configure: error: C compiler cannot create executables</strong></li>
<li>See `<a href="http://cid-e67e25d636aab24c.skydrive.live.com/self.aspx/Public/config.log" rel="nofollow noreferrer">config.log</a>' for more details.</li>
<li>configure failed for neon</li>
</ul>
<p>Since I'm no expert with Linux, I'm not sure how to proceed.</p>
<p>So the question is: what is the best way to upgrade (given the constraints of being with this hosted provider).</p>
<p><strong>Update:</strong></p>
<p>Contents of <a href="http://cid-e67e25d636aab24c.skydrive.live.com/self.aspx/Public/config.log" rel="nofollow noreferrer">config.log can be seen here</a> (don't know the best way to show files here at SO)</p>
<p><strong>Update:</strong></p>
<p>I seem to have been looking at the wrong config.log file.<br>
I probably should have been looking at <strong><a href="http://cid-e67e25d636aab24c.skydrive.live.com/self.aspx/Public/neon-config.log" rel="nofollow noreferrer">subversion.1.5.2/neon/config.log</a></strong></p>
|
[
{
"answer_id": 189948,
"author": "Aupajo",
"author_id": 10407,
"author_profile": "https://Stackoverflow.com/users/10407",
"pm_score": 3,
"selected": false,
"text": "mkdir ~/src\ncd ~/src\nwget http://subversion.tigris.org/downloads/subversion-1.5.2.tar.bz2\nwget http://subversion.tigris.org/downloads/subversion-deps-1.5.2.tar.bz2\ntar -xjf subversion-1.5.2.tar.bz2\ntar -xjf subversion-deps-1.5.2.tar.bz2\ncd subversion-1.5.2\n./configure --prefix=/home/$USER --with-ssl\nmake\nmake install\n"
},
{
"answer_id": 221637,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "./configure --prefix=/usr/bin --with-libs=/usr/bin/openssl --with-ssl\n apt-get install libssl-dev\n"
},
{
"answer_id": 330061,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 3,
"selected": true,
"text": "./configure .... --with-openssl=/path/to/openssl\n -fPIC make CC=\"gcc -fPIC\" LDFLAGS=\"/path/to/openssl/lib\"\n CC=\"gcc -fPIC\""
},
{
"answer_id": 419930,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "configure: error: C compiler cannot create executables\n apt-get install gcc apt-get install g++\n"
},
{
"answer_id": 63847971,
"author": "Nicolas PERNOUD",
"author_id": 14260656,
"author_profile": "https://Stackoverflow.com/users/14260656",
"pm_score": 0,
"selected": false,
"text": "sudo apt install -y pkg-config libtool libssl-dev"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18274/"
] |
189,921
|
<p>I'm trying to port an old library (that doesn't use namespaces as far as I can tell) to modern compilers. One of my targets can't tell the difference between System::TObject and ::TObject (without a namespace). System::TObject is native to the compiler.</p>
<p>I've tried a using directive, i.e. using ::TObject;</p>
<p>But that doesn't do it.</p>
<p>The obvious solution is to wrap all the original library in a namespace and then calling it by name- that should avoid the ambiguity. But is that the wisest solution? Is there any other solution? Adding a namespace would require changing a bunch of files and I don't know if it would have unwanted repercussions later.</p>
|
[
{
"answer_id": 189957,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 0,
"selected": false,
"text": "#define TObject TMadeUpNameObject\n"
},
{
"answer_id": 189990,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 0,
"selected": false,
"text": "namespace oldlib\n{\n #inclcude \"oldlib.h\"\n};\n"
},
{
"answer_id": 190100,
"author": "David Segonds",
"author_id": 13673,
"author_profile": "https://Stackoverflow.com/users/13673",
"pm_score": 0,
"selected": false,
"text": "#ifdef Symbol\n#undef Symbol\n#define Symbol ThirdPartySymbol\n#endif\n#include <third_party_header.h>\n#undef Symbol\n"
},
{
"answer_id": 190170,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 2,
"selected": false,
"text": "// In a wrapper header, eg: include_oldlib.h...\n\nnamespace oldlib\n{\n #include \"oldlib.h\"\n};\n\n#ifndef DONT_AUTO_INCLUDE_OLD_NAMESPACE\nusing namespace oldlib;\n#endif\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22885/"
] |
189,934
|
<p>I'm trying to convert some code that worked great in VB, but I can't figure out what objects to use in .Net. </p>
<pre><code> Dim oXMLHttp As XMLHTTP
oXMLHttp = New XMLHTTP
oXMLHttp.open "POST", "https://www.server.com/path", False
oXMLHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oXMLHttp.send requestString
</code></pre>
<p>Basically, I want to send an XML file to a server, then store the response that it returns. Can anyone point me in the right direction on this? </p>
|
[
{
"answer_id": 189966,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 2,
"selected": true,
"text": "Imports System.Net\nImports System.Web.HttpUtility\n\nPublic Class XMLHTTP\n'Makes an internet connection to specified URL \n Public Overridable Sub open(ByVal bstrMethod As String, _\n ByVal bstrUrl As String, Optional ByVal varAsync As _\n Object = False, Optional ByVal bstrUser _\n As Object = \"\", Optional ByVal bstrPassword As Object = \"\")\n Try\n strUrl = bstrUrl\n strMethod = bstrMethod\n\n 'Checking if proxy configuration \n 'is required...(blnIsProxy value \n 'from config file)\n If blnIsProxy Then\n 'Set the proxy object\n proxyObject = WebProxy.GetDefaultProxy()\n\n 'Finding if proxy exists and if so set \n 'the proxy configuration parameters...\n If Not (IsNothing(proxyObject.Address)) Then\n uriAddress = proxyObject.Address\n If Not (IsNothing(uriAddress)) Then\n _ProxyName = uriAddress.Host\n _ProxyPort = uriAddress.Port\n End If\n UpdateProxy()\n End If\n urlWebRequest.Proxy = proxyObject\n End If\n\n 'Make the webRequest...\n urlWebRequest = System.Net.HttpWebRequest.Create(strUrl)\n urlWebRequest.Method = strMethod\n\n If (strMethod = \"POST\") Then\n setRequestHeader(\"Content-Type\", _\n \"application/x-www-form-urlencoded\")\n End If\n\n 'Add the cookie values of jessionid of weblogic \n 'and PH-Session value of webseal \n 'for retaining the same session\n urlWebRequest.Headers.Add(\"Cookie\", str_g_cookieval)\n\n Catch exp As Exception\n SetErrStatusText(\"Error opening method level url connection\")\n End Try\n End Sub\n 'Sends the request with post parameters...\n Public Overridable Sub Send(Optional ByVal objBody As Object = \"\")\n Try\n Dim rspResult As System.Net.HttpWebResponse\n Dim strmRequestStream As System.IO.Stream\n Dim strmReceiveStream As System.IO.Stream\n Dim encode As System.Text.Encoding\n Dim sr As System.IO.StreamReader\n Dim bytBytes() As Byte\n Dim UrlEncoded As New System.Text.StringBuilder\n Dim reserved() As Char = {ChrW(63), ChrW(61), ChrW(38)}\n urlWebRequest.Expect = Nothing\n If (strMethod = \"POST\") Then\n If objBody <> Nothing Then\n Dim intICounter As Integer = 0\n Dim intJCounter As Integer = 0\n While intICounter < objBody.Length\n intJCounter = _\n objBody.IndexOfAny(reserved, intICounter)\n If intJCounter = -1 Then\nUrlEncoded.Append(System.Web.HttpUtility.UrlEncode(objBody.Substring(intICounter, _\n objBody.Length - intICounter)))\n Exit While\n End If\nUrlEncoded.Append(System.Web.HttpUtility.UrlEncode(objBody.Substring(intICounter, _\n intJCounter - intICounter)))\n UrlEncoded.Append(objBody.Substring(intJCounter, 1))\n intICounter = intJCounter + 1\n End While\n\n bytBytes = _\n System.Text.Encoding.UTF8.GetBytes(UrlEncoded.ToString())\n urlWebRequest.ContentLength = bytBytes.Length\n strmRequestStream = urlWebRequest.GetRequestStream\n strmRequestStream.Write(bytBytes, 0, bytBytes.Length)\n strmRequestStream.Close()\n Else\n urlWebRequest.ContentLength = 0\n End If\n End If\n rspResult = urlWebRequest.GetResponse()\n strmReceiveStream = rspResult.GetResponseStream()\n encode = System.Text.Encoding.GetEncoding(\"utf-8\")\n sr = New System.IO.StreamReader(strmReceiveStream, encode)\n\n Dim read(256) As Char\n Dim count As Integer = sr.Read(read, 0, 256)\n Do While count > 0\n Dim str As String = New String(read, 0, count)\n strResponseText = strResponseText & str\n count = sr.Read(read, 0, 256)\n Loop\n Catch exp As Exception\n SetErrStatusText(\"Error while sending parameters\")\n WritetoLog(exp.ToString)\n End Try\n End Sub\n 'Setting header values...\n Public Overridable Sub setRequestHeader(ByVal bstrHeader _\n As String, ByVal bstrValue As String)\n Select Case bstrHeader\n Case \"Referer\"\n urlWebRequest.Referer = bstrValue\n Case \"User-Agent\"\n urlWebRequest.UserAgent = bstrValue\n Case \"Content-Type\"\n urlWebRequest.ContentType = bstrValue\n Case Else\n urlWebRequest.Headers(bstrHeader) = bstrValue\n End Select\n End Sub\n\n Private Function UpdateProxy()\n Try\n If Not (IsNothing(uriAddress)) Then\n If ((Not IsNothing(_ProxyName)) And _\n (_ProxyName.Length > 0) And (_ProxyPort > 0)) Then\n proxyObject = New WebProxy(_ProxyName, _ProxyPort)\n Dim strByPass() As String = Split(strByPassList, \"|\")\n If strByPass.Length > 0 Then\n proxyObject.BypassList = strByPass\n End If\n proxyObject.BypassProxyOnLocal = True\n If blnNetworkCredentials Then\n If strDomain <> \"\" Then\n proxyObject.Credentials = New _\n NetworkCredential(strUserName, _\n strPwd, strDomain)\n Else\n proxyObject.Credentials = New _\n NetworkCredential(strUserName, _\n strPwd)\n End If\n End If\n End If\n End If\n Catch exp As Exception\n SetErrStatusText(\"Error while updating proxy configurations\")\n WritetoLog(exp.ToString)\n End Try\n End Function\n 'Property for setting the Responsetext\n Public Overridable ReadOnly Property ResponseText() As String\n Get\n ResponseText = strResponseText\n End Get\n End Property\n\n Private urlWebRequest As System.Net.HttpWebRequest\n Private urlWebResponse As System.Net.HttpWebResponse\n Private strResponseText As String\n Private strUrl As String\n Private strMethod As String\n Private proxyObject As WebProxy\n Private intCount As Integer\n Private uriAddress As Uri\n Private _ProxyName As String\n Private _ProxyPort As Integer\nEnd Class\n"
},
{
"answer_id": 190650,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 2,
"selected": false,
"text": "WebClient WebClient webClient = new WebClient();\n\nNameValueCollection values = new NameValueCollection();\n\nvalues.add(\"firstname\", \"Slarti\");\nvalues.add(\"lastname\", \"Bart-fast\");\n\nbyte[] response = webClient.UploadValues(\"http://server/path\", values);\n application/x-www-form-urlencoded NameValueCollection"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] |
189,943
|
<p>Here's what I would like to do:</p>
<p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p>
<p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p>
<p>I'm looking for simplicity rather than perfection.
I'm using python.</p>
|
[
{
"answer_id": 190061,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 5,
"selected": false,
"text": "i1 i2"
},
{
"answer_id": 196882,
"author": "elifiner",
"author_id": 15109,
"author_profile": "https://Stackoverflow.com/users/15109",
"pm_score": 6,
"selected": false,
"text": "import Image\nimport ImageChops\n\nim1 = Image.open(\"splash.png\")\nim2 = Image.open(\"splash2.png\")\n\ndiff = ImageChops.difference(im2, im1)\n diff.getbbox()"
},
{
"answer_id": 3935002,
"author": "sastanin",
"author_id": 25450,
"author_profile": "https://Stackoverflow.com/users/25450",
"pm_score": 9,
"selected": true,
"text": "scipy.misc.imread import sys\n\nfrom scipy.misc import imread\nfrom scipy.linalg import norm\nfrom scipy import sum, average\n def main():\n file1, file2 = sys.argv[1:1+2]\n # read images as 2D arrays (convert to grayscale for simplicity)\n img1 = to_grayscale(imread(file1).astype(float))\n img2 = to_grayscale(imread(file2).astype(float))\n # compare\n n_m, n_0 = compare_images(img1, img2)\n print \"Manhattan norm:\", n_m, \"/ per pixel:\", n_m/img1.size\n print \"Zero norm:\", n_0, \"/ per pixel:\", n_0*1.0/img1.size\n img1 img2 def compare_images(img1, img2):\n # normalize to compensate for exposure difference, this may be unnecessary\n # consider disabling it\n img1 = normalize(img1)\n img2 = normalize(img2)\n # calculate the difference and its norms\n diff = img1 - img2 # elementwise for scipy arrays\n m_norm = sum(abs(diff)) # Manhattan norm\n z_norm = norm(diff.ravel(), 0) # Zero norm\n return (m_norm, z_norm)\n imread .pgm def to_grayscale(arr):\n \"If arr is a color image (3D array), convert it to grayscale (2D array).\"\n if len(arr.shape) == 3:\n return average(arr, -1) # average over the last axis (color channels)\n else:\n return arr\n arr def normalize(arr):\n rng = arr.max()-arr.min()\n amin = arr.min()\n return (arr-amin)*255/rng\n main if __name__ == \"__main__\":\n main()\n $ python compare.py one.jpg one.jpg\nManhattan norm: 0.0 / per pixel: 0.0\nZero norm: 0 / per pixel: 0.0\n $ python compare.py one.jpg one-blurred.jpg \nManhattan norm: 92605183.67 / per pixel: 13.4210411116\nZero norm: 6900000 / per pixel: 1.0\n cv2"
},
{
"answer_id": 44106540,
"author": "admin",
"author_id": 6489637,
"author_profile": "https://Stackoverflow.com/users/6489637",
"pm_score": 2,
"selected": false,
"text": "import os\nfrom PIL import Image\nfrom PIL import ImageFile\nimport imagehash\n \n#just use to the size diferent picture\ndef compare_image(img_file1, img_file2):\n if img_file1 == img_file2:\n return True\n fp1 = open(img_file1, 'rb')\n fp2 = open(img_file2, 'rb')\n\n img1 = Image.open(fp1)\n img2 = Image.open(fp2)\n\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n b = img1 == img2\n\n fp1.close()\n fp2.close()\n\n return b\n\n\n\n\n\n#through picturu hash to compare\ndef get_hash_dict(dir):\n hash_dict = {}\n image_quantity = 0\n for _, _, files in os.walk(dir):\n for i, fileName in enumerate(files):\n with open(dir + fileName, 'rb') as fp:\n hash_dict[dir + fileName] = imagehash.average_hash(Image.open(fp))\n image_quantity += 1\n\n return hash_dict, image_quantity\n\ndef compare_image_with_hash(image_file_name_1, image_file_name_2, max_dif=0):\n \"\"\"\n max_dif: The maximum hash difference is allowed, the smaller and more accurate, the minimum is 0.\n recommend to use\n \"\"\"\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n hash_1 = None\n hash_2 = None\n with open(image_file_name_1, 'rb') as fp:\n hash_1 = imagehash.average_hash(Image.open(fp))\n with open(image_file_name_2, 'rb') as fp:\n hash_2 = imagehash.average_hash(Image.open(fp))\n dif = hash_1 - hash_2\n if dif < 0:\n dif = -dif\n if dif <= max_dif:\n return True\n else:\n return False\n\n\ndef compare_image_dir_with_hash(dir_1, dir_2, max_dif=0):\n \"\"\"\n max_dif: The maximum hash difference is allowed, the smaller and more accurate, the minimum is 0.\n\n \"\"\"\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n hash_dict_1, image_quantity_1 = get_hash_dict(dir_1)\n hash_dict_2, image_quantity_2 = get_hash_dict(dir_2)\n\n if image_quantity_1 > image_quantity_2:\n tmp = image_quantity_1\n image_quantity_1 = image_quantity_2\n image_quantity_2 = tmp\n\n tmp = hash_dict_1\n hash_dict_1 = hash_dict_2\n hash_dict_2 = tmp\n\n result_dict = {}\n\n for k in hash_dict_1.keys():\n result_dict[k] = None\n\n for dif_i in range(0, max_dif + 1):\n have_none = False\n\n for k_1 in result_dict.keys():\n if result_dict.get(k_1) is None:\n have_none = True\n\n if not have_none:\n return result_dict\n\n for k_1, v_1 in hash_dict_1.items():\n for k_2, v_2 in hash_dict_2.items():\n sub = (v_1 - v_2)\n if sub < 0:\n sub = -sub\n if sub == dif_i and result_dict.get(k_1) is None:\n result_dict[k_1] = k_2\n break\n return result_dict\n\n\ndef main():\n print(compare_image('image1\\\\815.jpg', 'image2\\\\5.jpg'))\n print(compare_image_with_hash('image1\\\\815.jpg', 'image2\\\\5.jpg', 7))\n r = compare_image_dir_with_hash('image1\\\\', 'image2\\\\', 10)\n for k in r.keys():\n print(k, r.get(k))\n\n\nif __name__ == '__main__':\n main()\n"
},
{
"answer_id": 49574931,
"author": "duhaime",
"author_id": 1727392,
"author_profile": "https://Stackoverflow.com/users/1727392",
"pm_score": 3,
"selected": false,
"text": "import sys\nfrom skimage.measure import compare_ssim\nfrom skimage.transform import resize\nfrom scipy.ndimage import imread\n\n# get two images - resize both to 1024 x 1024\nimg_a = resize(imread(sys.argv[1]), (2**10, 2**10))\nimg_b = resize(imread(sys.argv[2]), (2**10, 2**10))\n\n# score: {-1:1} measure of the structural similarity between the images\nscore, diff = compare_ssim(img_a, img_b, full=True)\nprint(score)\n"
},
{
"answer_id": 50879276,
"author": "zanfranceschi",
"author_id": 3149605,
"author_profile": "https://Stackoverflow.com/users/3149605",
"pm_score": 2,
"selected": false,
"text": "previous_screenshot = ...\ncurrent_screenshot = ...\n\n# simplify both images somehow\n\n# get the 100% corresponding value\nres = matchTemplate(previous_screenshot, previous_screenshot, TM_CCOEFF)\n_, hundred_p_val, _, _ = minMaxLoc(res)\n\n# hundred_p_val is now the 100%\n\nres = matchTemplate(previous_screenshot, current_screenshot, TM_CCOEFF)\n_, max_val, _, _ = minMaxLoc(res)\n\ndifference_percentage = max_val / hundred_p_val\n\n# the tolerance is now up to you\n"
},
{
"answer_id": 57098987,
"author": "Arian Soltani",
"author_id": 5259791,
"author_profile": "https://Stackoverflow.com/users/5259791",
"pm_score": 1,
"selected": false,
"text": "before = np.array(get_picture())\nwhile True:\n now = np.array(get_picture())\n MSE = np.mean((now - before)**2)\n\n if MSE > threshold:\n break\n\n before = now\n"
},
{
"answer_id": 66402594,
"author": "Pedro Vernetti",
"author_id": 4233943,
"author_profile": "https://Stackoverflow.com/users/4233943",
"pm_score": 1,
"selected": false,
"text": "== from PIL import Image\n\ndef imagesDifference( imageA, imageB ):\n A = list(Image.open(imageA, r'r').convert(r'RGB').getdata())\n B = list(Image.open(imageB, r'r').convert(r'RGB').getdata())\n if (len(A) != len(B)): return -1\n diff = []\n for i in range(0, len(A)):\n diff += [abs(A[i][0] - B[i][0]), abs(A[i][1] - B[i][1]), abs(A[i][2] - B[i][2])]\n return (sum(diff) / len(diff))\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498/"
] |
189,947
|
<p>Have a n-tire web application and search often times out after 30 secs. How to detect the root cause of the problem?</p>
|
[
{
"answer_id": 190061,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 5,
"selected": false,
"text": "i1 i2"
},
{
"answer_id": 196882,
"author": "elifiner",
"author_id": 15109,
"author_profile": "https://Stackoverflow.com/users/15109",
"pm_score": 6,
"selected": false,
"text": "import Image\nimport ImageChops\n\nim1 = Image.open(\"splash.png\")\nim2 = Image.open(\"splash2.png\")\n\ndiff = ImageChops.difference(im2, im1)\n diff.getbbox()"
},
{
"answer_id": 3935002,
"author": "sastanin",
"author_id": 25450,
"author_profile": "https://Stackoverflow.com/users/25450",
"pm_score": 9,
"selected": true,
"text": "scipy.misc.imread import sys\n\nfrom scipy.misc import imread\nfrom scipy.linalg import norm\nfrom scipy import sum, average\n def main():\n file1, file2 = sys.argv[1:1+2]\n # read images as 2D arrays (convert to grayscale for simplicity)\n img1 = to_grayscale(imread(file1).astype(float))\n img2 = to_grayscale(imread(file2).astype(float))\n # compare\n n_m, n_0 = compare_images(img1, img2)\n print \"Manhattan norm:\", n_m, \"/ per pixel:\", n_m/img1.size\n print \"Zero norm:\", n_0, \"/ per pixel:\", n_0*1.0/img1.size\n img1 img2 def compare_images(img1, img2):\n # normalize to compensate for exposure difference, this may be unnecessary\n # consider disabling it\n img1 = normalize(img1)\n img2 = normalize(img2)\n # calculate the difference and its norms\n diff = img1 - img2 # elementwise for scipy arrays\n m_norm = sum(abs(diff)) # Manhattan norm\n z_norm = norm(diff.ravel(), 0) # Zero norm\n return (m_norm, z_norm)\n imread .pgm def to_grayscale(arr):\n \"If arr is a color image (3D array), convert it to grayscale (2D array).\"\n if len(arr.shape) == 3:\n return average(arr, -1) # average over the last axis (color channels)\n else:\n return arr\n arr def normalize(arr):\n rng = arr.max()-arr.min()\n amin = arr.min()\n return (arr-amin)*255/rng\n main if __name__ == \"__main__\":\n main()\n $ python compare.py one.jpg one.jpg\nManhattan norm: 0.0 / per pixel: 0.0\nZero norm: 0 / per pixel: 0.0\n $ python compare.py one.jpg one-blurred.jpg \nManhattan norm: 92605183.67 / per pixel: 13.4210411116\nZero norm: 6900000 / per pixel: 1.0\n cv2"
},
{
"answer_id": 44106540,
"author": "admin",
"author_id": 6489637,
"author_profile": "https://Stackoverflow.com/users/6489637",
"pm_score": 2,
"selected": false,
"text": "import os\nfrom PIL import Image\nfrom PIL import ImageFile\nimport imagehash\n \n#just use to the size diferent picture\ndef compare_image(img_file1, img_file2):\n if img_file1 == img_file2:\n return True\n fp1 = open(img_file1, 'rb')\n fp2 = open(img_file2, 'rb')\n\n img1 = Image.open(fp1)\n img2 = Image.open(fp2)\n\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n b = img1 == img2\n\n fp1.close()\n fp2.close()\n\n return b\n\n\n\n\n\n#through picturu hash to compare\ndef get_hash_dict(dir):\n hash_dict = {}\n image_quantity = 0\n for _, _, files in os.walk(dir):\n for i, fileName in enumerate(files):\n with open(dir + fileName, 'rb') as fp:\n hash_dict[dir + fileName] = imagehash.average_hash(Image.open(fp))\n image_quantity += 1\n\n return hash_dict, image_quantity\n\ndef compare_image_with_hash(image_file_name_1, image_file_name_2, max_dif=0):\n \"\"\"\n max_dif: The maximum hash difference is allowed, the smaller and more accurate, the minimum is 0.\n recommend to use\n \"\"\"\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n hash_1 = None\n hash_2 = None\n with open(image_file_name_1, 'rb') as fp:\n hash_1 = imagehash.average_hash(Image.open(fp))\n with open(image_file_name_2, 'rb') as fp:\n hash_2 = imagehash.average_hash(Image.open(fp))\n dif = hash_1 - hash_2\n if dif < 0:\n dif = -dif\n if dif <= max_dif:\n return True\n else:\n return False\n\n\ndef compare_image_dir_with_hash(dir_1, dir_2, max_dif=0):\n \"\"\"\n max_dif: The maximum hash difference is allowed, the smaller and more accurate, the minimum is 0.\n\n \"\"\"\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n hash_dict_1, image_quantity_1 = get_hash_dict(dir_1)\n hash_dict_2, image_quantity_2 = get_hash_dict(dir_2)\n\n if image_quantity_1 > image_quantity_2:\n tmp = image_quantity_1\n image_quantity_1 = image_quantity_2\n image_quantity_2 = tmp\n\n tmp = hash_dict_1\n hash_dict_1 = hash_dict_2\n hash_dict_2 = tmp\n\n result_dict = {}\n\n for k in hash_dict_1.keys():\n result_dict[k] = None\n\n for dif_i in range(0, max_dif + 1):\n have_none = False\n\n for k_1 in result_dict.keys():\n if result_dict.get(k_1) is None:\n have_none = True\n\n if not have_none:\n return result_dict\n\n for k_1, v_1 in hash_dict_1.items():\n for k_2, v_2 in hash_dict_2.items():\n sub = (v_1 - v_2)\n if sub < 0:\n sub = -sub\n if sub == dif_i and result_dict.get(k_1) is None:\n result_dict[k_1] = k_2\n break\n return result_dict\n\n\ndef main():\n print(compare_image('image1\\\\815.jpg', 'image2\\\\5.jpg'))\n print(compare_image_with_hash('image1\\\\815.jpg', 'image2\\\\5.jpg', 7))\n r = compare_image_dir_with_hash('image1\\\\', 'image2\\\\', 10)\n for k in r.keys():\n print(k, r.get(k))\n\n\nif __name__ == '__main__':\n main()\n"
},
{
"answer_id": 49574931,
"author": "duhaime",
"author_id": 1727392,
"author_profile": "https://Stackoverflow.com/users/1727392",
"pm_score": 3,
"selected": false,
"text": "import sys\nfrom skimage.measure import compare_ssim\nfrom skimage.transform import resize\nfrom scipy.ndimage import imread\n\n# get two images - resize both to 1024 x 1024\nimg_a = resize(imread(sys.argv[1]), (2**10, 2**10))\nimg_b = resize(imread(sys.argv[2]), (2**10, 2**10))\n\n# score: {-1:1} measure of the structural similarity between the images\nscore, diff = compare_ssim(img_a, img_b, full=True)\nprint(score)\n"
},
{
"answer_id": 50879276,
"author": "zanfranceschi",
"author_id": 3149605,
"author_profile": "https://Stackoverflow.com/users/3149605",
"pm_score": 2,
"selected": false,
"text": "previous_screenshot = ...\ncurrent_screenshot = ...\n\n# simplify both images somehow\n\n# get the 100% corresponding value\nres = matchTemplate(previous_screenshot, previous_screenshot, TM_CCOEFF)\n_, hundred_p_val, _, _ = minMaxLoc(res)\n\n# hundred_p_val is now the 100%\n\nres = matchTemplate(previous_screenshot, current_screenshot, TM_CCOEFF)\n_, max_val, _, _ = minMaxLoc(res)\n\ndifference_percentage = max_val / hundred_p_val\n\n# the tolerance is now up to you\n"
},
{
"answer_id": 57098987,
"author": "Arian Soltani",
"author_id": 5259791,
"author_profile": "https://Stackoverflow.com/users/5259791",
"pm_score": 1,
"selected": false,
"text": "before = np.array(get_picture())\nwhile True:\n now = np.array(get_picture())\n MSE = np.mean((now - before)**2)\n\n if MSE > threshold:\n break\n\n before = now\n"
},
{
"answer_id": 66402594,
"author": "Pedro Vernetti",
"author_id": 4233943,
"author_profile": "https://Stackoverflow.com/users/4233943",
"pm_score": 1,
"selected": false,
"text": "== from PIL import Image\n\ndef imagesDifference( imageA, imageB ):\n A = list(Image.open(imageA, r'r').convert(r'RGB').getdata())\n B = list(Image.open(imageB, r'r').convert(r'RGB').getdata())\n if (len(A) != len(B)): return -1\n diff = []\n for i in range(0, len(A)):\n diff += [abs(A[i][0] - B[i][0]), abs(A[i][1] - B[i][1]), abs(A[i][2] - B[i][2])]\n return (sum(diff) / len(diff))\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26365/"
] |
189,972
|
<p>I know of the following:</p>
<ul>
<li>The venerable <code>getopt(3)</code></li>
<li>The extended <code>getopt_long</code></li>
<li>glibc's <a href="http://www.gnu.org/software/libtool/manual/libc/Argp.html" rel="noreferrer"><code>argp</code></a> parser for Unix-style argument vectors</li>
<li><a href="http://developer.gnome.org/arch/misc/popt.html" rel="noreferrer">popt</a> from the GNOME project (or its spiritual successor in <a href="http://library.gnome.org/devel/glib/stable/glib-Commandline-option-parser.html" rel="noreferrer">Glib</a>)</li>
</ul>
<p>I'm sure there's more that I haven't used or even heard of; a quick Google search reveals <a href="http://www.purposeful.co.uk/software/gopt/" rel="noreferrer">Gopt</a>, <a href="http://argtable.sourceforge.net/" rel="noreferrer">argtable</a>, and <a href="http://michael.dipperstein.com/optlist/" rel="noreferrer">Optlist</a>.</p>
<p>Personally, I like <code>argp</code> best, and every program I wrote using <code>getopt</code>/<code>getopt_long</code> (beyond a certain baseline of complexity) has been converted to use <code>argp</code>. It's more widely available than <code>popt</code>, more powerful than <code>getopt_long</code>, well-documented, consistent with all the GNU-style conventions, and very flexible. On the downside, it's far from the easiest to use (thanks to being so flexible), and the code to support it is quite verbose (as are many things in C).</p>
<p>What do you use, and why?</p>
<p>Yes, I mean C rather than C++. There are a ton of C++ parsers, but I don't use C++.</p>
<p>John Millikin notes that <code>popt</code> is no longer maintained. I list it because many programs still use it -- including AbiWord, rpm, rsync, and samba -- despite Gnome's efforts to <a href="http://live.gnome.org/ProjectRidley" rel="noreferrer">migrate away</a>. But I've added a link to Glib's argument parser now, too.</p>
<hr/>
<p>For C++ argument parsing, see the question <em><a href="https://stackoverflow.com/questions/253556/what-parameter-parser-libraries-are-there-for-c">What parameter parser libraries are there for C++?</a></em></p>
|
[
{
"answer_id": 189980,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "popt glib glib getopt"
},
{
"answer_id": 191821,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 5,
"selected": true,
"text": "getopt_long"
},
{
"answer_id": 44055394,
"author": "sigvaldm",
"author_id": 7896710,
"author_profile": "https://Stackoverflow.com/users/7896710",
"pm_score": 2,
"selected": false,
"text": "int main(int argc, char **argv){\n\n if(argopt(argc, argv, 'p')) printf(\"-p is set\\n\");\n if(argopt(argc, argv, 'q')) printf(\"-q is set\\n\");\n\n const char *f = argopt(argc, argv, 'f');\n if(f) printf(\"-f is %s\\n\",f);\n\n return 0;\n}\n $./main -f input.txt -rq\n-q is set\n-f is input.txt\n const char* argopt(int argc, const char *const *argv, char key){\n\n for(int i=1; i<argc; i++){\n const char *c = argv[i];\n if(*c!='-') continue;\n while(*++c) if(*c==key) return argv[(i+1)%argc];\n }\n\n return 0;\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20713/"
] |
189,976
|
<p>This is more of a design question. </p>
<p>I am building a tool that displays business objects in various ways (ie Tree Nodes, List View Items, Combo Boxes, Text Fields, etc). Anytime the user changes any of one of them, an event is raised that signals that that business object has been changed or the collection that it belongs to has been changed. Since this business object, or the collection that it might belong to, may be displayed in more than one place, each of those UI elements needs to be updated to reflect this change. Is there an elegant solution to having each type of UI element update correctly in the event of a change?</p>
<p>I have a few ideas of how this can be done, but I'd like to see if anyone has had this problem and was happy with their solution. This is a C# WinForm, but a solution can be in any language.</p>
<p>My current thoughts on the problem and a possible solution:</p>
<p>It gets more complicated when you want to clean up event bindings (ie businessObject.Changed -= ObjectChanged) when your business objects become part of a TreeNodeCollection/ListViewITemCollection/ComboBoxItemCollection and Clear() is called on the collection. </p>
<p>What about a "Service", where each object and its ui element can register itself with, where the business object's events can be listened for in one location, and each UI element would be updated when events are raised? When all UI elements have unregistered themselves, then the subscription to that object's event is removed. </p>
<p>The problem with this solution is that every control will have to be responsible for registering the UI component and the object on every creation - which can get messy.</p>
<p>Your thoughts?</p>
|
[
{
"answer_id": 189991,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public delegate void ObjectRefresh(BusinessObject obj);\n public event ObjectRefresh;\n if (ObjectRefresh)\n ObjectRefresh(this);\n BusinessObject obj = GetBusinessObject();\nobj.ObjectRefresh += this.ObjectRefresh;\n...\nprivate void ObjectRefresh(BusinessObject obj)\n{\n // update UI\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
189,985
|
<p>I want to put Apache 2.2.9 in front of a Weblogic 9.2 server on Windows XP. What does it take to do that ?<br></p>
<p>I probably need mod_proxy on the apache side ? <br></p>
<p>As far as Weblogic and apache are concerned, is there something similar to mod_jk ?<br></p>
<p>I would like this setup so that I can introduce some filtering later on. But for now, the goal is to allow other computers to access weblogic appserver so that Apache forwards all requests coming to it (at a certain URL) to Weblogic.</p>
<p>I have done this several times earlier BUT have forgotten how I did it.</p>
<p>Thanks for any pointers,</p>
<hr>
<p>I guess <a href="http://e-docs.bea.com/wls/docs81/plugins/apache.html" rel="nofollow noreferrer">http://e-docs.bea.com/wls/docs81/plugins/apache.html</a> answers most of the basic fundas. Will update the forum if I have more inputs.</p>
|
[
{
"answer_id": 5527885,
"author": "Ujjwal",
"author_id": 249186,
"author_profile": "https://Stackoverflow.com/users/249186",
"pm_score": 1,
"selected": false,
"text": "update httpd.conf to load weblogic_module --> mod_wl_20.so\n\n<IfModule mod_weblogic.c> \n WebLogicCluster w1s1.com:7001,w1s2.com:7001,w1s3.com:7001\n MatchExpression *.jsp \n MatchExpression *.xyz\n</IfModule>\n update httpd.conf to load proxy_module --> mod_proxy.so\n\n<Location /service>\n ProxyPass http://wls1.com:7001/service\n ProxyPassReverse http://wls1.com:7001/service\n</Location>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11142/"
] |
189,988
|
<p>An idiom commonly used in OO languages like Python and Ruby is instantiating an object and chaining methods that return a reference to the object itself, such as:</p>
<pre><code>s = User.new.login.get_db_data.get_session_data
</code></pre>
<p>In PHP, it is possible to replicate this behavior like so:</p>
<pre><code>$u = new User();
$s = $u->login()->get_db_data()->get_session_data();
</code></pre>
<p>Attempting the following results in <code>syntax error, unexpected T_OBJECT_OPERATOR</code>:</p>
<pre><code>$s = new User()->login()->get_db_data()->get_session_data();
</code></pre>
<p>It seems like this could be accomplished using static methods, which is probably what I'll end up doing, but I wanted to check the lazyweb: <strong>Is there actually a clean, simple way to instantiate PHP classes "inline" (as shown in the above snippet)</strong> for this purpose?</p>
<p>If I do decide to use static methods, <strong>is it too sorcerous to have a class's static method return an instantiation of the class itself</strong>? (Effectively writing my own constructor-that-isn't-a-constructor?) It feels kind of dirty, but if there aren't too many scary side effects, I might just do it.</p>
<p>I guess I could also pre-instantiate a UserFactory with a get_user() method, but I'm curious about solutions to what I asked above.</p>
|
[
{
"answer_id": 190014,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n class User\n {\n function __construct()\n {\n }\n\n function Login()\n {\n return $this;\n }\n\n function GetDbData()\n {\n return $this;\n }\n\n function GetSession()\n {\n return array(\"hello\" => \"world\");\n }\n }\n\n function Create($name)\n {\n return new $name();\n }\n\n $s = Create(\"User\")->Login()->GetDbData()->GetSession();\n\n var_dump($s);\n?>\n <?php\n\n class User\n {\n function __construct($test)\n {\n echo $test;\n }\n...\n }\n\n function CreateArgs($name)\n {\n $ref = new ReflectionClass($name);\n return $ref->newInstanceArgs(array_slice(func_get_args(), 1));\n }\n\n $s = CreateArgs(\"User\", \"hi\")->Login()->GetDbData()->GetSession();\n\n var_dump($s);\n?>\n"
},
{
"answer_id": 190027,
"author": "dcousineau",
"author_id": 20265,
"author_profile": "https://Stackoverflow.com/users/20265",
"pm_score": 2,
"selected": false,
"text": "class User\n{\n //...\n /**\n *\n * @return User\n */\n public static function instance()\n {\n $args = func_get_args();\n $class = new ReflectionClass(__CLASS__);\n return $class->newInstanceArgs($args);\n }\n //...\n}\n $s = User::instance()->login()->get_db_data()->get_session_data();\n return new self();\n"
},
{
"answer_id": 190052,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 5,
"selected": true,
"text": "$u = new User();\n$s = $u->login()->get_db_data()->get_session_data();\n"
},
{
"answer_id": 1429788,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "function hack($obj) { return $obj; }\n\n$mail = hack(new Zend_Mail())\n -> setBodyText('This is the text of the mail.')\n -> setFrom('somebody@example.com', 'Some Sender')\n -> addTo('somebody_else@example.com', 'Some Recipient')\n -> setSubject('TestSubject');\n"
},
{
"answer_id": 22400374,
"author": "igaster",
"author_id": 1680535,
"author_profile": "https://Stackoverflow.com/users/1680535",
"pm_score": 3,
"selected": false,
"text": "$Obj = new ClassName();\n$result = $Obj->memberFunction();\n $result = (new ClassName())->memberFunction();\n"
},
{
"answer_id": 31662890,
"author": "PHPDave",
"author_id": 3712596,
"author_profile": "https://Stackoverflow.com/users/3712596",
"pm_score": 1,
"selected": false,
"text": "<?php \n//PHP 5.4+ class member access on instantiation support.\n$s = (new User())->login()->get_db_data()->get_session_data();\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034/"
] |
189,993
|
<p>When I use ApacheBench to test https, the error is returned, "ssl handshake failed".</p>
<p>How can I use ApacheBench to test https?</p>
|
[
{
"answer_id": 4149548,
"author": "naugtur",
"author_id": 173077,
"author_profile": "https://Stackoverflow.com/users/173077",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\nK=200; \nHTTPSA='https://192.168.1.103:443/' \ndate +%M-%S-%N>wgetres.txt\nfor (( c=1; c<=$K; c++ ))\ndo\n wget --no-check-certificate --secure-protocol=SSLv3 --spider $HTTPSA\ndone\ndate +%M-%S-%N>>wgetres.txt\n"
},
{
"answer_id": 12224732,
"author": "comb",
"author_id": 786984,
"author_profile": "https://Stackoverflow.com/users/786984",
"pm_score": 3,
"selected": false,
"text": " --ssl Specifies that all communication between httperf and the server\n should utilize the Secure Sockets Layer (SSL) protocol. This\n option is available only if httperf was compiled with SSL supâ€\n port enabled.\n\n --ssl-ciphers=L\n This option is only meaningful if SSL is in use (see --ssl\n option). This option specifies the list L of cipher suites that\n httperf may use in negotiating a secure connection with the\n server. If the list contains more than one cipher suite, the\n ciphers must be separated by a colon. If the server does not\n accept any of the listed cipher suites, the connection estabâ€\n lishment will fail and httperf will exit immediately. If this\n option is not specified when the --ssl option is present then\n httperf will use all of the SSLv3 cipher suites provided by the\n underlying SSL library.\n\n --ssl-no-reuse\n This option is only meaningful if SSL and sessions are in use\n (see --ssl, --wsess, --wsesslog). When an SSL connection is\n established the client receives a session identifier (session\n id) from the server. On subsequent SSL connections, the client\n normally reuses this session id in order to avoid the expense of\n repeating the (slow) SSL handshake to establish a new SSL sesâ€\n sion and obtain another session id (even if the client attempts\n to re-use a session id, the server may force the client to reneâ€\n gotiate a session). By default httperf reuses the session id\n across all connections in a session. If the --ssl-no-reuse\n option is in effect, then httperf will not reuse the session id,\n and the entire SSL handshake will be performed for each new conâ€\n nection in a session.\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
190,006
|
<p>I've studied C programming in college some years ago and have developed some medium applications back then (nothing serious). Now I have to develop some more 'advanced' C applications (involving POSIX threads and RPC), but right now I'm a little rusty even with the basics.</p>
<p>Can anyone recommend me good online C reference manuals? This may help me get in tune faster.</p>
|
[
{
"answer_id": 202919,
"author": "Frank Szczerba",
"author_id": 8964,
"author_profile": "https://Stackoverflow.com/users/8964",
"pm_score": 2,
"selected": false,
"text": "man printf info printf"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26699/"
] |
190,007
|
<p>When developing Java applications, I often override Object methods (usually equals and hashCode). I would like some way to systematically check that I'm adhering to the contract for Object methods for every one of my classes. For example, I want tests that assert that for equal objects, the hash code is also equal. I'm using the JUnit test framework, so preferably I'd like some JUnit solution where I can automatically generate these tests, or some test case that can somehow visit all of my classes and make sure that the contract is upheld.</p>
<p>I'm using JDK6 and JUnit 4.4.</p>
|
[
{
"answer_id": 13152063,
"author": "Jeff Bowman",
"author_id": 1426891,
"author_profile": "https://Stackoverflow.com/users/1426891",
"pm_score": 0,
"selected": false,
"text": "EqualsTester a.equals(b) a.hashCode() == b.hashCode() new EqualsTester()\n .addEqualityGroup(\"hello\", \"h\" + \"ello\")\n .addEqualityGroup(\"world\", \"wor\" + \"ld\")\n .addEqualityGroup(2, 1 + 1)\n .testEquals();\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8217/"
] |
190,010
|
<p>In the <a href="https://docs.python.org/2/library/threading.html#thread-objects" rel="noreferrer">Python documentation</a>
it says:</p>
<blockquote>
<p>A thread can be flagged as a "daemon thread". The significance of this
flag is that the entire Python program exits when only daemon threads
are left. The initial value is inherited from the creating thread.</p>
</blockquote>
<p>Does anyone have a clearer explanation of what that means or a practical example showing where you would set threads as <code>daemonic</code>?</p>
<p>Clarify it for me: so the only situation you wouldn't set threads as <code>daemonic</code>, is when you want them to continue running after the main thread exits?</p>
|
[
{
"answer_id": 68556232,
"author": "Rohit",
"author_id": 6695608,
"author_profile": "https://Stackoverflow.com/users/6695608",
"pm_score": 4,
"selected": false,
"text": "dameon daemon daemon non-daemon non-daemon non-daemon daemon daemon daemon daemon daemon daemon non-daemon non-daemon daemon"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16148/"
] |
190,045
|
<p>I have a large int[] array and a much smaller int[] array. I want to fill up the large array with values from the small array, by repeat copying the small array into the large array until it is full (so that large[0] = large[13] = large[26] ... = small[0] etc.). I already have a simple method:</p>
<pre><code>int iSource = 0;
for (int i = 0; i < destArray.Length; i++)
{
if (iSource >= sourceArray.Length)
{
iSource = 0; // reset if at end of source
}
destArray[i] = sourceArray[iSource++];
}
</code></pre>
<p>But I need something more elegant, and hopefully faster.</p>
|
[
{
"answer_id": 68556232,
"author": "Rohit",
"author_id": 6695608,
"author_profile": "https://Stackoverflow.com/users/6695608",
"pm_score": 4,
"selected": false,
"text": "dameon daemon daemon non-daemon non-daemon non-daemon daemon daemon daemon daemon daemon daemon non-daemon non-daemon daemon"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
190,049
|
<p>Given a table structure like this:</p>
<pre><code>CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(32) NOT NULL,
`username` varchar(16) NOT NULL,
`password` char(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
);
</code></pre>
<p>Is there any use in using the LIMIT keyword when searching by username, or is the DB smart enough to know that there can only possibly be one result, and therefore stop searching once it's found one?</p>
<pre><code>SELECT * FROM `user` WHERE `username` = 'nick';
-- vs --
SELECT * FROM `user` WHERE `username` = 'nick' LIMIT 1;
</code></pre>
<hr>
<p><em>Update:</em> Thanks for the answers, they've been enlightening. It seems like, even though it's unnecessary, putting <code>LIMIT 1</code> on the query doesn't hurt, and probably increases readability (you don't have to go looking into the DB schema to know that only one is going to be returned). Special shoutout for JR's answer - I didn't even know you could do that with indices.</p>
<p>Also, there's a similar question I've found <a href="https://stackoverflow.com/questions/34488/does-limiting-a-query-to-one-record-improve-performance">here</a>, which might also help.</p>
|
[
{
"answer_id": 190079,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 3,
"selected": true,
"text": "LIMIT"
},
{
"answer_id": 190081,
"author": "JR Lawhorne",
"author_id": 22917,
"author_profile": "https://Stackoverflow.com/users/22917",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE `user` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(32) NOT NULL,\n `username` varchar(16) NOT NULL,\n `password` char(32) NOT NULL,\n PRIMARY KEY (`id`),\n KEY `username` (`username`(4))\n);\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
190,054
|
<p>I've been refactoring my models and controllers in an effort to remove code duplication, and so far it seems to be all peachy creamy. Currently I've got a bit of code that is common to two of my controllers, like so:</p>
<pre><code>def process_filters
# Filter hash we're going to pass to the model
filter_to_use = {}
# To process filters, we first query the model to find out what filters
# we should be looking for, as the model knows what we can filter.
Iso.available_filters.each do |filter|
# We should have our array with our filter listing.
# Check the purchase order model for a description
filter_name = filter[0][:filter_name]
# Filters are stored in a session variable, this way filters survive
# page reloads, etc. First thing we do, is set the session if new filters
# have been set for the filter.
session_name = session_filter_name( filter_name )
if params[session_name]
if params[session_name] == 'All'
session[session_name] = nil
else
session[session_name] = params[session_name]
filter_to_use[filter_name] = params[session_name]
end
elsif session[session_name]
# If params aren't read, we still need to filter based off the users
# session
filter_to_use[filter_name] = session[session_name]
end
end
# Just using this variable for now until I can refactor the helper code
# so that this is passed in.
@current_filter_values = filter_to_use
filter_to_use[:page] = @current_page
@isos = Iso.find_filtered( filter_to_use )
if @isos.out_of_bounds?
filter_to_use[:page] = session[:previous_page] = @current_page = 1
@isos = Iso.find_filtered( filter_to_use )
end
end
</code></pre>
<p>Now this code is exactly the same as code in another controller, except for the model reference (in this case Iso). Is there someway I can make that model reference dynamic? </p>
<p>Basically I'ld like to replace the Iso references (including the @iso variable) to something based off controller.controller_name or similar.</p>
|
[
{
"answer_id": 190079,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 3,
"selected": true,
"text": "LIMIT"
},
{
"answer_id": 190081,
"author": "JR Lawhorne",
"author_id": 22917,
"author_profile": "https://Stackoverflow.com/users/22917",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE `user` (\n `id` int(10) unsigned NOT NULL auto_increment,\n `name` varchar(32) NOT NULL,\n `username` varchar(16) NOT NULL,\n `password` char(32) NOT NULL,\n PRIMARY KEY (`id`),\n KEY `username` (`username`(4))\n);\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
] |
190,059
|
<p>I'm trying to create a c++ library for use on windows/MSVC.</p>
<p>My problem is that it seems that in order to link properly, I need to distribute a bunch of different versions, linked against different versions of MSVC's c++ runtimes - single and multi-threaded, debug and release, different compiler versions, various other security and other options.</p>
<p>I'd love to just distribute maybe two, 32 bit and 64 bit.</p>
<p>My idea is to maybe use a different new operator (say, mynew) and custom allocators for all my STL types. When creating the lib, /nodefaultlib. Then, when linking in from a parent project, require them to thunk mynew to new, and my stl allocator to the standard one (or one of their choosing). I guess I'd need to do delete, and a few other functions. Naturally I'd provide an example thunking implementation with the library, but this would hopefully save everyone a lot of headache.</p>
<p>Is this possible? Has anyone ever tried this? Is there a best practices for library creation/distribution on windows/MSVC?</p>
|
[
{
"answer_id": 190074,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "std::tr1::shared_ptr msvcrt.dll msvcrt"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9042/"
] |
190,066
|
<p>Does anyone have some good information on the usage of the .SaveChanges() method?</p>
<p>I am experiencing a variety of issues when attempting to use the .SaveChanges() method on my data context object. I am taking data from an existing data source, creating the appropriate EntityFramework/DataService objects, populating those created objects with data, adding those objects to the context and then saving that data by calling .SaveChanges.</p>
<p>The scenarios I've come up with (and the problems associated with them) are as such ... In each scenario I have a foreach loop that is taking data from rows in a DataTable and generating the objects, attaching them to the context as they go. (note: three objects a "member" and two "addresses" that are attached via a SetLink call) - basically this is a conversion tool to take data from one data store and massage it into a data store that is exposed by Data Services.</p>
<ul>
<li>Call .SaveChanges() without any parameters once at the end of the foreach loop (i.e. outside the loop)
<ul>
<li>OutOfMemory error about 1/3 of the way (30,000 out of 90,000 saves) - not sure how that is happening though as each save item is a seperate SQL call to the database, what is there to run out of memory on?</li>
</ul></li>
<li>Call .SaveChanges() without any parameters once per loop
<ul>
<li>This works, but takes absolutly forever (8 hours for 90,000 saves)</li>
</ul></li>
<li>Call .SaveChanges(SaveChangesOption.Batch) once at the end of the foreach loop
<ul>
<li>Same OutOfMemory error, but without any saves to the database</li>
</ul></li>
<li>Call .SaveChanges(SaveChangesOption.Batch) once per loop
<ul>
<li>404 not found error</li>
</ul></li>
<li>Call .SaveChanges(SaveChangesOption.Batch) once per 10 loops
<ul>
<li>400 Bad Request error (occassionally)</li>
<li>OutOfMemory after a number of itterations</li>
</ul></li>
<li>A number of random attempts to create the context once per loop, or have it as a variable at the start of the loop or have it as a private member variable that is available.
<ul>
<li>Differing results, unable to quantify, none really that good</li>
</ul></li>
</ul>
<p>What is the prefered method of calling .SaveChanges() from a client object when doing a large data load like this? Is there something I'm not getting about how .SaveChanges() works? Can anyone provide more details on how once should be utilizing this function and what (if any) are the limitations to saving data via Data Services? Are there any best practices around the .SaveChanges() method call? Is there any particularly good documentation on the .SaveChanges() method call?</p>
|
[
{
"answer_id": 359658,
"author": "Maghis",
"author_id": 45355,
"author_profile": "https://Stackoverflow.com/users/45355",
"pm_score": 3,
"selected": true,
"text": "int i = 0;\nforeach (var item in collection)\n{\n // do something with your data\n if ((i++ % 10) == 0)\n context.SaveChanges();\n}\ncontext.SaveChanges();\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25719/"
] |
190,102
|
<p>I want to use data binding with an XML document to populate a simple form that shows details about a list of people. I've got it all set up and working like so right now:</p>
<pre><code><Window x:Class="DataBindingSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Window.Resources>
<XmlDataProvider x:Key="xmlProvider" XPath="People" Source="c:\someuri.xml"/>
</Window.Resources>
<Grid>
<ListBox Name="personList" ItemsSource="{Binding Source={StaticResource xmlProvider}, XPath=Person}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding XPath=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<GroupBox Header="GroupBox" Name="groupBox1" DataContext="{Binding ElementName=personList, Path=SelectedItem}">
<Grid>
<TextBox Name="nameText" Text="{Binding XPath=Name}"/>
<ComboBox Name="genderCombo" Text="{Binding XPath=Gender}">
<ComboBoxItem>Male</ComboBoxItem>
<ComboBoxItem>Female</ComboBoxItem>
</ComboBox>
</Grid>
</GroupBox>
</Grid>
</Window>
</code></pre>
<p>(All position/layout elements have been removed for clarity)</p>
<p>Now this works great! If I provide it with some XML that matches the paths provided I get a list of names in the listbox that show both the name and gender in the appropriate fields when clicked. The problem comes when I start to try and use namespaces in my XML source. The XAML then changes to look like this:</p>
<pre><code><Window x:Class="DataBindingSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Window.Resources>
<XmlNamespaceMappingCollection x:Key="namespaceMappings">
<XmlNamespaceMapping Uri="http://www.mynamespace.com" Prefix="mns"/>
</XmlNamespaceMappingCollection>
<XmlDataProvider x:Key="xmlProvider" XmlNamespaceManager="{StaticResource namespaceMappings}" XPath="mns:People" Source="c:\someuriwithnamespaces.xml"/>
</Window.Resources>
<Grid>
<ListBox Name="personList" ItemsSource="{Binding Source={StaticResource xmlProvider}, XPath=mns:Person}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding XPath=mns:Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<GroupBox Header="GroupBox" Name="groupBox1" DataContext="{Binding ElementName=personList, Path=SelectedItem}">
<Grid>
<TextBox Name="nameText" Text="{Binding XPath=mns:Name}"/>
<ComboBox Name="genderCombo" Text="{Binding XPath=mns:Gender}">
<ComboBoxItem>Male</ComboBoxItem>
<ComboBoxItem>Female</ComboBoxItem>
</ComboBox>
</Grid>
</GroupBox>
</Grid>
</Window>
</code></pre>
<p>With this code (and the appropriately namespaced xml, of course) the Listbox still displays the names properly, but clicking on those names no longer updates the Name and Gender fields! My suspicion is that somehow the xml namespace is reacting adversely to the groupbox's DataContext, but I'm not sure why or how. Does anyone know how to use XML namespaces in this context? </p>
|
[
{
"answer_id": 191467,
"author": "aogan",
"author_id": 4795,
"author_profile": "https://Stackoverflow.com/users/4795",
"pm_score": 2,
"selected": true,
"text": " <TextBox Name=\"nameText\">\n <TextBox.Text>\n <Binding XPath=\"*[local-name()='Name']\" />\n </TextBox.Text>\n </TextBox>\n"
},
{
"answer_id": 206879,
"author": "Toji",
"author_id": 25968,
"author_profile": "https://Stackoverflow.com/users/25968",
"pm_score": 2,
"selected": false,
"text": " <XmlDataProvider x:Key=\"dataProvider\"\n XmlNamespaceManager=\"{StaticResource namespaceMappings}\"\n XPath=\"p:players/p:player\">\n <x:XData>\n <p:players xmlns:p=\"http://www.footballism.com/2005/SoccerPlayers\">\n <p:player>\n <p:fullName>Sebastian Batistuta</p:fullName>\n <p:age>26</p:age>\n </p:player>\n <p:player>\n <p:fullName>Andriey Shevchenko</p:fullName>\n <p:age>30</p:age>\n </p:player>\n <p:player>\n <p:fullName>Paviel Nedved</p:fullName>\n <p:age>21</p:age>\n </p:player>\n <p:player>\n <p:fullName>David Beckham</p:fullName>\n <p:age>19</p:age>\n </p:player>\n </p:players>\n </x:XData>\n </XmlDataProvider>\n</Page.Resources>\n<StackPanel>\n <TextBlock\n Text=\"{Binding XPath=p:fullName}\"\n FontWeight=\"Bold\"\n Binding.XmlNamespaceManager=\"{StaticResource namespaceMappings}\"\n DataContext=\"{Binding ElementName=listBox, Path=SelectedItem}\"/>\n <ListBox ItemsSource=\"{Binding Source={StaticResource dataProvider}}\"\n x:Name=\"listBox\"\n DisplayMemberPath=\"p:fullName\">\n </ListBox>\n</StackPanel> </Page>\n <XmlDataProvider x:Key=\"dataProvider\"\n XmlNamespaceManager=\"{StaticResource namespaceMappings}\"\n XPath=\"p:players/p:player\">\n <x:XData>\n <p:players xmlns:p=\"http://www.footballism.com/2005/SoccerPlayers\">\n <p:player>\n <p:fullName>Sebastian Batistuta</p:fullName>\n <p:age>26</p:age>\n </p:player>\n <p:player>\n <p:fullName>Andriey Shevchenko</p:fullName>\n <p:age>30</p:age>\n </p:player>\n <p:player>\n <p:fullName>Paviel Nedved</p:fullName>\n <p:age>21</p:age>\n </p:player>\n <p:player>\n <p:fullName>David Beckham</p:fullName>\n <p:age>19</p:age>\n </p:player>\n </p:players>\n </x:XData>\n </XmlDataProvider>\n</Page.Resources>\n<StackPanel DataContext=\"{Binding Source={StaticResource dataProvider}}\">\n <TextBlock\n Text=\"{Binding XPath=p:fullName}\"\n FontWeight=\"Bold\"/>\n <ListBox ItemsSource=\"{Binding}\"\n x:Name=\"listBox\"\n DisplayMemberPath=\"p:fullName\"\n IsSynchronizedWithCurrentItem=\"True\">\n </ListBox>\n</StackPanel> </Page>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25968/"
] |
190,108
|
<p>I am having trouble grabbing the values from the form once processed. I need your help.</p>
<pre><code>function updateUser($table, $id) {
if($_POST) {
processUpdate($table, $id);
} else {
updateForm($table, $id);
}
}
function processUpdate($table, $id) {
print $table; //testing
print $id; //testing
$email=addslashes($HTTP_POST_VARS['email']);
$lname=addslashes($HTTP_POST_VARS['lname']);
$fname=addslashes($HTTP_POST_VARS['fname']);
print $lname;
//which table do we update
switch($table) {
case "maillist":
$result = mysql_query("UPDATE $table SET email='$email', lname='$lname', fname='$fname' WHERE id='$id'")
or die(mysql_error());
break;
}
}
</code></pre>
<p>The function updateForm($table, $id); just outputs the form, has email, lname, fname fields. And when you process the form, the action is the same, w/ the table and id being passed thru the URL, so it GET's the id and table that way, and for lname, fname, and email, it should grab it via post.</p>
<p>EDIT: this is what the form tag is for the updateForm function: <code><form method="post" action="?mode=upd&id='.$id.'&table='.$table.'"></code></p>
<p>But for some reason, it does not post the values.</p>
|
[
{
"answer_id": 190120,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<form method = \"post\" action = \"...\">\n $_POST $HTTP_POST_VARS"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
190,135
|
<p>I need to generate random numbers in the range 1 - 10000 continuously with out duplication.
Any recommendations?</p>
<p>Description: we are building a new version for our application, which maintains records in Sqlite DB. in the last version of our application, we did not had unique key for each record. But now with new upgraded version, we need to support the import facility from the last version's DB. So what we do is, we read each and every record from the old DB and generate a random number for the unique key and store it in new DB. Here we many need to import up to 10000 records continuously.</p>
|
[
{
"answer_id": 190182,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n\nclass GaranteedNoRepeatRandom\n{\n public:\n GaranteedNoRepeatRandom(int limit)\n :data(limit)\n ,index(0)\n {\n for(int loop=0;loop < limit;++loop)\n { data[loop] = loop;\n }\n // Note: random_shuffle optionally takes a third parameter\n // as the rand number generator.\n std::random_shuffle(&data[0],&data[0]+limit);\n }\n\n unsigned int rand()\n {\n unsigned int result = data[index];\n index = (index+1) % data.size();\n\n // Add code to re-shuffle after index wraps around\n return result;\n }\n private:\n std::vector<unsigned int> data;\n std::vector<unsigned int>::size_type index;\n};\n\nint main()\n{\n GaranteedNoRepeatRandom gen(10000);\n\n for(int loop =0;loop < 10;++loop)\n {\n std::cout << gen.rand() << \"\\n\";\n }\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21045/"
] |
190,138
|
<p>I want to create a collection in VB.NET, but I only want it to accept objects of a certain type. For example, I want to create a class called "FooCollection" that acts like a collection in every way, but only accepts objects of type "Foo".</p>
<p>I thought I could do this using generics, using the following syntax:</p>
<pre><code> Public Class FooCollection(Of type As Foo)
Inherits CollectionBase
...
End Class
</code></pre>
<p>But I get an error when I compile it that I "must implement a default accessor", so clearly there's something missing. I don't want to specify the type it accepts when I instantiate - I want the FooCollection itself to specific that it only accepts Foo objects. I've seen it done in C# with a strong-typed list, so maybe all I'm looking for is VB.NET syntax.</p>
<p>Thanks for your help!</p>
<p><strong>EDIT: Thanks for the answer. That would do it, but I wanted to have the classtype named a certain way, I actually accomplished exactly what I was looking for with the following code:</strong></p>
<pre><code>Public Class FooCollection
Inherits List(Of Foo)
End Class
</code></pre>
|
[
{
"answer_id": 190153,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 4,
"selected": true,
"text": "List(Of Foo) System.Collections.Generic Private myList As New List(Of Foo) 'Creates a Foo List'\nPrivate myIntList As New List(Of Integer) 'Creates an Integer List'\n MSDN > List(T) Class (System.Collections.Generic)"
},
{
"answer_id": 2269794,
"author": "Jeff Cope",
"author_id": 273952,
"author_profile": "https://Stackoverflow.com/users/273952",
"pm_score": 1,
"selected": false,
"text": "Default Public Property Item(ByVal Index As Integer) As Foo\nGet\n Return CType(List.Item(Index), Foo)\nEnd Get\nSet(ByVal Value As Foo)\n List.Item(Index) = Value\nEnd Set\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8114/"
] |
190,145
|
<p>I know it's a long shot, but is there some package or means to insert emoticons into a LaTeX document?</p>
|
[
{
"answer_id": 190195,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 3,
"selected": false,
"text": "0x2639 0x263B 0x2686 0x2689"
},
{
"answer_id": 190321,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 6,
"selected": true,
"text": "$\\ddot\\smile$\n \\usepackage{wasysym}\n\\smiley\n\\frownie\n"
},
{
"answer_id": 33983439,
"author": "Martin Ueding",
"author_id": 653152,
"author_profile": "https://Stackoverflow.com/users/653152",
"pm_score": 2,
"selected": false,
"text": "tikzsymbols"
},
{
"answer_id": 57076064,
"author": "Ryutaroh Matsumoto",
"author_id": 11797631,
"author_profile": "https://Stackoverflow.com/users/11797631",
"pm_score": 4,
"selected": false,
"text": "xelatex lualatex \\documentclass{article}\n\\usepackage{fontspec}\n\\setmainfont{Symbola}\n\\begin{document}\n\n \n\\end{document}\n \\fontspec{Segoe UI Emoji}[RawFeature={ccmp,dist}] \\fontspec{Symbola} harflatex luahblatex \\documentclass{minimal}\n\\usepackage{harfload}\n\\usepackage{fontspec}\n\n\\begin{document}\n\\noindent\n\\fontspec{Noto Color Emoji}[RawFeature={mode=harf}]\n☃⛄\\quad ❤️\n\\end{document}\n harflatex luahblatex"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] |
190,160
|
<p>I am currently developing a Rails application using a database that was designed before I was aware of Rails existence.<br>
I have currently created some migrations to add some new tables and new columns to existing tables.</p>
<p>I would like to have the migrations to recreate the full database.</p>
<p>Which steps should I follow?<br>
Should I create all the migrations by hand?</p>
<p>EDIT: I am interested in the database schema not in the database contents</p>
|
[
{
"answer_id": 192585,
"author": "Thomas Brice",
"author_id": 8179,
"author_profile": "https://Stackoverflow.com/users/8179",
"pm_score": 3,
"selected": true,
"text": "rake db:schema:dump db/schema.rb db/schema.rb RAILS_ENV=production rake db:schema:dump schema.rb"
},
{
"answer_id": 193117,
"author": "scottd",
"author_id": 5935,
"author_profile": "https://Stackoverflow.com/users/5935",
"pm_score": 3,
"selected": false,
"text": "class CreateTables < ActiveRecord::Migration\n def self.up\n `cp #{Rails.root}/db/schema_base.rb #{Rails.root}/db/schema.rb`\n Rake::Task['db:schema:load'].invoke\n end\n\n def self.down\n end\nend\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14755/"
] |
190,168
|
<p>I am trying to set my DOS environment variable in Ruby, and have it persist after the script exits. For example, if I want a ruby script <code>set_abc_env.rb</code> to set environment variable 'ABC' to 'blah', I expect to run the following:</p>
<pre><code>C:> echo %ABC%
C:> set_abc_env.rb
C:> echo %ABC% blah
</code></pre>
<p>How do I do this?</p>
|
[
{
"answer_id": 190437,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 6,
"selected": true,
"text": "i = ENV['ABC']; # nil\nENV['ABC'] = '123';\ni = ENV['ABC']; # '123'\n require 'win32/registry.rb'\n\nWin32::Registry::HKEY_CURRENT_USER.open('Environment', Win32::Registry::KEY_WRITE) do |reg|\n reg['ABC'] = '123'\nend\n require 'Win32API' \n\nSendMessageTimeout = Win32API.new('user32', 'SendMessageTimeout', 'LLLPLLP', 'L') \nHWND_BROADCAST = 0xffff\nWM_SETTINGCHANGE = 0x001A\nSMTO_ABORTIFHUNG = 2\nresult = 0\nSendMessageTimeout.call(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 'Environment', SMTO_ABORTIFHUNG, 5000, result) \n"
},
{
"answer_id": 5492321,
"author": "konung",
"author_id": 198424,
"author_profile": "https://Stackoverflow.com/users/198424",
"pm_score": 1,
"selected": false,
"text": "def switch_ruby_env\n if RUBY_VERSION.match(\"1.8.7\").nil? \n `setenv -m CUSTOM_PATH \" \"`\n else\n `setenv -m CUSTOM_PATH -delete`\n end\nend \n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24560/"
] |
190,184
|
<p>I often use the <code>execv()</code> function in C++, but if some of the arguments are in C++ strings, it annoys me that I cannot do this:</p>
<pre><code>const char *args[4];
args[0] = "/usr/bin/whatever";
args[1] = filename.c_str();
args[2] = someparameter.c_str();
args[3] = 0;
execv(args[0], args);
</code></pre>
<p>This doesn't compile because <code>execv()</code> takes <code>char *const argv[]</code> which is not compatible with <code>const char *</code>, so I have to copy my <code>std::string</code>s to character arrays using <code>strdup()</code>, which is a pain.</p>
<p>Does anyone know the reason for this?</p>
|
[
{
"answer_id": 190208,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 6,
"selected": true,
"text": "const_cast c_str() argv[] envp[] const argv[] envp[]"
},
{
"answer_id": 5433327,
"author": "Tomi",
"author_id": 676834,
"author_profile": "https://Stackoverflow.com/users/676834",
"pm_score": -1,
"selected": false,
"text": "#define execve xexecve\n#include <...>\n#include <...>\n#include <...>\n#undef execve\n\n// in case of c++\nextern \"C\" {\n int execve(const char * filename, char ** argvs, char * const * envp);\n}\n"
},
{
"answer_id": 29501925,
"author": "cmccabe",
"author_id": 560814,
"author_profile": "https://Stackoverflow.com/users/560814",
"pm_score": 1,
"selected": false,
"text": "const char * const args[] = {\n \"/usr/bin/whatever\",\n filename.c_str(),\n someparameter.c_str(),\n 0};\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
] |
190,194
|
<p>How do you create a database backup of a mysql database in VB.Net? </p>
|
[
{
"answer_id": 256271,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 1,
"selected": false,
"text": "mysqldump --host=[HOSTNAME] --user=[USER] --password=[PASSWORD] -R [DATABASE NAME] > [PATH TO BACKUP FILE]\n mysql --host=[HOSTNAME] --user=[USER] --password=[PASSWORD] [DATABASE NAME] < [PATH TO BACKUP FILE]\n"
},
{
"answer_id": 14009385,
"author": "mjb",
"author_id": 520848,
"author_profile": "https://Stackoverflow.com/users/520848",
"pm_score": 3,
"selected": false,
"text": "Dim conn As MySqlConnection = New MySqlConnection(constr)\nDim cmd As MySqlCommand = New MySqlCommand\ncmd.Connection = conn\nconn.Open\nDim mb As MySqlBackup = New MySqlBackup(cmd)\nmb.ExportToFile(\"C:\\backup.sql\")\nconn.Close\n Dim conn As MySqlConnection = New MySqlConnection(constr)\nDim cmd As MySqlCommand = New MySqlCommand\ncmd.Connection = conn\nconn.Open\nDim mb As MySqlBackup = New MySqlBackup(cmd)\nmb.ImportFromFile(\"C:\\backup.sql\")\nconn.Close\n"
},
{
"answer_id": 14957354,
"author": "Allan Empalmado",
"author_id": 1119553,
"author_profile": "https://Stackoverflow.com/users/1119553",
"pm_score": 0,
"selected": false,
"text": " Using myProcess As New Process()\n Dim newfiledb As String = BACKUPDIR_PATH & Format(Now(), \"MMM_dd_yyyy@h~mm_tt\").ToString & \"_local.sql\"\n Try\n myProcess.StartInfo.FileName = \"mysqldump.exe\"\n myProcess.StartInfo.WorkingDirectory = LIB_PATH\n myProcess.StartInfo.Arguments = \"--host=localhost --user=username --password=yourpassword yourdatabase -r \" & newfiledb\n myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden\n myProcess.Start()\n myProcess.WaitForExit()\n MsgBox(\"Backup Created ... \" & vbNewLine & newfiledb)\n Catch ex As Exception\n MsgBox(ex.Message, vbCritical + vbOKOnly, ex.Message)\n Finally\n myProcess.Close()\n End Try\n End Using\n"
},
{
"answer_id": 29105049,
"author": "GGSoft",
"author_id": 3326849,
"author_profile": "https://Stackoverflow.com/users/3326849",
"pm_score": 2,
"selected": false,
"text": "Imports System.Text\nPublic Class Form1\n Dim OutputStream As System.IO.StreamWriter\n Sub OnDataReceived1(ByVal Sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs)\n If e.Data IsNot Nothing Then\n Dim text As String = e.Data\n Dim bytes As Byte() = Encoding.Default.GetBytes(text)\n text = Encoding.UTF8.GetString(bytes)\n OutputStream.WriteLine(text)\n End If\n End Sub\n\n Sub CreateBackup()\n Dim mysqldumpPath As String = \"d:\\mysqldump.exe\"\n Dim host As String = \"localhost\"\n Dim user As String = \"root\"\n Dim pswd As String = \"Yourpwd\"\n Dim dbnm As String = \"BaseName\"\n Dim cmd As String = String.Format(\"-h{0} -u{1} -p{2} {3}\", host, user, pswd, dbnm)\n Dim filePath As String = \"d:\\backup\\fieName.sql\"\n OutputStream = New System.IO.StreamWriter(filePath, False, System.Text.Encoding.UTF8)\n\n Dim startInfo As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo()\n startInfo.FileName = mysqldumpPath\n startInfo.Arguments = cmd\n\n startInfo.RedirectStandardError = True\n startInfo.RedirectStandardInput = False\n startInfo.RedirectStandardOutput = True \n startInfo.UseShellExecute = False\n startInfo.CreateNoWindow = True\n startInfo.ErrorDialog = False\n\n Dim proc As System.Diagnostics.Process = New System.Diagnostics.Process()\n proc.StartInfo = startInfo\n AddHandler proc.OutputDataReceived, AddressOf OnDataReceived1\n proc.Start()\n proc.BeginOutputReadLine()\n proc.WaitForExit()\n\n OutputStream.Flush()\n OutputStream.Close()\n proc.Close()\n End Sub\n\n Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n\n CreateBackup()\n\n End Sub\n End Class\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25078/"
] |
190,198
|
<p>I am trying to generate equivalent MD5 hashes in both JavaScript and .Net. Not having done either, I decided to use against a third party calculation - this <a href="http://www.johnmaguire.us/tools/hashcalc/index.php?strtohash=password&mode=hash" rel="nofollow noreferrer">web site</a> for the word "password". I will add in salts later, but at the moment, I can't get the .net version to match up with the web site's hash:</p>
<pre><code>5f4dcc3b5aa765d61d8327deb882cf99
</code></pre>
<p>I'm guessing it is an encoding problem, but I've tried about 8 different variations of methods for calculating an MD5 hash in .Net, and none of them match what I have obtained in JavaScript (or from the web site). This <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx" rel="nofollow noreferrer">MSDN example</a> is one of the methods I have tried, which results in this hash which i have commonly received: </p>
<pre><code>7c6a180b36896a0a8c02787eeafb0e4c
</code></pre>
<p>Edit: Sadly, I've accidentally been providing different source strings to the two different implementations. EBSAK. :-/ Still be interested to hear your answer to the follow-up.</p>
<p>Bonus question: what encoding/format would be best to store hashed values in a database?</p>
|
[
{
"answer_id": 190206,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "$ echo -n password | md5\n5f4dcc3b5aa765d61d8327deb882cf99\n"
},
{
"answer_id": 190210,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "Private Function MD5Hash(ByVal str As String) As String\n\n Dim md5 As MD5 = MD5CryptoServiceProvider.Create\n Dim hashed As Byte() = md5.ComputeHash(Encoding.Default.GetBytes(str))\n Dim sb As New StringBuilder\n\n For i As Integer = 0 To hashed.Length - 1\n sb.AppendFormat(\"{0:x2}\", hashed(i))\n Next\n\n Return sb.ToString\n\nEnd Function\n"
},
{
"answer_id": 190214,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Gets the Base 64 encoded SHA1 hashed password\n/// </summary>\n/// <returns>A Base 64 encoded string representing the SHA1 Hash of the password</returns>\npublic string ToBase64SHA1String()\n{\n return Convert.ToBase64String(this.GetSHA1HashCode());\n\n}\n"
},
{
"answer_id": 190226,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 4,
"selected": true,
"text": " // Hash an input string and return the hash as\n // a 32 character hexadecimal string.\n static string getMd5Hash(string input)\n {\n // Create a new instance of the MD5CryptoServiceProvider object.\n MD5 md5Hasher = MD5.Create();\n\n // Convert the input string to a byte array and compute the hash.\n byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));\n\n // Create a new Stringbuilder to collect the bytes\n // and create a string.\n StringBuilder sBuilder = new StringBuilder();\n\n // Loop through each byte of the hashed data \n // and format each one as a hexadecimal string.\n for (int i = 0; i < data.Length; i++)\n {\n sBuilder.Append(data[i].ToString(\"x2\"));\n }\n\n // Return the hexadecimal string.\n return sBuilder.ToString();\n }\n\n\n static void Main(string[] args)\n {\n System.Console.WriteLine(getMd5Hash(\"password\"));\n }\n 5f4dcc3b5aa765d61d8327deb882cf99\n"
},
{
"answer_id": 7237431,
"author": "sharkswithlasers",
"author_id": 918760,
"author_profile": "https://Stackoverflow.com/users/918760",
"pm_score": 2,
"selected": false,
"text": "password1 password password password1 7c6a180b36896a0a8c02787eeafb0e4c\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525/"
] |
190,224
|
<p>I've made some unit tests (in test class). The tutorial I've read said that I should make a TestSuite for the unittests.</p>
<p>Odd is that when I'm running the unit test directly (selecting the test class - Run as jUnit test) everything is working fine, altough when I'm trying the same thing with the test suite there's always an exception: java.lang.Exception: No runnable methods.</p>
<p>Here is the code of the test suite:</p>
<pre><code>import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test suite for com.xxx.yyyy.test");
//$JUnit-BEGIN$
suite.addTestSuite(TestCase.class);
//$JUnit-END$
return suite;
}
}
</code></pre>
<p>Any ideas why this isn't working ?</p>
|
[
{
"answer_id": 190347,
"author": "bernhardrusch",
"author_id": 3056,
"author_profile": "https://Stackoverflow.com/users/3056",
"pm_score": 4,
"selected": true,
"text": "import org.junit.runner.RunWith;\nimport org.junit.runners.Suite;\nimport org.junit.runners.Suite.SuiteClasses;\n\n\n@RunWith(value=Suite.class)\n@SuiteClasses(value={TestCase.class})\npublic class AllTests {\n\n}\n import static org.junit.Assert.assertTrue;\nimport org.junit.Test;\n\npublic class TestCase {\n@Test\n public void test1 {\n assertTrue (tmp.getTermin().equals(soll));\n }\n}\n"
},
{
"answer_id": 49088825,
"author": "AmiNadimi",
"author_id": 4192897,
"author_profile": "https://Stackoverflow.com/users/4192897",
"pm_score": 2,
"selected": false,
"text": "@Test import org.junit.Test import org.testng.annotations.Test org.junit.jupiter.api.Test"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3056/"
] |
190,227
|
<p>Assume my objects are in perfect working order (i.e. TDD makes me think they work).</p>
<p>I have a list that I create like this (except indented properly):</p>
<pre><code>var result = from v in vendors
from p in v.Products
orderby p.Name
select p;
</code></pre>
<p>This works - I get all products from all vendors.</p>
<p>Now I have a list of conditions, built up at runtime by the user. Let's apply them:</p>
<pre><code>foreach (Attribute a in requiredAttributes)
{
result = result.Where(p => p.Attributes.Contains(a));
}
</code></pre>
<p>This may be primitive, but I thought it'd work. However, after this foreach loop is finished, when you enumerate "result" it will contain all products that has the LAST Attribute of the requiredAttributes collection in it's Attributes property (also a collection).</p>
<p>To me, this smells like "a" is overwritten somewhere with each trip trough the loop, and only the last one applies.</p>
<p>Short of somehow writing an extension method to IEnumerable called ContainsAll(IEnumerable) or something to that effect, how can I achieve what I want, which is basically a logical AND, giving me only those products that has ALL the required attributes?</p>
|
[
{
"answer_id": 190234,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 3,
"selected": false,
"text": "var result = from v in vendors\n from p in v.Products\n where requiredAttributes.All(a => p.Attributes.Contains(a))\n orderby p.Name\n select p;\n"
},
{
"answer_id": 190254,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "foreach (Attribute a in requiredAttributes)\n{\n Attribute copy = a;\n result = result.Where(p => p.Attributes.Contains(copy));\n}\n"
},
{
"answer_id": 190260,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 3,
"selected": false,
"text": "foreach (Attribute a in requiredAttributes){ \n result = result.Where(p => p.Attributes.Contains(a));\n}\n foreach (Attribute a in requiredAttributes){ \n Attribute b = a;\n result = result.Where(p => p.Attributes.Contains(b));\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2122/"
] |
190,229
|
<p><code>itoa()</code> is a really handy function to convert a number to a string. Linux does not seem to have <code>itoa()</code>, is there an equivalent function or do I have to use <code>sprintf(str, "%d", num)</code>?</p>
|
[
{
"answer_id": 190235,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 8,
"selected": true,
"text": "libc itoa() sprintf(target_string,\"%d\",source_int) snprintf(target_string, size_of_target_string_in_bytes, \"%d\", source_int) itoa() gcc libc itoa() #include <stdlib.h>\n itoa() /* itoa example */\n#include <stdio.h>\n#include <stdlib.h>\n\nint main ()\n{\n int i;\n char buffer [33];\n printf (\"Enter a number: \");\n scanf (\"%d\",&i);\n itoa (i,buffer,10);\n printf (\"decimal: %s\\n\",buffer);\n itoa (i,buffer,16);\n printf (\"hexadecimal: %s\\n\",buffer);\n itoa (i,buffer,2);\n printf (\"binary: %s\\n\",buffer);\n return 0;\n}\n Enter a number: 1750\ndecimal: 1750\nhexadecimal: 6d6\nbinary: 11011010110\n"
},
{
"answer_id": 190250,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "itoa snprintf"
},
{
"answer_id": 192700,
"author": "James Antill",
"author_id": 10314,
"author_profile": "https://Stackoverflow.com/users/10314",
"pm_score": 4,
"selected": false,
"text": "const char *my_itoa_buf(char *buf, size_t len, int num)\n{\n static char loc_buf[sizeof(int) * CHAR_BITS]; /* not thread safe */\n\n if (!buf)\n {\n buf = loc_buf;\n len = sizeof(loc_buf);\n }\n\n if (snprintf(buf, len, \"%d\", num) == -1)\n return \"\"; /* or whatever */\n\n return buf;\n}\n\nconst char *my_itoa(int num)\n{ return my_itoa_buf(NULL, 0, num); }\n"
},
{
"answer_id": 12085310,
"author": "Archana Chatterjee",
"author_id": 1618752,
"author_profile": "https://Stackoverflow.com/users/1618752",
"pm_score": -1,
"selected": false,
"text": "void itochar(int x, char *buffer, int radix);\n\nint main()\n{\n char buffer[10];\n itochar(725, buffer, 10);\n printf (\"\\n %s \\n\", buffer);\n return 0;\n}\n\nvoid itochar(int x, char *buffer, int radix)\n{\n int i = 0 , n,s;\n n = s;\n while (n > 0)\n {\n s = n%radix;\n n = n/radix;\n buffer[i++] = '0' + s;\n }\n buffer[i] = '\\0';\n strrev(buffer);\n}\n"
},
{
"answer_id": 13361077,
"author": "mmdemirbas",
"author_id": 471214,
"author_profile": "https://Stackoverflow.com/users/471214",
"pm_score": 3,
"selected": false,
"text": "sprintf char *itoa(long n)\n{\n int len = n==0 ? 1 : floor(log10l(labs(n)))+1;\n if (n<0) len++; // room for negative sign '-'\n\n char *buf = calloc(sizeof(char), len+1); // +1 for null\n snprintf(buf, len+1, \"%ld\", n);\n return buf;\n}\n free char *num_str = itoa(123456789L);\n// ... \nfree(num_str);\n"
},
{
"answer_id": 13388063,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": false,
"text": "std::to_string itoa std::string itos(int n)\n{\n const int max_size = std::numeric_limits<int>::digits10 + 1 /*sign*/ + 1 /*0-terminator*/;\n char buffer[max_size] = {0};\n sprintf(buffer, \"%d\", n);\n return std::string(buffer);\n}\n snprintf sprintf"
},
{
"answer_id": 14394283,
"author": "the sudhakar",
"author_id": 1989534,
"author_profile": "https://Stackoverflow.com/users/1989534",
"pm_score": 2,
"selected": false,
"text": " char* itoah(long num, char* s, int len)\n {\n long n, m = 16;\n int i = 16+2;\n int shift = 'a'- ('9'+1);\n\n\n if(!s || len < 1)\n return 0;\n\n n = num < 0 ? -1 : 1;\n n = n * num;\n\n len = len > i ? i : len;\n i = len < i ? len : i;\n\n s[i-1] = 0;\n i--;\n\n if(!num)\n {\n if(len < 2)\n return &s[i];\n\n s[i-1]='0';\n return &s[i-1];\n }\n\n while(i && n)\n {\n s[i-1] = n % m + '0';\n\n if (s[i-1] > '9')\n s[i-1] += shift ;\n\n n = n/m;\n i--;\n }\n\n if(num < 0)\n {\n if(i)\n {\n s[i-1] = '-';\n i--;\n }\n }\n\n return &s[i];\n }\n"
},
{
"answer_id": 16042640,
"author": "Chris Desjardins",
"author_id": 1602642,
"author_profile": "https://Stackoverflow.com/users/1602642",
"pm_score": 2,
"selected": false,
"text": "static char _numberSystem[] = \"0123456789ABCDEF\";\nstatic char _twosComp[] = \"FEDCBA9876543210\";\n\nstatic void safestrrev(char *buffer, const int bufferSize, const int strlen)\n{\n int len = strlen;\n if (len > bufferSize)\n {\n len = bufferSize;\n }\n for (int index = 0; index < (len / 2); index++)\n {\n char ch = buffer[index];\n buffer[index] = buffer[len - index - 1];\n buffer[len - index - 1] = ch;\n }\n}\n\nstatic int negateBuffer(char *buffer, const int bufferSize, const int strlen, const int radix)\n{\n int len = strlen;\n if (len > bufferSize)\n {\n len = bufferSize;\n }\n if (radix == 10)\n {\n if (len < (bufferSize - 1))\n {\n buffer[len++] = '-';\n buffer[len] = '\\0';\n }\n }\n else\n {\n int twosCompIndex = 0;\n for (int index = 0; index < len; index++)\n {\n if ((buffer[index] >= '0') && (buffer[index] <= '9'))\n {\n twosCompIndex = buffer[index] - '0';\n }\n else if ((buffer[index] >= 'A') && (buffer[index] <= 'F'))\n {\n twosCompIndex = buffer[index] - 'A' + 10;\n }\n else if ((buffer[index] >= 'a') && (buffer[index] <= 'f'))\n {\n twosCompIndex = buffer[index] - 'a' + 10;\n }\n twosCompIndex += (16 - radix);\n buffer[index] = _twosComp[twosCompIndex];\n }\n if (len < (bufferSize - 1))\n {\n buffer[len++] = _numberSystem[radix - 1];\n buffer[len] = 0;\n }\n }\n return len;\n}\n\nstatic int twosNegation(const int x, const int radix)\n{\n int n = x;\n if (x < 0)\n {\n if (radix == 10)\n {\n n = -x;\n }\n else\n {\n n = ~x;\n }\n }\n return n;\n}\n\nstatic char *safeitoa(const int x, char *buffer, const int bufferSize, const int radix)\n{\n int strlen = 0;\n int n = twosNegation(x, radix);\n int nuberSystemIndex = 0;\n\n if (radix <= 16)\n {\n do\n {\n if (strlen < (bufferSize - 1))\n {\n nuberSystemIndex = (n % radix);\n buffer[strlen++] = _numberSystem[nuberSystemIndex];\n buffer[strlen] = '\\0';\n n = n / radix;\n }\n else\n {\n break;\n }\n } while (n != 0);\n if (x < 0)\n {\n strlen = negateBuffer(buffer, bufferSize, strlen, radix);\n }\n safestrrev(buffer, bufferSize, strlen);\n return buffer;\n }\n return NULL;\n}\n"
},
{
"answer_id": 16095691,
"author": "waaagh",
"author_id": 1610731,
"author_profile": "https://Stackoverflow.com/users/1610731",
"pm_score": 2,
"selected": false,
"text": "#define INT_LEN (10)\n#define HEX_LEN (8)\n#define BIN_LEN (32)\n#define OCT_LEN (11)\n\nstatic char * my_itoa ( int value, char * str, int base )\n{\n int i,n =2,tmp;\n char buf[BIN_LEN+1];\n\n\n switch(base)\n {\n case 16:\n for(i = 0;i<HEX_LEN;++i)\n {\n if(value/base>0)\n {\n n++;\n }\n }\n snprintf(str, n, \"%x\" ,value);\n break;\n case 10:\n for(i = 0;i<INT_LEN;++i)\n {\n if(value/base>0)\n {\n n++;\n }\n }\n snprintf(str, n, \"%d\" ,value);\n break;\n case 8:\n for(i = 0;i<OCT_LEN;++i)\n {\n if(value/base>0)\n {\n n++;\n }\n }\n snprintf(str, n, \"%o\" ,value);\n break;\n case 2:\n for(i = 0,tmp = value;i<BIN_LEN;++i)\n {\n if(tmp/base>0)\n {\n n++;\n }\n tmp/=base;\n }\n for(i = 1 ,tmp = value; i<n;++i)\n {\n if(tmp%2 != 0)\n {\n buf[n-i-1] ='1';\n }\n else\n {\n buf[n-i-1] ='0';\n }\n tmp/=base;\n }\n buf[n-1] = '\\0';\n strcpy(str,buf);\n break;\n default:\n return NULL;\n }\n return str;\n}\n"
},
{
"answer_id": 21168986,
"author": "Andres Romero",
"author_id": 1126085,
"author_profile": "https://Stackoverflow.com/users/1126085",
"pm_score": 2,
"selected": false,
"text": "void binary(unsigned int n)\n{\n for(int shift=sizeof(int)*8-1;shift>=0;shift--)\n {\n if (n >> shift & 1)\n printf(\"1\");\n else\n printf(\"0\");\n\n }\n printf(\"\\n\");\n} \n"
},
{
"answer_id": 29544416,
"author": "haccks",
"author_id": 2455888,
"author_profile": "https://Stackoverflow.com/users/2455888",
"pm_score": 5,
"selected": false,
"text": "itoa itoa /* itoa: convert n to characters in s */\n void itoa(int n, char s[])\n {\n int i, sign;\n\n if ((sign = n) < 0) /* record sign */\n n = -n; /* make n positive */\n i = 0;\n do { /* generate digits in reverse order */\n s[i++] = n % 10 + '0'; /* get next digit */\n } while ((n /= 10) > 0); /* delete it */\n if (sign < 0)\n s[i++] = '-';\n s[i] = '\\0';\n reverse(s);\n} \n reverse #include <string.h>\n\n /* reverse: reverse string s in place */\n void reverse(char s[])\n {\n int i, j;\n char c;\n\n for (i = 0, j = strlen(s)-1; i<j; i++, j--) {\n c = s[i];\n s[i] = s[j];\n s[j] = c;\n }\n} \n"
},
{
"answer_id": 29544825,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": false,
"text": "itoa() char *itoa(int value, char *str, int base); INT_MIN NULL NULL #include <stdlib.h>\n#include <limits.h>\n#include <string.h>\n\n// Buffer sized for a decimal string of a `signed int`, 28/93 > log10(2)\n#define SIGNED_PRINT_SIZE(object) ((sizeof(object) * CHAR_BIT - 1)* 28 / 93 + 3)\n\nchar *itoa_x(int number, char *dest, size_t dest_size) {\n if (dest == NULL) {\n return NULL;\n }\n\n char buf[SIGNED_PRINT_SIZE(number)];\n char *p = &buf[sizeof buf - 1];\n\n // Work with negative absolute value\n int neg_num = number < 0 ? number : -number;\n\n // Form string\n *p = '\\0';\n do {\n *--p = (char) ('0' - neg_num % 10);\n neg_num /= 10;\n } while (neg_num);\n if (number < 0) {\n *--p = '-';\n }\n\n // Copy string\n size_t src_size = (size_t) (&buf[sizeof buf] - p);\n if (src_size > dest_size) {\n // Not enough room\n return NULL;\n }\n return memcpy(dest, p, src_size);\n}\n char *itoa_x(int number, char *dest, size_t dest_size, int base) {\n if (dest == NULL || base < 2 || base > 36) {\n return NULL;\n }\n\n char buf[sizeof number * CHAR_BIT + 2]; // worst case: itoa(INT_MIN,,,2)\n char *p = &buf[sizeof buf - 1];\n\n // Work with negative absolute value to avoid UB of `abs(INT_MIN)`\n int neg_num = number < 0 ? number : -number;\n\n // Form string\n *p = '\\0';\n do {\n *--p = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"[-(neg_num % base)];\n neg_num /= base;\n } while (neg_num);\n if (number < 0) {\n *--p = '-';\n }\n\n // Copy string\n size_t src_size = (size_t) (&buf[sizeof buf] - p);\n if (src_size > dest_size) {\n // Not enough room\n return NULL;\n }\n return memcpy(dest, p, src_size);\n}\n div_t qr;\n do {\n qr = div(neg_num, base);\n *--p = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"[-qr.rem];\n neg_num = qr.quot;\n } while (neg_num);\n"
},
{
"answer_id": 36391225,
"author": "Vlatko Šurlan",
"author_id": 2924916,
"author_profile": "https://Stackoverflow.com/users/2924916",
"pm_score": 2,
"selected": false,
"text": "char *\nint2str(long int val, char *dst, int radix, \n int upcase)\n{\n char buffer[65];\n char *p;\n long int new_val;\n char *dig_vec= upcase ? _dig_vec_upper : _dig_vec_lower;\n ulong uval= (ulong) val;\n\n if (radix < 0)\n {\n if (radix < -36 || radix > -2)\n return NullS;\n if (val < 0)\n {\n *dst++ = '-';\n /* Avoid integer overflow in (-val) for LLONG_MIN (BUG#31799). */\n uval = (ulong)0 - uval;\n }\n radix = -radix;\n }\n else if (radix > 36 || radix < 2)\n return NullS;\n\n /*\n The slightly contorted code which follows is due to the fact that\n few machines directly support unsigned long / and %. Certainly\n the VAX C compiler generates a subroutine call. In the interests\n of efficiency (hollow laugh) I let this happen for the first digit\n only; after that \"val\" will be in range so that signed integer\n division will do. Sorry 'bout that. CHECK THE CODE PRODUCED BY\n YOUR C COMPILER. The first % and / should be unsigned, the second\n % and / signed, but C compilers tend to be extraordinarily\n sensitive to minor details of style. This works on a VAX, that's\n all I claim for it.\n */\n p = &buffer[sizeof(buffer)-1];\n *p = '\\0';\n new_val= uval / (ulong) radix;\n *--p = dig_vec[(uchar) (uval- (ulong) new_val*(ulong) radix)];\n val = new_val;\n while (val != 0)\n {\n ldiv_t res;\n res=ldiv(val,radix);\n *--p = dig_vec[res.rem];\n val= res.quot;\n }\n while ((*dst++ = *p++) != 0) ;\n return dst-1;\n}\n"
},
{
"answer_id": 46732059,
"author": "rick-rick-rick",
"author_id": 8741673,
"author_profile": "https://Stackoverflow.com/users/8741673",
"pm_score": 3,
"selected": false,
"text": "/*\n=============\nitoa\n\nConvert integer to string\n\nPARAMS:\n- value A 64-bit number to convert\n- str Destination buffer; should be 66 characters long for radix2, 24 - radix8, 22 - radix10, 18 - radix16.\n- radix Radix must be in range -36 .. 36. Negative values used for signed numbers.\n=============\n*/\n\nchar* itoa (unsigned long long value, char str[], int radix)\n{\n char buf [66];\n char* dest = buf + sizeof(buf);\n boolean sign = false;\n\n if (value == 0) {\n memcpy (str, \"0\", 2);\n return str;\n }\n\n if (radix < 0) {\n radix = -radix;\n if ( (long long) value < 0) {\n value = -value;\n sign = true;\n }\n }\n\n *--dest = '\\0';\n\n switch (radix)\n {\n case 16:\n while (value) {\n * --dest = '0' + (value & 0xF);\n if (*dest > '9') *dest += 'A' - '9' - 1;\n value >>= 4;\n }\n break;\n case 10:\n while (value) {\n *--dest = '0' + (value % 10);\n value /= 10;\n }\n break;\n\n case 8:\n while (value) {\n *--dest = '0' + (value & 7);\n value >>= 3;\n }\n break;\n\n case 2:\n while (value) {\n *--dest = '0' + (value & 1);\n value >>= 1;\n }\n break;\n\n default: // The slow version, but universal\n while (value) {\n *--dest = '0' + (value % radix);\n if (*dest > '9') *dest += 'A' - '9' - 1;\n value /= radix;\n }\n break;\n }\n\n if (sign) *--dest = '-';\n\n memcpy (str, dest, buf +sizeof(buf) - dest);\n return str;\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
] |
190,232
|
<pre><code>inline int factorial(int n)
{
if(!n) return 1;
else return n*factorial(n-1);
}
</code></pre>
<p>As I was reading <a href="https://rads.stackoverflow.com/amzn/click/com/0201543303" rel="noreferrer" rel="nofollow noreferrer">this</a>, found that the above code would lead to "infinite compilation" if not handled by compiler correctly.</p>
<p>How does the compiler decide whether to inline a function or not ?</p>
|
[
{
"answer_id": 190256,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 5,
"selected": false,
"text": "inline #pragma --max-inline-insns-recursive"
},
{
"answer_id": 190268,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 8,
"selected": true,
"text": "inline inline inline int factorial(int n)\n{\n if (n <= 1)\n {\n return 1;\n }\n else\n {\n return n * factorial(n - 1);\n }\n}\n\nint f(int x)\n{\n return factorial(x);\n}\n int factorial(int n)\n{\n if (n <= 1)\n {\n return 1;\n }\n else\n {\n return n * factorial(n - 1);\n }\n}\n\nint f(int x)\n{\n if (x <= 1)\n {\n return 1;\n }\n else\n {\n int x2 = x - 1;\n if (x2 <= 1)\n {\n return x * 1;\n }\n else\n {\n int x3 = x2 - 1;\n if (x3 <= 1)\n {\n return x * x2 * 1;\n }\n else\n {\n return x * x2 * x3 * factorial(x3 - 1);\n }\n }\n }\n}\n"
},
{
"answer_id": 190275,
"author": "yungchin",
"author_id": 25756,
"author_profile": "https://Stackoverflow.com/users/25756",
"pm_score": 2,
"selected": false,
"text": "template <int N>\nstruct Factorial \n{\n enum { value = N * Factorial<N - 1>::value };\n};\n\ntemplate <>\nstruct Factorial<0> \n{\n enum { value = 1 };\n};\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26724/"
] |
190,236
|
<p>I have found no way of dumping the stack on all threads in .NET. Neither a signal to be send to the process nor programatic access to all the threads. I can only get access to the current thread via Thread.CurrentThread.</p>
<p>Any tricks ?</p>
|
[
{
"answer_id": 190247,
"author": "smaclell",
"author_id": 22914,
"author_profile": "https://Stackoverflow.com/users/22914",
"pm_score": 0,
"selected": false,
"text": "Using System.Diagnostics;\n\nvar threads = Process.GetCurrentProcess().Threads;\n"
},
{
"answer_id": 190271,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": false,
"text": "void CrashHandler::WriteThreadInfo(StringWriter* sw, ArrayList* threads, String* type)\n{\n sw->WriteLine(type);\n\n IEnumerator* ie = threads->GetEnumerator();\n while(ie->MoveNext())\n {\n botNETThread* bnt = static_cast<botNETThread*>(ie->Current);\n if(!bnt->IsAlive) continue;\n sw->WriteLine(String::Concat(S\"ORIGIN ASSEMBLY: \", bnt->Assembly->FullName));\n sw->WriteLine(String::Concat(S\"THREAD NAME: \", (bnt->Name && bnt->Name->Length)?bnt->Name:S\"Unnamed thread\"));\n\n sw->Write(GetStackTrace(bnt->_thread));\n sw->WriteLine();\n sw->WriteLine();\n }\n}\n\nString* CrashHandler::GetStackTrace(Thread* t)\n{\n\n System::Diagnostics::StackTrace __gc * trace1 = __gc new System::Diagnostics::StackTrace(t, true);\n\n System::String __gc * text1 = System::Environment::NewLine;\n System::Text::StringBuilder __gc * builder1 = __gc new System::Text::StringBuilder(255);\n for (System::Int32 num1 = 0; (num1 < trace1->FrameCount); num1++)\n {\n System::Diagnostics::StackFrame __gc * frame1 = trace1->GetFrame(num1);\n builder1->Append(S\" at \");\n System::Reflection::MethodBase __gc * base1 = frame1->GetMethod();\n System::Type __gc * type1 = base1->DeclaringType;\n if (type1 != 0)\n {\n System::String __gc * text2 = type1->Namespace;\n if (text2 != 0)\n {\n builder1->Append(text2);\n if (builder1 != 0)\n {\n builder1->Append(S\".\");\n }\n }\n builder1->Append(type1->Name);\n builder1->Append(S\".\");\n }\n builder1->Append(base1->Name);\n builder1->Append(S\"(\");\n System::Reflection::ParameterInfo __gc * infoArray1 __gc [] = base1->GetParameters();\n for (System::Int32 num2 = 0; (num2 < infoArray1->Length); num2++)\n {\n System::String __gc * text3 = S\"<UnknownType>\";\n if (infoArray1[num2]->ParameterType != 0)\n {\n text3 = infoArray1[num2]->ParameterType->Name;\n }\n builder1->Append(System::String::Concat(((num2 != 0) ? S\", \" : S\"\"), text3, S\" \", infoArray1[num2]->Name));\n }\n builder1->Append(S\")\");\n if (frame1->GetILOffset() != -1)\n {\n System::String __gc * text4 = 0;\n try\n {\n text4 = frame1->GetFileName();\n }\n catch (System::Security::SecurityException*)\n {\n }\n if (text4 != 0)\n {\n builder1->Append(System::String::Concat(S\" in \", text4, S\":line \", frame1->GetFileLineNumber().ToString()));\n }\n }\n if (num1 != (trace1->FrameCount - 1))\n {\n builder1->Append(text1);\n }\n }\n return builder1->ToString();\n\n\n\n}\n"
},
{
"answer_id": 615426,
"author": "Squirrel",
"author_id": 11835,
"author_profile": "https://Stackoverflow.com/users/11835",
"pm_score": 3,
"selected": false,
"text": " static void WriteThreadInfo(StringBuilder sw, IEnumerable<Thread> threads)\n {\n foreach(Thread thread in threads)\n {\n if(!thread.IsAlive) continue;\n sw.Append(String.Concat(\"THREAD NAME: \", thread.Name));\n\n sw.Append(GetStackTrace(thread));\n sw.AppendLine();\n sw.AppendLine();\n }\n }\n\n static String GetStackTrace(Thread t)\n {\n t.Suspend();\n var trace1 = new StackTrace(t, true);\n t.Resume();\n\n String text1 = System.Environment.NewLine;\n var builder1 = new StringBuilder(255);\n for (Int32 num1 = 0; (num1 < trace1.FrameCount); num1++)\n {\n StackFrame frame1 = trace1.GetFrame(num1);\n builder1.Append(\" at \");\n System.Reflection.MethodBase base1 = frame1.GetMethod();\n Type type1 = base1.DeclaringType;\n if (type1 != null)\n {\n String text2 = type1.Namespace;\n if (text2 != null)\n {\n builder1.Append(text2);\n builder1.Append(\".\"); \n }\n builder1.Append(type1.Name);\n builder1.Append(\".\");\n }\n builder1.Append(base1.Name);\n builder1.Append(\"(\");\n System.Reflection.ParameterInfo [] infoArray1 = base1.GetParameters();\n for (Int32 num2 = 0; (num2 < infoArray1.Length); num2++)\n {\n String text3 = \"<UnknownType>\";\n if (infoArray1[num2].ParameterType != null)\n {\n text3 = infoArray1[num2].ParameterType.Name;\n }\n builder1.Append(String.Concat(((num2 != 0) ? \", \" : \"\"), text3, \" \", infoArray1[num2].Name));\n }\n builder1.Append(\")\");\n if (frame1.GetILOffset() != -1)\n {\n String text4 = null;\n try\n {\n text4 = frame1.GetFileName();\n }\n catch (System.Security.SecurityException)\n {\n }\n if (text4 != null)\n {\n builder1.Append(String.Concat(\" in \", text4, \":line \", frame1.GetFileLineNumber().ToString()));\n }\n }\n if (num1 != (trace1.FrameCount - 1))\n {\n builder1.Append(text1);\n }\n }\n return builder1.ToString();\n }\n"
},
{
"answer_id": 38526361,
"author": "Søren Boisen",
"author_id": 567000,
"author_profile": "https://Stackoverflow.com/users/567000",
"pm_score": 2,
"selected": false,
"text": "using Microsoft.Diagnostics.Runtime;\n\nusing (DataTarget target = DataTarget.AttachToProcess(\n Process.GetCurrentProcess().Id, 5000, AttachFlag.Passive))\n{\n ClrRuntime runtime = target.ClrVersions.First().CreateRuntime();\n foreach (ClrThread thread in runtime.Threads)\n {\n IList<ClrStackFrame> stackFrames = thread.StackTrace;\n PrintStackTrace(stackFrames); \n }\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
190,243
|
<p>One of our internally written tool is fed a cvs commit trace of the form:</p>
<pre><code>Checking in src/com/package/AFile.java;
/home/cvs/src/com/package/AFile.java,v <-- Afile.java
new revision: 1.1.2.56; previous revision: 1.1.2.55
done
</code></pre>
<p>The tool then acquires the file from cvs by issuing a <code>cvs update -r 1.1.2.56</code> command in a working directory that already have specific branch of code checked-out. </p>
<p>This commands work correctly if there is an existing version of <strong>AFile.java</strong> in working directory. But when we get a trace of a file that has no version in working directory the command is not able to acquire the file.</p>
<p>Is there a way to do it? </p>
|
[
{
"answer_id": 190317,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 6,
"selected": true,
"text": "cvs checkout -r <revision> -p filename.ext > ~/tmp/filename.ext\n cvs export -r <revision> -d ~/tmp module/filename.ext\n"
},
{
"answer_id": 16150687,
"author": "Jess",
"author_id": 1804678,
"author_profile": "https://Stackoverflow.com/users/1804678",
"pm_score": 2,
"selected": false,
"text": "cvs --help -H $ cvs -H checkout\nUsage:\n cvs checkout [-ANPRcflnps] [-r rev] [-D date] [-d dir]\n [-j rev1] [-j rev2] [-k kopt] modules...\n -A Reset any sticky tags/date/kopts.\n -N Don't shorten module paths if -d specified.\n -P Prune empty directories.\n -R Process directories recursively.\n -c \"cat\" the module database.\n -f Force a head revision match if tag/date not found.\n -l Local directory only, not recursive\n -n Do not run module program (if any).\n -p Check out files to standard output (avoids stickiness).\n -s Like -c, but include module status.\n -r rev Check out revision or tag. (implies -P) (is sticky)\n -D date Check out revisions as of date. (implies -P) (is sticky)\n -d dir Check out into dir instead of module name.\n -k kopt Use RCS kopt -k option on checkout. (is sticky)\n -j rev Merge in changes made between current revision and rev.\n(Specify the --help global option for a list of other help options)\n"
},
{
"answer_id": 34062839,
"author": "Jeegar Patel",
"author_id": 775964,
"author_profile": "https://Stackoverflow.com/users/775964",
"pm_score": 2,
"selected": false,
"text": "cvs checkout -r <revision> -p filename.ext > ~/tmp/filename.ext\n cvs checkout: cannot find module `filename.ext` -ignored.\n cvs checkout -r <revision> -p Module_name/path_to_file/filename.ext > ~/tmp/filename.ext\n"
},
{
"answer_id": 42814624,
"author": "CpnCrunch",
"author_id": 1192732,
"author_profile": "https://Stackoverflow.com/users/1192732",
"pm_score": 1,
"selected": false,
"text": "cvs diff -r <revision> <file> > /tmp/patch\ncp <file> /tmp\ncd /tmp\npatch -R < patch\n"
},
{
"answer_id": 71642449,
"author": "Charlie",
"author_id": 4111860,
"author_profile": "https://Stackoverflow.com/users/4111860",
"pm_score": 0,
"selected": false,
"text": "cd <to_your_file_directory>\nmv user.cpp user.cpp.bak\ncvs update -r 1.55 user.cpp\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18027/"
] |
190,251
|
<p>I have a multi-table query, similar to this (simplified version)</p>
<pre><code>SELECT columns, count(table2.rev_id) As rev_count, sum(table2.rev_rating) As sum_rev_rating
FROM table1
LEFT JOIN table2
ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0 AND rev_status = 1
GROUP BY dom_url
ORDER BY sum_rev_rating/rev_count DESC
</code></pre>
<p>The problem is in the <code>ORDER BY</code> clause. This causes a MySQL error to show, which is as follows:</p>
<blockquote>
<p>Reference 'sum_ rev_ rating' not supported (reference to group function)</p>
</blockquote>
|
[
{
"answer_id": 190319,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "SELECT columns, count(table2.rev_id) As rev_count, \n sum(table2.rev_rating) As sum_rev_rating,\n sum(table2.rev_rating)/count(table2.rev_id) as rev_ratio\nFROM table1\n LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from \nWHERE dom_lastreview != 0 \nAND rev_status = 1 \nGROUP BY dom_url \nORDER BY rev_Ratio DESC\n SELECT * from (\n SELECT columns, count(table2.rev_id) As rev_count, \n sum(table2.rev_rating) As sum_rev_rating \n FROM table1\n LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from \n WHERE dom_lastreview != 0 \n AND rev_status = 1 \n GROUP BY dom_url \n) X\nORDER BY X.sum_rev_rating/X.rev_count DESC\n SELECT * from (\n SELECT columns, count(table2.rev_id) As rev_count, \n sum(table2.rev_rating) As sum_rev_rating,\n sum(table2.rev_rating)/count(table2.rev_id) as rev_ratio\n FROM table1\n LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from \n WHERE dom_lastreview != 0 \n AND rev_status = 1 \n GROUP BY dom_url \n) X\nORDER BY rev_Ratio DESC\n"
},
{
"answer_id": 190327,
"author": "djt",
"author_id": 26677,
"author_profile": "https://Stackoverflow.com/users/26677",
"pm_score": 5,
"selected": true,
"text": "SELECT columns, count(table2.rev_id) As rev_count, sum(table2.rev_rating) As sum_rev_rating, sum(table2.rev_rating)/count(table2.rev_id) as avg_rev_rating\nFROM table1\nLEFT JOIN table2\nON table1.dom_id = table2.rev_domain_from \nWHERE dom_lastreview != 0 AND rev_status = 1 \nGROUP BY dom_url \nORDER BY avg_rev_rating DESC\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
190,253
|
<p>I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.</p>
<p>I have looked for this myself but have been unable to find information on the syntax and how to use it. Does anyone know where the documentation for the syntax is?</p>
<p>EDIT: The attribute filters allow you to select based on patterns of an attribute value.</p>
|
[
{
"answer_id": 190255,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 9,
"selected": true,
"text": "div <div class=\"asdf\">\n :regex $(\"div:regex(class, .*sd.*)\")\n : jQuery.expr[':'] jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {\n return function (elem) {\n var matchParams = expression.split(','),\n validLabels = /^(data|css):/,\n attr = {\n method: matchParams[0].match(validLabels) ?\n matchParams[0].split(':')[0] : 'attr',\n property: matchParams.shift().replace(validLabels, '')\n },\n regexFlags = 'ig',\n regex = new RegExp(matchParams.join('').replace(/^\\s+|\\s+$/g, ''), regexFlags);\n return regex.test(jQuery(elem)[attr.method](attr.property));\n }\n});\n"
},
{
"answer_id": 193787,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 10,
"selected": false,
"text": "filter $('div')\n .filter(function() {\n return this.id.match(/abc+d/);\n })\n .html(\"Matched!\"); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"abcd\">Not matched</div>\n<div id=\"abccd\">Not matched</div>\n<div id=\"abcccd\">Not matched</div>\n<div id=\"abd\">Not matched</div>"
},
{
"answer_id": 1873261,
"author": "irfan akhtar",
"author_id": 227919,
"author_profile": "https://Stackoverflow.com/users/227919",
"pm_score": 2,
"selected": false,
"text": "$(\"input[name='option[colour]'] :checked \")\n"
},
{
"answer_id": 9927306,
"author": "Kamil Dąbrowski",
"author_id": 1088058,
"author_profile": "https://Stackoverflow.com/users/1088058",
"pm_score": 5,
"selected": false,
"text": "var test = $('#id').attr('value').match(/[^a-z0-9 ]+/);\n"
},
{
"answer_id": 19788198,
"author": "Nicolas Janel",
"author_id": 279326,
"author_profile": "https://Stackoverflow.com/users/279326",
"pm_score": 6,
"selected": false,
"text": "^ $(\"div[id^='abc']\")\n"
},
{
"answer_id": 24740738,
"author": "dnxit",
"author_id": 1106625,
"author_profile": "https://Stackoverflow.com/users/1106625",
"pm_score": 8,
"selected": false,
"text": " $(\"input[id*='DiscountType']\").each(function (i, el) {\n //It'll be an array of elements\n });\n $(\"input[id^='DiscountType']\").each(function (i, el) {\n //It'll be an array of elements\n });\n $(\"input[id$='DiscountType']\").each(function (i, el) {\n //It'll be an array of elements\n });\n $(\"input[id!='DiscountType']\").each(function (i, el) {\n //It'll be an array of elements\n });\n $(\"input[name~='DiscountType']\").each(function (i, el) {\n //It'll be an array of elements\n });\n $(\"input[id|='DiscountType']\").each(function (i, el) {\n //It'll be an array of elements\n });\n"
},
{
"answer_id": 32132590,
"author": "brook hong",
"author_id": 1044881,
"author_profile": "https://Stackoverflow.com/users/1044881",
"pm_score": 3,
"selected": false,
"text": "(function($){\n $.fn.regex = function(pattern, fn, fn_a){\n var fn = fn || $.fn.text;\n return this.filter(function() {\n return pattern.test(fn.apply($(this), fn_a));\n });\n };\n})(jQuery);\n $('span').regex(/Sent/)\n $('span').regex(/tooltip.year/, $.fn.attr, ['class'])\n"
},
{
"answer_id": 33841205,
"author": "Prakash GPz",
"author_id": 1817755,
"author_profile": "https://Stackoverflow.com/users/1817755",
"pm_score": 1,
"selected": false,
"text": "$(':contains(\"search string\")')"
},
{
"answer_id": 48848460,
"author": "Vishnu Prasanth G",
"author_id": 6624082,
"author_profile": "https://Stackoverflow.com/users/6624082",
"pm_score": 2,
"selected": false,
"text": "document.querySelectorAll(\"[id^='select2-qownerName_select-result']\"); $(\"[id^='select2-qownerName_select-result']\")"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5360/"
] |
190,257
|
<p>What is the best database schema to track role-based access controls for a web application?</p>
<p>I am using Rails, but the RBAC plugin linked by Google looks unmaintained (only 300 commits to SVN; latest was almost a year ago).</p>
<p>The concept is simple enough to implement from scratch, yet complex and important enough that it's worth getting right.</p>
<p>So how do others architect and implement their RBAC model?</p>
|
[
{
"answer_id": 195766,
"author": "Yuval",
"author_id": 2819,
"author_profile": "https://Stackoverflow.com/users/2819",
"pm_score": 2,
"selected": false,
"text": "rule 14: guest role + page name + read permission\nrule 46: approver role + add column + execute permission\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2938/"
] |
190,270
|
<p>I just got a dedicated server from a hosting company, and for some reason, it didn't have IIS installed.
It did have .Net 2.0, though.</p>
<p>So I installed IIS, but now my ASP.net websites won't work.
I just get a 404, no event log entries, nothing...</p>
<p>I noticed in the redistributable package information that:
"To access the features of ASP.NET, IIS with the latest security updates must be installed prior to installing the .NET Framework"</p>
<p>I also can't uninstall .Net, it just won't let me...</p>
<p>Is there a way to reinstall .Net 2.0, or somehow do whatever it is it does to IIS to make it work?</p>
<p>Thanks!
Daniel</p>
|
[
{
"answer_id": 190276,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 5,
"selected": true,
"text": "aspnet_regiis -i\n C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
190,292
|
<p>I'm currently working with PHPUnit to try and develop tests alongside what I'm writing, however, I'm currently working on writing the Session Manager, and am having issues doing so...</p>
<p>The constructor for the Session handling class is</p>
<pre><code>private function __construct()
{
if (!headers_sent())
{
session_start();
self::$session_id = session_id();
}
}
</code></pre>
<p>However, as PHPUnit sends out text before it starts the testing, any testing on this Object returns a failed test, as the HTTP "Headers" have been sent...</p>
|
[
{
"answer_id": 190498,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 6,
"selected": true,
"text": "echo header exit session_start WebTestCase"
},
{
"answer_id": 282582,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "session_start() private function __construct(SessionWrapper $wrapper)\n{\n if (!$wrapper->headers_sent())\n {\n $wrapper->session_start();\n $this->session_id = $wrapper->session_id();\n }\n}\n"
},
{
"answer_id": 1701041,
"author": "Dominik",
"author_id": 169773,
"author_profile": "https://Stackoverflow.com/users/169773",
"pm_score": 4,
"selected": false,
"text": "session_start();\n phpunit --bootstrap pathToBootstrap.php --anotherSwitch /your/test/path/\n"
},
{
"answer_id": 4059399,
"author": "Michael",
"author_id": 492243,
"author_profile": "https://Stackoverflow.com/users/492243",
"pm_score": 4,
"selected": false,
"text": "<?php\n\nob_start();\n\nrequire_once 'YourFramework/AllTests.php';\n\nclass AllTests {\n public static function suite() {\n $suite = new PHPUnit_Framework_TestSuite('YourFramework');\n $suite->addTest(YourFramework_AllTests::suite());\n return $suite;\n }\n}\n"
},
{
"answer_id": 7822192,
"author": "Flip Vernooij",
"author_id": 1003261,
"author_profile": "https://Stackoverflow.com/users/1003261",
"pm_score": 0,
"selected": false,
"text": "// phpunit_bootstrap.php\ndefine('UNITTEST_RUNNING', true);\n\n// bootstrap.php (application bootstrap)\ndefined('UNITTEST_RUNNING') || define('UNITTEST_RUNNING', false);\n.....\nif(UNITTEST_RUNNING===false){\n session_start();\n}\n public function __set($name, $value){\n if(UNITTEST_RUNNING===true){\n $name='_' . $name;\n $this->$name=$value;\n }\n throw new Exception('__set() can only be used when unittesting!');\n }\n"
},
{
"answer_id": 24778590,
"author": "Juanjo Lainez Reche",
"author_id": 2550230,
"author_profile": "https://Stackoverflow.com/users/2550230",
"pm_score": 4,
"selected": false,
"text": "phpunit --stderr /path/to/your/test\n"
},
{
"answer_id": 33445778,
"author": "user487772",
"author_id": 619978,
"author_profile": "https://Stackoverflow.com/users/619978",
"pm_score": 1,
"selected": false,
"text": "/**\n * @runInSeparateProcess\n * @requires extension xdebug\n */\npublic function testGivenHeaderIsIncludedIntoResponse()\n{\n $customHeaderName = 'foo';\n $customHeaderValue = 'bar';\n\n // Here execute the code which is supposed to set headers\n // ...\n\n $expectedHeader = $customHeaderName . ': ' . $customHeaderValue;\n $headers = xdebug_get_headers();\n\n $this->assertContains($expectedHeader, $headers);\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20010/"
] |
190,295
|
<p>How do I test the concrete methods of an abstract class with PHPUnit?</p>
<p>I'd expect that I'd have to create some sort of object as part of the test. Though, I've no idea the best practice for this or if PHPUnit allows for this.</p>
|
[
{
"answer_id": 2241159,
"author": "Victor Farazdagi",
"author_id": 238300,
"author_profile": "https://Stackoverflow.com/users/238300",
"pm_score": 9,
"selected": true,
"text": "abstract class AbstractClass\n{\n public function concreteMethod()\n {\n return $this->abstractMethod();\n }\n\n public abstract function abstractMethod();\n}\n\nclass AbstractClassTest extends PHPUnit_Framework_TestCase\n{\n public function testConcreteMethod()\n {\n $stub = $this->getMockForAbstractClass('AbstractClass');\n $stub->expects($this->any())\n ->method('abstractMethod')\n ->will($this->returnValue(TRUE));\n\n $this->assertTrue($stub->concreteMethod());\n }\n}\n"
},
{
"answer_id": 4987710,
"author": "takeshin",
"author_id": 234780,
"author_profile": "https://Stackoverflow.com/users/234780",
"pm_score": 5,
"selected": false,
"text": "getMockForAbstractClass() protected function setUp()\n{\n $stub = $this->getMockForAbstractClass('Some_Abstract_Class');\n $this->_object = $stub;\n}\n sudo pear channel-update pear.phpunit.de\nsudo pear upgrade phpunit/PHPUnit\n"
},
{
"answer_id": 48889062,
"author": "GordonM",
"author_id": 477127,
"author_profile": "https://Stackoverflow.com/users/477127",
"pm_score": 6,
"selected": false,
"text": "class AbstractClassTest extends \\PHPUnit_Framework_TestCase\n{\n /**\n * @var AbstractClass\n */\n private $testedClass;\n\n public function setUp()\n {\n $this->testedClass = new class extends AbstractClass {\n\n protected function abstractMethod()\n {\n // Put a barebones implementation here\n }\n };\n }\n\n // Put your tests here\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20010/"
] |
190,296
|
<p>What are the best practices for modeling inheritance in databases?</p>
<p>What are the trade-offs (e.g. queriability)?</p>
<p>(I'm most interested in SQL Server and .NET, but I also want to understand how other platforms address this issue.)</p>
|
[
{
"answer_id": 190306,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 9,
"selected": true,
"text": "class Person {\n public int ID;\n public string FirstName;\n public string LastName;\n}\n\nclass Employee : Person {\n public DateTime StartDate;\n}\n table Person\n------------\nint id (PK)\nstring firstname\nstring lastname\n\ntable Employee\n--------------\nint id (PK, FK)\ndatetime startdate\n table Person\n------------\nint id (PK)\nint rowtype (0 = \"Person\", 1 = \"Employee\")\nstring firstname\nstring lastname\ndatetime startdate\n table Person\n------------\nint id (PK)\nstring firstname\nstring lastname\n\ntable Employee\n--------------\nint id (PK)\nstring firstname\nstring lastname\ndatetime startdate\n"
},
{
"answer_id": 190309,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "create table Object (\n Id int NOT NULL --primary key, auto-increment\n Name varchar(32)\n)\ncreate table SubObject (\n Id int NOT NULL --primary key and also foreign key to Object\n Description varchar(32)\n)\n"
},
{
"answer_id": 25452683,
"author": "imang",
"author_id": 3684279,
"author_profile": "https://Stackoverflow.com/users/3684279",
"pm_score": 4,
"selected": false,
"text": " select public class Shape {\nint id;\nColor color;\nThickness thickness;\n//other fields\n}\n\npublic class Rectangle : Shape {\nPoint topLeft;\nPoint bottomRight;\n}\n\npublic class Circle : Shape {\nPoint center;\nint radius;\n}\n table Shape\n-----------\nint id; (PK)\nint color;\nint thichkness;\nint rowType; (0 = Rectangle, 1 = Circle, 2 = ...)\n\ntable Rectangle\n----------\nint ShapeID; (FK on delete cascade)\nint topLeftX;\nint topLeftY;\nint bottomRightX;\nint bottomRightY;\n\ntable Circle\n----------\nint ShapeID; (FK on delete cascade) \nint centerX;\nint center;\nint radius;\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73794/"
] |
190,326
|
<p>How can I find out the decorated name that will be asigned to each method name ? I'm trying to find out what the decorated name is , so that I may export it , in a DLL .</p>
|
[
{
"answer_id": 190333,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "__declspec(dllexport)"
},
{
"answer_id": 190346,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "extern \"C\""
},
{
"answer_id": 213560,
"author": "Vhaerun",
"author_id": 11234,
"author_profile": "https://Stackoverflow.com/users/11234",
"pm_score": 2,
"selected": false,
"text": "dumpbin /symbols File.obj\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
] |
190,344
|
<p>Problem is described and demonstrated on the following links:</p>
<ul>
<li><a href="https://web.archive.org/web/20081123055336/http://paulstovell.com/blog/wpf-why-is-my-text-so-blurry" rel="noreferrer">Paul Stovell WPF: Blurry Text Rendering </a></li>
<li><a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=445078" rel="noreferrer">www.gamedev.net forum</a></li>
<li><a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=380919&wa=wsignin1.0" rel="noreferrer">Microsoft Connect: WPF text renderer produces badly blurred text on small font sizes</a></li>
</ul>
<p>Explanation: <a href="http://windowsclient.net/wpf/white-papers/wpftextclarity.aspx" rel="noreferrer">Text Clarity in WPF</a>. This link has font comparison.</p>
<p>I would like to collect all possible solutions for this problem. Microsoft Expression Blend uses WPF but fonts look readable. </p>
<ul>
<li>Dark background as in Microsoft Expression Blend</li>
<li>Increasing the font size and changing the font (Calibri ... ) <a href="https://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem#190521">[link]</a></li>
<li>Embed windows forms <a href="https://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem#190540">[link]</a></li>
<li>Use GDI+ and/or Windows Forms TextRenderer class to render text to a bitmap, and then render that bitmap as a WPF control. <a href="https://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem#283216">[link]</a></li>
</ul>
<p>Are there any more solutions?</p>
<p><a href="https://stackoverflow.com/questions/190344/wpf-blurry-fonts-problem-solutions/1494126#1494126"><strong>This is going to be fixed in VS2010 (and WPF4) beta 2</strong></a></p>
<p><strong>IT LOOKS LIKE IT HAS BEEN FINALLY SOLVED !</strong> </p>
<p><a href="http://www.hanselman.com/blog/WPFAndTextBlurrinessNowWithCompleteClarity.aspx?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+ScottHanselman+%28Scott+Hanselman+-+ComputerZen.com%29&utm_content=Google+Reader" rel="noreferrer"><strong>Scott Hanselman's ComputerZen.com: WPF and Text Blurriness, now with complete Clarity</strong></a> </p>
|
[
{
"answer_id": 1631635,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 5,
"selected": false,
"text": "<!-- don't do this --->\n<Border>\n <Border.Effect>\n <DropShadowEffect BlurRadius=\"25\" ShadowDepth=\"0\" Opacity=\"1\"/>\n </Border.Effect>\n <TextBlock Text=\"This Text Will Be Blurry\" />\n</Border>\n\n<!-- Do this instead -->\n<Grid>\n <Rectangle>\n <Rectangle.Effect>\n <DropShadowEffect BlurRadius=\"25\" ShadowDepth=\"0\" Opacity=\"1\"/>\n </Rectangle.Effect>\n </Rectangle>\n <TextBlock Text=\"This Text Will Be Crisp and Clear\" />\n</Grid>\n"
},
{
"answer_id": 5166585,
"author": "Helge Klein",
"author_id": 234152,
"author_profile": "https://Stackoverflow.com/users/234152",
"pm_score": 7,
"selected": false,
"text": "TextOptions.TextFormattingMode=\"Display\"\n"
},
{
"answer_id": 23184011,
"author": "Gabriel",
"author_id": 1365104,
"author_profile": "https://Stackoverflow.com/users/1365104",
"pm_score": 3,
"selected": false,
"text": "TextOptions.TextRenderingMode\nTextOptions.TextFormattingMode\nRenderOptions.ClearTypeHint\n SnapToDevicePixels TextOptions.TextRenderingMode=\"Auto\"\nTextOptions.TextFormattingMode=\"Ideal\"\nRenderOptions.ClearTypeHint=\"Auto\"\n TransitioningContentControl"
},
{
"answer_id": 55356817,
"author": "Edward Brey",
"author_id": 145173,
"author_profile": "https://Stackoverflow.com/users/145173",
"pm_score": 1,
"selected": false,
"text": "public class SnappyWindow : Window\n{\n public SnappyWindow()\n {\n SetValue(TextOptions.TextFormattingModeProperty, TextFormattingMode.Display);\n }\n}\n"
},
{
"answer_id": 72998815,
"author": "erez",
"author_id": 6141062,
"author_profile": "https://Stackoverflow.com/users/6141062",
"pm_score": 1,
"selected": false,
"text": "UseLayoutRounding=\"True\" UseLayoutRounding SnapToDevicePixels"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438025/"
] |
190,368
|
<p>In Scala, is it possible to get the string representation of a type at runtime? I am trying to do something along these lines:</p>
<pre><code>def printTheNameOfThisType[T]() = {
println(T.toString)
}
</code></pre>
|
[
{
"answer_id": 190574,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 4,
"selected": true,
"text": "10:48 <seet_> http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible?\n10:48 <seet_> possible\n10:48 <lambdabot> Title: Getting the string representation of a type at runtime in Scala - Stack Overflow,\n http://tinyurl.com/53242l\n10:49 <mapreduce> Types aren't objects.\n10:49 <mapreduce> or values\n10:49 <mapreduce> println(classOf[T]) should give you something, but probably not what you want.\n"
},
{
"answer_id": 195294,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 2,
"selected": false,
"text": "object Test {\n def main (args : Array[String]) {\n println(classOf[List[String]])\n }\n}\n $ scala Test \nclass scala.List\n object TestSv {\n def main(args:Array[String]){\n narf[String]\n }\n def narf[T](){\n println(classOf[T])\n }\n}\n"
},
{
"answer_id": 392339,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "object Foo {\n def apply[T <: AnyRef](t: T)(implicit m: scala.reflect.Manifest[T]) = println(\"t was \" + t.toString + \" of class \" + t.getClass.getName() + \", erased from \" + m.erasure)\n}\n"
},
{
"answer_id": 31191219,
"author": "Julie",
"author_id": 8217,
"author_profile": "https://Stackoverflow.com/users/8217",
"pm_score": 3,
"selected": false,
"text": "TypeTag scala-reflect import scala.reflect.runtime.universe._\ndef printTheNameOfThisType[T: TypeTag]() = {\n println(typeOf[T].toString)\n}\n scala> printTheNameOfThisType[Int]\nInt\n\nscala> printTheNameOfThisType[String]\nString\n\nscala> printTheNameOfThisType[List[Int]]\nscala.List[Int]\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10475/"
] |
190,376
|
<p>An interesting issue came up recently. We came across some code that is using <code>hashCode()</code> as a salt source for MD5 encryption but this raises the question: will <code>hashCode()</code> return the same value for the same object on different VMs, different JDK versions and operating systems? Even if its not guaranteed, has it changed at any point up til now?</p>
<p>EDIT: I really mean <code>String.hashCode()</code> rather than the more general <code>Object.hashCode()</code>, which of course can be overridden.</p>
|
[
{
"answer_id": 191851,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 2,
"selected": false,
"text": "s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18393/"
] |
190,380
|
<p>I am trying to store more than 1 data item at a single index in my linked-list. All of the examples in my textbook seem to illustrate adding only 1 piece of data per index. I'm assuming it is possible to add more?</p>
<p>For example, using the Collections API to store an integer I would do the following:</p>
<pre><code>LinkedList <Integer>linky = new LinkedList<Integer>();
int num1 = 2, num2 = 22, num3 = 25, num4 = 1337;
linky.add(num1);
</code></pre>
<p>How would I go about adding num2, num3, and num4 to the same first index in the list? Thanks guys. </p>
|
[
{
"answer_id": 190390,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "private struct Node\n{\n int Num1;\n int Num2;\n int Num3;\n}\n LinkedList<Node> list = new LnkedList<Node>();\n\nNode n = new Node();\nn.Num1 = 10;\nn.Num2 = 100;\nn.Num3 = 1000;\nlist.Add(n);\n"
},
{
"answer_id": 190392,
"author": "Gregor",
"author_id": 26153,
"author_profile": "https://Stackoverflow.com/users/26153",
"pm_score": 1,
"selected": false,
"text": "LinkedList<LinkedList<Integer>> linky = new LinkedList<LinkedList<Integer>>();\n//...\nlinky.add(new LinkedList<Integer>().add( //...\n"
},
{
"answer_id": 190393,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 5,
"selected": true,
"text": "LinkedList <Integer>linky = new LinkedList<Integer>();\nint num1 = 2, num2 = 22, num3 = 25, num4 = 1337;\nlinky.add(num1);\nlinky.add(num2);\nlinky.add(num3);\nlinky.add(num4);\n class class GroupOfFourInts\n{\n int myInt1;\n int myInt2;\n int myInt3;\n int myInt4;\n\n public GroupOfFourInts(int a, int b, int c, int d)\n {\n myInt1 = a; myInt2 = b; myInt3 = c; myInt4 = d;\n }\n}\n\nclass someOtherClass\n{\n\n public static void main(String[] args)\n {\n LinkedList<GroupOfFourInts> linky = new LinkedList<GroupOfFourInts>();\n GroupOfFourInts group1 = new GroupOfFourInts(1,2,3,4);\n GroupOfFourInts group2 = new GroupOfFourInts(1337,7331,2345,6789);\n linky.add(group1);\n linky.add(group2);\n }\n}\n linky int"
},
{
"answer_id": 190400,
"author": "GavinCattell",
"author_id": 21644,
"author_profile": "https://Stackoverflow.com/users/21644",
"pm_score": 1,
"selected": false,
"text": "private Class Node\n{\n //You might want to make these private, and make setters and getters\n public int Num1;\n public int Num2;\n puclic int Num3;\n}\n\nLinkedList<Node> list = new LinkedList<Node>();\n\nNode n = new Node();\nn.Num1 = 10;\nn.Num2 = 100;\nn.Num3 = 1000;\nlist.Add(n);\n"
},
{
"answer_id": 190416,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 0,
"selected": false,
"text": "import java.util.LinkedList;\nclass Node {\n int num1;\n int num2;\n int num3;\n int num4;\n public Node(int a, int b, int c, int d) {\n num1 = a; num2 = b; num3 = c; num4 = d;\n }\n}\npublic class dummy {\n public static void main(String[] args) {\n LinkedList <Node>linky = new LinkedList<Node>();\n x myNode = new Node(2, 22, 25, 1337);\n linky.add(myNode);\n }\n}\n"
},
{
"answer_id": 190424,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 0,
"selected": false,
"text": "LinkedList <Integer>linky = new LinkedList<Integer>();\nlinky.add(num1);\n\n// Lots of code possibly adding elements somewhere else in the list\n\nif (linky.size() > 0) { // Always good to be sure; especially if this is in another methode\n int first = linky.get(0);\n linky.set(0, first + num2);// Value of linky.get(0) is num1 + num2 \n}\n\n\n// The same again\n// Lots of code possibly adding elements somewhere else in the list\n\nif (linky.size() > 0) { // Always good to be sure; especially if this is in another methode\n int first = linky.get(0);\n linky.set(0, first + num3); // Value of linky.get(0) is num1 + num2 + num3\n}\n // added static, Class to class\nprivate static class Node\n{\n //You might want to make these private, and make setters and getters\n public int Num1;\n public int Num2;\n puclic int Num3;\n}\n\n// Prefer interfaces if possible\nList<Node> list = new LinkedList<Node>();\n\nNode n = new Node();\nn.Num1 = 10;\nn.Num2 = 100;\nn.Num3 = 1000;\nlist.add(n); // Add -> add\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14013/"
] |
190,385
|
<p>How do I manipulate images at the pixel level in C#?</p>
<p>I need to be able to read/modify each bitmap pixel RGB values separately. </p>
<p>A code sample would be appreciated.</p>
|
[
{
"answer_id": 190420,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 4,
"selected": false,
"text": " public static Bitmap Diff(Bitmap src1, Bitmap src2, int x1, int y1, int x2, int y2, int width, int height)\n{\n Bitmap diffBM = new Bitmap(width, height, PixelFormat.Format24bppRgb);\n\n for (int y = 0; y < height; y++)\n {\n for (int x = 0; x < width; x++)\n {\n //Get Both Colours at the pixel point\n Color col1 = src1.GetPixel(x1 + x, y1 + y);\n Color col2 = src2.GetPixel(x2 + x, y2 + y);\n\n // Get the difference RGB\n int r = 0, g = 0, b = 0;\n r = Math.Abs(col1.R - col2.R);\n g = Math.Abs(col1.G - col2.G);\n b = Math.Abs(col1.B - col2.B);\n\n // Invert the difference average\n int dif = 255 - ((r+g+b) / 3);\n\n // Create new grayscale RGB colour\n Color newcol = Color.FromArgb(dif, dif, dif);\n\n diffBM.SetPixel(x, y, newcol);\n\n }\n }\n\n return diffBM;\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3515/"
] |
190,396
|
<p>How do you use the <strong>CSS</strong> <code>content</code> property to add <strong>HTML</strong> entities?</p>
<p>Using something like this just prints <code>&nbsp;</code> to the screen instead of the non-breaking space:</p>
<pre class="lang-css prettyprint-override"><code>.breadcrumbs a:before {
content: '&nbsp;';
}
</code></pre>
|
[
{
"answer_id": 190406,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": ".breadcrumbs a:before {\n content: '>\\00a0';\n}\n"
},
{
"answer_id": 190412,
"author": "mathieu",
"author_id": 971,
"author_profile": "https://Stackoverflow.com/users/971",
"pm_score": 11,
"selected": true,
"text": ".breadcrumbs a:before {\n content: '\\0000a0';\n}\n"
},
{
"answer_id": 1412764,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 6,
"selected": false,
"text": " '\\a0 ' \\00a0 content:'>\\a0 '; /* or */\ncontent:'>\\0000a0'; /* because you'll find: */\ncontent:'No\\a0 Break'; /* and */\ncontent:'No\\0000a0Break'; /* becomes No Break as opposed to below */\n \\0000a0 content:'No\\00a0Break' /* becomes No਋reak */\n"
},
{
"answer_id": 1851564,
"author": "Dare",
"author_id": 225321,
"author_profile": "https://Stackoverflow.com/users/225321",
"pm_score": 4,
"selected": false,
"text": "nbsp .breadcrumbs a:before { content: '>'; padding-right: .5em; }\n display:inline-block"
},
{
"answer_id": 8523731,
"author": "netgoblin",
"author_id": 967024,
"author_profile": "https://Stackoverflow.com/users/967024",
"pm_score": 6,
"selected": false,
"text": "▾ \\25BE 9662 25BE \\"
},
{
"answer_id": 8595802,
"author": "PointedEars",
"author_id": 855543,
"author_profile": "https://Stackoverflow.com/users/855543",
"pm_score": 8,
"selected": false,
"text": "   NO-BREAK SPACE .breadcrumbs a:before {\n content: '\\a0';\n}\n .breadcrumbs a:before {\n content: '\\0000a0foo';\n}\n .breadcrumbs a:before {\n content: '\\a0 foo';\n}\n f \\a0f GURMUKHI LETTER EE foo NO-BREAK SPACE '\\a0 foo' '\\0000a0foo' .breadcrumbs a:before {\n content: '\\a0 foo';\n}\n .breadcrumbs a:before {\n content: '\\a0\\20 foo';\n}\n"
},
{
"answer_id": 30105665,
"author": "Ferhat KOÇER",
"author_id": 3129822,
"author_profile": "https://Stackoverflow.com/users/3129822",
"pm_score": 4,
"selected": false,
"text": ".breadcrumbs a:before {\n content: '\\0021ac';\n}\n"
},
{
"answer_id": 39891538,
"author": "Tarandeep Singh",
"author_id": 2754038,
"author_profile": "https://Stackoverflow.com/users/2754038",
"pm_score": 0,
"selected": false,
"text": "<div class=\"ics\">⛱</div> .ics::before {content: \"\\9969;\"} <div class=\"ics\"></div>"
},
{
"answer_id": 47108182,
"author": "brian-welch",
"author_id": 1562842,
"author_profile": "https://Stackoverflow.com/users/1562842",
"pm_score": 1,
"selected": false,
"text": ".breadcrumbs a::before {\n content: '>';\n margin-left: 8px;\n margin-right: 8px;\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
190,421
|
<p>Is there a PHP function to find out the name of the caller function in a given function?</p>
|
[
{
"answer_id": 190425,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": false,
"text": "debug_backtrace()"
},
{
"answer_id": 190426,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 8,
"selected": false,
"text": "$trace = debug_backtrace();\n$caller = $trace[1];\n\necho \"Called by {$caller['function']}\";\nif (isset($caller['class']))\n echo \" in {$caller['class']}\";\n"
},
{
"answer_id": 9934684,
"author": "svassr",
"author_id": 1157322,
"author_profile": "https://Stackoverflow.com/users/1157322",
"pm_score": 4,
"selected": false,
"text": "<?php\n Class MyClass\n {\n function __construct(){\n $this->callee();\n }\n function callee() {\n echo sprintf(\"callee() called @ %s: %s from %s::%s\",\n xdebug_call_file(),\n xdebug_call_line(),\n xdebug_call_class(),\n xdebug_call_function()\n );\n }\n }\n $rollDebug = new MyClass();\n?>\n callee() called @ /var/www/xd.php: 16 from MyClass::__construct\n sudo aptitude install php5-xdebug\n sudo aptitude install php5-dev\n"
},
{
"answer_id": 12463381,
"author": "Paul Gobée",
"author_id": 1872387,
"author_profile": "https://Stackoverflow.com/users/1872387",
"pm_score": 3,
"selected": false,
"text": "/**\n * Gets the caller of the function where this function is called from\n * @param string what to return? (Leave empty to get all, or specify: \"class\", \"function\", \"line\", \"class\", etc.) - options see: http://php.net/manual/en/function.debug-backtrace.php\n */\nfunction getCaller($what = NULL)\n{\n $trace = debug_backtrace();\n $previousCall = $trace[2]; // 0 is this call, 1 is call in previous function, 2 is caller of that function\n\n if(isset($what))\n {\n return $previousCall[$what];\n }\n else\n {\n return $previousCall;\n } \n}\n"
},
{
"answer_id": 12813039,
"author": "MANISH ZOPE",
"author_id": 932826,
"author_profile": "https://Stackoverflow.com/users/932826",
"pm_score": 4,
"selected": false,
"text": "public function getCallingFunctionName($completeTrace=false)\n {\n $trace=debug_backtrace();\n if($completeTrace)\n {\n $str = '';\n foreach($trace as $caller)\n {\n $str .= \" -- Called by {$caller['function']}\";\n if (isset($caller['class']))\n $str .= \" From Class {$caller['class']}\";\n }\n }\n else\n {\n $caller=$trace[2];\n $str = \"Called by {$caller['function']}\";\n if (isset($caller['class']))\n $str .= \" From Class {$caller['class']}\";\n }\n return $str;\n }\n"
},
{
"answer_id": 13502124,
"author": "Gershon Herczeg",
"author_id": 1109024,
"author_profile": "https://Stackoverflow.com/users/1109024",
"pm_score": 2,
"selected": false,
"text": "var_dump(debug_backtrace());"
},
{
"answer_id": 25545623,
"author": "flori",
"author_id": 793476,
"author_profile": "https://Stackoverflow.com/users/793476",
"pm_score": 4,
"selected": false,
"text": "echo debug_backtrace()[1]['function'];\n echo debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];\n"
},
{
"answer_id": 28849906,
"author": "lrd",
"author_id": 3343023,
"author_profile": "https://Stackoverflow.com/users/3343023",
"pm_score": 2,
"selected": false,
"text": "class basicFunctions{\n\n public function getCallerFunction(){\n return debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'];\n }\n\n}\n function a($authorisedFunctionsList = array(\"b\")){\n $ref = new basicFunctions;\n $caller = $ref->getCallerFunction();\n\n if(in_array($caller,$authorisedFunctionsList)):\n echo \"Welcome!\";\n return true;\n else:\n echo \"Unauthorised caller!\";\n return false; \n endif;\n}\n\nfunction b(){\n $executionContinues = $this->a();\n $executionContinues or exit;\n\n //Do something else..\n}\n"
},
{
"answer_id": 35658760,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 0,
"selected": false,
"text": "$caller = next(debug_backtrace())['function'];\n"
},
{
"answer_id": 62665184,
"author": "Uriahs Victor",
"author_id": 4484799,
"author_profile": "https://Stackoverflow.com/users/4484799",
"pm_score": 0,
"selected": false,
"text": "\n// Outputs an easy to read call trace\n// Credit: https://www.php.net/manual/en/function.debug-backtrace.php#112238\n// Gist: https://gist.github.com/UVLabs/692e542d3b53e079d36bc53b4ea20a4b\n\nClass MyClass{\n\npublic function generateCallTrace()\n{\n $e = new Exception();\n $trace = explode(\"\\n\", $e->getTraceAsString());\n // reverse array to make steps line up chronologically\n $trace = array_reverse($trace);\n array_shift($trace); // remove {main}\n array_pop($trace); // remove call to this method\n $length = count($trace);\n $result = array();\n \n for ($i = 0; $i < $length; $i++)\n {\n $result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering\n }\n \n return \"\\t\" . implode(\"\\n\\t\", $result);\n}\n\n}\n\n// call function where needed to output call trace\n\n/**\nExample output:\n1) /var/www/test/test.php(15): SomeClass->__construct()\n2) /var/www/test/SomeClass.class.php(36): SomeClass->callSomething()\n**/```\n"
},
{
"answer_id": 71605491,
"author": "Imran Zahoor",
"author_id": 1843175,
"author_profile": "https://Stackoverflow.com/users/1843175",
"pm_score": 0,
"selected": false,
"text": "use ReflectionClass;\n\nclass DebugUtils\n{\n /**\n * Generates debug traces in user readable form\n *\n * @param integer $steps\n * @param boolean $skipFirstEntry\n * @param boolean $withoutNamespaces\n * @return string\n */\n public static function getReadableBackTracke(\n $steps = 4,\n $skipFirstEntry = true,\n $withoutNamespaces = true\n ) {\n $str = '';\n try {\n $backtrace = debug_backtrace(false, $steps);\n\n // Removing first array entry\n // to make sure getReadableBackTracke() method doesn't gets displayed\n if ($skipFirstEntry)\n array_shift($backtrace);\n\n // Reserved, so it gets displayed in calling order\n $backtrace = array_reverse($backtrace);\n\n foreach ($backtrace as $caller) {\n if ($str) {\n $str .= ' --> ';\n }\n if (isset($caller['class'])) {\n $class = $caller['class'];\n if ($withoutNamespaces) {\n $class = (new ReflectionClass($class))->getShortName();\n }\n $str .= $class . $caller['type'];\n }\n $str .= $caller['function'];\n }\n } catch (\\Throwable $th) {\n return null;\n }\n\n return $str;\n }\n}\n DebugUtils::getReadableBackTracke() SomeClass->method1 --> SomeOtherClass->method2 --> TargetClass->targetMethod\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
190,431
|
<p>My motivation for trying out git-svn is the effortless merging and branching. Then I noticed that man git-svn(1) says: </p>
<blockquote>
<p>Running git-merge or git-pull is NOT recommended on a branch you plan
to dcommit from. Subversion does not represent merges in any
reasonable or useful fashion; so users using Subversion cannot see any
merges you've made. Furthermore, if you merge or pull from a git
branch that is a mirror of an SVN branch, dcommit may commit to the
wrong branch.</p>
</blockquote>
<p>Does this mean I cannot create a local branch from svn/trunk (or a branch), hack away, merge back into svn/trunk, then dcommit? I understand that svn users will see the same mess that merges in svn pre 1.5.x have always been, but are there any other drawbacks? That last sentence worries me, too. Do people routinely do these kinds of things?</p>
|
[
{
"answer_id": 190447,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": false,
"text": "git svn dcommit -n"
},
{
"answer_id": 1526673,
"author": "luntain",
"author_id": 5978,
"author_profile": "https://Stackoverflow.com/users/5978",
"pm_score": 3,
"selected": false,
"text": "git svn fetch\ngit checkout remotes/trunk -b big-merge\ngit merge --squash svn-branch\n git commit\n"
},
{
"answer_id": 2423689,
"author": "JoeyJ",
"author_id": 291324,
"author_profile": "https://Stackoverflow.com/users/291324",
"pm_score": 3,
"selected": false,
"text": "git rebase master topic\n"
},
{
"answer_id": 4238528,
"author": "Sebastien Varrette",
"author_id": 492649,
"author_profile": "https://Stackoverflow.com/users/492649",
"pm_score": 8,
"selected": true,
"text": "--no-ff -s trunk/ branches/ tags/ git svn clone [-s] <svn-url>\n -b git checkout -b work\n -s ...\n(work)$> git commit -s -m \"msg 1\"\n...\n(work)$> git commit -s -m \"msg 2\"\n...\n(work)$> git commit -s -m \"msg 3\"\n (work)$> git stash\n (work)$> git checkout master\n(master)$> git svn rebase\n (master)$> git checkout work\n(work)$> git rebase master\n (work)$> git log --graph --oneline --decorate\n --no-ff (work)$> git checkout master\n(master)$> git merge --no-ff work\n (master)$> git log --graph --oneline --decorate\n* 56a779b (work, master) Merge branch 'work'\n|\\ \n| * af6f7ae msg 3\n| * 8750643 msg 2\n| * 08464ae msg 1\n|/ \n* 21e20fa (git-svn) last svn commit\n amend (master)$> git commit --amend\n (master)$> git svn dcommit\n (master)$> git checkout work\n(work)$> git stash pop\n"
},
{
"answer_id": 4546438,
"author": "Yaakov Belch",
"author_id": 104746,
"author_profile": "https://Stackoverflow.com/users/104746",
"pm_score": 5,
"selected": false,
"text": "$> git svn clone <svn-repository-url> <local-directory>\n $> git checkout master\n$> git svn rebase\n $> git checkout -b work\n $> git commit -am '-- finished a little piece of work'\n $> git log\n $> git rebase -i 74e4068360e34b2ccf0c5869703af458cde0cdcb\n $> git checkout master\n$> git svn rebase\n $> git checkout master\n$> git merge work # (1) merge your 'work' into 'master'\n$> git branch -d work # (2) remove the work branch immediately after merging\n$> git svn dcommit # (3) push your changes to the svn repository\n $> git checkout -b work\n$> git branch # show my branches:\n master\n* work\n $> git checkout master\n$> git svn rebase # 'svn pull' changes\n$> git checkout work # go to my work\n$> git checkout -b integration # make a copy of the branch\n$> git merge master # integrate my changes with theirs\n$> ... check/fix/debug ...\n$> ... rewrite history with rebase -i if needed\n\n$> git checkout master # try again to push my changes\n$> git svn rebase # hopefully no further changes to merge\n$> git merge integration # (1) merge your work with theirs\n$> git branch -d work # (2) remove branches that are merged\n$> git branch -d integration # (2) remove branches that are merged\n$> git svn dcommit # (3) push your changes to the svn repository\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5179/"
] |
190,450
|
<p>Up until recently, I've been storing multiple values into different hashes with the same keys as follows:</p>
<pre><code>%boss = (
"Allan" => "George",
"Bob" => "George",
"George" => "lisa" );
%status = (
"Allan" => "Contractor",
"Bob" => "Part-time",
"George" => "Full-time" );
</code></pre>
<p>and then I can reference <code>$boss("Bob")</code> and <code>$status("Bob")</code> but this gets unwieldy if there's a lot of properties each key can have and I have to worry about keeping the hashes in sync.</p>
<p>Is there a better way for storing multiple values in a hash? I could store the values as</p>
<pre><code> "Bob" => "George:Part-time"
</code></pre>
<p>and then disassemble the strings with split, but there must be a more elegant way.</p>
|
[
{
"answer_id": 190467,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "~> more test.pl\n%chums = ( \"Allan\" => {\"Boss\" => \"George\", \"Status\" => \"Contractor\"},\n \"Bob\" => {\"Boss\" => \"Peter\", \"Status\" => \"Part-time\"} );\n\nprint $chums{\"Allan\"}{\"Boss\"}.\"\\n\";\nprint $chums{\"Bob\"}{\"Boss\"}.\"\\n\";\nprint $chums{\"Bob\"}{\"Status\"}.\"\\n\";\n$chums{\"Bob\"}{\"Wife\"} = \"Pam\";\nprint $chums{\"Bob\"}{\"Wife\"}.\"\\n\";\n\n~> perl test.pl\nGeorge\nPeter\nPart-time\nPam\n"
},
{
"answer_id": 190479,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 2,
"selected": false,
"text": "my %employees = (\n \"Allan\" => { \"Boss\" => \"George\", \"Status\" => \"Contractor\" },\n);\n\nprint $employees{\"Allan\"}{\"Boss\"}, \"\\n\";\n"
},
{
"answer_id": 190497,
"author": "tsee",
"author_id": 13164,
"author_profile": "https://Stackoverflow.com/users/13164",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/perl\npackage Employee;\nuse Moose;\nhas 'name' => ( is => 'rw', isa => 'Str' );\n\n# should really use a Status class\nhas 'status' => ( is => 'rw', isa => 'Str' );\n\nhas 'superior' => (\n is => 'rw',\n isa => 'Employee',\n default => undef,\n);\n\n###############\npackage main;\nuse strict;\nuse warnings;\n\nmy %employees; # maybe use a class for this, too\n\n$employees{George} = Employee->new(\n name => 'George',\n status => 'Boss',\n);\n\n$employees{Allan} = Employee->new(\n name => 'Allan',\n status => 'Contractor',\n superior => $employees{George},\n);\n\nprint $employees{Allan}->superior->name, \"\\n\";\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14860/"
] |
190,454
|
<p>I have a very large (~6GB) SVN repository, for which I've written a batch file script to do an incremental backup each day. The script checks when the last backup was run and dumps only the revisions since then.</p>
<p>The files are named: <code>backup-{lower_revision}-{higher_revision}.svn</code> eg: <code>backup-156-162.svn</code>, <code>backup-163-170.svn</code>.</p>
<p>This means that I have quite a lot of small dump files, which I guess is fine (better than a lot of 6GB dump files), but I'm a little bit worried about how much work it would be to restore from these backups should I need to.</p>
<p>To reduce the total number of files, I've taken to doing a full dump on the first of each month, but still, should I need to restore on the 30th, that's gonna be 30 dump files which could take a while.</p>
<p>What I have been considering is:</p>
<ul>
<li>Manual:<br>
<code>svnadmin load c:\myRepo < backup-1-10.svn</code><br>
<em>wait</em><br>
<code>svnadmin load c:\myRepo < backup-11-24.svn</code><br>
<em>wait</em><br>
etc...</li>
<li>Batch file to make the above process a bit less tedious</li>
<li>Appending each of the files together and doing one load (if that is even possible?)</li>
</ul>
<p>What would be the best way to work with these files, should I need to restore?</p>
<p><em>ps: the OS is Windows</em></p>
|
[
{
"answer_id": 3315992,
"author": "PuO2",
"author_id": 399977,
"author_profile": "https://Stackoverflow.com/users/399977",
"pm_score": 0,
"selected": false,
"text": "svn look youngest [live_repo]\nsvn look youngest [copied_repo]\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
190,461
|
<p>I asked <a href="https://stackoverflow.com/questions/188043/security-crytography-stupid-challege-response-protocol">here</a> about a protocol that I was asked to implement, and how secure it was. Since it seemed clear from the very beginning that it was shit. Being so I ask:</p>
<p>Can you guys point me to some very simple login protocol (I am null at cryptography systems)?? I am developing both server and client side of the application and I have my own messengering system, so I have enough freedom.</p>
<p>Only 2 special characteristics for your suggestions.</p>
<ol>
<li><p>Simple: the network this application is going to run over is not specially insecure and I only want to avoid the sending of the password in plain text</p></li>
<li><p>If possible, not a too long interchange of messages. The shorter, the better.</p></li>
</ol>
|
[
{
"answer_id": 195444,
"author": "Huibert Gill",
"author_id": 1254442,
"author_profile": "https://Stackoverflow.com/users/1254442",
"pm_score": 2,
"selected": false,
"text": "md5(login_name + domain_or_appname_salt + password);\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366094/"
] |
190,464
|
<p>This is a pretty-much theoretical question, but..</p>
<p><strong>How much of an operating system could be written in a language like Python, Ruby, Perl, or Lisp, Haskell etc?</strong></p>
<p>It seems like a lot of the stuff like init.d could trivially be done in a scripting language. One of the firewall-device-OS's (<a href="http://m0n0.ch/wall/" rel="noreferrer">m0n0wall</a>) uses PHP for its system-configuration (including on boot). And one could argue that "emacs is an OS, mostly written in Lisp"..</p>
<p>Of course there are bits that would have to be assembly/C, but how much could be regular .py/rb/.pl/.el/.hk files..? It might not have the best performance, but it would be, by far, the most easiest-to-modify OS ever...</p>
|
[
{
"answer_id": 190482,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "sh sh"
},
{
"answer_id": 1678386,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": 3,
"selected": false,
"text": "asm = MetaASM()\nasm.r1 = 1234\nasm.r2 = r1 + 5\nasm.io.out(r1)\n asm = ASM(\"IA-32\")\nasm.xor(asm.eax, asm.eax)\nasm.cr0 = asm.eax\nasm.invtlb\nasm.fs.0x00123456 = asm.eax\nasm.al = 123\nasm.dword.ptr.eax = 1234 # mov dword ptr [eax], 1234\nasm.push(asm.eax)\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
190,476
|
<p>I have those maps in my repository. </p>
<pre><code>public IQueryable<AwType> GetAwTypes()
{
return from awt in _db.AwTypes
select new AwType
{
Id = awt.Id,
Header = awt.Header,
Description = awt.Description
};
}
public IQueryable<Aw> GetAws()
{
return from aw in _db.Aws
select new Aw
{
Id = aw.Id,
Bw = (from bw in GetBws()
where bw.Id == aw.Bw
select bw
).SingleOrDefault(),
AwType = (from awt in GetAwTypes()
where awt.Id == awAwType
select awt
).SingleOrDefault(),
AwAttribute = aw.AwAttribute
};
}
</code></pre>
<p>In service I want to get count of Bws grouped by AwType as <code>List<KeyValuePair<AwType, int>></code>.
When I call that linq query :</p>
<pre><code>var awGroups = from aw in _repository.GetAws()
group aw by aw.AwType into newGroup
select newGroup;
List<KeyValuePair<AwType, int>> RetGroups = new List<KeyValuePair<AwType, int>>();
foreach (var group in awGroups)
{
RetGroups.Add(new KeyValuePair<AwType, int>(group.Key, group.Count()));
}
return RetGroups;
</code></pre>
<p>I get an error that is saying I can't group by on an object I have to group by a scalar value like aw.AwType.Id.</p>
<p>Is there a way to get "AwType, int" pairs in one call?</p>
|
[
{
"answer_id": 198446,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": true,
"text": "var awGroups = from aw in _repository.GetAws()\ngroup aw by aw.AwType.ID into newGroup //changed to group on ID\nselect newGroup;\n\nList<KeyValuePair<AwType, int>> RetGroups = new List<KeyValuePair<AwType, int>>();\nforeach (var group in awGroups)\n{\n //changed to get the first element of the group and examine its AwType\n RetGroups.Add(new KeyValuePair<AwType, int>(group.First().AwType, group.Count()));\n}\nreturn RetGroups;\n"
},
{
"answer_id": 198523,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "var awGroups = from aw in _repository.GetAws()\ngroup aw by aw.AwType.Id, aw.AwType.Header, aw.AwType.Description into newGroup\nselect newGroup;\n var awGroups = from aw in _repository.GetAws()\ngroup aw by aw.AwType.Id into newGroup\nselect newGroup;\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11374/"
] |
190,480
|
<p>How to to configure apache + mod_lisp + clisp and set up a "Hello World!"? I couldn't find any complete howto on the subject. Thanks.</p>
<p>Edit: Vebjorn's solution works, but then I don't how to code the "hello world!". Can anyone tell me how to proceed? There's something like SWANKing the clisp, then connect to it with SLIME, but then when I launch mod_lisp's demo, the test page is not served and my slime doesn't return?</p>
<p>Thanks again.</p>
|
[
{
"answer_id": 190567,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 3,
"selected": false,
"text": "sudo apxs -i -c mod_lisp.c httpd.conf sudo apachectl restart"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26416/"
] |
190,493
|
<p>I am trying to figure out how to add a custom control to the iPhone MoviePlayer.
For an example of what I am trying to do see the following image.</p>
<p><img src="https://i.stack.imgur.com/Zt5MG.jpg" alt="alt text"></p>
<p>I am trying to add something like the controls on the right and left of the basic movie controls.</p>
<p>I had done this in the Open SDK by adding a subclass to the playerview, but now in the official SDK and Apple moving to MPMoviePlayerController I am not sure how to do it.</p>
<p>Also with my old 1.x firmware way it required me to capture touch events and hide/show the control myself. I am hoping there is a way that would do this with the standard controls, but if not, that is fine.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 194646,
"author": "kdbdallas",
"author_id": 26728,
"author_profile": "https://Stackoverflow.com/users/26728",
"pm_score": 4,
"selected": true,
"text": "id vvController = [theMovie videoViewController];\n[[vvController _overlayView] addSubview:mainView];\n"
},
{
"answer_id": 1616670,
"author": "sfjava",
"author_id": 158852,
"author_profile": "https://Stackoverflow.com/users/158852",
"pm_score": 3,
"selected": false,
"text": "// use slight \"hack\" to get our (parent) movie-player window, should always (?) be the UIWindow at index = 1\n//\nUIWindow *moviePlayerWindow= [[[UIApplication sharedApplication] windows] objectAtIndex:1];\n\nmyOverlayView.center = CGPointMake(\n moviePlayerWindow.bounds.size.width - (myOverlayView.bounds.size.height / 2) - myOverlayView.display_origin.y,\n moviePlayerWindow.center.y\n ); // center our overlay-view\n\nmyOverlayView.hidden = NO; // and show it\n\nif( [moviePlayerWindow viewWithTag: MY_OVERLAY_VIEW_TAG] == nil ) {\n // haven't added our overlay-view as a sub-view to the main MoviePlayer window yet... so do that now\n myOverlayView.tag = MY_OVERLAY_VIEW_TAG;\n [moviePlayerWindow addSubview: myOverlayView];\n}\n[moviePlayerWindow bringSubviewToFront: myOverlayView]; // in any case, bring it to the foreground\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26728/"
] |
190,504
|
<p>I've been working on a project in Delphi 7 where I wanted to have forms inherit components from other forms. I was able to get this working, but came across the following issues (and I'm going to post the solutions to hopefully help others in the future):</p>
<ol>
<li>In the .pas file of a form, I would change the form to inherit from some other form, but it wouldn't get the components from the ancestor form.</li>
<li>For certain descendant forms, I would get the following error message when opening the form at design time: "Error creating form: Ancestor for 'TAncestorForm' not found." I would have to first manually open the ancestor form, and then I could open the descendant form.</li>
</ol>
|
[
{
"answer_id": 190506,
"author": "Liron Yahdav",
"author_id": 62,
"author_profile": "https://Stackoverflow.com/users/62",
"pm_score": 6,
"selected": true,
"text": "type TMyForm = class(TAncestorForm) inherited object inherited MyForm: TMyForm var AncestorForm: TAncestorForm; uses unAncestor in 'unAncestor.pas' {AncestorForm}"
},
{
"answer_id": 1614977,
"author": "Unknown Coder",
"author_id": 195500,
"author_profile": "https://Stackoverflow.com/users/195500",
"pm_score": 1,
"selected": false,
"text": "uses\n Forms,\n ancestorFrame in 'ancestorFrame.pas' {AncestorFrame : TFrame},\n frame1Unit in 'frame1Unit.pas' {frame1:TFrame},\n frame2Unit in 'frame2Unit .pas' {frame2:TFrame},\n <DCCReference include=\"frame1Unit.pas\">\n <Form>frame1</Form>\n <DesignClass>TFrame</DesignClass>\n</DCCReference>\n TFrame1 = class(TAncestorFrame)\n inherited Frame1:TFrame1\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62/"
] |
190,524
|
<p>I have created some extra functionality on my Linq-to-SQL classes to make things easier as I develop my applications. For example I have defined a property that retrieves active contracts from a list of contracts. However if I try to use this property in a lambda expression or in general in a query it either throws an exception that there is no SQL statement matching that property or it generates one query per item (= a lot of roundtrips to the server).</p>
<p>The queries themselves are not overly complex f.ex:</p>
<pre><code>var activeContracts = customer.Contracts.Where(w => w.ContractEndDate == null);
</code></pre>
<p>Whereas I would like it to read as:</p>
<pre><code>var activeContracts = customer.ActiveContracts;
</code></pre>
<p>The main reason for me doing this is because it will minimize logical errors on my part and if I in the future want to change what defines an active contract I don't have to redo a lot of code.</p>
<p>Is there a way to specify on a property what SQL it should genereate. Or is there a way to make sure it is usable in a query like below?</p>
<pre><code>var singleContractCustomers = db.Customers.Where(w => w.ActiveContracts.Count() == 1);
</code></pre>
|
[
{
"answer_id": 190655,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": " public static Expression<Func<Customer, bool>> HasActiveContract\n {\n get { return cust => cust.Contracts.Count() == 1; }\n }\n var filtered = db.Customers.Where(Customer.HasActiveContract);\n public IQueryable<Customer> CustomersWithActiveContract\n {\n get { return Customers.Where(Customer.HasActiveContract); }\n }\n"
},
{
"answer_id": 190972,
"author": "Kristoffer L",
"author_id": 26746,
"author_profile": "https://Stackoverflow.com/users/26746",
"pm_score": 1,
"selected": false,
"text": "{SELECT [t0].[CustomerID], [t0].[cFirstName], [t0].[cLastName]\nFROM [dbo].[Customers] AS [t0]\nWHERE ((\n SELECT COUNT(*)\n FROM [dbo].[Contracts] AS [t1]\n WHERE (([t1].[ContractEndDate] > @p0) OR ([t1].[ContractEndDate] IS NULL)) AND ([t1].[cId] = [t0].[cId])\n )) > @p1\n}\n"
},
{
"answer_id": 13400298,
"author": "luksan",
"author_id": 166131,
"author_profile": "https://Stackoverflow.com/users/166131",
"pm_score": 1,
"selected": false,
"text": "partial class Customer\n{\n private static readonly CompiledExpression<Employee,IEnumerable<Contract>> activeContractsExpression\n = DefaultTranslationOf<Customer>\n .Property(c => c.ActiveContracts)\n .Is(c => c.Contracts.Where(x => x.ContractEndDate == null));\n\n public IEnumerable<Contract> ActiveContracts\n {\n get \n { \n // This is only called when you access your property outside a query\n return activeContractsExpression.Evaluate(this);\n }\n }\n}\n var singleContractCustomers = db.Customers.WithTranslations()\n .Where(w => w.ActiveContracts.Count() == 1);\n WithTranslations() IQueryable Microsoft.Linq.Translations.Auto System.Linq WithTranslations()"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26746/"
] |
190,525
|
<p>I'm not sure how familiar people are with the hobbit monitoring system - <a href="http://hobbitmon.sourceforge.net/" rel="nofollow noreferrer">http://hobbitmon.sourceforge.net/</a> - but I've got a tricky question.</p>
<p>I've got a custom test, which returns two NCV values. One value normally returns ~300 milliseconds, the other one returns 500 000 euro. Obviously, these two values don't graph very well together. :)</p>
<p>Question is, can hobbit display two graphs for this one test? If so, how do I do it?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 190655,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": " public static Expression<Func<Customer, bool>> HasActiveContract\n {\n get { return cust => cust.Contracts.Count() == 1; }\n }\n var filtered = db.Customers.Where(Customer.HasActiveContract);\n public IQueryable<Customer> CustomersWithActiveContract\n {\n get { return Customers.Where(Customer.HasActiveContract); }\n }\n"
},
{
"answer_id": 190972,
"author": "Kristoffer L",
"author_id": 26746,
"author_profile": "https://Stackoverflow.com/users/26746",
"pm_score": 1,
"selected": false,
"text": "{SELECT [t0].[CustomerID], [t0].[cFirstName], [t0].[cLastName]\nFROM [dbo].[Customers] AS [t0]\nWHERE ((\n SELECT COUNT(*)\n FROM [dbo].[Contracts] AS [t1]\n WHERE (([t1].[ContractEndDate] > @p0) OR ([t1].[ContractEndDate] IS NULL)) AND ([t1].[cId] = [t0].[cId])\n )) > @p1\n}\n"
},
{
"answer_id": 13400298,
"author": "luksan",
"author_id": 166131,
"author_profile": "https://Stackoverflow.com/users/166131",
"pm_score": 1,
"selected": false,
"text": "partial class Customer\n{\n private static readonly CompiledExpression<Employee,IEnumerable<Contract>> activeContractsExpression\n = DefaultTranslationOf<Customer>\n .Property(c => c.ActiveContracts)\n .Is(c => c.Contracts.Where(x => x.ContractEndDate == null));\n\n public IEnumerable<Contract> ActiveContracts\n {\n get \n { \n // This is only called when you access your property outside a query\n return activeContractsExpression.Evaluate(this);\n }\n }\n}\n var singleContractCustomers = db.Customers.WithTranslations()\n .Where(w => w.ActiveContracts.Count() == 1);\n WithTranslations() IQueryable Microsoft.Linq.Translations.Auto System.Linq WithTranslations()"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18673/"
] |
190,542
|
<p>I'm using Java for accessing Alfresco content server via it's web service API for importing some content into it. Content should have some NamedValue properties set to UTF-8(cyrillic) string. I keep getting the Sax parser exception:</p>
<pre><code>org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x1b) was found in the element content of the document.
</code></pre>
<p>The code looks something like this:</p>
<pre><code>NamedValue[] namedValueProperties = new NamedValue[2];
namedValueProperties[0] = Utils.createNamedValue(Constants.PROP_NAME, name );
namedValueProperties[1] = Utils.createNamedValue("{my.custom.model}myProperty", cyrillicString);
CMLCreate create = new CMLCreate("1", parentReference, null, null, null, documentType, namedValueProperties);
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
UpdateResult[] results = null;
try {
results = WebServiceFactory.getRepositoryService().update(cml);
} catch (...)
Here comes the "org.xml.sax.SAXParseException"
}
</code></pre>
<p>Does anyone know how to solve this problem?</p>
|
[
{
"answer_id": 197082,
"author": "Aleksandar Marinkovic",
"author_id": 26747,
"author_profile": "https://Stackoverflow.com/users/26747",
"pm_score": 3,
"selected": true,
"text": "alfresco-web-service-client.jar bcprov-jdk15-136.jar xmlsec-1.4.0.jar bcprov-jdk15-137.jar xmlsec-1.4.1.jar"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26747/"
] |
190,543
|
<p>Is it possible to programmatically, or otherwise, increase the width of the Windows console window? Or do I need to create a wrapper program that looks and acts like the console somehow? Are there any programs around that do this already? I use Cygwin extensively in my development, and it seems a little ridiculous to me that all console windows in Windows are width limited.</p>
<p>If it matters at all, I'm running Windows XP.</p>
|
[
{
"answer_id": 190603,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 1,
"selected": false,
"text": "size"
},
{
"answer_id": 8848967,
"author": "rob",
"author_id": 799759,
"author_profile": "https://Stackoverflow.com/users/799759",
"pm_score": 2,
"selected": false,
"text": "mode \n system(\"mode... \n"
},
{
"answer_id": 9488388,
"author": "Sergey",
"author_id": 739731,
"author_profile": "https://Stackoverflow.com/users/739731",
"pm_score": 3,
"selected": false,
"text": "system(\"mode 45, 20\");\n system(\"mode CON: COLS=120\");\n"
},
{
"answer_id": 11121214,
"author": "James",
"author_id": 1469461,
"author_profile": "https://Stackoverflow.com/users/1469461",
"pm_score": 1,
"selected": false,
"text": "@echo off\nsetlocal enabledelayedexpansion\nREM Changing working folder back to current directory\n%~d0\nCD %~dp0\nREM Folder changed\nbash --login -i -c \"cd {insert_directory_name_here} && exec ./execution-file-here\"\ncls\nexit 1\n"
},
{
"answer_id": 30919157,
"author": "DeveloperDan",
"author_id": 381082,
"author_profile": "https://Stackoverflow.com/users/381082",
"pm_score": 3,
"selected": false,
"text": "static void setConsoleSize()\n {\n System.Console.SetWindowPosition(0,0); // sets window position to upper left\n System.Console.SetBufferSize(200,300); // make sure buffer is bigger than window\n System.Console.SetWindowSize(122,54); //set window size to almost full screen \n //width - maxSet(127,57) (width, height)\n\n //System.Console.ResetColor(); //resets fore and background colors to default\n\n } // End setConsoleSize()\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
190,553
|
<p>In the following code, both <code>amp_swap()</code> and <code>star_swap()</code> seems to be doing the same thing. So why will someone prefer to use one over the other? Which one is the preferred notation and why? Or is it just a matter of taste?</p>
<pre><code>#include <iostream>
using namespace std;
void amp_swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
void star_swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int a = 10, b = 20;
cout << "Using amp_swap(): " << endl;
amp_swap(a, b);
cout << "a = " << a << ", b = " << b << endl;
cout << "Using star_swap(): " << endl;
star_swap(&a, &b);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
</code></pre>
<p>Thanks for your time!</p>
<hr>
<p>See Also</p>
<p><H2><a href="https://stackoverflow.com/questions/57483"><strong>Difference between pointer variable and reference variable in C++</strong></a></H2></p>
|
[
{
"answer_id": 190564,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "(int *param) (int ¶m)"
},
{
"answer_id": 190565,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 5,
"selected": true,
"text": "star_swap(NULL, NULL);\n amp_swap(NULL, NULL); // This won't compile\n"
},
{
"answer_id": 190568,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "amp_swap() x y x y int *const x"
},
{
"answer_id": 190579,
"author": "m_pGladiator",
"author_id": 446104,
"author_profile": "https://Stackoverflow.com/users/446104",
"pm_score": 2,
"selected": false,
"text": "amp_swap star_swap & amp_swap"
},
{
"answer_id": 190589,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 2,
"selected": false,
"text": "int &ri = i; ri = j;"
},
{
"answer_id": 190607,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "swap(a, b);\nswap(&a, &b); // This cries “will modify arguments” loud and clear.\n swap ref swap(ref a, ref b);\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7205/"
] |
190,559
|
<p><em>When using threads I sometimes visualise them as weaving together 3 or more dimensional interconnections between Objects in a Spatial context. This isn't a general use case scenario, but for what I do it is a useful way to think about it.</em></p>
<h3>Are there any APIs which you use which aid threading?</h3>
<h3>Have you used threads in a manner which doesn't conceptualise as thread being a process?</h3>
|
[
{
"answer_id": 190651,
"author": "Chris Vest",
"author_id": 13251,
"author_profile": "https://Stackoverflow.com/users/13251",
"pm_score": 5,
"selected": true,
"text": "java.util.concurrent"
},
{
"answer_id": 705084,
"author": "Yuval Adam",
"author_id": 24545,
"author_profile": "https://Stackoverflow.com/users/24545",
"pm_score": 3,
"selected": false,
"text": "java.util.concurrent Runnable Thread Executors Runnable Semaphore wait() notify()"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
190,560
|
<p>I am trying to animate a change in backgroundColor using jQuery on mouseover.</p>
<p>I have checked some example and I seem to have it right, it works with other properties like fontSize, but with backgroundColor I get and "Invalid Property" js error.
The element I am working with is a div.</p>
<pre><code>$(".usercontent").mouseover(function() {
$(this).animate({ backgroundColor: "olive" }, "slow");
});
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 590065,
"author": "menardmam",
"author_id": 71830,
"author_profile": "https://Stackoverflow.com/users/71830",
"pm_score": 6,
"selected": false,
"text": "<!-- include Google's AJAX API loader -->\n<script src=\"http://www.google.com/jsapi\"></script>\n<!-- load JQuery and UI from Google (need to use UI to animate colors) -->\n<script type=\"text/javascript\">\ngoogle.load(\"jqueryui\", \"1.5.2\");\n</script>\n\n\n<script type=\"text/javascript\">\n$(document).ready(function() {\n$('#menu ul li.item').hover(\n function() {\n $(this).stop().animate({backgroundColor:'#4E1402'}, 300);\n }, function () {\n $(this).stop().animate({backgroundColor:'#943D20'}, 100);\n });\n});\n</script>\n"
},
{
"answer_id": 1184410,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "aqua:[0,255,255],\nazure:[240,255,255],\nbeige:[245,245,220],\nblack:[0,0,0],\nblue:[0,0,255],\nbrown:[165,42,42],\ncyan:[0,255,255],\ndarkblue:[0,0,139],\ndarkcyan:[0,139,139],\ndarkgrey:[169,169,169],\ndarkgreen:[0,100,0],\ndarkkhaki:[189,183,107],\ndarkmagenta:[139,0,139],\ndarkolivegreen:[85,107,47],\ndarkorange:[255,140,0],\ndarkorchid:[153,50,204],\ndarkred:[139,0,0],\ndarksalmon:[233,150,122],\ndarkviolet:[148,0,211],\nfuchsia:[255,0,255],\ngold:[255,215,0],\ngreen:[0,128,0],\nindigo:[75,0,130],\nkhaki:[240,230,140],\nlightblue:[173,216,230],\nlightcyan:[224,255,255],\nlightgreen:[144,238,144],\nlightgrey:[211,211,211],\nlightpink:[255,182,193],\nlightyellow:[255,255,224],\nlime:[0,255,0],\nmagenta:[255,0,255],\nmaroon:[128,0,0],\nnavy:[0,0,128],\nolive:[128,128,0],\norange:[255,165,0],\npink:[255,192,203],\npurple:[128,0,128],\nviolet:[128,0,128],\nred:[255,0,0],\nsilver:[192,192,192],\nwhite:[255,255,255],\nyellow:[255,255,0]\n"
},
{
"answer_id": 2302005,
"author": "Andrew",
"author_id": 148346,
"author_profile": "https://Stackoverflow.com/users/148346",
"pm_score": 9,
"selected": true,
"text": "(function (d) {\n d.each([\"backgroundColor\", \"borderBottomColor\", \"borderLeftColor\", \"borderRightColor\", \"borderTopColor\", \"color\", \"outlineColor\"], function (f, e) {\n d.fx.step[e] = function (g) {\n if (!g.colorInit) {\n g.start = c(g.elem, e);\n g.end = b(g.end);\n g.colorInit = true\n }\n g.elem.style[e] = \"rgb(\" + [Math.max(Math.min(parseInt((g.pos * (g.end[0] - g.start[0])) + g.start[0]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[1] - g.start[1])) + g.start[1]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[2] - g.start[2])) + g.start[2]), 255), 0)].join(\",\") + \")\"\n }\n });\n\n function b(f) {\n var e;\n if (f && f.constructor == Array && f.length == 3) {\n return f\n }\n if (e = /rgb\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)/.exec(f)) {\n return [parseInt(e[1]), parseInt(e[2]), parseInt(e[3])]\n }\n if (e = /rgb\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)/.exec(f)) {\n return [parseFloat(e[1]) * 2.55, parseFloat(e[2]) * 2.55, parseFloat(e[3]) * 2.55]\n }\n if (e = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)) {\n return [parseInt(e[1], 16), parseInt(e[2], 16), parseInt(e[3], 16)]\n }\n if (e = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)) {\n return [parseInt(e[1] + e[1], 16), parseInt(e[2] + e[2], 16), parseInt(e[3] + e[3], 16)]\n }\n if (e = /rgba\\(0, 0, 0, 0\\)/.exec(f)) {\n return a.transparent\n }\n return a[d.trim(f).toLowerCase()]\n }\n function c(g, e) {\n var f;\n do {\n f = d.css(g, e);\n if (f != \"\" && f != \"transparent\" || d.nodeName(g, \"body\")) {\n break\n }\n e = \"backgroundColor\"\n } while (g = g.parentNode);\n return b(f)\n }\n var a = {\n aqua: [0, 255, 255],\n azure: [240, 255, 255],\n beige: [245, 245, 220],\n black: [0, 0, 0],\n blue: [0, 0, 255],\n brown: [165, 42, 42],\n cyan: [0, 255, 255],\n darkblue: [0, 0, 139],\n darkcyan: [0, 139, 139],\n darkgrey: [169, 169, 169],\n darkgreen: [0, 100, 0],\n darkkhaki: [189, 183, 107],\n darkmagenta: [139, 0, 139],\n darkolivegreen: [85, 107, 47],\n darkorange: [255, 140, 0],\n darkorchid: [153, 50, 204],\n darkred: [139, 0, 0],\n darksalmon: [233, 150, 122],\n darkviolet: [148, 0, 211],\n fuchsia: [255, 0, 255],\n gold: [255, 215, 0],\n green: [0, 128, 0],\n indigo: [75, 0, 130],\n khaki: [240, 230, 140],\n lightblue: [173, 216, 230],\n lightcyan: [224, 255, 255],\n lightgreen: [144, 238, 144],\n lightgrey: [211, 211, 211],\n lightpink: [255, 182, 193],\n lightyellow: [255, 255, 224],\n lime: [0, 255, 0],\n magenta: [255, 0, 255],\n maroon: [128, 0, 0],\n navy: [0, 0, 128],\n olive: [128, 128, 0],\n orange: [255, 165, 0],\n pink: [255, 192, 203],\n purple: [128, 0, 128],\n violet: [128, 0, 128],\n red: [255, 0, 0],\n silver: [192, 192, 192],\n white: [255, 255, 255],\n yellow: [255, 255, 0],\n transparent: [255, 255, 255]\n }\n})(jQuery);\n"
},
{
"answer_id": 3895425,
"author": "Peter Ajtai",
"author_id": 186636,
"author_profile": "https://Stackoverflow.com/users/186636",
"pm_score": 4,
"selected": false,
"text": "$(function(){\n var $mytd = $('#mytd'), $elie = $mytd.clone(), os = $mytd.offset();\n\n // Create clone w other bg and position it on original\n $elie.toggleClass(\"class1, class2\").appendTo(\"body\")\n .offset({top: os.top, left: os.left}).hide();\n\n $mytd.mouseover(function() { \n // Fade original\n $mytd.fadeOut(3000, function() {\n $mytd.toggleClass(\"class1, class2\").show();\n $elie.toggleClass(\"class1, class2\").hide(); \n });\n // Show clone at same time\n $elie.fadeIn(3000);\n });\n});\n .toggleClass() .offset() .fadeIn() .fadeOut()"
},
{
"answer_id": 4087898,
"author": "Andy",
"author_id": 104247,
"author_profile": "https://Stackoverflow.com/users/104247",
"pm_score": 3,
"selected": false,
"text": "jQuery(element).animate({ backgroundColor: \"#FCFCD8\" },1).delay(1000).animate({ backgroundColor: \"#EFEAEA\" }, 1500);\n"
},
{
"answer_id": 4611026,
"author": "Orhaan",
"author_id": 287084,
"author_profile": "https://Stackoverflow.com/users/287084",
"pm_score": 1,
"selected": false,
"text": "$(\"#container\").colorBlend([{\n colorList:[\"white\", \"yellow\"], \n param:\"background-color\",\n cycles: 1,\n duration: 500\n}]);\n"
},
{
"answer_id": 5086660,
"author": "Mary Daisy Sanchez",
"author_id": 560756,
"author_profile": "https://Stackoverflow.com/users/560756",
"pm_score": 0,
"selected": false,
"text": "jQuery(\".usercontent\").hover(function() {\n jQuery(this).animate({backgroundColor:\"pink\"}, \"slow\");\n},function(){\n jQuery(this).animate({backgroundColor:\"white\"}, \"slow\");\n});\n jQuery(\".usercontent\").hover(function() {\n\n jQuery(this).fadeout(\"slow\",function(){\n jQuery(this).animate({\"color\",\"yellow\"}, \"slow\");\n });\n});\n"
},
{
"answer_id": 6993089,
"author": "Faraz Kelhini",
"author_id": 530659,
"author_profile": "https://Stackoverflow.com/users/530659",
"pm_score": 4,
"selected": false,
"text": "/******************************************************************************/\n/****************************** COLOR ANIMATIONS ******************************/\n/******************************************************************************/\n\n// override the animation for color styles\n$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor',\n 'borderRightColor', 'borderTopColor', 'borderColor', 'color', 'outlineColor'],\nfunction(i, attr) {\n $.fx.step[attr] = function(fx) {\n if (!fx.colorInit) {\n fx.start = getColor(fx.elem, attr);\n fx.end = getRGB(fx.end);\n fx.colorInit = true;\n }\n\n fx.elem.style[attr] = 'rgb(' +\n Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0], 10), 255), 0) + ',' +\n Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1], 10), 255), 0) + ',' +\n Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2], 10), 255), 0) + ')';\n };\n});\n\n// Color Conversion functions from highlightFade\n// By Blair Mitchelmore\n// http://jquery.offput.ca/highlightFade/\n\n// Parse strings looking for color tuples [255,255,255]\nfunction getRGB(color) {\n var result;\n\n // Check if we're already dealing with an array of colors\n if ( color && color.constructor == Array && color.length == 3 )\n return color;\n\n // Look for rgb(num,num,num)\n if (result = /rgb\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)/.exec(color))\n return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)];\n\n // Look for rgb(num%,num%,num%)\n if (result = /rgb\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)/.exec(color))\n return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];\n\n // Look for #a0b1c2\n if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))\n return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];\n\n // Look for #fff\n if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))\n return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];\n\n // Look for rgba(0, 0, 0, 0) == transparent in Safari 3\n if (result = /rgba\\(0, 0, 0, 0\\)/.exec(color))\n return colors['transparent'];\n\n // Otherwise, we're most likely dealing with a named color\n return colors[$.trim(color).toLowerCase()];\n}\n\nfunction getColor(elem, attr) {\n var color;\n\n do {\n color = $.curCSS(elem, attr);\n\n // Keep going until we find an element that has color, or we hit the body\n if ( color != '' && color != 'transparent' || $.nodeName(elem, \"body\") )\n break;\n\n attr = \"backgroundColor\";\n } while ( elem = elem.parentNode );\n\n return getRGB(color);\n};\n $.each([\"backgroundColor\",\"borderBottomColor\",\"borderLeftColor\",\"borderRightColor\",\"borderTopColor\",\"borderColor\",\"color\",\"outlineColor\"],function(b,a){$.fx.step[a]=function(c){if(!c.colorInit){c.start=getColor(c.elem,a);c.end=getRGB(c.end);c.colorInit=true}c.elem.style[a]=\"rgb(\"+Math.max(Math.min(parseInt((c.pos*(c.end[0]-c.start[0]))+c.start[0],10),255),0)+\",\"+Math.max(Math.min(parseInt((c.pos*(c.end[1]-c.start[1]))+c.start[1],10),255),0)+\",\"+Math.max(Math.min(parseInt((c.pos*(c.end[2]-c.start[2]))+c.start[2],10),255),0)+\")\"}});function getRGB(b){var a;if(b&&b.constructor==Array&&b.length==3){return b}if(a=/rgb\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)/.exec(b)){return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)]}if(a=/rgb\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)/.exec(b)){return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55]}if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b)){return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16)]}if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b)){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)]}if(a=/rgba\\(0, 0, 0, 0\\)/.exec(b)){return colors.transparent}return colors[$.trim(b).toLowerCase()]}function getColor(c,a){var b;do{b=$.curCSS(c,a);if(b!=\"\"&&b!=\"transparent\"||$.nodeName(c,\"body\")){break}a=\"backgroundColor\"}while(c=c.parentNode);return getRGB(b)};\n a.test {\n color: red;\n -moz-transition-property: color; /* FF4+ */\n -moz-transition-duration: 1s;\n -webkit-transition-property: color; /* Saf3.2+, Chrome */\n -webkit-transition-duration: 1s;\n -o-transition-property: color; /* Opera 10.5+ */\n -o-transition-duration: 1s;\n -ms-transition-property: color; /* IE10? */\n -ms-transition-duration: 1s;\n transition-property: color; /* Standard */\n transition-duration: 1s;\n }\n\n a.test:hover {\n color: blue;\n }\n /* shorthand notation for transition properties */\n/* transition: [transition-property] [transition-duration] [transition-timing-function] [transition-delay]; */\n\na.test {\n color: red;\n -moz-transition: color 1s;\n -webkit-transition: color 1s;\n -o-transition: color 1s;\n -ms-transition: color 1s;\n transition: color 1s;\n }\n\na.test {\n color: blue;\n }\n if ( !cssTransitions() ) {\n $(document).ready(function(){\n $(\".test\").hover(function () {\n $(this).stop().animate({ backgroundColor: \"red\" },500)\n }, function() {\n $(this).stop().animate({ backgroundColor: \"blue\" },500)} \n );\n }); \n}\n"
},
{
"answer_id": 8587086,
"author": "Anton Rodin",
"author_id": 1107702,
"author_profile": "https://Stackoverflow.com/users/1107702",
"pm_score": 0,
"selected": false,
"text": "-moz-transition: background .2s linear;\n-webkit-transition: background .2s linear;\n-o-transition: background .2s linear;\ntransition: background .2s linear;\n"
},
{
"answer_id": 12896867,
"author": "Pebbl",
"author_id": 1490904,
"author_profile": "https://Stackoverflow.com/users/1490904",
"pm_score": 2,
"selected": false,
"text": "element\n .css('color','#FF0000')\n;\n$('<div />')\n .css('width',0)\n .animate(\n {'width':100},\n {\n duration: 3000,\n step:function(now){\n var v = (255 - 255/100 * now).toString(16);\n v = (v.length < 2 ? '0' : '') + v.substr(0,2);\n element.css('color','#'+v+'0000');\n }\n }\n )\n;\n width setInterval .stop() easing duration"
},
{
"answer_id": 13822204,
"author": "Jimbo Jones",
"author_id": 1156525,
"author_profile": "https://Stackoverflow.com/users/1156525",
"pm_score": 3,
"selected": false,
"text": " $('.mylinkholder a').hover(\n function () {\n $(this).css({ backgroundColor: '#f0f0f0' }); \n },\n function () {\n $(this).css({ backgroundColor: '#fff' });\n }\n );\n .mylinkholder a\n {\n transition: background-color .5s ease-in-out;\n -moz-transition: background-color .5s ease-in-out;\n -webkit-transition: background-color .5s ease-in-out; \n -o-transition: background-color .5s ease-in-out; \n }\n"
},
{
"answer_id": 14214879,
"author": "user1029978",
"author_id": 1029978,
"author_profile": "https://Stackoverflow.com/users/1029978",
"pm_score": 1,
"selected": false,
"text": "jQuery(\".usercontent\").mouseover(function() {\n jQuery(\".usercontent\").animate({backgroundColor:'red'}, 'fast', 'linear', function() {\n jQuery(this).animate({\n backgroundColor: 'white'\n }, 'normal', 'linear', function() {\n jQuery(this).css({'background':'none', backgroundColor : ''});\n });\n });\n"
},
{
"answer_id": 15234173,
"author": "volf",
"author_id": 841333,
"author_profile": "https://Stackoverflow.com/users/841333",
"pm_score": 6,
"selected": false,
"text": "#foo {background:red; @include transition(background 1s)}\n#foo:hover {background:yellow}\n #foo {\nbackground:red;\n-webkit-transition:background 1s;\n-moz-transition:background 1s;\n-o-transition:background 1s;\ntransition:background 1s\n}\n#foo:hover {background:yellow}\n"
},
{
"answer_id": 27926653,
"author": "mag",
"author_id": 2057712,
"author_profile": "https://Stackoverflow.com/users/2057712",
"pm_score": 2,
"selected": false,
"text": "(function($) { \n\n var i = 0; \n\n var someBackground = $(\".someBackground\"); \n var someColors = [ \"yellow\", \"red\", \"blue\", \"pink\" ]; \n\n\n someBackground.css('backgroundColor', someColors[0]); \n\n window.setInterval(function() { \n i = i == someColors.length ? 0 : i; \n someBackground.animate({backgroundColor: someColors[i]}, 3000); \n i++; \n }, 30); \n\n})(jQuery); \n"
},
{
"answer_id": 44585068,
"author": "Darush",
"author_id": 4726718,
"author_profile": "https://Stackoverflow.com/users/4726718",
"pm_score": 3,
"selected": false,
"text": "<script src=\"https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile\"></script>\n"
},
{
"answer_id": 68067629,
"author": "lendoo",
"author_id": 11338800,
"author_profile": "https://Stackoverflow.com/users/11338800",
"pm_score": 1,
"selected": false,
"text": "selector.css({\n backgroundColor: \"#555\",\n transition: \"background-color 1.8s\"\n});\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6125/"
] |
190,590
|
<p>Ruby has a wealth of conditional constructs, including <code>if</code>/<code>unless</code>, <code>while</code>/<code>until</code> etc.</p>
<p>The <code>while</code> block from C:</p>
<pre><code>while (condition) {
...
}
</code></pre>
<p>can be directly translated to Ruby:</p>
<pre><code>while condition
...
end
</code></pre>
<p>However, I can't seem to find a <em>built-in</em> equivalent in Ruby for a C-like <code>do ... while</code> block in which the block contents are executed at least once:</p>
<pre><code>do {
...
} while (condition);
</code></pre>
<p>Any suggestions?</p>
|
[
{
"answer_id": 190591,
"author": "Cristian Diaconescu",
"author_id": 11545,
"author_profile": "https://Stackoverflow.com/users/11545",
"pm_score": 6,
"selected": true,
"text": "loop break loop do\n ...\n break unless condition\nend\n"
},
{
"answer_id": 190626,
"author": "IDBD",
"author_id": 7403,
"author_profile": "https://Stackoverflow.com/users/7403",
"pm_score": -1,
"selected": false,
"text": "while condition\n ...\nend\n"
},
{
"answer_id": 191363,
"author": "Gene T",
"author_id": 413049,
"author_profile": "https://Stackoverflow.com/users/413049",
"pm_score": 4,
"selected": false,
"text": "i=1\nbegin\n ...\n i+=1 \nend until 10==x\n"
},
{
"answer_id": 1659169,
"author": "haoqi",
"author_id": 131492,
"author_profile": "https://Stackoverflow.com/users/131492",
"pm_score": 3,
"selected": false,
"text": "number=3\nbegin\n puts number\n number-=1\nend while number>0\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545/"
] |
190,593
|
<p>I'm creating some text boxes on my form programmatically which I need to reference later using FindControl.</p>
<p>I've put the FindControl instruction in the page load method after the code which creates them but get an error:</p>
<blockquote>
<p><strong>Object reference not set to an instance of an object.</strong></p>
</blockquote>
<p>I assume this is because the textbox controls are not created until later in the lifecycle and therefore cannot be referenced from within Page_Load. </p>
<p>Can someone advise where in my code-behind I would need to place the FindControl instruction so that it can find these programmatically created text boxes?</p>
|
[
{
"answer_id": 190628,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 2,
"selected": false,
"text": "TextBox txt = new TextBox();\n...\ntxt.Text = \"Text\";\n"
},
{
"answer_id": 237659,
"author": "Brian Boatright",
"author_id": 3747,
"author_profile": "https://Stackoverflow.com/users/3747",
"pm_score": 1,
"selected": false,
"text": "Dim imgStep2PreviewIcon As Image = Eyespike.Utilities.FindControl(Of Control)(Page, \"imgStep1PreviewIcon\")\nimgStep2PreviewIcon.Visible = False\n Public Shadows Function FindControl(ByVal id As String) As Control\n Return FindControl(Of Control)(Page, id)\nEnd Function\n\nPublic Shared Shadows Function FindControl(Of T As Control)(ByVal startingControl As Control, ByVal id As String) As T\n Dim found As Control = startingControl\n If (String.IsNullOrEmpty(id) OrElse (found Is Nothing)) Then Return CType(Nothing, T)\n If String.Compare(id, found.ID) = 0 Then Return found\n For Each ctl As Control In startingControl.Controls\n found = FindControl(Of Control)(ctl, id)\n If (found IsNot Nothing) Then Return found\n Next\n Return CType(Nothing, T)\nEnd Function\n public new Control FindControl(string id)\n{\n return FindControl<Control>(Page, id);\n}\n\npublic static new T FindControl<T>(Control startingControl, string id) where T : Control\n{\n Control found = startingControl;\n if ((string.IsNullOrEmpty(id) || (found == null))) return (T)null; \n if (string.Compare(id, found.ID) == 0) return found; \n foreach (Control ctl in startingControl.Controls) {\n found = FindControl<Control>(ctl, id);\n if ((found != null)) return found; \n }\n return (T)null;\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26126/"
] |
190,594
|
<p>I have a Rails app that I need to deploy. Here are the facts:</p>
<ul>
<li>The app was developed on Windows and requires Windows binary gems</li>
<li>The app is to be deployed onto an Open Solaris shared server (Joyent)</li>
<li>I do not have permissions to install gems on the server</li>
<li>For the non-binary gems, I can simply do a <code>rake gems:unpack</code> locally and then upload; this works just fine.</li>
</ul>
<p>So my question is, how do I get the <strong>binary</strong> gems I need onto my production server?</p>
|
[
{
"answer_id": 190669,
"author": "Christoph Schiessl",
"author_id": 20467,
"author_profile": "https://Stackoverflow.com/users/20467",
"pm_score": 0,
"selected": false,
"text": "vendor/gems"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] |
190,597
|
<p>Say I have class A with</p>
<pre><code>class A {
final String foo() {
// .. computing result, contacting database, whatever ..
return "some computed value";
}
// ... and a bazillion other methods, some of them final.
}
</code></pre>
<p>Now I have class B with</p>
<pre><code>class B {
String methodIWantToTest(A a) {
String output = a.foo();
// ... whatever this method does, e.g.:
output += "_suffix";
return output;
}
}
</code></pre>
<p>How would I go about unit testing this method? The reason <code>foo()</code> is final is because we don't want our classes which extend A to change its functionality. But at the same time to truly unit test the method, I don't want it to reach out and run the actual <code>A.foo()</code> method.</p>
<p>Is there a way to, say, remove the final keyword and add an annotation along the lines of <code>@finalUnlessTest</code>? What would you recommend? Refactoring A to an interface would be very, very difficult, seeing as how it's one of our central classes and is unfortunately <s>pretty</s> extremely coupled.</p>
<p><strong>Edit #1</strong> Sorry, forgot to mention, we're talking Java. We are not using a mocking framework as of yet.</p>
<p><strong>Answer</strong> OK, so: wow. <a href="http://jmockit.org" rel="nofollow noreferrer">JMockit</a> is just incredible and is in my eyes the killer app for testing legacy code. Unbelievably useful especially in my case. Thanks so much! You basically would do something like the following for my psuedo-example:</p>
<pre><code>class AMock {
final String foo() {
return "myTestValue";
}
}
class Test extends TestCase {
A mockedA;
B b;
protected void setUp() {
Mockit.redefineMethods( A.class, AMock.class ); // this "pipes" all mocked methods from A to AMock
mockedA = new A(); // NOT new AMock()!!!
b = new B();
}
public void testB() {
assertEquals("myTestValue",mockedA.foo());
assertEquals("myTestValue_suffix",b.methodIWantToTest(mockedA));
}
}
</code></pre>
<p>Is this frickin' cool or what?</p>
|
[
{
"answer_id": 197066,
"author": "David Turner",
"author_id": 10171,
"author_profile": "https://Stackoverflow.com/users/10171",
"pm_score": 0,
"selected": false,
"text": "public class Jobber {\n\n public final String foo() {\n return fooFactory() ;\n }\n\n String fooFactory() {\n return \"jobber\" ;\n }\n\n\n public static void main(String[] args) {\n\n Jobber jobber = new Jobber() { String fooFactory() { return \"prefix \" + super.fooFactory() ;} } ;\n\n System.out.println(jobber.foo() );\n }\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
190,598
|
<p>Delphi 2009 has changed its string type to use 2 bytes to represent a character, which allows support for unicode char sets. Now when you get sizeof(string) you get length(String) * sizeof(char) . Sizeof(char) currently being 2. </p>
<p>What I am interested in is whether anyone knows of a way which on a character by character basis it is possible to find out if it would fit in a single byte, eg find out if a char is ascii or Unicode.</p>
<p>What I'm primarily interested in knowing, is before my string goes to a database (oracle, Documentum) how many bytes the string will use up.</p>
<p>We need to be able to enforce limits before hand and ideally (as we have a large installed base) without having to change the database. If a string field allows 12 bytes, in delphi 2009 a string of length 7 would always show as using 14 bytes even though once it got to the db it would only use 7 if ascii or 14 if double byte, or somewhere in between if a mixture.</p>
|
[
{
"answer_id": 190604,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "if ord(c) < 128 then\n // is an ascii character\n"
},
{
"answer_id": 190630,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 2,
"selected": false,
"text": "function IsAnsi(const AString: string): Boolean;\nvar\n tempansi : AnsiString;\n temp : string;\nbegin\n tempansi := AnsiString(AString);\n temp := tempansi;\n Result := temp = AString;\nend;\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6244/"
] |
190,625
|
<p>I have created the following stored procedure..</p>
<pre><code>CREATE PROCEDURE [dbo].[UDSPRBHPRIMBUSTYPESTARTUP]
(
@CODE CHAR(5)
, @DESC VARCHAR(255) OUTPUT
)
AS
DECLARE @SERVERNAME nvarchar(30)
DECLARE @DBASE nvarchar(30)
DECLARE @SQL nvarchar(2000)
SET @SERVERNAME =
Convert(nvarchar,
(SELECT spData FROM dbSpecificData WHERE spLookup = 'CMSSERVER'))
SET @DBASE =
Convert(nvarchar,
(SELECT spData FROM dbSpecificData WHERE spLookup = 'CMSDBNAME'))
SET @SQL =
'SELECT clnt_cat_desc FROM ' + @SERVERNAME +
'.' + @DBASE + '.dbo.hbl_clnt_cat WHERE inactive = ''N''
AND clnt_cat_code = ''' + @CODE + ''''
EXECUTE sp_executeSQL @SQL
RETURN
</code></pre>
<p>This procedure is used in many different databases and many different servers and is written as dynamic SQL to simplify maintenance. The procedure also runs on a different server than the one the procedure points to.</p>
<p>I want to use the output of this procedure as a value in a table...</p>
<pre><code>DECLARE @clid BIGINT
DECLARE @fileid BIGINT
DECLARE @myCode CHAR(5)
DECLARE @myDesc VARCHAR(255)
DECLARE @@tempDesc VARCHAR(255)
SET @clid = 1831400022
SET @fileid = 2072551358
SET @myCode =
(SELECT _clientPrimBusinessType FROM udbhextclient WHERE clid = @clid)
SET @myDesc =
EXEC UDSPRBHPRIMBUSTYPESTARTUP @CODE = @myCode, @DESC = @@tempDesc OUTPUT
----------------------------------------------------------------------------
SELECT
a.clid
, b.fileid
, c.usrfullname AS ClientPartner
, e.usrfullname AS ClientFeeEarner
, @myDesc AS ClientPrimaryBusinessType
FROM
dbclient a
INNER JOIN
dbFile b
ON
a.clid = b.clid
INNER JOIN
dbuser c
ON
a.feeusrid = c.usrid
INNER JOIN
udbhextclient d
ON
a.clid = d.clid
INNER JOIN
dbuser e
ON
d._ClientFeeEarner = e.usrid
WHERE
a.clid = @clid
AND b.fileid = @fileid
</code></pre>
<p>I know this is the incorrect syntax, but you can see what I am trying to achieve this without resorting to temporary tables as this would mean maintenance across 30 different servers with 3 to 5 databases on each.</p>
<p>Smink - Tried your solution and got the following results...</p>
<p><img src="https://farm4.static.flickr.com/3029/2928268613_dd3c454f92.jpg" alt="Running Smink's Solution"></p>
|
[
{
"answer_id": 190648,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION [dbo].[my_function]\n(\n @par2 UNIQUEIDENTIFIER, \n @par2 UNIQUEIDENTIFIER,\n @par3 UNIQUEIDENTIFIER\n)\nRETURNS @returntable TABLE \n(\n col1 UNIQUEIDENTIFIER,\n col2 NVARCHAR(50),\n col3 NVARCHAR(50)\n)\nAS\nBEGIN\n...\nEND\n"
},
{
"answer_id": 190665,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": true,
"text": "SET @myDesc = \n EXEC UDSPRBHPRIMBUSTYPESTARTUP @CODE = @myCode, @DESC = @@tempDesc OUTPUT\n EXEC UDSPRBHPRIMBUSTYPESTARTUP @CODE = @myCode, @DESC = @tempDesc OUTPUT\n @DESC SET @SQL = \n 'SELECT @DESC = clnt_cat_desc FROM ' + @SERVERNAME + \n '.' + @DBASE + '.dbo.hbl_clnt_cat WHERE inactive = ''N''\n AND clnt_cat_code = ''' + @CODE + ''''\n\nEXECUTE sp_executeSQL @SQL, N'@DESC varchar(255) output', @DESC output\n @tempDesc SELECT\n a.clid\n , b.fileid\n , c.usrfullname AS ClientPartner\n , e.usrfullname AS ClientFeeEarner\n , @tempDesc AS ClientPrimaryBusinessType\n SET @SQL = \n 'SELECT clnt_cat_desc \n FROM ' + QUOTENAME(@SERVERNAME) + '.' + QUOTENAME(@DBASE) + '.dbo.hbl_clnt_cat\n WHERE inactive = ''N''\n AND clnt_cat_code = @CODE'\n\nEXECUTE sp_executeSQL @SQL, N'@CODE CHAR(5)', @CODE\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/978/"
] |
190,629
|
<p>I am writing a drop-in replacement for a legacy application in Java. One of the requirements is that the ini files that the older application used have to be read as-is into the new Java Application. The format of this ini files is the common windows style, with header sections and key=value pairs, using # as the character for commenting.</p>
<p>I tried using the Properties class from Java, but of course that won't work if there is name clashes between different headers.</p>
<p>So the question is, what would be the easiest way to read in this INI file and access the keys?</p>
|
[
{
"answer_id": 190633,
"author": "Mario Ortegón",
"author_id": 2309,
"author_profile": "https://Stackoverflow.com/users/2309",
"pm_score": 8,
"selected": true,
"text": "Ini ini = new Ini(new File(filename));\njava.util.prefs.Preferences prefs = new IniPreferences(ini);\nSystem.out.println(\"grumpy/homePage: \" + prefs.node(\"grumpy\").get(\"homePage\", null));\n"
},
{
"answer_id": 197026,
"author": "Peter",
"author_id": 26483,
"author_profile": "https://Stackoverflow.com/users/26483",
"pm_score": 4,
"selected": false,
"text": "Properties props = new Properties();\ntry (FileInputStream in = new FileInputStream(path)) {\n props.load(in);\n}\n"
},
{
"answer_id": 486816,
"author": "user50217",
"author_id": 50217,
"author_profile": "https://Stackoverflow.com/users/50217",
"pm_score": 4,
"selected": false,
"text": "HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile); \n\n// Get Section names in ini file \nSet setOfSections = iniConfObj.getSections();\nIterator sectionNames = setOfSections.iterator();\n\nwhile(sectionNames.hasNext()){\n\n String sectionName = sectionNames.next().toString();\n\n SubnodeConfiguration sObj = iniObj.getSection(sectionName);\n Iterator it1 = sObj.getKeys();\n\n while (it1.hasNext()) {\n // Get element\n Object key = it1.next();\n System.out.print(\"Key \" + key.toString() + \" Value \" + \n sObj.getString(key.toString()) + \"\\n\");\n}\n"
},
{
"answer_id": 4851893,
"author": "tshepang",
"author_id": 321731,
"author_profile": "https://Stackoverflow.com/users/321731",
"pm_score": 6,
"selected": false,
"text": "[header]\nkey = value\n value Ini ini = new Ini(new File(\"/path/to/file\"));\nSystem.out.println(ini.get(\"header\", \"key\"));\n"
},
{
"answer_id": 15638381,
"author": "Aerospace",
"author_id": 1770831,
"author_profile": "https://Stackoverflow.com/users/1770831",
"pm_score": 5,
"selected": false,
"text": "package windows.prefs;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class IniFile {\n\n private Pattern _section = Pattern.compile( \"\\\\s*\\\\[([^]]*)\\\\]\\\\s*\" );\n private Pattern _keyValue = Pattern.compile( \"\\\\s*([^=]*)=(.*)\" );\n private Map< String,\n Map< String,\n String >> _entries = new HashMap<>();\n\n public IniFile( String path ) throws IOException {\n load( path );\n }\n\n public void load( String path ) throws IOException {\n try( BufferedReader br = new BufferedReader( new FileReader( path ))) {\n String line;\n String section = null;\n while(( line = br.readLine()) != null ) {\n Matcher m = _section.matcher( line );\n if( m.matches()) {\n section = m.group( 1 ).trim();\n }\n else if( section != null ) {\n m = _keyValue.matcher( line );\n if( m.matches()) {\n String key = m.group( 1 ).trim();\n String value = m.group( 2 ).trim();\n Map< String, String > kv = _entries.get( section );\n if( kv == null ) {\n _entries.put( section, kv = new HashMap<>()); \n }\n kv.put( key, value );\n }\n }\n }\n }\n }\n\n public String getString( String section, String key, String defaultvalue ) {\n Map< String, String > kv = _entries.get( section );\n if( kv == null ) {\n return defaultvalue;\n }\n return kv.get( key );\n }\n\n public int getInt( String section, String key, int defaultvalue ) {\n Map< String, String > kv = _entries.get( section );\n if( kv == null ) {\n return defaultvalue;\n }\n return Integer.parseInt( kv.get( key ));\n }\n\n public float getFloat( String section, String key, float defaultvalue ) {\n Map< String, String > kv = _entries.get( section );\n if( kv == null ) {\n return defaultvalue;\n }\n return Float.parseFloat( kv.get( key ));\n }\n\n public double getDouble( String section, String key, double defaultvalue ) {\n Map< String, String > kv = _entries.get( section );\n if( kv == null ) {\n return defaultvalue;\n }\n return Double.parseDouble( kv.get( key ));\n }\n}\n"
},
{
"answer_id": 18897822,
"author": "Mark",
"author_id": 2795935,
"author_profile": "https://Stackoverflow.com/users/2795935",
"pm_score": 2,
"selected": false,
"text": "Configurable config = Configuration.getInstance(); \nString host = config.getStringValue(\"host\"); \nint port = config.getIntValue(\"port\"); \nnew Connection(host, port);\n"
},
{
"answer_id": 41084504,
"author": "hoat4",
"author_id": 2804761,
"author_profile": "https://Stackoverflow.com/users/2804761",
"pm_score": 4,
"selected": false,
"text": "java.util.Properties public static Map<String, Properties> parseINI(Reader reader) throws IOException {\n Map<String, Properties> result = new HashMap();\n new Properties() {\n\n private Properties section;\n\n @Override\n public Object put(Object key, Object value) {\n String header = (((String) key) + \" \" + value).trim();\n if (header.startsWith(\"[\") && header.endsWith(\"]\"))\n return result.put(header.substring(1, header.length() - 1), \n section = new Properties());\n else\n return section.put(key, value);\n }\n\n }.load(reader);\n return result;\n}\n"
},
{
"answer_id": 54649170,
"author": "Desmond",
"author_id": 11050483,
"author_profile": "https://Stackoverflow.com/users/11050483",
"pm_score": -1,
"selected": false,
"text": "//import java.io.FileInputStream;\n//import java.io.FileInputStream;\n\nProperties prop = new Properties();\n//c:\\\\myapp\\\\config.ini is the location of the ini file\n//ini file should look like host=localhost\nprop.load(new FileInputStream(\"c:\\\\myapp\\\\config.ini\"));\nString host = prop.getProperty(\"host\");\n"
},
{
"answer_id": 59332344,
"author": "Bradley Willcott",
"author_id": 12349591,
"author_profile": "https://Stackoverflow.com/users/12349591",
"pm_score": 0,
"selected": false,
"text": "java.util.Properties private boolean _spaceCharOn = false;\n private boolean isSpaceSeparator(char c) {\n if (_spaceCharOn) {\n return (c == ' ' || c == '\\t' || c == '\\f');\n } else {\n return (c == '\\t' || c == '\\f');\n }\n}\n load0(...) Properties IniFile.java Properties"
},
{
"answer_id": 62985998,
"author": "denka",
"author_id": 4181616,
"author_profile": "https://Stackoverflow.com/users/4181616",
"pm_score": 0,
"selected": false,
"text": " Path location = ...;\n try (BufferedReader br = new BufferedReader(new FileReader(location.toFile()))) {\n String line;\n String section = null;\n while ((line = br.readLine()) != null) {\n Matcher m = this.section.matcher(line);\n if (m.matches()) {\n section = m.group(1).trim();\n entries.computeIfAbsent(section, k -> new HashMap<>());\n } else if (section != null) {\n m = keyValue.matcher(line);\n if (m.matches()) {\n String key = m.group(1).trim();\n String value = m.group(2).trim();\n entries.get(section).put(key, value);\n }\n }\n }\n } catch (IOException ex) {\n System.err.println(\"Failed to read and parse INI file '\" + location + \"', \" + ex.getMessage());\n ex.printStackTrace(System.err);\n }\n\n"
},
{
"answer_id": 68219318,
"author": "Hai Mai",
"author_id": 11327766,
"author_profile": "https://Stackoverflow.com/users/11327766",
"pm_score": 0,
"selected": false,
"text": " Properties properties = new Properties();\n Ini ini = new Ini(new File(\"path/to/file\"));\n ini.forEach((header, map) -> {\n map.forEach((subKey, value) -> {\n StringBuilder key = new StringBuilder(header);\n key.append(\".\" + subKey);\n properties.put(key.toString(), value);\n });\n });\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309/"
] |
190,642
|
<p>The code below crashes IE6 for some reason. Much as IE is god-awful, i have never seen this before. Does anyone have any ideas?</p>
<pre><code><div id="edit">
<?php
$a = $_POST['category'];
if ($a == "")
{
$a = $_GET['category'];
}
$result = mysql_query("SELECT * FROM media WHERE related_page_id = $a && type= 'copy'");
?>
<table width="460px;">
<tr>
<td>Item</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>Associated Images</td>
</tr>
<tr>
<td colspan="5">&nbsp;</td>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr style='vertical-align:top'><td>$row[title]</td>";
echo "<td><a href='addimage.php?id=$row[id]&&category=$a'>Add image/file</a>";
echo "<td><a href='change.php?id=$row[id]&&category=$a'>edit</a></td>";
echo "<td><a href='delete.php?id=$row[id]&&category=$a'>delete</a></td>";
echo "<td>";
$id = $row['id'];
$result1 = mysql_query("SELECT * FROM media WHERE assets = $id");
while($row1 = mysql_fetch_array($result1))
{
echo "<a href='$row1[path]'>$row1[title]</a> | <a href='delete.php?id=$row1[id]&&category=$a'>remove?</a><br />";
}
echo "</td></tr>";
}
if($a == 1 || $a == 3 || $a == 5){
}else{
echo "<tr><td colspan='5'>&nbsp;</td></tr>";
echo "<tr><td colspan='5'><a href='change.php?id=0&&category=$a'>New Item</a></td></tr>";
}
?>
</div>
</div>
</div>
</table>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 190657,
"author": "Rimas Kudelis",
"author_id": 25804,
"author_profile": "https://Stackoverflow.com/users/25804",
"pm_score": 0,
"selected": false,
"text": "&"
},
{
"answer_id": 190659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n\n <script type=\"text/javascript\" src=\"../javascript/tiny_mce/tiny_mce.js\"></script>\n <script type=\"text/javascript\">\n tinyMCE.init({\n mode : \"textareas\",\n theme : \"advanced\"\n });\n </script>\n\n\n <title>Chapman Corp Site - CMS</title>\n <link rel=\"stylesheet\" href=\"../css/admin.css\" type=\"text/css\" media=\"screen\" title=\"Chapman\" charset=\"utf-8\" />\n <!--[if lte IE 6]> \n<link rel=\"stylesheet\" href=\"../css/ie6.css\" type=\"text/css\" media=\"screen\" />\n<script type=\"text/javascript\" src=\"../javascript/unitpngfix.js\"></script>\n<![endif]-->\n\n</head>\n<body>\n<div id=\"page\">\n<div id =\"content\">\n<p><a href=\"index.php\">Home</a></p><div id=\"edit\">\n\n<table width=\"460px;\">\n <tr>\n <td>Item</td>\n <td> </td>\n <td> </td>\n\n <td> </td>\n <td>Associated Images</td>\n </tr>\n <tr>\n <td colspan=\"5\"> </td>\n </tr>\n<tr style='vertical-align:top'><td>Home</td><td><a href='addimage.php?id=77&&category=1'>Add image/file</a><td><a href='change.php?id=77&&category=1'>edit</a></td><td><a href='delete.php?id=77&&category=1'>delete</a></td><td><a href='../uploads/footer.jpg'>footer.jpg</a> | <a href='delete.php?id=88&&category=1'>remove?</a><br /></td></tr></div>\n\n</div>\n</div>\n</table>\n</body>\n</html>\n"
},
{
"answer_id": 190660,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 3,
"selected": false,
"text": "td echo \"<td><a href='addimage.php?id=$row[id]&&category=$a'>Add image/file</a>\";\n </div>\n</div>\n</div>\n</table>\n </table>\n</div>\n</div>\n</div>\n $a $a = $_POST['category'];\nif ($a == \"\")\n{\n $a = $_GET['category'];\n}\n\n$result = mysql_query(\"SELECT * FROM media WHERE related_page_id = $a && type= 'copy'\");\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
190,667
|
<p>I'm using a CListCtrl control to display information in my MFC app. At the moment I have LVS_EX_CHECKBOXES set in SetExtendedStyle so all rows in the control have a checkbox next to them. What I would like however is that only some of the rows in the control have checkboxes. Is this possible ? If it is how is this done ?</p>
<p>Thanks</p>
<p>Ian</p>
|
[
{
"answer_id": 190728,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 4,
"selected": true,
"text": "LVITEM lvi;\nlvi.stateMask = LVIS_STATEIMAGEMASK;\nlvi.state = INDEXTOSTATEIMAGEMASK(0);\n::SendMessage(m_hWnd, LVM_SETITEMSTATE, nItem, (LPARAM)&lvi);\n SetCheck(Item, true/false);\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3875/"
] |
190,675
|
<p>How can I read the colors of an image with python using google app engine?</p>
<p><strong>Example:</strong> I like to build a function to determine the most striking colors of an image to set a harmonic background color for it.</p>
|
[
{
"answer_id": 193432,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "import png\n\npoint = (10, 20) # coordinates of pixel to read\n\nreader = png.Reader(filename='image.png') # streams are also accepted\nw, h, pixels, metadata = reader.read()\npixel_byte_width = 4 if metadata['has_alpha'] else 3\npixel_position = point[0] + point[1] * w\nprint pixels[\n pixel_position * pixel_byte_width :\n (pixel_position + 1) * pixel_byte_width]\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26763/"
] |
190,681
|
<p><a href="http://en.wikipedia.org/wiki/Loop_unwinding" rel="noreferrer">Loop unwinding</a> is a common way to help the compiler to optimize performance. I was wondering if and to what extent the performance gain is affected by what is in the body of the loop:</p>
<ol>
<li>number of statements</li>
<li>number of function calls</li>
<li>use of complex data types, virtual methods, etc.</li>
<li>dynamic (de)allocation of memory</li>
</ol>
<p>What rules (of thumb?) do you use to decide whether or not to unwind a performance critical loop? What other optimisation do you consider in these cases?</p>
|
[
{
"answer_id": 191051,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 1,
"selected": false,
"text": "for(int i=0; i<256; i++)\n{\n a+=(ptr + i) << 8;\n a-=(ptr + i - k) << 8;\n // And possibly some more\n}\n #define UNROLL (i) \\\n a+=(ptr[i]) << 8; \\\n a-=(ptr[i-k]) << 8;\n\n\nfor(int i=0; i<32; i++)\n{\n UNROLL(i);\n UNROLL(i+1);\n UNROLL(i+2);\n UNROLL(i+3);\n UNROLL(i+4);\n UNROLL(i+5);\n UNROLL(i+6);\n UNROLL(i+7);\n}\n // Bad\nMOV r1, 4\n// ...\nADD r2, r2, 1\n// ...\nADD r2, r2, 4\n // Better\nADD r2, r2, 8\n"
},
{
"answer_id": 195622,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": 0,
"selected": false,
"text": "while(first != last && !(*first == val))\n ++first;\n"
},
{
"answer_id": 25681437,
"author": "Tomas Kubes",
"author_id": 518530,
"author_profile": "https://Stackoverflow.com/users/518530",
"pm_score": 0,
"selected": false,
"text": "template<class TData,class TSum>\ninline TSum SumV(const TData* pVec, int nCount)\n{\n const TData* pEndOfVec = pVec + nCount;\n TSum nAccum = 0;\n\n while(pVec < pEndOfVec)\n {\n nAccum += (TSum)(*pVec++);\n }\n return nAccum;\n}\n template<class TData,class TSum>\ninline TSum SumV(const TData* pVec, int nCount)\n{\n const TData* pEndOfVec = pVec + nCount;\n TSum nAccum = 0;\n\n int nCount4 = nCount - nCount % 4;\n const TData* pEndOfVec4 = pVec + nCount4;\n while (pVec < pEndOfVec4)\n {\n TSum val1 = (TSum)(pVec[0]);\n TSum val2 = (TSum)(pVec[1]);\n TSum val3 = (TSum)(pVec[2]);\n TSum val4 = (TSum)(pVec[3]);\n nAccum += val1 + val2 + val3 + val4;\n pVec += 4;\n } \n\n while(pVec < pEndOfVec)\n {\n nAccum += (TSum)(*pVec++);\n }\n return nAccum;\n}\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
] |
190,691
|
<p>I'm working with dRuby and basicly I'm calling a remote method that returns me an object.</p>
<p>In the clientside I have this code:</p>
<pre><code>handle_error(response) if response.is_a?(Error)
</code></pre>
<p>where response is the DRbObject. (I've developed this code before using dRuby and I'm returning an Error object if something went wrong). The problem is that now </p>
<pre><code>response.is_a?(Error)
</code></pre>
<p>comes back with "false" because the object is actually a DRbObject.
Any idea on how I can check the class of my application object?</p>
<p>Thanks!
Roberto</p>
|
[
{
"answer_id": 195616,
"author": "Federico Builes",
"author_id": 161,
"author_profile": "https://Stackoverflow.com/users/161",
"pm_score": 2,
"selected": false,
"text": "response.kind_of?(Error)\n response.respond_to?(some_method_on_your_errors)\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22083/"
] |
190,701
|
<p>I'm writing a small article on humanly readable alternatives to Guids/UIDs, for example those used on TinyURL for the url hashes (which are often printed in magazines, so need to be short).</p>
<p>The simple uid I'm generating is - 6 characters: either a lowercase letter (a-z) or 0-9. </p>
<p>"According to my calculations captain", that's 6 mutually exclusive events, although calculating the probability of a clash gets a little harder than P(A or B) = P(A) + P(B), as obviously it includes numbers and from the code below, you can see it works out whether to use a number or letter using 50/50.</p>
<p>I'm interested in the clash rate and if the code below is a realistic simulation of anticipated clash rate you'd get from generating a hash. On average I get 40-50 clashes per million, however bare in mind the uid wouldn't be generated a million times at once, but probably only around 10-1000 times a minute.</p>
<p>What is the probability of a clash each time, and can anyone suggest a better way of doing it?</p>
<pre><code>static Random _random = new Random();
public static void main()
{
// Size of the key, 6
HashSet<string> set = new HashSet<string>();
int clashes = 0;
for (int n=0;n < 1000000;n++)
{
StringBuilder builder = new StringBuilder();
for (int i =0;i < 7;i++)
{
if (_random.NextDouble() > 0.5)
{
builder.Append((char)_random.Next(97,123));
}
else
{
builder.Append(_random.Next(0,9).ToString());
}
}
if (set.Contains(builder.ToString()))
{
clashes++;
Console.WriteLine("clash: (" +n+ ")" +builder.ToString());
}
set.Add(builder.ToString());
_random.Next();
//Console.Write(builder.ToString());
}
Console.WriteLine("Clashes: " +clashes);
Console.ReadLine();
}
</code></pre>
<p><strong>UPDATE:</strong>
<a href="http://www.yetanotherchris.me/home/2009/3/3/friendly-unique-id-generation-part-1.html" rel="nofollow noreferrer">Here's the resulting article</a> from this question</p>
<p>I really asked two questions here so I was cheating. The answer I was after was rcar's, however Sklivvz's is also the answer to the 2nd part (an alternative). Is it possible to make a custom unique id generator in a database, or would it be client side (which would be 2 possible reads first)?</p>
<p>The general idea I was after was using Ids in databases or other stores that can be used by phone or printed material, not a giant 16 byte guid.</p>
<p><strong>UPDATE 2:</strong> I put the formula for two mutually exclusive events above instead of 2 independent ones (as getting an 'a' the first time doesn't mean you can't get an 'a' the second time). Should've been P(A and B) = P(A) x P(B) </p>
|
[
{
"answer_id": 190719,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 5,
"selected": false,
"text": "Id URL\n 1 http://google.com\n 2 ...\n... ...\n156 ...\n... ...\n http://example.com/1\nhttp://example.com/2\n...\nhttp://example.com/2W\n...\n"
},
{
"answer_id": 190752,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "7QDBkvCA1+B9K/U0vrQx1A\n7QDBkvCA1+B9K/U0vrQx1A==\n 5:$Hj:Pf\\4RLB9%kU\\Lj \n"
},
{
"answer_id": 190760,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 3,
"selected": true,
"text": "p = ( 0.5 * ( (0.5*1/10) + (0.5*1/26) ) )^6\n"
},
{
"answer_id": 191152,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 3,
"selected": false,
"text": "select dbo.FX_CONV (123456) -- returns \"1f5n\"\n\nselect dbo.FX_CONV (123457) -- returns \"1f5o\"\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21574/"
] |
190,702
|
<p>Given this data set:</p>
<pre><code>ID Name City Birthyear
1 Egon Spengler New York 1957
2 Mac Taylor New York 1955
3 Sarah Connor Los Angeles 1959
4 Jean-Luc Picard La Barre 2305
5 Ellen Ripley Nostromo 2092
6 James T. Kirk Riverside 2233
7 Henry Jones Chicago 1899
</code></pre>
<p>I need to find the 3 oldest persons, but only one of every city.</p>
<p>If it would just be the three oldest, it would be...</p>
<ul>
<li>Henry Jones / Chicago</li>
<li>Mac Taylor / New York</li>
<li>Egon Spengler / New York</li>
</ul>
<p>However since both Egon Spengler and Mac Taylor are located in New York, Egon Spengler would drop out and the next one (Sarah Connor / Los Angeles) would come in instead.</p>
<p>Any elegant solutions?</p>
<p><strong>Update:</strong></p>
<p>Currently a variation of PConroy is the best/fastest solution:</p>
<pre><code>SELECT P.*, COUNT(*) AS ct
FROM people P
JOIN (SELECT MIN(Birthyear) AS Birthyear
FROM people
GROUP by City) P2 ON P2.Birthyear = P.Birthyear
GROUP BY P.City
ORDER BY P.Birthyear ASC
LIMIT 10;
</code></pre>
<p>His original query with "IN" is extremly slow with big datasets (aborted after 5 minutes), but moving the subquery to a JOIN will speed it up a lot. It took about 0.15 seconds for approx. 1 mio rows in my test environment. I have an index on "City, Birthyear" and a second one just on "Birthyear".</p>
<p>Note: This is related to...</p>
<ul>
<li><a href="https://stackoverflow.com/questions/150610/selecting-unique-rows-in-a-set-of-two-possibilities">Selecting unique rows in a set of two possibilities</a></li>
<li><a href="https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price">SQL Query to get latest price</a></li>
</ul>
|
[
{
"answer_id": 190735,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "SELECT\n Id, Name, City, Birthyear\nFROM\n TheTable\nWHERE\n Id IN (SELECT TOP 1 Id FROM TheTable i WHERE i.City = TheTable.City ORDER BY Birthyear)\n"
},
{
"answer_id": 190761,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 2,
"selected": false,
"text": "select p.* from people p,\n(select city, max(age) as mage from people group by city) t\nwhere p.city = t.city and p.age = t.mage\norder by p.age desc\n"
},
{
"answer_id": 190764,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 5,
"selected": true,
"text": "IN Birthyear Birthyear SELECT Name, City, Birthyear, COUNT(*) AS ct\nFROM table\nWHERE Birthyear IN (SELECT MIN(Birthyear)\n FROM table\n GROUP by City)\nGROUP BY City\nORDER BY Birthyear DESC LIMIT 3;\n\n+-----------------+-------------+------+----+\n| name | city | year | ct |\n+-----------------+-------------+------+----+\n| Henry Jones | Chicago | 1899 | 1 |\n| Mac Taylor | New York | 1955 | 1 |\n| Sarah Connor | Los Angeles | 1959 | 1 |\n+-----------------+-------------+------+----+\n GROUP BY City Birthyear ct Birthyear"
},
{
"answer_id": 190884,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 1,
"selected": false,
"text": "select id, name, city, dob \ninto people\nfrom\n(select 1 id,'Egon Spengler' name, 'New York' city , 1957 dob\nunion all select 2, 'Mac Taylor','New York', 1955\nunion all select 3, 'Sarah Connor','Los Angeles', 1959\nunion all select 4, 'Jean-Luc Picard','La Barre', 2305\nunion all select 5, 'Ellen Ripley','Nostromo', 2092\nunion all select 6, 'James T. Kirk','Riverside', 2233\nunion all select 7, 'Henry Jones','Chicago', 1899\nunion all select 8, 'Blah','New York', 1955) a\n select \n * \nfrom \n people p\n left join people p1\n ON \n p.city = p1.city\n and (p.dob > p1.dob and p.id <> p1.id)\n or (p.dob = p1.dob and p.id > p1.id)\nwhere\n p1.id is null\norder by \n p.dob\n"
},
{
"answer_id": 3484267,
"author": "gondo",
"author_id": 309268,
"author_profile": "https://Stackoverflow.com/users/309268",
"pm_score": 1,
"selected": false,
"text": "SELECT P.*, COUNT(*) AS ct\n FROM people P\n JOIN (SELECT City, MIN(Birthyear) AS Birthyear\n FROM people \n GROUP by City) P2 USING(Birthyear, City)\n GROUP BY P.City\n ORDER BY P.Birthyear ASC \n LIMIT 10;\n SELECT P.*, COUNT(*) AS ct\n FROM people P\n JOIN (SELECT City, MIN(Birthyear) AS Birthyear\n FROM people \n GROUP by City) P2 ON P2.Birthyear = P.Birthyear AND P2.City = P.City\n GROUP BY P.City\n ORDER BY P.Birthyear ASC \n LIMIT 10;\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999/"
] |
190,714
|
<p>I have a Java application that's very String-heavy - it takes a feed of huge numbers of big, different String objects.</p>
<p>Do I need to worry about the String Constant Pool for memory and performance?</p>
<p>Is there any way to see how big the pool is at any point?</p>
|
[
{
"answer_id": 190754,
"author": "Mario Ortegón",
"author_id": 2309,
"author_profile": "https://Stackoverflow.com/users/2309",
"pm_score": 2,
"selected": false,
"text": "-XX:MaxPermSize=64m\n"
},
{
"answer_id": 190848,
"author": "mfx",
"author_id": 8015,
"author_profile": "https://Stackoverflow.com/users/8015",
"pm_score": 3,
"selected": true,
"text": "substring() char[] String large = ... // read 10k string\n String small = large.substring(...) // extrakt a few chars\n large = null; // large String object no longer reachable,\n // but 10k char[] still alive, as long as small lives\n"
},
{
"answer_id": 31980852,
"author": "Ankush soni",
"author_id": 4796407,
"author_profile": "https://Stackoverflow.com/users/4796407",
"pm_score": 0,
"selected": false,
"text": "public String substring(int beginIndex, int endIndex) {\n if (beginIndex < 0) {\n throw new StringIndexOutOfBoundsException(beginIndex);\n }\n if (endIndex > value.length) {\n throw new StringIndexOutOfBoundsException(endIndex);\n }\n int subLen = endIndex - beginIndex;\n if (subLen < 0) {\n throw new StringIndexOutOfBoundsException(subLen);\n }\n return ((beginIndex == 0) && (endIndex == value.length)) ? this\n : new String(value, beginIndex, subLen);\n }\n public String(char value[], int offset, int count) {\n if (offset < 0) {\n throw new StringIndexOutOfBoundsException(offset);\n }\n if (count < 0) {\n throw new StringIndexOutOfBoundsException(count);\n }\n // Note: offset or count might be near -1>>>1.\n if (offset > value.length - count) {\n throw new StringIndexOutOfBoundsException(offset + count);\n }\n this.value = Arrays.copyOfRange(value, offset, offset+count);\n }\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/190714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2362/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.