qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
72,209 |
<p>Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palindrome.
I have seen many programmers using recursion as a means to show off when a simple iteration algorithm can fit the bill.
Does the compiler play a vital role in deciding what to use?</p>
|
[
{
"answer_id": 72803,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 1,
"selected": false,
"text": "int count(int i) {\n return i >= 100000000 ? i : count(i+1);\n}\n"
},
{
"answer_id": 278563,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "sub f{\n my($l,$r) = @_;\n\n if( $l >= $r ){\n return $l;\n } else {\n\n # return f( $l+1, $r );\n\n @_ = ( $l+1, $r );\n goto &f;\n\n }\n}\n my @_; local @_;"
},
{
"answer_id": 6463107,
"author": "Harikrishnan",
"author_id": 721597,
"author_profile": "https://Stackoverflow.com/users/721597",
"pm_score": 3,
"selected": false,
"text": "int factorial ( int input )\n{\n int x, fact = 1;\n for ( x = input; x > 1; x--)\n fact *= x;\n return fact;\n}\n int factorial ( int input )\n{\n if (input == 0)\n {\n return 1;\n }\n return input * factorial(input - 1);\n}\n if (input == 0)"
},
{
"answer_id": 13775120,
"author": "Nikunj Banka",
"author_id": 1737817,
"author_profile": "https://Stackoverflow.com/users/1737817",
"pm_score": 3,
"selected": false,
"text": "public static void sort(Comparable[] a)\n{\n int N = a.length;\n aux = new Comparable[N];\n for (int sz = 1; sz < N; sz = sz+sz)\n for (int lo = 0; lo < N-sz; lo += sz+sz)\n merge(a, lo, lo+sz-1, Math.min(lo+sz+sz-1, N-1));\n}\n private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi)\n{\n if (hi <= lo) return;\n int mid = lo + (hi - lo) / 2;\n sort(a, aux, lo, mid);\n sort(a, aux, mid+1, hi);\n merge(a, aux, lo, mid, hi);\n}\n"
},
{
"answer_id": 15581513,
"author": "nomen",
"author_id": 738762,
"author_profile": "https://Stackoverflow.com/users/738762",
"pm_score": -1,
"selected": false,
"text": "data Tree a = Branch (Tree a) (Tree a)\n | Leaf a\n deriving (Eq)\n example :: Tree Int\nexample = Branch (Leaf 1) \n (Branch (Leaf 2) \n (Leaf 3))\n addOne :: Tree Int -> Tree Int\naddOne (Branch a b) = Branch (addOne a) (addOne b)\naddOne (Leaf a) = Leaf (a + 1)\n instance Functor Tree where fmap f (Leaf a) = Leaf (f a)\n fmap f (Branch a b) = Branch (fmap f a) (fmap f b)\n addOne' = fmap (+1)\n addOne'' = cata go where\n go (Leaf a) = Leaf (a + 1)\n go (Branch a b) = Branch a b\n"
},
{
"answer_id": 32613300,
"author": "AlphaG33k",
"author_id": 4937914,
"author_profile": "https://Stackoverflow.com/users/4937914",
"pm_score": 1,
"selected": false,
"text": "(function recursionVsForLoop(global) {\n \"use strict\";\n\n // Perf test\n function perfTest() {}\n\n perfTest.prototype.do = function(ns, fn) {\n console.time(ns);\n fn();\n console.timeEnd(ns);\n };\n\n // Recursion method\n (function recur() {\n var count = 0;\n global.recurFn = function recurFn(fn, cycles) {\n fn();\n count = count + 1;\n if (count !== cycles) recurFn(fn, cycles);\n };\n })();\n\n // Looped method\n function loopFn(fn, cycles) {\n for (var i = 0; i < cycles; i++) {\n fn();\n }\n }\n\n // Tests\n var curTest = new perfTest(),\n testsToRun = 100;\n\n curTest.do('recursion', function() {\n recurFn(function() {\n console.log('a recur run.');\n }, testsToRun);\n });\n\n curTest.do('loop', function() {\n loopFn(function() {\n console.log('a loop run.');\n }, testsToRun);\n });\n\n})(window);\n"
},
{
"answer_id": 33048493,
"author": "Titas Chanda",
"author_id": 5395216,
"author_profile": "https://Stackoverflow.com/users/5395216",
"pm_score": 2,
"selected": false,
"text": "-O3 -O2 g++ 1,000,000 12x12 10 iterative + optimisation flag -O3 -> 2.79.. sec\nrecursive + optimisation flag -O3 -> 1.32.. sec\n\niterative + No-optimisation flag -> 2.83.. sec\nrecursive + No-optimisation flag -> 4.15.. sec\n -std=c++11"
},
{
"answer_id": 59900284,
"author": "Vladimir Nabokov",
"author_id": 2285111,
"author_profile": "https://Stackoverflow.com/users/2285111",
"pm_score": 1,
"selected": false,
"text": " //key-task, value-list of tasks the key task depends on\n //\"adjacency map\":\n Map<Integer, List<Integer>> tasksMap = new HashMap<>();\n tasksMap.put(0, new ArrayList<>());\n tasksMap.put(1, new ArrayList<>());\n\n List<Integer> t2 = new ArrayList<>();\n t2.add(0);\n t2.add(1);\n tasksMap.put(2, t2);\n\n List<Integer> t3 = new ArrayList<>();\n t3.add(2);\n t3.add(10);\n tasksMap.put(3, t3);\n\n List<Integer> t4 = new ArrayList<>();\n t4.add(3);\n tasksMap.put(4, t4);\n\n List<Integer> t5 = new ArrayList<>();\n t5.add(3);\n tasksMap.put(5, t5);\n\n tasksMap.put(6, new ArrayList<>());\n tasksMap.put(7, new ArrayList<>());\n\n List<Integer> t8 = new ArrayList<>();\n t8.add(5);\n tasksMap.put(8, t8);\n\n List<Integer> t9 = new ArrayList<>();\n t9.add(4);\n tasksMap.put(9, t9);\n\n tasksMap.put(10, new ArrayList<>());\n\n //task to analyze:\n int task = 5;\n\n\n List<Integer> res11 = getTasksInOrderDftReqPostOrder(tasksMap, task);\n System.out.println(res11);**//note, no reverse required**\n\n List<Integer> res12 = getTasksInOrderDftReqPreOrder(tasksMap, task);\n Collections.reverse(res12);//note reverse!\n System.out.println(res12);\n\n private static List<Integer> getTasksInOrderDftReqPreOrder(Map<Integer, List<Integer>> tasksMap, int task) {\n List<Integer> result = new ArrayList<>();\n Set<Integer> visited = new HashSet<>();\n reqPreOrder(tasksMap,task,result, visited);\n return result;\n }\n\nprivate static void reqPreOrder(Map<Integer, List<Integer>> tasksMap, int task, List<Integer> result, Set<Integer> visited) {\n\n if(!visited.contains(task)) {\n visited.add(task);\n result.add(task);//pre order!\n List<Integer> children = tasksMap.get(task);\n if (children != null && children.size() > 0) {\n for (Integer child : children) {\n reqPreOrder(tasksMap,child,result, visited);\n }\n }\n }\n}\n\nprivate static List<Integer> getTasksInOrderDftReqPostOrder(Map<Integer, List<Integer>> tasksMap, int task) {\n List<Integer> result = new ArrayList<>();\n Set<Integer> visited = new HashSet<>();\n reqPostOrder(tasksMap,task,result, visited);\n return result;\n}\n\nprivate static void reqPostOrder(Map<Integer, List<Integer>> tasksMap, int task, List<Integer> result, Set<Integer> visited) {\n if(!visited.contains(task)) {\n visited.add(task);\n List<Integer> children = tasksMap.get(task);\n if (children != null && children.size() > 0) {\n for (Integer child : children) {\n reqPostOrder(tasksMap,child,result, visited);\n }\n }\n result.add(task);//post order!\n }\n}\n List<Integer> res1 = getTasksInOrderDftStack(tasksMap, task);\n Collections.reverse(res1);//note reverse!\n System.out.println(res1);\n\n private static List<Integer> getTasksInOrderDftStack(Map<Integer, List<Integer>> tasksMap, int task) {\n List<Integer> result = new ArrayList<>();\n Set<Integer> visited = new HashSet<>();\n Stack<Integer> st = new Stack<>();\n\n\n st.add(task);\n visited.add(task);\n\n while(!st.isEmpty()){\n Integer node = st.pop();\n List<Integer> children = tasksMap.get(node);\n result.add(node);\n if(children!=null && children.size() > 0){\n for(Integer child:children){\n if(!visited.contains(child)){\n st.add(child);\n visited.add(child);\n }\n }\n }\n //If you put it here - it does not matter - it is anyway a pre-order\n //result.add(node);\n }\n return result;\n}\n dft(n){\n mark(n)\n for(child: n.children){\n if(marked(child)) \n explode - cycle found!!!\n dft(child)\n }\n unmark(n)\n}\n"
},
{
"answer_id": 60530502,
"author": "nonopolarity",
"author_id": 325418,
"author_profile": "https://Stackoverflow.com/users/325418",
"pm_score": 1,
"selected": false,
"text": "n n n n n 20000 n 1000 n 5000 20000"
},
{
"answer_id": 74271649,
"author": "chen",
"author_id": 20064859,
"author_profile": "https://Stackoverflow.com/users/20064859",
"pm_score": 0,
"selected": false,
"text": "def TowerOfHanoi(n , source, destination, auxiliary):\n if n==1:\n print (\"Move disk 1 from source\",source,\"to destination\",destination)\n return\n TowerOfHanoi(n-1, source, auxiliary, destination)\n print (\"Move disk\",n,\"from source\",source,\"to destination\",destination)\n TowerOfHanoi(n-1, auxiliary, destination, source)\n # Python3 program for iterative Tower of Hanoi\nimport sys\n \n# A structure to represent a stack\nclass Stack:\n # Constructor to set the data of\n # the newly created tree node\n def __init__(self, capacity):\n self.capacity = capacity\n self.top = -1\n self.array = [0]*capacity\n \n# function to create a stack of given capacity.\ndef createStack(capacity):\n stack = Stack(capacity)\n return stack\n \n# Stack is full when top is equal to the last index\ndef isFull(stack):\n return (stack.top == (stack.capacity - 1))\n \n# Stack is empty when top is equal to -1\ndef isEmpty(stack):\n return (stack.top == -1)\n \n# Function to add an item to stack.\n# It increases top by 1\ndef push(stack, item):\n if(isFull(stack)):\n return\n stack.top+=1\n stack.array[stack.top] = item\n \n# Function to remove an item from stack.\n# It decreases top by 1\ndef Pop(stack):\n if(isEmpty(stack)):\n return -sys.maxsize\n Top = stack.top\n stack.top-=1\n return stack.array[Top]\n \n# Function to implement legal\n# movement between two poles\ndef moveDisksBetweenTwoPoles(src, dest, s, d):\n pole1TopDisk = Pop(src)\n pole2TopDisk = Pop(dest)\n \n # When pole 1 is empty\n if (pole1TopDisk == -sys.maxsize):\n push(src, pole2TopDisk)\n moveDisk(d, s, pole2TopDisk)\n \n # When pole2 pole is empty\n else if (pole2TopDisk == -sys.maxsize):\n push(dest, pole1TopDisk)\n moveDisk(s, d, pole1TopDisk)\n \n # When top disk of pole1 > top disk of pole2\n else if (pole1TopDisk > pole2TopDisk):\n push(src, pole1TopDisk)\n push(src, pole2TopDisk)\n moveDisk(d, s, pole2TopDisk)\n \n # When top disk of pole1 < top disk of pole2\n else:\n push(dest, pole2TopDisk)\n push(dest, pole1TopDisk)\n moveDisk(s, d, pole1TopDisk)\n \n# Function to show the movement of disks\ndef moveDisk(fromPeg, toPeg, disk):\n print(\"Move the disk\", disk, \"from '\", fromPeg, \"' to '\", toPeg, \"'\")\n \n# Function to implement TOH puzzle\ndef tohIterative(num_of_disks, src, aux, dest):\n s, d, a = 'S', 'D', 'A'\n \n # If number of disks is even, then interchange\n # destination pole and auxiliary pole\n if (num_of_disks % 2 == 0):\n temp = d\n d = a\n a = temp\n total_num_of_moves = int(pow(2, num_of_disks) - 1)\n \n # Larger disks will be pushed first\n for i in range(num_of_disks, 0, -1):\n push(src, i)\n \n for i in range(1, total_num_of_moves + 1):\n if (i % 3 == 1):\n moveDisksBetweenTwoPoles(src, dest, s, d)\n \n else if (i % 3 == 2):\n moveDisksBetweenTwoPoles(src, aux, s, a)\n \n else if (i % 3 == 0):\n moveDisksBetweenTwoPoles(aux, dest, a, d)\n \n# Input: number of disks\nnum_of_disks = 3\n \n# Create three stacks of size 'num_of_disks'\n# to hold the disks\nsrc = createStack(num_of_disks)\ndest = createStack(num_of_disks)\naux = createStack(num_of_disks)\n \ntohIterative(num_of_disks, src, aux, dest)\n if m == 0:\n # BASE CASE\n return n + 1\n elif m > 0 and n == 0:\n # RECURSIVE CASE\n return ackermann(m - 1, 1)\n elif m > 0 and n > 0:\n # RECURSIVE CASE\n return ackermann(m - 1, ackermann(m, n - 1))\n callStack = [{'m': 2, 'n': 3, 'indentation': 0, 'instrPtr': 'start'}]\nreturnValue = None\n\nwhile len(callStack) != 0:\n m = callStack[-1]['m']\n n = callStack[-1]['n']\n indentation = callStack[-1]['indentation']\n instrPtr = callStack[-1]['instrPtr']\n\n if instrPtr == 'start':\n print('%sackermann(%s, %s)' % (' ' * indentation, m, n))\n\n if m == 0:\n # BASE CASE\n returnValue = n + 1\n callStack.pop()\n continue\n elif m > 0 and n == 0:\n # RECURSIVE CASE\n callStack[-1]['instrPtr'] = 'after first recursive case'\n callStack.append({'m': m - 1, 'n': 1, 'indentation': indentation + 1, 'instrPtr': 'start'})\n continue\n elif m > 0 and n > 0:\n # RECURSIVE CASE\n callStack[-1]['instrPtr'] = 'after second recursive case, inner call'\n callStack.append({'m': m, 'n': n - 1, 'indentation': indentation + 1, 'instrPtr': 'start'})\n continue\n elif instrPtr == 'after first recursive case':\n returnValue = returnValue\n callStack.pop()\n continue\n elif instrPtr == 'after second recursive case, inner call':\n callStack[-1]['innerCallResult'] = returnValue\n callStack[-1]['instrPtr'] = 'after second recursive case, outer call'\n callStack.append({'m': m - 1, 'n': returnValue, 'indentation': indentation + 1, 'instrPtr': 'start'})\n continue\n elif instrPtr == 'after second recursive case, outer call':\n returnValue = returnValue\n callStack.pop()\n continue\nprint(returnValue)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
] |
72,220 |
<p>I'm a Java-developer toying with Ruby, and loving it. I have understood that because of Ruby's metaprogramming facilities my unit-tests become much cleaner and I don't need nasty mocking frameworks. I have a class which needs the <code>File</code> class's services and in my test I don't want to touch my real filesystem. In Java I would use some virtual file system for easier "seams" to pass fake-objects in but in Ruby that's obviously overkill. What I come up seems already really nice compared to the Java-world. In my class under test I have an optional constructor parameter: </p>
<pre><code>def initialize(file_class=File)
</code></pre>
<p>When I need to open files within my class, I can then do this:</p>
<pre><code>@file_class.open(filename)
</code></pre>
<p>And the call goes to either the real File-class, or in case of my unit-test, it goes to a fake-class which doesn't touch the filesystem. I know there must be a better way to do this with metaprogramming?</p>
|
[
{
"answer_id": 72248,
"author": "Brian Phillips",
"author_id": 7230,
"author_profile": "https://Stackoverflow.com/users/7230",
"pm_score": 4,
"selected": false,
"text": "\nrequire 'mocha'\n\nmock_file_obj = mock(\"My Mock File\") do\n stubs(:some_instance_method).returns(\"foo\")\nend\n\nFile.stubs(:new).with(is_a(String)).returns(mock_file_obj)\n"
},
{
"answer_id": 17243303,
"author": "Mulan",
"author_id": 633183,
"author_profile": "https://Stackoverflow.com/users/633183",
"pm_score": 1,
"selected": false,
"text": "# lib/real_thing.rb\nclass RealThing\n def initialize a, b, c\n # ...\n end\nend\n\n# test/test_real_thing.rb\nclass TestRealThing < MiniTest::Unit::TestCase\n\n class Fake < RealThing; end\n\n def test_real_thing_initializer\n fake = mock()\n Fake.expects(:new).with(1, 2, 3).returns(fake)\n assert_equal fake, Fake.new(1, 2, 3)\n end\n\nend\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4110/"
] |
72,237 |
<p>I recently came across an issue with Windows 2003 (apparently it also exists in other versions too), where if an SSL/TLS server is requesting client certificate authentication and it has more than 16KB of trusted certificate DNs, Internet Explorer (or any other app that uses schannel.dll) is unable to complete the SSL handshake. (In a nutshell, the server breaks the message into chunks of 2^14 bytes, as per RFC 2246 sec. 6.2.1, but Schannel wasn't written to support that. I've gotten confirmation from Microsoft support that this is a flaw in Schannel and that they're considering fixing it in a future release.)</p>
<p>So I'm trying to find a way to easily parse through my trusted certificates (I use Apache as my server, so all of them are in PEM format) to get the total ASN.1-format length of the DNs (which is how they get sent over the wire during the handshake), and thereby see if I'm getting too close to the limit. I haven't yet been able to find a way to do this, though: the OpenSSL asn1parse function comes close, but it doesn't seem to provide a way to get the ASN.1 sequence for just the issuer name, which is what I need.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 189109,
"author": "Seth",
"author_id": 20503,
"author_profile": "https://Stackoverflow.com/users/20503",
"pm_score": 0,
"selected": false,
"text": " 0:d=0 hl=4 l= 621 cons: SEQUENCE\n 4:d=1 hl=4 l= 470 cons: SEQUENCE\n 8:d=2 hl=2 l= 3 cons: cont [ 0 ]\n 10:d=3 hl=2 l= 1 prim: INTEGER :02\n 13:d=2 hl=2 l= 1 prim: INTEGER :02\n 16:d=2 hl=2 l= 13 cons: SEQUENCE\n 18:d=3 hl=2 l= 9 prim: OBJECT :sha1WithRSAEncryption\n 29:d=3 hl=2 l= 0 prim: NULL\n 31:d=2 hl=2 l= 64 cons: SEQUENCE\n 33:d=3 hl=2 l= 11 cons: SET\n 35:d=4 hl=2 l= 9 cons: SEQUENCE\n 37:d=5 hl=2 l= 3 prim: OBJECT :countryName\n 42:d=5 hl=2 l= 2 prim: PRINTABLESTRING :US\n 46:d=3 hl=2 l= 26 cons: SET\n 48:d=4 hl=2 l= 24 cons: SEQUENCE\n 50:d=5 hl=2 l= 3 prim: OBJECT :organizationName\n 55:d=5 hl=2 l= 17 prim: PRINTABLESTRING :Test Certificates\n 74:d=3 hl=2 l= 21 cons: SET\n 76:d=4 hl=2 l= 19 cons: SEQUENCE\n 78:d=5 hl=2 l= 3 prim: OBJECT :commonName\n 83:d=5 hl=2 l= 12 prim: PRINTABLESTRING :Trust Anchor\n 97:d=2 hl=2 l= 30 cons: SEQUENCE\n 99:d=3 hl=2 l= 13 prim: UTCTIME :010419145720Z\n 114:d=3 hl=2 l= 13 prim: UTCTIME :110419145720Z\n 129:d=2 hl=2 l= 59 cons: SEQUENCE\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12204/"
] |
72,242 |
<p>The page <em><a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">Protecting Your Cookies: HttpOnly</a></em> explains why making HttpOnly cookies is a good idea.</p>
<p>How do I set this property in Ruby on Rails?</p>
|
[
{
"answer_id": 4470104,
"author": "jim",
"author_id": 468629,
"author_profile": "https://Stackoverflow.com/users/468629",
"pm_score": 4,
"selected": false,
"text": ":http_only :httponly :http_only"
},
{
"answer_id": 40474742,
"author": "ilgam",
"author_id": 3834822,
"author_profile": "https://Stackoverflow.com/users/3834822",
"pm_score": 2,
"selected": false,
"text": "config/initializers/session_store.rb # Be sure to restart your server when you modify this file.\nRails.application.config.session_store :cookie_store, key: \"_my_application_session\"\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
] |
72,264 |
<p>I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE. </p>
<p>What are the steps to create such an executable?</p>
|
[
{
"answer_id": 72296,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 5,
"selected": true,
"text": "namespace MyLib\n{\n public class MyClass\n {\n static MyClass()\n {\n ResourceExtractor.ExtractResourceToFile(\"MyLib.ManagedService.dll\", \"managedservice.dll\");\n ResourceExtractor.ExtractResourceToFile(\"MyLib.UnmanagedService.dll\", \"unmanagedservice.dll\");\n }\n\n ...\n public static class ResourceExtractor\n{\n public static void ExtractResourceToFile(string resourceName, string filename)\n {\n if (!System.IO.File.Exists(filename))\n using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))\n using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))\n {\n byte[] b = new byte[s.Length];\n s.Read(b, 0, b.Length);\n fs.Write(b, 0, b.Length);\n }\n }\n}\n [DllImport(\"unmanagedservice.dll\")] public extern static int Add(int a, int b);\n"
},
{
"answer_id": 72357,
"author": "Raithlin",
"author_id": 6528,
"author_profile": "https://Stackoverflow.com/users/6528",
"pm_score": 2,
"selected": false,
"text": "/clr ilmerge /out:Composite.exe MyMainApp.exe Utility.dll\n"
},
{
"answer_id": 6362480,
"author": "Lars Holm Jensen",
"author_id": 348005,
"author_profile": "https://Stackoverflow.com/users/348005",
"pm_score": 2,
"selected": false,
"text": "public App()\n{\n AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n}\n\nSystem.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(\".dll\",\"\");\n\n dllName = dllName.Replace(\".\", \"_\");\n\n if (dllName.EndsWith(\"_resources\")) return null;\n\n System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + \".Properties.Resources\", System.Reflection.Assembly.GetExecutingAssembly());\n\n byte[] bytes = (byte[])rm.GetObject(dllName);\n\n return System.Reflection.Assembly.Load(bytes);\n}\n"
},
{
"answer_id": 10599956,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 0,
"selected": false,
"text": "ResolveHandler ResolveHandler static void Main()\n{\n AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n {\n string assemblyName = new AssemblyName(args.Name).Name;\n if (assemblyName.EndsWith(\".resources\"))\n return null;\n\n string dllName = assemblyName + \".dll\";\n string dllFullPath = Path.Combine(GetMyApplicationSpecificPath(), dllName);\n\n using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + \".Resources.\" + dllName))\n {\n byte[] data = new byte[stream.Length];\n s.Read(data, 0, data.Length);\n\n //or just byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);\n\n File.WriteAllBytes(dllFullPath, data);\n }\n\n return Assembly.LoadFrom(dllFullPath);\n };\n}\n GetMyApplicationSpecificPath()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12113/"
] |
72,271 |
<p>What is the reason for the following warning in some C++ compilers?</p>
<blockquote>
<p>No newline at end of file</p>
</blockquote>
<p>Why should I have an empty line at the end of a source/header file?</p>
|
[
{
"answer_id": 72391,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 3,
"selected": false,
"text": "#include #include"
},
{
"answer_id": 72409,
"author": "TJ Seabrooks",
"author_id": 3022,
"author_profile": "https://Stackoverflow.com/users/3022",
"pm_score": 9,
"selected": true,
"text": "#include #include <foo.h> foo.h foo.cpp foo.cpp"
},
{
"answer_id": 6773704,
"author": "keya",
"author_id": 855566,
"author_profile": "https://Stackoverflow.com/users/855566",
"pm_score": -1,
"selected": false,
"text": "#include <iostream> <iostream.h> using std::cout;"
},
{
"answer_id": 27624582,
"author": "Jan-Philip Loos",
"author_id": 605745,
"author_profile": "https://Stackoverflow.com/users/605745",
"pm_score": 2,
"selected": false,
"text": "GL_ARB_shading_language_include MyHeader.h #endif // __MY_HEADER_H__ #include \"MyHeader.h\""
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
72,275 |
<p>Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn't? In which cases will it save me the use of locking?</p>
|
[
{
"answer_id": 72328,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 4,
"selected": false,
"text": "volatile"
},
{
"answer_id": 73076,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 6,
"selected": false,
"text": "#include <iostream>\nvoid main()\n{\n int j = 0;\n for (int i = 0 ; i < 100 ; ++i)\n {\n j += i;\n }\n for (volatile int i = 0 ; i < 100 ; ++i)\n {\n j += i;\n }\n std::cout << j;\n}\n void main()\n{\n00401000 push ecx \n int j = 0;\n00401001 xor ecx,ecx \n for (int i = 0 ; i < 100 ; ++i)\n00401003 xor eax,eax \n00401005 mov edx,1 \n0040100A lea ebx,[ebx] \n {\n j += i;\n00401010 add ecx,eax \n00401012 add eax,edx \n00401014 cmp eax,64h \n00401017 jl main+10h (401010h) \n }\n for (volatile int i = 0 ; i < 100 ; ++i)\n00401019 mov dword ptr [esp],0 \n00401020 mov eax,dword ptr [esp] \n00401023 cmp eax,64h \n00401026 jge main+3Eh (40103Eh) \n00401028 jmp main+30h (401030h) \n0040102A lea ebx,[ebx] \n {\n j += i;\n00401030 add ecx,dword ptr [esp] \n00401033 add dword ptr [esp],edx \n00401036 mov eax,dword ptr [esp] \n00401039 cmp eax,64h \n0040103C jl main+30h (401030h) \n }\n std::cout << j;\n0040103E push ecx \n0040103F mov ecx,dword ptr [__imp_std::cout (40203Ch)] \n00401045 call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (402038h)] \n}\n0040104B xor eax,eax \n0040104D pop ecx \n0040104E ret \n"
},
{
"answer_id": 35274777,
"author": "Aliaksei Maniuk",
"author_id": 1370029,
"author_profile": "https://Stackoverflow.com/users/1370029",
"pm_score": 1,
"selected": false,
"text": " private static int _flag = 0;\n private static int _value = 0;\n\n var t1 = Task.Run(() =>\n {\n _value = 10; /* compiler could switch these lines */\n _flag = 5;\n });\n\n var t2 = Task.Run(() =>\n {\n if (_flag == 5)\n {\n Console.WriteLine(\"Value: {0}\", _value);\n }\n });\n private static volatile int _flag = 0;\n"
},
{
"answer_id": 58905467,
"author": "Christina Katsakoula",
"author_id": 12388334,
"author_profile": "https://Stackoverflow.com/users/12388334",
"pm_score": 3,
"selected": false,
"text": "When you mark an object or a variable as volatile, it becomes a candidate for volatile reads and writes. It should be noted that in C# all memory writes are volatile irrespective of whether you are writing data to a volatile or a non-volatile object. However, the ambiguity happens when you are reading data. When you are reading data that is non-volatile, the executing thread may or may not always get the latest value. If the object is volatile, the thread always gets the most up-to-date value"
},
{
"answer_id": 65144763,
"author": "Yarl",
"author_id": 5987619,
"author_profile": "https://Stackoverflow.com/users/5987619",
"pm_score": 3,
"selected": false,
"text": "public class Worker\n{\n public void DoWork()\n {\n bool work = false;\n while (!_shouldStop)\n {\n work = !work; // simulate some work\n }\n Console.WriteLine(\"Worker thread: terminating gracefully.\");\n }\n public void RequestStop()\n {\n _shouldStop = true;\n }\n \n private volatile bool _shouldStop;\n}\n using System;\nusing System.Threading;\nclass Test\n{\n public static int result; \n public static volatile bool finished;\n static void Thread2() {\n result = 143; \n finished = true; \n }\n static void Main() {\n\n finished = false;\n new Thread(new ThreadStart(Thread2)).Start();\n\n for (;;) {\n if (finished) {\n Console.WriteLine(\"result = {0}\", result);\n return;\n }\n }\n }\n}\n volatile volatile volatile lock Interlocked"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3389/"
] |
72,281 |
<p>Receiving the following error when attempting to run a CLR stored proc. Any help is much appreciated.</p>
<pre><code>Msg 10314, Level 16, State 11, Line 1
An error occurred in the Microsoft .NET Framework while trying to load assembly id 65752. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:
System.IO.FileLoadException: Could not load file or assembly 'orders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A)
System.IO.FileLoadException:
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
</code></pre>
|
[
{
"answer_id": 72463,
"author": "homeskillet",
"author_id": 3400,
"author_profile": "https://Stackoverflow.com/users/3400",
"pm_score": 6,
"selected": false,
"text": "USE database_name\nGO\n\nEXEC sp_changedbowner 'sa'\nALTER DATABASE database_name SET TRUSTWORTHY ON \n"
},
{
"answer_id": 25848214,
"author": "Musakkhir Sayyed",
"author_id": 3894854,
"author_profile": "https://Stackoverflow.com/users/3894854",
"pm_score": -1,
"selected": false,
"text": "ALTER AUTHORIZATION ON DATABASE::mydb TO sa;\nALTER DATABASE [myDB] SET TRUSTWORTHY ON\nGO\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3400/"
] |
72,298 |
<p>Visual Studio solutions contain two types of hidden user files. One is the solution <code>.suo</code> file which is a binary file. The other is the project <code>.user</code> file which is a text file. Exactly what data do these files contain?</p>
<p>I've also been wondering whether I should add these files to source control (Subversion in my case). If I don't add these files and another developer checks out the solution, will Visual Studio automatically create new user files?</p>
|
[
{
"answer_id": 84115,
"author": "JXG",
"author_id": 15456,
"author_profile": "https://Stackoverflow.com/users/15456",
"pm_score": 6,
"selected": false,
"text": "*.suo *.user svn:ignore"
},
{
"answer_id": 51533299,
"author": "adheen",
"author_id": 1320144,
"author_profile": "https://Stackoverflow.com/users/1320144",
"pm_score": 1,
"selected": false,
"text": "<LocalDebuggerEnvironment>PATH=C:\\xyz\\bin$(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>"
},
{
"answer_id": 54726210,
"author": "Stephen Kennedy",
"author_id": 397817,
"author_profile": "https://Stackoverflow.com/users/397817",
"pm_score": 2,
"selected": false,
"text": "global-ignore"
},
{
"answer_id": 55900626,
"author": "AntonK",
"author_id": 536172,
"author_profile": "https://Stackoverflow.com/users/536172",
"pm_score": 2,
"selected": false,
"text": ".suo .user .suo .vs .user .user.SAMPLE"
},
{
"answer_id": 66044006,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 3,
"selected": false,
"text": ".gitignore .suo dotnet tool install -g suo\n keys view suo keys <path-to-suo-file>\n nuget\nProjInfoEx\nBookmarkState\nDebuggerWatches\nHiddenSlnFolders\nObjMgrContentsV8\nUnloadedProjects\nClassViewContents\nOutliningStateDir\nProjExplorerState\nTaskListShortcuts\nXmlPackageOptions\nBackgroundLoadData\nDebuggerExceptions\nDebuggerFindSource\nDebuggerFindSymbol\nILSpy-234190A6EE66\nMRU Solution Files\nUnloadedProjectsEx\nApplicationInsights\nDebuggerBreakpoints\nOutliningStateV1674\n...\n view $ suo view nuget --format=utf8 .suo\nnuget\n\n?{\"WindowSettings\":{\"project:MyProject\":{\"SourceRepository\":\"nuget.org\",\"ShowPreviewWindow\":false,\"ShowDeprecatedFrameworkWindow\":true,\"RemoveDependencies\":false,\"ForceRemove\":false,\"IncludePrerelease\":false,\"SelectedFilter\":\"UpdatesAvailable\",\"DependencyBehavior\":\"Lowest\",\"FileConflictAction\":\"PromptUser\",\"OptionsExpanded\":false,\"SortPropertyName\":\"ProjectName\",\"SortDirection\":\"Ascending\"}}}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203/"
] |
72,304 |
<p>I'd like to add the <code>HttpOnly</code> flag to <code>JSF/richfaces</code> cookies, especially the session cookie, to up the level of security on my web app. Any ideas? </p>
|
[
{
"answer_id": 72371,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 0,
"selected": false,
"text": "response.setHeader(\"Set-Cookie\", \"yourcookiename=yourcookievalue; HTTPOnly\");\n"
},
{
"answer_id": 75371,
"author": "user13229",
"author_id": 13229,
"author_profile": "https://Stackoverflow.com/users/13229",
"pm_score": 1,
"selected": false,
"text": "FacesContext facesContext = FacesContext.getCurrentInstance().getFacesContext();\n\nHttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();\n\nresponse.addHeader(\"Set-Cookie\", \"yourcookiename=yourcookievalue; HTTPOnly\");\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
72,312 |
<p>PERL? Perl? perl? What's good style?</p>
<p>I know the answer—I just wanted to make sure the question was out there and questioners were aware that there is a correct form.</p>
|
[
{
"answer_id": 736455,
"author": "Peter Krumins",
"author_id": 80237,
"author_profile": "https://Stackoverflow.com/users/80237",
"pm_score": 1,
"selected": false,
"text": "perl"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/423836/"
] |
72,358 |
<p>I am using Tomcat as a server and Internet Explorer 6 as a browser. A web page in our app has about 75 images. We are using SSL. It seems to be very slow at loading all the content. How can I configure Tomcat so that IE caches the images?</p>
|
[
{
"answer_id": 83182,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 4,
"selected": true,
"text": "<Location /images>\n FileEtag none\n ExpiresActive on\n ExpiresDefault \"access plus 1 month\"\n</Location>\n SetEnvIf User-Agent \".*MSIE.*\" \\\n nokeepalive ssl-unclean-shutdown \\\n downgrade-1.0 force-response-1.0\n BrowserMatch \"MSIE [1-4]\" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0\nBrowserMatch \"MSIE [5-9]\" ssl-unclean-shutdown\n"
},
{
"answer_id": 84091,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 3,
"selected": false,
"text": "<Files ~ \"\\.(gif|jpe?g|png|ico|css|js|cab|jar|swf)$\">\n # Expire these things\n # Three days after access time\n ExpiresDefault \"now plus 3 days\"\n # This makes Firefox 3 cache images over SSL\n Header set Cache-Control public\n</Files>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959/"
] |
72,360 |
<p>here is what a I'm doing: </p>
<pre><code>object ReturnMatch(System.Type type)
{
foreach(object obj in myObjects)
{
if (obj == type)
{
return obj;
}
}
}
</code></pre>
<p>However, if obj is a subclass of <code>type</code>, it will not match. But I would like the function to return the same way as if I was using the operator <code>is</code>.</p>
<p>I tried the following, but it won't compile:</p>
<pre><code>if (obj is type) // won't compile in C# 2.0
</code></pre>
<p>The best solution I came up with was:</p>
<pre><code>if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))
</code></pre>
<p>Isn't there a way to use operator <code>is</code> to make the code cleaner?</p>
|
[
{
"answer_id": 72384,
"author": "Thunder3",
"author_id": 2832,
"author_profile": "https://Stackoverflow.com/users/2832",
"pm_score": 2,
"selected": false,
"text": "type.IsAssignableFrom(obj.GetType())\n"
},
{
"answer_id": 72407,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "if(obj is type)\n"
},
{
"answer_id": 72503,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 0,
"selected": false,
"text": "foreach(object obj in myObjects)\n{\n if (obj is type)\n {\n return obj;\n }\n}\n class Level1\n {\n }\n\n class Level2A : Level1\n {\n }\n\n class Level2B : Level1\n {\n }\n\n class Level3A2A : Level2A\n {\n }\n\n\n class Program\n {\n static void Main(string[] args)\n {\n object[] objects = new object[] {\"testing\", new Level1(), new Level2A(), new Level2B(), new Level3A2A(), new object() };\n\n\n ReturnMatch(typeof(Level1), objects);\n Console.ReadLine();\n }\n\n\n static void ReturnMatch(Type arbitraryType, object[] objects)\n {\n foreach (object obj in objects)\n {\n Type objType = obj.GetType();\n\n Console.Write(arbitraryType.ToString() + \" is \");\n\n if (!arbitraryType.IsAssignableFrom(objType))\n Console.Write(\"not \");\n\n Console.WriteLine(\"assignable from \" + objType.ToString());\n\n }\n }\n }\n"
},
{
"answer_id": 72550,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 4,
"selected": true,
"text": "Type theTypeWeWant; // From argument or whatever\nforeach (object o in myCollection)\n{\n if (theTypeWeWant.IsAssignableFrom(o.GetType))\n return o;\n}\n private T FindObjectOfType<T>() where T: class\n{\n foreach(object o in myCollection)\n {\n if (o is T)\n return (T) o;\n }\n return null;\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10833/"
] |
72,381 |
<p>I'm trying to use the following code but it's returning the wrong day of month.</p>
<pre><code>Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);
cal.set(Calendar.DAY_OF_MONTH, 0);
return cal.getTime();
</code></pre>
|
[
{
"answer_id": 72438,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 5,
"selected": true,
"text": "\nCalendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\nint noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);\n \nCalendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\ncal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));\n"
},
{
"answer_id": 72460,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 2,
"selected": false,
"text": "Calendar cal = Calendar.getInstance();\ncal.setTime(sampleDay.getTime());\ncal.roll(Calendar.MONTH, true);\ncal.set(Calendar.DAY_OF_MONTH, 0);\ncal.add(Calendar.DAY_OF_MONTH, -1);\n DateTime date = new DateTime(sampleDay.getTime());\nreturn date.plusMonths(1).withDayOfMonth(0).minusDays(1).getMillis();\n"
},
{
"answer_id": 4981993,
"author": "John",
"author_id": 157080,
"author_profile": "https://Stackoverflow.com/users/157080",
"pm_score": 1,
"selected": false,
"text": "DateTime monthEnd = dt.getEndOfMonth();\n"
},
{
"answer_id": 13409132,
"author": "Nick",
"author_id": 1828375,
"author_profile": "https://Stackoverflow.com/users/1828375",
"pm_score": -1,
"selected": false,
"text": "Dim MyDate As Date = #11/14/2012# 'This is just an example date\n\nMyDate = MyDate.AddDays(DateTime.DaysInMonth(MyDate.Year, MyDate.Month) - MyDate.Day)\n"
},
{
"answer_id": 38032903,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "YearMonth.from(\n LocalDate.now( ZoneId.of( \"America/Montreal\" ) )\n).atEndOfMonth()\n LocalDate LocalDate ZoneId zoneId = ZoneId.of( \"America/Montreal\" );\nLocalDate today = LocalDate.now( zoneId ); // 2016-06-25\n YearMonth YearMonth YearMonth currentYearMonth = YearMonth.from( today ); // 2016-06\nLocalDate lastDayOfCurrentYearMonth = currentYearMonth.atEndOfMonth(); // 2016-06-30\n LocalDate YearMonth TemporalAdjuster TemporalAdjuster"
},
{
"answer_id": 46914556,
"author": "Pierre Henry",
"author_id": 315677,
"author_profile": "https://Stackoverflow.com/users/315677",
"pm_score": 2,
"selected": false,
"text": "TemporalAdjuster date LocalDate LocalDate date = LocalDate.of(2018, 1, 22);\n LocalDate date = LocalDate.now();\n TemporalAdjuster TemporalAdjusters LocalDate first = date.with(TemporalAdjusters.firstDayOfMonth());\nLocalDate last = date.with(TemporalAdjusters.lastDayOfMonth());\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
72,393 |
<p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:</p>
<pre><code>result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness")
# result is None`
</code></pre>
<p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p>
<pre><code>regex = ".*(a_regex_of_pure_awesomeness)"
</code></pre>
<p>into</p>
<pre><code>regex = "a_regex_of_pure_awesomeness"
</code></pre>
<p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
|
[
{
"answer_id": 72449,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "re.match() re.search() re.match() ^ re.search() ^"
},
{
"answer_id": 72501,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 2,
"selected": false,
"text": ">>> import re\n>>> pattern = re.compile(\"url\")\n>>> string = \" url\"\n>>> pattern.match(string)\n>>> pattern.search(string)\n<_sre.SRE_Match object at 0xb7f7a6e8>\n"
},
{
"answer_id": 78072,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "from BeautifulSoup import BeautifulSoup \n\nsoup = BeautifulSoup(your_html)\nfor a in soup.findAll('a', href=True):\n # do something with `a` w/ href attribute\n print a['href']\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
72,410 |
<p>How should I store (and present) the text on a website intended for worldwide use, with several languages? The content is mostly in the form of 500+ word articles, although I will need to translate tiny snippets of text on each page too (such as "print this article" or "back to menu").</p>
<p>I know there are several CMS packages that handle multiple languages, but I have to integrate with our existing ASP systems too, so I am ignoring such solutions.</p>
<p>One concern I have is that Google should be able to find the pages, even for foreign users. I am less concerned about issues with processing dates and currencies.</p>
<p>I worry that, left to my own devices, I will invent a way of doing this which work, but eventually lead to disaster! I want to know what professional solutions you have actually used on real projects, not untried ideas! Thanks very much.</p>
<hr>
<p>I looked at RESX files, but felt they were unsuitable for all but the most trivial translation solutions (I will elaborate if anyone wants to know).</p>
<p>Google will help me with translating the text, but not storing/presenting it.</p>
<p>Has anyone worked on a multi-language project that relied on their own code for presentation?</p>
<hr>
<p>Any thoughts on serving up content in the following ways, and which is best?</p>
<ul>
<li><a href="http://www.website.com/text/view.asp?id=12345&lang=fr" rel="nofollow noreferrer">http://www.website.com/text/view.asp?id=12345&lang=fr</a></li>
<li><a href="http://www.website.com/text/12345/bonjour_mes_amis.htm" rel="nofollow noreferrer">http://www.website.com/text/12345/bonjour_mes_amis.htm</a></li>
<li><a href="http://fr.website.com/text/12345" rel="nofollow noreferrer">http://fr.website.com/text/12345</a></li>
</ul>
<p>(these are not real URLs, i was just showing examples)</p>
|
[
{
"answer_id": 120364,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": true,
"text": "<%$ Resources: LanguageProvider, Path/To/Localisation %>\n <globalization resourceProviderFactoryType=\"FactoryClassName, AssemblyName\"/>\n FactoryClassName ResourceProviderFactory"
},
{
"answer_id": 933135,
"author": "ilya n.",
"author_id": 115200,
"author_profile": "https://Stackoverflow.com/users/115200",
"pm_score": 0,
"selected": false,
"text": "site.com/content/example.fr /content/example .html example example.fr\nexample.en\nexample.vi\n example.vi example.en"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11461/"
] |
72,442 |
<p>I have a nullable property, and I want to return a null value. How do I do that in VB.NET ?</p>
<p>Currently I use this solution, but I think there might be a better way.</p>
<pre><code> Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
Get
If Current.Request.QueryString("rid") <> "" Then
Return CInt(Current.Request.QueryString("rid"))
Else
Return (New Nullable(Of Integer)).Value
End If
End Get
End Property
</code></pre>
|
[
{
"answer_id": 78272,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 1,
"selected": false,
"text": "Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n If Current.Request.QueryString(\"rid\") <> \"\" Then\n Return CInt(Current.Request.QueryString(\"rid\"))\n Else\n Return Nothing\n End If\n End Get\nEnd Property\n"
},
{
"answer_id": 439923,
"author": "Barbaros Alp",
"author_id": 51734,
"author_profile": "https://Stackoverflow.com/users/51734",
"pm_score": 0,
"selected": false,
"text": "finder.Advisor = ucEstateFinder.Advisor == \"-1\" ? (long?)null : long.Parse(ucEstateFinder.Advisor);\n (long?)null"
},
{
"answer_id": 21494597,
"author": "Mark Hurd",
"author_id": 256431,
"author_profile": "https://Stackoverflow.com/users/256431",
"pm_score": 0,
"selected": false,
"text": "Nothing .Value Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n If Current.Request.QueryString(\"rid\") <> \"\" Then\n Return CInt(Current.Request.QueryString(\"rid\"))\n Else\n Return New Nullable(Of Integer)\n End If\n End Get\nEnd Property\n If Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)\n Get\n Return If(Current.Request.QueryString(\"rid\") <> \"\", _\n CInt(Current.Request.QueryString(\"rid\")), _\n New Nullable(Of Integer))\n End Get\nEnd Property\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6776/"
] |
72,458 |
<p><strong>Problem</strong></p>
<p>I need to redirect some short convenience URLs to longer actual URLs. The site in question uses a set of subdomains to identify a set of development or live versions.</p>
<p>I would like the URL to which certain requests are redirected to include the HTTP_HOST such that I don't have to create a custom .htaccess file for each host.</p>
<p><strong>Host-specific Example (snipped from .htaccess file)</strong></p>
<pre><code>Redirect /terms http://support.dev01.example.com/articles/terms/
</code></pre>
<p>This example works fine for the development version running at dev01.example.com. If I use the same line in the main .htaccess file for the development version running under dev02.example.com I'd end up being redirected to the wrong place.</p>
<p><strong>Ideal rule (not sure of the correct syntax)</strong></p>
<pre><code>Redirect /terms http://support.{HTTP_HOST}/articles/terms/
</code></pre>
<p>This rule does not work and merely serves as an example of what I'd like to achieve. I could then use the exact same rule under many different hosts and get the correct result.</p>
<p><strong>Answers?</strong></p>
<ul>
<li>Can this be done with mod_alias or does it require the more complex mod_rewrite?</li>
<li>How can this be achieved using mod_alias or mod_rewrite? I'd prefer a mod_alias solution if possible.</li>
</ul>
<p><strong>Clarifications</strong></p>
<p>I'm not staying on the same server. I'd like:</p>
<ul>
<li>http://<strong>example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>example.com</strong>/articles/terms/</li>
<li><a href="https://secure" rel="nofollow noreferrer">https://secure</a>.<strong>example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>example.com</strong>/articles/terms/</li>
<li>http://<strong>dev.example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>dev.example.com</strong>/articles/terms/</li>
<li><a href="https://secure" rel="nofollow noreferrer">https://secure</a>.<strong>dev.example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>dev.example.com</strong>/articles/terms/</li>
</ul>
<p>I'd like to be able to use the same rule in the .htaccess file on both example.com and dev.example.com. In this situation I'd need to be able to refer to the HTTP_HOST as a variable rather than specifying it literally in the URL to which requests are redirected.</p>
<p>I'll investigate the HTTP_HOST parameter as suggested but was hoping for a working example.</p>
|
[
{
"answer_id": 72530,
"author": "Nicholas",
"author_id": 8054,
"author_profile": "https://Stackoverflow.com/users/8054",
"pm_score": -1,
"selected": false,
"text": "RewriteCond %{HTTP_HOST} ^www\\.domain\\.com$ [NC]\nRewriteRule ^(.*)$ http://www.domain2.com/$1\n"
},
{
"answer_id": 72597,
"author": "Colonel Sponsz",
"author_id": 11651,
"author_profile": "https://Stackoverflow.com/users/11651",
"pm_score": -1,
"selected": false,
"text": "RedirectMatch 301 ^/terms$ /articles/terms/\n http://example.com/terms -> http://example.com/articles/terms\n http://test.example.com/terms -> http://test.example.com/articles/terms\n http://example.com/terms -> http://server02.example.com/articles/terms\n"
},
{
"answer_id": 72652,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": -1,
"selected": false,
"text": "Redirect temp /terms /articles/terms/\n"
},
{
"answer_id": 72707,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": -1,
"selected": false,
"text": "Alias /terms /www/public/articles/terms/\n"
},
{
"answer_id": 72828,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 0,
"selected": false,
"text": "RewriteCond %{HTTP_HOST} (.*)\nRewriteRule ^/terms http://support.%1/article/terms [NC,R=302]\n"
},
{
"answer_id": 10010128,
"author": "jornare",
"author_id": 1249477,
"author_profile": "https://Stackoverflow.com/users/1249477",
"pm_score": 0,
"selected": false,
"text": "//301 Redirect Entire Directory\nRedirectMatch 301 /terms(.*) /articles/terms/$1\n\n//Change default directory page\nDirectoryIndex \n"
},
{
"answer_id": 10024434,
"author": "Olivier Pons",
"author_id": 106140,
"author_profile": "https://Stackoverflow.com/users/106140",
"pm_score": 3,
"selected": true,
"text": "RewriteCond %{HTTP_HOST} support\\.(([^\\.]+))\\.example\\.com\nRewriteRule ^/terms http://support.%1/article/terms [NC,QSA,R]\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5343/"
] |
72,479 |
<p>Can anyone tell me what exactly does this Java code do?</p>
<pre><code>SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[20];
synchronized (random)
{
random.nextBytes(bytes);
}
return Base64.encode(bytes);
</code></pre>
<hr>
<p>Step by step explanation will be useful so that I can recreate this code in VB. Thanks</p>
|
[
{
"answer_id": 72588,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "SecureRandom random = SecureRandom.getInstance(\"SHA1PRNG\");\nbyte[] bytes = new byte[20];\nsynchronized (random) { random.nextBytes(bytes); }\nreturn Base64.encode(bytes);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12178/"
] |
72,482 |
<p>Is it possible in a large GWT project, load some portion of JavaScript lazy, on the fly?
Like overlays. </p>
<p>PS: Iframes is not a solution.</p>
|
[
{
"answer_id": 76295,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 0,
"selected": false,
"text": "<body onload=\"onloadHandler();\">\n<script type=\"text/javascript\">\nfunction onloadHandler() {\n if (document.createElement && document.getElementsByTagName) {\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = './test.js';\n var heads = document.getElementsByTagName('head');\n if (heads && heads[0]) {\n heads[0].appendChild(script);\n }\n }\n}\nfunction iAmReady(theName) {\n if ('undefined' != typeof window[theName]) {\n window[theName]();\n }\n}\nfunction test() {\n // stuff to do when test.js loads\n} \n</script>\n iAmReady('test');\n appendChild()"
},
{
"answer_id": 967116,
"author": "Eric Walker",
"author_id": 61048,
"author_profile": "https://Stackoverflow.com/users/61048",
"pm_score": 3,
"selected": false,
"text": "GWT.runAsync JavaScript GWT"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12259/"
] |
72,515 |
<p>I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?</p>
<p>I would like to be able to use a RichTextBox to allow better formatting of the input value.
Can this be done without creating a custom editor class?</p>
|
[
{
"answer_id": 72651,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 3,
"selected": true,
"text": "[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]\npublic override string Text\n{\n get { return _string; }\n set { _string = value; }\n}\n [Editor(\"System.Windows.Forms.Design.StringArrayEditor, \n System.Design, Version=2.0.0.0, \n Culture=neutral, \n PublicKeyToken=b03f5f7f11d50a3a\", \n typeof(UITypeEditor))]\npublic string[] Lines\n{\n get { return _lines; }\n set { _lines = value; }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2533/"
] |
72,528 |
<p>How would you create a database in Microsoft Access that is searchable only by certain fields and controlled by only a few (necessary) text boxes and check boxes on a form so it is easy to use - no difficult queries?</p>
<p>Example:
You have several text boxes and several corresponding check boxes on a form, and when the check box next to the text box is checked, the text box is enabled and you can then search by what is entered into said text box</p>
<p>(Actually I already know this, just playing stackoverflow jeopardy, where I ask a question I know the answer just to increase the world's coding knowledge! answer coming in about 5 mins)</p>
|
[
{
"answer_id": 72798,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 1,
"selected": false,
"text": "*cable* *cable*"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
72,537 |
<p>In a SharePoint list I want an auto number column that as I add to the list gets incremented. How best can I go about this?</p>
|
[
{
"answer_id": 73422,
"author": "dariom",
"author_id": 12389,
"author_profile": "https://Stackoverflow.com/users/12389",
"pm_score": 3,
"selected": false,
"text": "<FieldType> <FieldType> =\"CUST\" & [ID]"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12318/"
] |
72,552 |
<p>What does the <code>volatile</code> keyword do? In C++ what problem does it solve?</p>
<p>In my case, I have never knowingly needed it.</p>
|
[
{
"answer_id": 72576,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 7,
"selected": false,
"text": "volatile volatile"
},
{
"answer_id": 72617,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 9,
"selected": true,
"text": "volatile void waitForSemaphore()\n{\n volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/\n while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);\n}\n volatile"
},
{
"answer_id": 72962,
"author": "MikeZ",
"author_id": 12402,
"author_profile": "https://Stackoverflow.com/users/12402",
"pm_score": 6,
"selected": false,
"text": "volatile"
},
{
"answer_id": 81460,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": false,
"text": "template <typename T> \nclass Foo {\n std::enable_if_t<sizeof(T)==4, void> f(T& t) \n { std::cout << 1 << t; }\n void f(T volatile& t) \n { std::cout << 2 << const_cast<T&>(t); }\n\n void bar() { T t; f(t); }\n};\n volatile T volatile f volatile"
},
{
"answer_id": 82306,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 5,
"selected": false,
"text": "LONG __cdecl InterlockedIncrement(\n __inout LONG volatile *Addend\n);\n"
},
{
"answer_id": 17900959,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "volatile volatile sig_atomic_t volatile signal abort raise volatile sig_atomic_t abort _Exit quick_exit signal signal errno static volatile sig_atomic_t sig_num = 0;\n\nstatic void sig_handler(int signum)\n{\n signal(signum, sig_handler);\n sig_num = signum;\n}\n printf()"
},
{
"answer_id": 39875143,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 2,
"selected": false,
"text": "volatile volatile volatile"
},
{
"answer_id": 46888720,
"author": "Joachim",
"author_id": 1961484,
"author_profile": "https://Stackoverflow.com/users/1961484",
"pm_score": 2,
"selected": false,
"text": "volatile volatile volatile int* p = ...; // point to some memory\nwhile( *p!=0 ) {} // loop until the memory becomes zero\n while( *p!=0 ) { g(); }\n volatile volatile volatile"
},
{
"answer_id": 51598967,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "volatile volatile volatile volatile register volatile volatile volatile volatile volatile"
},
{
"answer_id": 59002919,
"author": "curiousguy",
"author_id": 963864,
"author_profile": "https://Stackoverflow.com/users/963864",
"pm_score": 2,
"selected": false,
"text": "scanf cin printf cout"
},
{
"answer_id": 61495883,
"author": "Rohit",
"author_id": 3049983,
"author_profile": "https://Stackoverflow.com/users/3049983",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n\nint x;\n\nint main(){\n char buf[50];\n x = 8;\n\n if(x == 8)\n printf(\"x is 8\\n\");\n else\n sprintf(buf, \"x is not 8\\n\");\n\n x=1000;\n while(x > 5)\n x--;\n return 0;\n}\n g++ -S -O3 -c -fverbose-asm -Wa,-adhln assembly.cpp\n main:\n.LFB1594:\n subq $40, %rsp #,\n .seh_stackalloc 40\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:10: printf(\"x is 8\\n\");\n leaq .LC0(%rip), %rcx #,\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:10: printf(\"x is 8\\n\");\n call _ZL6printfPKcz.constprop.0 #\n # assembly.cpp:18: }\n xorl %eax, %eax #\n movl $5, x(%rip) #, x\n addq $40, %rsp #,\n ret \n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n sprintf x while while 5 x movl $5, x(%rip) x x = 8; if(x == 8) else assembly.cpp int x; volatile int x; main:\n.LFB1594:\n subq $104, %rsp #,\n .seh_stackalloc 104\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:9: if(x == 8)\n movl x(%rip), %eax # x, x.1_1\n # assembly.cpp:9: if(x == 8)\n cmpl $8, %eax #, x.1_1\n je .L11 #,\n # assembly.cpp:12: sprintf(buf, \"x is not 8\\n\");\n leaq 32(%rsp), %rcx #, tmp93\n leaq .LC0(%rip), %rdx #,\n call _ZL7sprintfPcPKcz.constprop.0 #\n.L7:\n # assembly.cpp:14: x=1000;\n movl $1000, x(%rip) #, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_15\n cmpl $5, %eax #, x.3_15\n jle .L8 #,\n .p2align 4,,10\n.L9:\n # assembly.cpp:16: x--;\n movl x(%rip), %eax # x, x.4_3\n subl $1, %eax #, _4\n movl %eax, x(%rip) # _4, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_2\n cmpl $5, %eax #, x.3_2\n jg .L9 #,\n.L8:\n # assembly.cpp:18: }\n xorl %eax, %eax #\n addq $104, %rsp #,\n ret \n.L11:\n # assembly.cpp:10: printf(\"x is 8\\n\");\n leaq .LC1(%rip), %rcx #,\n call _ZL6printfPKcz.constprop.1 #\n jmp .L7 #\n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n sprintf printf while x sprintf while"
},
{
"answer_id": 65641563,
"author": "alex_noname",
"author_id": 13782669,
"author_profile": "https://Stackoverflow.com/users/13782669",
"pm_score": 1,
"selected": false,
"text": "volatile C++ volatile C# Java C++ volatile C++ volatile C++ volatile volatile int vi; int vi = 5; int read_back = vi; read_back == 5 int i = vi; int j = vi; i == j vi"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2167252/"
] |
72,556 |
<p>I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.</p>
<p>Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.</p>
|
[
{
"answer_id": 72576,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 7,
"selected": false,
"text": "volatile volatile"
},
{
"answer_id": 72617,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 9,
"selected": true,
"text": "volatile void waitForSemaphore()\n{\n volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/\n while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED);\n}\n volatile"
},
{
"answer_id": 72962,
"author": "MikeZ",
"author_id": 12402,
"author_profile": "https://Stackoverflow.com/users/12402",
"pm_score": 6,
"selected": false,
"text": "volatile"
},
{
"answer_id": 81460,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": false,
"text": "template <typename T> \nclass Foo {\n std::enable_if_t<sizeof(T)==4, void> f(T& t) \n { std::cout << 1 << t; }\n void f(T volatile& t) \n { std::cout << 2 << const_cast<T&>(t); }\n\n void bar() { T t; f(t); }\n};\n volatile T volatile f volatile"
},
{
"answer_id": 82306,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 5,
"selected": false,
"text": "LONG __cdecl InterlockedIncrement(\n __inout LONG volatile *Addend\n);\n"
},
{
"answer_id": 17900959,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "volatile volatile sig_atomic_t volatile signal abort raise volatile sig_atomic_t abort _Exit quick_exit signal signal errno static volatile sig_atomic_t sig_num = 0;\n\nstatic void sig_handler(int signum)\n{\n signal(signum, sig_handler);\n sig_num = signum;\n}\n printf()"
},
{
"answer_id": 39875143,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 2,
"selected": false,
"text": "volatile volatile volatile"
},
{
"answer_id": 46888720,
"author": "Joachim",
"author_id": 1961484,
"author_profile": "https://Stackoverflow.com/users/1961484",
"pm_score": 2,
"selected": false,
"text": "volatile volatile volatile int* p = ...; // point to some memory\nwhile( *p!=0 ) {} // loop until the memory becomes zero\n while( *p!=0 ) { g(); }\n volatile volatile volatile"
},
{
"answer_id": 51598967,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "volatile volatile volatile volatile register volatile volatile volatile volatile volatile"
},
{
"answer_id": 59002919,
"author": "curiousguy",
"author_id": 963864,
"author_profile": "https://Stackoverflow.com/users/963864",
"pm_score": 2,
"selected": false,
"text": "scanf cin printf cout"
},
{
"answer_id": 61495883,
"author": "Rohit",
"author_id": 3049983,
"author_profile": "https://Stackoverflow.com/users/3049983",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n\nint x;\n\nint main(){\n char buf[50];\n x = 8;\n\n if(x == 8)\n printf(\"x is 8\\n\");\n else\n sprintf(buf, \"x is not 8\\n\");\n\n x=1000;\n while(x > 5)\n x--;\n return 0;\n}\n g++ -S -O3 -c -fverbose-asm -Wa,-adhln assembly.cpp\n main:\n.LFB1594:\n subq $40, %rsp #,\n .seh_stackalloc 40\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:10: printf(\"x is 8\\n\");\n leaq .LC0(%rip), %rcx #,\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:10: printf(\"x is 8\\n\");\n call _ZL6printfPKcz.constprop.0 #\n # assembly.cpp:18: }\n xorl %eax, %eax #\n movl $5, x(%rip) #, x\n addq $40, %rsp #,\n ret \n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n sprintf x while while 5 x movl $5, x(%rip) x x = 8; if(x == 8) else assembly.cpp int x; volatile int x; main:\n.LFB1594:\n subq $104, %rsp #,\n .seh_stackalloc 104\n .seh_endprologue\n # assembly.cpp:5: int main(){\n call __main #\n # assembly.cpp:7: x = 8;\n movl $8, x(%rip) #, x\n # assembly.cpp:9: if(x == 8)\n movl x(%rip), %eax # x, x.1_1\n # assembly.cpp:9: if(x == 8)\n cmpl $8, %eax #, x.1_1\n je .L11 #,\n # assembly.cpp:12: sprintf(buf, \"x is not 8\\n\");\n leaq 32(%rsp), %rcx #, tmp93\n leaq .LC0(%rip), %rdx #,\n call _ZL7sprintfPcPKcz.constprop.0 #\n.L7:\n # assembly.cpp:14: x=1000;\n movl $1000, x(%rip) #, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_15\n cmpl $5, %eax #, x.3_15\n jle .L8 #,\n .p2align 4,,10\n.L9:\n # assembly.cpp:16: x--;\n movl x(%rip), %eax # x, x.4_3\n subl $1, %eax #, _4\n movl %eax, x(%rip) # _4, x\n # assembly.cpp:15: while(x > 5)\n movl x(%rip), %eax # x, x.3_2\n cmpl $5, %eax #, x.3_2\n jg .L9 #,\n.L8:\n # assembly.cpp:18: }\n xorl %eax, %eax #\n addq $104, %rsp #,\n ret \n.L11:\n # assembly.cpp:10: printf(\"x is 8\\n\");\n leaq .LC1(%rip), %rcx #,\n call _ZL6printfPKcz.constprop.1 #\n jmp .L7 #\n .seh_endproc\n .p2align 4,,15\n .def _GLOBAL__sub_I_x; .scl 3; .type 32; .endef\n .seh_proc _GLOBAL__sub_I_x\n sprintf printf while x sprintf while"
},
{
"answer_id": 65641563,
"author": "alex_noname",
"author_id": 13782669,
"author_profile": "https://Stackoverflow.com/users/13782669",
"pm_score": 1,
"selected": false,
"text": "volatile C++ volatile C# Java C++ volatile C++ volatile C++ volatile volatile int vi; int vi = 5; int read_back = vi; read_back == 5 int i = vi; int j = vi; i == j vi"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12333/"
] |
72,562 |
<p>Is there a good way to find out which exceptions a procedure/function can raise in Delphi (including it's called procedures/functions)? </p>
<p>In Java you always have to declare which exceptions that can be thrown, but this is not the case in Delphi, which could lead to unhandled exceptions. </p>
<p>Are there any code analysis tools that detects unhandled exceptions?</p>
|
[
{
"answer_id": 72709,
"author": "Lars Fosdal",
"author_id": 10002,
"author_profile": "https://Stackoverflow.com/users/10002",
"pm_score": 2,
"selected": false,
"text": "try\n ThisFunctionMayFail;\nexcept\n // but it sure won't crash the application\n on e:exception\n do begin\n // something sensible to handle the error \n // or perhaps log and/or display the the generic e.description message\n end\nend;\n"
},
{
"answer_id": 73954,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 3,
"selected": false,
"text": "// Other code . . . \ntry\n SomeProcedure()\nexcept // BAD IDEA!\n ShowMessage('I caught them all!');\nend;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11300/"
] |
72,564 |
<p>I'm kind of interested in getting some feedback about this technique I picked up from somewhere.</p>
<p>I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the top for this sort of thing, plus PHP4 does not offer this.</p>
<p>Basically the technique involves returning true for success, and <em>something</em> which <em>equates</em> to false for failure. Here's an example to show what I mean:</p>
<pre><code>define ('DUPLICATE_USERNAME', false);
define ('DATABASE_ERROR', 0);
define ('INSUFFICIENT_DETAILS', 0.0);
define ('OK', true);
function createUser($username) {
// create the user and return the appropriate constant from the above
}
</code></pre>
<p>The beauty of this is that in your calling code, if you don't care WHY the user creation failed, you can write simple and readable code:</p>
<pre><code>if (createUser('fred')) {
// yay, it worked!
} else {
// aww, it didn't work.
}
</code></pre>
<p>If you particularly want to check why it didn't work (for logging, display to the user, or do whatever), use identity comparison with ===</p>
<pre><code>$status = createUser('fred');
if ($status) {
// yay, it worked!
} else if ($status === DUPLICATE_USERNAME) {
// tell the user about it and get them to try again.
} else {
// aww, it didn't work. log it and show a generic error message? whatever.
}
</code></pre>
<p>The way I see it, the benefits of this are that it is a normal expectation that a successful execution of a function like that would return true, and failure return false.</p>
<p>The downside is that you can only have <code>7 "error" return values: false, 0, 0.0, "0", null, "", and (object) null.</code> If you forget to use identity checking you could get your program flow all wrong. Someone else has told me that using constants like an <code>enum</code> where they all equate to false is <code>"ick"</code>.</p>
<hr>
<p>So, to restate the question: how acceptable is a practise like this? Would you recommend a different way to achieve the same thing? </p>
|
[
{
"answer_id": 72661,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": -1,
"selected": false,
"text": "class Result\n{\n var $_result;\n var $_errormsg;\n\n function Result($res, $error)\n {\n $this->_result = $res;\n $ths->_errorMsg = $error\n }\n\n function getResult()\n {\n return $this->_result;\n }\n\n function isError()\n {\n return ! ((boolean) $this->_result);\n }\n\n function getErrorMessage()\n {\n return $this->_errorMsg;\n }\n"
},
{
"answer_id": 72673,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": -1,
"selected": false,
"text": "if (succeeded(result = MyFunction()))\n ...\nelse\n ...\n"
},
{
"answer_id": 72730,
"author": "Jeremy Privett",
"author_id": 560,
"author_profile": "https://Stackoverflow.com/users/560",
"pm_score": 5,
"selected": true,
"text": "function createUser($username, &$error)\n if (createUser('fred', $error)) {\n echo 'success';\n}\nelse {\n echo $error;\n}\n"
},
{
"answer_id": 72838,
"author": "ljorquera",
"author_id": 9132,
"author_profile": "https://Stackoverflow.com/users/9132",
"pm_score": 0,
"selected": false,
"text": "define ('OK', 0);\ndefine ('DUPLICATE_USERNAME', 1);\ndefine ('DATABASE_ERROR', 2);\ndefine ('INSUFFICIENT_DETAILS', 3);\n if (createUser('fred') == OK) {\n //OK\n\n}\nelse {\n //Fail\n}\n"
},
{
"answer_id": 72926,
"author": "rami",
"author_id": 9629,
"author_profile": "https://Stackoverflow.com/users/9629",
"pm_score": 0,
"selected": false,
"text": "if (!createUser($username)) {\n// the dingo ate my user.\n// deal with it.\n}\n define(DUPLICATE_USERNAME, 4)\ndefine(USERNAME_NOT_ALPHANUM, 8)\n\nswitch ($status) {\ncase DUPLICATE_USERNAME:\n // sorry hun, there's someone else\n break;\ncase USERNAME_NOT_ALPHANUM:\n break;\ndefault:\n // yay, it worked\n}\n DUPLICATE_USERNAME & USERNAME_NOT_ALPHANUM"
},
{
"answer_id": 73049,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "if ( makeClient() )\n{ // happy scenario goes here }\n\nelse\n{\n // error handling all goes inside this block\n switch ( getMakeClientError() )\n { case: // .. }\n}\n"
},
{
"answer_id": 73455,
"author": "Markowitch",
"author_id": 11964,
"author_profile": "https://Stackoverflow.com/users/11964",
"pm_score": 0,
"selected": false,
"text": "inline _bstr_t IMyClass::GetName ( ) {\n BSTR _result;\n HRESULT _hr = get_name(&_result);\n if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));\n return _bstr_t(_result, false);\n}\n"
},
{
"answer_id": 73589,
"author": "Aquarion",
"author_id": 12696,
"author_profile": "https://Stackoverflow.com/users/12696",
"pm_score": 0,
"selected": false,
"text": "throw new Validation_Exception_SQLDuplicate(\"There's someone else, hun\");),\n return new Result($status, $stuff);\nif ($result->status == 0) {\n $stuff = $result->data;\n}\nelse {\n die('Oh hell');\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
72,568 |
<p>What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API? </p>
|
[
{
"answer_id": 73349,
"author": "Aaron",
"author_id": 11176,
"author_profile": "https://Stackoverflow.com/users/11176",
"pm_score": 2,
"selected": false,
"text": "class Foo(models.Model):\n name = models.CharField(max_length=255)\n\nclass FizzBuzz(models.Model):\n bleh = models.CharField(max_length=255)\n\nclass Bar(models.Model):\n foo = models.ForeignKey(Foo)\n fizzbuzz = models.ForeignKey(FizzBuzz) \n Fizzbuzz.objects.filter(bar__foo__name = \"Adrian\")\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
72,573 |
<p>Can you use CMFCVisualManager with a dialog based application to change the applications appearance? If so how is it done?</p>
<p>The idea is to change the shape, colour etc. of controls such as push buttons using the MFC Feature Pack released with MSVC 2008.</p>
|
[
{
"answer_id": 93554,
"author": "djeidot",
"author_id": 4880,
"author_profile": "https://Stackoverflow.com/users/4880",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n<assemblyIdentity\n version=\"1.0.0.0\"\n processorArchitecture=\"X86\"\n name=\"Program Name\"\n type=\"win32\"\n/>\n<description>Description of Program</description>\n<dependency>\n <dependentAssembly>\n <assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.Windows.Common-Controls\"\n version=\"6.0.0.0\"\n processorArchitecture=\"X86\"\n publicKeyToken=\"6595b64144ccf1df\"\n language=\"*\"\n />\n </dependentAssembly>\n</dependency>\n</assembly>\n"
},
{
"answer_id": 1467172,
"author": "djeidot",
"author_id": 4880,
"author_profile": "https://Stackoverflow.com/users/4880",
"pm_score": 0,
"selected": false,
"text": "OnApplicationLook CDialog OnApplicationLook OnInitDialog CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver);\nCMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007));\nCDockingManager::SetDockingMode(DT_SMART);\nRedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE);\n"
},
{
"answer_id": 26944194,
"author": "Ziggyware",
"author_id": 4255207,
"author_profile": "https://Stackoverflow.com/users/4255207",
"pm_score": 0,
"selected": false,
"text": "class CMFCApplication2Dlg : public CFrameWndEx\n{\n CMFCMenuBar bar;\npublic:\n CMFCApplication2Dlg() : CFrameWndEx()\n {\n LoadFrame(IDR_MAINFRAME);\n bar.Create(this);\n }\n};\n\nclass CMFCApplication2App : public CWinAppEx\n{\npublic:\n virtual BOOL InitInstance()\n {\n CWinAppEx::InitInstance();\n\n CMFCVisualManagerOffice2007::SetStyle(\n CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);\n\n CMFCVisualManager::SetDefaultManager(\n RUNTIME_CLASS(CMFCVisualManagerOffice2007));\n\n SetRegistryKey(_T(\"Local AppWizard-Generated Applications\"));\n\n m_pMainWnd = new CMFCApplication2Dlg();\n\n m_pMainWnd->ShowWindow(SW_SHOW);\n m_pMainWnd->UpdateWindow();\n\n return TRUE;\n }\n};\n\nCMFCApplication2App theApp;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12346/"
] |
72,580 |
<p>I have an app that I've written in C#/WinForms (<a href="http://www.thekbase.com" rel="nofollow noreferrer" title="TheKBase">my little app</a>). To make it cross-platform, I'm thinking of redoing it in Adobe AIR. Are there any arguments in favor of WinForms as a cross-platform app? Is there a cross-platform future for Winforms (e.g., Mono, etc.)? Suggestions for cross-platform UI development?</p>
<p>By cross-platform I mean, currently, Mac OSX, Windows and Linux.</p>
<p>This question was <a href="https://stackoverflow.com/questions/116468/winforms-for-mono-on-mac-linux-and-pc-redux">asked again and answered with better success</a>.</p>
|
[
{
"answer_id": 72632,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 0,
"selected": false,
"text": "</speculation>\n"
},
{
"answer_id": 72633,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": false,
"text": "Number int float double"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8047/"
] |
72,616 |
<p>I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, <em>not</em> a source code file -- but embed that file in the executable file like a resource.</p>
<p>(This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.)</p>
<p>Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.)</p>
|
[
{
"answer_id": 72692,
"author": "vava",
"author_id": 6258,
"author_profile": "https://Stackoverflow.com/users/6258",
"pm_score": 2,
"selected": false,
"text": "//queries.incl - SQL queries\nQ(SELECT * FROM Users)\nQ(INSERT [a] INTO Accounts)\n\n\n//source.cpp\n#define Q(query) #query,\nchar * queries[] = {\n#include \"queries.incl\"\n};\n#undef Q\n"
},
{
"answer_id": 73653,
"author": "tfinniga",
"author_id": 9042,
"author_profile": "https://Stackoverflow.com/users/9042",
"pm_score": 2,
"selected": false,
"text": "#include <string>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n\nusing namespace std;\n\nstd::string escapeLine( std::string orig )\n{\n string retme;\n for (unsigned int i=0; i<orig.size(); i++)\n {\n switch (orig[i])\n {\n case '\\\\':\n retme += \"\\\\\\\\\";\n break;\n case '\"':\n retme += \"\\\\\\\"\";\n break;\n case '\\n': // Strip out the final linefeed.\n break;\n default:\n retme += orig[i];\n }\n }\n retme += \"\\\\n\"; // Add an escaped linefeed to the escaped string.\n return retme;\n}\n\nint main( int argc, char ** argv )\n{\n string filenamein, filenameout;\n\n if ( argc > 1 )\n filenamein = argv[ 1 ];\n else\n {\n // Not enough arguments\n fprintf( stderr, \"Usage: %s <file to convert.mel> [ <output file name.mel> ]\\n\", argv[0] );\n exit( -1 );\n }\n\n if ( argc > 2 )\n filenameout = argv[ 2 ];\n else\n {\n string new_ending = \"_mel.h\";\n filenameout = filenamein;\n std::string::size_type pos;\n pos = filenameout.find( \".mel\" );\n if (pos == std::string::npos)\n filenameout += new_ending;\n else\n filenameout.replace( pos, new_ending.size(), new_ending );\n }\n\n printf( \"Converting \\\"%s\\\" to \\\"%s\\\"\\n\", filenamein.c_str(), filenameout.c_str() );\n\n ifstream filein( filenamein.c_str(), ios::in );\n ofstream fileout( filenameout.c_str(), ios::out );\n\n if (!filein.good())\n {\n fprintf( stderr, \"Unable to open input file %s\\n\", filenamein.c_str() );\n exit( -2 );\n }\n if (!fileout.good())\n {\n fprintf( stderr, \"Unable to open output file %s\\n\", filenameout.c_str() );\n exit( -3 );\n }\n\n // Write the file.\n fileout << \"tempstr = \";\n\n while( filein.good() )\n {\n string buff;\n if ( getline( filein, buff ) )\n {\n fileout << \"\\\"\" << escapeLine( buff ) << \"\\\"\" << endl;\n }\n }\n\n fileout << \";\" << endl;\n\n filein.close();\n fileout.close();\n\n return 0;\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
72,671 |
<p>I need to create a batch file which starts multiple console applications in a Windows .cmd file. This can be done using the start command.</p>
<p>However, the command has a path in it. I also need to pass paramaters which have spaces as well. How to do this?</p>
<p>E.g. batch file</p>
<pre><code>start "c:\path with spaces\app.exe" param1 "param with spaces"
</code></pre>
|
[
{
"answer_id": 72758,
"author": "Steffen",
"author_id": 6919,
"author_profile": "https://Stackoverflow.com/users/6919",
"pm_score": 4,
"selected": false,
"text": "start \"Dummy Title\" \"c:\\path with spaces\\app.exe\" param1 \"param with spaces\"\n"
},
{
"answer_id": 72796,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 8,
"selected": true,
"text": "start \"\" \"c:\\path with spaces\\app.exe\" param1 \"param with spaces\"\n"
},
{
"answer_id": 19316499,
"author": "Anupam Kapoor",
"author_id": 2870697,
"author_profile": "https://Stackoverflow.com/users/2870697",
"pm_score": -1,
"selected": false,
"text": "START C:\\Windows\\System32\\cscript.exe \"C:\\Documents and Settings\\akapoor\\Desktop\\Mail.vbs\"\n"
},
{
"answer_id": 43467194,
"author": "Mustafa Kemal",
"author_id": 3835640,
"author_profile": "https://Stackoverflow.com/users/3835640",
"pm_score": 2,
"selected": false,
"text": "start \"\" \"c:\\path with spaces\\app.exe\" \"C:\\path parameter\\param.exe\"\n start \"\" CALL \"c:\\path with spaces\\app.exe\" \"C:\\path parameter\\param.exe\"\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
72,672 |
<p>Has anyone written an 'UnFormat' routine for Delphi?</p>
<p>What I'm imagining is the <em>inverse</em> of <em>SysUtils.Format</em> and looks something like this </p>
<p>UnFormat('a number %n and another %n',[float1, float2]); </p>
<p>So you could unpack a string into a series of variables using format strings.</p>
<p>I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me.</p>
|
[
{
"answer_id": 72713,
"author": "PatrickvL",
"author_id": 12170,
"author_profile": "https://Stackoverflow.com/users/12170",
"pm_score": 5,
"selected": true,
"text": "function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;\nvar\n InputOffset: Integer;\n FormatOffset: Integer;\n InputChar: Char;\n FormatChar: Char;\n\n function _GetInputChar: Char;\n begin\n if InputOffset <= Length(Input) then\n begin\n Result := Input[InputOffset];\n Inc(InputOffset);\n end\n else\n Result := #0;\n end;\n\n function _PeekFormatChar: Char;\n begin\n if FormatOffset <= Length(Format) then\n Result := Format[FormatOffset]\n else\n Result := #0;\n end;\n\n function _GetFormatChar: Char;\n begin\n Result := _PeekFormatChar;\n if Result <> #0 then\n Inc(FormatOffset);\n end;\n\n function _ScanInputString(const Arg: Pointer = nil): string;\n var\n EndChar: Char;\n begin\n Result := '';\n EndChar := _PeekFormatChar;\n InputChar := _GetInputChar;\n while (InputChar > ' ')\n and (InputChar <> EndChar) do\n begin\n Result := Result + InputChar;\n InputChar := _GetInputChar;\n end;\n\n if InputChar <> #0 then\n Dec(InputOffset);\n\n if Assigned(Arg) then\n PString(Arg)^ := Result;\n end;\n\n function _ScanInputInteger(const Arg: Pointer): Boolean;\n var\n Value: string;\n begin\n Value := _ScanInputString;\n Result := TryStrToInt(Value, {out} PInteger(Arg)^);\n end;\n\n procedure _Raise;\n begin\n raise EConvertError.CreateFmt('Unknown ScanFormat character : \"%s\"!', [FormatChar]);\n end;\n\nbegin\n Result := 0;\n InputOffset := 1;\n FormatOffset := 1;\n FormatChar := _GetFormatChar;\n while FormatChar <> #0 do\n begin\n if FormatChar <> '%' then\n begin\n InputChar := _GetInputChar;\n if (InputChar = #0)\n or (FormatChar <> InputChar) then\n Exit;\n end\n else\n begin\n FormatChar := _GetFormatChar;\n case FormatChar of\n '%':\n if _GetInputChar <> '%' then\n Exit;\n 's':\n begin\n _ScanInputString(Args[Result]);\n Inc(Result);\n end;\n 'd', 'u':\n begin\n if not _ScanInputInteger(Args[Result]) then\n Exit;\n\n Inc(Result);\n end;\n else\n _Raise;\n end;\n end;\n\n FormatChar := _GetFormatChar;\n end;\nend;\n"
},
{
"answer_id": 73750,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 1,
"selected": false,
"text": "function NumStringParts(SourceStr,Delimiter:String):Integer;\nvar\n offset : integer;\n curnum : integer;\nbegin\n curnum := 1;\n offset := 1;\n while (offset <> 0) do\n begin\n Offset := Pos(Delimiter,SourceStr);\n if Offset <> 0 then\n begin\n Inc(CurNum);\n Delete(SourceStr,1,(Offset-1)+Length(Delimiter));\n end;\n end;\n result := CurNum;\nend;\n\nfunction GetStringPart(SourceStr,Delimiter:String;Num:Integer):string;\nvar\n offset : integer;\n CurNum : integer;\n CurPart : String;\nbegin\n CurNum := 1;\n Offset := 1;\n While (CurNum <= Num) and (Offset <> 0) do\n begin\n Offset := Pos(Delimiter,SourceStr);\n if Offset <> 0 then\n begin\n CurPart := Copy(SourceStr,1,Offset-1);\n Delete(SourceStr,1,(Offset-1)+Length(Delimiter));\n Inc(CurNum)\n end\n else\n CurPart := SourceStr;\n end;\n if CurNum >= Num then\n Result := CurPart\n else\n Result := '';\nend;\n var\n st : string;\n f1,f2 : double; \n begin\n st := 'a number 12.35 and another 13.415';\n ShowMessage('Total String parts = '+IntToStr(NumStringParts(st,#32)));\n f1 := StrToFloatDef(GetStringPart(st,#32,3),0.0);\n f2 := StrToFloatDef(GetStringPart(st,#32,6),0.0);\n ShowMessage('Float 1 = '+FloatToStr(F1)+' and Float 2 = '+FloatToStr(F2)); \n end; \n"
},
{
"answer_id": 76566,
"author": "Toby Allen",
"author_id": 6244,
"author_profile": "https://Stackoverflow.com/users/6244",
"pm_score": 2,
"selected": false,
"text": "'a number (.*?) and another (.*?)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12376/"
] |
72,677 |
<p>Imagine I have String in C#: "I Don’t see ya.."</p>
<p>I want to remove (replace to nothing or etc.) these "’" symbols. </p>
<p>How do I do this?</p>
|
[
{
"answer_id": 72759,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "\"I Don’t see ya..\".Replace( \"’\", string.Empty);\n"
},
{
"answer_id": 72770,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 1,
"selected": false,
"text": "char.IsLetterOrDigit;\n char.IsSymbol;\nchar.IsControl;\n"
},
{
"answer_id": 72844,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 0,
"selected": false,
"text": "I Donââ‚\n W R\n"
},
{
"answer_id": 16419143,
"author": "Chandra Sekhar k",
"author_id": 2358323,
"author_profile": "https://Stackoverflow.com/users/2358323",
"pm_score": 0,
"selected": false,
"text": " string InputString = \"This is grate kingdom¢Ã‚¬â\"; \n string replace = \"’\";\n string OutputString= Regex.Replace(InputString, replace, \"\");\n\n //OutputString having the following result \n"
},
{
"answer_id": 27134222,
"author": "BrianP007",
"author_id": 4282598,
"author_profile": "https://Stackoverflow.com/users/4282598",
"pm_score": 0,
"selected": false,
"text": "#!/usr/local/bin/perl -w\n\n# This runs in a dos window and shows the char, integer and hex values\n# for the weird chars. Install the HEX values in the REGEXP below until\n# the final test line looks normal. \n$str = 's: “Brian'; # Nuke the 3 werid chars in front of Brian.\n@str = split(//, $str);\nprintf(\"len str '$str' = %d, scalar \\@str = %d\\n\", \n length $str, scalar @str);\n$ii = -1;\nforeach $c (@str) {\n $ii++;\n printf(\"$ii) char '$c', ord=%03d, hex='%s'\\n\", \n ord($c), unpack(\"H*\", $c));\n}\n# Take the hex characters shown above, plug them into the below regexp\n# until the junk disappears!\n($s2 = $str) =~ s/[\\xE2\\x80\\x9C]//g; # << Insert HEX values HERE\nprint(\"S2=>$s2<\\n\"); # Final test\n\nResult:\nM:\\new\\6s-2014.1031-nef.halloween>nuke_junk.pl\nlen str 's: GÇ£Brian' = 11, scalar @str = 11\n0) char 's', ord=115, hex='73'\n1) char ':', ord=058, hex='3a'\n2) char ' ', ord=032, hex='20'\n3) char 'G', ord=226, hex='e2'\n4) char 'Ç', ord=128, hex='80'\n5) char '£', ord=156, hex='9c'\n6) char 'B', ord=066, hex='42'\n7) char 'r', ord=114, hex='72'\n8) char 'i', ord=105, hex='69'\n9) char 'a', ord=097, hex='61'\n10) char 'n', ord=110, hex='6e'\nS2=>s: Brian<\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5369/"
] |
72,682 |
<p>Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes.</p>
<p>Now you have a method, and you want to return a value. You <em>also</em> want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this:</p>
<pre><code>class FunctionResult<T>
{
public T payload;
public int result;
}
</code></pre>
<p>And then declare your functions like this:</p>
<pre><code>FunctionResult<string> MyFunction()
{
FunctionResult<string> result;
//...
return result;
}
</code></pre>
<p>One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it?</p>
|
[
{
"answer_id": 72846,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "FunctionResult Nullable Nullable NumberType.TryParse out"
},
{
"answer_id": 73016,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 1,
"selected": false,
"text": "bool TryMyFunction(out FunctionResult result){ \n\n //... \n result = new FunctionResult();\n}\n"
},
{
"answer_id": 73020,
"author": "Peter Davis",
"author_id": 12508,
"author_profile": "https://Stackoverflow.com/users/12508",
"pm_score": 3,
"selected": false,
"text": "int value;\nif (int.TryParse(\"123\", out value)) {\n // use value\n}\n int? value = int.TryParse(\"123\");\nif (value != null) {\n // use value\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
72,696 |
<p>I have some code like this:</p>
<pre><code>If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then
DoSomething()
End If
</code></pre>
<p>I don't care about the case. Should I use <code>OrdinalIgnoreCase</code>, <code>InvariantCultureIgnoreCase</code>, or <code>CurrentCultureIgnoreCase</code>?</p>
|
[
{
"answer_id": 72766,
"author": "Robert Taylor",
"author_id": 6375,
"author_profile": "https://Stackoverflow.com/users/6375",
"pm_score": 9,
"selected": true,
"text": "InvariantCulture String StringComparison.Ordinal StringComparison.OrdinalIgnoreCase StringComparison strcmp"
},
{
"answer_id": 6406284,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 6,
"selected": false,
"text": ".Equals OrdinalIgnoreCase OrdinalIgnoreCase \"\\u0061\\u030a\" \"\\u00e5\""
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7072/"
] |
72,699 |
<p>For example which is better:</p>
<pre><code>select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id
</code></pre>
<p>or</p>
<pre><code>select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id
</code></pre>
<p>better as in less work for the database, faster results.</p>
<p><strong>Note:</strong> Sybase, and there's an index on both tables of <code>country+id</code>.</p>
|
[
{
"answer_id": 73890,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 0,
"selected": false,
"text": "SELECT *\n FROM t1\n JOIN t2 ON t1.id = t2.id AND t1.country = t2.country\n WHERE t1.country = 'US'\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386/"
] |
72,723 |
<p>I have a svn repository, R, that depends on a library, l, in another repository.</p>
<p>The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R.</p>
<p>I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'.</p>
<p>If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above.</p>
|
[
{
"answer_id": 72925,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\nsvn co path://server/R svn-R\ngit clone path://server/l git-l\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
72,768 |
<p>I'm trying to figure out how to detect the type of credit card based purely on its number. Does anyone know of a definitive, reliable way to find this?</p>
|
[
{
"answer_id": 72801,
"author": "senfo",
"author_id": 10792,
"author_profile": "https://Stackoverflow.com/users/10792",
"pm_score": 11,
"selected": true,
"text": "^4[0-9]{6,}$ ^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$ ^3[47][0-9]{5,}$ ^3(?:0[0-5]|[68][0-9])[0-9]{4,}$ ^6(?:011|5[0-9]{2})[0-9]{3,}$ ^(?:2131|1800|35[0-9]{3})[0-9]{3,}$ 4444 4444 4444 4444\n 4444444444444444\n"
},
{
"answer_id": 2408585,
"author": "Rashy",
"author_id": 289587,
"author_profile": "https://Stackoverflow.com/users/289587",
"pm_score": 4,
"selected": false,
"text": "function isValidCreditCard(type, ccnum) {\n /* Visa: length 16, prefix 4, dashes optional.\n Mastercard: length 16, prefix 51-55, dashes optional.\n Discover: length 16, prefix 6011, dashes optional.\n American Express: length 15, prefix 34 or 37.\n Diners: length 14, prefix 30, 36, or 38. */\n\n var re = new Regex({\n \"visa\": \"/^4\\d{3}-?\\d{4}-?\\d{4}-?\\d\",\n \"mc\": \"/^5[1-5]\\d{2}-?\\d{4}-?\\d{4}-?\\d{4}$/\",\n \"disc\": \"/^6011-?\\d{4}-?\\d{4}-?\\d{4}$/\",\n \"amex\": \"/^3[47]\\d{13}$/\",\n \"diners\": \"/^3[068]\\d{12}$/\"\n }[type.toLowerCase()])\n\n if (!re.test(ccnum)) return false;\n // Remove all dashes for the checksum checks to eliminate negative numbers\n ccnum = ccnum.split(\"-\").join(\"\");\n // Checksum (\"Mod 10\")\n // Add even digits in even length strings or odd digits in odd length strings.\n var checksum = 0;\n for (var i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {\n checksum += parseInt(ccnum.charAt(i - 1));\n }\n // Analyze odd digits in even length strings or even digits in odd length strings.\n for (var i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {\n var digit = parseInt(ccnum.charAt(i - 1)) * 2;\n if (digit < 10) { checksum += digit; } else { checksum += (digit - 9); }\n }\n if ((checksum % 10) == 0) return true;\n else return false;\n}\n"
},
{
"answer_id": 11529211,
"author": "Parvez",
"author_id": 1531583,
"author_profile": "https://Stackoverflow.com/users/1531583",
"pm_score": 2,
"selected": false,
"text": "// abobjects.com, parvez ahmad ab bulk mailer\nuse below script\n\nfunction isValidCreditCard2(type, ccnum) {\n if (type == \"Visa\") {\n // Visa: length 16, prefix 4, dashes optional.\n var re = /^4\\d{3}?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == \"MasterCard\") {\n // Mastercard: length 16, prefix 51-55, dashes optional.\n var re = /^5[1-5]\\d{2}?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == \"Discover\") {\n // Discover: length 16, prefix 6011, dashes optional.\n var re = /^6011?\\d{4}?\\d{4}?\\d{4}$/;\n } else if (type == \"AmEx\") {\n // American Express: length 15, prefix 34 or 37.\n var re = /^3[4,7]\\d{13}$/;\n } else if (type == \"Diners\") {\n // Diners: length 14, prefix 30, 36, or 38.\n var re = /^3[0,6,8]\\d{12}$/;\n }\n if (!re.test(ccnum)) return false;\n return true;\n /*\n // Remove all dashes for the checksum checks to eliminate negative numbers\n ccnum = ccnum.split(\"-\").join(\"\");\n // Checksum (\"Mod 10\")\n // Add even digits in even length strings or odd digits in odd length strings.\n var checksum = 0;\n for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {\n checksum += parseInt(ccnum.charAt(i-1));\n }\n // Analyze odd digits in even length strings or even digits in odd length strings.\n for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {\n var digit = parseInt(ccnum.charAt(i-1)) * 2;\n if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }\n }\n if ((checksum % 10) == 0) return true; else return false;\n */\n\n }\njQuery.validator.addMethod(\"isValidCreditCard\", function(postalcode, element) { \n return isValidCreditCard2($(\"#cardType\").val(), $(\"#cardNum\").val()); \n\n}, \"<br>credit card is invalid\");\n\n\n Type</td>\n <td class=\"text\"> <form:select path=\"cardType\" cssclass=\"fields\" style=\"border: 1px solid #D5D5D5;padding: 0px 0px 0px 0px;width: 130px;height: 22px;\">\n <option value=\"SELECT\">SELECT</option>\n <option value=\"MasterCard\">Mastercard</option>\n <option value=\"Visa\">Visa</option>\n <option value=\"AmEx\">American Express</option>\n <option value=\"Discover\">Discover</option>\n </form:select> <font color=\"#FF0000\">*</font> \n\n$(\"#signupForm\").validate({\n\n rules:{\n companyName:{required: true},\n address1:{required: true},\n city:{required: true},\n state:{required: true},\n zip:{required: true},\n country:{required: true},\n chkAgree:{required: true},\n confPassword:{required: true},\n lastName:{required: true},\n firstName:{required: true},\n ccAddress1:{required: true},\n ccZip:{ \n postalcode : true\n },\n phone:{required: true},\n email:{\n required: true,\n email: true\n },\n userName:{\n required: true,\n minlength: 6\n },\n password:{\n required: true,\n minlength: 6\n }, \n cardNum:{ \n isValidCreditCard : true\n },\n"
},
{
"answer_id": 13842374,
"author": "Usman Younas",
"author_id": 1728403,
"author_profile": "https://Stackoverflow.com/users/1728403",
"pm_score": 5,
"selected": false,
"text": "public string GetCreditCardType(string CreditCardNumber)\n{\n Regex regVisa = new Regex(\"^4[0-9]{12}(?:[0-9]{3})?$\");\n Regex regMaster = new Regex(\"^5[1-5][0-9]{14}$\");\n Regex regExpress = new Regex(\"^3[47][0-9]{13}$\");\n Regex regDiners = new Regex(\"^3(?:0[0-5]|[68][0-9])[0-9]{11}$\");\n Regex regDiscover = new Regex(\"^6(?:011|5[0-9]{2})[0-9]{12}$\");\n Regex regJCB = new Regex(\"^(?:2131|1800|35\\\\d{3})\\\\d{11}$\");\n\n\n if (regVisa.IsMatch(CreditCardNumber))\n return \"VISA\";\n else if (regMaster.IsMatch(CreditCardNumber))\n return \"MASTER\";\n else if (regExpress.IsMatch(CreditCardNumber))\n return \"AEXPRESS\";\n else if (regDiners.IsMatch(CreditCardNumber))\n return \"DINERS\";\n else if (regDiscover.IsMatch(CreditCardNumber))\n return \"DISCOVERS\";\n else if (regJCB.IsMatch(CreditCardNumber))\n return \"JCB\";\n else\n return \"invalid\";\n}\n"
},
{
"answer_id": 15499262,
"author": "Fivell",
"author_id": 246544,
"author_profile": "https://Stackoverflow.com/users/246544",
"pm_score": 4,
"selected": false,
"text": "######## most used brands #########\n\n visa: [\n {length: [13, 16], prefixes: ['4']}\n ],\n mastercard: [\n {length: [16], prefixes: ['51', '52', '53', '54', '55']}\n ],\n\n amex: [\n {length: [15], prefixes: ['34', '37']}\n ],\n ######## other brands ########\n diners: [\n {length: [14], prefixes: ['300', '301', '302', '303', '304', '305', '36', '38']},\n ],\n\n #There are Diners Club (North America) cards that begin with 5. These are a joint venture between Diners Club and MasterCard, and are processed like a MasterCard\n # will be removed in next major version\n\n diners_us: [\n {length: [16], prefixes: ['54', '55']}\n ],\n\n discover: [\n {length: [16], prefixes: ['6011', '644', '645', '646', '647', '648',\n '649', '65']}\n ],\n\n jcb: [\n {length: [16], prefixes: ['3528', '3529', '353', '354', '355', '356', '357', '358', '1800', '2131']}\n ],\n\n\n laser: [\n {length: [16, 17, 18, 19], prefixes: ['6304', '6706', '6771']}\n ],\n\n solo: [\n {length: [16, 18, 19], prefixes: ['6334', '6767']}\n ],\n\n switch: [\n {length: [16, 18, 19], prefixes: ['633110', '633312', '633304', '633303', '633301', '633300']}\n\n ],\n\n maestro: [\n {length: [12, 13, 14, 15, 16, 17, 18, 19], prefixes: ['5010', '5011', '5012', '5013', '5014', '5015', '5016', '5017', '5018',\n '502', '503', '504', '505', '506', '507', '508',\n '6012', '6013', '6014', '6015', '6016', '6017', '6018', '6019',\n '602', '603', '604', '605', '6060',\n '677', '675', '674', '673', '672', '671', '670',\n '6760', '6761', '6762', '6763', '6764', '6765', '6766', '6768', '6769']}\n ],\n\n # Luhn validation are skipped for union pay cards because they have unknown generation algoritm\n unionpay: [\n {length: [16, 17, 18, 19], prefixes: ['622', '624', '625', '626', '628'], skip_luhn: true}\n ],\n\n dankrot: [\n {length: [16], prefixes: ['5019']}\n ],\n\n rupay: [\n {length: [16], prefixes: ['6061', '6062', '6063', '6064', '6065', '6066', '6067', '6068', '6069', '607', '608'], skip_luhn: true}\n ]\n\n}\n"
},
{
"answer_id": 18216511,
"author": "ismail",
"author_id": 2679740,
"author_profile": "https://Stackoverflow.com/users/2679740",
"pm_score": 3,
"selected": false,
"text": "<?php\nclass CreditcardType\n{\n public static $creditcardTypes = [\n [\n 'Name' => 'American Express',\n 'cardLength' => [15],\n 'cardPrefix' => ['34', '37'],\n ], [\n 'Name' => 'Maestro',\n 'cardLength' => [12, 13, 14, 15, 16, 17, 18, 19],\n 'cardPrefix' => ['5018', '5020', '5038', '6304', '6759', '6761', '6763'],\n ], [\n 'Name' => 'Mastercard',\n 'cardLength' => [16],\n 'cardPrefix' => ['51', '52', '53', '54', '55'],\n ], [\n 'Name' => 'Visa',\n 'cardLength' => [13, 16],\n 'cardPrefix' => ['4'],\n ], [\n 'Name' => 'JCB',\n 'cardLength' => [16],\n 'cardPrefix' => ['3528', '3529', '353', '354', '355', '356', '357', '358'],\n ], [\n 'Name' => 'Discover',\n 'cardLength' => [16],\n 'cardPrefix' => ['6011', '622126', '622127', '622128', '622129', '62213','62214', '62215', '62216', '62217', '62218', '62219','6222', '6223', '6224', '6225', '6226', '6227', '6228','62290', '62291', '622920', '622921', '622922', '622923','622924', '622925', '644', '645', '646', '647', '648','649', '65'],\n ], [\n 'Name' => 'Solo',\n 'cardLength' => [16, 18, 19],\n 'cardPrefix' => ['6334', '6767'],\n ], [\n 'Name' => 'Unionpay',\n 'cardLength' => [16, 17, 18, 19],\n 'cardPrefix' => ['622126', '622127', '622128', '622129', '62213', '62214','62215', '62216', '62217', '62218', '62219', '6222', '6223','6224', '6225', '6226', '6227', '6228', '62290', '62291','622920', '622921', '622922', '622923', '622924', '622925'],\n ], [\n 'Name' => 'Diners Club',\n 'cardLength' => [14],\n 'cardPrefix' => ['300', '301', '302', '303', '304', '305', '36'],\n ], [\n 'Name' => 'Diners Club US',\n 'cardLength' => [16],\n 'cardPrefix' => ['54', '55'],\n ], [\n 'Name' => 'Diners Club Carte Blanche',\n 'cardLength' => [14],\n 'cardPrefix' => ['300', '305'],\n ], [\n 'Name' => 'Laser',\n 'cardLength' => [16, 17, 18, 19],\n 'cardPrefix' => ['6304', '6706', '6771', '6709'],\n ],\n ];\n\n public static function getType($CCNumber)\n {\n $CCNumber = trim($CCNumber);\n $type = 'Unknown';\n foreach (CreditcardType::$creditcardTypes as $card) {\n if (! in_array(strlen($CCNumber), $card['cardLength'])) {\n continue;\n }\n $prefixes = '/^(' . implode('|', $card['cardPrefix']) . ')/';\n if (preg_match($prefixes, $CCNumber) == 1) {\n $type = $card['Name'];\n break;\n }\n }\n return $type;\n }\n}\n\n"
},
{
"answer_id": 19138852,
"author": "Anatoliy",
"author_id": 161832,
"author_profile": "https://Stackoverflow.com/users/161832",
"pm_score": 7,
"selected": false,
"text": "function detectCardType(number) {\n var re = {\n electron: /^(4026|417500|4405|4508|4844|4913|4917)\\d+$/,\n maestro: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\\d+$/,\n dankort: /^(5019)\\d+$/,\n interpayment: /^(636)\\d+$/,\n unionpay: /^(62|88)\\d+$/,\n visa: /^4[0-9]{12}(?:[0-9]{3})?$/,\n mastercard: /^5[1-5][0-9]{14}$/,\n amex: /^3[47][0-9]{13}$/,\n diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n jcb: /^(?:2131|1800|35\\d{3})\\d{11}$/\n }\n\n for(var key in re) {\n if(re[key].test(number)) {\n return key\n }\n }\n}\n describe('CreditCard', function() {\n describe('#detectCardType', function() {\n\n var cards = {\n '8800000000000000': 'UNIONPAY',\n\n '4026000000000000': 'ELECTRON',\n '4175000000000000': 'ELECTRON',\n '4405000000000000': 'ELECTRON',\n '4508000000000000': 'ELECTRON',\n '4844000000000000': 'ELECTRON',\n '4913000000000000': 'ELECTRON',\n '4917000000000000': 'ELECTRON',\n\n '5019000000000000': 'DANKORT',\n\n '5018000000000000': 'MAESTRO',\n '5020000000000000': 'MAESTRO',\n '5038000000000000': 'MAESTRO',\n '5612000000000000': 'MAESTRO',\n '5893000000000000': 'MAESTRO',\n '6304000000000000': 'MAESTRO',\n '6759000000000000': 'MAESTRO',\n '6761000000000000': 'MAESTRO',\n '6762000000000000': 'MAESTRO',\n '6763000000000000': 'MAESTRO',\n '0604000000000000': 'MAESTRO',\n '6390000000000000': 'MAESTRO',\n\n '3528000000000000': 'JCB',\n '3589000000000000': 'JCB',\n '3529000000000000': 'JCB',\n\n '6360000000000000': 'INTERPAYMENT',\n\n '4916338506082832': 'VISA',\n '4556015886206505': 'VISA',\n '4539048040151731': 'VISA',\n '4024007198964305': 'VISA',\n '4716175187624512': 'VISA',\n\n '5280934283171080': 'MASTERCARD',\n '5456060454627409': 'MASTERCARD',\n '5331113404316994': 'MASTERCARD',\n '5259474113320034': 'MASTERCARD',\n '5442179619690834': 'MASTERCARD',\n\n '6011894492395579': 'DISCOVER',\n '6011388644154687': 'DISCOVER',\n '6011880085013612': 'DISCOVER',\n '6011652795433988': 'DISCOVER',\n '6011375973328347': 'DISCOVER',\n\n '345936346788903': 'AMEX',\n '377669501013152': 'AMEX',\n '373083634595479': 'AMEX',\n '370710819865268': 'AMEX',\n '371095063560404': 'AMEX'\n };\n\n Object.keys(cards).forEach(function(number) {\n it('should detect card ' + number + ' as ' + cards[number], function() {\n Basket.detectCardType(number).should.equal(cards[number]);\n });\n });\n });\n});\n"
},
{
"answer_id": 21487404,
"author": "Pinch",
"author_id": 1513082,
"author_profile": "https://Stackoverflow.com/users/1513082",
"pm_score": 2,
"selected": false,
"text": "$(\"#CreditCardNumber\").focusout(function () {\n\n\n var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;\n var regMasterCard = /^5[1-5][0-9]{14}$/;\n var regAmex = /^3[47][0-9]{13}$/;\n var regDiscover = /^6(?:011|5[0-9]{2})[0-9]{12}$/;\n\n if (regVisa.test($(this).val())) {\n $(\"#CCImage\").html(\"<img height='40px' src='@Url.Content(\"~/images/visa.png\")'>\"); \n\n }\n\n else if (regMasterCard.test($(this).val())) {\n $(\"#CCImage\").html(\"<img height='40px' src='@Url.Content(\"~/images/mastercard.png\")'>\");\n\n }\n\n else if (regAmex.test($(this).val())) {\n\n $(\"#CCImage\").html(\"<img height='40px' src='@Url.Content(\"~/images/amex.png\")'>\");\n\n }\n else if (regDiscover.test($(this).val())) {\n\n $(\"#CCImage\").html(\"<img height='40px' src='@Url.Content(\"~/images/discover.png\")'>\");\n\n }\n else {\n $(\"#CCImage\").html(\"NA\");\n\n }\n\n });\n"
},
{
"answer_id": 21617574,
"author": "Janos Szabo",
"author_id": 1176373,
"author_profile": "https://Stackoverflow.com/users/1176373",
"pm_score": 6,
"selected": false,
"text": "^(?:2131|1800|35)[0-9]{0,}$ ^3[47][0-9]{0,}$ ^3(?:0[0-59]{1}|[689])[0-9]{0,}$ ^4[0-9]{0,}$ ^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$ ^(5[06789]|6)[0-9]{0,}$ ^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$ function cc_brand_id(cur_val) {\n // the regular expressions check for possible matches as you type, hence the OR operators based on the number of chars\n // regexp string length {0} provided for soonest detection of beginning of the card numbers this way it could be used for BIN CODE detection also\n\n //JCB\n jcb_regex = new RegExp('^(?:2131|1800|35)[0-9]{0,}$'); //2131, 1800, 35 (3528-3589)\n // American Express\n amex_regex = new RegExp('^3[47][0-9]{0,}$'); //34, 37\n // Diners Club\n diners_regex = new RegExp('^3(?:0[0-59]{1}|[689])[0-9]{0,}$'); //300-305, 309, 36, 38-39\n // Visa\n visa_regex = new RegExp('^4[0-9]{0,}$'); //4\n // MasterCard\n mastercard_regex = new RegExp('^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$'); //2221-2720, 51-55\n maestro_regex = new RegExp('^(5[06789]|6)[0-9]{0,}$'); //always growing in the range: 60-69, started with / not something else, but starting 5 must be encoded as mastercard anyway\n //Discover\n discover_regex = new RegExp('^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$');\n ////6011, 622126-622925, 644-649, 65\n\n\n // get rid of anything but numbers\n cur_val = cur_val.replace(/\\D/g, '');\n\n // checks per each, as their could be multiple hits\n //fix: ordering matter in detection, otherwise can give false results in rare cases\n var sel_brand = \"unknown\";\n if (cur_val.match(jcb_regex)) {\n sel_brand = \"jcb\";\n } else if (cur_val.match(amex_regex)) {\n sel_brand = \"amex\";\n } else if (cur_val.match(diners_regex)) {\n sel_brand = \"diners_club\";\n } else if (cur_val.match(visa_regex)) {\n sel_brand = \"visa\";\n } else if (cur_val.match(mastercard_regex)) {\n sel_brand = \"mastercard\";\n } else if (cur_val.match(discover_regex)) {\n sel_brand = \"discover\";\n } else if (cur_val.match(maestro_regex)) {\n if (cur_val[0] == '5') { //started 5 must be mastercard\n sel_brand = \"mastercard\";\n } else {\n sel_brand = \"maestro\"; //maestro is all 60-69 which is not something else, thats why this condition in the end\n }\n }\n\n return sel_brand;\n}\n /**\n * Obtain a brand constant from a PAN\n *\n * @param string $pan Credit card number\n * @param bool $include_sub_types Include detection of sub visa brands\n * @return string\n */\npublic static function getCardBrand($pan, $include_sub_types = false)\n{\n //maximum length is not fixed now, there are growing number of CCs has more numbers in length, limiting can give false negatives atm\n\n //these regexps accept not whole cc numbers too\n //visa\n $visa_regex = \"/^4[0-9]{0,}$/\";\n $vpreca_regex = \"/^428485[0-9]{0,}$/\";\n $postepay_regex = \"/^(402360|402361|403035|417631|529948){0,}$/\";\n $cartasi_regex = \"/^(432917|432930|453998)[0-9]{0,}$/\";\n $entropay_regex = \"/^(406742|410162|431380|459061|533844|522093)[0-9]{0,}$/\";\n $o2money_regex = \"/^(422793|475743)[0-9]{0,}$/\";\n\n // MasterCard\n $mastercard_regex = \"/^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$/\";\n $maestro_regex = \"/^(5[06789]|6)[0-9]{0,}$/\";\n $kukuruza_regex = \"/^525477[0-9]{0,}$/\";\n $yunacard_regex = \"/^541275[0-9]{0,}$/\";\n\n // American Express\n $amex_regex = \"/^3[47][0-9]{0,}$/\";\n\n // Diners Club\n $diners_regex = \"/^3(?:0[0-59]{1}|[689])[0-9]{0,}$/\";\n\n //Discover\n $discover_regex = \"/^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$/\";\n\n //JCB\n $jcb_regex = \"/^(?:2131|1800|35)[0-9]{0,}$/\";\n\n //ordering matter in detection, otherwise can give false results in rare cases\n if (preg_match($jcb_regex, $pan)) {\n return \"jcb\";\n }\n\n if (preg_match($amex_regex, $pan)) {\n return \"amex\";\n }\n\n if (preg_match($diners_regex, $pan)) {\n return \"diners_club\";\n }\n\n //sub visa/mastercard cards\n if ($include_sub_types) {\n if (preg_match($vpreca_regex, $pan)) {\n return \"v-preca\";\n }\n if (preg_match($postepay_regex, $pan)) {\n return \"postepay\";\n }\n if (preg_match($cartasi_regex, $pan)) {\n return \"cartasi\";\n }\n if (preg_match($entropay_regex, $pan)) {\n return \"entropay\";\n }\n if (preg_match($o2money_regex, $pan)) {\n return \"o2money\";\n }\n if (preg_match($kukuruza_regex, $pan)) {\n return \"kukuruza\";\n }\n if (preg_match($yunacard_regex, $pan)) {\n return \"yunacard\";\n }\n }\n\n if (preg_match($visa_regex, $pan)) {\n return \"visa\";\n }\n\n if (preg_match($mastercard_regex, $pan)) {\n return \"mastercard\";\n }\n\n if (preg_match($discover_regex, $pan)) {\n return \"discover\";\n }\n\n if (preg_match($maestro_regex, $pan)) {\n if ($pan[0] == '5') { //started 5 must be mastercard\n return \"mastercard\";\n }\n return \"maestro\"; //maestro is all 60-69 which is not something else, thats why this condition in the end\n\n }\n\n return \"unknown\"; //unknown for this system\n}\n"
},
{
"answer_id": 21998527,
"author": "rajan",
"author_id": 3348405,
"author_profile": "https://Stackoverflow.com/users/3348405",
"pm_score": 0,
"selected": false,
"text": "(4\\d{12}(?:\\d{3})?) (5[1-5]\\d{14}) (3[47]\\d{13}) ((?:5020|5038|6304|6579|6761)\\d{12}(?:\\d\\d)?) (3(?:0[0-5]|[68][0-9])[0-9]{11}) (6(?:011|5[0-9]{2})[0-9]{12}) (35[2-8][89]\\d\\d\\d{10})"
},
{
"answer_id": 22034170,
"author": "Gajus",
"author_id": 368691,
"author_profile": "https://Stackoverflow.com/users/368691",
"pm_score": 3,
"selected": false,
"text": "$credit_card['pan'] = preg_replace('/[^0-9]/', '', $credit_card['pan']);\n$inn = (int) mb_substr($credit_card['pan'], 0, 2);\n\n// @see http://en.wikipedia.org/wiki/List_of_Bank_Identification_Numbers#Overview\nif ($inn >= 40 && $inn <= 49) {\n $type = 'visa';\n} else if ($inn >= 51 && $inn <= 55) {\n $type = 'mastercard';\n} else if ($inn >= 60 && $inn <= 65) {\n $type = 'discover';\n} else if ($inn >= 34 && $inn <= 37) {\n $type = 'amex';\n} else {\n throw new \\UnexpectedValueException('Unsupported card type.');\n}\n"
},
{
"answer_id": 22631832,
"author": "Nick",
"author_id": 956278,
"author_profile": "https://Stackoverflow.com/users/956278",
"pm_score": 3,
"selected": false,
"text": " var getCardType = function (number) {\n var cards = {\n visa: /^4[0-9]{12}(?:[0-9]{3})?$/,\n mastercard: /^5[1-5][0-9]{14}$/,\n amex: /^3[47][0-9]{13}$/,\n diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n jcb: /^(?:2131|1800|35\\d{3})\\d{11}$/\n };\n for (var card in cards) {\n if (cards[card].test(number)) {\n return card;\n }\n }\n };\n"
},
{
"answer_id": 24615110,
"author": "ZurabWeb",
"author_id": 1016530,
"author_profile": "https://Stackoverflow.com/users/1016530",
"pm_score": 2,
"selected": false,
"text": "function detectCreditCardType() {\n var type = new Array;\n type[1] = '^4[0-9]{12}(?:[0-9]{3})?$'; // visa\n type[2] = '^5[1-5][0-9]{14}$'; // mastercard\n type[3] = '^6(?:011|5[0-9]{2})[0-9]{12}$'; // discover\n type[4] = '^3[47][0-9]{13}$'; // amex\n\n var ccnum = $('.creditcard').val().replace(/[^\\d.]/g, '');\n var returntype = 0;\n\n $.each(type, function(idx, re) {\n var regex = new RegExp(re);\n if(regex.test(ccnum) && idx>0) {\n returntype = idx;\n }\n });\n\n return returntype;\n}\n"
},
{
"answer_id": 29937208,
"author": "Nagama Inamdar",
"author_id": 2240243,
"author_profile": "https://Stackoverflow.com/users/2240243",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery.payment/1.2.3/jquery.payment.js \" ></script>\n $(document).ready(function() { \n var type = $.payment.cardType(\"4242 4242 4242 4242\"); //test card number\n console.log(type); \n}); \n"
},
{
"answer_id": 30957202,
"author": "angelcool.net",
"author_id": 2425880,
"author_profile": "https://Stackoverflow.com/users/2425880",
"pm_score": 3,
"selected": false,
"text": " public static function detectCardType($num)\n {\n $re = array(\n \"visa\" => \"/^4[0-9]{12}(?:[0-9]{3})?$/\",\n \"mastercard\" => \"/^5[1-5][0-9]{14}$/\",\n \"amex\" => \"/^3[47][0-9]{13}$/\",\n \"discover\" => \"/^6(?:011|5[0-9]{2})[0-9]{12}$/\",\n );\n\n if (preg_match($re['visa'],$num))\n {\n return 'visa';\n }\n else if (preg_match($re['mastercard'],$num))\n {\n return 'mastercard';\n }\n else if (preg_match($re['amex'],$num))\n {\n return 'amex';\n }\n else if (preg_match($re['discover'],$num))\n {\n return 'discover';\n }\n else\n {\n return false;\n }\n }\n"
},
{
"answer_id": 31734477,
"author": "ShadeTreeDeveloper",
"author_id": 633527,
"author_profile": "https://Stackoverflow.com/users/633527",
"pm_score": 2,
"selected": false,
"text": "var sf = smartForm.formatCC(myInputString);\nvar cardType = sf.cardType;\n"
},
{
"answer_id": 36483754,
"author": "Daisy R.",
"author_id": 1855263,
"author_profile": "https://Stackoverflow.com/users/1855263",
"pm_score": 3,
"selected": false,
"text": "print(self.validateCardType(self.creditCardField.text!))\n\nfunc validateCardType(testCard: String) -> String {\n\n let regVisa = \"^4[0-9]{12}(?:[0-9]{3})?$\"\n let regMaster = \"^5[1-5][0-9]{14}$\"\n let regExpress = \"^3[47][0-9]{13}$\"\n let regDiners = \"^3(?:0[0-5]|[68][0-9])[0-9]{11}$\"\n let regDiscover = \"^6(?:011|5[0-9]{2})[0-9]{12}$\"\n let regJCB = \"^(?:2131|1800|35\\\\d{3})\\\\d{11}$\"\n\n\n let regVisaTest = NSPredicate(format: \"SELF MATCHES %@\", regVisa)\n let regMasterTest = NSPredicate(format: \"SELF MATCHES %@\", regMaster)\n let regExpressTest = NSPredicate(format: \"SELF MATCHES %@\", regExpress)\n let regDinersTest = NSPredicate(format: \"SELF MATCHES %@\", regDiners)\n let regDiscoverTest = NSPredicate(format: \"SELF MATCHES %@\", regDiscover)\n let regJCBTest = NSPredicate(format: \"SELF MATCHES %@\", regJCB)\n\n\n if regVisaTest.evaluateWithObject(testCard){\n return \"Visa\"\n }\n else if regMasterTest.evaluateWithObject(testCard){\n return \"MasterCard\"\n }\n\n else if regExpressTest.evaluateWithObject(testCard){\n return \"American Express\"\n }\n\n else if regDinersTest.evaluateWithObject(testCard){\n return \"Diners Club\"\n }\n\n else if regDiscoverTest.evaluateWithObject(testCard){\n return \"Discover\"\n }\n\n else if regJCBTest.evaluateWithObject(testCard){\n return \"JCB\"\n }\n\n return \"\"\n\n}\n"
},
{
"answer_id": 36882835,
"author": "radtek",
"author_id": 2023392,
"author_profile": "https://Stackoverflow.com/users/2023392",
"pm_score": 2,
"selected": false,
"text": "True def is_american_express(cc_number):\n \"\"\"Checks if the card is an american express. If us billing address country code, & is_amex, use vpos\n https://en.wikipedia.org/wiki/Bank_card_number#cite_note-GenCardFeatures-3\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^3[47][0-9]{13}$', cc_number))\n\n\ndef is_visa(cc_number):\n \"\"\"Checks if the card is a visa, begins with 4 and 12 or 15 additional digits.\n :param cc_number: unicode card number\n \"\"\"\n\n # Standard Visa is 13 or 16, debit can be 19\n if bool(re.match(r'^4', cc_number)) and len(cc_number) in [13, 16, 19]:\n return True\n\n return False\n\n\ndef is_mastercard(cc_number):\n \"\"\"Checks if the card is a mastercard. Begins with 51-55 or 2221-2720 and 16 in length.\n :param cc_number: unicode card number\n \"\"\"\n if len(cc_number) == 16 and cc_number.isdigit(): # Check digit, before cast to int\n return bool(re.match(r'^5[1-5]', cc_number)) or int(cc_number[:4]) in range(2221, 2721)\n return False\n\n\ndef is_discover(cc_number):\n \"\"\"Checks if the card is discover, re would be too hard to maintain. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n if len(cc_number) == 16:\n try:\n # return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or cc_number[:6] in range(622126, 622926))\n return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or 622126 <= int(cc_number[:6]) <= 622925)\n except ValueError:\n return False\n return False\n\n\ndef is_jcb(cc_number):\n \"\"\"Checks if the card is a jcb. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n # return bool(re.match(r'^(?:2131|1800|35\\d{3})\\d{11}$', cc_number)) # wikipedia\n return bool(re.match(r'^35(2[89]|[3-8][0-9])[0-9]{12}$', cc_number)) # PawelDecowski\n\n\ndef is_diners_club(cc_number):\n \"\"\"Checks if the card is a diners club. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^3(?:0[0-6]|[68][0-9])[0-9]{11}$', cc_number)) # 0-5 = carte blance, 6 = international\n\n\ndef is_laser(cc_number):\n \"\"\"Checks if the card is laser. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^(6304|670[69]|6771)', cc_number))\n\n\ndef is_maestro(cc_number):\n \"\"\"Checks if the card is maestro. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n possible_lengths = [12, 13, 14, 15, 16, 17, 18, 19]\n return bool(re.match(r'^(50|5[6-9]|6[0-9])', cc_number)) and len(cc_number) in possible_lengths\n\n\n# Child cards\n\ndef is_visa_electron(cc_number):\n \"\"\"Child of visa. Checks if the card is a visa electron. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^(4026|417500|4508|4844|491(3|7))', cc_number)) and len(cc_number) == 16\n\n\ndef is_total_rewards_visa(cc_number):\n \"\"\"Child of visa. Checks if the card is a Total Rewards Visa. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^41277777[0-9]{8}$', cc_number))\n\n\ndef is_diners_club_carte_blanche(cc_number):\n \"\"\"Child card of diners. Checks if the card is a diners club carte blance. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^30[0-5][0-9]{11}$', cc_number)) # github PawelDecowski, jquery-creditcardvalidator\n\n\ndef is_diners_club_carte_international(cc_number):\n \"\"\"Child card of diners. Checks if the card is a diners club international. Not a supported card.\n :param cc_number: unicode card number\n \"\"\"\n return bool(re.match(r'^36[0-9]{12}$', cc_number)) # jquery-creditcardvalidator\n"
},
{
"answer_id": 37559946,
"author": "Vidyalaxmi",
"author_id": 2930683,
"author_profile": "https://Stackoverflow.com/users/2930683",
"pm_score": 2,
"selected": false,
"text": "enum CreditCardType: Int { // Enum which encapsulates different card types and method to find the type of card.\n\ncase Visa\ncase Master\ncase Amex\ncase Discover\n\nfunc validationRegex() -> String {\n var regex = \"\"\n switch self {\n case .Visa:\n regex = \"^4[0-9]{6,}$\"\n\n case .Master:\n regex = \"^5[1-5][0-9]{5,}$\"\n\n case .Amex:\n regex = \"^3[47][0-9]{13}$\"\n\n case .Discover:\n regex = \"^6(?:011|5[0-9]{2})[0-9]{12}$\"\n }\n\n return regex\n}\n\nfunc validate(cardNumber: String) -> Bool {\n let predicate = NSPredicate(format: \"SELF MATCHES %@\", validationRegex())\n return predicate.evaluateWithObject(cardNumber)\n}\n\n// Method returns the credit card type for given card number\nstatic func cardTypeForCreditCardNumber(cardNumber: String) -> CreditCardType? {\n var creditCardType: CreditCardType?\n\n var index = 0\n while let cardType = CreditCardType(rawValue: index) {\n if cardType.validate(cardNumber) {\n creditCardType = cardType\n break\n } else {\n index++\n }\n }\n return creditCardType\n }\n}\n"
},
{
"answer_id": 42667959,
"author": "Anoop M Maddasseri",
"author_id": 4694013,
"author_profile": "https://Stackoverflow.com/users/4694013",
"pm_score": 1,
"selected": false,
"text": "public static final String AMERICAN_EXPRESS = \"American Express\";\npublic static final String DISCOVER = \"Discover\";\npublic static final String JCB = \"JCB\";\npublic static final String DINERS_CLUB = \"Diners Club\";\npublic static final String VISA = \"Visa\";\npublic static final String MASTERCARD = \"MasterCard\";\npublic static final String UNKNOWN = \"Unknown\";\n // Based on http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29\npublic static final String[] PREFIXES_AMERICAN_EXPRESS = {\"34\", \"37\"};\npublic static final String[] PREFIXES_DISCOVER = {\"60\", \"62\", \"64\", \"65\"};\npublic static final String[] PREFIXES_JCB = {\"35\"};\npublic static final String[] PREFIXES_DINERS_CLUB = {\"300\", \"301\", \"302\", \"303\", \"304\", \"305\", \"309\", \"36\", \"38\", \"39\"};\npublic static final String[] PREFIXES_VISA = {\"4\"};\npublic static final String[] PREFIXES_MASTERCARD = {\n \"2221\", \"2222\", \"2223\", \"2224\", \"2225\", \"2226\", \"2227\", \"2228\", \"2229\",\n \"223\", \"224\", \"225\", \"226\", \"227\", \"228\", \"229\",\n \"23\", \"24\", \"25\", \"26\",\n \"270\", \"271\", \"2720\",\n \"50\", \"51\", \"52\", \"53\", \"54\", \"55\"\n };\n public String getBrand(String number) {\n\nString evaluatedType;\nif (StripeTextUtils.hasAnyPrefix(number, PREFIXES_AMERICAN_EXPRESS)) {\n evaluatedType = AMERICAN_EXPRESS;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DISCOVER)) {\n evaluatedType = DISCOVER;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_JCB)) {\n evaluatedType = JCB;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DINERS_CLUB)) {\n evaluatedType = DINERS_CLUB;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_VISA)) {\n evaluatedType = VISA;\n} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_MASTERCARD)) {\n evaluatedType = MASTERCARD;\n} else {\n evaluatedType = UNKNOWN;\n}\n return evaluatedType;\n}\n /**\n * Check to see if the input number has any of the given prefixes.\n *\n * @param number the number to test\n * @param prefixes the prefixes to test against\n * @return {@code true} if number begins with any of the input prefixes\n*/\n\npublic static boolean hasAnyPrefix(String number, String... prefixes) {\n if (number == null) {\n return false;\n }\n for (String prefix : prefixes) {\n if (number.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n}\n"
},
{
"answer_id": 49531091,
"author": "gaurav gupta",
"author_id": 5695805,
"author_profile": "https://Stackoverflow.com/users/5695805",
"pm_score": 0,
"selected": false,
"text": "follow Luhn’s algorithm\n\n private boolean validateCreditCardNumber(String str) {\n\n int[] ints = new int[str.length()];\n for (int i = 0; i < str.length(); i++) {\n ints[i] = Integer.parseInt(str.substring(i, i + 1));\n }\n for (int i = ints.length - 2; i >= 0; i = i - 2) {\n int j = ints[i];\n j = j * 2;\n if (j > 9) {\n j = j % 10 + 1;\n }\n ints[i] = j;\n }\n int sum = 0;\n for (int i = 0; i < ints.length; i++) {\n sum += ints[i];\n }\n if (sum % 10 == 0) {\n return true;\n } else {\n return false;\n }\n\n\n }\n\nthen call this method\n\nEdittext mCreditCardNumberEt;\n\n mCreditCardNumberEt.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n\n int cardcount= s.toString().length();\n if(cardcount>=16) {\n boolean cardnumbervalid= validateCreditCardNumber(s.toString());\n if(cardnumbervalid) {\n cardvalidtesting.setText(\"Valid Card\");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.green));\n }\n else {\n cardvalidtesting.setText(\"Invalid Card\");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));\n }\n }\n else if(cardcount>0 &&cardcount<16) {\n cardvalidtesting.setText(\"Invalid Card\");\n cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));\n }\n\n else {\n cardvalidtesting.setText(\"\");\n\n }\n\n\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n\n }\n });\n"
},
{
"answer_id": 58241706,
"author": "OhhhThatVarun",
"author_id": 7436566,
"author_profile": "https://Stackoverflow.com/users/7436566",
"pm_score": 1,
"selected": false,
"text": "private fun getCardType(number: String): String {\n\n val visa = Regex(\"^4[0-9]{12}(?:[0-9]{3})?$\")\n val mastercard = Regex(\"^5[1-5][0-9]{14}$\")\n val amx = Regex(\"^3[47][0-9]{13}$\")\n\n return when {\n visa.matches(number) -> \"Visa\"\n mastercard.matches(number) -> \"Mastercard\"\n amx.matches(number) -> \"American Express\"\n else -> \"Unknown\"\n }\n }\n"
},
{
"answer_id": 62955455,
"author": "Emanuel",
"author_id": 6638583,
"author_profile": "https://Stackoverflow.com/users/6638583",
"pm_score": 2,
"selected": false,
"text": "function getCardType (number) {\n const numberFormated = number.replace(/\\D/g, '')\n var patterns = {\n VISA: /^4[0-9]{12}(?:[0-9]{3})?$/,\n MASTER: /^5[1-5][0-9]{14}$/,\n AMEX: /^3[47][0-9]{13}$/,\n ELO: /^((((636368)|(438935)|(504175)|(451416)|(636297))\\d{0,10})|((5067)|(4576)|(4011))\\d{0,12})$/,\n AURA: /^(5078\\d{2})(\\d{2})(\\d{11})$/,\n JCB: /^(?:2131|1800|35\\d{3})\\d{11}$/,\n DINERS: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,\n DISCOVERY: /^6(?:011|5[0-9]{2})[0-9]{12}$/,\n HIPERCARD: /^(606282\\d{10}(\\d{3})?)|(3841\\d{15})$/,\n ELECTRON: /^(4026|417500|4405|4508|4844|4913|4917)\\d+$/,\n MAESTRO: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\\d+$/,\n DANKORT: /^(5019)\\d+$/,\n INTERPAYMENT: /^(636)\\d+$/,\n UNIONPAY: /^(62|88)\\d+$/,\n }\n for (var key in patterns) {\n if (patterns[key].test(numberFormated)) {\n return key\n }\n }\n}\n\nconsole.log(getCardType(\"4539 5684 7526 2091\"))"
},
{
"answer_id": 64923841,
"author": "Saharat Sittipanya",
"author_id": 10767168,
"author_profile": "https://Stackoverflow.com/users/10767168",
"pm_score": 2,
"selected": false,
"text": "extension String {\n \n func isMatch(_ Regex: String) -> Bool {\n \n do {\n let regex = try NSRegularExpression(pattern: Regex)\n let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self))\n return results.map {\n String(self[Range($0.range, in: self)!])\n }.count > 0\n } catch {\n return false\n }\n \n }\n \n func getCreditCardType() -> String? {\n \n let VISA_Regex = \"^4[0-9]{6,}$\"\n let MasterCard_Regex = \"^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$\"\n let AmericanExpress_Regex = \"^3[47][0-9]{5,}$\"\n let DinersClub_Regex = \"^3(?:0[0-5]|[68][0-9])[0-9]{4,}$\"\n let Discover_Regex = \"^6(?:011|5[0-9]{2})[0-9]{3,}$\"\n let JCB_Regex = \"^(?:2131|1800|35[0-9]{3})[0-9]{3,}$\"\n \n if self.isMatch(VISA_Regex) {\n return \"VISA\"\n } else if self.isMatch(MasterCard_Regex) {\n return \"MasterCard\"\n } else if self.isMatch(AmericanExpress_Regex) {\n return \"AmericanExpress\"\n } else if self.isMatch(DinersClub_Regex) {\n return \"DinersClub\"\n } else if self.isMatch(Discover_Regex) {\n return \"Discover\"\n } else if self.isMatch(JCB_Regex) {\n return \"JCB\"\n } else {\n return nil\n }\n \n }\n \n}\n \"1234123412341234\".getCreditCardType()\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12382/"
] |
72,769 |
<p>Problem (simplified to make things clearer):</p>
<ul>
1. there is one statically-linked static.lib that has a function that increments:
<pre><code>
extern int CallCount = 0;
int TheFunction()
{
void *p = &CallCount;
printf("Function called");
return CallCount++;
}
</code></pre>
2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method:
<pre><code>
int Managed::CallLibFunc()
{
return TheFunction();
}
</code></pre>
3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper:
<pre><code>
static void Main(string[] args)
{
Managed c1 = new Managed();
int val1 = c1.CallLibFunc();
// value is zero
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// value is one
}
</code></pre>
</ul>
<p>Question:</p>
<p>Based on what I have read in Essential .NET Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?</p>
<p>Thank you very much everyone!</p>
|
[
{
"answer_id": 157738,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "class CallCountHolder {\n public:\n CallCountHolder(int i) : count(i) {}\n int count;\n};\n\nstatic CallCountHolder cc(0);\nint TheFunction()\n{\n printf(\"Function called\");\n return cc.count++;\n}\n"
},
{
"answer_id": 693295,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Managed c1 = new Managed(); \n static void Main(string[] args)\n{\n\n { \n AppDomain ad = AppDomain.CreateDomain(\"NewDomain\");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // Value is zero\n\n AppDomain.Unload(ad)\n }\n { \n AppDomain ad = AppDomain.CreateDomain(\"NewDomain\");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // I think value is zero\n\n AppDomain.Unload(ad)\n }\n\n\n}\n`\n static void Main(string[] args)\n{\n\n { \n AppDomain ad = AppDomain.CreateDomain(\"NewDomain\");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // Value is zero \n\n AppDomain.Unload(ad)\n }\n { \n AppDomain ad = AppDomain.CreateDomain(\"NewDomain\");\n Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;\n int val2 = c.CallLibFunc();\n // I think value is one\n\n AppDomain.Unload(ad)\n }\nManaged c1 = new Managed(); \n\n\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2341/"
] |
72,789 |
<p>I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon in the demo config but continue to use the regular icon for the full version's config?</p>
|
[
{
"answer_id": 72877,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 4,
"selected": true,
"text": "#ifdef _DEMO_VERSION_\nIDR_MAINFRAME ICON \"demo.ico\"\n#else\nIDR_MAINFRAME ICON \"full.ico\"\n#endif\n"
},
{
"answer_id": 72880,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 2,
"selected": false,
"text": "del app.ico | copy app_full.ico app.ico\n del app.ico | copy app_demo.ico app.ico\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12117/"
] |
72,829 |
<p>Can anyone recommend a good (preferably open source) tool for creating WSDL files for some soap web services?</p>
<p>I've tried playing around with some of the eclipse plug ins available and was less than impressed with what I found.</p>
|
[
{
"answer_id": 73251,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 3,
"selected": false,
"text": "http://localhost/axis/{yourservice}?WSDL"
},
{
"answer_id": 570900,
"author": "John Greeley",
"author_id": 62209,
"author_profile": "https://Stackoverflow.com/users/62209",
"pm_score": 2,
"selected": false,
"text": "<BuyItem> <BuyItemResponse>"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2246765/"
] |
72,831 |
<p>Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?</p>
|
[
{
"answer_id": 72862,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 9,
"selected": true,
"text": "TextInfo.ToTitleCase() ToLower() string s = \"JOHN DOE\";\ns = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());\n// Produces \"John Doe\"\n string s = \"JOHN DOE\";\ns = new System.Globalization.CultureInfo(\"en-US\", false).TextInfo.ToTitleCase(s.ToLower());\n"
},
{
"answer_id": 72871,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 7,
"selected": false,
"text": "CultureInfo.CurrentCulture.TextInfo.ToTitleCase(\"hello world\");\n"
},
{
"answer_id": 72888,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();\nlastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();\n"
},
{
"answer_id": 72910,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "public static string FirstLetterToUpper(this String input)\n{\n return input = input.Substring(0, 1).ToUpper() + \n input.Substring(1, input.Length - 1);\n}\n"
},
{
"answer_id": 72939,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": -1,
"selected": false,
"text": "public string SentenceCase(string input)\n{\n return input(0, 1).ToUpper + input.Substring(1).ToLower;\n}\n"
},
{
"answer_id": 73691,
"author": "Jamie Ide",
"author_id": 12752,
"author_profile": "https://Stackoverflow.com/users/12752",
"pm_score": 3,
"selected": false,
"text": " public static string ToTitleCase(string str)\n {\n string result = str;\n if (!string.IsNullOrEmpty(str))\n {\n var words = str.Split(' ');\n for (int index = 0; index < words.Length; index++)\n {\n var s = words[index];\n if (s.Length > 0)\n {\n words[index] = s[0].ToString().ToUpper() + s.Substring(1);\n }\n }\n result = string.Join(\" \", words);\n }\n return result;\n }\n"
},
{
"answer_id": 74008,
"author": "Eddie Velasquez",
"author_id": 12851,
"author_profile": "https://Stackoverflow.com/users/12851",
"pm_score": 2,
"selected": false,
"text": "public static class StringExtensions\n{\n public static string ToProperCase( this string original )\n {\n if( String.IsNullOrEmpty( original ) )\n return original;\n\n string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );\n return result;\n }\n\n public static string WordToProperCase( this string word )\n {\n if( String.IsNullOrEmpty( word ) )\n return word;\n\n if( word.Length > 1 )\n return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );\n\n return word.ToUpper( CultureInfo.CurrentCulture );\n }\n\n private static readonly Regex _properNameRx = new Regex( @\"\\b(\\w+)\\b\" );\n private static readonly string[] _prefixes = {\n \"mc\"\n };\n\n private static string HandleWord( Match m )\n {\n string word = m.Groups[1].Value;\n\n foreach( string prefix in _prefixes )\n {\n if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )\n return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();\n }\n\n return word.WordToProperCase();\n }\n}\n"
},
{
"answer_id": 74023,
"author": "Andy Rose",
"author_id": 1762,
"author_profile": "https://Stackoverflow.com/users/1762",
"pm_score": 0,
"selected": false,
"text": "inputString = inputString.ToLower();\ninputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);\nint indexOfMc = inputString.IndexOf(\" Mc\");\nif(indexOfMc > 0)\n{\n inputString.Substring(0, indexOfMc + 3) + inputString[indexOfMc + 3].ToString().ToUpper() + inputString.Substring(indexOfMc + 4);\n}\n"
},
{
"answer_id": 3169381,
"author": "Ganesan SubbiahPandian",
"author_id": 382422,
"author_profile": "https://Stackoverflow.com/users/382422",
"pm_score": 5,
"selected": false,
"text": "String test = \"HELLO HOW ARE YOU\";\nstring s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);\n String test = \"HELLO HOW ARE YOU\";\nstring s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());\n"
},
{
"answer_id": 4759134,
"author": "Ton Snoei",
"author_id": 584472,
"author_profile": "https://Stackoverflow.com/users/584472",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Makes each first letter of a word uppercase. The rest will be lowercase\n/// </summary>\n/// <param name=\"Phrase\"></param>\n/// <returns></returns>\npublic static string FormatWordsWithFirstCapital(string Phrase)\n{\n MatchCollection Matches = Regex.Matches(Phrase, \"\\\\b\\\\w\");\n Phrase = Phrase.ToLower();\n foreach (Match Match in Matches)\n Phrase = Phrase.Remove(Match.Index, 1).Insert(Match.Index, Match.Value.ToUpper());\n\n return Phrase;\n}\n"
},
{
"answer_id": 12413336,
"author": "TrentVB",
"author_id": 1118056,
"author_profile": "https://Stackoverflow.com/users/1118056",
"pm_score": 0,
"selected": false,
"text": "using System.Globalization;\n...\nTextInfo myTi = new CultureInfo(\"en-Us\",false).TextInfo;\nstring raw = \"THIS IS ALL CAPS\";\nstring firstCapOnly = myTi.ToTitleCase(raw.ToLower());\n"
},
{
"answer_id": 14121370,
"author": "Arun",
"author_id": 1063254,
"author_profile": "https://Stackoverflow.com/users/1063254",
"pm_score": 0,
"selected": false,
"text": "String fName = \"firstname\";\nString lName = \"lastname\";\nString capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);\nString capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);\n"
},
{
"answer_id": 19517670,
"author": "polkduran",
"author_id": 848634,
"author_profile": "https://Stackoverflow.com/users/848634",
"pm_score": 4,
"selected": false,
"text": "CultureInfo.CurrentCulture.TextInfo.ToTitleCase ' string input = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(\"o'reilly, m'grego, d'angelo\");\n// input = O'reilly, M'grego, D'angelo\n \\b[a-zA-Z] \\b Regex.Replace(string input,string pattern,MatchEvaluator evaluator) string input = \"o'reilly, m'grego, d'angelo\";\ninput = Regex.Replace(input.ToLower(), @\"\\b[a-zA-Z]\", m => m.Value.ToUpper());\n// input = O'Reilly, M'Grego, D'Angelo\n MacDonald McFry (?<=\\b(?:mc|mac)?)[a-zA-Z] string input = \"o'reilly, m'grego, d'angelo, macdonald's, mcfry\";\ninput = Regex.Replace(input.ToLower(), @\"(?<=\\b(?:mc|mac)?)[a-zA-Z]\", m => m.Value.ToUpper());\n// input = O'Reilly, M'Grego, D'Angelo, MacDonald'S, McFry\n (?:mc|mac) du, de (?:mc|mac|du|de) MacDonald'S 's (?<!'s\\b) string input = \"o'reilly, m'grego, d'angelo, macdonald's, mcfry\";\ninput = Regex.Replace(input.ToLower(), @\"(?<=\\b(?:mc|mac)?)[a-zA-Z](?<!'s\\b)\", m => m.Value.ToUpper());\n// input = O'Reilly, M'Grego, D'Angelo, MacDonald's, McFry\n"
},
{
"answer_id": 40882007,
"author": "Govind Singh Rawat",
"author_id": 5580191,
"author_profile": "https://Stackoverflow.com/users/5580191",
"pm_score": 0,
"selected": false,
"text": " public static string ConvertToCaptilize(string input)\n {\n if (!string.IsNullOrEmpty(input))\n {\n string[] arrUserInput = input.Split(' ');\n\n\n // Initialize a string builder object for the output\n StringBuilder sbOutPut = new StringBuilder();\n\n\n // Loop thru each character in the string array\n foreach (string str in arrUserInput)\n {\n if (!string.IsNullOrEmpty(str))\n {\n var charArray = str.ToCharArray();\n int k = 0;\n foreach (var cr in charArray)\n {\n char c;\n c = k == 0 ? char.ToUpper(cr) : char.ToLower(cr);\n sbOutPut.Append(c);\n k++;\n }\n\n\n }\n sbOutPut.Append(\" \");\n }\n return sbOutPut.ToString();\n }\n return string.Empty;\n\n }\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9938/"
] |
72,852 |
<p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> (thanks John B)</p>
|
[
{
"answer_id": 465129,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 7,
"selected": false,
"text": "main.py\nsetup.py\napp/ ->\n __init__.py\n package_a/ ->\n __init__.py\n module_a.py\n package_b/ ->\n __init__.py\n module_b.py\n python main.py main.py import app.package_a.module_a module_a.py import app.package_b.module_b from app.package_a import module_a app main.py setup.py main.py"
},
{
"answer_id": 1083169,
"author": "iElectric",
"author_id": 133235,
"author_profile": "https://Stackoverflow.com/users/133235",
"pm_score": 5,
"selected": false,
"text": "def import_path(fullpath):\n \"\"\" \n Import a file with full path specification. Allows one to\n import from anywhere, something __import__ does not do. \n \"\"\"\n path, filename = os.path.split(fullpath)\n filename, ext = os.path.splitext(filename)\n sys.path.append(path)\n module = __import__(filename)\n reload(module) # Might be out of date\n del sys.path[-1]\n return module\n"
},
{
"answer_id": 6524846,
"author": "jung rhew",
"author_id": 821632,
"author_profile": "https://Stackoverflow.com/users/821632",
"pm_score": 2,
"selected": false,
"text": "from __future__ import absolute_import import string from pkg import string"
},
{
"answer_id": 7541369,
"author": "mossplix",
"author_id": 487623,
"author_profile": "https://Stackoverflow.com/users/487623",
"pm_score": 3,
"selected": false,
"text": "from .mod1 import stuff\n"
},
{
"answer_id": 9541554,
"author": "Garrett Berg",
"author_id": 674076,
"author_profile": "https://Stackoverflow.com/users/674076",
"pm_score": 4,
"selected": false,
"text": "mymodule\\\n __init__.py\n mymodule1\\\n __init__.py\n mymodule1_1\n mymodule2\\\n __init__.py\n mymodule2_1\n\n\nimport mymodule.mymodule1.mymodule1_1 \n if __name__ == '__main__':\n sys.path.insert(0, '../..')\n"
},
{
"answer_id": 9748770,
"author": "Andrew_1510",
"author_id": 451718,
"author_profile": "https://Stackoverflow.com/users/451718",
"pm_score": 1,
"selected": false,
"text": "bash$ export PYTHONPATH=/PATH/TO/APP\n import sub1.func1\n#...more import\n"
},
{
"answer_id": 12365065,
"author": "Gabriel",
"author_id": 1621769,
"author_profile": "https://Stackoverflow.com/users/1621769",
"pm_score": 1,
"selected": false,
"text": "__package__ __main__ sys.path \"package_head.subfolder.module_name\""
},
{
"answer_id": 14189875,
"author": "milkypostman",
"author_id": 154508,
"author_profile": "https://Stackoverflow.com/users/154508",
"pm_score": 4,
"selected": false,
"text": "scripts import os.path\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\")))\n"
},
{
"answer_id": 15458607,
"author": "Pankaj",
"author_id": 382630,
"author_profile": "https://Stackoverflow.com/users/382630",
"pm_score": 7,
"selected": false,
"text": "from ..sub2 import mod2 mod1.py app python -m app.sub1.mod1 __name__ __name__ __main__ relative import in non-package"
},
{
"answer_id": 20449492,
"author": "suhailvs",
"author_id": 2351696,
"author_profile": "https://Stackoverflow.com/users/2351696",
"pm_score": 5,
"selected": false,
"text": "nosklo's __init__.py main.py\napp/ ->\n __init__.py\n package_a/ ->\n __init__.py\n fun_a.py\n package_b/ ->\n __init__.py\n fun_b.py\n def print_a():\n print 'This is a function in dir package_a'\n from app.package_a.fun_a import print_a\ndef print_b():\n print 'This is a function in dir package_b'\n print 'going to call a function in dir package_a'\n print '-'*30\n print_a()\n from app.package_b import fun_b\nfun_b.print_b()\n $ python main.py This is a function in dir package_b\ngoing to call a function in dir package_a\n------------------------------\nThis is a function in dir package_a\n from app.package_b import fun_b from app.package_a.fun_a import print_a package_b package_a"
},
{
"answer_id": 30736316,
"author": "LondonRob",
"author_id": 2071807,
"author_profile": "https://Stackoverflow.com/users/2071807",
"pm_score": 3,
"selected": false,
"text": ".py import imp\n\nfoo = imp.load_source('module.name', '/path/to/file.py')\nfoo.MyClass()\n"
},
{
"answer_id": 35338828,
"author": "Роман Арсеньев",
"author_id": 5774201,
"author_profile": "https://Stackoverflow.com/users/5774201",
"pm_score": 6,
"selected": false,
"text": "import sys\nsys.path.insert(0, \"../settings\")\n\n\ntry:\n from local_settings import *\nexcept ImportError:\n print('No Import')\n"
},
{
"answer_id": 60846688,
"author": "Giorgos Myrianthous",
"author_id": 7131757,
"author_profile": "https://Stackoverflow.com/users/7131757",
"pm_score": 1,
"selected": false,
"text": "PYTHONPATH export PYTHONPATH=\"${PYTHONPATH}:/path/to/your/module/\"\n"
},
{
"answer_id": 70163621,
"author": "Rohit Kumar J",
"author_id": 14376181,
"author_profile": "https://Stackoverflow.com/users/14376181",
"pm_score": 0,
"selected": false,
"text": "import os\nimport inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nos.sys.path.insert(1, parentdir)\n# print(\"currentdir = \", currentdir)\n# print(\"parentdir=\", parentdir)\n"
},
{
"answer_id": 71315540,
"author": "F.M.F.",
"author_id": 4858818,
"author_profile": "https://Stackoverflow.com/users/4858818",
"pm_score": 0,
"selected": false,
"text": "import pathlib \nimport sys\nsys.path.append(pathlib.Path(__file__).parent.resolve())\nimport file_to_import # the actual intended import\n pathlib os.path"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497/"
] |
72,899 |
<p>How do I sort a list of dictionaries by a specific key's value? Given:</p>
<pre><code>[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
</code></pre>
<p>When sorted by <code>name</code>, it should become:</p>
<pre><code>[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
</code></pre>
|
[
{
"answer_id": 73019,
"author": "Bartosz Radaczyński",
"author_id": 985,
"author_profile": "https://Stackoverflow.com/users/985",
"pm_score": 5,
"selected": false,
"text": "[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))\n"
},
{
"answer_id": 73044,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 7,
"selected": false,
"text": "my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n\nmy_list.sort(lambda x,y : cmp(x['name'], y['name']))\n my_list key my_list = sorted(my_list, key=lambda k: k['name'])\n operator.itemgetter"
},
{
"answer_id": 73050,
"author": "Mario F",
"author_id": 3785,
"author_profile": "https://Stackoverflow.com/users/3785",
"pm_score": 13,
"selected": true,
"text": "sorted() key= newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) \n operator.itemgetter from operator import itemgetter\nnewlist = sorted(list_to_be_sorted, key=itemgetter('name')) \n reverse=True newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)\n"
},
{
"answer_id": 73098,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 5,
"selected": false,
"text": "import operator\na_list_of_dicts.sort(key=operator.itemgetter('name'))\n"
},
{
"answer_id": 73186,
"author": "Owen",
"author_id": 12592,
"author_profile": "https://Stackoverflow.com/users/12592",
"pm_score": 5,
"selected": false,
"text": "def mykey(adict): return adict['name']\nx = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]\nsorted(x, key=mykey)\n itemgetter from operator import itemgetter\nx = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]\nsorted(x, key=itemgetter('name'))\n"
},
{
"answer_id": 73465,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "import operator\n list_of_dicts.sort(key=operator.itemgetter('name'))\n list_of_dicts.sort(key=operator.itemgetter('age'))\n"
},
{
"answer_id": 2858683,
"author": "Dologan",
"author_id": 222135,
"author_profile": "https://Stackoverflow.com/users/222135",
"pm_score": 6,
"selected": false,
"text": "my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ]\nsortedlist = sorted(my_list , key=lambda elem: \"%02d %s\" % (elem['age'], elem['name']))\n"
},
{
"answer_id": 16772049,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 5,
"selected": false,
"text": "py = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n sort_on = \"name\"\ndecorated = [(dict_[sort_on], dict_) for dict_ in py]\ndecorated.sort()\nresult = [dict_ for (key, dict_) in decorated]\n >>> result\n[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]\n"
},
{
"answer_id": 23102554,
"author": "Shank_Transformer",
"author_id": 2819862,
"author_profile": "https://Stackoverflow.com/users/2819862",
"pm_score": 4,
"selected": false,
"text": "D sorted D = {'eggs': 3, 'ham': 1, 'spam': 2}\ndef get_count(tuple):\n return tuple[1]\n\nsorted(D.items(), key = get_count, reverse=True)\n# Or\nsorted(D.items(), key = lambda x: x[1], reverse=True) # Avoiding get_count function call\n"
},
{
"answer_id": 28094888,
"author": "vvladymyrov",
"author_id": 1296661,
"author_profile": "https://Stackoverflow.com/users/1296661",
"pm_score": 4,
"selected": false,
"text": "def sort_key_func(item):\n \"\"\" Helper function used to sort list of dicts\n\n :param item: dict\n :return: sorted list of tuples (k, v)\n \"\"\"\n pairs = []\n for k, v in item.items():\n pairs.append((k, v))\n return sorted(pairs)\nsorted(A, key=sort_key_func)\n"
},
{
"answer_id": 39281050,
"author": "abby sobh",
"author_id": 3135363,
"author_profile": "https://Stackoverflow.com/users/3135363",
"pm_score": 4,
"selected": false,
"text": "import pandas as pd\n\nlistOfDicts = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\ndf = pd.DataFrame(listOfDicts)\ndf = df.sort_values('name')\nsorted_listOfDicts = df.T.to_dict().values()\n setup_large = \"listOfDicts = [];\\\n[listOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10})) for _ in range(50000)];\\\nfrom operator import itemgetter;import pandas as pd;\\\ndf = pd.DataFrame(listOfDicts);\"\n\nsetup_small = \"listOfDicts = [];\\\nlistOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}));\\\nfrom operator import itemgetter;import pandas as pd;\\\ndf = pd.DataFrame(listOfDicts);\"\n\nmethod1 = \"newlist = sorted(listOfDicts, key=lambda k: k['name'])\"\nmethod2 = \"newlist = sorted(listOfDicts, key=itemgetter('name')) \"\nmethod3 = \"df = df.sort_values('name');\\\nsorted_listOfDicts = df.T.to_dict().values()\"\n\nimport timeit\nt = timeit.Timer(method1, setup_small)\nprint('Small Method LC: ' + str(t.timeit(100)))\nt = timeit.Timer(method2, setup_small)\nprint('Small Method LC2: ' + str(t.timeit(100)))\nt = timeit.Timer(method3, setup_small)\nprint('Small Method Pandas: ' + str(t.timeit(100)))\n\nt = timeit.Timer(method1, setup_large)\nprint('Large Method LC: ' + str(t.timeit(100)))\nt = timeit.Timer(method2, setup_large)\nprint('Large Method LC2: ' + str(t.timeit(100)))\nt = timeit.Timer(method3, setup_large)\nprint('Large Method Pandas: ' + str(t.timeit(1)))\n\n#Small Method LC: 0.000163078308105\n#Small Method LC2: 0.000134944915771\n#Small Method Pandas: 0.0712950229645\n#Large Method LC: 0.0321750640869\n#Large Method LC2: 0.0206089019775\n#Large Method Pandas: 5.81405615807\n"
},
{
"answer_id": 42855105,
"author": "forzagreen",
"author_id": 3495031,
"author_profile": "https://Stackoverflow.com/users/3495031",
"pm_score": 6,
"selected": false,
"text": "a = [{'name':'Homer', 'age':39}, ...]\n\n# This changes the list a\na.sort(key=lambda k : k['name'])\n\n# This returns a new list (a is not modified)\nsorted(a, key=lambda k : k['name']) \n"
},
{
"answer_id": 45094029,
"author": "uingtea",
"author_id": 4082344,
"author_profile": "https://Stackoverflow.com/users/4082344",
"pm_score": 4,
"selected": false,
"text": "lower() lists = [{'name':'Homer', 'age':39},\n {'name':'Bart', 'age':10},\n {'name':'abby', 'age':9}]\n\nlists = sorted(lists, key=lambda k: k['name'])\nprint(lists)\n# [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]\n\nlists = sorted(lists, key=lambda k: k['name'].lower())\nprint(lists)\n# [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]\n"
},
{
"answer_id": 47892332,
"author": "srikavineehari",
"author_id": 8709791,
"author_profile": "https://Stackoverflow.com/users/8709791",
"pm_score": 4,
"selected": false,
"text": "list dictionaries sort() def get_name(d):\n \"\"\" Return the value of a key in a dictionary. \"\"\"\n\n return d[\"name\"]\n list data_one = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\n data_one.sort(key=get_name)\n list sorted() list list data_two = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\nnew_data = sorted(data_two, key=get_name)\n data_one new_data >>> print(data_one)\n[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]\n>>> print(new_data)\n[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]\n"
},
{
"answer_id": 58179903,
"author": "Bejür",
"author_id": 7933218,
"author_profile": "https://Stackoverflow.com/users/7933218",
"pm_score": 4,
"selected": false,
"text": "sorted_list = sorted(list_to_sort, key= lambda x: x['name'])\n# Returns list of values\n list_to_sort.sort(key=operator.itemgetter('name'))\n# Edits the list, and does not return a new list\n # First option\npython3.6 -m timeit -s \"list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]\" -s \"sorted_l=[]\" \"sorted_l = sorted(list_to_sort, key=lambda e: e['name'])\"\n # Second option\npython3.6 -m timeit -s \"list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]\" -s \"sorted_l=[]\" -s \"import operator\" \"list_to_sort.sort(key=operator.itemgetter('name'))\"\n"
},
{
"answer_id": 59802559,
"author": "swac",
"author_id": 10452855,
"author_profile": "https://Stackoverflow.com/users/10452855",
"pm_score": 3,
"selected": false,
"text": "operator.itemgetter lambda itemgetter lambda lambda itemgetter import random\nimport operator\n\n# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.\nl = [{'name': ''.join(random.choices(string.ascii_lowercase, k=8)), 'age': random.randint(0, 100)} for i in range(100)]\n\n# Test the performance with a lambda function sorting on name\n%timeit sorted(l, key=lambda x: x['name'])\n13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n# Test the performance with itemgetter sorting on name\n%timeit sorted(l, key=operator.itemgetter('name'))\n10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n# Check that each technique produces the same sort order\nsorted(l, key=lambda x: x['name']) == sorted(l, key=operator.itemgetter('name'))\nTrue\n"
},
{
"answer_id": 69072597,
"author": "Tms91",
"author_id": 7658051,
"author_profile": "https://Stackoverflow.com/users/7658051",
"pm_score": 1,
"selected": false,
"text": "list_to_be_sorted = [\n {'name':'Homer', 'age':39}, \n {'name':'Milhouse', 'age':10}, \n {'name':'Bart', 'age':10} \n ]\n 'age' 'name' ORDER BY age, name newlist = sorted( list_to_be_sorted, key=lambda k: (k['age'], k['name']) )\n import operator\nnewlist = sorted( list_to_be_sorted, key=operator.itemgetter('age','name') )\n print(newlist)"
},
{
"answer_id": 72939809,
"author": "alex",
"author_id": 4444742,
"author_profile": "https://Stackoverflow.com/users/4444742",
"pm_score": 0,
"selected": false,
"text": "def cmpfun(a, b):\n for (name, inv) in cmps:\n res = cmp(a[name], b[name])\n if res != 0:\n return res * inv\n return 0\n\ndata = [\n dict(name='alice', age=10), \n dict(name='baruch', age=9), \n dict(name='alice', age=11),\n]\n\nall_cmps = [\n [('name', 1), ('age', -1)], \n [('name', 1), ('age', 1)], \n [('name', -1), ('age', 1)],]\n\nprint 'data:', data\nfor cmps in all_cmps: print 'sort:', cmps; print sorted(data, cmpfun)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12398/"
] |
72,913 |
<p>If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?</p>
|
[
{
"answer_id": 72963,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 1,
"selected": false,
"text": "Func<IEnumerator, object> f = ie => { ie.MoveNext(); return ie.Current; };\n"
},
{
"answer_id": 73007,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 3,
"selected": true,
"text": "e => e.MoveNext() ? e.Current : null\n"
},
{
"answer_id": 73041,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 0,
"selected": false,
"text": "List<string> strings = new List<string>()\n{\n \"Hello\", \"I\", \"am\", \"a\", \"list\", \"of\", \"strings.\"\n};\nIEnumerator<string> e = strings.GetEnumerator();\nFunc<string> f = () => e.MoveNext() ? e.Current : null;\nfor (; ; )\n{\n string str = f();\n if (str == null)\n break;\n\n Console.Write(str + \" \");\n}\n IEnumerator foreach (string str in strings)\n Console.Write(str + \" \");\n while (e.MoveNext())\n Console.Write(e.Current + \" \");\n"
},
{
"answer_id": 73058,
"author": "Nathan Baulch",
"author_id": 8799,
"author_profile": "https://Stackoverflow.com/users/8799",
"pm_score": 0,
"selected": false,
"text": "var iter = ((IEnumerable<char>)\"hello\").GetEnumerator();\n\n//with closure\n{\n Func<object> f =\n () =>\n {\n iter.MoveNext();\n return iter.Current;\n };\n Console.WriteLine(f());\n Console.WriteLine(f());\n}\n\n//without closure\n{\n Func<IEnumerator, object> f =\n ie =>\n {\n ie.MoveNext();\n return ie.Current;\n };\n Console.WriteLine(f(iter));\n Console.WriteLine(f(iter));\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
72,921 |
<p>I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem.</p>
<p>I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. <a href="https://stackoverflow.com/users/4465/levik">Internet Duct Tape's Greasemonkey tools, like Comment Ninja</a>, are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth.</p>
<p>I just want to be able to select a bunch of text on the comments page and click a bookmarklet (<a href="https://stackoverflow.com/users/8119/jacob">http://bookmarklets.com</a>) in Firefox that pops up a window listing all the IP addresses found in the selection.</p>
<p><strong>Update:</strong></p>
<p>I kind of combined a the answers from <a href="https://stackoverflow.com/users/4465/levik">levik</a> and <a href="https://stackoverflow.com/users/8119/jacob">Jacob</a> to come up with this:</p>
<pre><code>javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("<br>");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses)
</code></pre>
<p>The difference is that instead of an <em>alert</em> message, as in levik's answer, I open a new window similar to Jacob's answer. The <em>alert</em> doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a <em><br></em> for the join instead of levik's <em>\n</em>. </p>
<p>Thanks for all the help, guys.</p>
|
[
{
"answer_id": 73031,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 1,
"selected": false,
"text": "/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/\n/^([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+\\.([1-9][0-9]{0,2})+$/\n"
},
{
"answer_id": 73723,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 3,
"selected": true,
"text": "javascript:alert(\n document.getSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g)\n .join(\"\\n\"))\n"
},
{
"answer_id": 74377,
"author": "Jacob",
"author_id": 8119,
"author_profile": "https://Stackoverflow.com/users/8119",
"pm_score": 1,
"selected": false,
"text": "javascript:document.write(document.getSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g))\n CmdUtils.CreateCommand({\n name: \"findip\",\n preview: function( pblock ) {\n var msg = 'IP Addresses Found<br/><br/> ';\n ips = CmdUtils.getHtmlSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g);\n if(ips){\n msg += ips.join(\"<br/>\\n\");\n }else{\n msg += 'None';\n }\n pblock.innerHTML = msg;\n },\n\n execute: function() {\n ips = CmdUtils.getHtmlSelection().match(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/g);\n if(ips){\n CmdUtils.setSelection(ips.join(\"<br/>\\n\"));\n }\n }\n})\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12419/"
] |
72,931 |
<p>C++ just sucks too much of my time by making me micro-manage my own memory, making me type far too much (hello <code>std::vector<Thingy>::const_iterator it = lotsOfThingys.begin()</code>), and boring me with long compile times. What's the single best alternative for serious real-time graphics programming? Garbage collection is a must (as is the ability to avoid its use when necessary), and speed must be competitive with C++. A reasonable story for accessing C libs is also a must.</p>
<p>(Full disclosure: I have my own answer to this, but I'm interested to see what others have found to be good alternatives to C++ for real-time graphics work.)</p>
<p><strong>Edit:</strong> Thanks everyone for the thoughtful replies. Given that there's really no "right" answer to this question I won't be selecting any particular answer. Besides I'd just pick the language I happen to like as a C++ alternative, which wouldn't really be fair.</p>
|
[
{
"answer_id": 75555,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 4,
"selected": false,
"text": "std::vector::const_iterator it = lotsOfThingys.begin()) \nusing namespace std;\ntypedef vector::const_iterator ThingyConstIter;\n"
},
{
"answer_id": 75756,
"author": "Markowitch",
"author_id": 11964,
"author_profile": "https://Stackoverflow.com/users/11964",
"pm_score": 0,
"selected": false,
"text": "typedef std::vector<Thingy> Thingys;\nThingys::const_iterator it = lotsOfThingys.begin()\n"
},
{
"answer_id": 75838,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 4,
"selected": false,
"text": "BOOST_FOREACH( Thingy& t, lostOfThingys ) {\n // do something with 't'\n}\n"
},
{
"answer_id": 81496,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 4,
"selected": false,
"text": "auto it = lotsOfThingys.begin(); // Let the compiler figure it out.\nauto it2 = lotsOfFoos.begin();\nif (it==it2) // It's still strongly typed; a Thingy iter is not a Foo iter.\n"
},
{
"answer_id": 125586,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "canvas"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9631/"
] |
72,945 |
<p>Using Django's built in models, how would one create a triple-join between three models.</p>
<p>For example:</p>
<ul>
<li>Users, Roles, and Events are the models.</li>
<li>Users have many Roles, and Roles many Users. (ManyToMany)</li>
<li>Events have many Users, and Users many Events. (ManyToMany)</li>
<li>But for any given Event, any User may have only one Role.</li>
</ul>
<p>How can this be represented in the model?</p>
|
[
{
"answer_id": 73153,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 2,
"selected": false,
"text": "class Assignment(Model):\n user = ForeignKey(User)\n role = ForeignKey(Role)\n event = ForeignKey(Event)\n user.assignment_set.filter(role__name=\"Chaperon\")\nrole.assignment_set.filter(event__name=\"Silly Walkathon\")\n"
},
{
"answer_id": 76221,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 0,
"selected": false,
"text": "class User(models.Model):\n ...\n\nclass Event(models.Model):\n ...\n\nclass Role(models.Model):\n user = models.ForeignKey(User)\n event = models.ForeignKey(Event)\n"
},
{
"answer_id": 77898,
"author": "zuber",
"author_id": 9812,
"author_profile": "https://Stackoverflow.com/users/9812",
"pm_score": 5,
"selected": true,
"text": "class User(models.Model):\n name = models.CharField(max_length=128)\n\nclass Event(models.Model):\n name = models.CharField(max_length=128)\n members = models.ManyToManyField(User, through='Role')\n\n def __unicode__(self):\n return self.name\n\nclass Role(models.Model):\n person = models.ForeignKey(User)\n group = models.ForeignKey(Event)\n date_joined = models.DateField()\n invite_reason = models.CharField(max_length=64)\n"
},
{
"answer_id": 16290256,
"author": "Brent Washburne",
"author_id": 584846,
"author_profile": "https://Stackoverflow.com/users/584846",
"pm_score": 0,
"selected": false,
"text": "def event_users(event_name):\n return User.objects.filter(roles__events__name=event_name)\n SELECT `user`.`id`, `user`.`name` FROM `user` INNER JOIN `roles` ON (`user`.`id` = `roles`.`user_id`) INNER JOIN `event` ON (`roles`.`event_id` = `event`.`id`) WHERE `event`.`name` = \"event_name\"\n SELECT `user`.`id`, `user`.`name` FROM `user`, `roles`, `event` WHERE `user`.`id` = `roles`.`user_id` AND `roles`.`event_id` = `event`.`id` AND `event`.`name` = \"event_name\"\n from django.db import connection\ndef event_users(event_name):\n cursor = connection.cursor()\n cursor.execute('select U.name from user U, roles R, event E' \\\n ' where U.id=R.user_id and R.event_id=E.id and E.name=\"%s\"' % event_name)\n return [row[0] for row in cursor.fetchall()]\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8507/"
] |
72,958 |
<p>I am trying to program a small server+client in Javascript on Firefox, using XPCOM.</p>
<p>To get the HTTP message in Javascript, I am using the nsIScriptableInputStream interface.
This f**ing component through the read() method randomly cut the message and I cannot make it reliable.</p>
<p>Is anybody know a solution to get reliably the information? (I already tried a binary stream, same failure.)</p>
<p>J.</p>
|
[
{
"answer_id": 73939,
"author": "Chouser",
"author_id": 7624,
"author_profile": "https://Stackoverflow.com/users/7624",
"pm_score": 0,
"selected": false,
"text": "receiveMsg({type:\"text\", content:\"this is my message\"});\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
72,961 |
<p>So our SQL Server 2000 is giving me the error, "The log file for database is full. Back up the transaction log for the database to free up some log space."</p>
<p>How do I go about fixing this without deleting the log like some other sites have mentioned?</p>
<p>Additional Info: Enable AutoGrowth is enabled growing by 10% and is restricted to 40MB.</p>
|
[
{
"answer_id": 73074,
"author": "TrevorD",
"author_id": 12492,
"author_profile": "https://Stackoverflow.com/users/12492",
"pm_score": 4,
"selected": false,
"text": "backup log <dbname> with truncate_only \n backup log <dbname> to disk='c:\\somefile.bak'\n"
},
{
"answer_id": 73136,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "dump tran <db_name> with no_log;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2863/"
] |
72,994 |
<p>I want to simulate a 'Web 2.0' Lightbox style UI technique in a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> application. That is, to draw attention to some foreground control by 'dimming' all other content in the client area of a window. </p>
<p>The obvious solution is to create a control that is simply a partially transparent rectangle that can be docked to the client area of a window and brought to the front of the Z-Order. It needs to act like a dirty pain of glass through which the other controls can still be seen (and therefore continue to paint themselves). Is this possible? </p>
<p>I've had a good hunt round and tried a few techniques myself but thus far have been unsuccessful.
If it is not possible, what would be another way to do it?</p>
<p>See: <a href="http://www.useit.com/alertbox/application-design.html" rel="noreferrer">http://www.useit.com/alertbox/application-design.html</a> (under the Lightbox section for a screenshot to illustrate what I mean.)</p>
|
[
{
"answer_id": 73062,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "Opacity"
},
{
"answer_id": 73065,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "MyLightboxAwareForm LightboxEvent LightboxManager MyLightboxAwareForm Show Lightbox LightboxManager LightboxShown MyLightboxAwareForm"
},
{
"answer_id": 73191,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 4,
"selected": false,
"text": "public class DarkenArea : Form\n{\n public DarkenArea()\n {\n FormBorderStyle = FormBorderStyle.None;\n SizeGripStyle = SizeGripStyle.Hide;\n StartPosition = FormStartPosition.Manual;\n MaximizeBox = false;\n MinimizeBox = false;\n ShowInTaskbar = false;\n BackColor = Color.Magenta;\n TransparencyKey = Color.Magenta;\n Opacity = 0.5f;\n }\n}\n public void ShowWithoutActivate()\n{\n // Show the window without activating it (i.e. do not take focus)\n PlatformInvoke.ShowWindow(this.Handle, (short)SW_SHOWNOACTIVATE);\n}\n protected override void OnPaint(PaintEventArgs e)\n{\n base.OnPaint(e);\n // Do your painting here be exclude the area you want to be brighter\n}\n protected override void WndProc(ref Message m)\n{\n if (m.Msg == (int)WM_NCHITTEST)\n m.Result = (IntPtr)HTTRANSPARENT;\n else\n base.WndProc(ref m);\n}\n"
},
{
"answer_id": 169855,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 3,
"selected": false,
"text": "public Rectangle ControlBounds { get; set; }\nprivate void LBform_Load(object sender, EventArgs e)\n{\n Bitmap background = new Bitmap(this.Width, this.Height);\n Graphics g = Graphics.FromImage(background);\n g.FillRectangle(Brushes.Fuchsia, this.ControlBounds);\n\n g.Flush();\n\n this.BackgroundImage = background;\n this.Invalidate();\n}\n private void button1_Click(object sender, EventArgs e)\n{\n // setup user control:\n UserControl1 uc1 = new UserControl1();\n uc1.Left = (this.Width - uc1.Width) / 2;\n uc1.Top = (this.Height - uc1.Height) / 2;\n this.Controls.Add(uc1);\n uc1.BringToFront();\n\n // load the lightbox form:\n LBform lbform = new LBform();\n lbform.SetBounds(this.Left + 8, this.Top + 30, this.ClientRectangle.Width, this.ClientRectangle.Height);\n lbform.ControlBounds = uc1.Bounds;\n\n lbform.Owner = this;\n lbform.Show();\n}\n"
},
{
"answer_id": 5757080,
"author": "Gad",
"author_id": 25152,
"author_profile": "https://Stackoverflow.com/users/25152",
"pm_score": 1,
"selected": false,
"text": "public partial class Frame : UserControl\n{\n private Panel shadow = new Panel();\n private static float LIGHTBOX_OPACITY = 0.3f;\n\n public Frame()\n {\n InitializeComponent(); \n shadow.Dock = DockStyle.Fill;\n }\n\n public void ShowLightbox()\n {\n Bitmap bmp = new Bitmap(this.Width, this.Height);\n this.pnlContainer.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));\n shadow.BackgroundImage = SetImgOpacity(bmp, LIGHTBOX_OPACITY );\n this.Controls.Add(shadow);\n shadow.BringToFront();\n }\n\n // http://www.geekpedia.com/code110_Set-Image-Opacity-Using-Csharp.html\n private Image SetImgOpacity(Image imgPic, float imgOpac)\n {\n Bitmap bmpPic = new Bitmap(imgPic.Width, imgPic.Height);\n Graphics gfxPic = Graphics.FromImage(bmpPic);\n ColorMatrix cmxPic = new ColorMatrix();\n cmxPic.Matrix33 = imgOpac;\n ImageAttributes iaPic = new ImageAttributes();\n iaPic.SetColorMatrix(cmxPic, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);\n gfxPic.DrawImage(imgPic, new Rectangle(0, 0, bmpPic.Width, bmpPic.Height), 0, 0, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, iaPic);\n gfxPic.Dispose();\n return bmpPic;\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6199/"
] |
72,996 |
<p>I am creating an installer in IzPack. It is quite large, and I have broken up my XML files appropriately using <xinclude> and <xfragment> tags. Unfortunately, IzPack does not combine them together when you build your installer. This requires you to package the files with the installer, which just won't work. </p>
<p>I was about to start writing a tool in Java to load the XML files and combine them, but I don't want to go reinventing the wheel. </p>
<p>Do the Java XML libraries provide native handling of xinclude? A google didn't seem to turn up much. </p>
<p>Not a big deal if I have to write this myself, just wanted to check with you guys. Thanks.</p>
<p>Format of XML for example purposes:
File1.xml</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<xinclude href="example/File2.xml" />
</pack>
</packs>
</code></pre>
<p>File2.xml</p>
<pre><code><xfragment>
<file src="..." />
</xfragment>
</code></pre>
<p>File2 does not need the standard XML header. The xml file is parsed at build time, because the resources it specifies are included in the installer. What isn't included is the actual XML information (order to write the files, where to put them etc.)</p>
<p>What I am looking to have produced:</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<file src="..." />
</pack>
</packs>
</code></pre>
<p>Thanks, I am going to start whipping it together in Java now, but hopefully someone has a simple answer. </p>
<p>Tim Reynolds</p>
|
[
{
"answer_id": 73306,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 0,
"selected": false,
"text": "<xinclude ....> <xi:xinclude xmlns:xi=\"http://www.w3.org/2001/XInclude\" href=\"example/File2.xml\" />\n"
},
{
"answer_id": 74275,
"author": "Brian Agnew",
"author_id": 12960,
"author_profile": "https://Stackoverflow.com/users/12960",
"pm_score": 1,
"selected": false,
"text": "<xmltask source=\"templatefile.xml\" dest=\"finalfile.xml\">\n <insert path=\"/packs/pack[1]\" position=\"under\" file=\"pack1.xml\"/>\n</xmltask>\n"
},
{
"answer_id": 534077,
"author": "mattwright",
"author_id": 33106,
"author_profile": "https://Stackoverflow.com/users/33106",
"pm_score": 0,
"selected": false,
"text": "import javax.xml.parsers.SAXParserFactory;\n\nSAXParserFactory spf = SAXParserFactory.newInstance();\nspf.setNamespaceAware(true);\nspf.setXIncludeAware(true);\n"
},
{
"answer_id": 1302238,
"author": "denny",
"author_id": 159557,
"author_profile": "https://Stackoverflow.com/users/159557",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"iso-8859-1\" standalone=\"yes\" ?>\n<installation version=\"1.0\">\n<packs> \n <pack name=\"Transaction Service\" id=\"Transaction Service\" required=\"no\" >\n <xi:include href=\"example/File2.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\" />\n </pack>\n</packs>\n <?xml version=\"1.0\" encoding=\"iso-8859-1\" standalone=\"yes\" ?>\n<xfragment>\n <file src=\"...\" />\n</xfragment>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/72996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
73,000 |
<p>I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds <strong>all</strong> IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they <em>see</em> dialog on top of IE but it looks like it has hanged since it is not refreshe). </p>
<p>So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice. </p>
<p>Here's the code:</p>
<pre><code> PassDialog dialog = new PassDialog(parent);
/* do some non gui related initialization */
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
</code></pre>
<p>Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was: </p>
<pre><code>parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet);
</code></pre>
|
[
{
"answer_id": 73214,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 0,
"selected": false,
"text": "function getPassword() {\n return prompt(\"Enter Password\");\n}\n password = jso.call(\"getPassword\", new String[0]);\n"
},
{
"answer_id": 73525,
"author": "James A. N. Stauffer",
"author_id": 6770,
"author_profile": "https://Stackoverflow.com/users/6770",
"pm_score": 1,
"selected": false,
"text": "class TestClass {\nprotected void toFrontTimer(JFrame frame) {\n try {\n bringToFrontTimer = new java.util.Timer();\n bringToFrontTask = new BringToFrontTask(frame);\n bringToFrontTimer.schedule( bringToFrontTask, 300, 300);\n } catch (Throwable t) {\n t.printStackTrace();\n }\n}\n\nclass BringToFrontTask extends TimerTask {\n private Frame frame;\n public BringToFrontTask(Frame frame) {\n this.frame = frame;\n }\n public void run()\n {\n if(count < 2) {\n frame.toFront();\n } else {\n cancel();\n }\n count ++;\n }\n private int count = 0;\n}\n\npublic void cleanup() {\n if(bringToFrontTask != null) {\n bringToFrontTask.cancel();\n bringToFrontTask = null;\n }\n if(bringToFrontTimer != null) {\n bringToFrontTimer = null;\n }\n}\n\njava.util.Timer bringToFrontTimer = null;\njava.util.TimerTask bringToFrontTask = null;\n}\n"
},
{
"answer_id": 93914,
"author": "shemnon",
"author_id": 8020,
"author_profile": "https://Stackoverflow.com/users/8020",
"pm_score": 2,
"selected": true,
"text": "javax.swing.SwingUtilities.getWindowAncestor(theApplet)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7918/"
] |
73,022 |
<p>What is the difference between <strong>CodeFile</strong>="file.ascx.cs" and <strong>CodeBehind</strong>="file.ascx.cs" in the declaration of a ASP.NET user control?</p>
<p>Is one newer or recommended? Or do they have specific usage?</p>
|
[
{
"answer_id": 17006133,
"author": "DavidHyogo",
"author_id": 341180,
"author_profile": "https://Stackoverflow.com/users/341180",
"pm_score": 3,
"selected": false,
"text": "CodeFile=login.aspx.cs\n CodeBehind=login.aspx.cs\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] |
73,024 |
<p>This is from an example accompanying the agsXMPP .Net assembly. I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message. I guess what I'm looking for is an understanding of why <code>delegate(0)</code> accomplishes this, in the kind of simple terms I can understand.</p>
<pre><code>xmpp.OnLogin += delegate(object o) {
xmpp.Send(new Message(new Jid(JID_RECEIVER),
MessageType.chat,
"Hello, how are you?"));
};
</code></pre>
|
[
{
"answer_id": 73066,
"author": "André Chalella",
"author_id": 4850,
"author_profile": "https://Stackoverflow.com/users/4850",
"pm_score": 0,
"selected": false,
"text": "onLogin"
},
{
"answer_id": 73069,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 2,
"selected": false,
"text": "xmpp.OnLogin += EventHandler(MyMethod);\n public void MyMethod(object o) \n{ \n xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, \"Hello, how are you?\")); \n}\n"
},
{
"answer_id": 73083,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 2,
"selected": true,
"text": "delegate(object o){..} OnLogin delegate()"
},
{
"answer_id": 73092,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 0,
"selected": false,
"text": "delegate(object o) { statements; }\n public class MyClass\n{\n private XMPPObjectType xmpp;\n public void Main()\n {\n xmpp.OnLogin += MyMethod;\n }\n private void MyMethod(object o)\n {\n xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, \"Hello, how are you?\"));\n }\n}\n"
},
{
"answer_id": 73103,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": " // Check to see if we should fire the login event\n // ALso check to see if anything is subscribed to OnLogin \n // (It will be null otherwise)\n if (loggedIn && OnLogin != null)\n {\n // Anyone subscribed will now receive the event.\n OnLogin(this);\n }\n"
},
{
"answer_id": 73137,
"author": "Remi Despres-Smyth",
"author_id": 8169,
"author_profile": "https://Stackoverflow.com/users/8169",
"pm_score": 2,
"selected": false,
"text": "\nxmpp.OnLogin += delegate(object o) \n { \n xmpp.Send(\n new Message(new Jid(JID_RECEIVER), MessageType.chat, \"Hello, how are you?\")); \n };\n \ndelegate void OnLoginEventHandler(object o);\n\npublic void MyLoginEventHandler(object o)\n{\n xmpp.Send(\n new Message(new Jid(JID_RECEIVER), MessageType.chat, \"Hello, how are you?\")); \n}\n\n[...]\n\nxmpp.OnLogin += new OnLoginEventHandler(MyLoginEventHandler);\n"
},
{
"answer_id": 73254,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 2,
"selected": false,
"text": "OnLogin public event LoginEventHandler OnLogin;\n LoginEventHandler public delegate void LoginEventHandler(Object o);\n LoginEventHandler delegate xmpp.OnLogin += delegate(object o)\n { \n xmpp.Send(new Message(new Jid(JID_RECEIVER), \n MessageType.chat,\n \"Hello, how are you?\")); \n };\n OnLogin object o xmpp.OnLogin += delegate\n { \n xmpp.Send(new Message(new Jid(JID_RECEIVER), \n MessageType.chat,\n \"Hello, how are you?\")); \n };\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7574/"
] |
73,029 |
<p>I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project.</p>
<p>That's why I need to serve servlets and html (login.html) under the same context
to make authentication work. I don't want to secure the hole application since
different context should need different roles. The jetty javadoc states that a
ContextHandlerCollection can handle different handlers for one context but I don't
get it to work. My sample ignoring the authentication stuff will not work, why?</p>
<pre><code>ContextHandlerCollection contexts = new ContextHandlerCollection();
// serve html
Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS);
ctxADocs.setResourceBase("d:\\tmp\\ctxA");
ServletHolder ctxADocHolder= new ServletHolder();
ctxADocHolder.setInitParameter("dirAllowed", "false");
ctxADocHolder.setServlet(new DefaultServlet());
ctxADocs.addServlet(ctxADocHolder, "/");
// serve a sample servlet
Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS);
ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda");
ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/");
contexts.setHandlers(new Handler[]{ctxA, ctxADocs});
// end of snippet
</code></pre>
<p>Any helpful thought is welcome!</p>
<p>Thanks.</p>
<p>Okami</p>
|
[
{
"answer_id": 91072,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 1,
"selected": false,
"text": "<login-config>\n <auth-method>BASIC</auth-method>\n</login-config>\n<security-role>\n <role-name>MySiteRole</role-name>\n</security-role>\n\n<security-constraint>\n <display-name>ProtectEverything</display-name>\n <web-resource-collection>\n <web-resource-name>ProtectEverything</web-resource-name>\n <url-pattern>*.*</url-pattern>\n <url-pattern>/*</url-pattern>\n </web-resource-collection>\n <auth-constraint>\n <role-name>MySiteRole</role-name>\n </auth-constraint>\n</security-constraint>\n\n<security-constraint>\n <web-resource-collection>\n <web-resource-name>ExcludeLoginPage</web-resource-name>\n <url-pattern>/login.html</url-pattern>\n </web-resource-collection>\n <user-data-constraint>\n <transport-guarantee>NONE</transport-guarantee>\n </user-data-constraint>\n</security-constraint>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11450/"
] |
73,032 |
<p>I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.</p>
<p>I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example:</p>
<pre><code>ordered_list = [[1, 2], [1, 1], [2, 1]]
</code></pre>
<p>Any suggestions?</p>
<p>Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like:</p>
<pre><code>ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
</code></pre>
|
[
{
"answer_id": 73090,
"author": "Brian Phillips",
"author_id": 7230,
"author_profile": "https://Stackoverflow.com/users/7230",
"pm_score": 6,
"selected": true,
"text": "\nordered_list = [[1, \"b\"], [1, \"a\"], [2, \"a\"]]\nordered_list.sort! do |a,b|\n [a[0],b[1]] <=> [b[0], a[1]]\nend\n"
},
{
"answer_id": 73496,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 2,
"selected": false,
"text": "class Inverter\n attr_reader :o\n\n def initialize(o)\n @o = o\n end\n\n def <=>(other)\n if @o.is && other.o.is\n -(@o <=> other.o)\n else\n @o <=> other.o\n end\n end\nend\n your_objects.sort_by {|y| [y.prop1,Inverter.new(y.prop2)]}\n"
},
{
"answer_id": 76148,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 2,
"selected": false,
"text": "Enumerable#multisort items = [\n [3, \"Britney\"],\n [1, \"Corin\"],\n [2, \"Cody\"],\n [5, \"Adam\"],\n [1, \"Sally\"],\n [2, \"Zack\"],\n [5, \"Betty\"]\n]\n\nmodule Enumerable\n def multisort(*args)\n sort do |a, b|\n i, res = -1, 0\n res = a[i] <=> b[i] until !res.zero? or (i+=1) == a.size\n args[i] == false ? -res : res\n end\n end\nend\n\nitems.multisort(true, false)\n# => [[1, \"Sally\"], [1, \"Corin\"], [2, \"Zack\"], [2, \"Cody\"], [3, \"Britney\"], [5, \"Betty\"], [5, \"Adam\"]]\nitems.multisort(false, true)\n# => [[5, \"Adam\"], [5, \"Betty\"], [3, \"Britney\"], [2, \"Cody\"], [2, \"Zack\"], [1, \"Corin\"], [1, \"Sally\"]]\n"
},
{
"answer_id": 11320778,
"author": "TwoByteHero",
"author_id": 1311787,
"author_profile": "https://Stackoverflow.com/users/1311787",
"pm_score": 3,
"selected": false,
"text": "{|a,b| a.blah <=> b.blah} sort_by! sort_by sort! sort a b <=> something.sort!{|a,b| [a.blah, b.bleu, a.craw] <=> [b.blah, a.bleu, b.craw]}\n - sort_by sort_by! a.craw something.sort_by!{|a| [a.blah, -a.craw, a.bleu]}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3230/"
] |
73,037 |
<p>This is a 3 part question regarding embedded RegEx into SQL statements. </p>
<ol>
<li><p>How do you embed a RegEx expression into an Oracle PL/SQL
select statement that will parse out
the “DELINQUENT” string in the text
string shown below?</p></li>
<li><p>What is the performance impact if used within a
mission critical business
transaction?</p></li>
<li><p>Since embedding regex
into SQL was introduced in Oracle
10g and SQL Server 2005, is it
considered a recommended practice?</p></li>
</ol>
<hr>
<p>Dear Larry :</p>
<p>Thank you for using ABC's alert service.</p>
<p>ABC has detected a change in the status of one of your products in the state of KS. Please review the
information below to determine if this status change was intended.</p>
<p>ENTITY NAME: Oracle Systems, LLC</p>
<p>PREVIOUS STATUS: --</p>
<p>CURRENT STATUS: DELINQUENT</p>
<p>As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating
the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC
so that we can discontinue our services.</p>
<p>Kind regards,</p>
<p>Service Team 1
ABC</p>
<p>--PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.--</p>
<p>Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information
maintained by the responsible government agency or other sources of data upon which these alerts are based.</p>
|
[
{
"answer_id": 78318,
"author": "Sergey Stadnik",
"author_id": 10557,
"author_profile": "https://Stackoverflow.com/users/10557",
"pm_score": 2,
"selected": true,
"text": "SELECT emp_id, text\n FROM employee_comment\n WHERE REGEXP_LIKE(text,'...-....');\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048/"
] |
73,039 |
<p>In my web application there is a process that queries data from all over the web, filters it, and saves it to the database. As you can imagine this process takes some time. My current solution is to increase the page timeout and give an AJAX progress bar to the user while it loads. This is a problem for two reasons - 1) it still takes to long and the user must wait 2) it sometimes still times out.</p>
<p>I've dabbled in threading the process and have read I should async post it to a web service ("Fire and forget").</p>
<p>Some references I've read:<br>
- <a href="http://msdn.microsoft.com/en-us/library/ms978607.aspx#diforwc-ap02_plag_howtomultithread" rel="nofollow noreferrer">MSDN</a><br>
- <a href="http://aspalliance.com/329" rel="nofollow noreferrer">Fire and Forget</a></p>
<p>So my question is - what is the best method?</p>
<p>UPDATE: After the user inputs their data I would like to redirect them to the results page that incrementally updates as the process is running in the background.</p>
|
[
{
"answer_id": 73428,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 4,
"selected": true,
"text": "document.location = \"LongRunningProcess.aspx?taskID=2\". \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12442/"
] |
73,045 |
<p>I'm not talking about how to indent here. I'm looking for suggestions about the best way of organizing the chunks of code in a source file.</p>
<p>Do you arrange methods alphabetically? In the order you wrote them? Thematically? In some kind of 'didactic' order?</p>
<p>What organizing principles do you follow? Why?</p>
|
[
{
"answer_id": 73089,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 0,
"selected": false,
"text": "//====(DE)CONSTRUCTOR====\n...\n//====LOAD FUNCTIONS====\n...\n//====SAVE FUNCTIONS====\n...\n//====RESOURCE MANGEMENT FUNCTIONS====\n//(preventing multiple copies being loaded etc)\n...\n//====UTILL FUNCTIONS====\n//getting texture details, etc\n...\n//====OVERLOADED OPERTORS====\n....\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/423836/"
] |
73,051 |
<p>I need to run a stored procedure from a C# application.</p>
<p>I use the following code to do so:</p>
<pre><code>Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();
</code></pre>
<p>From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).</p>
<p>How can I customize these return codes?</p>
<p>H.</p>
|
[
{
"answer_id": 73108,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "SqlConnection SqlCommand System.Data.SqlClient SqlCommand"
},
{
"answer_id": 73193,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 2,
"selected": false,
"text": " myprocess.Start()\n procReader = myprocess.StandardOutput()\n\n While (Not procReader.EndOfStream)\n procLine = procReader.ReadLine()\n\n If (MatchesRegEx(errRegEx, procLine)) Then\n writeDebug(\"Error reg ex: [\" + errorRegEx + \"] has matched: [\" + procLine + \"] setting hasError to true.\")\n\n Me.hasError = True\n End If\n\n writeLog(procLine)\n End While\n\n procReader.Close()\n\n myprocess.WaitForExit(CInt(waitTime))\n"
},
{
"answer_id": 77400,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "SqlCommand SqlConnection SqlCommand"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12525/"
] |
73,063 |
<p>In Visual Studio 2005-2015 it is possible to find all lines containing certain references and display them in a "Find Results" window.</p>
<p>Now that these result lines are displayed, is there any keyboard shortcut that would allow adding debug breakpoints to all of them?</p>
|
[
{
"answer_id": 249501,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 5,
"selected": true,
"text": "Imports System\nImports System.IO\nImports System.Text.RegularExpressions\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module CustomMacros\n Sub BreakpointFindResults()\n Dim findResultsWindow As Window = DTE.Windows.Item(Constants.vsWindowKindFindResults1)\n\n Dim selection As TextSelection\n selection = findResultsWindow.Selection\n selection.SelectAll()\n\n Dim findResultsReader As New StringReader(selection.Text)\n Dim findResult As String = findResultsReader.ReadLine()\n\n Dim findResultRegex As New Regex(\"(?<Path>.*?)\\((?<LineNumber>\\d+)\\):\")\n\n While Not findResult Is Nothing\n Dim findResultMatch As Match = findResultRegex.Match(findResult)\n\n If findResultMatch.Success Then\n Dim path As String = findResultMatch.Groups.Item(\"Path\").Value\n Dim lineNumber As Integer = Integer.Parse(findResultMatch.Groups.Item(\"LineNumber\").Value)\n\n Try\n DTE.Debugger.Breakpoints.Add(\"\", path, lineNumber)\n Catch ex As Exception\n ' breakpoints can't be added everywhere\n End Try\n End If\n\n findResult = findResultsReader.ReadLine()\n End While\n End Sub\nEnd Module\n"
},
{
"answer_id": 797454,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " Sub BreakPointAtString()\n\n Try\n DTE.ExecuteCommand(\"Debug.DisableAllBreakpoints\")\n Catch ex As Exception\n\n End Try\n\n Dim tsSelection As String = DTE.ActiveDocument.Selection.text\n DTE.ActiveDocument.Selection.selectall()\n Dim AllText As String = DTE.ActiveDocument.Selection.Text\n\n Dim findResultsReader As New StringReader(AllText)\n Dim findResult As String = findResultsReader.ReadLine()\n Dim lineNum As Integer = 1\n\n Do Until findResultsReader.Peek = -1\n lineNum += 1\n findResult = findResultsReader.ReadLine()\n If Trim(findResult) = Trim(tsSelection) Then\n DTE.ActiveDocument.Selection.GotoLine(lineNum)\n DTE.ExecuteCommand(\"Debug.ToggleBreakpoint\")\n End If\n Loop\n\nEnd Sub\n"
},
{
"answer_id": 1631799,
"author": "Dmytro",
"author_id": 194487,
"author_profile": "https://Stackoverflow.com/users/194487",
"pm_score": 1,
"selected": false,
"text": "Error\n---------------------------\nError HRESULT E_FAIL has been returned from a call to a COM component.\n---------------------------\nOK \n---------------------------\n Sub BreakPointsFromSearch()\n Dim n As Integer = InputBox(\"Enter the number of search results\")\n\n For i = 1 To n\n DTE.ExecuteCommand(\"Edit.GoToNextLocation\")\n DTE.ExecuteCommand(\"Debug.ToggleBreakpoint\") \n Next\nEnd Sub\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12113/"
] |
73,078 |
<p>I'm convinced from <a href="http://www.masukomi.org/talks/unit_testing_talk_2/index.xul?data=slide_data.txt#page2" rel="nofollow noreferrer">this presentation</a> and other commentary here on the site that I need to learn to Unit Test. I also realize that there have been many questions about what unit testing is here. Each time I go to consider how it should be done in the application I am currently working on, I walk away confused. It is a xulrunner application application, and a lot of the logic is event-based - when a user clicks here, this action takes place.</p>
<p>Often the examples I see for testing are testing classes - they instantiate an object, give it mock data, then check the properties of the object afterward. That makes sense to me - but what about the non-object-oriented pieces?</p>
<p><a href="https://stackoverflow.com/questions/2364/what-is-your-experience-with-unit-testing-in-practice#2390">This guy mentioned</a> that GUI-based unit testing is difficult in most any testing framework, maybe that's the problem. The presentation linked above mentions that each test should only touch one class, one method at a time. That seems to rule out what I'm trying to do.</p>
<p>So the question - how does one unit testing procedural or event-based code? Provide a link to good documentation, or explain it yourself.</p>
<p>On a side note, I also have a challenge of not having found a testing framework that is set up to test xulrunner apps - it seems that the tools just aren't developed yet. I imagine this is more peripheral than my understanding the concepts, writing testable code, applying unit testing.</p>
|
[
{
"answer_id": 73156,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 2,
"selected": false,
"text": "private bool fired;\n\nprivate void HandlesEvent(object sender, EventArgs e)\n{\n fired = true;\n } \n\npublic void Test()\n{\n class.FireEvent += HandlesEvent;\n class.PErformEventFiringAction(null, null);\n\n Assert.IsTrue(fired);\n}\n"
},
{
"answer_id": 386348,
"author": "Kjetil Klaussen",
"author_id": 15599,
"author_profile": "https://Stackoverflow.com/users/15599",
"pm_score": 1,
"selected": false,
"text": "// Arrange\nvar car = new Car();\nstring changedPropertyName = \"\";\ncar.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)\n {\n if (sender == car) \n changedPropertyName = e.PropertyName;\n };\n\n// Act\ncar.Model = \"Volvo\";\n\n// Assert \nAssert.AreEqual(\"Model\", changedPropertyName, \n \"The notification of a property change was not fired correctly.\");\n INotifyPropertyChanged NotifyPropertyChanged"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525/"
] |
73,086 |
<p>I've been trying to come up with a way to create a 3 column web design where the center column has a constant width and is always centered. The columns to the left and right are variable. This is trivial in tables, but not correct semantically. </p>
<p>I haven't been able to get this working properly in all current browsers. Any tips on this?</p>
|
[
{
"answer_id": 73145,
"author": "David Cumps",
"author_id": 4329,
"author_profile": "https://Stackoverflow.com/users/4329",
"pm_score": 1,
"selected": false,
"text": "#maincenter {\n width: 200px;\n float: left;\n background: #fff;\n padding-bottom: 10px;\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12529/"
] |
73,087 |
<p>Is there a standard X / Gnome program that will display the X,Y width and depth in pixels of a window that I select? Something similar to the way an xterm shows you the width and depth of the window (in lines) as you resize it.</p>
<p>I'm running on Red Hat Enterprise Linux 4.4.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 73221,
"author": "Linulin",
"author_id": 12481,
"author_profile": "https://Stackoverflow.com/users/12481",
"pm_score": 3,
"selected": false,
"text": "$ xwininfo \n\nxwininfo: Please select the window about which you\n would like information by clicking the\n mouse in that window.\n\nxwininfo: Window id: 0x1200007 \"xeyes\"\n\n Absolute upper-left X: 1130\n Absolute upper-left Y: 0\n Relative upper-left X: 0\n Relative upper-left Y: 0\n Width: 150\n Height: 100\n Depth: 24\n Visual Class: TrueColor\n Border width: 0\n Class: InputOutput\n Colormap: 0x20 (installed)\n Bit Gravity State: NorthWestGravity\n Window Gravity State: NorthWestGravity\n Backing Store State: NotUseful\n Save Under State: no\n Map State: IsViewable\n Override Redirect State: no\n Corners: +1130+0 -0+0 -0-924 +1130-924\n -geometry 150x100-0+0\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9648/"
] |
73,109 |
<p>I'm working with a fairly simple database, from a Java application. We're trying to insert about 200k of text at a time, using the standard JDBC mysql adapter. We intermittently get a <code>com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column error.</code></p>
<p>The column type is <code>longtext</code>, and database collation is <code>UTF-8</code>. The error shows up using both <code>MyISAM</code> and <code>InnoDB</code> table engines. Max packet size has been set ot 1 GB on both client and server sides, so that shouldn't be causing a problem, either.</p>
|
[
{
"answer_id": 73232,
"author": "Aaron",
"author_id": 11176,
"author_profile": "https://Stackoverflow.com/users/11176",
"pm_score": 2,
"selected": false,
"text": "foo.status = 'inactive'\n foo.state = 'inactive'\n"
},
{
"answer_id": 12914251,
"author": "grigson",
"author_id": 1051262,
"author_profile": "https://Stackoverflow.com/users/1051262",
"pm_score": 2,
"selected": false,
"text": "MEDIUMTEXT LONGTEXT"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
73,110 |
<p>For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.</p>
<p>This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)</p>
<hr/>
<p>Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.</p>
<hr/>
<p>@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.</p>
<hr/>
<p>@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.</p>
|
[
{
"answer_id": 73173,
"author": "André Chalella",
"author_id": 4850,
"author_profile": "https://Stackoverflow.com/users/4850",
"pm_score": 3,
"selected": false,
"text": "WordWrap == false"
},
{
"answer_id": 89428,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 5,
"selected": true,
"text": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class MyTextBox : TextBox {\n private bool mScrollbars;\n public MyTextBox() {\n this.Multiline = true;\n this.ReadOnly = true;\n }\n private void checkForScrollbars() {\n bool scroll = false;\n int cnt = this.Lines.Length;\n if (cnt > 1) {\n int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y;\n if (pos0 >= 32768) pos0 -= 65536;\n int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y;\n if (pos1 >= 32768) pos1 -= 65536;\n int h = pos1 - pos0;\n scroll = cnt * h > (this.ClientSize.Height - 6); // 6 = padding\n }\n if (scroll != mScrollbars) {\n mScrollbars = scroll;\n this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;\n }\n }\n\n protected override void OnTextChanged(EventArgs e) {\n checkForScrollbars();\n base.OnTextChanged(e);\n }\n\n protected override void OnClientSizeChanged(EventArgs e) {\n checkForScrollbars();\n base.OnClientSizeChanged(e);\n }\n}\n"
},
{
"answer_id": 4147348,
"author": "b8adamson",
"author_id": 215954,
"author_profile": "https://Stackoverflow.com/users/215954",
"pm_score": 2,
"selected": false,
"text": " public partial class MyTextBox : TextBox\n {\n private bool mShowScrollBar = false;\n\n public MyTextBox()\n {\n InitializeComponent();\n\n checkForScrollbars();\n }\n\n private void checkForScrollbars()\n {\n bool showScrollBar = false;\n int padding = (this.BorderStyle == BorderStyle.Fixed3D) ? 14 : 10;\n\n using (Graphics g = this.CreateGraphics())\n {\n // Calcualte the size of the text area.\n SizeF textArea = g.MeasureString(this.Text,\n this.Font,\n this.Bounds.Width - padding);\n\n if (this.Text.EndsWith(Environment.NewLine))\n {\n // Include the height of a trailing new line in the height calculation \n textArea.Height += g.MeasureString(\"A\", this.Font).Height;\n }\n\n // Show the vertical ScrollBar if the text area\n // is taller than the control.\n showScrollBar = (Math.Ceiling(textArea.Height) >= (this.Bounds.Height - padding));\n\n if (showScrollBar != mShowScrollBar)\n {\n mShowScrollBar = showScrollBar;\n this.ScrollBars = showScrollBar ? ScrollBars.Vertical : ScrollBars.None;\n }\n }\n }\n\n protected override void OnTextChanged(EventArgs e)\n {\n checkForScrollbars();\n base.OnTextChanged(e);\n }\n\n protected override void OnResize(EventArgs e)\n {\n checkForScrollbars();\n base.OnResize(e);\n }\n }\n"
},
{
"answer_id": 25197797,
"author": "Michael Csikos",
"author_id": 1484559,
"author_profile": "https://Stackoverflow.com/users/1484559",
"pm_score": 0,
"selected": false,
"text": "public class TextBoxAutoScroll : TextBox\n{\n public void AutoScrollVertically(bool recalculateOnResize = false)\n {\n SuspendLayout();\n\n if (recalculateOnResize)\n {\n Resize -= OnResize;\n Resize += OnResize;\n }\n\n float linesHeight = 0;\n var borderStyle = BorderStyle;\n\n BorderStyle = BorderStyle.None;\n\n int textHeight = PreferredHeight;\n\n try\n {\n using (var graphics = CreateGraphics())\n {\n foreach (var text in Lines)\n {\n var textArea = graphics.MeasureString(text, Font);\n\n if (textArea.Width < Width)\n linesHeight += textHeight;\n else\n {\n var numLines = (float)Math.Ceiling(textArea.Width / Width);\n\n linesHeight += textHeight * numLines;\n }\n }\n }\n\n if (linesHeight > Height)\n ScrollBars = ScrollBars.Vertical;\n else\n ScrollBars = ScrollBars.None;\n }\n catch (Exception ex)\n {\n System.Diagnostics.Debug.WriteLine(ex);\n }\n finally\n {\n BorderStyle = borderStyle;\n\n ResumeLayout();\n }\n }\n\n private void OnResize(object sender, EventArgs e)\n {\n m_timerResize.Stop();\n\n m_timerResize.Tick -= OnDelayedResize;\n m_timerResize.Tick += OnDelayedResize;\n m_timerResize.Interval = 475;\n\n m_timerResize.Start();\n }\n\n Timer m_timerResize = new Timer();\n\n private void OnDelayedResize(object sender, EventArgs e)\n {\n m_timerResize.Stop();\n\n Resize -= OnResize;\n\n AutoScrollVertically();\n\n Resize += OnResize;\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
] |
73,117 |
<p>I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself)</p>
<pre>
Basics:
Player has a time machine. On each iteration of using the time machine, a parallel state
is created, co-existing with a previous state. One of the states must complete all the
objectives of the level before ending the stage. In addition, all the stages must be able
to end the stage normally, without causing a state paradox (wherein they should have
been able to finish the stage normally but, due to the interactions of another state,
were not).
</pre>
<p>So, that sort of explains how the game works. You should play it a bit to really
understand what my problem is. <br /></p>
<p>I'm thinking a good way to solve this would be to use linked lists to store each state,
which will probably either be a hash map, based on time, or a linked list that iterates
based on time. I'm still unsure.<br /></p>
<p>ACTUAL QUESTION:</p>
<p>Now that I have some rough specs, I need some help deciding on which data structures to use for this, and why. Also, I want to know what Graphics API/Layer I should use to do this: SDL, OpenGL, or DirectX (my current choice is SDL). And how would I go about implementing parallel states? With parallel threads?</p>
<p>EDIT (To clarify more):<br />
OS -- Windows (since this is a hobby project, may do this in Linux later)<br />
Graphics -- 2D
Language -- C++ (must be C++ -- this is practice for a course next semester)</p>
<p>Q-Unanswered: SDL : OpenGL : Direct X <br />
Q-Answered: Avoid Parallel Processing <br />
Q-Answered: Use STL to implement time-step actions.<br /></p>
<pre>
So far from what people have said, I should:
1. Use STL to store actions.
2. Iterate through actions based on time-step.
3. Forget parallel processing -- period. (But I'd still like some pointers as to how it
could be used and in what cases it should be used, since this is for practice).
</pre>
<p>Appending to the question, I've mostly used C#, PHP, and Java before so I wouldn't describe myself as a hotshot programmer. What C++ specific knowledge would help make this project easier for me? (ie. Vectors?)</p>
|
[
{
"answer_id": 73537,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 4,
"selected": true,
"text": "std::list<std::list<std::pair<unsigned long, Action> > > state;\n state.back().push_back(std::make_pair(currentFrame, VK_LEFT | KEY_PRESSED));\n typedef std::list<std::pair<unsigned long, Action> > StateList;\nstd::list<StateList::iterator> stateIteratorList;\n//\nforeach(it in stateIteratorList)\n{\n if(it->first == currentFrame)\n {\n performAction(it->second);\n ++it;\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6128/"
] |
73,123 |
<p>Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404?</p>
<p>For example:</p>
<pre><code>http://mywebsite.com/132483
</code></pre>
<p>would be sent to:</p>
<pre><code>http://mywebsite.com/scriptname.php?no=132483
</code></pre>
<p>but</p>
<pre><code>http://mywebsite.com/132483a or
http://mywebsite.com/asdf
</code></pre>
<p>would be handled as a 404 error.</p>
<p>I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible.</p>
|
[
{
"answer_id": 73184,
"author": "Adam Hopkinson",
"author_id": 12280,
"author_profile": "https://Stackoverflow.com/users/12280",
"pm_score": 4,
"selected": false,
"text": "RewriteEngine On\nRewriteRule ^([0-9]{6})$ /scriptname.php?no=$1 [L]\n"
},
{
"answer_id": 73315,
"author": "daniels",
"author_id": 9789,
"author_profile": "https://Stackoverflow.com/users/9789",
"pm_score": 3,
"selected": true,
"text": "<IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L]\n</IfModule>\n http://mywebsite.com/132483\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12513/"
] |
73,134 |
<p>I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array <code>new</code> thus:</p>
<pre class="lang-cpp prettyprint-override"><code>STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];
</code></pre>
<p>Later on however the memory is freed using a <code>delete</code> call:</p>
<pre class="lang-cpp prettyprint-override"><code>delete pStruct;
</code></pre>
<p>Will this mix of array <code>new[]</code> and non-array <code>delete</code> cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use <code>malloc</code> and <code>free</code> instead?</p>
|
[
{
"answer_id": 73157,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 0,
"selected": false,
"text": "STRUCT* pStruct = new STRUCT;\n...\ndelete pStruct;\n"
},
{
"answer_id": 73163,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 5,
"selected": true,
"text": "STRUCT delete [] (BYTE*) pStruct;\n"
},
{
"answer_id": 73189,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 0,
"selected": false,
"text": "delete[] (BYTE*)pStruct;\n"
},
{
"answer_id": 73201,
"author": "slicedlime",
"author_id": 11230,
"author_profile": "https://Stackoverflow.com/users/11230",
"pm_score": 3,
"selected": false,
"text": "delete delete [] delete delete [] (BYTE*)(pStruct);\n"
},
{
"answer_id": 73225,
"author": "QBziZ",
"author_id": 11572,
"author_profile": "https://Stackoverflow.com/users/11572",
"pm_score": 0,
"selected": false,
"text": "BYTE * pBytes = new BYTE [sizeof(STRUCT) + nPaddingSize];\n\nSTRUCT* pStruct = reinterpret_cast< STRUCT* > ( pBytes ) ;\n\n // do stuff with pStruct\n\ndelete [] pBytes ;\n"
},
{
"answer_id": 73295,
"author": "Len Holgate",
"author_id": 7925,
"author_profile": "https://Stackoverflow.com/users/7925",
"pm_score": 3,
"selected": false,
"text": "new delete delete [] pStruct;\n malloc free delete [] reinterpret_cast<BYTE *>(pStruct);\n malloc free"
},
{
"answer_id": 73368,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "struct STRUCT\n{\n void *operator new (size_t)\n {\n return new char [sizeof(STRUCT) + nPaddingSize];\n }\n\n void operator delete (void *memory)\n {\n delete [] reinterpret_cast <char *> (memory);\n }\n};\n\nvoid main()\n{\n STRUCT *s = new STRUCT;\n delete s;\n}\n"
},
{
"answer_id": 73420,
"author": "ben",
"author_id": 4607,
"author_profile": "https://Stackoverflow.com/users/4607",
"pm_score": 2,
"selected": false,
"text": "delete-expression:\n ::opt delete cast-expression\n ::opt delete [ ] cast-expression\n delete pStruct char STRUCT*"
},
{
"answer_id": 73718,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 3,
"selected": false,
"text": "std::vector delete std::vector<BYTE> backing(sizeof(STRUCT) + nPaddingSize);\nSTRUCT* pStruct = (STRUCT*)(&backing[0]);\n pStruct boost::scoped_array<BYTE> backing(new BYTE[sizeof(STRUCT) + nPaddingSize]);\nSTRUCT* pStruct = (STRUCT*)backing.get();\n boost::shared_array"
},
{
"answer_id": 74170,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "new STRUCT* pStruct = operator new(sizeof(STRUCT) + nPaddingSize);\n"
},
{
"answer_id": 74236,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 2,
"selected": false,
"text": "new delete malloc free new delete STRUCT* pStruct = (STRUCT*)::operator new (sizeof(STRUCT) + nPaddingSize);\n// ...\npStruct->~STRUCT (); // Call STRUCT destructor\n::operator delete (pStruct);\n new BYTE * pByteData = new BYTE[sizeof(STRUCT) + nPaddingSize];\nSTRUCT * pStruct = new (pByteData) STRUCT ();\n// ...\npStruct->~STRUCT ();\ndelete[] pByteData;\n"
},
{
"answer_id": 74361,
"author": "Eric",
"author_id": 12937,
"author_profile": "https://Stackoverflow.com/users/12937",
"pm_score": 0,
"selected": false,
"text": "STRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize];\n sizeof(STRUCT) nPaddingSize"
},
{
"answer_id": 108454,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 2,
"selected": false,
"text": "MyObject* ObjPtr = new MyObject;\n\n//...\n\ndelete MyObject;\n operator new operator delete new void* MemoryPtr = ::operator new( sizeof(MyObject) );\nMyObject* ObjPtr = new (MemoryPtr) MyObject;\n\n// ...\n\nObjPtr->~MyObject();\n::operator delete( MemoryPtr );\n new char[N] char delete MyObject class MyObject\n{\n void* operator new( std::size_t rqsize, std::size_t padding )\n {\n return ::operator new( rqsize + padding );\n }\n\n // Usual (non-placement) delete\n // We need to define this as our placement operator delete\n // function happens to have one of the allowed signatures for\n // a non-placement operator delete\n void operator delete( void* p )\n {\n ::operator delete( p );\n }\n\n // Placement operator delete\n void operator delete( void* p, std::size_t )\n {\n ::operator delete( p );\n }\n};\n // Called in one step like so:\nMyObject* ObjectPtr = new (padding) MyObject;\n delete ObjectPtr;\n operator new operator delete void* delete"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
73,162 |
<p>Is there an API call in .NET or a native DLL that I can use to create similar behaviour as Windows Live Messenger when a response comes from someone I chat with?</p>
|
[
{
"answer_id": 73208,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 2,
"selected": false,
"text": "HWND hHandle = FindWindow(NULL,\"YourApplicationName\");\nFLASHWINFO pf;\npf.cbSize = sizeof(FLASHWINFO);\npf.hwnd = hHandle;\npf.dwFlags = FLASHW_TIMER|FLASHW_TRAY; // (or FLASHW_ALL to flash and if it is not minimized)\npf.uCount = 8;\npf.dwTimeout = 75;\n\nFlashWindowEx(&pf);\n"
},
{
"answer_id": 73209,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "SetForegroundWindow"
},
{
"answer_id": 73287,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 2,
"selected": false,
"text": "void\nOnSize(HWND hwnd, UINT state, int cx, int cy)\n{\n if (state == SIZE_MINIMIZED) {\n FLASHWINFO fwi = { sizeof(fwi), hwnd,\n FLASHW_TIMERNOFG | FLASHW_ALL };\n FlashWindowEx(&fwi);\n }\n}\n"
},
{
"answer_id": 73383,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 6,
"selected": true,
"text": "[DllImport(\"user32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool FlashWindowEx(ref FLASHWINFO pwfi);\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct FLASHWINFO\n{\n public UInt32 cbSize;\n public IntPtr hwnd;\n public UInt32 dwFlags;\n public UInt32 uCount;\n public UInt32 dwTimeout;\n}\n\npublic const UInt32 FLASHW_ALL = 3; \n FLASHWINFO fInfo = new FLASHWINFO();\n\nfInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));\nfInfo.hwnd = hWnd;\nfInfo.dwFlags = FLASHW_ALL;\nfInfo.uCount = UInt32.MaxValue;\nfInfo.dwTimeout = 0;\n\nFlashWindowEx(ref fInfo);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6896/"
] |
73,168 |
<p>I am trying to scrape an html table and save its data in a database. What strategies/solutions have you found to be helpful in approaching this program.</p>
<p>I'm most comfortable with Java and PHP but really a solution in any language would be helpful.</p>
<p>EDIT: For more detail, the UTA (Salt Lake's Bus system) provides bus schedules on its website. Each schedule appears in a table that has stations in the header and times of departure in the rows. I would like to go through the schedules and save the information in the table in a form that I can then query. </p>
<p>Here's the <a href="http://www.rideuta.com/ridingUTA/schedules/routeSchedules.aspx" rel="nofollow noreferrer">starting point</a> for the schedules </p>
|
[
{
"answer_id": 73321,
"author": "pianohacker",
"author_id": 10956,
"author_profile": "https://Stackoverflow.com/users/10956",
"pm_score": 1,
"selected": false,
"text": "\n # cpan HTML::Parser\n"
},
{
"answer_id": 279752,
"author": "Thorvaldur",
"author_id": 35781,
"author_profile": "https://Stackoverflow.com/users/35781",
"pm_score": 1,
"selected": false,
"text": "from BeautifulSoup import BeautifulSoup\nimport urllib,string,csv,sys,os\nfrom string import replace\n\ndate_s = '&date1=01/01/08'\ndate_f = '&date=11/10/08'\nfx_url = 'http://www.oanda.com/convert/fxhistory?date_fmt=us'\nfx_url_end = '&lang=en&margin_fixed=0&format=CSV&redirected=1'\ncur1,cur2 = 'USD','AUD'\nfx_url = fx_url + date_f + date_s + '&exch=' + cur1 +'&exch2=' + cur1\nfx_url = fx_url +'&expr=' + cur2 + '&expr2=' + cur2 + fx_url_end\ndata = urllib.urlopen(fx_url).read()\nsoup = BeautifulSoup(data)\ndata = str(soup.findAll('pre', limit=1))\ndata = replace(data,'[<pre>','')\ndata = replace(data,'</pre>]','')\nfile_location = '/Users/location_edit_this'\nfile_name = file_location + 'usd_aus.csv'\nfile = open(file_name,\"w\")\nfile.write(data)\nfile.close()\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274/"
] |
73,198 |
<p>When using Linq to SQL and stored procedures, the class generated to describe the proc's result set uses char properties to represent char(1) columns in the SQL proc. I'd rather these be strings - is there any easy way to make this happen?</p>
|
[
{
"answer_id": 73812,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 0,
"selected": false,
"text": "var whatever =\n from x in something\n select new { yourString = Char.ToString(x.theChar); }\n"
},
{
"answer_id": 73976,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": true,
"text": "class MyTable\n{ int MyNum {get; set;}\n int YourNum {get; set;}\n char OneChar {get; set;}\n}\n class MyFixedTable\n{ int MyNum {get; set;}\n int YourNum {get; set;}\n string OneChar {get; set;}\n public MyFixedTable(MyTable t)\n {\n this,MyNum = t.MyNum;\n this.YourNum = t.YourNum;\n this.OneChar = new string(t.OneChar, 1);\n }\n}\n var q = from t in db.MyTable\n select t;\n var q = from t in db.MyTable\n select new MyFixTable(t);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12260/"
] |
73,227 |
<p>I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.</p>
|
[
{
"answer_id": 73271,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 2,
"selected": false,
"text": "Delegate delegate = x => \"hi!\";\nDelegate delegate = delegate(object x) { return \"hi\";};\n"
},
{
"answer_id": 73318,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 2,
"selected": false,
"text": "delegate string MyDelegate(int param1);\n (int i) => i.ToString();\n(int i) => \"ignored i\";\n(int i) => \"Step \" + i.ToString() + \" of 10\";\n Delegate Delegate"
},
{
"answer_id": 73367,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "Func<int, int> f = x => x + 1;\nExpression<Func<int, int>> exprTree = x => x + 1;\n"
},
{
"answer_id": 73408,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 0,
"selected": false,
"text": "something.Sort((x, y) => return x.CompareTo(y));\n something.Sort(sortMethod);\n...\n\nprivate int sortMethod(SomeType one, SomeType two)\n{\n one.CompareTo(two)\n}\n"
},
{
"answer_id": 73448,
"author": "Karg",
"author_id": 12685,
"author_profile": "https://Stackoverflow.com/users/12685",
"pm_score": 5,
"selected": false,
"text": "public delegate string TestDelegate(int i);\n\npublic void Test(TestDelegate d)\n{}\n Test(delegate(int i) { return String.Empty; });\nTest(delegate { return String.Empty; });\nTest(i => String.Empty);\nTest(D);\n\nprivate string D(int i)\n{\n return String.Empty;\n}\n Test(() => String.Empty); //Not allowed, lambda must match signature\nTest(D2); //Not allowed, method must match signature\n\nprivate string D2()\n{\n return String.Empty;\n}\n"
},
{
"answer_id": 73819,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 8,
"selected": true,
"text": "delegate Int32 BinaryIntOp(Int32 x, Int32 y);\n BinaryIntOp sumOfSquares = (a, b) => a*a + b*b;\n Int32 DiffOfSquares(Int32 x, Int32 y)\n{\n return x*x - y*y;\n}\n\nFunc<Int32, Int32, Int32> funcPtr = DiffOfSquares;\n"
},
{
"answer_id": 74079,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 0,
"selected": false,
"text": " private void button2_Click(object sender, EventArgs e) \n { \n BackgroundWorker worker = new BackgroundWorker(); \n worker.DoWork += new DoWorkEventHandler(worker_DoWork); \n worker.RunWorkerAsync(); \n } \n\n private delegate void UpdateProgDelegate(int count); \n private void UpdateText(int count) \n { \n if (this.lblTest.InvokeRequired) \n { \n UpdateProgDelegate updateCallBack = new UpdateProgDelegate(UpdateText); \n this.Invoke(updateCallBack, new object[] { count }); \n } \n else \n { \n lblTest.Text = count.ToString(); \n } \n } \n\n void worker_DoWork(object sender, DoWorkEventArgs e) \n { \n /* Old Skool delegate usage. See above for delegate and method definitions */ \n for (int i = 0; i < 50; i++) \n { \n UpdateText(i); \n Thread.Sleep(50); \n } \n\n // Anonymous Method \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke((MethodInvoker)(delegate() \n { \n lblTest.Text = i.ToString(); \n })); \n Thread.Sleep(50); \n } \n\n /* Lambda using the new Func delegate. This lets us take in an int and \n * return a string. The last parameter is the return type. so \n * So Func<int, string, double> would take in an int and a string \n * and return a double. count is our int parameter.*/ \n Func<int, string> UpdateProgress = (count) => lblTest.Text = count.ToString(); \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke(UpdateProgress, i); \n Thread.Sleep(50); \n } \n\n /* Finally we have a totally inline Lambda using the Action delegate \n * Action is more or less the same as Func but it returns void. We could \n * use it with parameters if we wanted to like this: \n * Action<string> UpdateProgress = (count) => lblT…*/ \n for (int i = 0; i < 50; i++) \n { \n lblTest.Invoke((Action)(() => lblTest.Text = i.ToString())); \n Thread.Sleep(50); \n } \n }\n"
},
{
"answer_id": 27059973,
"author": "Olorin",
"author_id": 1581875,
"author_profile": "https://Stackoverflow.com/users/1581875",
"pm_score": 0,
"selected": false,
"text": "typedef R (*thefunctionpointer) ( T ) ;\n thefunctionpointer T R thefunctionpointer = &thefunction ;\nR r = (*thefunctionpointer) ( t ) ; // where t is of type T\n thefunction T R delegate R thedelegate( T t ) ; // and yes, here the identifier t is needed\n thedelegate thedel = thefunction ;\nR r = thedel ( t ) ; // where t is of type T\n thefunction T R public delegate TResult Func<in T, out TResult>(T arg);\n Func<double, double> thefunctor = thefunction2; // call it a functor because it is\n // really as a functor that you should\n // \"see\" it\ndouble y = thefunctor(2.0);\n thefunction2 double thefunction2 double x double x*x => Func<double, double> thefunctor = ( (double x) => x * x ); // outer brackets are not\n // mandatory\n (double x) => x * x"
},
{
"answer_id": 50314365,
"author": "Yogesh Prajapati",
"author_id": 4959238,
"author_profile": "https://Stackoverflow.com/users/4959238",
"pm_score": 1,
"selected": false,
"text": "(string testString) => { Console.WriteLine(testString); };\n delegate void PrintTestString(string testString); // declare a delegate\n\nPrintTestString print = (string testString) => { Console.WriteLine(testString); }; \nprint();\n s => s.Age > someValue && s.Age < someValue // will return true/false\n Func< Student,bool> checkStudentAge = s => s.Age > someValue && s.Age < someValue ;\n\nbool result = checkStudentAge ( Student Object);\n"
},
{
"answer_id": 67167690,
"author": "Ievgen Martynov",
"author_id": 927030,
"author_profile": "https://Stackoverflow.com/users/927030",
"pm_score": 2,
"selected": false,
"text": "namespace System\n{\n // define a type\n public delegate TResult Func<in T, out TResult>(T arg);\n}\n\n// method with the compatible signature\npublic static bool IsPositive(int int32)\n{\n return int32 > 0;\n}\n\n// initiated and associate\nFunc<int, bool> isPositive = new Func<int, bool>(IsPositive);\n Func<int, bool> isPositive = delegate(int int32)\n{\n return int32 > 0;\n};\n Func<int, bool> isPositive = (int int32) =>\n{\n return int32 > 0;\n};\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538/"
] |
73,230 |
<p>If a user saves the password on the login form, ff3 is putting the saved password in the change password dialoge on the profile page, even though its <strong>not the same input name</strong> as the login. how can I prevent this?</p>
|
[
{
"answer_id": 73283,
"author": "Toby Mills",
"author_id": 12377,
"author_profile": "https://Stackoverflow.com/users/12377",
"pm_score": 3,
"selected": true,
"text": "print(\"<input type=\"text\" name=\"cc\" autocomplete=\"off\" />\");"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
73,261 |
<p>Many of the parameters for interacting with the Office Object model in VSTO require object parameters that are passed by reference, even when the notional type of the parameter is an int or string.</p>
<ol>
<li>I suppose that this mechanism is used so that code can modify the parameter, although I can't figure out why these need to be passed as generic object instead of as their more appropriate types. Can anyone enlighten me?</li>
<li><p>The mechanism I've been using (cribbed from help and MSDN resources) essentially creates a generic object that contains the appropriate data and then passes that to the method, for example:</p>
<p>object nextBookmarkName = "NextContent";
object nextBookmark = this.Bookmarks.get_Item( ref nextBookmarkName ).Range;</p>
<p>Microsoft.Office.Interop.Word.Range newRng = this.Range( ref nextBookmark, ref nextBookmark );</p></li>
</ol>
<p>This seems like a lot of extra code, but I can't see a better way to do it. I'm sure I'm missing something; what is it? Or is this really the best practice?</p>
|
[
{
"answer_id": 73310,
"author": "KTamas",
"author_id": 6541,
"author_profile": "https://Stackoverflow.com/users/6541",
"pm_score": 0,
"selected": false,
"text": "object oFalse = false, oTrue = true, oOne = 1;\n"
},
{
"answer_id": 165598,
"author": "rasx",
"author_id": 22944,
"author_profile": "https://Stackoverflow.com/users/22944",
"pm_score": 2,
"selected": false,
"text": "internal struct Argument\n{\n internal static object False = false;\n\n internal static object Missing = System.Type.Missing;\n\n internal static object True = true;\n}\n /// <summary>\n/// Defines the \"special characters\"\n/// in Microsoft Word that VSTO 1.x\n/// translates into C# strings.\n/// </summary>\ninternal struct Characters\n{\n /// <summary>\n /// Word Table end-of-cell marker.\n /// </summary>\n /// <remarks>\n /// Word Table end-of-row markers are also\n /// equal to this value.\n /// </remarks>\n internal static string CellBreak = \"\\r\\a\";\n\n /// <summary>\n /// Word line break (^l).\n /// </summary>\n internal static string LineBreak = \"\\v\";\n\n /// <summary>\n /// Word Paragraph break (^p).\n /// </summary>\n internal static string ParagraphBreak = \"\\r\";\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8151/"
] |
73,286 |
<p>I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction?</p>
|
[
{
"answer_id": 74542,
"author": "ben",
"author_id": 4607,
"author_profile": "https://Stackoverflow.com/users/4607",
"pm_score": 3,
"selected": false,
"text": "std::streambuf* old_rdbuf = std::cout.rdbuf();\nstd::stringbuf new_rdbuf;\n// replace default output buffer with string buffer\nstd::cout.rdbuf(&new_rdbuf);\n\n// write to new buffer, make sure to flush at the end\nstd::cout << \"hello, world\" << std::endl;\n\nstd::string s(new_rdbuf.str());\n// restore the default buffer before destroying the new one\nstd::cout.rdbuf(old_rdbuf);\n\n// show that the data actually went somewhere\nstd::cout << s.size() << \": \" << s;\n"
},
{
"answer_id": 6086817,
"author": "Yakov Galka",
"author_id": 277176,
"author_profile": "https://Stackoverflow.com/users/277176",
"pm_score": 4,
"selected": false,
"text": "#include <vector>\n#include <iostream>\n#include <windows.h>\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/tee.hpp>\n\nusing namespace std;\nnamespace io = boost::iostreams;\n\nstruct DebugSink\n{\n typedef char char_type;\n typedef io::sink_tag category;\n\n std::vector<char> _vec;\n\n std::streamsize write(const char *s, std::streamsize n)\n {\n _vec.assign(s, s+n);\n _vec.push_back(0); // we must null-terminate for WINAPI\n OutputDebugStringA(&_vec[0]);\n return n;\n }\n};\n\nint main()\n{\n typedef io::tee_device<DebugSink, std::streambuf> TeeDevice;\n TeeDevice device(DebugSink(), *cout.rdbuf());\n io::stream_buffer<TeeDevice> buf(device);\n cout.rdbuf(&buf);\n\n cout << \"hello world!\\n\";\n cout.flush(); // you may need to flush in some circumstances\n}\n X:\\full\\file\\name.txt(10) : message\n"
},
{
"answer_id": 57573500,
"author": "ejectamenta",
"author_id": 1740850,
"author_profile": "https://Stackoverflow.com/users/1740850",
"pm_score": 0,
"selected": false,
"text": "std::ostringstream oss;\n\noss << \"w:=\" << w << \" u=\" << u << \" vt=\" << vt << endl;\n\nTRACE(oss.str().data());\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1265473/"
] |
73,308 |
<p>I am trying to implement a request to an unreliable server. The request is a nice to have, but not 100% required for my perl script to successfully complete. The problem is that the server will occasionally deadlock (we're trying to figure out why) and the request will never succeed. Since the server thinks it is live, it keeps the socket connection open thus LWP::UserAgent's timeout value does us no good what-so-ever. What is the best way to enforce an absolute timeout on a request? </p>
<p>FYI, this is not an DNS problem. The deadlock has something to do with a massive number of updates hitting our Postgres database at the same time. For testing purposes, we've essentially put a while(1) {} line in the servers response handler. </p>
<p>Currently, the code looks like so:</p>
<pre><code>my $ua = LWP::UserAgent->new;
ua->timeout(5); $ua->cookie_jar({});
my $req = HTTP::Request->new(POST => "http://$host:$port/auth/login");
$req->content_type('application/x-www-form-urlencoded');
$req->content("login[user]=$username&login[password]=$password");
# This line never returns
$res = $ua->request($req);
</code></pre>
<p>I've tried using signals to trigger a timeout, but that does not seem to work. </p>
<pre><code>eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm(1);
$res = $ua->request($req);
alarm(0);
};
# This never runs
print "here\n";
</code></pre>
<p>The final answer I'm going to use was proposed by someone offline, but I'll mention it here. For some reason, SigAction works while $SIG(ALRM) does not. Still not sure why, but this has been tested to work. Here are two working versions:</p>
<pre><code># Takes a LWP::UserAgent, and a HTTP::Request, returns a HTTP::Request
sub ua_request_with_timeout {
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
use Sys::SigAction qw( timeout_call );
our $res = undef;
if( timeout_call( 5, sub {$res = $ua->request($req);}) ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
sub ua_request_with_timeout2 {
print "ua_request_with_timeout\n";
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
my $timeout_for_client = $ua->timeout() - 2;
our $socket_has_timedout = 0;
use POSIX;
sigaction SIGALRM, new POSIX::SigAction(
sub {
$socket_has_timedout = 1;
die "alarm timeout";
}
) or die "Error setting SIGALRM handler: $!\n";
my $res = undef;
eval {
alarm ($timeout_for_client);
$res = $ua->request($req);
alarm(0);
};
if ( $socket_has_timedout ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
</code></pre>
|
[
{
"answer_id": 76379,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 1,
"selected": false,
"text": "use LWP::UserAgent;\nuse IO::Pipe;\n\nmy $agent = new LWP::UserAgent;\n\nmy $finished = 0;\nmy $timeout = 5;\n\n$SIG{CHLD} = sub { wait, $finished = 1 };\n\nmy $pipe = new IO::Pipe;\nmy $pid = fork;\n\nif($pid == 0) {\n $pipe->writer;\n my $response = $agent->get(\"http://stackoverflow.com/\");\n $pipe->print($response->content);\n exit;\n}\n\n$pipe->reader;\n\nsleep($timeout);\n\nif($finished) {\n print \"Finished!\\n\";\n my $content = join('', $pipe->getlines);\n} \nelse {\n kill(9, $pid);\n print \"Timed out.\\n\";\n} \n"
},
{
"answer_id": 18542076,
"author": "Andrei Georgescu",
"author_id": 2734397,
"author_profile": "https://Stackoverflow.com/users/2734397",
"pm_score": 0,
"selected": false,
"text": "sub ua_request_with_timeout {\n my $ua = $_[0];\n my $request = $_[1];\n\n # Get whatever timeout is set for LWP and use that to \n # enforce a maximum timeout per request in case of server\n # deadlock. (This has happened.)`enter code here`\n my $timeout_for_client_sec = $ua->timeout();\n our $res_has_timedout = 0; \n\n use POSIX ':signal_h';\n\n my $newaction = POSIX::SigAction->new(\n sub { $res_has_timedout = 1; die \"web request timeout\"; },# the handler code ref\n POSIX::SigSet->new(SIGALRM),\n # not using (perl 5.8.2 and later) 'safe' switch or sa_flags\n ); \n\n my $oldaction = POSIX::SigAction->new();\n if(!sigaction(SIGALRM, $newaction, $oldaction)) {\n log('warn',\"Error setting SIGALRM handler: $!\");\n return $ua->request($request);\n } \n\n my $response = undef;\n eval {\n alarm ($timeout_for_client_sec);\n $response = $ua->request($request);\n alarm(0);\n }; \n\n alarm(0);# cancel alarm (if eval failed because of non alarm cause)\n if(!sigaction(SIGALRM, $oldaction )) {\n log('warn', \"Error resetting SIGALRM handler: $!\");\n }; \n\n if ( $res_has_timedout ) {\n log('warn', \"Timeout($timeout_for_client_sec sec) while waiting for a response from cred central\");\n return HTTP::Response->new(408); #408 is the HTTP timeout\n } else {\n return $response;\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12628/"
] |
73,319 |
<p>How do I duplicate a whole line in <strong>Vim</strong> in a similar way to <kbd>Ctrl</kbd>+<kbd>D</kbd> in IntelliJ IDEA/ Resharper or <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> in <strong>Eclipse</strong>?</p>
|
[
{
"answer_id": 73330,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 6,
"selected": false,
"text": "put"
},
{
"answer_id": 73362,
"author": "Linulin",
"author_id": 12481,
"author_profile": "https://Stackoverflow.com/users/12481",
"pm_score": 8,
"selected": false,
"text": "YP Yp yyp"
},
{
"answer_id": 73682,
"author": "Kwondri",
"author_id": 7691,
"author_profile": "https://Stackoverflow.com/users/7691",
"pm_score": 6,
"selected": false,
"text": "\"ayy a \"ap a \"a5yy a"
},
{
"answer_id": 1123441,
"author": "Rook",
"author_id": 62699,
"author_profile": "https://Stackoverflow.com/users/62699",
"pm_score": 4,
"selected": false,
"text": "nmap <C-d> mzyyp`z\n"
},
{
"answer_id": 10194014,
"author": "Benoit",
"author_id": 457352,
"author_profile": "https://Stackoverflow.com/users/457352",
"pm_score": 9,
"selected": false,
"text": ":t. :t 7 :,+t0 ,+ .,.+1 :1,t$ 1, 1,. :m :t :g :v :v/foo/m$ :+,$g/^\\s*class\\s\\+\\i\\+/t. class xxx :help range :help :t :help :g :help :m :help :v"
},
{
"answer_id": 21638849,
"author": "Adam",
"author_id": 313211,
"author_profile": "https://Stackoverflow.com/users/313211",
"pm_score": 8,
"selected": false,
"text": "yy\n p\n"
},
{
"answer_id": 29739390,
"author": "Chris Penner",
"author_id": 3907685,
"author_profile": "https://Stackoverflow.com/users/3907685",
"pm_score": 3,
"selected": false,
"text": "\" set Y to duplicate lines, works in visual mode as well.\nnnoremap Y yyp\nvnoremap Y y`>pgv\n"
},
{
"answer_id": 48734229,
"author": "jedi",
"author_id": 4741620,
"author_profile": "https://Stackoverflow.com/users/4741620",
"pm_score": 2,
"selected": false,
"text": ".vimrc nmap <S-C-d> <Esc>Yp imap <S-C-d> <Esc>Ypa"
},
{
"answer_id": 49780313,
"author": "yolenoyer",
"author_id": 3271687,
"author_profile": "https://Stackoverflow.com/users/3271687",
"pm_score": 1,
"selected": false,
"text": ":nnoremap yp Yp\n YP"
},
{
"answer_id": 49811528,
"author": "DarkWiiPlayer",
"author_id": 4984564,
"author_profile": "https://Stackoverflow.com/users/4984564",
"pm_score": 3,
"selected": false,
"text": "nnoremap <C-d> :copy .<CR>\nvnoremap <C-d> :copy '><CR>\n :copy copy . '<,'> copy '>"
},
{
"answer_id": 67353204,
"author": "frfernandezdev",
"author_id": 9309561,
"author_profile": "https://Stackoverflow.com/users/9309561",
"pm_score": 0,
"selected": false,
"text": "nnoremap <A-d> :t. <CR>==\ninoremap <A-d> <Esc>:t. <CR>==gi\nvnoremap <A-d> :t$ <CR>gv=gv\n"
},
{
"answer_id": 68621271,
"author": "Savrige",
"author_id": 2583490,
"author_profile": "https://Stackoverflow.com/users/2583490",
"pm_score": 2,
"selected": false,
"text": ".vimrc \" duplicate line in normal mode:\nnnoremap <C-D> Yp\n\" duplicate line in insert mode:\ninoremap <C-D> <Esc> Ypi\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11439/"
] |
73,320 |
<p>How do I set the column which has the header sort glyph, and its direction, in a .NET 2.0 WinForms ListView?</p>
<h2>Bump</h2>
<p>The listview is .net is not a managed control, it is a very thin wrapper around the Win32 ListView common control. It's not even a very good wrapper - it doesn't expose all the features of the real listview.</p>
<p>The Win32 listview common control supports drawing itself with themes. One of the themed elements is the header sort arrow. Windows Explorer's listview common control knows how to draw one of its columns with that theme element.</p>
<ul>
<li>does the Win32 listview support specifying which column has what sort order? </li>
<li>does the Win32 header control that the listview internally uses support specifying which column has what sort order? </li>
<li>does the win32 header control support custom drawing, so I can draw the header sort glyph myself?</li>
<li>does the win32 listview control support custom header drawing, so I can draw the header sort glyph myself?</li>
<li>does the .NET ListView control support custom header drawing, so I can draw the header sort glyph myself?</li>
</ul>
|
[
{
"answer_id": 36332488,
"author": "Adam",
"author_id": 5250659,
"author_profile": "https://Stackoverflow.com/users/5250659",
"pm_score": 2,
"selected": false,
"text": "public static class ListViewExtensions\n{\n public static void DrawSortArrow(this ListView listView, SortOrder sortOrder, int colIndex)\n {\n string upArrow = \"▲ \";\n string downArrow = \"▼ \";\n\n foreach (ColumnHeader ch in listView.Columns)\n {\n if (ch.Text.Contains(upArrow))\n ch.Text = ch.Text.Replace(upArrow, string.Empty);\n else if (ch.Text.Contains(downArrow))\n ch.Text = ch.Text.Replace(downArrow, string.Empty);\n }\n\n if (sortOrder == SortOrder.Ascending)\n listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, downArrow);\n else\n listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, upArrow);\n }\n}\n private void lstOffers_ColumnClick(object sender, ColumnClickEventArgs e)\n{\n lstOffers.DrawSortArrow(SortOrder.Descending, e.Column);\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
73,366 |
<p>What tools/websites do you use to read JavaDocs? </p>
<p>I currently use Firefox with 20+ tabs open when working on a J2EE project to have all the documentation available which is not very usable, is eating too much memory and is not searchable.</p>
<p>What I would expect from such a tool/website:</p>
<ul>
<li>Aggregate JavaDocs from different locations</li>
<li>Direct access to types like Ctrl+T in Eclipse or similar</li>
<li>Fulltext search</li>
<li>Cross referencing between all the Java libraries I've chosen</li>
<li>For a tool: offline support</li>
<li>Speed</li>
</ul>
<p>not mandatory: </p>
<ul>
<li>possibility to annotate things</li>
<li>support for different versions of a library (+ diffing ?)</li>
<li>IDE integration</li>
</ul>
<p>Edit:</p>
<p>Thanks for your answers. I knew most of the sites but gave them another try. Here is my judgement:</p>
<ul>
<li>built-in Eclipse/IDE features
<ul>
<li>tightly integrated</li>
<li>offline/online support</li>
</ul></li>
<li><a href="http://www.javadoconline.com" rel="noreferrer"><strike>javadoconline.com</strike></a> (no longer maintained)
<ul>
<li>works</li>
<li>clean looks</li>
<li>finds matches in more than one version of the api and allows easy switching</li>
<li>simple but working</li>
<li>fast</li>
</ul></li>
<li><a href="http://www.jdocs.com/" rel="noreferrer"><strike>jdocs</strike></a> (offline)
<ul>
<li>seems very sophisticated</li>
<li>sometimes slow</li>
<li>some recent versions of libraries seem to be missing (Seam 2.0.0, Hibernate Validators) but it looks like you can add them yourself</li>
<li>IDE integration (not tested)</li>
<li>wiki style comments to each item</li>
</ul></li>
<li><a href="http://www.docjar.com/" rel="noreferrer">docjar.com</a>
<ul>
<li>works</li>
<li>fast</li>
<li>cluttered UI</li>
</ul></li>
<li><a href="http://www.teria.com/~koseki/tools/gm/javadoc_isearch/" rel="noreferrer">javadoc_isearch</a>
<ul>
<li>greasemonkey script for firefox which makes navigating javadocs easier</li>
<li>works smooth and perfectly</li>
</ul></li>
</ul>
|
[
{
"answer_id": 14937310,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 1,
"selected": false,
"text": "~/.m2"
},
{
"answer_id": 24620136,
"author": "Max",
"author_id": 2416526,
"author_profile": "https://Stackoverflow.com/users/2416526",
"pm_score": 3,
"selected": false,
"text": "objectify-5.0.3-javadoc.jar objectify-5.0.3-javadoc.zip objectify-5.0.3-javadoc index.html"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7647/"
] |
73,385 |
<p>Is there an easy way to convert a string from csv format into a string[] or list? </p>
<p>I can guarantee that there are no commas in the data.</p>
|
[
{
"answer_id": 73390,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "CsvString.split(',');\n"
},
{
"answer_id": 73404,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 0,
"selected": false,
"text": "string[] lines = System.IO.File.ReadAllLines(\"yourfile.csv\");\n foreach (string line in lines)\n{\n string[] items = line.Split({','}};\n}\n"
},
{
"answer_id": 73414,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "string test = \"one,two,three\";\nstring[] okNow = test.Split(',');\n"
},
{
"answer_id": 73416,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 0,
"selected": false,
"text": "string s = \"1,2,3,4,5\";\n\nstring myStrings[] = s.Split({','}};\n"
},
{
"answer_id": 73419,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 0,
"selected": false,
"text": "separationChar[] = {';'}; // or '\\t' ',' etc.\nvar strArray = strCSV.Split(separationChar);\n"
},
{
"answer_id": 73426,
"author": "Ryan Steckler",
"author_id": 12673,
"author_profile": "https://Stackoverflow.com/users/12673",
"pm_score": 0,
"selected": false,
"text": "string[] splitStrings = myCsv.Split(\",\".ToCharArray());\n"
},
{
"answer_id": 73526,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "Regex rex = new Regex(\",(?=([^\\\"]*\\\"[^\\\"]*\\\")*(?![^\\\"]*\\\"))\");\nstring[] values = rex.Split( csvLine );\n"
},
{
"answer_id": 73639,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 4,
"selected": false,
"text": "using System.Text.RegularExpressions;\n\nstring[] line;\nline = Regex.Split( input, \",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*(?![^\\\"]*\\\"))\");\n"
},
{
"answer_id": 73980,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "Microsoft.VisualBasic.FileIO.TextFieldParser\n"
},
{
"answer_id": 74093,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 1,
"selected": false,
"text": "static IEnumerable<string> CsvParse(string input)\n{\n // null strings return a one-element enumeration containing null.\n if (input == null)\n {\n yield return null;\n yield break;\n }\n\n // we will 'eat' bits of the string until it's gone.\n String remaining = input;\n while (remaining.Length > 0)\n {\n\n if (remaining.StartsWith(\"\\\"\")) // deal with quotes\n {\n remaining = remaining.Substring(1); // pass over the initial quote.\n\n // find the end quote.\n int endQuotePosition = remaining.IndexOf(\"\\\"\");\n switch (endQuotePosition)\n {\n case -1:\n // unclosed quote.\n throw new ArgumentOutOfRangeException(\"Unclosed quote\");\n case 0:\n // the empty quote\n yield return \"\";\n remaining = remaining.Substring(2);\n break;\n default:\n string quote = remaining.Substring(0, endQuotePosition).Trim();\n remaining = remaining.Substring(endQuotePosition + 1);\n yield return quote;\n break;\n }\n }\n else // deal with commas\n {\n int nextComma = remaining.IndexOf(\",\");\n switch (nextComma)\n {\n case -1:\n // no more commas -- read to end\n yield return remaining.Trim();\n yield break;\n\n case 0:\n // the empty cell\n yield return \"\";\n remaining = remaining.Substring(1);\n break;\n\n default:\n // get everything until next comma\n string cell = remaining.Substring(0, nextComma).Trim();\n remaining = remaining.Substring(nextComma + 1);\n yield return cell;\n break;\n }\n }\n }\n\n}\n"
},
{
"answer_id": 84639,
"author": "JohnOpincar",
"author_id": 16245,
"author_profile": "https://Stackoverflow.com/users/16245",
"pm_score": 0,
"selected": false,
"text": "public static string CsvToTabDelimited(string line) {\n var ret = new StringBuilder(line.Length);\n bool inQuotes = false;\n for (int idx = 0; idx < line.Length; idx++) {\n if (line[idx] == '\"') {\n inQuotes = !inQuotes;\n } else {\n if (line[idx] == ',') {\n ret.Append(inQuotes ? ',' : '\\t');\n } else {\n ret.Append(line[idx]);\n }\n }\n }\n return ret.ToString();\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12653/"
] |
73,447 |
<p>What's the most efficient way to convert the output of this function from a varbinary() to a a varchar()?</p>
|
[
{
"answer_id": 73503,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 4,
"selected": true,
"text": "master.sys.fn_varbintohexstr(@binvalue)\n"
},
{
"answer_id": 7979858,
"author": "Cheburek",
"author_id": 311108,
"author_profile": "https://Stackoverflow.com/users/311108",
"pm_score": 2,
"selected": false,
"text": "CONVERT(varchar, @binary, 1)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366182/"
] |
73,456 |
<p>I have a weird problem with a dropdownbox selectedIndex always being set to 0 upon postback. I'm not accidentally rebinding it in my code. In fact I've placed a breakpoint at the very first line of the page_load event and the value is already set to zero. The dropdown is in the master page of my project, I don't know if that makes a difference. I'm not referencing the control in my content holder. </p>
<p>If I set my autoPostBack = 'true' the page works fine. I don't have to change any code and the selectedIndex is maintained. I have also tried setting enableViewState on and off and it doesn't make a difference. At this point I'm grasping at straws to figure out what's going on. I've never had this problem before.</p>
<p>Here is the code in my page_load event.</p>
<pre><code> If CartEstablished Then
txtCustNum.Visible = False
btnCustSearch.Visible = False
lblCustNum.Visible = True
ddlSalesType.Visible = False
lblSalesType.Visible = True
ddlTerms.Visible = False
lblTerms.Visible = True
lblTerms.Text = TermsDescription
Else
txtCustNum.Visible = True
btnCustSearch.Visible = True
lblCustNum.Visible = False
lblSalesType.Visible = False
ddlSalesType.Visible = True
lblTerms.Visible = False
ddlTerms.Visible = True
End If
If Page.IsPostBack Then
GetUIValues()
Else
LoadTermCodes()
End If
</code></pre>
<p>The LoadTermCodes is where I bind the dropdownlist that is causing me problems.</p>
|
[
{
"answer_id": 74783,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": -1,
"selected": false,
"text": " If Page.IsPostBack Then\n GetUIValues()\n Else\n If NOT Page.IsPostBack Then\n GetUIValues()\n Else\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288/"
] |
73,467 |
<p>I've got a custom handler applied to a class (using the Policy Injection Application Block in entlib 4) and I would like to know whether the input method is a property when Invoke is called. Following is what my handler looks like.</p>
<pre><code>[ConfigurationElementType(typeof(MyCustomHandlerData))]
public class MyCustomHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
if (input.MethodBase.IsPublic && (input.MethodBase.Name.Contains("get_") || input.MethodBase.Name.Contains("set_")))
{
Console.WriteLine("MyCustomHandler Invoke called with input of {0}", input.MethodBase.Name);
}
return getNext().Invoke(input, getNext);
}
public int Order { get; set; }
}
</code></pre>
<p>As you can see from my code sample, the best way I've thought of so far is by parsing the method name. Isn't there a better way to do this?</p>
|
[
{
"answer_id": 73908,
"author": "ShuggyCoUk",
"author_id": 12748,
"author_profile": "https://Stackoverflow.com/users/12748",
"pm_score": 3,
"selected": true,
"text": ".method public hidebysig specialname static int32 get_ExitCode() cil managed\n.method public hidebysig specialname static void set_ExitCode(int32 'value') cil managed\n if (m.IsSpecialName && (m.Attributes & MethodAttributes.HideBySig) != 0)) \n"
},
{
"answer_id": 24102577,
"author": "Paul Easter",
"author_id": 3583929,
"author_profile": "https://Stackoverflow.com/users/3583929",
"pm_score": 0,
"selected": false,
"text": "bool IsPropertySetter(MethodBase methodBase){\n return methodBase.IsSpecialName && methodBase.Name.StartsWith(\"set_\");\n}\n\nbool IsPropertyGetter(MethodBase methodBase){\n return methodBase.IsSpecialName && methodBase.Name.StartsWith(\"get_\");\n}\n Private Function IsPropertySetter(methodBase As MethodBase) As Boolean\n\n Return methodBase.IsSpecialName AndAlso methodBase.Name.StartsWith(\"set_\")\n\n End Function\n\n Private Function IsPropertyGetter(methodBase As MethodBase) As Boolean\n\n Return methodBase.IsSpecialName AndAlso methodBase.Name.StartsWith(\"get_\")\n\n End Function\n"
},
{
"answer_id": 40128143,
"author": "Tomaz Stih",
"author_id": 6286989,
"author_profile": "https://Stackoverflow.com/users/6286989",
"pm_score": 0,
"selected": false,
"text": " bool isProperty = method.ReflectedType.GetProperties().FirstOrDefault(p => \n p.GetGetMethod().GetHashCode() == method.GetHashCode() \n || p.GetSetMethod().GetHashCode() == method.GetHashCode())!=null;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6542/"
] |
73,468 |
<p>I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do.</p>
<p><strong>Is there a way of doing a non-blocking pthread_join?
Some sort of timed join would be good too.</strong></p>
<p>something like this:</p>
<pre>
foreach thread do
nb_pthread_join();
if still running
pthread_cancel();
</pre>
<p>I can think more cases where a a non-bloking join would be useful.</p>
<p>As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like.</p>
|
[
{
"answer_id": 81050,
"author": "shodanex",
"author_id": 11589,
"author_profile": "https://Stackoverflow.com/users/11589",
"pm_score": 1,
"selected": false,
"text": "pthread_join pthread_cond_timed_wait pthread_cond_wait"
},
{
"answer_id": 83788,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 2,
"selected": true,
"text": "int killed_threads = 0;\nfor(i = 0; i < num_threads; i++) {\n int return = pthread_cancel(threads[i]);\n if(return != ESRCH)\n killed_threads++;\n}\nif(killed_threads)\n printf(\"%d threads did not shutdown properly\\n\", killed_threads)\nelse\n printf(\"All threads exited successfully\");\n"
},
{
"answer_id": 1244687,
"author": "yves Baumes",
"author_id": 83331,
"author_profile": "https://Stackoverflow.com/users/83331",
"pm_score": 5,
"selected": false,
"text": "int pthread_tryjoin_np(pthread_t thread, void **retval);\n\nint pthread_timedjoin_np(pthread_t thread, void **retval,\n const struct timespec *abstime);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12661/"
] |
73,471 |
<p>I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)?</p>
|
[
{
"answer_id": 74256,
"author": "Phillip Wells",
"author_id": 3012,
"author_profile": "https://Stackoverflow.com/users/3012",
"pm_score": 4,
"selected": true,
"text": "Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting\n If uxContacts.CurrentCell IsNot Nothing Then\n If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then\n e.CellStyle.SelectionBackColor = Color.SteelBlue\n Else\n e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor\n End If\n End If\nEnd Sub\n"
},
{
"answer_id": 11961408,
"author": "Henry Rodriguez",
"author_id": 8892051,
"author_profile": "https://Stackoverflow.com/users/8892051",
"pm_score": 0,
"selected": false,
"text": "Private Sub DataGridView1_CellMouseMove(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseMove\n If e.RowIndex >= 0 Then\n DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = Color.Red\n End If\nEnd Sub\n\nPrivate Sub DataGridView1_CellMouseLeave(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellMouseLeave\n If e.RowIndex >= 0 Then\n DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = DataGridView1.DefaultCellStyle.SelectionBackColor\n End If\nEnd Sub\n"
},
{
"answer_id": 32944008,
"author": "Dennis Henry",
"author_id": 2790151,
"author_profile": "https://Stackoverflow.com/users/2790151",
"pm_score": 1,
"selected": false,
"text": "CellFormatting Private Sub Util_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvUtil.CellFormatting\n If dgvUtil.CurrentCell IsNot Nothing Then\n If e.RowIndex = dgvUtil.CurrentCell.RowIndex And e.ColumnIndex = dgvUtil.CurrentCell.ColumnIndex And (dgvUtil.CurrentCell.ColumnIndex = 10 Or dgvUtil.CurrentCell.ColumnIndex = 11 Or dgvUtil.CurrentCell.ColumnIndex = 13) Then\n e.CellStyle.SelectionBackColor = Color.SteelBlue\n Else\n e.CellStyle.SelectionBackColor = dgvUtil.DefaultCellStyle.SelectionBackColor\n End If\n End If\nEnd Sub\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3012/"
] |
73,474 |
<p>I am having a frequent problems with my web hosting (its shared)</p>
<p>I am not able to delete or change permission for a particular directory. The response is,</p>
<pre><code>Cannot delete. Directory may not be empty
</code></pre>
<p>I checked the permissions and it looks OK. There are 100's of files in this folder which I don't want. </p>
<p>I contacted my support and they solved it saying it was permission issue. But it reappeared. Any suggestions?</p>
<p>The server is Linux.</p>
|
[
{
"answer_id": 73549,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 3,
"selected": true,
"text": "$ rm -rf old_directory\n $ chmod -R +w old_directory\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12178/"
] |
73,476 |
<p>We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?</p>
|
[
{
"answer_id": 73483,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 3,
"selected": true,
"text": "char[] ch;\nAttributesImpl atts = new AttributesImpl();\nWriter writer = new StringWriter();\nStreamResult streamResult = new StreamResult(writer);\nSAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();\n\n// SAX2.0 ContentHandler\nTransformerHandler transformerHandler = tf.newTransformerHandler();\n\nTransformer serializer = transformerHandler.getTransformer();\n\nserializer.setOutputProperty(OutputKeys.ENCODING, \"UTF-8\");\n// serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, \"nodes.dtd\");\nserializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n\ntransformerHandler.setResult(streamResult);\n\ntransformerHandler.startDocument();\n\natts.clear();\n// atts.addAttribute(\"\", \"\", \"xmlns\", \"CDATA\", \"http://www.example.com/nodes\");\n// atts.addAttribute(\"\", \"\", \"xmlns:xsi\", \"CDATA\", \"http://www.w3.org/2001/XMLSchema-instance\");\n// atts.addAttribute(\"\", \"\", \"xsi:schemaLocation\", \"CDATA\", \"/nodes.xsd\");\ntransformerHandler.startElement(\"\", \"\", \"node_list\", atts);\n\n// displayName element\nif (displayName != null) {\n transformerHandler.startElement(\"\", \"\", \"display_name\", null);\n ch = displayName.toCharArray();\n transformerHandler.characters(ch, 0, ch.length);\n transformerHandler.endElement(\"\", \"\", \"display_name\");\n}\n\n// nodes element\ntransformerHandler.startElement(\"\", \"\", \"nodes\", null);\n\natts.clear();\natts.addAttribute(\"\", \"\", \"node_type\", \"CDATA\", \"sometype\");\ntransformerHandler.startElement(\"\", \"\", \"node\", atts);\n\nch = node.getValue().toCharArray();\ntransformerHandler.startElement(\"\", \"\", \"value\", null);\ntransformerHandler.characters(ch, 0, ch.length);\ntransformerHandler.endElement(\"\", \"\", \"value\");\n\ntransformerHandler.endElement(\"\", \"\", \"node\");\n\ntransformerHandler.endElement(\"\", \"\", \"nodes\");\n\ntransformerHandler.endElement(\"\", \"\", \"node_list\");\n\ntransformerHandler.endDocument();\n\nString xml = writer.toString();\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9254/"
] |
73,484 |
<p>Basically I would like to find a way to ddo something like:</p>
<pre><code><asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label>
</code></pre>
<p>I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution.
(MyProperty is a string property)
cheers</p>
|
[
{
"answer_id": 73558,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 2,
"selected": false,
"text": "<asp:Label id=\"lID\" runat=\"server\"><%= MyProperty %></asp:Label>\n"
},
{
"answer_id": 73585,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<div> <%=MyProperty\"%></div>\n"
},
{
"answer_id": 74054,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 4,
"selected": false,
"text": "<asp:Label runat=\"server\" Text='<%# MyProperty %>' />\n"
},
{
"answer_id": 75235,
"author": "mrflippy",
"author_id": 13292,
"author_profile": "https://Stackoverflow.com/users/13292",
"pm_score": 4,
"selected": true,
"text": "<%$ resources: ResourceKey %>\n <%$ appSettings: AppSettingsKey %>\n"
},
{
"answer_id": 2968964,
"author": "Brian",
"author_id": 357836,
"author_profile": "https://Stackoverflow.com/users/357836",
"pm_score": 0,
"selected": false,
"text": "<asp:Label ID=\"lblCurrentTime\" runat=\"server\">\n Last update: <%=DateTime.Now.ToString()%>\n</asp:Label>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1613872/"
] |
73,491 |
<p>I'm trying to use maven2 to build an axis2 project. My project is configured as a parent project with AAR, WAR, and EAR modules. When I run the parent project's package goal, the console shows a successful build and all of the files are created. However the AAR file generated by AAR project is not included in the generated WAR project. The AAR project is listed as a dependency of WAR project. When I explicitly run the WAR's package goal, the AAR file is then included in the WAR file.</p>
<p>Why would the parent's package goal not include the necessary dependency while running the child's package goal does?</p>
<p>I'm using the maven-war-plugin v2.1-alpha-2 in my war project.</p>
<p>Parent POM:</p>
<pre><code><parent>
<groupId>companyId</groupId>
<artifactId>build</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.nationwide.nf</groupId>
<artifactId>parent</artifactId>
<packaging>pom</packaging>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>ws-war</module>
<module>ws-aar</module>
<module>ws-ear</module>
</modules>
</code></pre>
<p>AAR POM:</p>
<pre><code><parent>
<artifactId>parent</artifactId>
<groupId>companyId</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>companyId</groupId>
<artifactId>ws-aar</artifactId>
<version>1.0.0-SNAPSHOT</version>
<description/>
<packaging>aar</packaging>
<dependencies>...</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-wsdl2code-maven-plugin</artifactId>
<version>1.4</version>
<configuration>...</configuration>
<executions>
<execution>
<goals>
<goal>wsdl2code</goal>
</goals>
<id>axis2-gen-sources</id>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-aar-maven-plugin</artifactId>
<version>1.4</version>
<extensions>true</extensions>
<configuration>...</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>WAR POM:</p>
<pre><code><parent>
<artifactId>parent</artifactId>
<groupId>companyId</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>companyId</groupId>
<artifactId>ws-war</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<description/>
<dependencies>
<dependency>
<groupId>companyId</groupId>
<artifactId>ws-aar</artifactId>
<type>aar</type>
<version>1.0.0-SNAPSHOT</version>
</dependency>
.
.
.
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-alpha-2</version>
<configuration>
<warName>appName</warName>
</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>Thanks,
Joe</p>
|
[
{
"answer_id": 89868,
"author": "user11087",
"author_id": 11087,
"author_profile": "https://Stackoverflow.com/users/11087",
"pm_score": 0,
"selected": false,
"text": "<dependency>\n <groupId>group-a</groupId>\n <artifactId>artifact-b</artifactId>\n <version>1.0</version>\n <type>aar</type>\n</dependency>\n mvn clean install\n"
},
{
"answer_id": 120938,
"author": "Joe",
"author_id": 5313,
"author_profile": "https://Stackoverflow.com/users/5313",
"pm_score": 3,
"selected": true,
"text": " <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-dependency-plugin</artifactId>\n <executions>\n <execution>\n <phase>process-classes</phase>\n <goals>\n <goal>copy-dependencies</goal>\n </goals>\n <configuration>\n <outputDirectory>\n ${project.build.directory}/${project.build.finalName}/WEB-INF/services\n </outputDirectory>\n <includeArtifactIds>\n ws-aar\n </includeArtifactIds>\n </configuration>\n </execution>\n </executions>\n </plugin>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5313/"
] |
73,498 |
<p>When I'm initializing a dialog, I'd like to select one of the radio buttons on the form. I don't see a way to associate a Control variable using the Class Wizard, like you would typically do with CButtons, CComboBoxes, etc...</p>
<p>Further, it doesn't like a CRadioButton class even exists.</p>
<p>How can I select one of the several radio buttons?</p>
|
[
{
"answer_id": 73531,
"author": "moswald",
"author_id": 8368,
"author_profile": "https://Stackoverflow.com/users/8368",
"pm_score": 4,
"selected": true,
"text": "CButton GetCheck SetCheck"
},
{
"answer_id": 73559,
"author": "Chris Karcher",
"author_id": 2773,
"author_profile": "https://Stackoverflow.com/users/2773",
"pm_score": 3,
"selected": false,
"text": "CButton* pButton = (CButton*)GetDlgItem(IDC_RADIOBUTTON);\npButton->SetCheck(true);\n"
},
{
"answer_id": 9307754,
"author": "Gargo",
"author_id": 1213334,
"author_profile": "https://Stackoverflow.com/users/1213334",
"pm_score": 1,
"selected": false,
"text": "void CMyDlg::DoDataExchange(CDataExchange* pDX)\n{\n ...\n DDX_Radio(pDX, IDC_RADIO1, m_Radio);\n ...\n}\n"
},
{
"answer_id": 46086524,
"author": "sailfish009",
"author_id": 7404323,
"author_profile": "https://Stackoverflow.com/users/7404323",
"pm_score": 1,
"selected": false,
"text": "::SendMessage(GetDlgItem(IDC_RADIO1)->m_hWnd, BM_SETCHECK, BST_CHECKED, NULL);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2773/"
] |
73,515 |
<p>I am getting some errors thrown in my code when I open a Windows Forms form in Visual Studio's designer. I would like to branch in my code and perform a different initialization if the form is being opened by designer than if it is being run for real. </p>
<p>How can I determine at run-time if the code is being executed as part of designer opening the form?</p>
|
[
{
"answer_id": 73533,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 2,
"selected": false,
"text": "System.Diagnostics.Debugger.IsAttached\n"
},
{
"answer_id": 73541,
"author": "Adrian Anttila",
"author_id": 5988,
"author_profile": "https://Stackoverflow.com/users/5988",
"pm_score": 1,
"selected": false,
"text": "if System.Diagnostics.Debugger.IsAttached"
},
{
"answer_id": 73568,
"author": "Ryan Steckler",
"author_id": 12673,
"author_profile": "https://Stackoverflow.com/users/12673",
"pm_score": 1,
"selected": false,
"text": "DesignMode if (!DesignMode)\n{\n//Do production runtime stuff\n}\n"
},
{
"answer_id": 73582,
"author": "Akselsson",
"author_id": 8862,
"author_profile": "https://Stackoverflow.com/users/8862",
"pm_score": 0,
"selected": false,
"text": "if (DesignMode)\n{\n DesignMode Only stuff\n}\n"
},
{
"answer_id": 73619,
"author": "ShuggyCoUk",
"author_id": 12748,
"author_profile": "https://Stackoverflow.com/users/12748",
"pm_score": 0,
"selected": false,
"text": "System.ComponentModel.Component.DesignMode == true\n"
},
{
"answer_id": 73659,
"author": "JohnV",
"author_id": 4589,
"author_profile": "https://Stackoverflow.com/users/4589",
"pm_score": 4,
"selected": false,
"text": "public bool HostedDesignMode\n{\n get \n {\n Control parent = Parent;\n while (parent!=null)\n {\n if(parent.DesignMode) return true;\n parent = parent.Parent;\n }\n return DesignMode;\n }\n}\n"
},
{
"answer_id": 353089,
"author": "GWLlosa",
"author_id": 18071,
"author_profile": "https://Stackoverflow.com/users/18071",
"pm_score": 4,
"selected": false,
"text": "public bool isInDesignMode\n{\n get\n {\n System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();\n bool res = process.ProcessName == \"devenv\";\n process.Dispose();\n return res;\n }\n}\n"
},
{
"answer_id": 353111,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " public bool IsDesignerHosted\n {\n get { return IsControlDesignerHosted(this); }\n }\n\n public bool IsControlDesignerHosted(System.Windows.Forms.Control ctrl)\n {\n if (ctrl != null)\n {\n if (ctrl.Site != null)\n {\n if (ctrl.Site.DesignMode == true)\n return true;\n else\n {\n if (IsControlDesignerHosted(ctrl.Parent))\n return true;\n else\n return false;\n }\n }\n else\n {\n if (IsControlDesignerHosted(ctrl.Parent))\n return true;\n else\n return false;\n }\n }\n else\n return false;\n }\n public bool IsControlDesignerHosted(System.Windows.Forms.Control ctrl)\n {\n if (ctrl == null) return false;\n if (ctrl.Site != null && ctrl.Site.DesignMode) return true;\n return IsControlDesignerHosted(ctrl.Parent);\n }\n"
},
{
"answer_id": 353162,
"author": "Eyvind",
"author_id": 25746,
"author_profile": "https://Stackoverflow.com/users/25746",
"pm_score": 0,
"selected": false,
"text": "Process.GetCurrentProcess().ProcessName.ToLower().Trim() == \"devenv\";\n"
},
{
"answer_id": 7801743,
"author": "Marty",
"author_id": 184630,
"author_profile": "https://Stackoverflow.com/users/184630",
"pm_score": 4,
"selected": false,
"text": "public static class Foo\n{\n public static bool IsApplicationRunning { get; set; }\n}\n [STAThread]\nstatic void Main()\n{\n Foo.IsApplicationRunning = true;\n // ... code goes here ...\n}\n if(Foo.IsApplicationRunning)\n{\n // Do runtime stuff\n}\nelse\n{\n // Do design time stuff\n}\n"
},
{
"answer_id": 10725662,
"author": "NET3",
"author_id": 1289709,
"author_profile": "https://Stackoverflow.com/users/1289709",
"pm_score": 6,
"selected": false,
"text": "if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)\n{\n // Design time logic\n}\n"
},
{
"answer_id": 11177035,
"author": "Andy",
"author_id": 1477990,
"author_profile": "https://Stackoverflow.com/users/1477990",
"pm_score": 1,
"selected": false,
"text": " public bool IsInDesignMode\n {\n get\n {\n Process p = Process.GetCurrentProcess();\n bool result = false;\n\n if (p.ProcessName.ToLower().Trim().IndexOf(\"vshost\") != -1)\n result = true;\n p.Dispose();\n\n return result;\n }\n }\n"
},
{
"answer_id": 11477586,
"author": "Bolek",
"author_id": 1524524,
"author_profile": "https://Stackoverflow.com/users/1524524",
"pm_score": 1,
"selected": false,
"text": "protected virtual DataGridView GetGrid()\n{\n throw new NotImplementedException(\"frmBase.GetGrid()\");\n}\n\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic int ColumnCount { get { return GetGrid().Columns.Count; } set { /*Some code*/ } }\n NotImplementedException()"
},
{
"answer_id": 12618972,
"author": "Johny Skovdal",
"author_id": 222134,
"author_profile": "https://Stackoverflow.com/users/222134",
"pm_score": 3,
"selected": false,
"text": "private static readonly string[] _designerProcessNames = new[] { \"xdesproc\", \"devenv\" };\n\nprivate static bool? _runningFromVisualStudioDesigner = null;\npublic static bool RunningFromVisualStudioDesigner\n{\n get\n {\n if (!_runningFromVisualStudioDesigner.HasValue)\n {\n using (System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess())\n {\n _runningFromVisualStudioDesigner = _designerProcessNames.Contains(currentProcess.ProcessName.ToLower().Trim());\n }\n }\n\n return _runningFromVisualStudioDesigner.Value;\n }\n}\n"
},
{
"answer_id": 13894231,
"author": "Martin",
"author_id": 419427,
"author_profile": "https://Stackoverflow.com/users/419427",
"pm_score": 2,
"selected": false,
"text": "using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())\n{\n bool inDesigner = process.ProcessName.ToLower().Trim() == \"devenv\";\n return inDesigner;\n}\n private bool isDesignMode()\n{\n bool bProcCheck = false;\n using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())\n {\n bProcCheck = process.ProcessName.ToLower().Trim() == \"devenv\";\n }\n\n bool bModeCheck = (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime);\n\n return bProcCheck || DesignMode || bModeCheck;\n}\n"
},
{
"answer_id": 15224011,
"author": "Ali Reza Kalantar",
"author_id": 2132827,
"author_profile": "https://Stackoverflow.com/users/2132827",
"pm_score": 0,
"selected": false,
"text": "private bool IsUnderDevelopment\n{\n get\n {\n System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();\n if (process.ProcessName.EndsWith(\".vshost\")) return true;\n else return false;\n }\n\n}\n"
},
{
"answer_id": 15700675,
"author": "Lozza",
"author_id": 2223846,
"author_profile": "https://Stackoverflow.com/users/2223846",
"pm_score": -1,
"selected": false,
"text": " /// <summary>\n /// Whether or not we are being run from the Visual Studio IDE\n /// </summary>\n public bool InIDE\n {\n get\n {\n return Process.GetCurrentProcess().ProcessName.ToLower().Trim().EndsWith(\"vshost\");\n }\n }\n"
},
{
"answer_id": 22781355,
"author": "pintergabor",
"author_id": 3484286,
"author_profile": "https://Stackoverflow.com/users/3484286",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Are we in design mode?\n/// </summary>\n/// <returns>True if in design mode</returns>\nprivate bool IsDesignMode() {\n // Ugly hack, but it works in every version\n return 0 == String.CompareOrdinal(\n \"devenv.exe\", 0,\n Application.ExecutablePath, Application.ExecutablePath.Length - 10, 10);\n}\n"
},
{
"answer_id": 28432133,
"author": "GeeC",
"author_id": 1287392,
"author_profile": "https://Stackoverflow.com/users/1287392",
"pm_score": 3,
"selected": false,
"text": "protected static bool IsInDesigner\n{\n get { return (Assembly.GetEntryAssembly() == null); }\n}\n"
},
{
"answer_id": 29023756,
"author": "JWP",
"author_id": 1522548,
"author_profile": "https://Stackoverflow.com/users/1522548",
"pm_score": 0,
"selected": false,
"text": " //Caters only to thing done while only in design mode\n if (App.Current.MainWindow == null){ // in design mode }\n\n //Avoids design mode problems\n if (App.Current.MainWindow != null) { //applicaiton is running }\n"
},
{
"answer_id": 30196577,
"author": "Gary",
"author_id": 4892369,
"author_profile": "https://Stackoverflow.com/users/4892369",
"pm_score": -1,
"selected": false,
"text": "string testString1 = \"\\\\bin\\\\\";\n//string testString = \"\\\\bin\\\\Debug\\\\\";\n//string testString = \"\\\\bin\\\\Release\\\\\";\n\nif (AppDomain.CurrentDomain.BaseDirectory.Contains(testString))\n{\n //Your code here\n}\n"
},
{
"answer_id": 36042135,
"author": "Gpower2",
"author_id": 3235669,
"author_profile": "https://Stackoverflow.com/users/3235669",
"pm_score": 0,
"selected": false,
"text": "public static Boolean GetDesignMode(this Control control)\n{\n BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static;\n PropertyInfo prop = control.GetType().GetProperty(\"DesignMode\", bindFlags);\n return (Boolean)prop.GetValue(control, null);\n}\n public bool HostedDesignMode\n{\n get\n {\n Control parent = Parent;\n while (parent != null)\n {\n if (parent.GetDesignMode()) return true;\n parent = parent.Parent;\n }\n return DesignMode;\n }\n}\n public static Boolean IsInDesignMode(this Control control)\n{\n Control parent = control.Parent;\n while (parent != null)\n {\n if (parent.GetDesignMode())\n {\n return true;\n }\n parent = parent.Parent;\n }\n return control.GetDesignMode();\n}\n"
},
{
"answer_id": 72997523,
"author": "NielW",
"author_id": 570206,
"author_profile": "https://Stackoverflow.com/users/570206",
"pm_score": 0,
"selected": false,
"text": "if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject()))\n{\n}\n GetIsInDesignMode"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12717/"
] |
73,519 |
<p>Linux/Gcc/LD - Toolchain.</p>
<p>I would like to remove STL/Boost debug symbols from libraries and executable, for two reasons:</p>
<ol>
<li>Linking gets very slow for big programs</li>
<li>Debugging jumps into stl/boost code, which is annoying</li>
</ol>
<p>For 1. incremental linking would be a big improvement, but AFAIK ld does not support incremental linking. There is a workaround "pseudo incremental linking" in an 1999 dr.dobb's journal (not in the web any more, but at <a href="http://web.archive.org/web/20000131063231/www.ddj.com/articles/1999/9910/9910d/9910d.htm" rel="nofollow noreferrer">archive.org</a> (the idea is to put everything in a dynamic library and all updated object files in an second one that is loaded first) but this is not really a general solution.</p>
<p>For 2. there is a script <a href="http://ubuntuforums.org/showthread.php?p=4368377" rel="nofollow noreferrer">here</a>, but a) it did not work for me (it did not remove symbols), b) it is very slow as it works at the end of the pipe, while it would be more efficient to remove the symbols earlier.</p>
<p>Obviously, the other debug symbols should stay in place.</p>
|
[
{
"answer_id": 42669612,
"author": "gospes",
"author_id": 2250406,
"author_profile": "https://Stackoverflow.com/users/2250406",
"pm_score": 1,
"selected": false,
"text": "> nm --debug-syms <objectfile>\n resize > nm --debug-syms --demangle <objectfile>\n > strip --wildcard \\\n --strip-symbol='_ZNKSt*' \\\n --strip-symbol='_ZNSt*' \\\n --strip-symbol='_ZSt*' \\\n --strip-symbol='_ZNSa*' \\\n <objectfile>\n nm vimdiff --wildcard skip file"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11344/"
] |
73,524 |
<p>I have a list of addresses from a Database for which I'd like to put markers on a Yahoo Map. The <a href="http://developer.yahoo.com/maps/ajax/V3.8/index.html#YMap" rel="nofollow noreferrer"><code>addMarker()</code> method</a> on YMap takes a YGeoPoint, which requires a latitude and longitude. However, Yahoo Maps must know how to convert from addresses because <code>drawZoomAndCenter(LocationType,ZoomLevel)</code> can take an address. I could convert by using <code>drawZoomAndCenter()</code> then <code>getCenterLatLon()</code> but is there a better way, which doesn't require a draw?</p>
|
[
{
"answer_id": 81551,
"author": "David Bick",
"author_id": 4914,
"author_profile": "https://Stackoverflow.com/users/4914",
"pm_score": 2,
"selected": true,
"text": "<script type=\"text/javascript\"> \nvar map = new YMap(document.getElementById('map'));\nmap.drawZoomAndCenter(\"Algeria\", 17);\n\nmap.geoCodeAddress(\"Cambridge, UK\");\n\nYEvent.Capture(map, EventsList.onEndGeoCode, function(geoCode) {\n if (geoCode.success)\n map.addOverlay(new YMarker(geoCode.GeoPoint));\n});\n</script>\n drawAndZoom"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5346/"
] |
73,527 |
<p>There are several plugin options for building a search engine into your Ruby on Rails application. Which of these is the best?</p>
<ul>
<li><a href="http://ts.freelancing-gods.com/" rel="noreferrer">Thinking Sphinx</a></li>
<li><a href="http://blog.evanweaver.com/files/doc/fauna/ultrasphinx/files/README.html" rel="noreferrer">UltraSphinx</a></li>
<li><a href="http://seattlerb.rubyforge.org/Sphincter/" rel="noreferrer">Sphincter</a></li>
<li><a href="http://www.datanoise.com/articles/2007/3/23/acts_as_sphinx-plugin" rel="noreferrer">acts_as_sphinx</a></li>
<li><a href="http://projects.jkraemer.net/acts_as_ferret/" rel="noreferrer">acts_as_ferret</a></li>
<li><a href="http://ferret.davebalmain.com/trac/" rel="noreferrer">Ferret</a></li>
<li><a href="http://locomotivation.com/2008/07/23/simple-ruby-on-rails-full-text-search-using-xapian" rel="noreferrer">acts_as_xapian</a></li>
<li><a href="http://github.com/railsfreaks/acts_as_solr/tree/master" rel="noreferrer">acts_as_solr</a></li>
<li><a href="http://hyperestraier.sourceforge.net/" rel="noreferrer">Hyper Estraier</a></li>
</ul>
|
[
{
"answer_id": 73618,
"author": "squadette",
"author_id": 7754,
"author_profile": "https://Stackoverflow.com/users/7754",
"pm_score": 5,
"selected": true,
"text": "require"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9594/"
] |
73,542 |
<p>I have an List and I'd like to wrap it into an IQueryable.</p>
<p>Is this possible?</p>
|
[
{
"answer_id": 73563,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 8,
"selected": true,
"text": "List<int> list = new List<int>() { 1, 2, 3, 4, };\nIQueryable<int> query = list.AsQueryable();\n AsQueryable() System.Linq"
},
{
"answer_id": 73564,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 4,
"selected": false,
"text": "AsQueryable<T>()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11835/"
] |
73,544 |
<p>Anyone know of a good, hopefully free FTP class for use in .NET that can actually work behind an HTTP proxy or FTP gateway? The FtpWebRequest stuff in .NET is horrible at best, and I really don't want to roll my own here.</p>
|
[
{
"answer_id": 2327985,
"author": "Martin Vobr",
"author_id": 16132,
"author_profile": "https://Stackoverflow.com/users/16132",
"pm_score": 2,
"selected": false,
"text": "// initialize FTP client \nFtp client = new Ftp();\n\n// setup proxy details \nclient.Proxy.ProxyType = FtpProxyType.HttpConnect;\nclient.Proxy.Host = proxyHostname;\nclient.Proxy.Port = proxyPort;\n\n// add proxy username and password when needed \nclient.Proxy.UserName = proxyUsername;\nclient.Proxy.Password = proxyPassword;\n\n// connect, login \nclient.Connect(hostname, port);\nclient.Login(username, password);\n\n// do some work \n// ... \n\n// disconnect \nclient.Disconnect();\n"
},
{
"answer_id": 12266161,
"author": "freggel",
"author_id": 49788,
"author_profile": "https://Stackoverflow.com/users/49788",
"pm_score": 0,
"selected": false,
"text": "Socks4ProxyClient socks = new Socks4ProxyClient(\"socksproxyhost\",1010);\nFtpClient ftp = new FtpClient(\"ftpshost\",2010,FtpSecurityProtocol.Tls1Explicit);\nftp.Proxy = socks;\nftp.Open(\"userid\", \"******\");\nftp.PutFile(@\"C:\\519ec30a-ae15-4bd5-8bcd-94ef3ca49165.xml\");\nConsole.WriteLine(ftp.GetDirListAsText());\nftp.Close();\n"
},
{
"answer_id": 20353970,
"author": "A. 'Eradicator' Polyakov",
"author_id": 3061817,
"author_profile": "https://Stackoverflow.com/users/3061817",
"pm_score": 0,
"selected": false,
"text": "public bool UploadFile(string localFilePath, string remoteDirectory)\n{\n var fileName = Path.GetFileName(localFilePath);\n string content;\n using (var reader = new StreamReader(localFilePath))\n content = reader.ReadToEnd();\n\n var proxyAuthB64Str = Convert.ToBase64String(Encoding.ASCII.GetBytes(_proxyUserName + \":\" + _proxyPassword));\n var sendStr = \"PUT ftp://\" + _ftpLogin + \":\" + _ftpPassword\n + \"@\" + _ftpHost + remoteDirectory + fileName + \" HTTP/1.1\\n\"\n + \"Host: \" + _ftpHost + \"\\n\"\n + \"User-Agent: Mozilla/4.0 (compatible; Eradicator; dotNetClient)\\n\" + \"Proxy-Authorization: Basic \" + proxyAuthB64Str + \"\\n\"\n + \"Content-Type: application/octet-stream\\n\"\n + \"Content-Length: \" + content.Length + \"\\n\"\n + \"Connection: close\\n\\n\" + content;\n\n var sendBytes = Encoding.ASCII.GetBytes(sendStr);\n\n using (var proxySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n {\n proxySocket.Connect(_proxyHost, _proxyPort);\n if (!proxySocket.Connected)\n throw new SocketException();\n proxySocket.Send(sendBytes);\n\n const int recvSize = 65536;\n var recvBytes = new byte[recvSize];\n proxySocket.Receive(recvBytes, recvSize, SocketFlags.Partial);\n\n var responseFirstLine = new string(Encoding.ASCII.GetChars(recvBytes)).Split(\"\\n\".ToCharArray()).Take(1).ElementAt(0);\n var httpResponseCode = Regex.Replace(responseFirstLine, @\"HTTP/1\\.\\d (\\d+) (\\w+)\", \"$1\");\n var httpResponseDescription = Regex.Replace(responseFirstLine, @\"HTTP/1\\.\\d (\\d+) (\\w+)\", \"$2\");\n return httpResponseCode.StartsWith(\"2\");\n }\n return false;\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91911/"
] |
73,580 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail">How do you send email from a Java app using Gmail?</a> </p>
</blockquote>
<p>How do I send an SMTP Message from Java?</p>
|
[
{
"answer_id": 73649,
"author": "tovare",
"author_id": 12677,
"author_profile": "https://Stackoverflow.com/users/12677",
"pm_score": 6,
"selected": true,
"text": "import java.io.*;\nimport java.net.InetAddress;\nimport java.util.Properties;\nimport java.util.Date;\n\nimport javax.mail.*;\n\nimport javax.mail.internet.*;\n\nimport com.sun.mail.smtp.*;\n\n\npublic class Distribution {\n\n public static void main(String args[]) throws Exception {\n Properties props = System.getProperties();\n props.put(\"mail.smtps.host\",\"smtp.gmail.com\");\n props.put(\"mail.smtps.auth\",\"true\");\n Session session = Session.getInstance(props, null);\n Message msg = new MimeMessage(session);\n msg.setFrom(new InternetAddress(\"[email protected]\"));;\n msg.setRecipients(Message.RecipientType.TO,\n InternetAddress.parse(\"[email protected]\", false));\n msg.setSubject(\"Heisann \"+System.currentTimeMillis());\n msg.setText(\"Med vennlig hilsennTov Are Jacobsen\");\n msg.setHeader(\"X-Mailer\", \"Tov Are's program\");\n msg.setSentDate(new Date());\n SMTPTransport t =\n (SMTPTransport)session.getTransport(\"smtps\");\n t.connect(\"smtp.gmail.com\", \"[email protected]\", \"<insert password here>\");\n t.sendMessage(msg, msg.getAllRecipients());\n System.out.println(\"Response: \" + t.getLastServerResponse());\n t.close();\n }\n}\n"
},
{
"answer_id": 90001,
"author": "Brad at Kademi",
"author_id": 17025,
"author_profile": "https://Stackoverflow.com/users/17025",
"pm_score": 3,
"selected": false,
"text": "MailQue.queMail(MimeMessage message)\n"
},
{
"answer_id": 4578893,
"author": "user527619",
"author_id": 527619,
"author_profile": "https://Stackoverflow.com/users/527619",
"pm_score": 1,
"selected": false,
"text": "import javax.mail.*;\nimport javax.mail.internet.*;\nimport java.util.*; \n\npublic void postMail(String recipients[], String subject,\n String message , String from) throws MessagingException {\n\n //Set the host smtp address\n Properties props = new Properties();\n props.put(\"mail.smtp.host\", \"smtp.jcom.net\");\n\n // create some properties and get the default Session\n Session session = Session.getDefaultInstance(props, null);\n session.setDebug(false);\n\n // create a message\n Message msg = new MimeMessage(session);\n\n // set the from and to address\n InternetAddress addressFrom = new InternetAddress(from);\n msg.setFrom(addressFrom);\n\n InternetAddress[] addressTo = new InternetAddress[recipients.length]; \n for (int i = 0; i < recipients.length; i++) {\n addressTo[i] = new InternetAddress(recipients[i]);\n }\n msg.setRecipients(Message.RecipientType.TO, addressTo);\n\n // Optional : You can also set your custom headers in the Email if you Want\n msg.addHeader(\"MyHeaderName\", \"myHeaderValue\");\n\n // Setting the Subject and Content Type\n msg.setSubject(subject);\n msg.setContent(message, \"text/plain\");\n Transport.send(msg);\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/73580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.