qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
58,280 |
<p>Is it possible to use an UnhandledException Handler in a Windows Service?</p>
<p>Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesn’t achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points:</p>
<pre>
<code>
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
Try
MyServiceComponent.Start()
Catch ex As Exception
'call into our exception handler
MyExceptionHandlingComponent.ManuallyHandleException (ex)
'zero is the default ExitCode for a successfull exit, so if we set it to non-zero
ExitCode = -1
'So, we use Environment.Exit, it seems to be the most appropriate thing to use
'we pass an exit code here as well, just in case.
System.Environment.Exit(-1)
End Try
End Sub
</code>
</pre>
<p>Is there a way my Custom Exception Handling component can deal with this better so I don't have to fill my OnStart with messy exception handling plumbing?</p>
|
[
{
"answer_id": 58450,
"author": "Scott",
"author_id": 6042,
"author_profile": "https://Stackoverflow.com/users/6042",
"pm_score": 5,
"selected": true,
"text": "\nPrivate Sub ServiceQueuedMainCallback(ByVal state As Object)\n Dim args As String() = DirectCast(state, String())\n Try \n Me.OnStart(args)\n Me.WriteEventLogEntry(Res.GetString(\"StartSuccessful\"))\n Me.status.checkPoint = 0\n Me.status.waitHint = 0\n Me.status.currentState = 4\n Catch exception As Exception\n Me.WriteEventLogEntry(Res.GetString(\"StartFailed\", New Object() { exception.ToString }), EventLogEntryType.Error)\n Me.status.currentState = 1\n Catch obj1 As Object\n Me.WriteEventLogEntry(Res.GetString(\"StartFailed\", New Object() { String.Empty }), EventLogEntryType.Error)\n Me.status.currentState = 1\n End Try\n Me.startCompletedSignal.Set\nEnd Sub\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6042/"
] |
58,294 |
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
|
[
{
"answer_id": 2646313,
"author": "frankjania",
"author_id": 317610,
"author_profile": "https://Stackoverflow.com/users/317610",
"pm_score": 0,
"selected": false,
"text": "import urllib\ndef get_my_ip_address():\n whatismyip = 'http://www.whatismyip.com/automation/n09230945.asp'\n return urllib.urlopen(whatismyip).readlines()[0]\n"
},
{
"answer_id": 8305740,
"author": "Rafael Lopes",
"author_id": 1070554,
"author_profile": "https://Stackoverflow.com/users/1070554",
"pm_score": 3,
"selected": false,
"text": "'''\nFinds your external IP address\n'''\n\nimport urllib\nimport re\n\ndef get_ip():\n group = re.compile(u'(?P<ip>\\d+\\.\\d+\\.\\d+\\.\\d+)').search(urllib.URLopener().open('http://jsonip.com/').read()).groupdict()\n return group['ip']\n\nif __name__ == '__main__':\n print get_ip()\n"
},
{
"answer_id": 8848856,
"author": "Vasilii Pascal",
"author_id": 1147450,
"author_profile": "https://Stackoverflow.com/users/1147450",
"pm_score": 1,
"selected": false,
"text": "print (urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read())\n"
},
{
"answer_id": 49715732,
"author": "Scott",
"author_id": 9614384,
"author_profile": "https://Stackoverflow.com/users/9614384",
"pm_score": 2,
"selected": false,
"text": "import requests\n\ndef detect_public_ip():\n try:\n # Use a get request for api.duckduckgo.com\n raw = requests.get('https://api.duckduckgo.com/?q=ip&format=json')\n # load the request as json, look for Answer.\n # split on spaces, find the 5th index ( as it starts at 0 ), which is the IP address\n answer = raw.json()[\"Answer\"].split()[4]\n # if there are any connection issues, error out\n except Exception as e:\n return 'Error: {0}'.format(e)\n # otherwise, return answer\n else:\n return answer\n\npublic_ip = detect_public_ip()\nprint(public_ip)\n"
},
{
"answer_id": 54043521,
"author": "Ahmed",
"author_id": 10679414,
"author_profile": "https://Stackoverflow.com/users/10679414",
"pm_score": 0,
"selected": false,
"text": " import requests\n\n myPublic_IP = requests.get(\"http://wtfismyip.com/text\").text.strip()\n\n print(\"\\n[+] My Public IP: \"+ myPublic_IP+\"\\n\")\n"
},
{
"answer_id": 66517656,
"author": "jamjam46",
"author_id": 14914535,
"author_profile": "https://Stackoverflow.com/users/14914535",
"pm_score": 1,
"selected": false,
"text": "import requests\n\nIP = requests.get('https://api.ipify.org/').text\nprint(f'Your IP is: {IP}')\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5342/"
] |
58,305 |
<p>Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?</p>
|
[
{
"answer_id": 58326,
"author": "David Citron",
"author_id": 5309,
"author_profile": "https://Stackoverflow.com/users/5309",
"pm_score": 9,
"selected": true,
"text": "java.awt.Robot Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());\nBufferedImage capture = new Robot().createScreenCapture(screenRect);\nImageIO.write(capture, \"bmp\", new File(args[0]));\n"
},
{
"answer_id": 10796047,
"author": "DejanLekic",
"author_id": 876497,
"author_profile": "https://Stackoverflow.com/users/876497",
"pm_score": 5,
"selected": false,
"text": "public static final void makeScreenshot(JFrame argFrame) {\n Rectangle rec = argFrame.getBounds();\n BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);\n argFrame.paint(bufferedImage.getGraphics());\n\n try {\n // Create temp file\n File temp = File.createTempFile(\"screenshot\", \".png\");\n\n // Use the ImageIO API to write the bufferedImage to a temporary file\n ImageIO.write(bufferedImage, \"png\", temp);\n\n // Delete temp file when program exits\n temp.deleteOnExit();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n}\n"
},
{
"answer_id": 17229248,
"author": "user2503881",
"author_id": 2503881,
"author_profile": "https://Stackoverflow.com/users/2503881",
"pm_score": 4,
"selected": false,
"text": "public void captureScreen(String fileName) throws Exception {\n Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n Rectangle screenRectangle = new Rectangle(screenSize);\n Robot robot = new Robot();\n BufferedImage image = robot.createScreenCapture(screenRectangle);\n ImageIO.write(image, \"png\", new File(fileName));\n}\n"
},
{
"answer_id": 18156495,
"author": "11101101b",
"author_id": 875305,
"author_profile": "https://Stackoverflow.com/users/875305",
"pm_score": 4,
"selected": false,
"text": "GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\nGraphicsDevice[] screens = ge.getScreenDevices();\n\nRectangle allScreenBounds = new Rectangle();\nfor (GraphicsDevice screen : screens) {\n Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();\n\n allScreenBounds.width += screenBounds.width;\n allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);\n}\n\nRobot robot = new Robot();\nBufferedImage screenShot = robot.createScreenCapture(allScreenBounds);\n"
},
{
"answer_id": 27603992,
"author": "Nilesh Jadav",
"author_id": 3966892,
"author_profile": "https://Stackoverflow.com/users/3966892",
"pm_score": 2,
"selected": false,
"text": "import java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Rectangle;\nimport java.awt.Robot;\nimport java.awt.Toolkit;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.image.BufferedImage;\nimport java.io.File; \nimport javax.imageio.ImageIO;\nimport javax.swing.*; \n\npublic class HelloWorldFrame extends JFrame implements ActionListener {\n\nJButton b;\npublic HelloWorldFrame() {\n this.setVisible(true);\n this.setLayout(null);\n b = new JButton(\"Click Here\");\n b.setBounds(380, 290, 120, 60);\n b.setBackground(Color.red);\n b.setVisible(true);\n b.addActionListener(this);\n add(b);\n setSize(1000, 700);\n}\npublic void actionPerformed(ActionEvent e)\n{\n if (e.getSource() == b) \n {\n this.dispose();\n try {\n Thread.sleep(1000);\n Toolkit tk = Toolkit.getDefaultToolkit(); \n Dimension d = tk.getScreenSize();\n Rectangle rec = new Rectangle(0, 0, d.width, d.height); \n Robot ro = new Robot();\n BufferedImage img = ro.createScreenCapture(rec);\n File f = new File(\"myimage.jpg\");//set appropriate path\n ImageIO.write(img, \"jpg\", f);\n } catch (Exception ex) {\n System.out.println(ex.getMessage());\n }\n }\n}\n\npublic static void main(String[] args) {\n HelloWorldFrame obj = new HelloWorldFrame();\n}\n}\n"
},
{
"answer_id": 31083752,
"author": "joe pelletier",
"author_id": 4088794,
"author_profile": "https://Stackoverflow.com/users/4088794",
"pm_score": 2,
"selected": false,
"text": "GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); \nGraphicsDevice[] screens = ge.getScreenDevices(); \nRectangle allScreenBounds = new Rectangle(); \nfor (GraphicsDevice screen : screens) { \n Rectangle screenBounds = screen.getDefaultConfiguration().getBounds(); \n allScreenBounds.width += screenBounds.width; \n allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);\n allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);\n allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);\n } \nRobot robot = new Robot();\nBufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);\nFile file = new File(\"C:\\\\Users\\\\Joe\\\\Desktop\\\\scr.png\");\nif(!file.exists())\n file.createNewFile();\nFileOutputStream fos = new FileOutputStream(file);\nImageIO.write( bufferedImage, \"png\", fos );\n"
},
{
"answer_id": 45937897,
"author": "Muhammad Yawar",
"author_id": 4770992,
"author_profile": "https://Stackoverflow.com/users/4770992",
"pm_score": 0,
"selected": false,
"text": "java.awt.Robot import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\nimport java.sql.SQLException;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport javax.imageio.ImageIO;\n\npublic class ServerApp extends Thread\n{\n private ServerSocket serverSocket=null;\n private static Socket server = null;\n private Date date = null;\n private static final String DIR_NAME = \"screenshots\";\n\n public ServerApp() throws IOException, ClassNotFoundException, Exception{\n serverSocket = new ServerSocket(61000);\n serverSocket.setSoTimeout(180000);\n }\n\npublic void run()\n {\n while(true)\n {\n try\n {\n server = serverSocket.accept();\n date = new Date();\n DateFormat dateFormat = new SimpleDateFormat(\"_yyMMdd_HHmmss\");\n String fileName = server.getInetAddress().getHostName().replace(\".\", \"-\");\n System.out.println(fileName);\n BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));\n ImageIO.write(img, \"png\", new File(\"D:\\\\screenshots\\\\\"+fileName+dateFormat.format(date)+\".png\"));\n System.out.println(\"Image received!!!!\");\n //lblimg.setIcon(img);\n }\n catch(SocketTimeoutException st)\n {\n System.out.println(\"Socket timed out!\"+st.toString());\n //createLogFile(\"[stocktimeoutexception]\"+stExp.getMessage());\n break;\n }\n catch(IOException e)\n {\n e.printStackTrace();\n break;\n }\n catch(Exception ex)\n {\n System.out.println(ex);\n }\n }\n }\n\n public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{\n ServerApp serverApp = new ServerApp();\n serverApp.createDirectory(DIR_NAME);\n Thread thread = new Thread(serverApp);\n thread.start();\n }\n\nprivate void createDirectory(String dirName) {\n File newDir = new File(\"D:\\\\\"+dirName);\n if(!newDir.exists()){\n boolean isCreated = newDir.mkdir();\n }\n }\n} \n package com.viremp.client;\n\nimport java.awt.AWTException;\nimport java.awt.Dimension;\nimport java.awt.Rectangle;\nimport java.awt.Robot;\nimport java.awt.Toolkit;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\n\npublic class ClientApp implements Runnable {\n private static long nextTime = 0;\n private static ClientApp clientApp = null;\n private String serverName = \"192.168.100.18\"; //loop back ip\n private int portNo = 61000;\n //private Socket serverSocket = null;\n\n /**\n * @param args\n * @throws InterruptedException \n */\n public static void main(String[] args) throws InterruptedException {\n clientApp = new ClientApp();\n clientApp.getNextFreq();\n Thread thread = new Thread(clientApp);\n thread.start();\n }\n\n private void getNextFreq() {\n long currentTime = System.currentTimeMillis();\n Random random = new Random();\n long value = random.nextInt(180000); //1800000\n nextTime = currentTime + value;\n //return currentTime+value;\n }\n\n @Override\n public void run() {\n while(true){\n if(nextTime < System.currentTimeMillis()){\n System.out.println(\" get screen shot \");\n try {\n clientApp.sendScreen();\n clientApp.getNextFreq();\n } catch (AWTException e) {\n // TODO Auto-generated catch block\n System.out.println(\" err\"+e);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n } catch(Exception e){\n e.printStackTrace();\n }\n\n }\n //System.out.println(\" statrted ....\");\n }\n\n }\n\n private void sendScreen()throws AWTException, IOException {\n Socket serverSocket = new Socket(serverName, portNo);\n Toolkit toolkit = Toolkit.getDefaultToolkit();\n Dimension dimensions = toolkit.getScreenSize();\n Robot robot = new Robot(); // Robot class \n BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));\n ImageIO.write(screenshot,\"png\",serverSocket.getOutputStream());\n serverSocket.close();\n }\n}\n"
},
{
"answer_id": 53084575,
"author": "MisterParser",
"author_id": 3123946,
"author_profile": "https://Stackoverflow.com/users/3123946",
"pm_score": 0,
"selected": false,
"text": "DisplayMode displayMode = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode();\nRectangle screenRectangle = new Rectangle(displayMode.getWidth(), displayMode.getHeight());\nBufferedImage screenShot = new Robot().createScreenCapture(screenRectangle);\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] |
58,306 |
<p>I am trying to determine the best time efficient algorithm to accomplish the task described below.</p>
<p>I have a set of records. For this set of records I have connection data which indicates how pairs of records from this set connect to one another. This basically represents an undirected graph, with the records being the vertices and the connection data the edges.</p>
<p>All of the records in the set have connection information (i.e. no orphan records are present; each record in the set connects to one or more other records in the set).</p>
<p>I want to choose any two records from the set and be able to show all simple paths between the chosen records. By "simple paths" I mean the paths which do not have repeated records in the path (i.e. finite paths only).</p>
<p>Note: The two chosen records will always be different (i.e. start and end vertex will never be the same; no cycles).</p>
<p>For example:</p>
<pre>
If I have the following records:
A, B, C, D, E
and the following represents the connections:
(A,B),(A,C),(B,A),(B,D),(B,E),(B,F),(C,A),(C,E),
(C,F),(D,B),(E,C),(E,F),(F,B),(F,C),(F,E)
[where (A,B) means record A connects to record B]
</pre>
<p>If I chose B as my starting record and E as my ending record, I would want to find all simple paths through the record connections that would connect record B to record E.</p>
<pre>
All paths connecting B to E:
B->E
B->F->E
B->F->C->E
B->A->C->E
B->A->C->F->E
</pre>
<p>This is an example, in practice I may have sets containing hundreds of thousands of records.</p>
|
[
{
"answer_id": 58444,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "static bool[] visited;//all false\nStack<int> currentway; initialize empty\n\nfunction findnodes(int nextnode)\n{\nif (nextnode==destnode)\n{\n print currentway \n return;\n}\nvisited[nextnode]=true;\nPush nextnode to the end of currentway.\nfor each node n accesible from nextnode:\n findnodes(n);\nvisited[nextnode]=false; \npop from currenteay\n}\n"
},
{
"answer_id": 58446,
"author": "Casey Watson",
"author_id": 4682,
"author_profile": "https://Stackoverflow.com/users/4682",
"pm_score": 8,
"selected": true,
"text": "import java.util.HashMap;\nimport java.util.LinkedHashSet;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Graph {\n private Map<String, LinkedHashSet<String>> map = new HashMap();\n\n public void addEdge(String node1, String node2) {\n LinkedHashSet<String> adjacent = map.get(node1);\n if(adjacent==null) {\n adjacent = new LinkedHashSet();\n map.put(node1, adjacent);\n }\n adjacent.add(node2);\n }\n\n public void addTwoWayVertex(String node1, String node2) {\n addEdge(node1, node2);\n addEdge(node2, node1);\n }\n\n public boolean isConnected(String node1, String node2) {\n Set adjacent = map.get(node1);\n if(adjacent==null) {\n return false;\n }\n return adjacent.contains(node2);\n }\n\n public LinkedList<String> adjacentNodes(String last) {\n LinkedHashSet<String> adjacent = map.get(last);\n if(adjacent==null) {\n return new LinkedList();\n }\n return new LinkedList<String>(adjacent);\n }\n}\n import java.util.LinkedList;\n\npublic class Search {\n\n private static final String START = \"B\";\n private static final String END = \"E\";\n\n public static void main(String[] args) {\n // this graph is directional\n Graph graph = new Graph();\n graph.addEdge(\"A\", \"B\");\n graph.addEdge(\"A\", \"C\");\n graph.addEdge(\"B\", \"A\");\n graph.addEdge(\"B\", \"D\");\n graph.addEdge(\"B\", \"E\"); // this is the only one-way connection\n graph.addEdge(\"B\", \"F\");\n graph.addEdge(\"C\", \"A\");\n graph.addEdge(\"C\", \"E\");\n graph.addEdge(\"C\", \"F\");\n graph.addEdge(\"D\", \"B\");\n graph.addEdge(\"E\", \"C\");\n graph.addEdge(\"E\", \"F\");\n graph.addEdge(\"F\", \"B\");\n graph.addEdge(\"F\", \"C\");\n graph.addEdge(\"F\", \"E\");\n LinkedList<String> visited = new LinkedList();\n visited.add(START);\n new Search().depthFirst(graph, visited);\n }\n\n private void depthFirst(Graph graph, LinkedList<String> visited) {\n LinkedList<String> nodes = graph.adjacentNodes(visited.getLast());\n // examine adjacent nodes\n for (String node : nodes) {\n if (visited.contains(node)) {\n continue;\n }\n if (node.equals(END)) {\n visited.add(node);\n printPath(visited);\n visited.removeLast();\n break;\n }\n }\n for (String node : nodes) {\n if (visited.contains(node) || node.equals(END)) {\n continue;\n }\n visited.addLast(node);\n depthFirst(graph, visited);\n visited.removeLast();\n }\n }\n\n private void printPath(LinkedList<String> visited) {\n for (String node : visited) {\n System.out.print(node);\n System.out.print(\" \");\n }\n System.out.println();\n }\n}\n B E \nB A C E \nB A C F E \nB F E \nB F C E \n"
},
{
"answer_id": 58507,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 0,
"selected": false,
"text": "(A,B) (A,C) (B,C) (B,D) (C,D) ABD ACD ABCD"
},
{
"answer_id": 4375881,
"author": "Vjeux",
"author_id": 232122,
"author_profile": "https://Stackoverflow.com/users/232122",
"pm_score": 0,
"selected": false,
"text": "Definition\n Atomic Paths A -> B\n Freeing the list\n Atomic Cycle A\n"
},
{
"answer_id": 8263753,
"author": "Haibin Liu",
"author_id": 1064820,
"author_profile": "https://Stackoverflow.com/users/1064820",
"pm_score": 3,
"selected": false,
"text": "public class Search {\n\nprivate static final String START = \"B\";\nprivate static final String END = \"E\";\n\npublic static void main(String[] args) {\n // this graph is directional\n Graph graph = new Graph();\n graph.addEdge(\"A\", \"B\");\n graph.addEdge(\"A\", \"C\");\n graph.addEdge(\"B\", \"A\");\n graph.addEdge(\"B\", \"D\");\n graph.addEdge(\"B\", \"E\"); // this is the only one-way connection\n graph.addEdge(\"B\", \"F\");\n graph.addEdge(\"C\", \"A\");\n graph.addEdge(\"C\", \"E\");\n graph.addEdge(\"C\", \"F\");\n graph.addEdge(\"D\", \"B\");\n graph.addEdge(\"E\", \"C\");\n graph.addEdge(\"E\", \"F\");\n graph.addEdge(\"F\", \"B\");\n graph.addEdge(\"F\", \"C\");\n graph.addEdge(\"F\", \"E\");\n List<ArrayList<String>> paths = new ArrayList<ArrayList<String>>();\n String currentNode = START;\n List<String> visited = new ArrayList<String>();\n visited.add(START);\n new Search().findAllPaths(graph, seen, paths, currentNode);\n for(ArrayList<String> path : paths){\n for (String node : path) {\n System.out.print(node);\n System.out.print(\" \");\n }\n System.out.println();\n } \n}\n\nprivate void findAllPaths(Graph graph, List<String> visited, List<ArrayList<String>> paths, String currentNode) { \n if (currentNode.equals(END)) { \n paths.add(new ArrayList(Arrays.asList(visited.toArray())));\n return;\n }\n else {\n LinkedList<String> nodes = graph.adjacentNodes(currentNode); \n for (String node : nodes) {\n if (visited.contains(node)) {\n continue;\n } \n List<String> temp = new ArrayList<String>();\n temp.addAll(visited);\n temp.add(node); \n findAllPaths(graph, temp, paths, node);\n }\n }\n}\n}\n B A C E \n\nB A C F E \n\nB E\n\nB F C E\n\nB F E \n"
},
{
"answer_id": 9247432,
"author": "Leon Chang",
"author_id": 1204860,
"author_profile": "https://Stackoverflow.com/users/1204860",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <stdbool.h>\n\n#define maxN 20 \n\nstruct nodeLink\n{\n\n char node1;\n char node2;\n\n};\n\nstruct stack\n{ \n int sp;\n char node[maxN];\n}; \n\nvoid initStk(stk)\nstruct stack *stk;\n{\n int i;\n for (i = 0; i < maxN; i++)\n stk->node[i] = ' ';\n stk->sp = -1; \n}\n\nvoid pushIn(stk, node)\nstruct stack *stk;\nchar node;\n{\n\n stk->sp++;\n stk->node[stk->sp] = node;\n\n} \n\nvoid popOutAll(stk)\nstruct stack *stk;\n{\n\n char node;\n int i, stkN = stk->sp;\n\n for (i = 0; i <= stkN; i++)\n {\n node = stk->node[i];\n if (i == 0)\n printf(\"src node : %c\", node);\n else if (i == stkN)\n printf(\" => %c : dst node.\\n\", node);\n else\n printf(\" => %c \", node);\n }\n\n}\n\n\n/* Test whether the node already exists in the stack */\nbool InStack(stk, InterN)\nstruct stack *stk;\nchar InterN;\n{\n\n int i, stkN = stk->sp; /* 0-based */\n bool rtn = false; \n\n for (i = 0; i <= stkN; i++)\n {\n if (stk->node[i] == InterN)\n {\n rtn = true;\n break;\n }\n }\n\n return rtn;\n\n}\n\nchar otherNode(targetNode, lnkNode)\nchar targetNode;\nstruct nodeLink *lnkNode;\n{\n\n return (lnkNode->node1 == targetNode) ? lnkNode->node2 : lnkNode->node1;\n\n}\n\nint entries = 8;\nstruct nodeLink topo[maxN] = \n {\n {'b', 'a'}, \n {'b', 'e'}, \n {'b', 'd'}, \n {'f', 'b'}, \n {'a', 'c'},\n {'c', 'f'}, \n {'c', 'e'},\n {'f', 'e'}, \n };\n\nchar srcNode = 'b', dstN = 'e'; \n\nint reachTime; \n\nvoid InterNode(interN, stk)\nchar interN;\nstruct stack *stk;\n{\n\n char otherInterN;\n int i, numInterN = 0;\n static int entryTime = 0;\n\n entryTime++;\n\n for (i = 0; i < entries; i++)\n {\n\n if (topo[i].node1 != interN && topo[i].node2 != interN) \n {\n continue; \n }\n\n otherInterN = otherNode(interN, &topo[i]);\n\n numInterN++;\n\n if (otherInterN == stk->node[stk->sp - 1])\n {\n continue; \n }\n\n /* Loop avoidance: abandon the route */\n if (InStack(stk, otherInterN) == true)\n {\n continue; \n }\n\n pushIn(stk, otherInterN);\n\n if (otherInterN == dstN)\n {\n popOutAll(stk);\n reachTime++;\n stk->sp --; /* back trace one node */\n continue;\n }\n else\n InterNode(otherInterN, stk);\n\n }\n\n stk->sp --;\n\n}\n\n\nint main()\n\n{\n\n struct stack stk;\n\n initStk(&stk);\n pushIn(&stk, srcNode); \n\n reachTime = 0;\n InterNode(srcNode, &stk);\n\n printf(\"\\nNumber of all possible and unique routes = %d\\n\", reachTime);\n\n}\n"
},
{
"answer_id": 25013511,
"author": "Avinash",
"author_id": 3116634,
"author_profile": "https://Stackoverflow.com/users/3116634",
"pm_score": 1,
"selected": false,
"text": "/* Checking Connection Between Two Edges */\n\n#include<stdio.h>\n#include<stdlib.h>\n#define MAX 100\n\n/*\n Data structure used\n\nvertex[] - used to Store The vertices\nsize - No. of vertices\nsz[] - size of child's\n*/\n\n/*Function Declaration */\nvoid initalize(int *vertex, int *sz, int size);\nint root(int *vertex, int i);\nvoid add(int *vertex, int *sz, int p, int q);\nint connected(int *vertex, int p, int q);\n\nint main() //Main Function\n{ \nchar filename[50], ch, ch1[MAX];\nint temp = 0, *vertex, first = 0, node1, node2, size = 0, *sz;\nFILE *fp;\n\n\nprintf(\"Enter the filename - \"); //Accept File Name\nscanf(\"%s\", filename);\nfp = fopen(filename, \"r\");\nif (fp == NULL)\n{\n printf(\"File does not exist\");\n exit(1);\n}\nwhile (1)\n{\n if (first == 0) //getting no. of vertices\n {\n ch = getc(fp);\n if (temp == 0)\n {\n fseek(fp, -1, 1);\n fscanf(fp, \"%s\", &ch1);\n fseek(fp, 1, 1);\n temp = 1;\n }\n if (isdigit(ch))\n {\n size = atoi(ch1);\n vertex = (int*) malloc(size * sizeof(int)); //dynamically allocate size \n sz = (int*) malloc(size * sizeof(int));\n initalize(vertex, sz, size); //initialization of vertex[] and sz[]\n }\n if (ch == '\\n')\n {\n first = 1;\n temp = 0;\n }\n }\n else\n {\n ch = fgetc(fp);\n if (isdigit(ch))\n temp = temp * 10 + (ch - 48); //calculating value from ch\n else\n {\n /* Validating the file */\n\n if (ch != ',' && ch != '\\n' && ch != EOF)\n {\n printf(\"\\n\\nUnkwown Character Detected.. Exiting..!\");\n\n exit(1);\n }\n if (ch == ',')\n node1 = temp;\n else\n {\n node2 = temp;\n printf(\"\\n\\n%d\\t%d\", node1, node2);\n if (node1 > node2)\n {\n temp = node1;\n node1 = node2;\n node2 = temp;\n }\n\n /* Adding the input nodes */\n\n if (!connected(vertex, node1, node2))\n add(vertex, sz, node1, node2);\n }\n temp = 0;\n }\n\n if (ch == EOF)\n {\n fclose(fp);\n break;\n }\n }\n}\n\ndo\n{\n printf(\"\\n\\n==== check if connected ===\");\n printf(\"\\nEnter First Vertex:\");\n scanf(\"%d\", &node1);\n printf(\"\\nEnter Second Vertex:\");\n scanf(\"%d\", &node2);\n\n /* Validating The Input */\n\n if( node1 > size || node2 > size )\n {\n printf(\"\\n\\n Invalid Node Value..\");\n break;\n }\n\n /* Checking the connectivity of nodes */\n\n if (connected(vertex, node1, node2))\n printf(\"Vertex %d and %d are Connected..!\", node1, node2);\n else\n printf(\"Vertex %d and %d are Not Connected..!\", node1, node2);\n\n\n printf(\"\\n 0/1: \");\n\n scanf(\"%d\", &temp);\n\n} while (temp != 0);\n\nfree((void*) vertex);\nfree((void*) sz);\n\n\nreturn 0;\n}\n\nvoid initalize(int *vertex, int *sz, int size) //Initialization of graph\n{\nint i;\nfor (i = 0; i < size; i++)\n{\n vertex[i] = i;\n sz[i] = 0;\n}\n}\nint root(int *vertex, int i) //obtaining the root\n{\nwhile (i != vertex[i])\n{\n vertex[i] = vertex[vertex[i]];\n i = vertex[i];\n}\nreturn i;\n}\n\n/* Time Complexity for Add --> logn */\nvoid add(int *vertex, int *sz, int p, int q) //Adding of node\n{\nint i, j;\ni = root(vertex, p);\nj = root(vertex, q);\n\n/* Adding small subtree in large subtree */\n\nif (sz[i] < sz[j])\n{\n vertex[i] = j;\n sz[j] += sz[i];\n}\nelse\n{\n vertex[j] = i;\n sz[i] += sz[j];\n}\n\n}\n\n/* Time Complexity for Search -->lg* n */\n\nint connected(int *vertex, int p, int q) //Checking of connectivity of nodes\n{\n/* Checking if root is same */\n\nif (root(vertex, p) == root(vertex, q))\n return 1;\n\nreturn 0;\n}\n"
},
{
"answer_id": 26429707,
"author": "batta",
"author_id": 444047,
"author_profile": "https://Stackoverflow.com/users/444047",
"pm_score": 2,
"selected": false,
"text": " void DepthFirstIterative(T start, T endNode)\n {\n var visited = new LinkedList<T>();\n var stack = new Stack<T>();\n\n stack.Push(start);\n\n while (stack.Count != 0)\n {\n var current = stack.Pop();\n\n if (visited.Contains(current))\n continue;\n\n visited.AddLast(current);\n\n var neighbours = AdjacentNodes(current);\n\n foreach (var neighbour in neighbours)\n {\n if (visited.Contains(neighbour))\n continue;\n\n if (neighbour.Equals(endNode))\n {\n visited.AddLast(neighbour);\n printPath(visited));\n visited.RemoveLast();\n break;\n }\n }\n\n bool isPushed = false;\n foreach (var neighbour in neighbours.Reverse())\n {\n if (neighbour.Equals(endNode) || visited.Contains(neighbour) || stack.Contains(neighbour))\n {\n continue;\n }\n\n isPushed = true;\n stack.Push(neighbour);\n }\n\n if (!isPushed)\n visited.RemoveLast();\n }\n }\n"
},
{
"answer_id": 35531270,
"author": "Ilmari Karonen",
"author_id": 411022,
"author_profile": "https://Stackoverflow.com/users/411022",
"pm_score": 3,
"selected": false,
"text": "yield # a generator function to find all simple paths between two nodes in a\n# graph, represented as a dictionary that maps nodes to their neighbors\ndef find_simple_paths(graph, start, end):\n visited = set()\n visited.add(start)\n\n nodestack = list()\n indexstack = list()\n current = start\n i = 0\n\n while True:\n # get a list of the neighbors of the current node\n neighbors = graph[current]\n\n # find the next unvisited neighbor of this node, if any\n while i < len(neighbors) and neighbors[i] in visited: i += 1\n\n if i >= len(neighbors):\n # we've reached the last neighbor of this node, backtrack\n visited.remove(current)\n if len(nodestack) < 1: break # can't backtrack, stop!\n current = nodestack.pop()\n i = indexstack.pop()\n elif neighbors[i] == end:\n # yay, we found the target node! let the caller process the path\n yield nodestack + [current, end]\n i += 1\n else:\n # push current node and index onto stacks, switch to neighbor\n nodestack.append(current)\n indexstack.append(i+1)\n visited.add(neighbors[i])\n current = neighbors[i]\n i = 0\n visited visited # test graph:\n# ,---B---.\n# A | D\n# `---C---'\ngraph = {\n \"A\": (\"B\", \"C\"),\n \"B\": (\"A\", \"C\", \"D\"),\n \"C\": (\"A\", \"B\", \"D\"),\n \"D\": (\"B\", \"C\"),\n}\n\n# find paths from A to D\nfor path in find_simple_paths(graph, \"A\", \"D\"): print \" -> \".join(path)\n C -> B B C A -> C -> B -> D graph = {\n \"A\": (\"B\", \"C\"),\n \"B\": (\"A\"),\n \"C\": (\"A\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"D\": (\"C\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"E\": (\"C\", \"D\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"F\": (\"C\", \"D\", \"E\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"G\": (\"C\", \"D\", \"E\", \"F\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"H\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"I\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"J\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"K\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"L\", \"M\", \"N\", \"O\"),\n \"L\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"M\", \"N\", \"O\"),\n \"M\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"N\", \"O\"),\n \"N\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"O\"),\n \"O\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\"),\n}\n"
},
{
"answer_id": 39172826,
"author": "Jamshed Katta",
"author_id": 4314880,
"author_profile": "https://Stackoverflow.com/users/4314880",
"pm_score": 0,
"selected": false,
"text": "private void getPaths(Graph graph, LinkedList<String> visitedNodes) {\n LinkedList<String> adjacent = graph.getAdjacent(visitedNodes.getLast());\n for(String node : adjacent){\n if(visitedNodes.contains(node)){\n continue;\n }\n if(node.equals(END)){\n visitedNodes.add(node);\n printPath(visitedNodes);\n visitedNodes.removeLast();\n }\n visitedNodes.add(node);\n getPaths(graph, visitedNodes);\n visitedNodes.removeLast(); \n }\n }\n"
},
{
"answer_id": 42600378,
"author": "SumNeuron",
"author_id": 5623899,
"author_profile": "https://Stackoverflow.com/users/5623899",
"pm_score": 1,
"selected": false,
"text": "find_paths[s, t, d, k] d k s t find_paths[s, t, d, k] <join> find_paths[t, s, d, k]\n def find_paths_recursion(graph, current, goal, current_depth, max_depth, num_paths, current_path, paths_found)\n current_path.append(current)\n\n if current_depth > max_depth:\n return\n\n if current == goal:\n if len(paths_found) <= number_of_paths_to_find:\n paths_found.append(copy(current_path))\n\n current_path.pop()\n return\n\n else:\n for successor in graph[current]:\n self.find_paths_recursion(graph, successor, goal, current_depth + 1, max_depth, num_paths, current_path, paths_found)\n\n current_path.pop()\n def find_paths[s, t, d, k]:\n paths_found = [] # PASSING THIS BY REFERENCE \n find_paths_recursion(s, t, 0, d, k, [], paths_found)\n [] paths_found graph hashed graph[vertex]"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3534/"
] |
58,340 |
<p>Using win forms with an <a href="http://en.wikipedia.org/wiki/Model-view-controller" rel="noreferrer">MVC</a>/<a href="http://msdn.microsoft.com/en-us/magazine/cc188690.aspx" rel="noreferrer">MVP</a> architecture, I would normally use a class to wrap a view to test the UI while using mocks for the model and controller/presenter. The wrapper class would make most everything in the UI an observable property for the test runner through properties and events.</p>
<p>Would this be a viable approach to testing a WPF app? Is there a better way? Are there any gotchas to watch out for?</p>
|
[
{
"answer_id": 40271736,
"author": "Justas",
"author_id": 407108,
"author_profile": "https://Stackoverflow.com/users/407108",
"pm_score": 4,
"selected": false,
"text": "using TestStack.White;\nusing TestStack.White.UIItems;\nusing TestStack.White.Factory;\n\n[TestMethod]\npublic void TestDoSomething()\n{\n //Opens the app\n var app = Application.Launch(\"MyApp.exe\");\n\n //Finds the main window (this and above line should be in [TestInitialize])\n var window = app.GetWindow(\"My App Window Title\", InitializeOption.NoCache);\n\n //Finds the button (see other Get...() methods for options)\n var btnMyButton = window.Get<Button>(\"btnMyButtonWPFname\");\n\n //Simulate clicking\n btnMyButton.Click();\n\n //Gets the result text box \n //Note: TextBox/Button is in TestStack.White.UIItems namespace\n var txtMyTextBox = window.Get<TextBox>(\"txtMyTextBox\");\n\n //Check for the result\n Assert.IsTrue(txtMyTextBox.Text == \"my expected result\");\n\n //Close the main window and the app (preferably in [TestCleanup])\n app.Close();\n}\n"
},
{
"answer_id": 57088744,
"author": "HHenn",
"author_id": 2003805,
"author_profile": "https://Stackoverflow.com/users/2003805",
"pm_score": 3,
"selected": false,
"text": " public class DesktopSession\n {\n protected const string WindowsApplicationDriverUrl = \"http://127.0.0.1:4723\";\n private const string NotepadAppId = @\"C:\\Windows\\System32\\notepad.exe\";\n \n protected static WindowsDriver<WindowsElement> session;\n protected static WindowsElement editBox;\n \n public static void Setup(TestContext context)\n {\n // Launch a new instance of Notepad application\n if (session == null)\n {\n // Create a new session to launch Notepad application\n var appCapabilities = new DesiredCapabilities();\n appCapabilities.SetCapability(\"app\", NotepadAppId);\n appCapabilities.SetCapability(\"platformName\", \"Windows\");\n appCapabilities.SetCapability(\"deviceName \", \"WindowsPC\");\n session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);\n Assert.IsNotNull(session);\n Assert.IsNotNull(session.SessionId);\n \n // Set implicit timeout to 1.5 seconds to make element search to retry every 500 ms for at most three times\n session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1.5);\n \n // Keep track of the edit box to be used throughout the session\n editBox = session.FindElementByClassName(\"Edit\");\n Assert.IsNotNull(editBox);\n }\n }\n \n public static void TearDown()\n {\n // Close the application and delete the session\n if (session != null)\n {\n session.Close();\n \n try\n {\n // Dismiss Save dialog if it is blocking the exit\n session.FindElementByName(\"Nicht speichern\").Click();\n }\n catch { }\n \n session.Quit();\n session = null;\n }\n }\n \n [TestInitialize]\n public void TestInitialize()\n {\n // Select all text and delete to clear the edit box\n editBox.SendKeys(Keys.Control + \"a\" + Keys.Control);\n editBox.SendKeys(Keys.Delete);\n Assert.AreEqual(string.Empty, editBox.Text);\n }\n } \n [TestClass]\n public class UnitTest1 : DesktopSession\n {\n [TestMethod]\n public void EditorEnterText()\n {\n Thread.Sleep(TimeSpan.FromSeconds(2));\n editBox.SendKeys(\"abcdeABCDE 12345\");\n Assert.AreEqual(@\"abcdeABCDE 12345\", editBox.Text);\n }\n \n [ClassInitialize]\n public static void ClassInitialize(TestContext context)\n {\n Setup(context);\n }\n \n [ClassCleanup]\n public static void ClassCleanup()\n {\n TearDown();\n }\n }\n C:\\Program Files\\Appium\\resources\\app\\node_modules\\appium\\node_modules\\appium-windows-driver\\lib\\installer.js\n const WAD_VER = \"1.1\";\nconst WAD_DL = `https://github.com/Microsoft/WinAppDriver/releases/download/v${WAD_VER}/WindowsApplicationDriver.msi`;\n protected const string WindowsApplicationDriverUrl = \"http://127.0.0.1:4723/wd/hub\";\n"
},
{
"answer_id": 63287686,
"author": "Lev",
"author_id": 3087417,
"author_profile": "https://Stackoverflow.com/users/3087417",
"pm_score": 3,
"selected": false,
"text": "using FlaUI.Core;\nusing FlaUI.Core.AutomationElements;\nusing FlaUI.UIA3;\nusing FluentAssertions;\nusing System;\nusing Xunit;\n\nnamespace Functional\n{\n public sealed class General : IDisposable\n {\n private readonly Application _app = Application.Launch(@\"..\\App.exe\");\n\n [Fact]\n public void AppStarts()\n {\n using var automation = new UIA3Automation();\n Window window = _app.GetMainWindow(automation, TimeSpan.FromSeconds(3));\n\n window.Should().NotBeNull(\"null means the window failed to load\");\n\n window.Title.Should().Be(\"App title\",\n \"otherwise, it could be message box with error in case of the wrong configuration\");\n }\n\n public void Dispose()\n {\n _app.Close();\n _app.Dispose();\n }\n }\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3826/"
] |
58,354 |
<p>What are some simple algorithm or data structure related "white boarding" problems that you find effective during the candidate screening process?</p>
<p>I have some simple ones that I use to validate problem solving skills and that can be simply expressed but have some opportunity for the application of some heuristics.</p>
<p>One of the basics that I use for junior developers is:</p>
<blockquote>
<p>Write a C# method that takes a string which contains a set of words (a sentence) and rotates those words X number of places to the right. When a word in the last position of the sentence is rotated it should show up at the front of the resulting string.</p>
</blockquote>
<p>When a candidate answers this question I look to see that they available .NET data structures and methods (string.Join, string.Split, List, etc...) to solve the problem. I also look for them to identify special cases for optimization. Like the number of times that the words need to be rotated isn't really X it's X % number of words.</p>
<p>What are some of the white board problems that you use to interview a candidate and what are some of the things you look for in an answer (do not need to post the actual answer).</p>
|
[
{
"answer_id": 90047,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 2,
"selected": false,
"text": "# @a and @b are two arrays which are already populated.\nmy @int;\nOUTER: for my $x (@a) {\n for my $y (@b) {\n if ($x eq $y) {\n push @int, $x;\n next OUTER;\n }\n }\n}\n @a = qw(\n hello\n world\n hello\n goodbye\n earthlings\n);\n@b = qw(\n earthlings\n say\n hello\n earthlings\n);\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
58,380 |
<p>The following bit of code catches the EOS Exception</p>
<pre><code>using (var reader = new BinaryReader(httpRequestBodyStream)) {
try {
while (true) {
bodyByteList.Add(reader.ReadByte());
}
} catch (EndOfStreamException) { }
}
</code></pre>
<p>So why do I still receive first-chance exceptions in my console? </p>
<blockquote>
<p>A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll</p>
</blockquote>
<p>Is there a way to hide these first chance exception messages?</p>
|
[
{
"answer_id": 58409,
"author": "loudej",
"author_id": 6056,
"author_profile": "https://Stackoverflow.com/users/6056",
"pm_score": 4,
"selected": false,
"text": "while (reader.PeekChar() != -1)\n{\n bodyByteList.Add(reader.ReadByte());\n}\n"
},
{
"answer_id": 1247084,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<DebuggerHidden()> _\nPublic Function Write(ByVal Text As String) As Boolean\n ...\n"
},
{
"answer_id": 23159773,
"author": "VoteCoffee",
"author_id": 848419,
"author_profile": "https://Stackoverflow.com/users/848419",
"pm_score": 2,
"selected": false,
"text": "Friend Sub AddTheHandler()\nAddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf FirstChanceExceptionHandler\nEnd Sub\n\n<Conditional(\"DEBUG\")>\nFriend Sub FirstChanceExceptionHandler( source As Object, e As Runtime.ExceptionServices.FirstChanceExceptionEventArgs)\n' Process first chance exception\n\nEnd Sub\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
] |
58,384 |
<p>I am facing a problem with .NET generics. The thing I want to do is saving an array of generics types (GraphicsItem):</p>
<pre><code>public class GraphicsItem<T>
{
private T _item;
public void Load(T item)
{
_item = item;
}
}
</code></pre>
<p>How can I save such open generic type in an array?</p>
|
[
{
"answer_id": 58406,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 0,
"selected": false,
"text": "static void foo()\n{\n var _bar = List<GraphicsItem<T>>();\n}\n static GraphicsItem<T>[] CreateArrays<T>()\n{\n GraphicsItem<T>[] _foo = new GraphicsItem<T>[1];\n\n // This can't work, because you don't know if T == typeof(string)\n // _foo[0] = (GraphicsItem<T>)new GraphicsItem<string>();\n\n // You can only create an array of the scoped type parameter T\n _foo[0] = new GraphicsItem<T>();\n\n List<GraphicsItem<T>> _bar = new List<GraphicsItem<T>>();\n\n // Again same reason as above\n // _bar.Add(new GraphicsItem<string>());\n\n // This works\n _bar.Add(new GraphicsItem<T>());\n\n return _bar.ToArray();\n}\n"
},
{
"answer_id": 58462,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 3,
"selected": true,
"text": "public class GraphicsItem<T> : IGraphicsItem\n{\n private T _item;\n\n public void Load(T item)\n {\n _item = item;\n }\n\n public void SomethingWhichIsNotGeneric(int i)\n {\n // Code goes here...\n }\n}\n\npublic interface IGraphicsItem\n{\n void SomethingWhichIsNotGeneric(int i);\n}\n var values = new List<IGraphicsItem>();\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2078/"
] |
58,399 |
<p>I love the way Mac OS <em>beautifully</em> renders fonts (not just browsers). I was wondering if we could somehow get the same rendering in browsers running on Windows?</p>
<p>Someone recommended sIFR but I guess that's useful when I need to use non-standard fonts?</p>
|
[
{
"answer_id": 2573130,
"author": "William",
"author_id": 213197,
"author_profile": "https://Stackoverflow.com/users/213197",
"pm_score": 0,
"selected": false,
"text": "g.setFont(new Font(\"Century Schoolbook\", Font.PLAIN, 36));\ng.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,\n RenderingHints.VALUE_FRACTIONALMETRICS_ON);\ng.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6059/"
] |
58,425 |
<p>I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException".</p>
<p>The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception."</p>
<p>Here is my app.xaml:</p>
<pre><code><Application x:Class="MyNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
</Application.Resources>
</Application>
</code></pre>
<p>And here is my app.xaml.cs (exception thrown at "public App()"):</p>
<pre><code>public partial class App : Application
{
public App()
{
Bootstrapper bootStrapper = new Bootstrapper();
bootStrapper.Run();
}
}
</code></pre>
<p>I have set the "App" class as the startup object in the project.</p>
<p>What is going astray?</p>
|
[
{
"answer_id": 58464,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 6,
"selected": true,
"text": "<configuration>\n <startup>\n <supportedRuntime version=\"v2.0.50727\" sku=\"Client\"/>\n </startup>\n <configSections>\n <section name=\"modules\" type=\"Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite\"/>\n </configSections>\n <modules>\n <module assemblyFile=\"Modules/MyNamespace.Modules.ModuleName.dll\" moduleType=\"MyNamespace.Modules.ModuleName.ModuleClass\" moduleName=\"Name\"/>\n </modules>\n</configuration>\n <configuration>\n <configSections>\n <section name=\"modules\" type=\"Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite\"/>\n </configSections>\n <modules>\n <module assemblyFile=\"Modules/MyNamespace.Modules.ModuleName.dll\" moduleType=\"MyNamespace.Modules.ModuleName.ModuleClass\" moduleName=\"Name\"/>\n </modules>\n <startup>\n <supportedRuntime version=\"v2.0.50727\" sku=\"Client\"/>\n </startup>\n</configuration>\n"
},
{
"answer_id": 14492905,
"author": "Lin Song Yang",
"author_id": 247011,
"author_profile": "https://Stackoverflow.com/users/247011",
"pm_score": 4,
"selected": false,
"text": "* ...</startup> ...</startup>*"
},
{
"answer_id": 36924610,
"author": "usefulBee",
"author_id": 2093880,
"author_profile": "https://Stackoverflow.com/users/2093880",
"pm_score": 2,
"selected": false,
"text": "\"Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element\""
},
{
"answer_id": 42322164,
"author": "Denis Kirin",
"author_id": 7191785,
"author_profile": "https://Stackoverflow.com/users/7191785",
"pm_score": 0,
"selected": false,
"text": "<configSections>\n<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->\n<section name=\"entityFramework\" type=\"System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" />\n"
},
{
"answer_id": 63356436,
"author": "Sely Lychee",
"author_id": 5128530,
"author_profile": "https://Stackoverflow.com/users/5128530",
"pm_score": 0,
"selected": false,
"text": "<startup>\n<supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.6.1\" />\n</startup>\n\n<configSections>\n<section name=\"entityFramework\" type=\"System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" />\n<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->\n</configSections>\n <configSections>\n<section name=\"entityFramework\" type=\"System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" />\n<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->\n</configSections>\n\n<startup>\n<supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.6.1\" />\n</startup>\n"
},
{
"answer_id": 70990589,
"author": "AviB",
"author_id": 4653372,
"author_profile": "https://Stackoverflow.com/users/4653372",
"pm_score": 0,
"selected": false,
"text": "System.TypeInitializationException\n HResult=0x80131534\n Message=The type initializer for 'System.Windows.Application' threw an exception.\n Source=PresentationFramework\n StackTrace:\n at System.Windows.Application..ctor()\n at ShortBarDetectionSystem.App..ctor()\n at ShortBarDetectionSystem.App.Main()\n\nInner Exception 1:\nTypeInitializationException: The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception.\n\nInner Exception 2:\nTypeInitializationException: The type initializer for 'MS.Internal.TraceDependencyProperty' threw an exception.\n\nInner Exception 3:\nConfigurationErrorsException: Configuration system failed to initialize\n\nInner Exception 4:\nConfigurationErrorsException: Section or group name 'oracle.manageddataaccess.client' is already defined. Updates to this may only occur at the configuration level where it is defined. (C:\\ShortBarDetectionSystem\\code\\framework\\TypeInitializationException\\ver0_1\\ShortBarDetectionSystem\\ShortBarDetectionSystem\\bin\\x64\\Debug\\GrateBarDefectDetectionSystem.exe.Config line 4)\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <configSections>\n <section name=\"oracle.manageddataaccess.client\" type=\"OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342\" />\n </configSections>\n <startup>\n <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.7.2\" />\n </startup>\n <system.data>\n <DbProviderFactories>\n <remove invariant=\"Oracle.ManagedDataAccess.Client\" />\n <add name=\"ODP.NET, Managed Driver\" invariant=\"Oracle.ManagedDataAccess.Client\" description=\"Oracle Data Provider for .NET, Managed Driver\" type=\"Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342\" />\n </DbProviderFactories>\n </system.data>\n <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"System.Runtime.CompilerServices.Unsafe\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-6.0.0.0\" newVersion=\"6.0.0.0\" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"System.Text.Json\" publicKeyToken=\"cc7b13ffcd2ddd51\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-6.0.0.0\" newVersion=\"6.0.0.0\" />\n </dependentAssembly>\n </assemblyBinding>\n </runtime>\n</configuration>\n <configSections>\n <section name=\"oracle.manageddataaccess.client\" type=\"OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342\" />\n </configSections>\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148/"
] |
58,429 |
<p>How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop.<p>
I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range.
<p>For example, if I had that table I could make a select to find the sum of numbers 100-200 like this:</p>
<pre><code>select sum(n) from numbers where n between 100 and 200
</code></pre>
<p>Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay.</p>
<p>[Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. <a href="https://stackoverflow.com/questions/58429/sql-set-based-range#59657">See below.</a></p>
|
[
{
"answer_id": 59314,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 4,
"selected": true,
"text": "WITH\n digits AS -- Limit recursion by just using it for digits.\n (SELECT\n LEVEL - 1 AS num\n FROM\n DUAL\n WHERE\n LEVEL < 10\n CONNECT BY\n num = (PRIOR num) + 1),\n numrange AS\n (SELECT\n ones.num\n + (tens.num * 10)\n + (hundreds.num * 100)\n AS num\n FROM\n digits ones\n CROSS JOIN\n digits tens\n CROSS JOIN\n digits hundreds\n WHERE\n hundreds.num in (1, 2)) -- Use the WHERE clause to restrict each digit as needed.\nSELECT\n -- Some columns and operations\nFROM\n numrange\n -- Join to other data if needed\n"
},
{
"answer_id": 59657,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 2,
"selected": false,
"text": "SELECT n FROM dbo.Range(1, 11, 2) -- returns odd integers 1 to 11\nSELECT n FROM dbo.RangeF(3.1, 3.5, 0.1) -- returns 3.1, 3.2, 3.3 and 3.4, but not 3.5 because of float inprecision. !fault(this)\n using System;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Collections;\n\n[assembly: CLSCompliant(true)]\nnamespace Range {\n public static partial class UserDefinedFunctions {\n [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = \"FillRow\", TableDefinition = \"n bigint\")]\n public static IEnumerable Range(SqlInt64 start, SqlInt64 end, SqlInt64 incr) {\n return new Ranger(start.Value, end.Value, incr.Value);\n }\n\n [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = \"FillRowF\", TableDefinition = \"n float\")]\n public static IEnumerable RangeF(SqlDouble start, SqlDouble end, SqlDouble incr) {\n return new RangerF(start.Value, end.Value, incr.Value);\n }\n\n public static void FillRow(object row, out SqlInt64 n) {\n n = new SqlInt64((long)row);\n }\n\n public static void FillRowF(object row, out SqlDouble n) {\n n = new SqlDouble((double)row);\n }\n }\n\n internal class Ranger : IEnumerable {\n Int64 _start, _end, _incr;\n\n public Ranger(Int64 start, Int64 end, Int64 incr) {\n _start = start; _end = end; _incr = incr;\n }\n\n public IEnumerator GetEnumerator() {\n return new RangerEnum(_start, _end, _incr);\n }\n }\n\n internal class RangerF : IEnumerable {\n double _start, _end, _incr;\n\n public RangerF(double start, double end, double incr) {\n _start = start; _end = end; _incr = incr;\n }\n\n public IEnumerator GetEnumerator() {\n return new RangerFEnum(_start, _end, _incr);\n }\n }\n\n internal class RangerEnum : IEnumerator {\n Int64 _cur, _start, _end, _incr;\n bool hasFetched = false;\n\n public RangerEnum(Int64 start, Int64 end, Int64 incr) {\n _start = _cur = start; _end = end; _incr = incr;\n if ((_start < _end ^ _incr > 0) || _incr == 0)\n throw new ArgumentException(\"Will never reach end!\");\n }\n\n public long Current {\n get { hasFetched = true; return _cur; }\n }\n\n object IEnumerator.Current {\n get { hasFetched = true; return _cur; }\n }\n\n public bool MoveNext() {\n if (hasFetched) _cur += _incr;\n return (_cur > _end ^ _incr > 0);\n }\n\n public void Reset() {\n _cur = _start; hasFetched = false;\n }\n }\n\n internal class RangerFEnum : IEnumerator {\n double _cur, _start, _end, _incr;\n bool hasFetched = false;\n\n public RangerFEnum(double start, double end, double incr) {\n _start = _cur = start; _end = end; _incr = incr;\n if ((_start < _end ^ _incr > 0) || _incr == 0)\n throw new ArgumentException(\"Will never reach end!\");\n }\n\n public double Current {\n get { hasFetched = true; return _cur; }\n }\n\n object IEnumerator.Current {\n get { hasFetched = true; return _cur; }\n }\n\n public bool MoveNext() {\n if (hasFetched) _cur += _incr;\n return (_cur > _end ^ _incr > 0);\n }\n\n public void Reset() {\n _cur = _start; hasFetched = false;\n }\n }\n}\n create assembly Range from 'Range.dll' with permission_set=safe -- mod path to point to actual dll location on disk.\ngo\ncreate function dbo.Range(@start bigint, @end bigint, @incr bigint)\n returns table(n bigint)\n as external name [Range].[Range.UserDefinedFunctions].[Range]\ngo\ncreate function dbo.RangeF(@start float, @end float, @incr float)\n returns table(n float)\n as external name [Range].[Range.UserDefinedFunctions].[RangeF]\ngo\n"
},
{
"answer_id": 153973,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "select sum(numberGenerator.rank)\nfrom\n(\nselect\n rank = ( select count(*) \n from reallyLargeTable t1 \n where t1.uniqueValue > t2.uniqueValue ), \n t2.uniqueValue id1, \n t2.uniqueValue id2\nfrom reallyLargeTable t2 \n) numberGenerator\nwhere rank between 1 and 10\n"
},
{
"answer_id": 7556043,
"author": "Mike Powell",
"author_id": 205,
"author_profile": "https://Stackoverflow.com/users/205",
"pm_score": 1,
"selected": false,
"text": "WITH CTE AS\n(\n SELECT 100 AS n\n UNION ALL\n SELECT n + 1 AS n FROM CTE WHERE n + 1 <= 200\n)\nSELECT n FROM CTE\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489/"
] |
58,431 |
<p>I have wondered for some time, what a nice, clean solution for joining an array of strings might look like.
Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma".</p>
<p>Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented.
When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string).
I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?).</p>
<p>Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant?</p>
|
[
{
"answer_id": 58437,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 4,
"selected": false,
"text": "separator = \"\"\nforeach(item in stringCollection)\n{\n concatenatedString += separator + item\n separator = \",\"\n}\n"
},
{
"answer_id": 58440,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 2,
"selected": false,
"text": "list = [\"Alpha\", \"Beta\", \"Gamma\"];\noutput = \"\";\nseparator = \"\";\nfor (int i = 0; i < list.length ; i++) {\n output = output + separator;\n output = output + list[i];\n separator = \", \";\n}\n"
},
{
"answer_id": 58452,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 3,
"selected": false,
"text": "public static string join(String[] strings, String sep) {\n if(strings.length == 0) return \"\";\n if(strings.length == 1) return strings[0];\n StringBuilder sb = new StringBuilder();\n sb.append(strings[0]);\n for(int i = 1; i < strings.length; i++) {\n sb.append(sep);\n sb.append(strings[i]);\n }\n return sb.toString();\n}\n"
},
{
"answer_id": 58455,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "private static StringBuilder RecJoin(IEnumerator<string> xs, string sep, StringBuilder result) {\n result.Append(xs.Current);\n if (xs.MoveNext()) {\n result.Append(sep);\n return RecJoin(xs, sep, result);\n } else\n return result;\n}\n\npublic static string Join(this IEnumerable<string> xs, string separator) {\n var i = xs.GetEnumerator();\n if (!i.MoveNext())\n return string.Empty;\n else\n return RecJoin(i, separator, new StringBuilder()).ToString();\n}\n"
},
{
"answer_id": 58496,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "$ echo \"Alpha\nBeta\nGamma\" | perl -e 'print(join(\", \", map {chomp; $_} <> ))'\nAlpha, Beta, Gamma\n for (i = 0; i < N-1; i++){\n strcat(s, a[i]);\n strcat(s, \", \");\n}\nstrcat(s, a[N]);\n"
},
{
"answer_id": 58515,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 3,
"selected": false,
"text": "separator = \",\"\nforeach (item in stringCollection)\n{\n concatenatedString += concatenatedString ? separator + item : item\n}\n"
},
{
"answer_id": 61319,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "join() join() print \", \".join([\"Alpha\", \"Beta\", \"Gamma\"])\n# Alpha, Beta, Gamma\n def join(seq, sep=\" \"):\n if not seq: return \"\"\n elif len(seq) == 1: return seq[0]\n return reduce(lambda x, y: x + sep + y, seq)\n\nprint join([\"Alpha\", \"Beta\", \"Gamma\"], \", \")\n# Alpha, Beta, Gamma\n join() PyDoc_STRVAR(join__doc__,\n\"S.join(sequence) -> string\\n\\\n\\n\\\nReturn a string which is the concatenation of the strings in the\\n\\\nsequence. The separator between elements is S.\");\n\nstatic PyObject *\nstring_join(PyStringObject *self, PyObject *orig)\n{\n char *sep = PyString_AS_STRING(self);\n const Py_ssize_t seplen = PyString_GET_SIZE(self);\n PyObject *res = NULL;\n char *p;\n Py_ssize_t seqlen = 0;\n size_t sz = 0;\n Py_ssize_t i;\n PyObject *seq, *item;\n\n seq = PySequence_Fast(orig, \"\");\n if (seq == NULL) {\n return NULL;\n }\n\n seqlen = PySequence_Size(seq);\n if (seqlen == 0) {\n Py_DECREF(seq);\n return PyString_FromString(\"\");\n }\n if (seqlen == 1) {\n item = PySequence_Fast_GET_ITEM(seq, 0);\n if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {\n Py_INCREF(item);\n Py_DECREF(seq);\n return item;\n }\n }\n\n /* There are at least two things to join, or else we have a subclass\n * of the builtin types in the sequence.\n * Do a pre-pass to figure out the total amount of space we'll\n * need (sz), see whether any argument is absurd, and defer to\n * the Unicode join if appropriate.\n */\n for (i = 0; i < seqlen; i++) {\n const size_t old_sz = sz;\n item = PySequence_Fast_GET_ITEM(seq, i);\n if (!PyString_Check(item)){\n#ifdef Py_USING_UNICODE\n if (PyUnicode_Check(item)) {\n /* Defer to Unicode join.\n * CAUTION: There's no gurantee that the\n * original sequence can be iterated over\n * again, so we must pass seq here.\n */\n PyObject *result;\n result = PyUnicode_Join((PyObject *)self, seq);\n Py_DECREF(seq);\n return result;\n }\n#endif\n PyErr_Format(PyExc_TypeError,\n \"sequence item %zd: expected string,\"\n \" %.80s found\",\n i, Py_TYPE(item)->tp_name);\n Py_DECREF(seq);\n return NULL;\n }\n sz += PyString_GET_SIZE(item);\n if (i != 0)\n sz += seplen;\n if (sz < old_sz || sz > PY_SSIZE_T_MAX) {\n PyErr_SetString(PyExc_OverflowError,\n \"join() result is too long for a Python string\");\n Py_DECREF(seq);\n return NULL;\n }\n }\n\n /* Allocate result space. */\n res = PyString_FromStringAndSize((char*)NULL, sz);\n if (res == NULL) {\n Py_DECREF(seq);\n return NULL;\n }\n\n /* Catenate everything. */\n p = PyString_AS_STRING(res);\n for (i = 0; i < seqlen; ++i) {\n size_t n;\n item = PySequence_Fast_GET_ITEM(seq, i);\n n = PyString_GET_SIZE(item);\n Py_MEMCPY(p, PyString_AS_STRING(item), n);\n p += n;\n if (i < seqlen - 1) {\n Py_MEMCPY(p, sep, seplen);\n p += seplen;\n }\n }\n\n Py_DECREF(seq);\n return res;\n}\n Catenate everything. /* Catenate everything. */\nfor each item in sequence\n copy-assign item\n if not last item\n copy-assign separator\n"
},
{
"answer_id": 61581,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "join() def join(seq, sep) \n seq.inject { |total, item| total << sep << item } or \"\" \nend\n\njoin([\"a\", \"b\", \"c\"], \", \")\n# => \"a, b, c\"\n"
},
{
"answer_id": 61623,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "join() use List::Util qw(reduce);\n\nsub mjoin($@) {$sep = shift; reduce {$a.$sep.$b} @_ or ''}\n\nsay mjoin(', ', qw(Alpha Beta Gamma));\n# Alpha, Beta, Gamma\n reduce sub mjoin($@) \n {\n my ($sep, $sum) = (shift, shift); \n $sum .= $sep.$_ for (@_); \n $sum or ''\n }\n"
},
{
"answer_id": 64299,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "sub join( $separator, @strings ){\n my $return = shift @strings;\n for @strings -> ( $string ){\n $return ~= $separator ~ $string;\n }\n return $return;\n}\n"
},
{
"answer_id": 76738,
"author": "Mark B",
"author_id": 13070,
"author_profile": "https://Stackoverflow.com/users/13070",
"pm_score": 0,
"selected": false,
"text": "import junit.framework.Assert;\nimport org.junit.Test;\n\npublic class StringUtil\n{\n public static String join(String delim, String... strings)\n {\n StringBuilder builder = new StringBuilder();\n\n if (strings != null)\n {\n for (String str : strings)\n {\n if (builder.length() > 0)\n {\n builder.append(delim);\n }\n\n builder.append(str);\n }\n } \n\n return builder.toString();\n }\n\n @Test\n public void joinTest()\n {\n Assert.assertEquals(\"\", StringUtil.join(\", \", null));\n Assert.assertEquals(\"\", StringUtil.join(\", \", \"\"));\n Assert.assertEquals(\"\", StringUtil.join(\", \", new String[0]));\n Assert.assertEquals(\"test\", StringUtil.join(\", \", \"test\"));\n Assert.assertEquals(\"foo, bar\", StringUtil.join(\", \", \"foo\", \"bar\"));\n Assert.assertEquals(\"foo, bar, baz\", StringUtil.join(\", \", \"foo\", \"bar\", \"baz\"));\n }\n}\n"
},
{
"answer_id": 80475,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " (defun concatenate-string(list)\n (cond ((= (length list) 1) (car list))\n ((= (length list) 2) (concatenate 'string (first list) \",\" (second list)))\n (t (let ((mid-point (floor (/ (- (length list) 1) 2))))\n (concatenate 'string \n (concatenate-string (subseq list 0 mid-point))\n \",\"\n (concatenate-string (subseq list mid-point (length list))))))))\n\n\n\n (concatenate-string '(\"a\" \"b\"))\n"
},
{
"answer_id": 437254,
"author": "blabla999",
"author_id": 48469,
"author_profile": "https://Stackoverflow.com/users/48469",
"pm_score": 1,
"selected": false,
"text": "join:collectionOfStrings separatedBy:sep\n\n |buffer|\n\n buffer := WriteStream on:''.\n collectionOfStrings \n do:[:each | buffer nextPutAll:each ]\n separatedBy:[ buffer nextPutAll:sep ].\n ^ buffer contents.\n #('A' 'B' 'C') asStringWith:','\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4991/"
] |
58,457 |
<p>How do you randomly select a table row in T-SQL based on an applied weight for all candidate rows?</p>
<p>For example, I have a set of rows in a table weighted at 50, 25, and 25 (which adds up to 100 but does not need to), and I want to select one of them randomly with a statistical outcome equivalent to the respective weight.</p>
|
[
{
"answer_id": 58459,
"author": "Dane",
"author_id": 2929,
"author_profile": "https://Stackoverflow.com/users/2929",
"pm_score": 3,
"selected": false,
"text": "DECLARE @id int, @weight_sum int, @weight_point int\nDECLARE @table TABLE (id int, weight int)\n\nINSERT INTO @table(id, weight) VALUES(1, 50)\nINSERT INTO @table(id, weight) VALUES(2, 25)\nINSERT INTO @table(id, weight) VALUES(3, 25)\n\nSELECT @weight_sum = SUM(weight)\nFROM @table\n\nSELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)\n\nSELECT TOP 1 @id = t1.id\nFROM @table t1, @table t2\nWHERE t1.id >= t2.id\nGROUP BY t1.id\nHAVING SUM(t2.weight) >= @weight_point\nORDER BY t1.id\n\nSELECT @id\n"
},
{
"answer_id": 58995,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "Function PickScore()\n 'Assume we have a database wrapper class instance called SQL and seeded a PRNG already\n 'Get count of scores in database\n Dim ScoreCount As Double = SQL.ExecuteScalar(\"SELECT COUNT(score) FROM [MyTable]\")\n ' You could also approximate this with just the number of records in the table, which might be faster.\n\n 'Random number between 0 and 1 with ScoreCount possible values\n Dim rand As Double = Random.GetNext(ScoreCount) / ScoreCount\n\n 'Use the equation y = 1 - x^3 to skew results in favor of higher scores\n ' For x between 0 and 1, y is also between 0 and 1 with a strong bias towards 1\n rand = 1 - (rand * rand * rand)\n\n 'Now we need to map the (0,1] vector to [1,Maxscore].\n 'Just find MaxScore and mutliply by rand\n Dim MaxScore As UInteger = SQL.ExecuteScalar(\"SELECT MAX(Score) FROM Songs\")\n Return MaxScore * rand\nEnd Function\n"
},
{
"answer_id": 454454,
"author": "MatBailie",
"author_id": 53341,
"author_profile": "https://Stackoverflow.com/users/53341",
"pm_score": 5,
"selected": true,
"text": "(n*n/2) DECLARE @id int, @weight_sum int, @weight_point int\nDECLARE @table TABLE (id int, weight int)\n\nINSERT INTO @table(id, weight) VALUES(1, 50)\nINSERT INTO @table(id, weight) VALUES(2, 25)\nINSERT INTO @table(id, weight) VALUES(3, 25)\n\nSELECT @weight_sum = SUM(weight)\nFROM @table\n\nSELECT @weight_point = FLOOR(((@weight_sum - 1) * RAND() + 1))\n\nSELECT\n @id = CASE WHEN @weight_point < 0 THEN @id ELSE [table].id END,\n @weight_point = @weight_point - [table].weight\nFROM\n @table [table]\nORDER BY\n [table].Weight DESC\n @id id @weight @weight_point SUM @id DECLARE @id int, @weight_sum int, @weight_point int, @next_weight int, @row_count int\nDECLARE @table TABLE (id int, weight int)\n\nINSERT INTO @table(id, weight) VALUES(1, 50)\nINSERT INTO @table(id, weight) VALUES(2, 25)\nINSERT INTO @table(id, weight) VALUES(3, 25)\n\nSELECT @weight_sum = SUM(weight)\nFROM @table\n\nSELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)\n\nSELECT @next_weight = MAX(weight) FROM @table\nSELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight\nSET @weight_point = @weight_point - (@next_weight * @row_count)\n\nWHILE (@weight_point > 0)\nBEGIN\n SELECT @next_weight = MAX(weight) FROM @table WHERE weight < @next_weight\n SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight\n SET @weight_point = @weight_point - (@next_weight * @row_count)\nEND\n\n-- # Once the @weight_point is less than 0, we know that the randomly chosen record\n-- # is in the group of records WHERE [table].weight = @next_weight\n\nSELECT @row_count = FLOOR(((@row_count - 1) * RAND() + 1))\n\nSELECT\n @id = CASE WHEN @row_count < 0 THEN @id ELSE [table].id END,\n @row_count = @row_count - 1\nFROM\n @table [table]\nWHERE\n [table].weight = @next_weight\nORDER BY\n [table].Weight DESC\n"
},
{
"answer_id": 51090191,
"author": "Shiroy",
"author_id": 1555435,
"author_profile": "https://Stackoverflow.com/users/1555435",
"pm_score": 2,
"selected": false,
"text": "Weight int SELECT * \nFROM \n(\n SELECT TOP 50 RowData, Weight \n FROM MyTable \n ORDER BY POWER(RAND(CAST(NEWID() AS VARBINARY)), (1.0/Weight)) DESC\n) X \nORDER BY Weight DESC\n 1.0 * ABS(CAST(CHECKSUM(NEWID()) AS bigint)) / CAST(0x7FFFFFFF AS INT) \n BIGINT INT"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2929/"
] |
58,478 |
<p>I want to send email from a Ruby application. Is there a call in the core language to do this or is there a library I should use? What's the best way to do this?</p>
|
[
{
"answer_id": 59285,
"author": "pauliephonic",
"author_id": 5374,
"author_profile": "https://Stackoverflow.com/users/5374",
"pm_score": 1,
"selected": false,
"text": "require 'net/smtp'\nSMTP_SERVER = 'mailserver01' #change to your server\n\ndef send_emails(sender_address, recipients, subject, message_body)\n recipients.each do |recipient_address|\n message_header =''\n message_header << \"From: <#{sender_address}>\\r\\n\"\n message_header << \"To: <#{recipient_address}>\\r\\n\"\n message_header << \"Subject: #{subject}\\r\\n\"\n message_header << \"Date: \" + Time.now.to_s + \"\\r\\n\"\n message = message_header + \"\\r\\n\" + message_body + \"\\r\\n\"\n Net::SMTP.start(SMTP_SERVER, 25) do |smtp|\n smtp.send_message message, sender_address, recipient_address\n end\n end\nend\nsend_emails('[email protected]',['[email protected]', '[email protected]'],'test Email',\"Hi there this is a test email hope you like it\")\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] |
58,482 |
<p>I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet:</p>
<pre><code>foo = ["goo", "baz"]
</code></pre>
<p>How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)?</p>
<p>Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this:</p>
<pre><code> [foo, goo, bar].each { |param|
if param.class != Array
puts "param_name wasn't an Array. It was a/an #{param.class}"
return "Error: param_name wasn't an Array"
end
}
</code></pre>
<p>My question is then: Can I replace the instances of 'param_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala <a href="https://stackoverflow.com/questions/58482/ruby-get-a-variables-name#58870">dbr's answer</a>) </p>
|
[
{
"answer_id": 58492,
"author": "Josh Moore",
"author_id": 5004,
"author_profile": "https://Stackoverflow.com/users/5004",
"pm_score": 2,
"selected": false,
"text": "instance_variables object.instance_variables\n self.instance_variables\n"
},
{
"answer_id": 58734,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "# Returns the first instance variable whose value == x\n# Returns nil if no name maps to the given value\ndef instance_variable_name_for(x)\n self.instance_variables.find do |var|\n x == self.instance_variable_get(var)\n end\nend\n"
},
{
"answer_id": 58765,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 2,
"selected": false,
"text": "Kernel::local_variables"
},
{
"answer_id": 58830,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 3,
"selected": false,
"text": "local_variables.each do |var|\n puts var if (eval(var).class != Fixnum)\nend\n Fixnum"
},
{
"answer_id": 58870,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 3,
"selected": false,
"text": "data_container = {'foo' => ['goo', 'baz']}\n ['content 1', 'content 2', 'etc'] {\"foo\" => foo, \"goo\" => goo, \"bar\"=>bar}.each do |param_name, param|\n if param.class != Array\n puts \"#{param_name} wasn't an Array. It was a/an #{param.class}\"\n puts \"Error: #{param_name} wasn't an Array\"\n end\nend\n"
},
{
"answer_id": 61729,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": false,
"text": "a = 1\nget_name(a)\n b = a\nget_name(b)\n [b,a].each do |arg|\n get_name(arg)\nend\n def do_stuff( arg )\n get_name(arg)\ndo\ndo_stuff(b)\n"
},
{
"answer_id": 63523,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 6,
"selected": true,
"text": "[\"foo\", \"goo\", \"bar\"].each { |param_name|\n param = eval(param_name)\n if param.class != Array\n puts \"#{param_name} wasn't an Array. It was a/an #{param.class}\"\n return \"Error: #{param_name} wasn't an Array\"\n end\n }\n"
},
{
"answer_id": 67910,
"author": "Greg Borenstein",
"author_id": 10419,
"author_profile": "https://Stackoverflow.com/users/10419",
"pm_score": 1,
"selected": false,
"text": "my_array = [foo, baz, bar]\nmy_array.each_with_index do |item, index|\n if item.class != Array\n puts \"#{my_array[index]} wasn't an Array. It was a/an #{item.class}\"\n end\nend\n"
},
{
"answer_id": 17029573,
"author": "Boris Stitnicky",
"author_id": 1153747,
"author_profile": "https://Stackoverflow.com/users/1153747",
"pm_score": 2,
"selected": false,
"text": "Module Class Struct Dog = Class.new\nDog.name # Dog\n x = Module.new # creating an anonymous module\nx.name #=> nil # the module does not know that it has been assigned to x\nAnimal = x # but will notice once we assign it to a constant\nx.name #=> \"Animal\"\n Rover = Dog.new\nRover.name #=> raises NoMethodError\n y_support/name_magic # first, gem install y_support\nrequire 'y_support/name_magic'\n\nclass Cat\n include NameMagic\nend\n tmp = Cat.new # nameless kitty\ntmp.name #=> nil\nJosie = tmp # by assigning to a constant, we name the kitty Josie\ntmp.name #=> :Josie\n #new NameMagic Array require 'y_support/name_magic'\nclass MyArr < Array\n include NameMagic\nend\n\nfoo = MyArr.new [\"goo\", \"baz\"] # not named yet\nfoo.name #=> nil\nFoo = foo # but assignment to a constant is noticed\nfoo.name #=> :Foo\n\n# You can even list the instances\nMyArr.instances #=> [[\"goo\", \"baz\"]]\nMyArr.instance_names #=> [:Foo]\n\n# Get an instance by name:\nMyArr.instance \"Foo\" #=> [\"goo\", \"baz\"]\nMyArr.instance :Foo #=> [\"goo\", \"baz\"]\n\n# Rename it:\nFoo.name = \"Quux\"\nFoo.name #=> :Quux\n\n# Or forget the name again:\nMyArr.forget :Quux\nFoo.name #=> nil\n\n# In addition, you can name the object upon creation even without assignment\nu = MyArr.new [1, 2], name: :Pair\nu.name #=> :Pair\nv = MyArr.new [1, 2, 3], ɴ: :Trinity\nv.name #=> :Trinity\n const_assigned"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
58,493 |
<p>I have an array of numbers that potentially have up to 8 decimal places and I need to find the smallest common number I can multiply them by so that they are all whole numbers. I need this so all the original numbers can all be multiplied out to the same scale and be processed by a sealed system that will only deal with whole numbers, then I can retrieve the results and divide them by the common multiplier to get my relative results.</p>
<p>Currently we do a few checks on the numbers and multiply by 100 or 1,000,000, but the processing done by the *sealed system can get quite expensive when dealing with large numbers so multiplying everything by a million just for the sake of it isn’t really a great option. As an approximation lets say that the sealed algorithm gets 10 times more expensive every time you multiply by a factor of 10.</p>
<p>What is the most efficient algorithm, that will also give the best possible result, to accomplish what I need and is there a mathematical name and/or formula for what I’m need?</p>
<p>*The sealed system isn’t really sealed. I own/maintain the source code for it but its 100,000 odd lines of proprietary magic and it has been thoroughly bug and performance tested, altering it to deal with floats is not an option for many reasons. It is a system that creates a grid of X by Y cells, then rects that are X by Y are dropped into the grid, “proprietary magic” occurs and results are spat out – obviously this is an extremely simplified version of reality, but it’s a good enough approximation.</p>
<p>So far there are quiet a few good answers and I wondered how I should go about choosing the ‘correct’ one. To begin with I figured the only fair way was to create each solution and performance test it, but I later realised that pure speed wasn’t the only relevant factor – an more accurate solution is also very relevant. I wrote the performance tests anyway, but currently the I’m choosing the correct answer based on speed as well accuracy using a ‘gut feel’ formula.</p>
<p>My performance tests process 1000 different sets of 100 randomly generated numbers.
Each algorithm is tested using the same set of random numbers.
Algorithms are written in .Net 3.5 (although thus far would be 2.0 compatible)
I tried pretty hard to make the tests as fair as possible.</p>
<ul>
<li>Greg – Multiply by large number
and then divide by GCD – 63
milliseconds</li>
<li>Andy – String Parsing
– 199 milliseconds </li>
<li>Eric – Decimal.GetBits – 160 milliseconds</li>
<li>Eric – Binary search – 32
milliseconds </li>
<li>Ima – sorry I couldn’t
figure out a how to implement your
solution easily in .Net (I didn’t
want to spend too long on it) </li>
<li>Bill – I figure your answer was pretty
close to Greg’s so didn’t implement
it. I’m sure it’d be a smidge faster
but potentially less accurate.</li>
</ul>
<p>So Greg’s Multiply by large number and then divide by GCD” solution was the second fastest algorithm and it gave the most accurate results so for now I’m calling it correct.</p>
<p>I really wanted the Decimal.GetBits solution to be the fastest, but it was very slow, I’m unsure if this is due to the conversion of a Double to a Decimal or the Bit masking and shifting. There should be a
similar usable solution for a straight Double using the BitConverter.GetBytes and some knowledge contained here: <a href="http://blogs.msdn.com/bclteam/archive/2007/05/29/bcl-refresher-floating-point-types-the-good-the-bad-and-the-ugly-inbar-gazit-matthew-greig.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/bclteam/archive/2007/05/29/bcl-refresher-floating-point-types-the-good-the-bad-and-the-ugly-inbar-gazit-matthew-greig.aspx</a> but my eyes just kept glazing over every time I read that article and I eventually ran out of time to try to implement a solution.</p>
<p>I’m always open to other solutions if anyone can think of something better.</p>
|
[
{
"answer_id": 58512,
"author": "Evil Andy",
"author_id": 4431,
"author_profile": "https://Stackoverflow.com/users/4431",
"pm_score": 0,
"selected": false,
"text": "myNumber.ToString().Substring(myNumber.ToString().IndexOf(\".\")+1).Length\n"
},
{
"answer_id": 60085,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 0,
"selected": false,
"text": "int NumDecimals( double d )\n{\n // make d positive for clarity; it won't change the result\n if( d<0 ) d=-d;\n\n // now do binary search on the possible numbers of post-decimal digits to \n // determine the actual number as quickly as possible:\n\n if( NeedsMore( d, 10e4 ) )\n {\n // more than 4 decimals\n if( NeedsMore( d, 10e6 ) )\n {\n // > 6 decimal places\n if( NeedsMore( d, 10e7 ) ) return 10e8;\n return 10e7;\n }\n else\n {\n // <= 6 decimal places\n if( NeedsMore( d, 10e5 ) ) return 10e6;\n return 10e5;\n }\n }\n else\n {\n // <= 4 decimal places\n // etc...\n }\n\n}\n\nbool NeedsMore( double d, double e )\n{\n // check whether the representation of D has more decimal points than the \n // power of 10 represented in e.\n return (d*e - Math.Floor( d*e )) > 0;\n}\n"
},
{
"answer_id": 60126,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 1,
"selected": false,
"text": "2.1 * 10/7 -> 3\n0.008 * 10^3/2^3 -> 1\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6042/"
] |
58,510 |
<p>I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to <a href="https://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java">this question</a> only in .Net.</p>
|
[
{
"answer_id": 58570,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 7,
"selected": true,
"text": "FindMimeFromData FindMimeFromData"
},
{
"answer_id": 62007,
"author": "Richard Gourlay",
"author_id": 2674,
"author_profile": "https://Stackoverflow.com/users/2674",
"pm_score": 8,
"selected": false,
"text": "using System.Runtime.InteropServices;\n [DllImport(@\"urlmon.dll\", CharSet = CharSet.Auto)]\n private extern static System.UInt32 FindMimeFromData(\n System.UInt32 pBC,\n [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,\n [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,\n System.UInt32 cbSize,\n [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,\n System.UInt32 dwMimeFlags,\n out System.UInt32 ppwzMimeOut,\n System.UInt32 dwReserverd\n );\n\n public static string getMimeFromFile(string filename)\n {\n if (!File.Exists(filename))\n throw new FileNotFoundException(filename + \" not found\");\n\n byte[] buffer = new byte[256];\n using (FileStream fs = new FileStream(filename, FileMode.Open))\n {\n if (fs.Length >= 256)\n fs.Read(buffer, 0, 256);\n else\n fs.Read(buffer, 0, (int)fs.Length);\n }\n try\n {\n System.UInt32 mimetype;\n FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);\n System.IntPtr mimeTypePtr = new IntPtr(mimetype);\n string mime = Marshal.PtrToStringUni(mimeTypePtr);\n Marshal.FreeCoTaskMem(mimeTypePtr);\n return mime;\n }\n catch (Exception e)\n {\n return \"unknown/unknown\";\n }\n }\n"
},
{
"answer_id": 1685614,
"author": "Serguei",
"author_id": 47693,
"author_profile": "https://Stackoverflow.com/users/47693",
"pm_score": 5,
"selected": false,
"text": " using System.IO;\n using Microsoft.Win32;\n\n string GetMimeType(FileInfo fileInfo)\n {\n string mimeType = \"application/unknown\";\n\n RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(\n fileInfo.Extension.ToLower()\n );\n\n if(regKey != null)\n {\n object contentType = regKey.GetValue(\"Content Type\");\n\n if(contentType != null)\n mimeType = contentType.ToString();\n }\n\n return mimeType;\n }\n"
},
{
"answer_id": 1718862,
"author": "Jamey",
"author_id": 209145,
"author_profile": "https://Stackoverflow.com/users/209145",
"pm_score": 2,
"selected": false,
"text": "FindMimeFromData text/plain application/octet-stream"
},
{
"answer_id": 7161265,
"author": "Anykey",
"author_id": 907728,
"author_profile": "https://Stackoverflow.com/users/907728",
"pm_score": 7,
"selected": false,
"text": "public static class MIMEAssistant\n{\n private static readonly Dictionary<string, string> MIMETypesDictionary = new Dictionary<string, string>\n {\n {\"ai\", \"application/postscript\"},\n {\"aif\", \"audio/x-aiff\"},\n {\"aifc\", \"audio/x-aiff\"},\n {\"aiff\", \"audio/x-aiff\"},\n {\"asc\", \"text/plain\"},\n {\"atom\", \"application/atom+xml\"},\n {\"au\", \"audio/basic\"},\n {\"avi\", \"video/x-msvideo\"},\n {\"bcpio\", \"application/x-bcpio\"},\n {\"bin\", \"application/octet-stream\"},\n {\"bmp\", \"image/bmp\"},\n {\"cdf\", \"application/x-netcdf\"},\n {\"cgm\", \"image/cgm\"},\n {\"class\", \"application/octet-stream\"},\n {\"cpio\", \"application/x-cpio\"},\n {\"cpt\", \"application/mac-compactpro\"},\n {\"csh\", \"application/x-csh\"},\n {\"css\", \"text/css\"},\n {\"dcr\", \"application/x-director\"},\n {\"dif\", \"video/x-dv\"},\n {\"dir\", \"application/x-director\"},\n {\"djv\", \"image/vnd.djvu\"},\n {\"djvu\", \"image/vnd.djvu\"},\n {\"dll\", \"application/octet-stream\"},\n {\"dmg\", \"application/octet-stream\"},\n {\"dms\", \"application/octet-stream\"},\n {\"doc\", \"application/msword\"},\n {\"docx\",\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"},\n {\"dotx\", \"application/vnd.openxmlformats-officedocument.wordprocessingml.template\"},\n {\"docm\",\"application/vnd.ms-word.document.macroEnabled.12\"},\n {\"dotm\",\"application/vnd.ms-word.template.macroEnabled.12\"},\n {\"dtd\", \"application/xml-dtd\"},\n {\"dv\", \"video/x-dv\"},\n {\"dvi\", \"application/x-dvi\"},\n {\"dxr\", \"application/x-director\"},\n {\"eps\", \"application/postscript\"},\n {\"etx\", \"text/x-setext\"},\n {\"exe\", \"application/octet-stream\"},\n {\"ez\", \"application/andrew-inset\"},\n {\"gif\", \"image/gif\"},\n {\"gram\", \"application/srgs\"},\n {\"grxml\", \"application/srgs+xml\"},\n {\"gtar\", \"application/x-gtar\"},\n {\"hdf\", \"application/x-hdf\"},\n {\"hqx\", \"application/mac-binhex40\"},\n {\"htm\", \"text/html\"},\n {\"html\", \"text/html\"},\n {\"ice\", \"x-conference/x-cooltalk\"},\n {\"ico\", \"image/x-icon\"},\n {\"ics\", \"text/calendar\"},\n {\"ief\", \"image/ief\"},\n {\"ifb\", \"text/calendar\"},\n {\"iges\", \"model/iges\"},\n {\"igs\", \"model/iges\"},\n {\"jnlp\", \"application/x-java-jnlp-file\"},\n {\"jp2\", \"image/jp2\"},\n {\"jpe\", \"image/jpeg\"},\n {\"jpeg\", \"image/jpeg\"},\n {\"jpg\", \"image/jpeg\"},\n {\"js\", \"application/x-javascript\"},\n {\"kar\", \"audio/midi\"},\n {\"latex\", \"application/x-latex\"},\n {\"lha\", \"application/octet-stream\"},\n {\"lzh\", \"application/octet-stream\"},\n {\"m3u\", \"audio/x-mpegurl\"},\n {\"m4a\", \"audio/mp4a-latm\"},\n {\"m4b\", \"audio/mp4a-latm\"},\n {\"m4p\", \"audio/mp4a-latm\"},\n {\"m4u\", \"video/vnd.mpegurl\"},\n {\"m4v\", \"video/x-m4v\"},\n {\"mac\", \"image/x-macpaint\"},\n {\"man\", \"application/x-troff-man\"},\n {\"mathml\", \"application/mathml+xml\"},\n {\"me\", \"application/x-troff-me\"},\n {\"mesh\", \"model/mesh\"},\n {\"mid\", \"audio/midi\"},\n {\"midi\", \"audio/midi\"},\n {\"mif\", \"application/vnd.mif\"},\n {\"mov\", \"video/quicktime\"},\n {\"movie\", \"video/x-sgi-movie\"},\n {\"mp2\", \"audio/mpeg\"},\n {\"mp3\", \"audio/mpeg\"},\n {\"mp4\", \"video/mp4\"},\n {\"mpe\", \"video/mpeg\"},\n {\"mpeg\", \"video/mpeg\"},\n {\"mpg\", \"video/mpeg\"},\n {\"mpga\", \"audio/mpeg\"},\n {\"ms\", \"application/x-troff-ms\"},\n {\"msh\", \"model/mesh\"},\n {\"mxu\", \"video/vnd.mpegurl\"},\n {\"nc\", \"application/x-netcdf\"},\n {\"oda\", \"application/oda\"},\n {\"ogg\", \"application/ogg\"},\n {\"pbm\", \"image/x-portable-bitmap\"},\n {\"pct\", \"image/pict\"},\n {\"pdb\", \"chemical/x-pdb\"},\n {\"pdf\", \"application/pdf\"},\n {\"pgm\", \"image/x-portable-graymap\"},\n {\"pgn\", \"application/x-chess-pgn\"},\n {\"pic\", \"image/pict\"},\n {\"pict\", \"image/pict\"},\n {\"png\", \"image/png\"}, \n {\"pnm\", \"image/x-portable-anymap\"},\n {\"pnt\", \"image/x-macpaint\"},\n {\"pntg\", \"image/x-macpaint\"},\n {\"ppm\", \"image/x-portable-pixmap\"},\n {\"ppt\", \"application/vnd.ms-powerpoint\"},\n {\"pptx\",\"application/vnd.openxmlformats-officedocument.presentationml.presentation\"},\n {\"potx\",\"application/vnd.openxmlformats-officedocument.presentationml.template\"},\n {\"ppsx\",\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\"},\n {\"ppam\",\"application/vnd.ms-powerpoint.addin.macroEnabled.12\"},\n {\"pptm\",\"application/vnd.ms-powerpoint.presentation.macroEnabled.12\"},\n {\"potm\",\"application/vnd.ms-powerpoint.template.macroEnabled.12\"},\n {\"ppsm\",\"application/vnd.ms-powerpoint.slideshow.macroEnabled.12\"},\n {\"ps\", \"application/postscript\"},\n {\"qt\", \"video/quicktime\"},\n {\"qti\", \"image/x-quicktime\"},\n {\"qtif\", \"image/x-quicktime\"},\n {\"ra\", \"audio/x-pn-realaudio\"},\n {\"ram\", \"audio/x-pn-realaudio\"},\n {\"ras\", \"image/x-cmu-raster\"},\n {\"rdf\", \"application/rdf+xml\"},\n {\"rgb\", \"image/x-rgb\"},\n {\"rm\", \"application/vnd.rn-realmedia\"},\n {\"roff\", \"application/x-troff\"},\n {\"rtf\", \"text/rtf\"},\n {\"rtx\", \"text/richtext\"},\n {\"sgm\", \"text/sgml\"},\n {\"sgml\", \"text/sgml\"},\n {\"sh\", \"application/x-sh\"},\n {\"shar\", \"application/x-shar\"},\n {\"silo\", \"model/mesh\"},\n {\"sit\", \"application/x-stuffit\"},\n {\"skd\", \"application/x-koan\"},\n {\"skm\", \"application/x-koan\"},\n {\"skp\", \"application/x-koan\"},\n {\"skt\", \"application/x-koan\"},\n {\"smi\", \"application/smil\"},\n {\"smil\", \"application/smil\"},\n {\"snd\", \"audio/basic\"},\n {\"so\", \"application/octet-stream\"},\n {\"spl\", \"application/x-futuresplash\"},\n {\"src\", \"application/x-wais-source\"},\n {\"sv4cpio\", \"application/x-sv4cpio\"},\n {\"sv4crc\", \"application/x-sv4crc\"},\n {\"svg\", \"image/svg+xml\"},\n {\"swf\", \"application/x-shockwave-flash\"},\n {\"t\", \"application/x-troff\"},\n {\"tar\", \"application/x-tar\"},\n {\"tcl\", \"application/x-tcl\"},\n {\"tex\", \"application/x-tex\"},\n {\"texi\", \"application/x-texinfo\"},\n {\"texinfo\", \"application/x-texinfo\"},\n {\"tif\", \"image/tiff\"},\n {\"tiff\", \"image/tiff\"},\n {\"tr\", \"application/x-troff\"},\n {\"tsv\", \"text/tab-separated-values\"},\n {\"txt\", \"text/plain\"},\n {\"ustar\", \"application/x-ustar\"},\n {\"vcd\", \"application/x-cdlink\"},\n {\"vrml\", \"model/vrml\"},\n {\"vxml\", \"application/voicexml+xml\"},\n {\"wav\", \"audio/x-wav\"},\n {\"wbmp\", \"image/vnd.wap.wbmp\"},\n {\"wbmxl\", \"application/vnd.wap.wbxml\"},\n {\"wml\", \"text/vnd.wap.wml\"},\n {\"wmlc\", \"application/vnd.wap.wmlc\"},\n {\"wmls\", \"text/vnd.wap.wmlscript\"},\n {\"wmlsc\", \"application/vnd.wap.wmlscriptc\"},\n {\"wrl\", \"model/vrml\"},\n {\"xbm\", \"image/x-xbitmap\"},\n {\"xht\", \"application/xhtml+xml\"},\n {\"xhtml\", \"application/xhtml+xml\"},\n {\"xls\", \"application/vnd.ms-excel\"}, \n {\"xml\", \"application/xml\"},\n {\"xpm\", \"image/x-xpixmap\"},\n {\"xsl\", \"application/xml\"},\n {\"xlsx\",\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"},\n {\"xltx\",\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\"},\n {\"xlsm\",\"application/vnd.ms-excel.sheet.macroEnabled.12\"},\n {\"xltm\",\"application/vnd.ms-excel.template.macroEnabled.12\"},\n {\"xlam\",\"application/vnd.ms-excel.addin.macroEnabled.12\"},\n {\"xlsb\",\"application/vnd.ms-excel.sheet.binary.macroEnabled.12\"},\n {\"xslt\", \"application/xslt+xml\"},\n {\"xul\", \"application/vnd.mozilla.xul+xml\"},\n {\"xwd\", \"image/x-xwindowdump\"},\n {\"xyz\", \"chemical/x-xyz\"},\n {\"zip\", \"application/zip\"}\n };\n\n public static string GetMIMEType(string fileName)\n {\n //get file extension\n string extension = Path.GetExtension(fileName).ToLowerInvariant();\n\n if (extension.Length > 0 && \n MIMETypesDictionary.ContainsKey(extension.Remove(0, 1)))\n {\n return MIMETypesDictionary[extension.Remove(0, 1)];\n }\n return \"unknown/unknown\";\n }\n}\n"
},
{
"answer_id": 8051777,
"author": "EvgeniySu",
"author_id": 1035766,
"author_profile": "https://Stackoverflow.com/users/1035766",
"pm_score": 2,
"selected": false,
"text": " Public Shared Function GetFromFileName(ByVal fileName As String) As String\n Return GetFromExtension(Path.GetExtension(fileName).Remove(0, 1))\n End Function\n\n Public Shared Function GetFromExtension(ByVal extension As String) As String\n If extension.StartsWith(\".\"c) Then\n extension = extension.Remove(0, 1)\n End If\n\n If MIMETypesDictionary.ContainsKey(extension) Then\n Return MIMETypesDictionary(extension)\n End If\n\n Return \"unknown/unknown\"\n End Function\n\n Private Shared ReadOnly MIMETypesDictionary As New Dictionary(Of String, String)() From { _\n {\"ai\", \"application/postscript\"}, _\n {\"aif\", \"audio/x-aiff\"}, _\n {\"aifc\", \"audio/x-aiff\"}, _\n {\"aiff\", \"audio/x-aiff\"}, _\n {\"asc\", \"text/plain\"}, _\n {\"atom\", \"application/atom+xml\"}, _\n {\"au\", \"audio/basic\"}, _\n {\"avi\", \"video/x-msvideo\"}, _\n {\"bcpio\", \"application/x-bcpio\"}, _\n {\"bin\", \"application/octet-stream\"}, _\n {\"bmp\", \"image/bmp\"}, _\n {\"cdf\", \"application/x-netcdf\"}, _\n {\"cgm\", \"image/cgm\"}, _\n {\"class\", \"application/octet-stream\"}, _\n {\"cpio\", \"application/x-cpio\"}, _\n {\"cpt\", \"application/mac-compactpro\"}, _\n {\"csh\", \"application/x-csh\"}, _\n {\"css\", \"text/css\"}, _\n {\"dcr\", \"application/x-director\"}, _\n {\"dif\", \"video/x-dv\"}, _\n {\"dir\", \"application/x-director\"}, _\n {\"djv\", \"image/vnd.djvu\"}, _\n {\"djvu\", \"image/vnd.djvu\"}, _\n {\"dll\", \"application/octet-stream\"}, _\n {\"dmg\", \"application/octet-stream\"}, _\n {\"dms\", \"application/octet-stream\"}, _\n {\"doc\", \"application/msword\"}, _\n {\"dtd\", \"application/xml-dtd\"}, _\n {\"dv\", \"video/x-dv\"}, _\n {\"dvi\", \"application/x-dvi\"}, _\n {\"dxr\", \"application/x-director\"}, _\n {\"eps\", \"application/postscript\"}, _\n {\"etx\", \"text/x-setext\"}, _\n {\"exe\", \"application/octet-stream\"}, _\n {\"ez\", \"application/andrew-inset\"}, _\n {\"gif\", \"image/gif\"}, _\n {\"gram\", \"application/srgs\"}, _\n {\"grxml\", \"application/srgs+xml\"}, _\n {\"gtar\", \"application/x-gtar\"}, _\n {\"hdf\", \"application/x-hdf\"}, _\n {\"hqx\", \"application/mac-binhex40\"}, _\n {\"htm\", \"text/html\"}, _\n {\"html\", \"text/html\"}, _\n {\"ice\", \"x-conference/x-cooltalk\"}, _\n {\"ico\", \"image/x-icon\"}, _\n {\"ics\", \"text/calendar\"}, _\n {\"ief\", \"image/ief\"}, _\n {\"ifb\", \"text/calendar\"}, _\n {\"iges\", \"model/iges\"}, _\n {\"igs\", \"model/iges\"}, _\n {\"jnlp\", \"application/x-java-jnlp-file\"}, _\n {\"jp2\", \"image/jp2\"}, _\n {\"jpe\", \"image/jpeg\"}, _\n {\"jpeg\", \"image/jpeg\"}, _\n {\"jpg\", \"image/jpeg\"}, _\n {\"js\", \"application/x-javascript\"}, _\n {\"kar\", \"audio/midi\"}, _\n {\"latex\", \"application/x-latex\"}, _\n {\"lha\", \"application/octet-stream\"}, _\n {\"lzh\", \"application/octet-stream\"}, _\n {\"m3u\", \"audio/x-mpegurl\"}, _\n {\"m4a\", \"audio/mp4a-latm\"}, _\n {\"m4b\", \"audio/mp4a-latm\"}, _\n {\"m4p\", \"audio/mp4a-latm\"}, _\n {\"m4u\", \"video/vnd.mpegurl\"}, _\n {\"m4v\", \"video/x-m4v\"}, _\n {\"mac\", \"image/x-macpaint\"}, _\n {\"man\", \"application/x-troff-man\"}, _\n {\"mathml\", \"application/mathml+xml\"}, _\n {\"me\", \"application/x-troff-me\"}, _\n {\"mesh\", \"model/mesh\"}, _\n {\"mid\", \"audio/midi\"}, _\n {\"midi\", \"audio/midi\"}, _\n {\"mif\", \"application/vnd.mif\"}, _\n {\"mov\", \"video/quicktime\"}, _\n {\"movie\", \"video/x-sgi-movie\"}, _\n {\"mp2\", \"audio/mpeg\"}, _\n {\"mp3\", \"audio/mpeg\"}, _\n {\"mp4\", \"video/mp4\"}, _\n {\"mpe\", \"video/mpeg\"}, _\n {\"mpeg\", \"video/mpeg\"}, _\n {\"mpg\", \"video/mpeg\"}, _\n {\"mpga\", \"audio/mpeg\"}, _\n {\"ms\", \"application/x-troff-ms\"}, _\n {\"msh\", \"model/mesh\"}, _\n {\"mxu\", \"video/vnd.mpegurl\"}, _\n {\"nc\", \"application/x-netcdf\"}, _\n {\"oda\", \"application/oda\"}, _\n {\"ogg\", \"application/ogg\"}, _\n {\"pbm\", \"image/x-portable-bitmap\"}, _\n {\"pct\", \"image/pict\"}, _\n {\"pdb\", \"chemical/x-pdb\"}, _\n {\"pdf\", \"application/pdf\"}, _\n {\"pgm\", \"image/x-portable-graymap\"}, _\n {\"pgn\", \"application/x-chess-pgn\"}, _\n {\"pic\", \"image/pict\"}, _\n {\"pict\", \"image/pict\"}, _\n {\"png\", \"image/png\"}, _\n {\"pnm\", \"image/x-portable-anymap\"}, _\n {\"pnt\", \"image/x-macpaint\"}, _\n {\"pntg\", \"image/x-macpaint\"}, _\n {\"ppm\", \"image/x-portable-pixmap\"}, _\n {\"ppt\", \"application/vnd.ms-powerpoint\"}, _\n {\"ps\", \"application/postscript\"}, _\n {\"qt\", \"video/quicktime\"}, _\n {\"qti\", \"image/x-quicktime\"}, _\n {\"qtif\", \"image/x-quicktime\"}, _\n {\"ra\", \"audio/x-pn-realaudio\"}, _\n {\"ram\", \"audio/x-pn-realaudio\"}, _\n {\"ras\", \"image/x-cmu-raster\"}, _\n {\"rdf\", \"application/rdf+xml\"}, _\n {\"rgb\", \"image/x-rgb\"}, _\n {\"rm\", \"application/vnd.rn-realmedia\"}, _\n {\"roff\", \"application/x-troff\"}, _\n {\"rtf\", \"text/rtf\"}, _\n {\"rtx\", \"text/richtext\"}, _\n {\"sgm\", \"text/sgml\"}, _\n {\"sgml\", \"text/sgml\"}, _\n {\"sh\", \"application/x-sh\"}, _\n {\"shar\", \"application/x-shar\"}, _\n {\"silo\", \"model/mesh\"}, _\n {\"sit\", \"application/x-stuffit\"}, _\n {\"skd\", \"application/x-koan\"}, _\n {\"skm\", \"application/x-koan\"}, _\n {\"skp\", \"application/x-koan\"}, _\n {\"skt\", \"application/x-koan\"}, _\n {\"smi\", \"application/smil\"}, _\n {\"smil\", \"application/smil\"}, _\n {\"snd\", \"audio/basic\"}, _\n {\"so\", \"application/octet-stream\"}, _\n {\"spl\", \"application/x-futuresplash\"}, _\n {\"src\", \"application/x-wais-source\"}, _\n {\"sv4cpio\", \"application/x-sv4cpio\"}, _\n {\"sv4crc\", \"application/x-sv4crc\"}, _\n {\"svg\", \"image/svg+xml\"}, _\n {\"swf\", \"application/x-shockwave-flash\"}, _\n {\"t\", \"application/x-troff\"}, _\n {\"tar\", \"application/x-tar\"}, _\n {\"tcl\", \"application/x-tcl\"}, _\n {\"tex\", \"application/x-tex\"}, _\n {\"texi\", \"application/x-texinfo\"}, _\n {\"texinfo\", \"application/x-texinfo\"}, _\n {\"tif\", \"image/tiff\"}, _\n {\"tiff\", \"image/tiff\"}, _\n {\"tr\", \"application/x-troff\"}, _\n {\"tsv\", \"text/tab-separated-values\"}, _\n {\"txt\", \"text/plain\"}, _\n {\"ustar\", \"application/x-ustar\"}, _\n {\"vcd\", \"application/x-cdlink\"}, _\n {\"vrml\", \"model/vrml\"}, _\n {\"vxml\", \"application/voicexml+xml\"}, _\n {\"wav\", \"audio/x-wav\"}, _\n {\"wbmp\", \"image/vnd.wap.wbmp\"}, _\n {\"wbmxl\", \"application/vnd.wap.wbxml\"}, _\n {\"wml\", \"text/vnd.wap.wml\"}, _\n {\"wmlc\", \"application/vnd.wap.wmlc\"}, _\n {\"wmls\", \"text/vnd.wap.wmlscript\"}, _\n {\"wmlsc\", \"application/vnd.wap.wmlscriptc\"}, _\n {\"wrl\", \"model/vrml\"}, _\n {\"xbm\", \"image/x-xbitmap\"}, _\n {\"xht\", \"application/xhtml+xml\"}, _\n {\"xhtml\", \"application/xhtml+xml\"}, _\n {\"xls\", \"application/vnd.ms-excel\"}, _\n {\"xml\", \"application/xml\"}, _\n {\"xpm\", \"image/x-xpixmap\"}, _\n {\"xsl\", \"application/xml\"}, _\n {\"xslt\", \"application/xslt+xml\"}, _\n {\"xul\", \"application/vnd.mozilla.xul+xml\"}, _\n {\"xwd\", \"image/x-xwindowdump\"}, _\n {\"xyz\", \"chemical/x-xyz\"}, _\n {\"zip\", \"application/zip\"} _\n }\n"
},
{
"answer_id": 9435701,
"author": "CESAR CASTELLO BRANCO",
"author_id": 1231382,
"author_profile": "https://Stackoverflow.com/users/1231382",
"pm_score": 3,
"selected": false,
"text": " using System.Runtime.InteropServices;\n\n [DllImport (@\"urlmon.dll\", CharSet = CharSet.Auto)]\n private extern static System.UInt32 FindMimeFromData(\n System.UInt32 pBC, \n [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,\n [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,\n System.UInt32 cbSize,\n [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,\n System.UInt32 dwMimeFlags,\n out System.UInt32 ppwzMimeOut,\n System.UInt32 dwReserverd\n );\n\n private string GetMimeFromRegistry (string Filename)\n {\n string mime = \"application/octetstream\";\n string ext = System.IO.Path.GetExtension(Filename).ToLower();\n Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);\n if (rk != null && rk.GetValue(\"Content Type\") != null)\n mime = rk.GetValue(\"Content Type\").ToString();\n return mime;\n }\n\n public string GetMimeTypeFromFileAndRegistry (string filename)\n {\n if (!File.Exists(filename))\n {\n return GetMimeFromRegistry (filename);\n }\n\n byte[] buffer = new byte[256];\n\n using (FileStream fs = new FileStream(filename, FileMode.Open))\n {\n if (fs.Length >= 256)\n fs.Read(buffer, 0, 256);\n else\n fs.Read(buffer, 0, (int)fs.Length);\n }\n\n try\n { \n System.UInt32 mimetype;\n\n FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);\n\n System.IntPtr mimeTypePtr = new IntPtr(mimetype);\n\n string mime = Marshal.PtrToStringUni(mimeTypePtr);\n\n Marshal.FreeCoTaskMem(mimeTypePtr);\n\n if (string.IsNullOrWhiteSpace (mime) || \n mime ==\"text/plain\" || mime == \"application/octet-stream\") \n {\n return GetMimeFromRegistry (filename);\n }\n\n return mime;\n }\n catch (Exception e)\n {\n return GetMimeFromRegistry (filename);\n }\n }\n"
},
{
"answer_id": 13614746,
"author": "Gaff",
"author_id": 695874,
"author_profile": "https://Stackoverflow.com/users/695874",
"pm_score": 7,
"selected": false,
"text": "public class MimeType\n{\n private static readonly byte[] BMP = { 66, 77 };\n private static readonly byte[] DOC = { 208, 207, 17, 224, 161, 177, 26, 225 };\n private static readonly byte[] EXE_DLL = { 77, 90 };\n private static readonly byte[] GIF = { 71, 73, 70, 56 };\n private static readonly byte[] ICO = { 0, 0, 1, 0 };\n private static readonly byte[] JPG = { 255, 216, 255 };\n private static readonly byte[] MP3 = { 255, 251, 48 };\n private static readonly byte[] OGG = { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 };\n private static readonly byte[] PDF = { 37, 80, 68, 70, 45, 49, 46 };\n private static readonly byte[] PNG = { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 };\n private static readonly byte[] RAR = { 82, 97, 114, 33, 26, 7, 0 };\n private static readonly byte[] SWF = { 70, 87, 83 };\n private static readonly byte[] TIFF = { 73, 73, 42, 0 };\n private static readonly byte[] TORRENT = { 100, 56, 58, 97, 110, 110, 111, 117, 110, 99, 101 };\n private static readonly byte[] TTF = { 0, 1, 0, 0, 0 };\n private static readonly byte[] WAV_AVI = { 82, 73, 70, 70 };\n private static readonly byte[] WMV_WMA = { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 };\n private static readonly byte[] ZIP_DOCX = { 80, 75, 3, 4 };\n\n public static string GetMimeType(byte[] file, string fileName)\n {\n\n string mime = \"application/octet-stream\"; //DEFAULT UNKNOWN MIME TYPE\n\n //Ensure that the filename isn't empty or null\n if (string.IsNullOrWhiteSpace(fileName))\n {\n return mime;\n }\n\n //Get the file extension\n string extension = Path.GetExtension(fileName) == null\n ? string.Empty\n : Path.GetExtension(fileName).ToUpper();\n\n //Get the MIME Type\n if (file.Take(2).SequenceEqual(BMP))\n {\n mime = \"image/bmp\";\n }\n else if (file.Take(8).SequenceEqual(DOC))\n {\n mime = \"application/msword\";\n }\n else if (file.Take(2).SequenceEqual(EXE_DLL))\n {\n mime = \"application/x-msdownload\"; //both use same mime type\n }\n else if (file.Take(4).SequenceEqual(GIF))\n {\n mime = \"image/gif\";\n }\n else if (file.Take(4).SequenceEqual(ICO))\n {\n mime = \"image/x-icon\";\n }\n else if (file.Take(3).SequenceEqual(JPG))\n {\n mime = \"image/jpeg\";\n }\n else if (file.Take(3).SequenceEqual(MP3))\n {\n mime = \"audio/mpeg\";\n }\n else if (file.Take(14).SequenceEqual(OGG))\n {\n if (extension == \".OGX\")\n {\n mime = \"application/ogg\";\n }\n else if (extension == \".OGA\")\n {\n mime = \"audio/ogg\";\n }\n else\n {\n mime = \"video/ogg\";\n }\n }\n else if (file.Take(7).SequenceEqual(PDF))\n {\n mime = \"application/pdf\";\n }\n else if (file.Take(16).SequenceEqual(PNG))\n {\n mime = \"image/png\";\n }\n else if (file.Take(7).SequenceEqual(RAR))\n {\n mime = \"application/x-rar-compressed\";\n }\n else if (file.Take(3).SequenceEqual(SWF))\n {\n mime = \"application/x-shockwave-flash\";\n }\n else if (file.Take(4).SequenceEqual(TIFF))\n {\n mime = \"image/tiff\";\n }\n else if (file.Take(11).SequenceEqual(TORRENT))\n {\n mime = \"application/x-bittorrent\";\n }\n else if (file.Take(5).SequenceEqual(TTF))\n {\n mime = \"application/x-font-ttf\";\n }\n else if (file.Take(4).SequenceEqual(WAV_AVI))\n {\n mime = extension == \".AVI\" ? \"video/x-msvideo\" : \"audio/x-wav\";\n }\n else if (file.Take(16).SequenceEqual(WMV_WMA))\n {\n mime = extension == \".WMA\" ? \"audio/x-ms-wma\" : \"video/x-ms-wmv\";\n }\n else if (file.Take(4).SequenceEqual(ZIP_DOCX))\n {\n mime = extension == \".DOCX\" ? \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\" : \"application/x-zip-compressed\";\n }\n\n return mime;\n }\n\n\n}\n"
},
{
"answer_id": 15236493,
"author": "warrior",
"author_id": 1880844,
"author_profile": "https://Stackoverflow.com/users/1880844",
"pm_score": 1,
"selected": false,
"text": "public bool CheckMimeMapExtension(string fileExtension)\n {\n try\n {\n\n using (\n ServerManager serverManager = new ServerManager())\n { \n // connects to default app.config\n var config = serverManager.GetApplicationHostConfiguration();\n var staticContent = config.GetSection(\"system.webServer/staticContent\");\n var mimeMap = staticContent.GetCollection();\n\n foreach (var mimeType in mimeMap)\n {\n\n if (((String)mimeType[\"fileExtension\"]).Equals(fileExtension, StringComparison.OrdinalIgnoreCase))\n return true;\n\n }\n\n }\n return false;\n }\n catch (Exception ex)\n { \n Console.WriteLine(\"An exception has occurred: \\n{0}\", ex.Message);\n Console.Read();\n }\n\n return false;\n\n }\n"
},
{
"answer_id": 16469313,
"author": "Frederick Samson",
"author_id": 2099690,
"author_profile": "https://Stackoverflow.com/users/2099690",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.InteropServices;\n\nusing Microsoft.Win32;\n\nnamespace YourNamespace\n{\n public static class MimeTypeParser\n {\n [DllImport(@\"urlmon.dll\", CharSet = CharSet.Auto)]\n private extern static System.UInt32 FindMimeFromData(\n System.UInt32 pBC,\n [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,\n [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,\n System.UInt32 cbSize,\n [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,\n System.UInt32 dwMimeFlags,\n out System.UInt32 ppwzMimeOut,\n System.UInt32 dwReserverd\n );\n\n public static string GetMimeType(string sFilePath)\n {\n string sMimeType = GetMimeTypeFromList(sFilePath);\n\n if (String.IsNullOrEmpty(sMimeType))\n {\n sMimeType = GetMimeTypeFromFile(sFilePath);\n\n if (String.IsNullOrEmpty(sMimeType))\n {\n sMimeType = GetMimeTypeFromRegistry(sFilePath);\n }\n }\n\n return sMimeType;\n }\n\n public static string GetMimeTypeFromList(string sFileNameOrPath)\n {\n string sMimeType = null;\n string sExtensionWithoutDot = Path.GetExtension(sFileNameOrPath).Substring(1).ToLower();\n\n if (!String.IsNullOrEmpty(sExtensionWithoutDot) && spDicMIMETypes.ContainsKey(sExtensionWithoutDot))\n {\n sMimeType = spDicMIMETypes[sExtensionWithoutDot];\n }\n\n return sMimeType;\n }\n\n public static string GetMimeTypeFromRegistry(string sFileNameOrPath)\n {\n string sMimeType = null;\n string sExtension = Path.GetExtension(sFileNameOrPath).ToLower();\n RegistryKey pKey = Registry.ClassesRoot.OpenSubKey(sExtension);\n\n if (pKey != null && pKey.GetValue(\"Content Type\") != null)\n {\n sMimeType = pKey.GetValue(\"Content Type\").ToString();\n }\n\n return sMimeType;\n }\n\n public static string GetMimeTypeFromFile(string sFilePath)\n {\n string sMimeType = null;\n\n if (File.Exists(sFilePath))\n {\n byte[] abytBuffer = new byte[256];\n\n using (FileStream pFileStream = new FileStream(sFilePath, FileMode.Open))\n {\n if (pFileStream.Length >= 256)\n {\n pFileStream.Read(abytBuffer, 0, 256);\n }\n else\n {\n pFileStream.Read(abytBuffer, 0, (int)pFileStream.Length);\n }\n }\n\n try\n {\n UInt32 unMimeType;\n\n FindMimeFromData(0, null, abytBuffer, 256, null, 0, out unMimeType, 0);\n\n IntPtr pMimeType = new IntPtr(unMimeType);\n string sMimeTypeFromFile = Marshal.PtrToStringUni(pMimeType);\n\n Marshal.FreeCoTaskMem(pMimeType);\n\n if (!String.IsNullOrEmpty(sMimeTypeFromFile) && sMimeTypeFromFile != \"text/plain\" && sMimeTypeFromFile != \"application/octet-stream\")\n {\n sMimeType = sMimeTypeFromFile;\n }\n }\n catch {}\n }\n\n return sMimeType;\n }\n\n private static readonly Dictionary<string, string> spDicMIMETypes = new Dictionary<string, string>\n {\n {\"ai\", \"application/postscript\"},\n {\"aif\", \"audio/x-aiff\"},\n {\"aifc\", \"audio/x-aiff\"},\n {\"aiff\", \"audio/x-aiff\"},\n {\"asc\", \"text/plain\"},\n {\"atom\", \"application/atom+xml\"},\n {\"au\", \"audio/basic\"},\n {\"avi\", \"video/x-msvideo\"},\n {\"bcpio\", \"application/x-bcpio\"},\n {\"bin\", \"application/octet-stream\"},\n {\"bmp\", \"image/bmp\"},\n {\"cdf\", \"application/x-netcdf\"},\n {\"cgm\", \"image/cgm\"},\n {\"class\", \"application/octet-stream\"},\n {\"cpio\", \"application/x-cpio\"},\n {\"cpt\", \"application/mac-compactpro\"},\n {\"csh\", \"application/x-csh\"},\n {\"css\", \"text/css\"},\n {\"dcr\", \"application/x-director\"},\n {\"dif\", \"video/x-dv\"},\n {\"dir\", \"application/x-director\"},\n {\"djv\", \"image/vnd.djvu\"},\n {\"djvu\", \"image/vnd.djvu\"},\n {\"dll\", \"application/octet-stream\"},\n {\"dmg\", \"application/octet-stream\"},\n {\"dms\", \"application/octet-stream\"},\n {\"doc\", \"application/msword\"},\n {\"docx\",\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"},\n {\"dotx\", \"application/vnd.openxmlformats-officedocument.wordprocessingml.template\"},\n {\"docm\",\"application/vnd.ms-word.document.macroEnabled.12\"},\n {\"dotm\",\"application/vnd.ms-word.template.macroEnabled.12\"},\n {\"dtd\", \"application/xml-dtd\"},\n {\"dv\", \"video/x-dv\"},\n {\"dvi\", \"application/x-dvi\"},\n {\"dxr\", \"application/x-director\"},\n {\"eps\", \"application/postscript\"},\n {\"etx\", \"text/x-setext\"},\n {\"exe\", \"application/octet-stream\"},\n {\"ez\", \"application/andrew-inset\"},\n {\"gif\", \"image/gif\"},\n {\"gram\", \"application/srgs\"},\n {\"grxml\", \"application/srgs+xml\"},\n {\"gtar\", \"application/x-gtar\"},\n {\"hdf\", \"application/x-hdf\"},\n {\"hqx\", \"application/mac-binhex40\"},\n {\"htc\", \"text/x-component\"},\n {\"htm\", \"text/html\"},\n {\"html\", \"text/html\"},\n {\"ice\", \"x-conference/x-cooltalk\"},\n {\"ico\", \"image/x-icon\"},\n {\"ics\", \"text/calendar\"},\n {\"ief\", \"image/ief\"},\n {\"ifb\", \"text/calendar\"},\n {\"iges\", \"model/iges\"},\n {\"igs\", \"model/iges\"},\n {\"jnlp\", \"application/x-java-jnlp-file\"},\n {\"jp2\", \"image/jp2\"},\n {\"jpe\", \"image/jpeg\"},\n {\"jpeg\", \"image/jpeg\"},\n {\"jpg\", \"image/jpeg\"},\n {\"js\", \"application/x-javascript\"},\n {\"kar\", \"audio/midi\"},\n {\"latex\", \"application/x-latex\"},\n {\"lha\", \"application/octet-stream\"},\n {\"lzh\", \"application/octet-stream\"},\n {\"m3u\", \"audio/x-mpegurl\"},\n {\"m4a\", \"audio/mp4a-latm\"},\n {\"m4b\", \"audio/mp4a-latm\"},\n {\"m4p\", \"audio/mp4a-latm\"},\n {\"m4u\", \"video/vnd.mpegurl\"},\n {\"m4v\", \"video/x-m4v\"},\n {\"mac\", \"image/x-macpaint\"},\n {\"man\", \"application/x-troff-man\"},\n {\"mathml\", \"application/mathml+xml\"},\n {\"me\", \"application/x-troff-me\"},\n {\"mesh\", \"model/mesh\"},\n {\"mid\", \"audio/midi\"},\n {\"midi\", \"audio/midi\"},\n {\"mif\", \"application/vnd.mif\"},\n {\"mov\", \"video/quicktime\"},\n {\"movie\", \"video/x-sgi-movie\"},\n {\"mp2\", \"audio/mpeg\"},\n {\"mp3\", \"audio/mpeg\"},\n {\"mp4\", \"video/mp4\"},\n {\"mpe\", \"video/mpeg\"},\n {\"mpeg\", \"video/mpeg\"},\n {\"mpg\", \"video/mpeg\"},\n {\"mpga\", \"audio/mpeg\"},\n {\"ms\", \"application/x-troff-ms\"},\n {\"msh\", \"model/mesh\"},\n {\"mxu\", \"video/vnd.mpegurl\"},\n {\"nc\", \"application/x-netcdf\"},\n {\"oda\", \"application/oda\"},\n {\"ogg\", \"application/ogg\"},\n {\"pbm\", \"image/x-portable-bitmap\"},\n {\"pct\", \"image/pict\"},\n {\"pdb\", \"chemical/x-pdb\"},\n {\"pdf\", \"application/pdf\"},\n {\"pgm\", \"image/x-portable-graymap\"},\n {\"pgn\", \"application/x-chess-pgn\"},\n {\"pic\", \"image/pict\"},\n {\"pict\", \"image/pict\"},\n {\"png\", \"image/png\"}, \n {\"pnm\", \"image/x-portable-anymap\"},\n {\"pnt\", \"image/x-macpaint\"},\n {\"pntg\", \"image/x-macpaint\"},\n {\"ppm\", \"image/x-portable-pixmap\"},\n {\"ppt\", \"application/vnd.ms-powerpoint\"},\n {\"pptx\",\"application/vnd.openxmlformats-officedocument.presentationml.presentation\"},\n {\"potx\",\"application/vnd.openxmlformats-officedocument.presentationml.template\"},\n {\"ppsx\",\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\"},\n {\"ppam\",\"application/vnd.ms-powerpoint.addin.macroEnabled.12\"},\n {\"pptm\",\"application/vnd.ms-powerpoint.presentation.macroEnabled.12\"},\n {\"potm\",\"application/vnd.ms-powerpoint.template.macroEnabled.12\"},\n {\"ppsm\",\"application/vnd.ms-powerpoint.slideshow.macroEnabled.12\"},\n {\"ps\", \"application/postscript\"},\n {\"qt\", \"video/quicktime\"},\n {\"qti\", \"image/x-quicktime\"},\n {\"qtif\", \"image/x-quicktime\"},\n {\"ra\", \"audio/x-pn-realaudio\"},\n {\"ram\", \"audio/x-pn-realaudio\"},\n {\"ras\", \"image/x-cmu-raster\"},\n {\"rdf\", \"application/rdf+xml\"},\n {\"rgb\", \"image/x-rgb\"},\n {\"rm\", \"application/vnd.rn-realmedia\"},\n {\"roff\", \"application/x-troff\"},\n {\"rtf\", \"text/rtf\"},\n {\"rtx\", \"text/richtext\"},\n {\"sgm\", \"text/sgml\"},\n {\"sgml\", \"text/sgml\"},\n {\"sh\", \"application/x-sh\"},\n {\"shar\", \"application/x-shar\"},\n {\"silo\", \"model/mesh\"},\n {\"sit\", \"application/x-stuffit\"},\n {\"skd\", \"application/x-koan\"},\n {\"skm\", \"application/x-koan\"},\n {\"skp\", \"application/x-koan\"},\n {\"skt\", \"application/x-koan\"},\n {\"smi\", \"application/smil\"},\n {\"smil\", \"application/smil\"},\n {\"snd\", \"audio/basic\"},\n {\"so\", \"application/octet-stream\"},\n {\"spl\", \"application/x-futuresplash\"},\n {\"src\", \"application/x-wais-source\"},\n {\"sv4cpio\", \"application/x-sv4cpio\"},\n {\"sv4crc\", \"application/x-sv4crc\"},\n {\"svg\", \"image/svg+xml\"},\n {\"swf\", \"application/x-shockwave-flash\"},\n {\"t\", \"application/x-troff\"},\n {\"tar\", \"application/x-tar\"},\n {\"tcl\", \"application/x-tcl\"},\n {\"tex\", \"application/x-tex\"},\n {\"texi\", \"application/x-texinfo\"},\n {\"texinfo\", \"application/x-texinfo\"},\n {\"tif\", \"image/tiff\"},\n {\"tiff\", \"image/tiff\"},\n {\"tr\", \"application/x-troff\"},\n {\"tsv\", \"text/tab-separated-values\"},\n {\"txt\", \"text/plain\"},\n {\"ustar\", \"application/x-ustar\"},\n {\"vcd\", \"application/x-cdlink\"},\n {\"vrml\", \"model/vrml\"},\n {\"vxml\", \"application/voicexml+xml\"},\n {\"wav\", \"audio/x-wav\"},\n {\"wbmp\", \"image/vnd.wap.wbmp\"},\n {\"wbmxl\", \"application/vnd.wap.wbxml\"},\n {\"wml\", \"text/vnd.wap.wml\"},\n {\"wmlc\", \"application/vnd.wap.wmlc\"},\n {\"wmls\", \"text/vnd.wap.wmlscript\"},\n {\"wmlsc\", \"application/vnd.wap.wmlscriptc\"},\n {\"wrl\", \"model/vrml\"},\n {\"xbm\", \"image/x-xbitmap\"},\n {\"xht\", \"application/xhtml+xml\"},\n {\"xhtml\", \"application/xhtml+xml\"},\n {\"xls\", \"application/vnd.ms-excel\"}, \n {\"xml\", \"application/xml\"},\n {\"xpm\", \"image/x-xpixmap\"},\n {\"xsl\", \"application/xml\"},\n {\"xlsx\",\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"},\n {\"xltx\",\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\"},\n {\"xlsm\",\"application/vnd.ms-excel.sheet.macroEnabled.12\"},\n {\"xltm\",\"application/vnd.ms-excel.template.macroEnabled.12\"},\n {\"xlam\",\"application/vnd.ms-excel.addin.macroEnabled.12\"},\n {\"xlsb\",\"application/vnd.ms-excel.sheet.binary.macroEnabled.12\"},\n {\"xslt\", \"application/xslt+xml\"},\n {\"xul\", \"application/vnd.mozilla.xul+xml\"},\n {\"xwd\", \"image/x-xwindowdump\"},\n {\"xyz\", \"chemical/x-xyz\"},\n {\"zip\", \"application/zip\"}\n };\n }\n}\n"
},
{
"answer_id": 19401456,
"author": "Ognyan Dimitrov",
"author_id": 1042934,
"author_profile": "https://Stackoverflow.com/users/1042934",
"pm_score": 0,
"selected": false,
"text": "public class DefaultMimeResolver : IMimeResolver\n{\n private readonly IFileRepository _fileRepository;\n\n public DefaultMimeResolver(IFileRepository fileRepository)\n {\n _fileRepository = fileRepository;\n }\n\n [DllImport(@\"urlmon.dll\", CharSet = CharSet.Auto)]\n private static extern System.UInt32 FindMimeFromData(\n System.UInt32 pBC, [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,\n [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,\n System.UInt32 cbSize,\n [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,\n System.UInt32 dwMimeFlags,\n out System.UInt32 ppwzMimeOut,\n System.UInt32 dwReserverd);\n\n\n public string GetMimeTypeFromFileExtension(string fileExtension)\n {\n if (string.IsNullOrEmpty(fileExtension))\n {\n throw new ArgumentNullException(\"fileExtension\");\n }\n\n string mimeType = GetMimeTypeFromList(fileExtension);\n\n if (String.IsNullOrEmpty(mimeType))\n {\n mimeType = GetMimeTypeFromRegistry(fileExtension);\n }\n\n return mimeType;\n }\n\n public string GetMimeTypeFromFile(string filePath)\n {\n if (string.IsNullOrEmpty(filePath))\n {\n throw new ArgumentNullException(\"filePath\");\n }\n\n if (!File.Exists(filePath))\n {\n throw new FileNotFoundException(\"File not found : \", filePath);\n }\n\n string mimeType = GetMimeTypeFromList(Path.GetExtension(filePath).ToLower());\n\n if (String.IsNullOrEmpty(mimeType))\n {\n mimeType = GetMimeTypeFromRegistry(Path.GetExtension(filePath).ToLower());\n\n if (String.IsNullOrEmpty(mimeType))\n {\n mimeType = GetMimeTypeFromFileInternal(filePath);\n }\n }\n\n return mimeType;\n }\n\n private string GetMimeTypeFromList(string fileExtension)\n {\n string mimeType = null;\n\n if (fileExtension.StartsWith(\".\"))\n {\n fileExtension = fileExtension.TrimStart('.');\n }\n\n if (!String.IsNullOrEmpty(fileExtension) && _mimeTypes.ContainsKey(fileExtension))\n {\n mimeType = _mimeTypes[fileExtension];\n }\n\n return mimeType;\n }\n\n private string GetMimeTypeFromRegistry(string fileExtension)\n {\n string mimeType = null;\n try\n {\n RegistryKey key = Registry.ClassesRoot.OpenSubKey(fileExtension);\n\n if (key != null && key.GetValue(\"Content Type\") != null)\n {\n mimeType = key.GetValue(\"Content Type\").ToString();\n }\n }\n catch (Exception)\n {\n // Empty. When this code is running in limited mode accessing registry is not allowed.\n }\n\n return mimeType;\n }\n\n private string GetMimeTypeFromFileInternal(string filePath)\n {\n string mimeType = null;\n\n if (!File.Exists(filePath))\n {\n return null;\n }\n\n byte[] byteBuffer = new byte[256];\n\n using (FileStream fileStream = _fileRepository.Get(filePath))\n {\n if (fileStream.Length >= 256)\n {\n fileStream.Read(byteBuffer, 0, 256);\n }\n else\n {\n fileStream.Read(byteBuffer, 0, (int)fileStream.Length);\n }\n }\n\n try\n {\n UInt32 MimeTypeNum;\n\n FindMimeFromData(0, null, byteBuffer, 256, null, 0, out MimeTypeNum, 0);\n\n IntPtr mimeTypePtr = new IntPtr(MimeTypeNum);\n string mimeTypeFromFile = Marshal.PtrToStringUni(mimeTypePtr);\n\n Marshal.FreeCoTaskMem(mimeTypePtr);\n\n if (!String.IsNullOrEmpty(mimeTypeFromFile) && mimeTypeFromFile != \"text/plain\" && mimeTypeFromFile != \"application/octet-stream\")\n {\n mimeType = mimeTypeFromFile;\n }\n }\n catch\n {\n // Empty. \n }\n\n return mimeType;\n }\n\n private readonly Dictionary<string, string> _mimeTypes = new Dictionary<string, string>\n {\n {\"ai\", \"application/postscript\"},\n {\"aif\", \"audio/x-aiff\"},\n {\"aifc\", \"audio/x-aiff\"},\n {\"aiff\", \"audio/x-aiff\"},\n {\"asc\", \"text/plain\"},\n {\"atom\", \"application/atom+xml\"},\n {\"au\", \"audio/basic\"},\n {\"avi\", \"video/x-msvideo\"},\n {\"bcpio\", \"application/x-bcpio\"},\n {\"bin\", \"application/octet-stream\"},\n {\"bmp\", \"image/bmp\"},\n {\"cdf\", \"application/x-netcdf\"},\n {\"cgm\", \"image/cgm\"},\n {\"class\", \"application/octet-stream\"},\n {\"cpio\", \"application/x-cpio\"},\n {\"cpt\", \"application/mac-compactpro\"},\n {\"csh\", \"application/x-csh\"},\n {\"css\", \"text/css\"},\n {\"dcr\", \"application/x-director\"},\n {\"dif\", \"video/x-dv\"},\n {\"dir\", \"application/x-director\"},\n {\"djv\", \"image/vnd.djvu\"},\n {\"djvu\", \"image/vnd.djvu\"},\n {\"dll\", \"application/octet-stream\"},\n {\"dmg\", \"application/octet-stream\"},\n {\"dms\", \"application/octet-stream\"},\n {\"doc\", \"application/msword\"},\n {\"docx\", \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"},\n {\"dotx\", \"application/vnd.openxmlformats-officedocument.wordprocessingml.template\"},\n {\"docm\", \"application/vnd.ms-word.document.macroEnabled.12\"},\n {\"dotm\", \"application/vnd.ms-word.template.macroEnabled.12\"},\n {\"dtd\", \"application/xml-dtd\"},\n {\"dv\", \"video/x-dv\"},\n {\"dvi\", \"application/x-dvi\"},\n {\"dxr\", \"application/x-director\"},\n {\"eps\", \"application/postscript\"},\n {\"etx\", \"text/x-setext\"},\n {\"exe\", \"application/octet-stream\"},\n {\"ez\", \"application/andrew-inset\"},\n {\"gif\", \"image/gif\"},\n {\"gram\", \"application/srgs\"},\n {\"grxml\", \"application/srgs+xml\"},\n {\"gtar\", \"application/x-gtar\"},\n {\"hdf\", \"application/x-hdf\"},\n {\"hqx\", \"application/mac-binhex40\"},\n {\"htc\", \"text/x-component\"},\n {\"htm\", \"text/html\"},\n {\"html\", \"text/html\"},\n {\"ice\", \"x-conference/x-cooltalk\"},\n {\"ico\", \"image/x-icon\"},\n {\"ics\", \"text/calendar\"},\n {\"ief\", \"image/ief\"},\n {\"ifb\", \"text/calendar\"},\n {\"iges\", \"model/iges\"},\n {\"igs\", \"model/iges\"},\n {\"jnlp\", \"application/x-java-jnlp-file\"},\n {\"jp2\", \"image/jp2\"},\n {\"jpe\", \"image/jpeg\"},\n {\"jpeg\", \"image/jpeg\"},\n {\"jpg\", \"image/jpeg\"},\n {\"js\", \"application/x-javascript\"},\n {\"kar\", \"audio/midi\"},\n {\"latex\", \"application/x-latex\"},\n {\"lha\", \"application/octet-stream\"},\n {\"lzh\", \"application/octet-stream\"},\n {\"m3u\", \"audio/x-mpegurl\"},\n {\"m4a\", \"audio/mp4a-latm\"},\n {\"m4b\", \"audio/mp4a-latm\"},\n {\"m4p\", \"audio/mp4a-latm\"},\n {\"m4u\", \"video/vnd.mpegurl\"},\n {\"m4v\", \"video/x-m4v\"},\n {\"mac\", \"image/x-macpaint\"},\n {\"man\", \"application/x-troff-man\"},\n {\"mathml\", \"application/mathml+xml\"},\n {\"me\", \"application/x-troff-me\"},\n {\"mesh\", \"model/mesh\"},\n {\"mid\", \"audio/midi\"},\n {\"midi\", \"audio/midi\"},\n {\"mif\", \"application/vnd.mif\"},\n {\"mov\", \"video/quicktime\"},\n {\"movie\", \"video/x-sgi-movie\"},\n {\"mp2\", \"audio/mpeg\"},\n {\"mp3\", \"audio/mpeg\"},\n {\"mp4\", \"video/mp4\"},\n {\"mpe\", \"video/mpeg\"},\n {\"mpeg\", \"video/mpeg\"},\n {\"mpg\", \"video/mpeg\"},\n {\"mpga\", \"audio/mpeg\"},\n {\"ms\", \"application/x-troff-ms\"},\n {\"msh\", \"model/mesh\"},\n {\"mxu\", \"video/vnd.mpegurl\"},\n {\"nc\", \"application/x-netcdf\"},\n {\"oda\", \"application/oda\"},\n {\"ogg\", \"application/ogg\"},\n {\"pbm\", \"image/x-portable-bitmap\"},\n {\"pct\", \"image/pict\"},\n {\"pdb\", \"chemical/x-pdb\"},\n {\"pdf\", \"application/pdf\"},\n {\"pgm\", \"image/x-portable-graymap\"},\n {\"pgn\", \"application/x-chess-pgn\"},\n {\"pic\", \"image/pict\"},\n {\"pict\", \"image/pict\"},\n {\"png\", \"image/png\"},\n {\"pnm\", \"image/x-portable-anymap\"},\n {\"pnt\", \"image/x-macpaint\"},\n {\"pntg\", \"image/x-macpaint\"},\n {\"ppm\", \"image/x-portable-pixmap\"},\n {\"ppt\", \"application/vnd.ms-powerpoint\"},\n {\"pptx\", \"application/vnd.openxmlformats-officedocument.presentationml.presentation\"},\n {\"potx\", \"application/vnd.openxmlformats-officedocument.presentationml.template\"},\n {\"ppsx\", \"application/vnd.openxmlformats-officedocument.presentationml.slideshow\"},\n {\"ppam\", \"application/vnd.ms-powerpoint.addin.macroEnabled.12\"},\n {\"pptm\", \"application/vnd.ms-powerpoint.presentation.macroEnabled.12\"},\n {\"potm\", \"application/vnd.ms-powerpoint.template.macroEnabled.12\"},\n {\"ppsm\", \"application/vnd.ms-powerpoint.slideshow.macroEnabled.12\"},\n {\"ps\", \"application/postscript\"},\n {\"qt\", \"video/quicktime\"},\n {\"qti\", \"image/x-quicktime\"},\n {\"qtif\", \"image/x-quicktime\"},\n {\"ra\", \"audio/x-pn-realaudio\"},\n {\"ram\", \"audio/x-pn-realaudio\"},\n {\"ras\", \"image/x-cmu-raster\"},\n {\"rdf\", \"application/rdf+xml\"},\n {\"rgb\", \"image/x-rgb\"},\n {\"rm\", \"application/vnd.rn-realmedia\"},\n {\"roff\", \"application/x-troff\"},\n {\"rtf\", \"text/rtf\"},\n {\"rtx\", \"text/richtext\"},\n {\"sgm\", \"text/sgml\"},\n {\"sgml\", \"text/sgml\"},\n {\"sh\", \"application/x-sh\"},\n {\"shar\", \"application/x-shar\"},\n {\"silo\", \"model/mesh\"},\n {\"sit\", \"application/x-stuffit\"},\n {\"skd\", \"application/x-koan\"},\n {\"skm\", \"application/x-koan\"},\n {\"skp\", \"application/x-koan\"},\n {\"skt\", \"application/x-koan\"},\n {\"smi\", \"application/smil\"},\n {\"smil\", \"application/smil\"},\n {\"snd\", \"audio/basic\"},\n {\"so\", \"application/octet-stream\"},\n {\"spl\", \"application/x-futuresplash\"},\n {\"src\", \"application/x-wais-source\"},\n {\"sv4cpio\", \"application/x-sv4cpio\"},\n {\"sv4crc\", \"application/x-sv4crc\"},\n {\"svg\", \"image/svg+xml\"},\n {\"swf\", \"application/x-shockwave-flash\"},\n {\"t\", \"application/x-troff\"},\n {\"tar\", \"application/x-tar\"},\n {\"tcl\", \"application/x-tcl\"},\n {\"tex\", \"application/x-tex\"},\n {\"texi\", \"application/x-texinfo\"},\n {\"texinfo\", \"application/x-texinfo\"},\n {\"tif\", \"image/tiff\"},\n {\"tiff\", \"image/tiff\"},\n {\"tr\", \"application/x-troff\"},\n {\"tsv\", \"text/tab-separated-values\"},\n {\"txt\", \"text/plain\"},\n {\"ustar\", \"application/x-ustar\"},\n {\"vcd\", \"application/x-cdlink\"},\n {\"vrml\", \"model/vrml\"},\n {\"vxml\", \"application/voicexml+xml\"},\n {\"wav\", \"audio/x-wav\"},\n {\"wbmp\", \"image/vnd.wap.wbmp\"},\n {\"wbmxl\", \"application/vnd.wap.wbxml\"},\n {\"wml\", \"text/vnd.wap.wml\"},\n {\"wmlc\", \"application/vnd.wap.wmlc\"},\n {\"wmls\", \"text/vnd.wap.wmlscript\"},\n {\"wmlsc\", \"application/vnd.wap.wmlscriptc\"},\n {\"wrl\", \"model/vrml\"},\n {\"xbm\", \"image/x-xbitmap\"},\n {\"xht\", \"application/xhtml+xml\"},\n {\"xhtml\", \"application/xhtml+xml\"},\n {\"xls\", \"application/vnd.ms-excel\"},\n {\"xml\", \"application/xml\"},\n {\"xpm\", \"image/x-xpixmap\"},\n {\"xsl\", \"application/xml\"},\n {\"xlsx\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"},\n {\"xltx\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.template\"},\n {\"xlsm\", \"application/vnd.ms-excel.sheet.macroEnabled.12\"},\n {\"xltm\", \"application/vnd.ms-excel.template.macroEnabled.12\"},\n {\"xlam\", \"application/vnd.ms-excel.addin.macroEnabled.12\"},\n {\"xlsb\", \"application/vnd.ms-excel.sheet.binary.macroEnabled.12\"},\n {\"xslt\", \"application/xslt+xml\"},\n {\"xul\", \"application/vnd.mozilla.xul+xml\"},\n {\"xwd\", \"image/x-xwindowdump\"},\n {\"xyz\", \"chemical/x-xyz\"},\n {\"zip\", \"application/zip\"}\n };\n}\n"
},
{
"answer_id": 22475295,
"author": "tie",
"author_id": 922741,
"author_profile": "https://Stackoverflow.com/users/922741",
"pm_score": 2,
"selected": false,
"text": "using System.Runtime.InteropServices;\n public static string GetMimeFromFile(string filename)\n{\n\n if (!File.Exists(filename))\n throw new FileNotFoundException(filename + \" not found\");\n\n const int maxContent = 256;\n\n var buffer = new byte[maxContent];\n using (var fs = new FileStream(filename, FileMode.Open))\n {\n if (fs.Length >= maxContent)\n fs.Read(buffer, 0, maxContent);\n else\n fs.Read(buffer, 0, (int) fs.Length);\n }\n\n var mimeTypePtr = IntPtr.Zero;\n try\n {\n var result = FindMimeFromData(IntPtr.Zero, null, buffer, maxContent, null, 0, out mimeTypePtr, 0);\n if (result != 0)\n {\n Marshal.FreeCoTaskMem(mimeTypePtr);\n throw Marshal.GetExceptionForHR(result);\n }\n\n var mime = Marshal.PtrToStringUni(mimeTypePtr);\n Marshal.FreeCoTaskMem(mimeTypePtr);\n return mime;\n }\n catch (Exception e)\n {\n if (mimeTypePtr != IntPtr.Zero)\n {\n Marshal.FreeCoTaskMem(mimeTypePtr);\n }\n return \"unknown/unknown\";\n }\n}\n\n[DllImport(\"urlmon.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]\nprivate static extern int FindMimeFromData(IntPtr pBC,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,\n [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,\n int cbSize,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,\n int dwMimeFlags,\n out IntPtr ppwzMimeOut,\n int dwReserved);\n"
},
{
"answer_id": 24089256,
"author": "cookch10msu",
"author_id": 1112224,
"author_profile": "https://Stackoverflow.com/users/1112224",
"pm_score": 2,
"selected": false,
"text": "Imports System.Runtime.InteropServices\n\n<DllImport(\"urlmon.dll\", CharSet:=CharSet.Auto)> _\nPrivate Shared Function FindMimeFromData(pBC As System.UInt32, <MarshalAs(UnmanagedType.LPStr)> pwzUrl As System.String, <MarshalAs(UnmanagedType.LPArray)> pBuffer As Byte(), cbSize As System.UInt32, <MarshalAs(UnmanagedType.LPStr)> pwzMimeProposed As System.String, dwMimeFlags As System.UInt32, _\nByRef ppwzMimeOut As System.UInt32, dwReserverd As System.UInt32) As System.UInt32\nEnd Function\nPrivate Function GetMimeType(ByVal f As FileInfo) As String\n 'See http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature\n Dim returnValue As String = \"\"\n Dim fileStream As FileStream = Nothing\n Dim fileStreamLength As Long = 0\n Dim fileStreamIsLessThanBByteSize As Boolean = False\n\n Const byteSize As Integer = 255\n Const bbyteSize As Integer = byteSize + 1\n\n Const ambiguousMimeType As String = \"application/octet-stream\"\n Const unknownMimeType As String = \"unknown/unknown\"\n\n Dim buffer As Byte() = New Byte(byteSize) {}\n Dim fnGetMimeTypeValue As New Func(Of Byte(), Integer, String)(\n Function(_buffer As Byte(), _bbyteSize As Integer) As String\n Dim _returnValue As String = \"\"\n Dim mimeType As UInt32 = 0\n FindMimeFromData(0, Nothing, _buffer, _bbyteSize, Nothing, 0, mimeType, 0)\n Dim mimeTypePtr As IntPtr = New IntPtr(mimeType)\n _returnValue = Marshal.PtrToStringUni(mimeTypePtr)\n Marshal.FreeCoTaskMem(mimeTypePtr)\n Return _returnValue\n End Function)\n\n If (f.Exists()) Then\n Try\n fileStream = New FileStream(f.FullName(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)\n fileStreamLength = fileStream.Length()\n\n If (fileStreamLength >= bbyteSize) Then\n fileStream.Read(buffer, 0, bbyteSize)\n Else\n fileStreamIsLessThanBByteSize = True\n fileStream.Read(buffer, 0, CInt(fileStreamLength))\n End If\n\n returnValue = fnGetMimeTypeValue(buffer, bbyteSize)\n\n If (returnValue.Equals(ambiguousMimeType, StringComparison.OrdinalIgnoreCase) AndAlso fileStreamIsLessThanBByteSize AndAlso fileStreamLength > 0) Then\n 'Duplicate the stream content until the stream length is >= bbyteSize to get a more deterministic mime type analysis.\n Dim currentBuffer As Byte() = buffer.Take(fileStreamLength).ToArray()\n Dim repeatCount As Integer = Math.Floor((bbyteSize / fileStreamLength) + 1)\n Dim bBufferList As List(Of Byte) = New List(Of Byte)\n While (repeatCount > 0)\n bBufferList.AddRange(currentBuffer)\n repeatCount -= 1\n End While\n Dim bbuffer As Byte() = bBufferList.Take(bbyteSize).ToArray()\n returnValue = fnGetMimeTypeValue(bbuffer, bbyteSize)\n End If\n Catch ex As Exception\n returnValue = unknownMimeType\n Finally\n If (fileStream IsNot Nothing) Then fileStream.Close()\n End Try\n End If\n Return returnValue\nEnd Function\n"
},
{
"answer_id": 45365396,
"author": "maechler",
"author_id": 4494425,
"author_profile": "https://Stackoverflow.com/users/4494425",
"pm_score": 0,
"selected": false,
"text": "MimeTypes g_MimeTypes = new MimeTypes(\"mime-types.xml\");\nsbyte [] fileData = null;\n\nusing (System.IO.FileStream srcFile = new System.IO.FileStream(strFile, System.IO.FileMode.Open))\n{\n byte [] data = new byte[srcFile.Length];\n srcFile.Read(data, 0, (Int32)srcFile.Length);\n fileData = Winista.Mime.SupportUtil.ToSByteArray(data);\n}\n\nMimeType oMimeType = g_MimeTypes.GetMimeType(fileData);\n"
},
{
"answer_id": 59190598,
"author": "Ivan Kirichuk",
"author_id": 9336690,
"author_profile": "https://Stackoverflow.com/users/9336690",
"pm_score": 0,
"selected": false,
"text": "UInt32 mimetype;\nFindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);\n AccessViolationException \"Attempted to read or write protected memory.\nThis is often an indication that other memory is corrupt\"\n [DllImport(\"urlmon.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, \n SetLastError = false)]\n static extern int FindMimeFromData(IntPtr pBC,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,\n [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, \n SizeParamIndex=3)]\n byte[] pBuffer,\n int cbSize,\n [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,\n int dwMimeFlags,\n out IntPtr ppwzMimeOut,\n int dwReserved);\n\n string getMimeFromFile(byte[] fileSource)\n {\n byte[] buffer = new byte[256];\n using (Stream stream = new MemoryStream(fileSource))\n {\n if (stream.Length >= 256)\n stream.Read(buffer, 0, 256);\n else\n stream.Read(buffer, 0, (int)stream.Length);\n }\n\n try\n {\n IntPtr mimeTypePtr;\n FindMimeFromData(IntPtr.Zero, null, buffer, buffer.Length,\n null, 0, out mimeTypePtr, 0);\n\n string mime = Marshal.PtrToStringUni(mimeTypePtr);\n Marshal.FreeCoTaskMem(mimeTypePtr);\n return mime;\n }\n catch (Exception ex)\n {\n return \"unknown/unknown\";\n }\n }\n"
},
{
"answer_id": 59371020,
"author": "GetoX",
"author_id": 4477336,
"author_profile": "https://Stackoverflow.com/users/4477336",
"pm_score": 0,
"selected": false,
"text": " //init\n var mimeTypes = new MimeTypes();\n\n //usage by filepath\n var mimeType1 = mimeTypes.GetMimeTypeFromFile(filePath);\n"
},
{
"answer_id": 60026738,
"author": "Egbert Nierop",
"author_id": 2410689,
"author_profile": "https://Stackoverflow.com/users/2410689",
"pm_score": 4,
"selected": false,
"text": "HeyRed.Mime.MimeGuesser.GuessMimeType public static string MimeTypeFrom(byte[] dataBytes, string fileName)\n {\n var contentType = HeyRed.Mime.MimeGuesser.GuessMimeType(dataBytes);\n if (string.IsNullOrEmpty(contentType))\n {\n return HeyRed.Mime.MimeTypesMap.GetMimeType(fileName);\n }\n return contentType;\n"
},
{
"answer_id": 61893701,
"author": "Artem Beziazychnyi",
"author_id": 9349612,
"author_profile": "https://Stackoverflow.com/users/9349612",
"pm_score": 3,
"selected": false,
"text": "private readonly Dictionary<string, byte[]> _mimeTypes = new Dictionary<string, byte[]>\n {\n {\"image/jpeg\", new byte[] {255, 216, 255}},\n {\"image/jpg\", new byte[] {255, 216, 255}},\n {\"image/pjpeg\", new byte[] {255, 216, 255}},\n {\"image/apng\", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},\n {\"image/png\", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},\n {\"image/bmp\", new byte[] {66, 77}},\n {\"image/gif\", new byte[] {71, 73, 70, 56}},\n };\n\nprivate bool ValidateMimeType(byte[] file, string contentType)\n {\n var imageType = _mimeTypes.SingleOrDefault(x => x.Key.Equals(contentType));\n\n return file.Take(imageType.Value.Length).SequenceEqual(imageType.Value);\n }\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2674/"
] |
58,513 |
<p>How do I Unit Test a MVC redirection?</p>
<pre><code>public ActionResult Create(Product product)
{
_productTask.Save(product);
return RedirectToAction("Success");
}
public ActionResult Success()
{
return View();
}
</code></pre>
<p>Is <a href="http://www.ayende.com/Blog/archive/2007/12/13/Dont-like-visibility-levels-change-that.aspx" rel="nofollow noreferrer">Ayende's</a> approach still the best way to go, with preview 5:</p>
<pre><code> public static void RenderView(this Controller self, string action)
{
typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} );
}
</code></pre>
<p>Seems odd to have to do this, especially as the MVC team have said they are writing the framework to be testable.</p>
|
[
{
"answer_id": 58818,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 6,
"selected": true,
"text": "[TestFixture]\npublic class RedirectTester\n{\n [Test]\n public void Should_redirect_to_success_action()\n {\n var controller = new RedirectController();\n var result = controller.Index() as RedirectToRouteResult;\n Assert.That(result, Is.Not.Null);\n Assert.That(result.Values[\"action\"], Is.EqualTo(\"success\"));\n }\n}\n\npublic class RedirectController : Controller\n{\n public ActionResult Index()\n {\n return RedirectToAction(\"success\");\n }\n}\n"
},
{
"answer_id": 35017463,
"author": "Kevin O'Shaughnessy",
"author_id": 4253016,
"author_profile": "https://Stackoverflow.com/users/4253016",
"pm_score": 0,
"selected": false,
"text": " [Test]\n public void ShouldRedirectToSuccessAction()\n {\n var controller = new RedirectController();\n var result = controller.Index() as RedirectToRouteResult;\n\n Assert.That(result.RouteValues[\"action\"], Is.EqualTo(\"success\"));\n }\n Assert.That(result.RouteValues[\"controller\"], Is.EqualTo(\"New\"));\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
58,517 |
<p>Is there a way to combine Enums in VB.net?</p>
|
[
{
"answer_id": 58526,
"author": "Jonas Follesø",
"author_id": 1199387,
"author_profile": "https://Stackoverflow.com/users/1199387",
"pm_score": 1,
"selected": false,
"text": "Enum |= &= Enum Flags Anchor"
},
{
"answer_id": 58527,
"author": "Dave Arkell",
"author_id": 4002,
"author_profile": "https://Stackoverflow.com/users/4002",
"pm_score": 7,
"selected": true,
"text": "<Flags()> _\nEnum CombinationEnums As Integer\n HasButton = 1\n TitleBar = 2\n [ReadOnly] = 4\n ETC = 8\nEnd Enum\n Dim settings As CombinationEnums\nsettings = CombinationEnums.TitleBar Or CombinationEnums.Readonly\n If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then\n Window.TitleBar = True\nEnd If\n"
},
{
"answer_id": 58535,
"author": "Tyler",
"author_id": 5642,
"author_profile": "https://Stackoverflow.com/users/5642",
"pm_score": 2,
"selected": false,
"text": "<FlagsAttribute> _\nPublic Enumeration SecurityRights\nNone = 0\nRead = 1\nWrite = 2\nExecute = 4\n Public Sub New ( _\n options As SecurityRights _\n)\n\nNew UserPrivileges(SecurityRights.Read OR SecurityRights.Execute)\n //Check to see if user has Write rights\nIf (user.Privileges And SecurityRights.Write = SecurityRigths.Write) Then\n //Do something clever...\nElse\n //Tell user he can't write.\nEnd If\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
58,520 |
<p>We need to regularly synchronize many dozens of binary files (project executables and DLLs) between many developers at several different locations, so that every developer has an up to date environment to build and test at. Due to nature of the project, updates must be done often and on-demand (overnight updates are not sufficient). This is not pretty, but we are stuck with it for a time.</p>
<p>We settled on using a regular version (source) control system: put everything into it as binary files, get-latest before testing and check-in updated DLL after testing.</p>
<p>It works fine, but a version control client has a lot of features which don't make sense for us and people occasionally get confused.</p>
<p>Are there any tools better suited for the task? Or may be a completely different approach?</p>
<p><strong>Update:</strong> </p>
<p>I need to clarify that it's not a tightly integrated project - more like extensible system with a heap of "plugins", including thrid-party ones. We need to make sure those modules-plugins works nicely with recent versions of each other and the core. Centralised build as was suggested was considered initially, but it's not an option.</p>
|
[
{
"answer_id": 58576,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 0,
"selected": false,
"text": "const char cvsid[] = \"@(#)INETOPS_filter_ip_$Revision: 1.9 $\"; what filter_ip | grep INETOPS INETOPS_filter_ip_$Revision: 1.9 $"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5733/"
] |
58,538 |
<p>I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation.</p>
<p>Does anyone know the best way to do this using the WiX framework.</p>
|
[
{
"answer_id": 58686,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 7,
"selected": true,
"text": "<Wix xmlns=\"http://schemas.microsoft.com/wix/2006/wi\"\n xmlns:util=\"http://schemas.microsoft.com/wix/UtilExtension\">\n\n <Component ...>\n ...\n <util:EventSource Log=\"Application\" Name=\"*source name*\"\n EventMessageFile=\"*path to message file*\"/>\n ...\n </Component>\n"
},
{
"answer_id": 574055,
"author": "Gordon",
"author_id": 69455,
"author_profile": "https://Stackoverflow.com/users/69455",
"pm_score": 4,
"selected": false,
"text": "<Util:EventSource\n xmlns:Util=\"http://schemas.microsoft.com/wix/UtilExtension\"\n Name=\"ROOT Builder\"\n Log=\"Application\"\n EventMessageFile=\"%SystemRoot%\\Microsoft.NET\\Framework\\v2.0.50727\\EventLogMessages.dll\"\n/>\n"
},
{
"answer_id": 5029747,
"author": "Daniel Fisher lennybacon",
"author_id": 12679,
"author_profile": "https://Stackoverflow.com/users/12679",
"pm_score": 4,
"selected": false,
"text": "EventMessageFile=\"[NETFRAMEWORK20INSTALLROOTDIR]EventLogMessages.dll\"\n EventMessageFile=\"[NETFRAMEWORK40FULLINSTALLROOTDIR]EventLogMessages.dll\"\n EventMessageFile=\"[NETFRAMEWORK40FULLINSTALLROOTDIR64]EventLogMessages.dll\"\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182/"
] |
58,540 |
<p>When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error:</p>
<blockquote>
<p>Parameters cannot be extracted from the SQL command. The provider might not help to parse parameter information from the command. In that case, use the "SQL command from variable" access mode, in which the entire SQL command is stored in a variable.<br>
ADDITIONAL INFORMATION:<br>
Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle) </p>
</blockquote>
<p>I have tried following the suggestion here but don't quite understand what is required:<a href="http://microsoftdw.blogspot.com/2005/11/parameterized-queries-against-oracle.html" rel="noreferrer">Parameterized queries against Oracle</a></p>
<p>Any ideas?</p>
|
[
{
"answer_id": 59116,
"author": "Rich Lawrence",
"author_id": 1281,
"author_profile": "https://Stackoverflow.com/users/1281",
"pm_score": 5,
"selected": true,
"text": "select * from book where book.BOOK_ID = ?\n \"select * from book where book.BOOK_ID = \" + @[User::BookID]\n"
},
{
"answer_id": 51440458,
"author": "toha",
"author_id": 1084742,
"author_profile": "https://Stackoverflow.com/users/1084742",
"pm_score": 1,
"selected": false,
"text": "SQL_DTFLOW_FULL variable data type STRING SELECT * FROM BOOK WHERE BOOK_ID = @BookID --@BookID is SQL Parameter\n SQL_DTFLOW_BOOKID variable data type STRING SQL_{TASK NAME}_{VariableName} SQL_DTFLOW_FULL SQL Command From Variable SQL_DTFLOW_FULL SQL_DTFLOW_FULL"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1281/"
] |
58,543 |
<p>I have an application that I would like to embed inside our companies CMS. The only way to do that (I am told), is to load it in an <code><iframe></code>.</p>
<p>Easy: just set <code>height</code> and <code>width</code> to <code>100%</code>! Except, it doesn't work.</p>
<p>I did find out about setting <code>frameborder</code> to <code>0</code>, so it at least <em>looks</em> like part of the site, but I'd prefer not to have an ugly scrollbar <em>inside</em> a page that allready has one.</p>
<p>Do you know of any tricks to do this?</p>
<p><strong>EDIT:</strong> I think I need to clarify my question somewhat:</p>
<ul>
<li>the company CMS displays the fluff and stuff for our whole website</li>
<li>most pages created through the CMS</li>
<li>my application isn't, but they will let me embedd it in an <code><iframe></code></li>
<li>I have no control over the <code>iframe</code>, so any solution must work from the referenced page (according to the <code>src</code> attribute of the <code>iframe</code> tag)</li>
<li>the CMS displays a footer, so setting the height to 1 million pixels is not a good idea</li>
</ul>
<p>Can I access the parent pages DOM from the referenced page? This might help, but I can see some people might not want this to be possible...</p>
<p>This technique seems to work (<a href="http://bytes.com/forum/thread91876.html" rel="noreferrer">gleaned</a> from several sources, but inspired by the <a href="http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe" rel="noreferrer">link</a> from the accepted answer:</p>
<p>In parent document:</p>
<pre><code><iframe id="MyIFRAME" name="MyIFRAME"
src="http://localhost/child.html"
scrolling="auto" width="100%" frameborder="0">
no iframes supported...
</iframe>
</code></pre>
<p>In child:</p>
<pre><code><!-- ... -->
<body>
<script type="text/javascript">
function resizeIframe() {
var docHeight;
if (typeof document.height != 'undefined') {
docHeight = document.height;
}
else if (document.compatMode && document.compatMode != 'BackCompat') {
docHeight = document.documentElement.scrollHeight;
}
else if (document.body
&& typeof document.body.scrollHeight != 'undefined') {
docHeight = document.body.scrollHeight;
}
// magic number: suppress generation of scrollbars...
docHeight += 20;
parent.document.getElementById('MyIFRAME').style.height = docHeight + "px";
}
parent.document.getElementById('MyIFRAME').onload = resizeIframe;
parent.window.onresize = resizeIframe;
</script>
</body>
</code></pre>
<p><strong>BTW:</strong> This will only work if parent and child are in the same domain due to a restriction in JavaScript for security reasons...</p>
|
[
{
"answer_id": 58562,
"author": "Adam Hepton",
"author_id": 2268,
"author_profile": "https://Stackoverflow.com/users/2268",
"pm_score": 0,
"selected": false,
"text": "scrolling=no iframe"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
58,547 |
<p>In C++ we acquiring a resource in a constructor and release it in a destructor.</p>
<p>So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever.</p>
<p>AFAIK java classes don't have destructors. So how does one do the resource management in Java.</p>
<p>For example:</p>
<pre><code>public int foo() {
Resource f = new Resource();
DoSomething(f);
f.Release();
}
</code></pre>
<p>How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we?</p>
|
[
{
"answer_id": 58552,
"author": "qbeuek",
"author_id": 5348,
"author_profile": "https://Stackoverflow.com/users/5348",
"pm_score": 3,
"selected": true,
"text": "public int foo() {\n Resource f = new Resource();\n try {\n DoSomething(f);\n }\n finally {\n f.Release();\n }\n}\n"
},
{
"answer_id": 58817,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "public int foo() {\n withResource(new WithResource() { public void run(Resource resource) {\n doSomething(resource);\n }});\n}\n\n...\n\npublic interface WithResource {\n void run(Resource resource);\n}\n\npublic static void withResource(WithResource handler) {\n Resource resource = new Resource();\n try {\n handler.run(resource);\n } finally {\n resource.release();\n }\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
] |
58,554 |
<p>I'm using Eclipse as my IDE for a C++ project, and I would love for it to tell me where a given symbol is defined and what the parameters are for a function.</p>
<p>However, there's a catch: I also use <a href="http://www.lazycplusplus.com/" rel="nofollow noreferrer">Lazy C++</a>, a tool that takes a single source file and generates the .h and the .cpp files. Those .lzz files look like headers, but this tool supports some very mild syntactic benefits, like combining nested namespaces into a qualified name. Additionally, it has some special tags to tell the tool specifically where to put what (in header or in source file).</p>
<p>So my typical SourceFile.lzz looks like this:</p>
<pre><code>$hdr
#include <iosfwd>
#include "ProjectA/BaseClass.h"
$end
$src
#include <iostream>
#include "ProjectB/OtherClass.h"
$end
// Forward declarations
namespace BigScope::ProjectB
{
class OtherClass;
}
namespace BigScope::ProjectA
{
class MyClass : public ProjectA::BaseClass
{
void SomeMethod(const ProjectB::OtherClass& Foo) { }
}
}
</code></pre>
<p>As you see, it's still recognizable C++, but with a few extras.</p>
<p>For some reason, CDT's indexer does not seem to want to index anything, and I don't know what's wrong. In the Indexer View, it shows me an empty tree, but tells me that it has some 15000 symbols and more stuff, none of which I can seem to access.</p>
<p>So here's my <strong>question</strong>: how can I make the Indexer output some more information about what it's doing and why it fails when it does so, and can I tweak it more than with just the GUI-accessible options?</p>
<p>Thanks,</p>
<p>Carl</p>
|
[
{
"answer_id": 837016,
"author": "Mike Kucera",
"author_id": 102367,
"author_profile": "https://Stackoverflow.com/users/102367",
"pm_score": 1,
"selected": false,
"text": "$hdr $end $src"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2095/"
] |
58,558 |
<p>I'm trying to check, using an automated discovery tool, when JAR files in remote J2EE application servers have changed content. Currently, the system downloads the whole JAR using WMI to checksum it locally, which is slow for large JARs.</p>
<p>For UNIXy servers (and Windows servers with Cygwin), I can just log in over SSH and run <code>md5sum foo.jar</code>. Ideally, I'd like to avoid installing extra software on the remote servers (there may be thousands), so is there a good way to do this on vanilla Windows servers?</p>
|
[
{
"answer_id": 837016,
"author": "Mike Kucera",
"author_id": 102367,
"author_profile": "https://Stackoverflow.com/users/102367",
"pm_score": 1,
"selected": false,
"text": "$hdr $end $src"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4702/"
] |
58,561 |
<p>I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?</p>
<p>An example :</p>
<pre><code>final StringBuilder hql = new StringBuilder();
hql.append( "select bob.id from " )
.append( bob.class.getName() ).append( " bob " )
.append( "where bob.id > 10");
final Query query = session.createQuery( hql.toString() );
return query.list();
</code></pre>
|
[
{
"answer_id": 58624,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 6,
"selected": false,
"text": "Criteria.forClass(bob.class.getName())\n .add(Restrictions.gt(\"id\", 10))\n .setProjection(Projections.property(\"id\"))\n );\n"
},
{
"answer_id": 17128402,
"author": "korosmatick",
"author_id": 1885786,
"author_profile": "https://Stackoverflow.com/users/1885786",
"pm_score": 4,
"selected": false,
"text": "Criteria criteria = session.createCriteria(bob.class);\n\ncriteria.add(Expression.gt(\"id\", 10));\n\ncriteria.setProjection(Projections.property(\"id\"));\n\ncriteria.addOrder(Order.asc(\"id\"));\n\nreturn criteria.list();\n"
},
{
"answer_id": 29683153,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 1,
"selected": false,
"text": "List<Long> myList = session.createSQLQuery(\"select single_column from table_name\")\n .addScalar(\"single_column\", StandardBasicTypes.LONG).list();\n"
},
{
"answer_id": 37202954,
"author": "Nalaka Dissanayake",
"author_id": 3650354,
"author_profile": "https://Stackoverflow.com/users/3650354",
"pm_score": -1,
"selected": false,
"text": " bob bb=null;\n\n Criteria criteria = session.createCriteria(bob.class); \n criteria.add(Restrictions.eq(\"id\",id));\n\n bb = (bob) criteria.uniqueResult();\n"
},
{
"answer_id": 57584281,
"author": "Ajinz",
"author_id": 11607606,
"author_profile": "https://Stackoverflow.com/users/11607606",
"pm_score": 2,
"selected": false,
"text": "SessionFactory sessionFactory; \nCriteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class);\ncrit.setProjection(Projections.property(\"id\"));\nList result = crit.list();\n [1,2,3] [{\"id\":1},{\"id\":2}] SessionFactory sessionFactory; \nCriteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class); \ncrit.setProjection(Projections.property(\"id\").as(\"id\")); \nList result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
58,564 |
<p>I have a core dump file from a process that has probably a file descriptor leak (it opens files and sockets but apparently sometimes forgets to close some of them). Is there a way to find out which files and sockets the process had opened before crashing? I can't easily reproduce the crash, so analyzing the core file seems to be the only way to get a hint on the bug.</p>
|
[
{
"answer_id": 58580,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "strace open socket close"
},
{
"answer_id": 58606,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "fd = open(\"/tmp/foo\",O_CREAT);\n//do stuff\nfd = open(\"/tmp/bar\",O_CREAT); //Oops, forgot to close(fd)\n"
},
{
"answer_id": 59039,
"author": "Martin Del Vecchio",
"author_id": 5397,
"author_profile": "https://Stackoverflow.com/users/5397",
"pm_score": 3,
"selected": false,
"text": "Anderson cxc # ls -l /proc/8247/fd\ntotal 0\nlrwx------ 1 root root 64 Sep 12 06:05 0 -> /dev/pts/0\nlrwx------ 1 root root 64 Sep 12 06:05 1 -> /dev/pts/0\nlrwx------ 1 root root 64 Sep 12 06:05 10 -> anon_inode:[eventpoll]\nlrwx------ 1 root root 64 Sep 12 06:05 11 -> socket:[124061]\nlrwx------ 1 root root 64 Sep 12 06:05 12 -> socket:[124063]\nlrwx------ 1 root root 64 Sep 12 06:05 13 -> socket:[124064]\nlrwx------ 1 root root 64 Sep 12 06:05 14 -> /dev/driver0\nlr-x------ 1 root root 64 Sep 12 06:05 16 -> /temp/app/whatever.tar.gz\nlr-x------ 1 root root 64 Sep 12 06:05 17 -> /dev/urandom\n"
},
{
"answer_id": 65548,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 4,
"selected": false,
"text": "$ gcc -g -o something something.c\n$ ./something\nSegmentation fault (core dumped)\n$ gdb something core\n"
},
{
"answer_id": 27558400,
"author": "JodieC",
"author_id": 1467450,
"author_profile": "https://Stackoverflow.com/users/1467450",
"pm_score": 2,
"selected": false,
"text": "strings strings core.14930|grep jodie\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148773/"
] |
58,584 |
<p>Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse?</p>
<p>I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions?</p>
<p>And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs?</p>
|
[
{
"answer_id": 58588,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 6,
"selected": true,
"text": "vim Eclipse yank cut VISUAL :'<,'>s/^/# /\n # '< '>"
},
{
"answer_id": 58592,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 2,
"selected": false,
"text": "V 40j d"
},
{
"answer_id": 58610,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 4,
"selected": false,
"text": "ma\n :'a,.d\n ma a a d :'a,.ya b - yank from 'a to current line and put in buffer 'b'\n:'a,.ya B - yank from 'a to current line and append to buffer 'b'\n:'a,.s/^/#/ - from 'a to current line, substitute '#' for line begin\n(i.e. comment out in Perl)\n:'s,.s#^#//# - from 'a to current line, substitute '//' for line begin\n(i.e. comment out in C++)\n 'a a (backtick-a) refers to the character marked by"
},
{
"answer_id": 65593,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 0,
"selected": false,
"text": ":'b,'ed\n V40j:s/^/#/\n"
},
{
"answer_id": 274837,
"author": "Dergachev",
"author_id": 9621,
"author_profile": "https://Stackoverflow.com/users/9621",
"pm_score": 1,
"selected": false,
"text": "V \"visual line selection mode\n30 \"optionally set scroll value to 30\nCTRL-D \"jump down a screen, repeated as necessary\ny \" yank your selection\n"
},
{
"answer_id": 560369,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": ":20,200d\n :20,200m300\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
58,614 |
<p>I'm developing a multi-threaded app for a Linux embedded platform.</p>
<p>At the moment I'm setting the stack size for each thread (via pthread_set_attr) to a fairly large default value. I would like to fine tune that value for each thread to something smaller to reduce my application's memory usage. I could go through the trial and error route of setting each thread's stack size to progressively smaller values until the program crashed, but the application uses ~15 threads each with completely different functionality/attributes so that approach would be extremely time consuming.</p>
<p>I would much rather prefer being able to directly measure each thread's stack usage. Is there some utility people can recommend to do this? (For example, I come from a vxWorks background and using the 'ti' command from the vxWorks shell directly gives stats on the stack usage as well as other useful info on the task status.)</p>
<p>Thanks</p>
|
[
{
"answer_id": 58628,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 2,
"selected": false,
"text": "__thread void* stack_start;\n__thread long stack_max_size = 0L;\n\nvoid check_stack_size() {\n // address of 'nowhere' approximates end of stack\n char nowhere;\n void* stack_end = (void*)&nowhere;\n // may want to double check stack grows downward on your platform\n long stack_size = (long)stack_start - (long)stack_end;\n // update max_stack_size for this thread\n if (stack_size > stack_max_size)\n stack_max_size = stack_size;\n}\n void thread_proc() {\n char nowhere;\n stack_start = (void*)&nowhere;\n // do stuff including calls to check_stack_size()\n // in deeply nested functions\n // output stack_max_size here\n}\n"
},
{
"answer_id": 58980,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "pthread_attr_getstackaddr"
},
{
"answer_id": 28856039,
"author": "d99kris",
"author_id": 485047,
"author_profile": "https://Stackoverflow.com/users/485047",
"pm_score": 3,
"selected": false,
"text": "valgrind --tool=drd --show-stack-usage=yes PROG\n stackusage PROG\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6089/"
] |
58,620 |
<p>How do I create a button control (with <code>CreateWindow</code> of a <code>BUTTON</code> window class) that has a standard system-wide size (especially height) that's consistent with the rest of Windows applications?
I should of course take DPI into account and probably other settings.</p>
<blockquote>
<p><strong>Remark:</strong> Using <code>USE_CW_DEFAULT</code> for width and height results in a 0, 0 size button, so that's not a solution.</p>
</blockquote>
|
[
{
"answer_id": 58689,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 4,
"selected": true,
"text": "LONG units = GetDialogBaseUnits();\nm_hButton = CreateWindow(TEXT(\"BUTTON\"), TEXT(\"Close\"), \n WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, \n 0, 0, MulDiv(LOWORD(units), 50, 4), MulDiv(HIWORD(units), 14, 8),\n hwnd, NULL, hInst, NULL);\n GetDialogBaseUnits() GetTextMetrics() tmHeight tmAveCharWidth TEXTMETRIC MapDialogRect() tmAveCharWidth GetTextExtentPoint32() BCM_GETIDEALSIZE Button_GetIdealSize()"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5049/"
] |
58,621 |
<p>How do I make an MD5 hash of a string with Delphi?</p>
|
[
{
"answer_id": 58626,
"author": "devstopfix",
"author_id": 3366,
"author_profile": "https://Stackoverflow.com/users/3366",
"pm_score": 5,
"selected": false,
"text": "uses SysUtils, IdGlobal, IdHash, IdHashMessageDigest;\n\nwith TIdHashMessageDigest5.Create do\ntry\n Result := TIdHash128.AsHex(HashValue('Hello, world'));\nfinally\n Free;\nend;\n DCPCrypt"
},
{
"answer_id": 83202,
"author": "Schalk Versteeg",
"author_id": 15724,
"author_profile": "https://Stackoverflow.com/users/15724",
"pm_score": 4,
"selected": false,
"text": "DCPCrypt"
},
{
"answer_id": 7412013,
"author": "mjn",
"author_id": 80901,
"author_profile": "https://Stackoverflow.com/users/80901",
"pm_score": 3,
"selected": false,
"text": "BobJenkinsHash (Value, Length(Value) * SizeOf(Value), 0)"
},
{
"answer_id": 18233500,
"author": "Stéphane B.",
"author_id": 281600,
"author_profile": "https://Stackoverflow.com/users/281600",
"pm_score": 4,
"selected": false,
"text": "class function getMd5HashString(value: string): string;\nvar\n hashMessageDigest5 : TIdHashMessageDigest5;\nbegin\n hashMessageDigest5 := nil;\n try\n hashMessageDigest5 := TIdHashMessageDigest5.Create;\n Result := IdGlobal.IndyLowerCase ( hashMessageDigest5.HashStringAsHex ( value ) );\n finally\n hashMessageDigest5.Free;\n end;\nend;\n"
},
{
"answer_id": 28132865,
"author": "StanE",
"author_id": 1854856,
"author_profile": "https://Stackoverflow.com/users/1854856",
"pm_score": 3,
"selected": false,
"text": "function MD5String(str: String): String;\nbegin\n with TIdHashMessageDigest5.Create do\n try\n Result := HashStringAsHex(str);\n finally\n Free;\n end;\nend;\n HashString HashStringAsHex HashBytes HashBytesAsHex HashStream HashStreamAsHex"
},
{
"answer_id": 60603912,
"author": "Schneider Infosystems Ltd",
"author_id": 2685300,
"author_profile": "https://Stackoverflow.com/users/2685300",
"pm_score": 4,
"selected": false,
"text": "system.Hash MD5HashCode := THashMD5.GetHashString(ClearTextString);\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3366/"
] |
58,622 |
<p>I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have <code>/* .. */</code> comments, and also has its own self-documentation facility which seems to be the pythonic way to document.</p>
<p>Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of?</p>
|
[
{
"answer_id": 58701,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": true,
"text": "\"\"\"@package docstring\nDocumentation for this module.\n\nMore details.\n\"\"\"\n\ndef func():\n \"\"\"Documentation for a function.\n\n More details.\n \"\"\"\n pass\n # ## @package pyexample\n# Documentation for this module.\n#\n# More details.\n\n## Documentation for a function.\n#\n# More details.\ndef func():\n pass\n OPTMIZE_OUTPUT_JAVA YES"
},
{
"answer_id": 59955,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 5,
"selected": false,
"text": "help()"
},
{
"answer_id": 35377654,
"author": "Havok",
"author_id": 439494,
"author_profile": "https://Stackoverflow.com/users/439494",
"pm_score": 5,
"selected": false,
"text": "autosummary_generate"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] |
58,638 |
<p>How do I take a set of polygons which contain arbitrary values and create a corresponding bitmap where each pixel contains the value of the polygon at that location?</p>
<p>To put the question into context, my polygons contain information about the average number of people per square kilometre within the polygon. I need to create a raster/bitmap that contains pixels representing the population in 200 metre bins.</p>
<p>I've done something similar in the past where I've used a polygon to create a mask by drawing into a bitmap and filling values, then converting the bitmap into an array that I can manipulate. I'm sure there's a better method for doing this!</p>
<p>I'm clarifying the question a bit more as requested.</p>
<ol>
<li>There are multiple polygons, each polygon is a set of vectors</li>
<li>Each polygon will have a single unique value</li>
<li>The polygons don't overlap</li>
</ol>
<p>Thanks</p>
<p>Nick</p>
|
[
{
"answer_id": 58793,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 2,
"selected": false,
"text": "PolygonToRaster_conversion (in_features, value_field, out_raster_dataset, cell_assignment, priority_field, cellsize)\n"
},
{
"answer_id": 799493,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 2,
"selected": false,
"text": " have a NY * 2 array of x positions: int x[NY][2]\nforeach polygon\n clear the array to -1\n for each edge line\n foreach horizontal raster line iy intersecting the line\n generate ix, the x position where the raster intersects the line\n if x[iy][0] == -1, set it to ix, else set x[iy][1] to ix\n end foreach iy\n end foreach edge\n foreach iy\n fill the pixels between x[iy][0] and x[iy][1] with the polygons label\n end foreach iy\nend foreach polygon\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
] |
58,649 |
<p>I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...). </p>
<p>Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically?
Thanks!</p>
|
[
{
"answer_id": 156640,
"author": "Dave Griffiths",
"author_id": 15379,
"author_profile": "https://Stackoverflow.com/users/15379",
"pm_score": 6,
"selected": true,
"text": "var directories = ImageMetadataReader.ReadMetadata(imagePath);\n\n// print out all metadata\nforeach (var directory in directories)\nforeach (var tag in directory.Tags)\n Console.WriteLine($\"{directory.Name} - {tag.Name} = {tag.Description}\");\n\n// access the date time\nvar subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();\nvar dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime);\n"
},
{
"answer_id": 63352062,
"author": "Shoaib Khan",
"author_id": 11795958,
"author_profile": "https://Stackoverflow.com/users/11795958",
"pm_score": 0,
"selected": false,
"text": "using (Metadata metadata = new Metadata(\"image.jpg\"))\n{\n IExif root = metadata.GetRootPackage() as IExif;\n if (root != null && root.ExifPackage != null)\n {\n Console.WriteLine(root.ExifPackage.DateTime);\n }\n}\n"
},
{
"answer_id": 74401570,
"author": "Gray Programmerz",
"author_id": 14919621,
"author_profile": "https://Stackoverflow.com/users/14919621",
"pm_score": 0,
"selected": false,
"text": "var prop = ShellFile.FromFilePath(f).Properties;\nvar Dimensions = prop.GetProperty(\"Dimensions\").ValueAsObject.ToString(); \n//1280 x 800\n\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091/"
] |
58,670 |
<p>Does anyone know a method to programmatically close the CD tray on Windows 2000 or higher?
Open CD tray exists, but I can't seem to make it close especially under W2k. </p>
<p>I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK.</p>
|
[
{
"answer_id": 58725,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 4,
"selected": true,
"text": "\n[DllImport(\"winmm.dll\", EntryPoint = \"mciSendStringA\", CharSet = CharSet.Ansi)]\n protected static extern int mciSendString(string lpstrCommand,StringBuilder lpstrReturnString,int uReturnLength,IntPtr hwndCallback);\n\n public void OpenCloseCD(bool Open)\n {\n if (Open)\n {\n mciSendString(\"set cdaudio door open\", null, 0, IntPtr.Zero);\n }\n else\n {\n mciSendString(\"set cdaudio door closed\", null, 0, IntPtr.Zero);\n }\n}\n\n"
},
{
"answer_id": 77291,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 4,
"selected": false,
"text": "bool ejectDisk(TCHAR driveLetter)\n{\n TCHAR tmp[10];\n _stprintf(tmp, _T(\"\\\\\\\\.\\\\%c:\"), driveLetter);\n HANDLE handle = CreateFile(tmp, GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);\n DWORD bytes = 0;\n DeviceIoControl(handle, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &bytes, 0);\n DeviceIoControl(handle, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0, &bytes, 0);\n DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, 0, 0, 0, 0, &bytes, 0);\n CloseHandle(handle);\n return true;\n}\n"
},
{
"answer_id": 30512979,
"author": "James Johnston",
"author_id": 562766,
"author_profile": "https://Stackoverflow.com/users/562766",
"pm_score": 3,
"selected": false,
"text": "CreateFile DeviceIoControl FSCTL_LOCK_VOLUME DeviceIoControl FSCTL_DISMOUNT_VOLUME DeviceIoControl IOCTL_STORAGE_MEDIA_REMOVAL PREVENT_MEDIA_REMOVAL FALSE DeviceIoControl IOCTL_STORAGE_EJECT_MEDIA IOCTL_DISK_EJECT_MEDIA"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3225/"
] |
58,694 |
<p>I want to prevent XSS attacks in my web application. I found that HTML Encoding the output can really prevent XSS attacks. Now the problem is that how do I HTML encode every single output in my application? I there a way to automate this?</p>
<p>I appreciate answers for JSP, ASP.net and PHP.</p>
|
[
{
"answer_id": 58791,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 1,
"selected": false,
"text": "echo \"blah\";\n myecho('blah');\n"
},
{
"answer_id": 58938,
"author": "Peter Bernier",
"author_id": 6112,
"author_profile": "https://Stackoverflow.com/users/6112",
"pm_score": 1,
"selected": false,
"text": "Server.HtmlEncode(string)"
},
{
"answer_id": 60730,
"author": "ddowns",
"author_id": 5201,
"author_profile": "https://Stackoverflow.com/users/5201",
"pm_score": 0,
"selected": false,
"text": "Var dsFirstName, uhsFirstName : String;\n\nBegin\n\nuhsFirstName := request.queryfields.value['firstname'];\n\ndsFirstName := dsHtmlToDB(uhsFirstName);\n"
},
{
"answer_id": 69004,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 2,
"selected": false,
"text": "<input name=\"someName.someProperty\" value=\"<c:out value='${someName.someProperty}' />\" />\n"
},
{
"answer_id": 8879609,
"author": "leemes",
"author_id": 592323,
"author_profile": "https://Stackoverflow.com/users/592323",
"pm_score": 0,
"selected": false,
"text": "<textarea> <input> encodeForHTML($input) // Encode data for use in HTML using HTML entity encoding\nencodeForHTMLAttribute($input) // Encode data for use in HTML attributes.\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
58,697 |
<p>The situation: I have a pieceofcrapuous laptop. One of the things that make it pieceofcrapuous is that the battery is dead, and the power cable pulls out of the back with little effort.</p>
<p>I recently received a non-pieceofcrapuous laptop, and I am in the process of copying everything from old to new. I'm trying to xcopy c:*.* from the old machine to an external hard drive, but because the cord pulls out so frequently, the xcopy is interrupted fairly often.</p>
<p>What I need is a switch in XCopy that will copy eveything except for files that already exist in the destination folder -- the exact opposite of the behavior of the /U switch. </p>
<p>Does anyone know of a way to do this? </p>
|
[
{
"answer_id": 58729,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": true,
"text": "xcopy \"O:\\*.*\" N:\\Whatever /C /D /S /H \n\n/C Continues copying even if errors occur. \n/D:m-d-y Copies files changed on or after the specified date. \n If no date is given, copies only those files whose source time \n is newer than the destination time. \n/S Copies directories and subdirectories except empty ones. \n/H Copies hidden and system files also. \n"
},
{
"answer_id": 10194265,
"author": "rud3y",
"author_id": 1010904,
"author_profile": "https://Stackoverflow.com/users/1010904",
"pm_score": 1,
"selected": false,
"text": "robocopy c:\\sourceDirectory\\*.* d:\\destinationDirectory\\*.* /R:5 /W:3 /Z /XX /TEE\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] |
58,709 |
<p>I'm using ADO.NET to access SQL Server 2005 and would like to be able to log from inside the T-SQL stored procedures that I'm calling. Is that somehow possible?</p>
<p>I'm unable to see output from the 'print'-statement when using ADO.NET and since I want to use logging just for debuging the ideal solution would be to emit messages to DebugView from SysInternals.</p>
|
[
{
"answer_id": 59017,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 0,
"selected": false,
"text": "create procedure usp_LoggableProc \n\n@log varchar(max) OUTPUT \n\nas\n\n-- T-SQL statement here ...\n\nselect @log = @log + 'X is foo'\n string log = (string)SqlCommand.Parameters[\"@log\"].Value;\n RAISERROR('X is Foo', 10, 1)\n"
},
{
"answer_id": 545415,
"author": "Jonas Engman",
"author_id": 4164,
"author_profile": "https://Stackoverflow.com/users/4164",
"pm_score": 4,
"selected": true,
"text": "using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\npublic partial class StoredProcedures\n{\n [Microsoft.SqlServer.Server.SqlProcedure]\n public static int Debug(string s)\n {\n System.Diagnostics.Debug.WriteLine(s);\n return 0;\n }\n }\n}\n USE [master]\nCREATE ASYMMETRIC KEY DebugProcKey FROM EXECUTABLE FILE =\n'C:\\..\\SqlServerProject1\\bin\\Debug\\SqlServerProject1.dll'\n\nCREATE LOGIN DebugProcLogin FROM ASYMMETRIC KEY DebugProcKey \n\nGRANT UNSAFE ASSEMBLY TO DebugProcLogin \n USE [mydb]\nCREATE ASSEMBLY SqlServerProject1 FROM\n'C:\\..\\SqlServerProject1\\bin\\Debug\\SqlServerProject1.dll' \nWITH PERMISSION_SET = unsafe\n\nCREATE FUNCTION dbo.Debug( @message as nvarchar(200) )\nRETURNS int\nAS EXTERNAL NAME SqlServerProject1.[StoredProcedures].Debug\n exec Debug @message = 'Hello World'\n"
},
{
"answer_id": 1765319,
"author": "Steve D",
"author_id": 214836,
"author_profile": "https://Stackoverflow.com/users/214836",
"pm_score": 1,
"selected": false,
"text": "sqlConnection.InfoMessage += new SqlInfoMessageEventHandler(MySqlConnectionInfoMessageHandler);\n MySqlConnectionInfoMessageHandler(object sender, SqlInfoMessageEventArgs e)\n"
},
{
"answer_id": 60612988,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "select @cmdtxt = \"echo \" + @logEntry + \" >> drive:\\path\\filename.txt\"\nexec master..xp_cmdshell @cmdtxt\n"
},
{
"answer_id": 69202552,
"author": "Curt",
"author_id": 1754010,
"author_profile": "https://Stackoverflow.com/users/1754010",
"pm_score": 0,
"selected": false,
"text": "USE TX\nGO\n\nCREATE PROCEDURE dbo.LogError(@errorSource Varchar(32), @msg Varchar(400))\nAS BEGIN\n SET NOCOUNT ON\n IF @@TRANCOUNT > 0 \n EXEC [127.0.0.1].TX.dbo.LogError @errorSource, @msg \n ELSE\n INSERT INTO TX.dbo.ErrorLog(source_module, message)\n SELECT @errorSource, @msg\n END\n GO\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4164/"
] |
58,711 |
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p>
<pre><code>Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
</code></pre>
<p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p>
<p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin => 10</code>), and from ruby (extensively using blocks in sensible ways)</p>
<p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p>
<pre><code>def Shoeless(Shoes.app):
self.t = para("Not clicked!")
def on_click_func(self):
alert("You clicked the button!")
self.t.replace("clicked!")
b = button("The label", click=self.on_click_func)
</code></pre>
<p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p>
<p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p>
<pre><code>class BaseControl:
def __init__(self):
self.func = None
def clicked(self, func):
self.func = func
def __call__(self):
if self.func is not None:
self.func()
class Button(BaseControl):
pass
class Label(BaseControl):
pass
# The actual applications code (that the end-user would write)
class MyApp:
ok = Button()
la = Label()
@ok.clicked
def clickeryHappened():
print "OK Clicked!"
if __name__ == '__main__':
a = MyApp()
a.ok() # trigger the clicked action
</code></pre>
<p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p>
<p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
|
[
{
"answer_id": 58990,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "from Boots import App, Para, Button, alert\n\ndef Shoeless(App):\n t = Para(text = 'Not Clicked')\n b = Button(label = 'The label')\n\n def on_b_clicked(self):\n alert('You clicked the button!')\n self.t.text = 'Clicked!'\n App Para Button t b dict __prepare__"
},
{
"answer_id": 62780,
"author": "A Nony Mouse",
"author_id": 7182,
"author_profile": "https://Stackoverflow.com/users/7182",
"pm_score": 2,
"selected": false,
"text": "class w(Wndw):\n title='Hello World'\n class txt(Txt): # either a new class\n text='Insert name here'\n lbl=Lbl(text='Hello') # or an instance\n class greet(Bbt):\n text='Greet'\n def click(self): #on_click method\n self.frame.lbl.text='Hello %s.'%self.frame.txt.text\n\napp=w()\n"
},
{
"answer_id": 335358,
"author": "liori",
"author_id": 42610,
"author_profile": "https://Stackoverflow.com/users/42610",
"pm_score": 1,
"selected": false,
"text": "class MyWindow(Window):\n class VBox:\n entry = Entry()\n bigtext = TextView()\n\n def on_entry_accepted(text):\n bigtext.value = eval(text).__doc__\n"
},
{
"answer_id": 335443,
"author": "Suraj",
"author_id": 39446,
"author_profile": "https://Stackoverflow.com/users/39446",
"pm_score": 1,
"selected": false,
"text": "class MyWindow(Window):\n contents = (\n para('Hello World!'),\n button('Click Me', id='ok'),\n para('Epilog'),\n )\n\n def __init__(self):\n self['#ok'].click(self.message)\n self['para'].hover(self.blend_in, self.blend_out)\n\n def message(self):\n print 'You clicked!'\n\n def blend_in(self, object):\n object.background = '#333333'\n\n def blend_out(self, object):\n object.background = 'WindowBackground'\n"
},
{
"answer_id": 335887,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": 2,
"selected": false,
"text": "with Shoes():\n t = Para(\"Not clicked!\")\n with Button(\"The Label\"):\n Alert(\"You clicked the button!\")\n t.replace(\"Clicked!\")\n context = None\n\nclass Nestable(object):\n def __init__(self,caption=None):\n self.caption = caption\n self.things = []\n\n global context\n if context:\n context.add(self)\n\n def __enter__(self):\n global context\n self.parent = context\n context = self\n\n def __exit__(self, type, value, traceback):\n global context\n context = self.parent\n\n def add(self,thing):\n self.things.append(thing)\n print \"Adding a %s to %s\" % (thing,self)\n\n def __str__(self):\n return \"%s(%s)\" % (self.__class__.__name__, self.caption)\n\n\nclass Shoes(Nestable):\n pass\n\nclass Button(Nestable):\n pass\n\nclass Alert(Nestable):\n pass\n\nclass Para(Nestable):\n def replace(self,caption):\n Command(self,\"replace\",caption)\n\nclass Command(Nestable):\n def __init__(self, target, command, caption):\n self.command = command\n self.target = target\n Nestable.__init__(self,caption)\n\n def __str__(self):\n return \"Command(%s text of %s with \\\"%s\\\")\" % (self.command, self.target, self.caption)\n\n def execute(self):\n self.target.caption = self.caption\n"
},
{
"answer_id": 336089,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "MAIN_WINDOW.my_layout.my_edit.text"
},
{
"answer_id": 336525,
"author": "samuraisam",
"author_id": 42751,
"author_profile": "https://Stackoverflow.com/users/42751",
"pm_score": 2,
"selected": false,
"text": "## All you need is this class:\n\nclass MainWindow(Window):\n my_button = Button('Click Me')\n my_paragraph = Text('This is the text you wish to place')\n my_alert = AlertBox('What what what!!!')\n\n @my_button.clicked\n def my_button_clicked(self, button, event):\n self.my_paragraph.text.append('And now you clicked on it, the button that is.')\n\n @my_paragraph.text.changed\n def my_paragraph_text_changed(self, text, event):\n self.button.text = 'No more clicks!'\n\n @my_button.text.changed\n def my_button_text_changed(self, text, event):\n self.my_alert.show()\n\n\n## The Style class is automatically gnerated by the framework\n## but you can override it by defining it in the class:\n##\n## class MainWindow(Window):\n## class Style:\n## my_blah = {'style-info': 'value'}\n##\n## or like you see below:\n\nclass Style:\n my_button = {\n 'background-color': '#ccc',\n 'font-size': '14px'}\n my_paragraph = {\n 'background-color': '#fff',\n 'color': '#000',\n 'font-size': '14px',\n 'border': '1px solid black',\n 'border-radius': '3px'}\n\nMainWindow.Style = Style\n\n## The layout class is automatically generated\n## by the framework but you can override it by defining it\n## in the class, same as the Style class above, or by\n## defining it like this:\n\nclass MainLayout(Layout):\n def __init__(self, style):\n # It takes the custom or automatically generated style class upon instantiation\n style.window.pack(HBox().pack(style.my_paragraph, style.my_button))\n\nMainWindow.Layout = MainLayout\n\nif __name__ == '__main__':\n run(App(main=MainWindow))\n"
},
{
"answer_id": 336583,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "class MyWindow(GladeWrapper):\n GladeWrapper.__init__(self, \"my_glade_file.xml\", \"mainWindow\")\n self.GtkWindow.show()\n\n def button_click_event (self, *args):\n self.button1.set_label(\"CLICKED\")\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
58,743 |
<p>As an example take the following code:</p>
<pre><code>public enum ExampleEnum { FooBar, BarFoo }
public class ExampleClass : INotifyPropertyChanged
{
private ExampleEnum example;
public ExampleEnum ExampleProperty
{ get { return example; } { /* set and notify */; } }
}
</code></pre>
<p>I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay. Optimally I want my ComboBox definition to look something like this:</p>
<pre><code><ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" />
</code></pre>
<p>Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually.</p>
<p>Is there a better or some kind of canonical way? Would you usually use Converters and how would you populate the ComboBox with the right values? I don't even want to get started with i18n right now.</p>
<p><strong>Edit</strong></p>
<p>So one question was answered: How do I populate the ComboBox with the right values.</p>
<p>Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method:</p>
<pre><code><Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type sys:Enum}"
x:Key="ExampleEnumValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="ExampleEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
</code></pre>
<p>This I can use as an ItemsSource for my ComboBox:</p>
<pre><code><ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/>
</code></pre>
|
[
{
"answer_id": 58766,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 5,
"selected": false,
"text": "typesComboBox1.ItemsSource = Enum.GetValues(typeof(ExampleEnum));\n"
},
{
"answer_id": 58819,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 0,
"selected": false,
"text": "<ComboBox ItemsSource=\"{Binding Source={StaticResource ExampleEnumValues}}\"\n SelectedValue=\"{Binding Path=ExampleProperty}\" />\n"
},
{
"answer_id": 74011,
"author": "Greg",
"author_id": 11013,
"author_profile": "https://Stackoverflow.com/users/11013",
"pm_score": 3,
"selected": false,
"text": "<Style x:Key=\"enumStyle\" TargetType=\"{x:Type TextBlock}\">\n <Setter Property=\"Text\" Value=\"<NULL>\"/>\n <Style.Triggers>\n <Trigger Property=\"Tag\">\n <Trigger.Value>\n <proj:YourEnum>Value1<proj:YourEnum>\n </Trigger.Value>\n <Setter Property=\"Text\" Value=\"{DynamicResource yourFriendlyValue1}\"/>\n </Trigger>\n <!-- add more triggers here to reflect your enum -->\n </Style.Triggers>\n</Style>\n <Style TargetType=\"{x:Type ComboBoxItem}\">\n <Setter Property=\"ContentTemplate\">\n <Setter.Value>\n <DataTemplate>\n <TextBlock Tag=\"{Binding}\" Style=\"{StaticResource enumStyle}\"/>\n </DataTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n <ComboBox SelectedValue=\"{Binding Path=your property goes here}\" SelectedValuePath=\"Content\">\n <ComboBox.Items>\n <ComboBoxItem>\n <proj:YourEnum>Value1</proj:YourEnum>\n </ComboBoxItem>\n </ComboBox.Items>\n</ComboBox>\n"
},
{
"answer_id": 4398752,
"author": "Gregor Slavec",
"author_id": 355257,
"author_profile": "https://Stackoverflow.com/users/355257",
"pm_score": 8,
"selected": false,
"text": "enum Status\n{\n [Description(\"Available.\")]\n Available,\n [Description(\"Not here right now.\")]\n Away,\n [Description(\"I don't have time right now.\")]\n Busy\n}\n xmlns:my=\"clr-namespace:namespace_to_enumeration_extension_class\n <ComboBox \n ItemsSource=\"{Binding Source={my:Enumeration {x:Type my:Status}}}\" \n DisplayMemberPath=\"Description\" \n SelectedValue=\"{Binding CurrentStatus}\" \n SelectedValuePath=\"Value\" /> \n public class EnumerationExtension : MarkupExtension\n {\n private Type _enumType;\n\n\n public EnumerationExtension(Type enumType)\n {\n if (enumType == null)\n throw new ArgumentNullException(\"enumType\");\n\n EnumType = enumType;\n }\n\n public Type EnumType\n {\n get { return _enumType; }\n private set\n {\n if (_enumType == value)\n return;\n\n var enumType = Nullable.GetUnderlyingType(value) ?? value;\n\n if (enumType.IsEnum == false)\n throw new ArgumentException(\"Type must be an Enum.\");\n\n _enumType = value;\n }\n }\n\n public override object ProvideValue(IServiceProvider serviceProvider) // or IXamlServiceProvider for UWP and WinUI\n {\n var enumValues = Enum.GetValues(EnumType);\n\n return (\n from object enumValue in enumValues\n select new EnumerationMember{\n Value = enumValue,\n Description = GetDescription(enumValue)\n }).ToArray();\n }\n\n private string GetDescription(object enumValue)\n {\n var descriptionAttribute = EnumType\n .GetField(enumValue.ToString())\n .GetCustomAttributes(typeof (DescriptionAttribute), false)\n .FirstOrDefault() as DescriptionAttribute;\n\n\n return descriptionAttribute != null\n ? descriptionAttribute.Description\n : enumValue.ToString();\n }\n\n public class EnumerationMember\n {\n public string Description { get; set; }\n public object Value { get; set; }\n }\n }\n"
},
{
"answer_id": 5803123,
"author": "user659130",
"author_id": 659130,
"author_profile": "https://Stackoverflow.com/users/659130",
"pm_score": 8,
"selected": false,
"text": "public MyEnumType SelectedMyEnumType \n{\n get { return _selectedMyEnumType; }\n set { \n _selectedMyEnumType = value;\n OnPropertyChanged(\"SelectedMyEnumType\");\n }\n}\n\npublic IEnumerable<MyEnumType> MyEnumTypeValues\n{\n get\n {\n return Enum.GetValues(typeof(MyEnumType))\n .Cast<MyEnumType>();\n }\n}\n ItemSource MyEnumTypeValues SelectedItem SelectedMyEnumType <ComboBox SelectedItem=\"{Binding SelectedMyEnumType}\" ItemsSource=\"{Binding MyEnumTypeValues}\"></ComboBox>\n"
},
{
"answer_id": 7685443,
"author": "Martin Liversage",
"author_id": 98607,
"author_profile": "https://Stackoverflow.com/users/98607",
"pm_score": 5,
"selected": false,
"text": "System.ComponentModel.DescriptionAttribute public enum ExampleEnum {\n\n [Description(\"Foo Bar\")]\n FooBar,\n\n [Description(\"Bar Foo\")]\n BarFoo\n\n}\n public class EnumItemsSource : Collection<String>, IValueConverter {\n\n Type type;\n\n IDictionary<Object, Object> valueToNameMap;\n\n IDictionary<Object, Object> nameToValueMap;\n\n public Type Type {\n get { return this.type; }\n set {\n if (!value.IsEnum)\n throw new ArgumentException(\"Type is not an enum.\", \"value\");\n this.type = value;\n Initialize();\n }\n }\n\n public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {\n return this.valueToNameMap[value];\n }\n\n public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {\n return this.nameToValueMap[value];\n }\n\n void Initialize() {\n this.valueToNameMap = this.type\n .GetFields(BindingFlags.Static | BindingFlags.Public)\n .ToDictionary(fi => fi.GetValue(null), GetDescription);\n this.nameToValueMap = this.valueToNameMap\n .ToDictionary(kvp => kvp.Value, kvp => kvp.Key);\n Clear();\n foreach (String name in this.nameToValueMap.Keys)\n Add(name);\n }\n\n static Object GetDescription(FieldInfo fieldInfo) {\n var descriptionAttribute =\n (DescriptionAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));\n return descriptionAttribute != null ? descriptionAttribute.Description : fieldInfo.Name;\n }\n\n}\n <Windows.Resources>\n <local:EnumItemsSource\n x:Key=\"ExampleEnumItemsSource\"\n Type=\"{x:Type local:ExampleEnum}\"/>\n</Windows.Resources>\n<ComboBox\n ItemsSource=\"{StaticResource ExampleEnumItemsSource}\"\n SelectedValue=\"{Binding ExampleProperty, Converter={StaticResource ExampleEnumItemsSource}}\"/> \n"
},
{
"answer_id": 12415665,
"author": "CoperNick",
"author_id": 1457197,
"author_profile": "https://Stackoverflow.com/users/1457197",
"pm_score": 7,
"selected": false,
"text": "DisplayMemberPath SelectedValuePath KeyValuePair <ComboBox Name=\"fooBarComboBox\" \n ItemsSource=\"{Binding Path=ExampleEnumsWithCaptions}\" \n DisplayMemberPath=\"Value\" \n SelectedValuePath=\"Key\"\n SelectedValue=\"{Binding Path=ExampleProperty, Mode=TwoWay}\" > \n public Dictionary<ExampleEnum, string> ExampleEnumsWithCaptions { get; } =\n new Dictionary<ExampleEnum, string>()\n {\n {ExampleEnum.FooBar, \"Foo Bar\"},\n {ExampleEnum.BarFoo, \"Reversed Foo Bar\"},\n //{ExampleEnum.None, \"Hidden in UI\"},\n };\n\n\nprivate ExampleEnum example;\npublic ExampleEnum ExampleProperty\n{\n get { return example; }\n set { /* set and notify */; }\n}\n"
},
{
"answer_id": 14976878,
"author": "Jack",
"author_id": 794594,
"author_profile": "https://Stackoverflow.com/users/794594",
"pm_score": 3,
"selected": false,
"text": "static IEnumerable<object> GetEnum<T>() {\n var type = typeof(T);\n var names = Enum.GetNames(type);\n var values = Enum.GetValues(type);\n var pairs =\n Enumerable.Range(0, names.Length)\n .Select(i => new {\n Name = names.GetValue(i)\n , Value = values.GetValue(i) })\n .OrderBy(pair => pair.Name);\n return pairs;\n}//method\n public IEnumerable<object> EnumSearchTypes {\n get {\n return GetEnum<SearchTypes>();\n }\n}//property\n <ComboBox\n SelectedValue =\"{Binding SearchType}\"\n ItemsSource =\"{Binding EnumSearchTypes}\"\n DisplayMemberPath =\"Name\"\n SelectedValuePath =\"Value\"\n/>\n"
},
{
"answer_id": 28173443,
"author": "druss",
"author_id": 1246590,
"author_profile": "https://Stackoverflow.com/users/1246590",
"pm_score": 5,
"selected": false,
"text": "<ObjectDataProvider x:Key=\"enumValues\"\n MethodName=\"GetValues\" ObjectType=\"{x:Type System:Enum}\">\n <ObjectDataProvider.MethodParameters>\n <x:Type TypeName=\"local:ExampleEnum\"/>\n </ObjectDataProvider.MethodParameters>\n </ObjectDataProvider>\n ItemsSource=\"{Binding Source={StaticResource enumValues}}\"\n"
},
{
"answer_id": 31142863,
"author": "Contango",
"author_id": 107409,
"author_profile": "https://Stackoverflow.com/users/107409",
"pm_score": 1,
"selected": false,
"text": "DevExpress Gregor S. ComboBoxEdit ComboBoxEdit <dxe:ComboBoxEdit ItemsSource=\"{Binding Source={xamlExtensions:XamlExtensionEnumDropdown {x:myEnum:EnumFilter}}}\"\n SelectedItem=\"{Binding BrokerOrderBookingFilterSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\"\n DisplayMember=\"Description\"\n MinWidth=\"144\" Margin=\"5\" \n HorizontalAlignment=\"Left\"\n IsTextEditable=\"False\"\n ValidateOnTextInput=\"False\"\n AutoComplete=\"False\"\n IncrementalFiltering=\"True\"\n FilterCondition=\"Like\"\n ImmediatePopup=\"True\"/>\n xamlExtensions xmlns:xamlExtensions=\"clr-namespace:XamlExtensions\"\n myEnum xmlns:myEnum=\"clr-namespace:MyNamespace\"\n namespace MyNamespace\n{\n public enum EnumFilter\n {\n [Description(\"Free as a bird\")]\n Free = 0,\n\n [Description(\"I'm Somewhat Busy\")]\n SomewhatBusy = 1,\n\n [Description(\"I'm Really Busy\")]\n ReallyBusy = 2\n }\n}\n SelectedItemValue DevExpress ViewModel private EnumFilter _filterSelected = EnumFilter.All;\npublic object FilterSelected\n{\n get\n {\n return (EnumFilter)_filterSelected;\n }\n set\n {\n var x = (XamlExtensionEnumDropdown.EnumerationMember)value;\n if (x != null)\n {\n _filterSelected = (EnumFilter)x.Value;\n }\n OnPropertyChanged(\"FilterSelected\");\n }\n}\n namespace XamlExtensions\n{\n /// <summary>\n /// Intent: XAML markup extension to add support for enums into any dropdown box, see http://bit.ly/1g70oJy. We can name the items in the\n /// dropdown box by using the [Description] attribute on the enum values.\n /// </summary>\n public class XamlExtensionEnumDropdown : MarkupExtension\n {\n private Type _enumType;\n\n\n public XamlExtensionEnumDropdown(Type enumType)\n {\n if (enumType == null)\n {\n throw new ArgumentNullException(\"enumType\");\n }\n\n EnumType = enumType;\n }\n\n public Type EnumType\n {\n get { return _enumType; }\n private set\n {\n if (_enumType == value)\n {\n return;\n }\n\n var enumType = Nullable.GetUnderlyingType(value) ?? value;\n\n if (enumType.IsEnum == false)\n {\n throw new ArgumentException(\"Type must be an Enum.\");\n }\n\n _enumType = value;\n }\n }\n\n public override object ProvideValue(IServiceProvider serviceProvider)\n {\n var enumValues = Enum.GetValues(EnumType);\n\n return (\n from object enumValue in enumValues\n select new EnumerationMember\n {\n Value = enumValue,\n Description = GetDescription(enumValue)\n }).ToArray();\n }\n\n private string GetDescription(object enumValue)\n {\n var descriptionAttribute = EnumType\n .GetField(enumValue.ToString())\n .GetCustomAttributes(typeof (DescriptionAttribute), false)\n .FirstOrDefault() as DescriptionAttribute;\n\n\n return descriptionAttribute != null\n ? descriptionAttribute.Description\n : enumValue.ToString();\n }\n\n #region Nested type: EnumerationMember\n public class EnumerationMember\n {\n public string Description { get; set; }\n public object Value { get; set; }\n }\n #endregion\n }\n}\n"
},
{
"answer_id": 40537502,
"author": "LawMan",
"author_id": 2574087,
"author_profile": "https://Stackoverflow.com/users/2574087",
"pm_score": 0,
"selected": false,
"text": "<enumComboBox:EnumComboBox EnumType=\"{x:Type demoApplication:Status}\" SelectedValue=\"{Binding Status}\" />\n"
},
{
"answer_id": 43624661,
"author": "MotKohn",
"author_id": 5976576,
"author_profile": "https://Stackoverflow.com/users/5976576",
"pm_score": 2,
"selected": false,
"text": "public Array ExampleEnumValues => Enum.GetValues(typeof(ExampleEnum));\n <ComboBox ItemsSource=\"{Binding ExampleEnumValues}\" ... />\n"
},
{
"answer_id": 45089218,
"author": "Nick",
"author_id": 862495,
"author_profile": "https://Stackoverflow.com/users/862495",
"pm_score": 3,
"selected": false,
"text": "ValueConverter <ComboBox ItemsSource=\"{Binding Path=ExampleProperty, Converter={x:EnumToCollectionConverter}, Mode=OneTime}\"\n SelectedValuePath=\"Value\"\n DisplayMemberPath=\"Description\"\n SelectedValue=\"{Binding Path=ExampleProperty}\" />\n public static class EnumHelper\n{\n public static string Description(this Enum e)\n {\n return (e.GetType()\n .GetField(e.ToString())\n .GetCustomAttributes(typeof(DescriptionAttribute), false)\n .FirstOrDefault() as DescriptionAttribute)?.Description ?? e.ToString();\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(IEnumerable<ValueDescription>))]\npublic class EnumToCollectionConverter : MarkupExtension, IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return Enum.GetValues(value.GetType())\n .Cast<Enum>()\n .Select(e => new ValueDescription() { Value = e, Description = e.Description()})\n .ToList();\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return null;\n }\n public override object ProvideValue(IServiceProvider serviceProvider)\n {\n return this;\n }\n}\n ValueDescription Value Description Tuple Item1 Item2 KeyValuePair Key Value"
},
{
"answer_id": 65741894,
"author": "proa",
"author_id": 7564013,
"author_profile": "https://Stackoverflow.com/users/7564013",
"pm_score": 1,
"selected": false,
"text": " public enum RULE\n {\n [Description( \"Любые, без ограничений\" )]\n any,\n [Description( \"Любые если будет три в ряд\" )]\n anyThree,\n [Description( \"Соседние, без ограничений\" )]\n nearAny,\n [Description( \"Соседние если будет три в ряд\" )]\n nearThree\n }\n\n class ExtendRULE\n {\n public static object Values\n {\n get\n {\n List<object> list = new List<object>();\n foreach( RULE rule in Enum.GetValues( typeof( RULE ) ) )\n {\n string desc = rule.GetType().GetMember( rule.ToString() )[0].GetCustomAttribute<DescriptionAttribute>().Description;\n list.Add( new { value = rule, desc = desc } );\n }\n return list;\n }\n }\n }\n <StackPanel>\n <ListBox ItemsSource= \"{Binding Source={x:Static model:ExtendRULE.Values}}\" DisplayMemberPath=\"desc\" SelectedValuePath=\"value\" SelectedValue=\"{Binding SelectedRule}\"/>\n <ComboBox ItemsSource=\"{Binding Source={x:Static model:ExtendRULE.Values}}\" DisplayMemberPath=\"desc\" SelectedValuePath=\"value\" SelectedValue=\"{Binding SelectedRule}\"/> \n</StackPanel>\n"
},
{
"answer_id": 70387321,
"author": "BionicCode",
"author_id": 3141792,
"author_profile": "https://Stackoverflow.com/users/3141792",
"pm_score": 1,
"selected": false,
"text": "MarkupExtension Enum.GetValues Enum.GetNames IEnumerable ComboBox.ItemsSource IEnumerable<ExampleEnum> values = Enum.GetValues<ExampleEnum>();\nIEnumerable<string> names = Enum.GetNames<ExampleEnum>();\n DataGrid IValueConverter ComboBox ComboBox.SelectedItem // Define enumeration without minding any UI elements and context\npublic enum ExampleEnum \n{ \n FooBar = 0, \n BarFoo \n}\n // Define readable enum display values in the UI context.\n// Display names can come from a localizable resource.\npublic class BindingSource : INotifyPropertyChanged\n{\n public BindingSource()\n {\n ItemModels = new List<ItemModel> \n {\n new ItemModel { Label = \"Foo Bar Display\", Value = ExampleEnum.FooBar },\n new ItemModel { Label = \"Bar Foo Display\", Value = ExampleEnum.BarFoo }\n }\n }\n\n public List<ItemModel> ItemModels { get; }\n\n private ItemModel selectedItemModel;\n public ItemModel SelectedItemModel { get => selectedItemModel; => set and notify; }\n}\n public class ItemModel\n{ \n public string Label { get; set; }\n public ExampleEnum Value { get; set; }\n}\n <Window>\n <Window.DataContext>\n <BindingSource />\n </Window.DataContext>\n\n <ComboBox ItemsSource=\"{Binding ItemModels}\"\n DisplayMemberName=\"DisplayValue\"\n SelectedItem=\"{Binding SelectedItemModel}\" />\n</Window>\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733/"
] |
58,744 |
<p>I want to copy the entire contents of a directory from one location to another in C#.</p>
<p>There doesn't appear to be a way to do this using <code>System.IO</code> classes without lots of recursion.</p>
<p>There is a method in VB that we can use if we add a reference to <code>Microsoft.VisualBasic</code>:</p>
<pre><code>new Microsoft.VisualBasic.Devices.Computer().
FileSystem.CopyDirectory( sourceFolder, outputFolder );
</code></pre>
<p>This seems like a rather ugly hack. Is there a better way?</p>
|
[
{
"answer_id": 58759,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 6,
"selected": false,
"text": "Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory);\n"
},
{
"answer_id": 58762,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "string path = \"C:\\\\a\";\nstring[] dirs = Directory.GetDirectories(path, \"*.*\", SearchOption.AllDirectories);\nstring newpath = \"C:\\\\x\";\ntry\n{\n Directory.CreateDirectory(newpath);\n}\ncatch (IOException ex)\n{\n Console.WriteLine(ex.Message);\n}\nfor (int j = 0; j < dirs.Length; j++)\n{\n try\n {\n Directory.CreateDirectory(dirs[j].Replace(path, newpath));\n }\n catch (IOException ex)\n {\n Console.WriteLine(ex.Message);\n }\n}\n\nstring[] files = Directory.GetFiles(path, \"*.*\", SearchOption.AllDirectories);\nfor (int j = 0; j < files.Length; j++) \n{\n try\n {\n File.Copy(files[j], files[j].Replace(path, newpath));\n }\n catch (IOException ex)\n {\n Console.WriteLine(ex.Message);\n }\n}\n"
},
{
"answer_id": 58770,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Runtime.InteropServices;\n\nnamespace MyNameSpace\n{\n public class ShellFileOperation\n {\n private static String StringArrayToMultiString(String[] stringArray)\n {\n String multiString = \"\";\n\n if (stringArray == null)\n return \"\";\n\n for (int i=0 ; i<stringArray.Length ; i++)\n multiString += stringArray[i] + '\\0';\n\n multiString += '\\0';\n\n return multiString;\n }\n\n public static bool Copy(string source, string dest)\n {\n return Copy(new String[] { source }, new String[] { dest });\n }\n\n public static bool Copy(String[] source, String[] dest)\n {\n Win32.SHFILEOPSTRUCT FileOpStruct = new Win32.SHFILEOPSTRUCT();\n\n FileOpStruct.hwnd = IntPtr.Zero;\n FileOpStruct.wFunc = (uint)Win32.FO_COPY;\n\n String multiSource = StringArrayToMultiString(source);\n String multiDest = StringArrayToMultiString(dest);\n FileOpStruct.pFrom = Marshal.StringToHGlobalUni(multiSource);\n FileOpStruct.pTo = Marshal.StringToHGlobalUni(multiDest);\n\n FileOpStruct.fFlags = (ushort)Win32.ShellFileOperationFlags.FOF_NOCONFIRMATION;\n FileOpStruct.lpszProgressTitle = \"\";\n FileOpStruct.fAnyOperationsAborted = 0;\n FileOpStruct.hNameMappings = IntPtr.Zero;\n\n int retval = Win32.SHFileOperation(ref FileOpStruct);\n\n if(retval != 0) return false;\n return true;\n }\n\n public static bool Move(string source, string dest)\n {\n return Move(new String[] { source }, new String[] { dest });\n }\n\n public static bool Delete(string file)\n {\n Win32.SHFILEOPSTRUCT FileOpStruct = new Win32.SHFILEOPSTRUCT();\n\n FileOpStruct.hwnd = IntPtr.Zero;\n FileOpStruct.wFunc = (uint)Win32.FO_DELETE;\n\n String multiSource = StringArrayToMultiString(new string[] { file });\n FileOpStruct.pFrom = Marshal.StringToHGlobalUni(multiSource);\n FileOpStruct.pTo = IntPtr.Zero;\n\n FileOpStruct.fFlags = (ushort)Win32.ShellFileOperationFlags.FOF_SILENT | (ushort)Win32.ShellFileOperationFlags.FOF_NOCONFIRMATION | (ushort)Win32.ShellFileOperationFlags.FOF_NOERRORUI | (ushort)Win32.ShellFileOperationFlags.FOF_NOCONFIRMMKDIR;\n FileOpStruct.lpszProgressTitle = \"\";\n FileOpStruct.fAnyOperationsAborted = 0;\n FileOpStruct.hNameMappings = IntPtr.Zero;\n\n int retval = Win32.SHFileOperation(ref FileOpStruct);\n\n if(retval != 0) return false;\n return true;\n }\n\n public static bool Move(String[] source, String[] dest)\n {\n Win32.SHFILEOPSTRUCT FileOpStruct = new Win32.SHFILEOPSTRUCT();\n\n FileOpStruct.hwnd = IntPtr.Zero;\n FileOpStruct.wFunc = (uint)Win32.FO_MOVE;\n\n String multiSource = StringArrayToMultiString(source);\n String multiDest = StringArrayToMultiString(dest);\n FileOpStruct.pFrom = Marshal.StringToHGlobalUni(multiSource);\n FileOpStruct.pTo = Marshal.StringToHGlobalUni(multiDest);\n\n FileOpStruct.fFlags = (ushort)Win32.ShellFileOperationFlags.FOF_NOCONFIRMATION;\n FileOpStruct.lpszProgressTitle = \"\";\n FileOpStruct.fAnyOperationsAborted = 0;\n FileOpStruct.hNameMappings = IntPtr.Zero;\n\n int retval = Win32.SHFileOperation(ref FileOpStruct);\n\n if(retval != 0) return false;\n return true;\n }\n }\n}\n"
},
{
"answer_id": 58779,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": false,
"text": "public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) {\n foreach (DirectoryInfo dir in source.GetDirectories())\n CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));\n foreach (FileInfo file in source.GetFiles())\n file.CopyTo(Path.Combine(target.FullName, file.Name));\n}\n Microsoft.VisualBasic.Devices.Computer.FileSystem.CopyDirectory"
},
{
"answer_id": 58820,
"author": "d4nt",
"author_id": 1039,
"author_profile": "https://Stackoverflow.com/users/1039",
"pm_score": 6,
"selected": false,
"text": "Process proc = new Process();\nproc.StartInfo.UseShellExecute = true;\nproc.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, \"xcopy.exe\");\nproc.StartInfo.Arguments = @\"C:\\source C:\\destination /E /I\";\nproc.Start();\n"
},
{
"answer_id": 690980,
"author": "Justin R.",
"author_id": 4593,
"author_profile": "https://Stackoverflow.com/users/4593",
"pm_score": 7,
"selected": false,
"text": "using System;\nusing System.IO;\n\nclass CopyDir\n{\n public static void Copy(string sourceDirectory, string targetDirectory)\n {\n DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);\n DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);\n\n CopyAll(diSource, diTarget);\n }\n\n public static void CopyAll(DirectoryInfo source, DirectoryInfo target)\n {\n Directory.CreateDirectory(target.FullName);\n\n // Copy each file into the new directory.\n foreach (FileInfo fi in source.GetFiles())\n {\n Console.WriteLine(@\"Copying {0}\\{1}\", target.FullName, fi.Name);\n fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);\n }\n\n // Copy each subdirectory using recursion.\n foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())\n {\n DirectoryInfo nextTargetSubDir =\n target.CreateSubdirectory(diSourceSubDir.Name);\n CopyAll(diSourceSubDir, nextTargetSubDir);\n }\n }\n\n public static void Main()\n {\n string sourceDirectory = @\"c:\\sourceDirectory\";\n string targetDirectory = @\"c:\\targetDirectory\";\n\n Copy(sourceDirectory, targetDirectory);\n }\n\n // Output will vary based on the contents of the source directory.\n}\n"
},
{
"answer_id": 2527714,
"author": "Jens Granlund",
"author_id": 214222,
"author_profile": "https://Stackoverflow.com/users/214222",
"pm_score": 4,
"selected": false,
"text": "public static void CopyDirectory(string source, string target)\n{\n var stack = new Stack<Folders>();\n stack.Push(new Folders(source, target));\n\n while (stack.Count > 0)\n {\n var folders = stack.Pop();\n Directory.CreateDirectory(folders.Target);\n foreach (var file in Directory.GetFiles(folders.Source, \"*.*\"))\n {\n File.Copy(file, Path.Combine(folders.Target, Path.GetFileName(file)));\n }\n\n foreach (var folder in Directory.GetDirectories(folders.Source))\n {\n stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));\n }\n }\n}\n\npublic class Folders\n{\n public string Source { get; private set; }\n public string Target { get; private set; }\n\n public Folders(string source, string target)\n {\n Source = source;\n Target = target;\n }\n}\n"
},
{
"answer_id": 3822913,
"author": "tboswell",
"author_id": 461882,
"author_profile": "https://Stackoverflow.com/users/461882",
"pm_score": 10,
"selected": true,
"text": "private static void CopyFilesRecursively(string sourcePath, string targetPath)\n{\n //Now Create all of the directories\n foreach (string dirPath in Directory.GetDirectories(sourcePath, \"*\", SearchOption.AllDirectories))\n {\n Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));\n }\n\n //Copy all the files & Replaces any files with the same name\n foreach (string newPath in Directory.GetFiles(sourcePath, \"*.*\",SearchOption.AllDirectories))\n {\n File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);\n }\n}\n"
},
{
"answer_id": 8022011,
"author": "eduardomozart",
"author_id": 1031340,
"author_profile": "https://Stackoverflow.com/users/1031340",
"pm_score": 5,
"selected": false,
"text": "string source_dir = @\"E:\\\";\nstring destination_dir = @\"C:\\\";\n\n// substring is to remove destination_dir absolute path (E:\\).\n\n// Create subdirectory structure in destination \n foreach (string dir in System.IO.Directory.GetDirectories(source_dir, \"*\", System.IO.SearchOption.AllDirectories))\n {\n System.IO.Directory.CreateDirectory(System.IO.Path.Combine(destination_dir, dir.Substring(source_dir.Length + 1)));\n // Example:\n // > C:\\sources (and not C:\\E:\\sources)\n }\n\n foreach (string file_name in System.IO.Directory.GetFiles(source_dir, \"*\", System.IO.SearchOption.AllDirectories))\n {\n System.IO.File.Copy(file_name, System.IO.Path.Combine(destination_dir, file_name.Substring(source_dir.Length + 1)));\n }\n"
},
{
"answer_id": 9127432,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 2,
"selected": false,
"text": "public void CopyFolder(string source, string destination)\n{\n string xcopyPath = Environment.GetEnvironmentVariable(\"WINDIR\") + @\"\\System32\\xcopy.exe\";\n ProcessStartInfo info = new ProcessStartInfo(xcopyPath);\n info.UseShellExecute = false;\n info.RedirectStandardOutput = true;\n info.Arguments = string.Format(\"\\\"{0}\\\" \\\"{1}\\\" /E /I\", source, destination);\n\n Process process = Process.Start(info);\n process.WaitForExit();\n string result = process.StandardOutput.ReadToEnd();\n\n if (process.ExitCode != 0)\n {\n // Or your own custom exception, or just return false if you prefer.\n throw new InvalidOperationException(string.Format(\"Failed to copy {0} to {1}: {2}\", source, destination, result));\n }\n}\n"
},
{
"answer_id": 12543017,
"author": "Khoi_Vjz_Boy",
"author_id": 1332062,
"author_profile": "https://Stackoverflow.com/users/1332062",
"pm_score": 2,
"selected": false,
"text": " private void KCOPY(string source, string destination)\n {\n if (IsFile(source))\n {\n string target = Path.Combine(destination, Path.GetFileName(source));\n File.Copy(source, target, true);\n }\n else\n {\n string fileName = Path.GetFileName(source);\n string target = System.IO.Path.Combine(destination, fileName);\n if (!System.IO.Directory.Exists(target))\n {\n System.IO.Directory.CreateDirectory(target);\n }\n\n List<string> files = GetAllFileAndFolder(source);\n\n foreach (string file in files)\n {\n KCOPY(file, target);\n }\n }\n }\n\n private List<string> GetAllFileAndFolder(string path)\n {\n List<string> allFile = new List<string>();\n foreach (string dir in Directory.GetDirectories(path))\n {\n allFile.Add(dir);\n }\n foreach (string file in Directory.GetFiles(path))\n {\n allFile.Add(file);\n }\n\n return allFile;\n }\n private bool IsFile(string path)\n {\n if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory)\n {\n return false;\n }\n return true;\n }\n"
},
{
"answer_id": 15648301,
"author": "Daryl",
"author_id": 814454,
"author_profile": "https://Stackoverflow.com/users/814454",
"pm_score": 1,
"selected": false,
"text": "overwrite public static DirectoryInfo CopyTo(this DirectoryInfo sourceDir, string destinationPath, bool overwrite = false)\n{\n var sourcePath = sourceDir.FullName;\n\n var destination = new DirectoryInfo(destinationPath);\n\n destination.Create();\n\n foreach (var sourceSubDirPath in Directory.EnumerateDirectories(sourcePath, \"*\", SearchOption.AllDirectories))\n Directory.CreateDirectory(sourceSubDirPath.Replace(sourcePath, destinationPath));\n\n foreach (var file in Directory.EnumerateFiles(sourcePath, \"*\", SearchOption.AllDirectories))\n File.Copy(file, file.Replace(sourcePath, destinationPath), overwrite);\n\n return destination;\n}\n"
},
{
"answer_id": 29463011,
"author": "toddmo",
"author_id": 1045881,
"author_profile": "https://Stackoverflow.com/users/1045881",
"pm_score": 2,
"selected": false,
"text": "source target target DirectoryInfo public static DirectoryInfo CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)\n{\n var newDirectoryInfo = target.CreateSubdirectory(source.Name);\n foreach (var fileInfo in source.GetFiles())\n fileInfo.CopyTo(Path.Combine(newDirectoryInfo.FullName, fileInfo.Name));\n\n foreach (var childDirectoryInfo in source.GetDirectories())\n CopyFilesRecursively(childDirectoryInfo, newDirectoryInfo);\n\n return newDirectoryInfo;\n}\n"
},
{
"answer_id": 35742118,
"author": "bh_earth0",
"author_id": 3137362,
"author_profile": "https://Stackoverflow.com/users/3137362",
"pm_score": 2,
"selected": false,
"text": "public static void copyAll(string SourcePath , string DestinationPath )\n{\n //Now Create all of the directories\n foreach (string dirPath in Directory.GetDirectories(SourcePath, \"*\", SearchOption.AllDirectories))\n Directory.CreateDirectory(Path.Combine(DestinationPath ,dirPath.Remove(0, SourcePath.Length )) );\n\n //Copy all the files & Replaces any files with the same name\n foreach (string newPath in Directory.GetFiles(SourcePath, \"*.*\", SearchOption.AllDirectories))\n File.Copy(newPath, Path.Combine(DestinationPath , newPath.Remove(0, SourcePath.Length)) , true);\n }\n"
},
{
"answer_id": 45199038,
"author": "iato",
"author_id": 5116032,
"author_profile": "https://Stackoverflow.com/users/5116032",
"pm_score": 2,
"selected": false,
"text": "static void Main()\n{\n // Copy from the current directory, include subdirectories.\n DirectoryCopy(\".\", @\".\\temp\", true);\n}\n\nprivate static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)\n{\n // Get the subdirectories for the specified directory.\n DirectoryInfo dir = new DirectoryInfo(sourceDirName);\n\n if (!dir.Exists)\n {\n throw new DirectoryNotFoundException(\n \"Source directory does not exist or could not be found: \"\n + sourceDirName);\n }\n\n DirectoryInfo[] dirs = dir.GetDirectories();\n // If the destination directory doesn't exist, create it.\n if (!Directory.Exists(destDirName))\n {\n Directory.CreateDirectory(destDirName);\n }\n\n // Get the files in the directory and copy them to the new location.\n FileInfo[] files = dir.GetFiles();\n foreach (FileInfo file in files)\n {\n string temppath = Path.Combine(destDirName, file.Name);\n file.CopyTo(temppath, false);\n }\n\n // If copying subdirectories, copy them and their contents to new location.\n if (copySubDirs)\n {\n foreach (DirectoryInfo subdir in dirs)\n {\n string temppath = Path.Combine(destDirName, subdir.Name);\n DirectoryCopy(subdir.FullName, temppath, copySubDirs);\n }\n }\n}\n"
},
{
"answer_id": 45614470,
"author": "Ahmed Sabry",
"author_id": 4707576,
"author_profile": "https://Stackoverflow.com/users/4707576",
"pm_score": 1,
"selected": false,
"text": "public static class Extensions\n{\n public static void CopyTo(this DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)\n {\n if (!source.Exists) return;\n if (!target.Exists) target.Create();\n\n Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) => \n CopyTo(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));\n\n foreach (var sourceFile in source.GetFiles())\n sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles);\n }\n public static void CopyTo(this DirectoryInfo source, string target, bool overwiteFiles = true)\n {\n CopyTo(source, new DirectoryInfo(target), overwiteFiles);\n }\n}\n"
},
{
"answer_id": 46857070,
"author": "malballah",
"author_id": 7633869,
"author_profile": "https://Stackoverflow.com/users/7633869",
"pm_score": 0,
"selected": false,
"text": "public static bool CopyTo(this DirectoryInfo source, string destination)\n {\n try\n {\n foreach (string dirPath in Directory.GetDirectories(source.FullName))\n {\n var newDirPath = dirPath.Replace(source.FullName, destination);\n Directory.CreateDirectory(newDirPath);\n new DirectoryInfo(dirPath).CopyTo(newDirPath);\n }\n //Copy all the files & Replaces any files with the same name\n foreach (string filePath in Directory.GetFiles(source.FullName))\n {\n File.Copy(filePath, filePath.Replace(source.FullName,destination), true);\n }\n return true;\n }\n catch (IOException exp)\n {\n return false;\n }\n }\n"
},
{
"answer_id": 49461959,
"author": "Termininja",
"author_id": 3618581,
"author_profile": "https://Stackoverflow.com/users/3618581",
"pm_score": 1,
"selected": false,
"text": "foreach (var f in Directory.GetFileSystemEntries(path, \"*\", SearchOption.AllDirectories))\n{\n var output = Regex.Replace(f, @\"^\" + path, newPath);\n if (File.Exists(f)) File.Copy(f, output, true);\n else Directory.CreateDirectory(output);\n}\n"
},
{
"answer_id": 51376395,
"author": "AlexanderD",
"author_id": 5214808,
"author_profile": "https://Stackoverflow.com/users/5214808",
"pm_score": 2,
"selected": false,
"text": "var src = \"c:\\src\";\nvar dest = \"c:\\dest\";\nvar cmp = CompressionLevel.NoCompression;\nvar zip = source_folder + \".zip\";\n\nZipFile.CreateFromDirectory(src, zip, cmp, includeBaseDirectory: false);\nZipFile.ExtractToDirectory(zip, dest_folder);\n\nFile.Delete(zip);\n"
},
{
"answer_id": 53405237,
"author": "OKEEngine",
"author_id": 662649,
"author_profile": "https://Stackoverflow.com/users/662649",
"pm_score": 2,
"selected": false,
"text": "public static void CopyEntireDirectory(string path, string newPath)\n{\n Parallel.ForEach(Directory.GetFileSystemEntries(path, \"*\", SearchOption.AllDirectories)\n ,(fileName) =>\n {\n string output = Regex.Replace(fileName, \"^\" + Regex.Escape(path), newPath);\n if (File.Exists(fileName))\n {\n Directory.CreateDirectory(Path.GetDirectoryName(output));\n File.Copy(fileName, output, true);\n }\n else\n Directory.CreateDirectory(output);\n });\n}\n public static void CopyEntireDirectory(DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)\n{\n if (!source.Exists) return;\n if (!target.Exists) target.Create();\n\n Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) =>\n CopyEntireDirectory(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));\n\n Parallel.ForEach(source.GetFiles(), sourceFile =>\n sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles));\n}\n"
},
{
"answer_id": 55596428,
"author": "Lakmal",
"author_id": 1547297,
"author_profile": "https://Stackoverflow.com/users/1547297",
"pm_score": 0,
"selected": false,
"text": " public static void CopyAndReplaceAll(string SourcePath, string DestinationPath, string backupPath)\n {\n foreach (string dirPath in Directory.GetDirectories(SourcePath, \"*\", SearchOption.AllDirectories))\n {\n Directory.CreateDirectory($\"{DestinationPath}{dirPath.Remove(0, SourcePath.Length)}\");\n Directory.CreateDirectory($\"{backupPath}{dirPath.Remove(0, SourcePath.Length)}\");\n }\n foreach (string newPath in Directory.GetFiles(SourcePath, \"*.*\", SearchOption.AllDirectories))\n {\n if (!File.Exists($\"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}\"))\n File.Copy(newPath, $\"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}\");\n else\n File.Replace(newPath\n , $\"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}\"\n , $\"{ backupPath}{newPath.Remove(0, SourcePath.Length)}\", false);\n }\n }\n"
},
{
"answer_id": 55981013,
"author": "Arash.Zandi",
"author_id": 3046588,
"author_profile": "https://Stackoverflow.com/users/3046588",
"pm_score": 0,
"selected": false,
"text": "private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs = true)\n {\n // Get the subdirectories for the specified directory.\n DirectoryInfo dir = new DirectoryInfo(sourceDirName);\n\n if (!dir.Exists)\n {\n throw new DirectoryNotFoundException(\n \"Source directory does not exist or could not be found: \"\n + sourceDirName);\n }\n\n DirectoryInfo[] dirs = dir.GetDirectories();\n // If the destination directory doesn't exist, create it.\n if (!Directory.Exists(destDirName))\n {\n Directory.CreateDirectory(destDirName);\n }\n\n // Get the files in the directory and copy them to the new location.\n FileInfo[] files = dir.GetFiles();\n foreach (FileInfo file in files)\n {\n string temppath = Path.Combine(destDirName, file.Name);\n file.CopyTo(temppath, false);\n }\n\n // If copying subdirectories, copy them and their contents to new location.\n if (copySubDirs)\n {\n foreach (DirectoryInfo subdir in dirs)\n {\n string temppath = Path.Combine(destDirName, subdir.Name);\n DirectoryCopy(subdir.FullName, temppath, copySubDirs);\n }\n }\n }\n string source = @\"J:\\source\\\";\nstring dest= @\"J:\\destination\\\";\nDirectoryCopy(source, dest);\n string source = @\"J:\\source\\\";\n string dest= @\"J:\\destination\\\";\n DirectoryCopy(source, Path.Combine(dest, new DirectoryInfo(source).Name));\n"
},
{
"answer_id": 67476219,
"author": "Rahul Shukla",
"author_id": 7160482,
"author_profile": "https://Stackoverflow.com/users/7160482",
"pm_score": 0,
"selected": false,
"text": "public static void Copy()\n {\n string sourceDir = @\"C:\\test\\source\\\";\n string destination = @\"C:\\test\\destination\\\";\n\n string[] textFiles = Directory.GetFiles(sourceDir, \"*.txt\", SearchOption.AllDirectories);\n\n foreach (string textFile in textFiles)\n {\n string fileName = textFile.Substring(sourceDir.Length);\n string directoryPath = Path.Combine(destination, Path.GetDirectoryName(fileName));\n if (!Directory.Exists(directoryPath))\n Directory.CreateDirectory(directoryPath);\n\n File.Copy(textFile, Path.Combine(directoryPath, Path.GetFileName(textFile)), true);\n }\n }\n"
},
{
"answer_id": 69069991,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 2,
"selected": false,
"text": "namespace System.IO {\n public static class ExtensionMethods {\n\n public static void CopyTo(this DirectoryInfo srcPath, string destPath) {\n Directory.CreateDirectory(destPath);\n Parallel.ForEach(srcPath.GetDirectories(\"*\", SearchOption.AllDirectories), \n srcInfo => Directory.CreateDirectory($\"{destPath}{srcInfo.FullName[srcPath.FullName.Length..]}\"));\n Parallel.ForEach(srcPath.GetFiles(\"*\", SearchOption.AllDirectories), \n srcInfo => File.Copy(srcInfo.FullName, $\"{destPath}{srcInfo.FullName[srcPath.FullName.Length..]}\", true));\n });\n }\n\n }\n}\n new DirectoryInfo(sourcePath).CopyTo(destinationPath);\n"
},
{
"answer_id": 69789211,
"author": "M. Mennan Kara",
"author_id": 1301389,
"author_profile": "https://Stackoverflow.com/users/1301389",
"pm_score": 0,
"selected": false,
"text": "public static void Copy(\n string source,\n string destination,\n string pattern = \"*\",\n bool includeSubFolders = true,\n bool overwrite = true,\n bool overwriteOnlyIfSourceIsNewer = false)\n{\n if (File.Exists(source))\n {\n // Source is a file, copy and leave\n CopyFile(source, destination);\n return;\n }\n\n if (!Directory.Exists(source))\n {\n throw new DirectoryNotFoundException($\"Source directory does not exists: `{source}`\");\n }\n\n var files = Directory.GetFiles(\n source,\n pattern,\n includeSubFolders ?\n SearchOption.AllDirectories :\n SearchOption.TopDirectoryOnly);\n\n foreach (var file in files)\n {\n var newFile = file.Replace(source, destination);\n CopyFile(file, newFile, overwrite, overwriteOnlyIfSourceIsNewer);\n }\n}\n\nprivate static void CopyFile(\n string source,\n string destination,\n bool overwrite = true,\n bool overwriteIfSourceIsNewer = false)\n{\n if (!overwrite && File.Exists(destination))\n {\n return;\n }\n\n if (overwriteIfSourceIsNewer && File.Exists(destination))\n {\n var sourceLastModified = File.GetLastWriteTimeUtc(source);\n var destinationLastModified = File.GetLastWriteTimeUtc(destination);\n if (sourceLastModified <= destinationLastModified)\n {\n return;\n }\n\n CreateDirectory(destination);\n File.Copy(source, destination, overwrite);\n return;\n }\n\n CreateDirectory(destination);\n File.Copy(source, destination, overwrite);\n}\n\nprivate static void CreateDirectory(string filePath)\n{\n var targetDirectory = Path.GetDirectoryName(filePath);\n if (targetDirectory != null && !Directory.Exists(targetDirectory))\n {\n Directory.CreateDirectory(targetDirectory);\n }\n}\n"
},
{
"answer_id": 70086547,
"author": "Rui Caramalho",
"author_id": 10756362,
"author_profile": "https://Stackoverflow.com/users/10756362",
"pm_score": 0,
"selected": false,
"text": "FileShare.ReadWrite ExceptionToString() ex.Message log4net.ILog _log /// <summary>\n/// Recursive Directory Copy\n/// </summary>\n/// <param name=\"fromPath\"></param>\n/// <param name=\"toPath\"></param>\n/// <param name=\"continueOnException\">on error, continue to copy next file</param>\n/// <param name=\"skipHiddenFiles\">To avoid files like thumbs.db</param>\n/// <param name=\"skipByModifiedDate\">Does not copy if the destiny file has the same or more recent modified date</param>\n/// <remarks>\n/// </remarks>\npublic static void CopyEntireDirectory(string fromPath, string toPath, bool continueOnException = false, bool skipHiddenFiles = true, bool skipByModifiedDate = true)\n{\n log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);\n string nl = Environment.NewLine;\n\n string sourcePath = \"\";\n string destPath = \"\";\n string _exMsg = \"\";\n\n void TreateException(Exception ex)\n {\n _log.Warn(_exMsg);\n if (continueOnException == false)\n {\n throw new Exception($\"{_exMsg}{nl}----{nl}{ex.ExceptionToString()}\");\n }\n }\n\n try\n {\n foreach (string fileName in Directory.GetFileSystemEntries(fromPath, \"*\", SearchOption.AllDirectories))\n {\n sourcePath = fileName;\n destPath = Regex.Replace(fileName, \"^\" + Regex.Escape(fromPath), toPath);\n\n Directory.CreateDirectory(Path.GetDirectoryName(destPath));\n \n _log.Debug(FileCopyStream(sourcePath, destPath,skipHiddenFiles,skipByModifiedDate));\n }\n }\n // Directory must be less than 148 characters, File must be less than 261 characters\n catch (PathTooLongException)\n {\n throw new Exception($\"Both paths must be less than 148 characters:{nl}{sourcePath}{nl}{destPath}\");\n }\n // Not enough disk space. Cancel further copies\n catch (IOException ex) when ((ex.HResult & 0xFFFF) == 0x27 || (ex.HResult & 0xFFFF) == 0x70)\n {\n throw new Exception($\"Not enough disk space:{nl}'{toPath}'\");\n }\n // used by another process\n catch (IOException ex) when ((uint)ex.HResult == 0x80070020)\n {\n _exMsg = $\"File is being used by another process:{nl}'{destPath}'{nl}{ex.Message}\";\n TreateException(ex);\n }\n catch (UnauthorizedAccessException ex)\n {\n _exMsg = $\"Unauthorized Access Exception:{nl}from:'{sourcePath}'{nl}to:{destPath}\";\n TreateException(ex);\n }\n catch (Exception ex)\n {\n _exMsg = $\"from:'{sourcePath}'{nl}to:{destPath}\";\n TreateException(ex);\n }\n}\n\n/// <summary>\n/// File Copy using Stream 64K and trying to avoid locks with fileshare\n/// </summary>\n/// <param name=\"sourcePath\"></param>\n/// <param name=\"destPath\"></param>\n/// <param name=\"skipHiddenFiles\">To avoid files like thumbs.db</param>\n/// <param name=\"skipByModifiedDate\">Does not copy if the destiny file has the same or more recent modified date</param>\npublic static string FileCopyStream(string sourcePath, string destPath, bool skipHiddenFiles = true, bool skipByModifiedDate = true)\n{\n // Buffer should be 64K = 65536 bytes \n // Increasing the buffer size beyond 64k will not help in any circunstance,\n // as the underlying SMB protocol does not support buffer lengths beyond 64k.\"\n byte[] buffer = new byte[65536];\n\n if (!File.Exists(sourcePath))\n return $\"is not a file: '{sourcePath}'\";\n\n FileInfo sourcefileInfo = new FileInfo(sourcePath);\n FileInfo destFileInfo = null;\n if (File.Exists(destPath))\n destFileInfo = new FileInfo(destPath);\n\n if (skipHiddenFiles)\n {\n if (sourcefileInfo.Attributes.HasFlag(FileAttributes.Hidden))\n return $\"Hidden File Not Copied: '{sourcePath}'\";\n }\n\n using (FileStream input = sourcefileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n using (FileStream output = new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite, buffer.Length))\n {\n if (skipByModifiedDate && destFileInfo != null)\n {\n if (destFileInfo.LastWriteTime < sourcefileInfo.LastWriteTime)\n {\n input.CopyTo(output, buffer.Length);\n destFileInfo.LastWriteTime = sourcefileInfo.LastWriteTime;\n return $\"Replaced: '{sourcePath}'\";\n }\n else\n {\n return $\"NOT replaced (more recent or same file): '{sourcePath}'\";\n }\n }\n else\n {\n input.CopyTo(output, buffer.Length);\n destFileInfo = new FileInfo(destPath);\n destFileInfo.LastWriteTime = sourcefileInfo.LastWriteTime;\n return $\"New File: '{sourcePath}'\";\n }\n }\n}\n"
},
{
"answer_id": 73630610,
"author": "Rafi Henig",
"author_id": 9369606,
"author_profile": "https://Stackoverflow.com/users/9369606",
"pm_score": 0,
"selected": false,
"text": "public async Task CopyAsync(StorageFolder source, StorageFolder dest)\n{\n foreach (var item in await source.GetItemsAsync())\n\n if (item is StorageFile file)\n await file.CopyAsync(dest);\n\n else if (item is StorageFolder folder)\n await CopyAsync(folder, await dest.CreateFolderAsync(folder.Name, CreationCollisionOption.OpenIfExists));\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
58,750 |
<p>Is it possible to obtain raw logs from Google Analytic? Is there any tool that can generate the raw logs from GA?</p>
|
[
{
"answer_id": 68766,
"author": "Shermozle",
"author_id": 10788,
"author_profile": "https://Stackoverflow.com/users/10788",
"pm_score": 5,
"selected": true,
"text": "var _ugifpath2=\"http://www.google-analytics.com/__utm.gif\";\nif (_udl.protocol==\"https:\") _ugifpath2=\"https://ssl.google-analytics.com/__utm.gif\";\n __utm.gif 127.0.0.1 - - [02/Oct/2008:10:17:18 +1000] \"GET /__utm.gif?utmwv=1.3&utmn=172543292&utmcs=ISO-8859-1&utmsr=1280x1024&utmsc=32-bit&utmul=en-us&utmje=1&utmfl=9.0%20%20r124&utmdt=My%20Web%20Page&utmhn=www.mydomain.com&utmhid=979599568&utmr=-&utmp=/urlgoeshere/&utmac=UA-1715941-2&utmcc=__utma%3D113887236.511203954.1220404968.1222846275.1222906638.33%3B%2B__utmz%3D113887236.1222393496.27.2.utmccn%3D(organic)%7Cutmcsr%3Dgoogle%7Cutmctr%3Dsapphire%2Btechnologies%2Bsite%253Arumble.net%7Cutmcmd%3Dorganic%3B%2B HTTP/1.0\" 200 35 \"http://www.mydomain.com/urlgoeshere/\" \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.2.153.1 Safari/525.19\"\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370899/"
] |
58,755 |
<p>What is the best way to do per-user database connections in <code>Rails</code>? </p>
<p>I realize this is a poor Rails design practice, but we're gradually replacing an existing web application that uses one database per user. A complete redesign/rewrite is not feasible.</p>
|
[
{
"answer_id": 59063,
"author": "Kevin Kaske",
"author_id": 2737,
"author_profile": "https://Stackoverflow.com/users/2737",
"pm_score": 4,
"selected": true,
"text": "class ApplicationController < ActionController::Base\n\n before_filter :hijack_db\n\n def hijack_db\n db_name = request.subdomains.first + \"_clientdb\"\n\n # lets manually connect to the proper db\n ActiveRecord::Base.establish_connection(\n :adapter => ActiveRecord::Base.configurations[ENV[\"RAILS_ENV\"]]['adapter'],\n :host => ActiveRecord::Base.configurations[ENV[\"RAILS_ENV\"]]['host'],\n :username => ActiveRecord::Base.configurations[ENV[\"RAILS_ENV\"]]['username'],\n :password => ActiveRecord::Base.configurations[ENV[\"RAILS_ENV\"]]['password'],\n :database => db_name\n )\n end\nend\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/624/"
] |
58,774 |
<p>I want to paste something I have cut from my desktop into a file open in Vi.</p>
<p>But if I paste the tabs embed on top of each other across the page.</p>
<p>I think it is some sort of visual mode change but can't find the command.</p>
|
[
{
"answer_id": 58794,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 7,
"selected": true,
"text": "autoindent <Esc> :set noai\n\n<paste all you want>\n\n<Esc> :set ai\n .exrc map ^P :set noai^M\nmap ^N :set ai^M\n paste autoindent textwidth wrapmargin <Esc> :set paste\n\n<paste all you want>\n\n<Esc> :set nopaste\n .vimrc set pastetoggle=<C-P> \" Ctrl-P toggles paste mode\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6096/"
] |
58,782 |
<p>I need to copy files using Windows command-line (available on XP Pro or later by default) and show progress during the process.</p>
<p>The progress indicator could be in a terminal or a GUI window. It is intended to be used during batch file scripting.</p>
|
[
{
"answer_id": 58785,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 4,
"selected": false,
"text": "robocopy"
},
{
"answer_id": 13695754,
"author": "djangofan",
"author_id": 118228,
"author_profile": "https://Stackoverflow.com/users/118228",
"pm_score": 0,
"selected": false,
"text": "@ECHO off\nSETLOCAL ENABLEDELAYEDEXPANSION\nmode con:cols=210 lines=50\nECHO Starting 1-way backup of MEDIA(M:) to BACKUP(G:)...\nrobocopy.exe M:\\ G:\\ *.* /E /PURGE /SEC /NP /NJH /NJS /XD \"$RECYCLE.BIN\" \"System Volume Information\" /TEE /R:5 /COPYALL /LOG:from_M_to_G.log\nECHO Finished with backup.\npause\n"
},
{
"answer_id": 18197248,
"author": "Iconiu",
"author_id": 1377604,
"author_profile": "https://Stackoverflow.com/users/1377604",
"pm_score": 3,
"selected": false,
"text": "Model Exe OS switches index size time link speed \n8760w dism Win8 /export-wim index 1 6.27GB 2:21 link 1Gbps\n8760w dism Win8 /export-wim index 2 7.92GB 1:29 link 1Gbps\n6305 wdsmcast winpe32 /trans-file res.RWM 7.92GB 6:54 link 1Gbps\n6305 dism Winpe32 /export-wim index 1 6.27GB 2:20 link 1Gbps\n6305 dism Winpe32 /export-wim index 2 7.92GB 1:34 link 1Gbps\n6305 copy Winpe32 /z Whole 7.92GB 25:48 link 1Gbps\n6305 copy Winpe32 none Wim 7.92GB 1:17 link 1Gbps\n6305 xcopy Winpe32 /z /j Wim 7.92GB 23:54 link 1Gbps\n6305 xcopy Winpe32 /j Wim 7.92GB 1:38 link 1Gbps\n6305 VBS.copy Winpe32 Wim 7.92 1:21 link 1Gbps\n6305 robocopy Winpe32 Wim 7.92 1:17 link 1Gbps\n"
},
{
"answer_id": 25733912,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 4,
"selected": false,
"text": "esentutl /y \"FILE.EXT\" /d \"DEST.EXT\" /o\n y /h"
},
{
"answer_id": 65947395,
"author": "CommanderBoss Ge",
"author_id": 15071410,
"author_profile": "https://Stackoverflow.com/users/15071410",
"pm_score": 0,
"selected": false,
"text": "@echo off\ntitle NTU Installer\nsetlocal EnableDelayedExpansion\n\n@echo Iniciando instalacao...\nif not exist \"C:\\NTU\" (\n md \"C:\\NTU\n)\nif not exist \"C:\\NTU\\Profile\" (\n md \"C:\\NTU\\Profile\"\n)\nping -n 5 localhost >nul\n\nfor %%f in (*.*) do set/a vb+=1\nset \"barra=\"\n::loop da barra\nfor /l %%i in (1,1,70) do set \"barra=!barra!Û\"\nrem barra vaiza para ser preenchida\nset \"resto=\"\nrem loop da barra vazia\nfor /l %%i in (1,1,110) do set \"resto=!resto!\"\nset i=0\nrem carregameno de arquivos\nfor %%f in (*.*) do (\n >>\"log_ntu.css\" (\n copy \"%%f\" \"C:\\NTU\">nul\n echo Copiado:%%f\n )\n cls\n set /a i+=1,percent=i*100/vb,barlen=70*percent/100\n for %%a in (!barlen!) do echo !percent!%% / \n [!barra:~0,%%a!%resto%]\n echo Instalado:[%%f] / Complete:[!percent!%%/100%]\n ping localhost -n 1.9 >nul\n)\nxcopy /e \"Profile\" \"C:\\NTU\\Profile\">\"log_profile.css\" \n\n@echo Criando atalho na area de trabalho...\ncopy \"NTU.lnk\" \"C:\\Users\\%username%\\Desktop\">nul\nping localhost -n 4 >nul\n\n@echo Arquivos instalados!\npause\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
58,783 |
<p>I know there are quite a few line count tools around. Is there something simple that's not a part some other big package that you use ?</p>
|
[
{
"answer_id": 58811,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "find . -name *.cs -exec wc -l {} \\;\n"
},
{
"answer_id": 212802,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "import os, sys\ntotal_count = 0\nfor root, dirs, filenames in os.walk(sys.argv[1]):\n dirs[:] = [ # prune search path\n dir for dir in dirs\n if dir.lower() not in ('.svn', 'excludefrombuild')]\n for filename in filenames:\n if os.path.splitext(filename)[1].lower() in ('.cpp', '.h'):\n fullname = os.path.join(root, filename)\n count = 0\n for line in open(fullname): count += 1\n total_count += count\n print count, fullname\nprint total_count\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] |
58,825 |
<p>Has anyone else found VIM's syntax highlighting of Javascript sub-optimal? I'm finding that sometimes I need to scroll around in order to get the syntax highlighting adjusted, as sometimes it mysteriously drops all highlighting.</p>
<p>Are there any work-arounds or ways to fix this? I'm using vim 7.1.</p>
|
[
{
"answer_id": 59211,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 4,
"selected": false,
"text": ":syn sync fromstart\n :help syn-sync\n :help syntax\n"
},
{
"answer_id": 5652956,
"author": "Jose Elera",
"author_id": 428786,
"author_profile": "https://Stackoverflow.com/users/428786",
"pm_score": 4,
"selected": false,
"text": "Nazca"
},
{
"answer_id": 40917247,
"author": "jorgeh",
"author_id": 1620879,
"author_profile": "https://Stackoverflow.com/users/1620879",
"pm_score": 3,
"selected": false,
"text": ".html :syntax sync minlines=200 :syntax sync fromstart .vimrc autocmd BufEnter *.html :syntax sync fromstart\n .html"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] |
58,827 |
<p>OK, I am not sure if the title it completely accurate, open to suggestions!</p>
<p>I am in the process of creating an ASP.NET custom control, this is something that is still relatively new to me, so please bear with me.</p>
<p>I am thinking about the event model. Since we are not using Web Controls there are no events being fired from buttons, rather I am manually calling <strong>__doPostBack</strong> with the appropriate arguments. However this can obviously mean that there are a lot of postbacks occuring when say, selecting options (which render differently when selected).</p>
<p>In time, I will need to make this more Ajax-y and responsive, so I will need to change the event binding to call local Javascript.</p>
<p>So, I was thinking I should be able to toggle the "mode" of the control, it can either use postback and handlle itself, or you can specify the Javascript function names to call instead of the doPostBack.</p>
<ul>
<li>What are your thoughts on this?</li>
<li>Am I approaching the raising of the events from the control in the wrong way? (totally open to suggestions here!)</li>
<li>How would you approach a similar problem?
<hr></li>
</ul>
<h2>Edit - To Clarify</h2>
<ul>
<li>I am creating a custom rendered control (i.e. inherits from WebControl).</li>
<li>We are not using existnig Web Controls since we want complete control over the rendered output.</li>
<li>AFAIK the only way to get a server side event to occur from a custom rendered control is to call doPostBack from the rendered elements (please correct if wrong!).</li>
<li>ASP.NET MVC is not an option.</li>
</ul>
|
[
{
"answer_id": 59211,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 4,
"selected": false,
"text": ":syn sync fromstart\n :help syn-sync\n :help syntax\n"
},
{
"answer_id": 5652956,
"author": "Jose Elera",
"author_id": 428786,
"author_profile": "https://Stackoverflow.com/users/428786",
"pm_score": 4,
"selected": false,
"text": "Nazca"
},
{
"answer_id": 40917247,
"author": "jorgeh",
"author_id": 1620879,
"author_profile": "https://Stackoverflow.com/users/1620879",
"pm_score": 3,
"selected": false,
"text": ".html :syntax sync minlines=200 :syntax sync fromstart .vimrc autocmd BufEnter *.html :syntax sync fromstart\n .html"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
58,831 |
<p>My boss found a bug in a query I created, and I don't understand the reasoning behind the bug, although the query results prove he's correct. Here's the query (simplified version) before the fix:</p>
<pre><code>select PTNO,PTNM,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
</code></pre>
<p>and here it is after the fix:</p>
<pre><code>select PTNO,PTNM,PARTS.CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
</code></pre>
<p>The bug was, that null values were being shown for column CATCD, i.e. the query results included results from table CATEGORIES instead of PARTS.
Here's what I don't understand: if there was ambiguity in the original query, why didn't Oracle throw an error? As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity.
Am I wrong, or just not thinking about this problem correctly?</p>
<p>Update:</p>
<p>Here's a revised example, where the ambiguity error is not thrown:</p>
<pre><code>CREATE TABLE PARTS (PTNO NUMBER, CATCD NUMBER, SECCD NUMBER);
CREATE TABLE CATEGORIES(CATCD NUMBER);
CREATE TABLE SECTIONS(SECCD NUMBER, CATCD NUMBER);
select PTNO,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD)
left join SECTIONS on (SECTIONS.SECCD=PARTS.SECCD) ;
</code></pre>
<p>Anybody have a clue?</p>
|
[
{
"answer_id": 58902,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "select id\nfrom sysobjects s\nleft join syscolumns c on s.id = c.id\n select id\nfrom sysobjects \nleft join syscolumns on sysobjects.id = syscolumns.id\n"
},
{
"answer_id": 58907,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 3,
"selected": false,
"text": "create table parts (ptno number , ptnm number , catcd number); \ncreate table CATEGORIES (catcd number);\n\nselect PTNO,PTNM,CATCD from PARTS \nleft join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);\n"
},
{
"answer_id": 64169,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "select ptno, catcd\nfrom parts, categories, sections\nwhere categories.catcd (+) = parts.catcd\n and sections.seccd (+) = parts.seccd\n select ptno, catcd\nfrom (\n select ptno, seccd, catcd\n from parts\n left join categories on (categories.CATCD=parts.CATCD) \n)\nleft join sections on (sections.SECCD=parts.SECCD)\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751/"
] |
58,841 |
<p>How can I get precompiled headers working with GCC?</p>
<p>I have had no luck in my attempts and I haven't seen many good examples for how to set it up. I've tried on <a href="https://en.wikipedia.org/wiki/Cygwin" rel="nofollow noreferrer">Cygwin</a> GCC 3.4.4 and using 4.0 on <a href="https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29" rel="nofollow noreferrer">Ubuntu</a>.</p>
|
[
{
"answer_id": 60577,
"author": "simon",
"author_id": 4875,
"author_profile": "https://Stackoverflow.com/users/4875",
"pm_score": 3,
"selected": false,
"text": "g++ $(CPPFLAGS) test.h\n"
},
{
"answer_id": 1191407,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 6,
"selected": false,
"text": ".gch stdafx.h.gch stdafx.h #include <string>\n#include <stdio.h>\n #include \"stdafx.h\"\nint main(int argc, char**argv)\n{\n std::string s = \"Hi\";\n return 0;\n}\n > g++ -c stdafx.h -o stdafx.h.gch > g++ a.cpp > ./a.out"
},
{
"answer_id": 2935536,
"author": "User1",
"author_id": 125380,
"author_profile": "https://Stackoverflow.com/users/125380",
"pm_score": 6,
"selected": false,
"text": "#include <boost/xpressive/xpressive.hpp>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::xpressive;\n\n// A simple regular expression test\nint main()\n{\n std::string hello(\"Hello, World!\");\n\n sregex rex = sregex::compile( \"(\\\\w+) (\\\\w+)!\" );\n smatch what;\n\n if( regex_match( hello, what, rex ) )\n {\n std::cout << what[0] << '\\n'; // Whole match\n std::cout << what[1] << '\\n'; // First capture\n std::cout << what[2] << '\\n'; // Second capture\n }\n return 0;\n}\n -H g++ -Wall -fexceptions -g -c main.cpp -o obj/Debug/main.o\n sudo g++ -Wall -fexceptions -g /usr/local/include/boost/xpressive/xpressive.hpp\n -H g++ -Wall -fexceptions -H -g -c main.cpp -o obj/Debug/main.o\n\n! /usr/local/include/boost/xpressive/xpressive.hpp.gch\nmain.cpp\n. /usr/include/c++/4.4/iostream\n.. /usr/include/c++/4.4/x86_64-linux-gnu/bits/c++config.h\n.. /usr/include/c++/4.4/ostream\n.. /usr/include/c++/4.4/istream\nmain.cpp\n g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3\n"
},
{
"answer_id": 10756166,
"author": "psaghelyi",
"author_id": 315527,
"author_profile": "https://Stackoverflow.com/users/315527",
"pm_score": 3,
"selected": false,
"text": "-x -x c++-header -x c++ pch.h // Put your common include files here: Boost, STL as well as your project's headers.\n main.cpp #include \"pch.h\"\n// Use the PCH here.\n $ g++ -x c++-header -o pch.h.gch -c pch.h\n pch.h.gch pch.h pch.h"
},
{
"answer_id": 60571708,
"author": "Íhor Mé",
"author_id": 2617351,
"author_profile": "https://Stackoverflow.com/users/2617351",
"pm_score": 2,
"selected": false,
"text": "-include your_header.h bits/stdc++.h #include <bits/stdc++.h>\n g++ sol.cpp -H -O3 -pthread -lm -std=c++14 -o executable\n . /usr/include/x86_64-linux-gnu/c++/7/bits/stdc++.h\n bits stdc++.h g++ bits/stdc++.h -O3 -std=c++14 -pthread\n bits/stdc++.gch g++ sol.cpp -O3 -pthread -lm -std=c++14 -o executable\n g++ sol.cpp -include bits/stdc++.h -O3 -pthread -lm -std=c++14 -o executable\n .gch .h -include bits/stdc++.h *.h *.cpp -O3 -pthread *.gch time g++ sol.cpp ...\n g++ sol.cpp -H -O3 -pthread -lm -std=c++14 -o executable\n ! ! ./bits/stdc++.h.gch\n....\n"
},
{
"answer_id": 65730829,
"author": "Brad Robinson",
"author_id": 77002,
"author_profile": "https://Stackoverflow.com/users/77002",
"pm_score": 0,
"selected": false,
"text": ".gch .h -H"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5200/"
] |
58,851 |
<p>I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.</p>
|
[
{
"answer_id": 58892,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 3,
"selected": false,
"text": " $ cat gdbtest.c\n int abc = 43;\n\n int main()\n {\n abc = 10;\n }\n $ gcc -g -o gdbtest gdbtest.c\n $ gdb gdbtest\n ...\n (gdb) watch abc\n Hardware watchpoint 1: abc\n (gdb) r\n Starting program: /home/mweerden/gdbtest \n ...\n\n Old value = 43\n New value = 10\n main () at gdbtest.c:6\n 6 }\n (gdb) quit\n"
},
{
"answer_id": 59146,
"author": "asksol",
"author_id": 5577,
"author_profile": "https://Stackoverflow.com/users/5577",
"pm_score": 9,
"selected": true,
"text": "gdb$ rwatch *0xfeedface\nHardware read watchpoint 2: *0xfeedface\n gdb$ rwatch $ebx+0xec1a04f\nExpression cannot be implemented with read/access watchpoint.\n gdb$ print $ebx \n$13 = 0x135700\ngdb$ rwatch *0x135700+0xec1a04f\nHardware read watchpoint 3: *0x135700 + 0xec1a04f\ngdb$ c\nHardware read watchpoint 3: *0x135700 + 0xec1a04f\n\nValue = 0xec34daf\n0x9527d6e7 in objc_msgSend ()\n gdb$ show can-use-hw-watchpoints\nDebugger's willingness to use watchpoint hardware is 1.\n"
},
{
"answer_id": 966525,
"author": "Smirnov",
"author_id": 89207,
"author_profile": "https://Stackoverflow.com/users/89207",
"pm_score": 5,
"selected": false,
"text": "(char *)(0x135700 +0xec1a04f) rwatch *0x135700+0xec1a04f rwatch *(0x135700+0xec1a04f) ()"
},
{
"answer_id": 31202563,
"author": "Paolo M",
"author_id": 2508150,
"author_profile": "https://Stackoverflow.com/users/2508150",
"pm_score": 5,
"selected": false,
"text": "(gdb) watch foo foo (gdb) watch *(int*)0x12345678 (gdb) watch a*b + c/d"
},
{
"answer_id": 70610117,
"author": "Singh",
"author_id": 13032809,
"author_profile": "https://Stackoverflow.com/users/13032809",
"pm_score": 0,
"selected": false,
"text": "int main()\n{\nint i = 0;\nint j;\ni = 3840 // binary 1100 0000 0000 to take into account endianness\nother code..\n}\n Thread 1 \"testing2\" h\nBreakpoint 2 at 0x10040109b: file testing2.c, line 10.\n(gdb) s\n7 i = 3840;\n(gdb) p i\n$1 = 0\n(gdb) p &i\n$2 = (int *) 0xffffcbfc\n(gdb) watch *0xffffcbfc\nHardware watchpoint 3: *0xffffcbfc\n(gdb) s\n[New Thread 13168.0xa74]\n\nThread 1 \"testing2\" hit Breakpoint 2, main () at testing2.c:10\n10 b = a;\n(gdb) p i\n$3 = 3840\n(gdb) p *0xffffcbfc\n$4 = 3840\n(gdb) p/t *0xffffcbfc\n$5 = 111100000000\n (gdb) p &i\n$6 = (int *) 0xffffcbfc\n(gdb) p i\n$7 = 0\n(gdb) watch *(int *) 0xffffcbfc\nHardware watchpoint 6: *(int *) 0xffffcbfc\n(gdb) b 10\nBreakpoint 7 at 0x10040109b: file testing2.c, line 10.\n(gdb) i b\nNum Type Disp Enb Address What\n6 hw watchpoint keep y *(int *) 0xffffcbfc\n7 breakpoint keep y 0x000000010040109b in main at testing2.c:10\n(gdb) n\n[New Thread 21508.0x3c30]\n\nThread 1 \"testing2\" hit Hardware watchpoint 6: *(int *) 0xffffcbfc\n\nOld value = 0\nNew value = 3840\n\nThread 1 \"testing2\" hit Breakpoint 7, main () at testing2.c:10\n10 b = a;\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3022/"
] |
58,872 |
<p>I've read in several places that the rectangle functions in emacs are very useful. I've read a bit about them, and I can't quite figure why. I mean, when you want to kill a paragraph, you mark the first row/column and then the last one, and that's actually a rectangle, right? But you can still use the normal kill...</p>
<p>So what kind of transformations would you do with them?</p>
|
[
{
"answer_id": 58885,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 6,
"selected": true,
"text": "M-x delete-rectangle M-x kill-rectangle M-x yank-rectangle 1. alligator alphorn\n2. baboon bugle\n3. crocodile cornet\n4. dog didgeridoo\n5. elephant euphonium \n6. fish flugelhorn \n7. gopher guitar\n M-x kill-rectangle 1. alphorn\n2. bugle\n3. cornet\n4. didgeridoo\n5. euphonium \n6. flugelhorn\n7. guitar\n M-x yank-rectangle 1. alphorn alligator \n2. bugle baboon \n3. cornet crocodile \n4. didgeridoo dog \n5. euphonium elephant \n6. flugelhorn fish \n7. guitar gopher \n"
},
{
"answer_id": 59523,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": false,
"text": "C-x r k C-x r t C-x r C-SPC C-x r t <SPC> <SPC> <SPC> <SPC> <RET> C-x r k C-x r r C-x r y C-x r o C-x r c C-x r t C-x r k"
},
{
"answer_id": 23968635,
"author": "Adobe",
"author_id": 788700,
"author_profile": "https://Stackoverflow.com/users/788700",
"pm_score": 1,
"selected": false,
"text": "(rectangle-number-lines START END START-AT &optional FORMAT)\n\nInsert numbers in front of the region-rectangle.\n\nSTART-AT, if non-nil, should be a number from which to begin\ncounting. FORMAT, if non-nil, should be a format string to pass\nto `format' along with the line count. When called interactively\nwith a prefix argument, prompt for START-AT and FORMAT.\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3785/"
] |
58,910 |
<p>I've been trying to convert SVG images to PNG using C#, without having to write too much code. Can anyone recommend a library or example code for doing this?</p>
|
[
{
"answer_id": 548553,
"author": "stevenvh",
"author_id": 66056,
"author_profile": "https://Stackoverflow.com/users/66056",
"pm_score": 3,
"selected": false,
"text": "procedure ExecNewProcess(ProgramName : String; Wait: Boolean);\nvar\n StartInfo : TStartupInfo;\n ProcInfo : TProcessInformation;\n CreateOK : Boolean;\nbegin\n FillChar(StartInfo, SizeOf(TStartupInfo), #0);\n FillChar(ProcInfo, SizeOf(TProcessInformation), #0);\n StartInfo.cb := SizeOf(TStartupInfo);\n CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,\n CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,\n nil, nil, StartInfo, ProcInfo);\n if CreateOK then begin\n //may or may not be needed. Usually wait for child processes\n if Wait then\n WaitForSingleObject(ProcInfo.hProcess, INFINITE);\n end else\n ShowMessage('Unable to run ' + ProgramName);\n\n CloseHandle(ProcInfo.hProcess);\n CloseHandle(ProcInfo.hThread);\nend;\n\nprocedure ConvertSVGtoPNG(aFilename: String);\nconst\n ExecLine = 'c:\\windows\\system32\\java.exe -jar C:\\Apps\\batik-1.7\\batik-rasterizer.jar ';\nbegin\n ExecNewProcess(ExecLine + aFilename, True);\nend;\n"
},
{
"answer_id": 7003793,
"author": "nw.",
"author_id": 307960,
"author_profile": "https://Stackoverflow.com/users/307960",
"pm_score": 4,
"selected": false,
"text": "[DllImport(\"kernel32.dll\", SetLastError = true)]\nstatic extern bool SetDllDirectory(string pathname);\n\n[DllImport(\"libgobject-2.0-0.dll\", SetLastError = true)]\nstatic extern void g_type_init(); \n\n[DllImport(\"librsvg-2-2.dll\", SetLastError = true)]\nstatic extern IntPtr rsvg_pixbuf_from_file_at_size(string file_name, int width, int height, out IntPtr error);\n\n[DllImport(\"libgdk_pixbuf-2.0-0.dll\", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\nstatic extern bool gdk_pixbuf_save(IntPtr pixbuf, string filename, string type, out IntPtr error, __arglist);\n\npublic static void RasterizeSvg(string inputFileName, string outputFileName)\n{\n bool callSuccessful = SetDllDirectory(\"C:\\\\Program Files\\\\GIMP-2.0\\\\bin\");\n if (!callSuccessful)\n {\n throw new Exception(\"Could not set DLL directory\");\n }\n g_type_init();\n IntPtr error;\n IntPtr result = rsvg_pixbuf_from_file_at_size(inputFileName, -1, -1, out error);\n if (error != IntPtr.Zero)\n {\n throw new Exception(Marshal.ReadInt32(error).ToString());\n }\n callSuccessful = gdk_pixbuf_save(result, outputFileName, \"png\", out error, __arglist(null));\n if (!callSuccessful)\n {\n throw new Exception(error.ToInt32().ToString());\n }\n}\n"
},
{
"answer_id": 12884409,
"author": "Anish",
"author_id": 463469,
"author_profile": "https://Stackoverflow.com/users/463469",
"pm_score": 6,
"selected": false,
"text": "var byteArray = Encoding.ASCII.GetBytes(svgFileContents);\nusing (var stream = new MemoryStream(byteArray))\n{\n var svgDocument = SvgDocument.Open(stream);\n var bitmap = svgDocument.Draw();\n bitmap.Save(path, ImageFormat.Png);\n}\n"
},
{
"answer_id": 14878965,
"author": "Michal Kieloch",
"author_id": 936038,
"author_profile": "https://Stackoverflow.com/users/936038",
"pm_score": 2,
"selected": false,
"text": " foreach(var child in svgDocument.Children)\n {\n SetFont(child);\n }\n\n public void SetFont(SvgElement element)\n {\n foreach(var child in element.Children)\n {\n SetFont(child); //Call this function again with the child, this will loop\n //until the element has no more children\n }\n\n try\n {\n var svgText = (SvgText)parent; //try to cast the element as a SvgText\n //if it succeeds you can modify the font\n\n svgText.Font = new Font(\"Arial\", 12.0f);\n svgText.FontSize = new SvgUnit(12.0f);\n }\n catch\n {\n\n }\n }\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5744/"
] |
58,916 |
<p>Suppose I have a table called Companies that has a DepartmentID column. There's also a Departaments table that has as EmployeeID column. Of course I have an Employee table as well. The problem is that I want to delete a company, so first i have to delete all the employees for every departament and then all the departaments in the company.
Cascade Delete is not an option, therefore i wish to use nested transactions. I'm new to SQL so I would appreciate your help.</p>
|
[
{
"answer_id": 58943,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "BEGIN\n delete from Employee where departmentId = 1;\n BEGIN\n delete from Department where companyId = 2;\n BEGIN\n delete from Company where companyId = 2;\n END\n END\nEND\n"
},
{
"answer_id": 58974,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 3,
"selected": true,
"text": "BEGIN TRAN\n\nDELETE FROM Employee\n FROM Employee\n INNER JOIN Department ON Employee.DepartmentID = Department.DepartmentID\n INNER JOIN Company ON Department.CompanyID = Company.CompanyID\n WHERE Company.CompanyID = @CompanyID\n\nDELETE FROM Department\n FROM Department\n INNER JOIN Company ON Department.CompanyID = Company.CompanyID\n WHERE Company.CompanyID = @CompanyID\n\nDELETE FROM Company\n WHERE Company.CompanyID = @CompanyID\n\nCOMMIT TRAN\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] |
58,925 |
<p>I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?</p>
|
[
{
"answer_id": 58931,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 6,
"selected": true,
"text": "public string RenderControlToHtml(Control ControlToRender)\n{\n System.Text.StringBuilder sb = new System.Text.StringBuilder();\n System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);\n System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);\n ControlToRender.RenderControl(htmlWriter);\n return sb.ToString();\n}\n"
},
{
"answer_id": 59323,
"author": "a7drew",
"author_id": 4239,
"author_profile": "https://Stackoverflow.com/users/4239",
"pm_score": 3,
"selected": false,
"text": "public void GetHtmlFromMySweetControl(HttpContext context)\n{\n HttpRequest httpRequest = context.Request;\n HttpResponse httpResponse = context.Response;\n\n string foo = httpRequest[\"foo\"];\n\n Page pageHolder = new Page();\n string path = \"~/usercontrols/MySweetControl.ascx\";\n MySweetControl ctrl = (MySweetControl)pageHolder.LoadControl(path);\n ctrl.BindProducts(foo);\n pageHolder.Controls.Add(ctrl);\n\n StringWriter sw = new StringWriter();\n context.Server.Execute(pageHolder, sw, false);\n httpResponse.Write(sw.ToString());\n}\n"
},
{
"answer_id": 32765865,
"author": "avs099",
"author_id": 1246870,
"author_profile": "https://Stackoverflow.com/users/1246870",
"pm_score": 4,
"selected": false,
"text": "David Basarab a7drew Context Server.Execute private string RenderControl()\n{\n var sb = new System.Text.StringBuilder();\n using (var stWriter = new System.IO.StringWriter(sb))\n using (var htmlWriter = new HtmlTextWriter(stWriter))\n {\n var p = new Page();\n var ctrl = (YourControl)p.LoadControl(\"~/controls/building blocks/YourControl.ascx\");\n ctrl.Visible = true;\n\n // do your own init logic if needed\n\n p.Controls.Add(ctrl);\n ctrl.RenderControl(htmlWriter);\n return sb.ToString();\n }\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
58,937 |
<p>Using VB.NET, how do I toggle the state of Caps Lock? </p>
|
[
{
"answer_id": 58941,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 4,
"selected": true,
"text": "Imports System.Runtime.InteropServices\n\nPublic Class Form2\n\n Private Declare Sub keybd_event Lib \"user32\" ( _\n ByVal bVk As Byte, _\n ByVal bScan As Byte, _\n ByVal dwFlags As Integer, _\n ByVal dwExtraInfo As Integer _\n )\n Private Const VK_CAPITAL As Integer = &H14\n Private Const KEYEVENTF_EXTENDEDKEY As Integer = &H1\n Private Const KEYEVENTF_KEYUP As Integer = &H2\n\n Private Sub Button1_Click( _\n ByVal sender As System.Object, _\n ByVal e As System.EventArgs _\n ) Handles Button1.Click\n\n ' Toggle CapsLock\n\n ' Simulate the Key Press\n keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)\n\n ' Simulate the Key Release\n keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)\n End Sub\n\nEnd Class \n"
},
{
"answer_id": 58942,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 3,
"selected": false,
"text": "Public Class Form1\n Private Declare Sub keybd_event Lib \"user32\" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)\n Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n Call keybd_event(System.Windows.Forms.Keys.CapsLock, &H14, 1, 0)\n Call keybd_event(System.Windows.Forms.Keys.CapsLock, &H14, 3, 0)\n End Sub\nEnd Class\n"
},
{
"answer_id": 33616002,
"author": "Ben",
"author_id": 5543707,
"author_profile": "https://Stackoverflow.com/users/5543707",
"pm_score": 0,
"selected": false,
"text": "Private Declare Sub keybd_event Lib \"user32\" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)\nPrivate Const KEYEVENTF_EXTENDEDKEY As Integer = &H1\nPrivate Const KEYEVENTF_KEYUP As Integer = &H2\n'put this where you want to turn caps lock on or off\nkeybd_event(VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)\nkeybd_event(VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133/"
] |
58,939 |
<p>I'm trying to get an event to fire whenever a choice is made from a <code>JComboBox</code>.</p>
<p>The problem I'm having is that there is no obvious <code>addSelectionListener()</code> method.</p>
<p>I've tried to use <code>actionPerformed()</code>, but it never fires.</p>
<p>Short of overriding the model for the <code>JComboBox</code>, I'm out of ideas.</p>
<p>How do I get notified of a selection change on a <code>JComboBox</code>?**</p>
<p><strong>Edit:</strong> I have to apologize. It turns out I was using a misbehaving subclass of <code>JComboBox</code>, but I'll leave the question up since your answer is good.</p>
|
[
{
"answer_id": 58963,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 9,
"selected": true,
"text": "combo.addActionListener (new ActionListener () {\n public void actionPerformed(ActionEvent e) {\n doSomething();\n }\n});\n addItemListener() ItemEvents"
},
{
"answer_id": 58965,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 5,
"selected": false,
"text": "itemStateChanged() ItemListener"
},
{
"answer_id": 2187058,
"author": "JavaKeith",
"author_id": 264662,
"author_profile": "https://Stackoverflow.com/users/264662",
"pm_score": 3,
"selected": false,
"text": " int selectedIndex = myComboBox.getSelectedIndex();\n Object selectedObject = myComboBox.getSelectedItem();\n String selectedValue = myComboBox.getSelectedValue().toString();\n"
},
{
"answer_id": 14424530,
"author": "Viacheslav",
"author_id": 1043067,
"author_profile": "https://Stackoverflow.com/users/1043067",
"pm_score": 7,
"selected": false,
"text": "ItemListener class ItemChangeListener implements ItemListener{\n @Override\n public void itemStateChanged(ItemEvent event) {\n if (event.getStateChange() == ItemEvent.SELECTED) {\n Object item = event.getItem();\n // do something with object\n }\n } \n}\n addItemListener(new ItemChangeListener());\n"
},
{
"answer_id": 17846338,
"author": "Ahuramazda",
"author_id": 2581460,
"author_profile": "https://Stackoverflow.com/users/2581460",
"pm_score": 4,
"selected": false,
"text": "JComboBox comboBox = new JComboBox();\n\ncomboBox.setBounds(84, 45, 150, 20);\ncontentPane.add(comboBox);\n\nJComboBox comboBox_1 = new JComboBox();\ncomboBox_1.setBounds(84, 97, 150, 20);\ncontentPane.add(comboBox_1);\ncomboBox.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent arg0) {\n //Do Something\n }\n});\n"
},
{
"answer_id": 64692212,
"author": "Mehmet Onar",
"author_id": 6573672,
"author_profile": "https://Stackoverflow.com/users/6573672",
"pm_score": 2,
"selected": false,
"text": "getComboBox().addItemListener(this::comboBoxitemStateChanged);\n public void comboBoxitemStateChanged(ItemEvent e) {\n if (e.getStateChange() == ItemEvent.SELECTED) {\n YourObject selectedItem = (YourObject) e.getItem();\n //TODO your actitons\n }\n}\n"
},
{
"answer_id": 68821546,
"author": "EverCpp",
"author_id": 12048805,
"author_profile": "https://Stackoverflow.com/users/12048805",
"pm_score": 2,
"selected": false,
"text": " cb = new JComboBox<String>();\n cb.setBounds(10, 33, 46, 22);\n panelConfig.add(cb);\n for(int i = 0; i < 10; ++i)\n {\n cb.addItem(Integer.toString(i));\n }\n cb.addItemListener(new ItemListener()\n {\n @Override\n public void itemStateChanged(ItemEvent e)\n {\n if(e.getID() == temEvent.ITEM_STATE_CHANGED)\n {\n if(e.getStateChange() == ItemEvent.SELECTED)\n {\n JComboBox<String> cb = (JComboBox<String>) e.getSource();\n String newSelection = (String) cb.getSelectedItem();\n System.out.println(\"newSelection: \" + newSelection);\n }\n }\n }\n });\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
58,940 |
<p>I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?</p>
<pre><code>CREATE PROCEDURE getOrder (@orderId as numeric) AS
BEGIN
select order_address, order_number from order_table where order_id = @orderId
select item, number_of_items, cost from order_line where order_id = @orderId
END
</code></pre>
<p>I need to be able to iterate through both result sets individually.</p>
<p>EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.</p>
<p>The result sets returned by the procedures are not the same data types or number of columns.</p>
|
[
{
"answer_id": 59015,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 6,
"selected": true,
"text": "INSERT INTO #Table (...columns...)\nEXEC MySproc ...parameters...\n"
},
{
"answer_id": 879516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "CREATE PROCEDURE [dbo].[usp_SF_Read] AS\nSET NOCOUNT ON;\nCREATE TABLE #Table01 (Document_ID VARCHAR(100)\n , Document_status_definition_uid INT\n , Document_status_Code VARCHAR(100) \n , Attachment_count INT\n , PRIMARY KEY (Document_ID));\n Partial Public Class StoredProcedures\n <Microsoft.SqlServer.Server.SqlProcedure()> _\n Public Shared Sub usp_SF_ReadSFIntoTables()\n\n End Sub\nEnd Class\n New SqlConnection(\"context connection=true\") Dim dataset As DataSet = New DataSet\n With New SqlDataAdapter(cmd)\n .Fill(dataset) ' get all the data.\n End With\n'you can use dataset.ReadXmlSchema at this point...\n"
},
{
"answer_id": 7168255,
"author": "Daniel Barbalace",
"author_id": 908590,
"author_profile": "https://Stackoverflow.com/users/908590",
"pm_score": 3,
"selected": false,
"text": "if (N = -1 or N = 0)\n select ...\n\nif (N = -1 or N = 1)\n select ...\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1836/"
] |
58,969 |
<p>I'm starting to learn how to use PHPUnit to test the website I'm working on. The problem I'm running into is that I have five different user types defined and I need to be able to test every class with the different types. I currently have a user class and I would like to pass this to each function but I can't figure out how to pass this or test the different errors that could come back as being correct or not.</p>
<p><b>Edit:</b> I should have said. I have a user class and I want to pass a different instance of this class to each unit test. </p>
|
[
{
"answer_id": 63442,
"author": "Andrew Culver",
"author_id": 7549,
"author_profile": "https://Stackoverflow.com/users/7549",
"pm_score": 3,
"selected": true,
"text": "class User\n{\n public function commonFunctionality()\n {\n return 'Something';\n }\n\n public function modifiedFunctionality()\n {\n return 'One Thing';\n }\n}\n\nclass SpecialUser extends User\n{\n public function specialFunctionality()\n {\n return 'Nothing';\n }\n\n public function modifiedFunctionality()\n {\n return 'Another Thing';\n }\n}\n class Test_User extends PHPUnit_Framework_TestCase\n{\n public function create()\n {\n return new User();\n }\n\n public function testCommonFunctionality()\n {\n $user = $this->create();\n $this->assertEquals('Something', $user->commonFunctionality);\n }\n\n public function testModifiedFunctionality()\n {\n $user = $this->create();\n $this->assertEquals('One Thing', $user->commonFunctionality);\n }\n}\n\nclass Test_SpecialUser extends Test_User\n{\n public function create() {\n return new SpecialUser();\n }\n\n public function testSpecialFunctionality()\n {\n $user = $this->create();\n $this->assertEquals('Nothing', $user->commonFunctionality);\n }\n\n public function testModifiedFunctionality()\n {\n $user = $this->create();\n $this->assertEquals('Another Thing', $user->commonFunctionality);\n }\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4437/"
] |
58,976 |
<p>How do I find out whether or not Caps Lock is activated, using VB.NET?</p>
<p>This is a follow-up to my <a href="https://stackoverflow.com/questions/58937/how-do-i-toggle-caps-lock-in-vbnet">earlier question</a>.</p>
|
[
{
"answer_id": 58991,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "Declare Function GetKeyState Lib \"user32\" \n Alias \"GetKeyState\" (ByValnVirtKey As Int32) As Int16\n\nPrivate Const VK_CAPSLOCK = &H14\n\nIf GetKeyState(VK_CAPSLOCK) = 1 Then ...\n"
},
{
"answer_id": 58993,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 5,
"selected": true,
"text": "Imports System\nImports System.Windows.Forms\nImports Microsoft.VisualBasic\n\nPublic Class CapsLockIndicator\n\n Public Shared Sub Main()\n if Control.IsKeyLocked(Keys.CapsLock) Then\n MessageBox.Show(\"The Caps Lock key is ON.\")\n Else\n MessageBox.Show(\"The Caps Lock key is OFF.\")\n End If\n End Sub 'Main\nEnd Class 'CapsLockIndicator\n using System;\nusing System.Windows.Forms;\n\npublic class CapsLockIndicator\n{\n public static void Main()\n {\n if (Control.IsKeyLocked(Keys.CapsLock)) {\n MessageBox.Show(\"The Caps Lock key is ON.\");\n }\n else {\n MessageBox.Show(\"The Caps Lock key is OFF.\");\n }\n }\n}\n"
},
{
"answer_id": 29317731,
"author": "JumboUser155",
"author_id": 4401083,
"author_profile": "https://Stackoverflow.com/users/4401083",
"pm_score": 2,
"selected": false,
"text": "label1 Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick\n If My.Computer.Keyboard.CapsLock = True Then\n Label1.Text = \"Caps Lock Enabled\"\n Else\n Label1.Text = \"Caps Lock Disabled\"\n End If\nEnd Sub\n"
},
{
"answer_id": 43073619,
"author": "Thomas Bailey",
"author_id": 6416987,
"author_profile": "https://Stackoverflow.com/users/6416987",
"pm_score": 0,
"selected": false,
"text": "Me.KeyDown My.Computer.Keyboard.CapsLock Me.Keydown Private Sub WindowLogin_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown\n\n If Keyboard.IsKeyDown(Key.Enter) Then\n Call SignIn()\n End If\n\nEnd Sub\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133/"
] |
58,988 |
<p>The Interface Segregation Principle (ISP) says that many client specific interfaces are better than one general purpose interface. Why is this important?</p>
|
[
{
"answer_id": 17999321,
"author": "isJustMe",
"author_id": 571946,
"author_profile": "https://Stackoverflow.com/users/571946",
"pm_score": 3,
"selected": false,
"text": "public interface Reportable {\n\n void printPDF();\n void printWord();\n void printExcel();\n void printPPT();\n void printHTML();\n\n\n}\n"
},
{
"answer_id": 56398042,
"author": "Scott Hannen",
"author_id": 5101046,
"author_profile": "https://Stackoverflow.com/users/5101046",
"pm_score": 2,
"selected": false,
"text": "Red Green Blue Red Green Blue Red Blue Green Blue Red Green Blue Red Blue Red Blue Green Green Blue Blue Green Red Blue List<E> List<E> List<E>"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/58988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3012/"
] |
59,007 |
<p>I'd like to automate TortoiseSVN as part of a commit process.
Specifically I'd like to dynamically create a log entry for the commit dialog.</p>
<p>I know that I can launch the commit dialog either from the commandline or by right clicking on a folder and selecting svncommit.</p>
<p>I'd like to use the start commit hook to setup a log entry.
I thought this worked by passing an entry file name in the MESSAGEFILE variable but when I add a hook script it cannot see this variable (hook launched successfully after right clicking and choosing svncommit).</p>
<p>When I try using the commandline I use the /logmsgfile parameter but it seems to have no effect.</p>
<p>I'm using tortoisesvn 1.5.3.</p>
|
[
{
"answer_id": 59379,
"author": "Nathan Jones",
"author_id": 5848,
"author_profile": "https://Stackoverflow.com/users/5848",
"pm_score": 1,
"selected": false,
"text": "GenerateLogMsg.exe > tmp.msg\n\"C:\\Program Files\\TortoiseSVN\\bin\\TortoiseProc.exe\" /command:commit /path:. /logmsgfile:\"C:\\Documents and Settings\\User\\My Documents\\Visual Studio Projects\\Project\\tmp.msg\"\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427/"
] |
59,013 |
<p>Context:
I'm in charge of running a service written in .NET. Proprietary application. It uses a SQL Server database. It ran as a user member of the Administrators group in the local machine. It worked alright before I added the machine to a domain.</p>
<p>So, I added the machine to a domain (Win 2003) and changed the user to a member of the Power Users group and now, the</p>
<p>Problem:
Some of the SQL sentences it tries to execute are "magically" in spanish localization (where , separates floating point numbers instead of .), leading to errors. </p>
<blockquote>
<p>There are fewer columns in the INSERT
statement than values specified in the
VALUES clause. The number of values in
the VALUES clause must match the
number of columns specified in the
INSERT statement. at
System.Data.SqlClient.SqlConnection.OnError(SqlException
exception, Boolean breakConnection)</p>
</blockquote>
<p>Operating System and Regional Settings in the machine are in English. I asked the provider of the application and he said:</p>
<blockquote>
<p>Looks like you have a combination of
code running under Spanish locale, and
SQL server under English locale. So
the SQL expects '15.28' and not
'15,28'</p>
</blockquote>
<p>Which looks wrong to me in various levels (how can SQL Server distinguish between commas to separate arguments and commas belonging to a floating point number?).</p>
<p>So, the code seems to be grabbing the spanish locale from somewhere, I don't know if it's the user it runs as, or someplace else (global policy, maybe?). But the question is</p>
<p>What are the places where localization is defined on a machine/user/domain basis?</p>
<p>I don't know all the places I must search for the culprit, so please help me to find it!</p>
|
[
{
"answer_id": 59071,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 3,
"selected": true,
"text": "HKEY_CURRENT_USER\\Control Panel\\International\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
59,016 |
<p>The Open/Closed Principle states that software entities (classes, modules, etc.) should be open for extension, but closed for modification. What does this mean, and why is it an important principle of good object-oriented design?</p>
|
[
{
"answer_id": 44913685,
"author": "maysara",
"author_id": 5503714,
"author_profile": "https://Stackoverflow.com/users/5503714",
"pm_score": 3,
"selected": false,
"text": "var juiceTypes = ['Mango','Apple','Lemon'];\nfunction juiceMaker(type){\n if(juiceTypes.indexOf(type)!=-1)\n console.log('Here is your juice, Have a nice day');\n else\n console.log('sorry, Error happned');\n}\n\nexports.makeJuice = juiceMaker;\n var juiceTypes = [];\nfunction juiceMaker(type){\n if(juiceTypes.indexOf(type)!=-1)\n console.log('Here is your juice, Have a nice day');\n else\n console.log('sorry, Error happned');\n}\nfunction addType(typeName){\n if(juiceTypes.indexOf(typeName)==-1)\n juiceTypes.push(typeName);\n}\nfunction removeType(typeName){\n let index = juiceTypes.indexOf(typeName)\n if(index!==-1)\n juiceTypes.splice(index,1);\n}\n\nexports.makeJuice = juiceMaker;\nexports.addType = addType;\nexports.removeType = removeType;\n"
},
{
"answer_id": 61270467,
"author": "Sumanth Varada",
"author_id": 4044987,
"author_profile": "https://Stackoverflow.com/users/4044987",
"pm_score": 3,
"selected": false,
"text": "class Rectangle {\n public int width;\n public int lenth;\n}\n\nclass Circle {\n public int radius;\n}\n\nclass AreaService {\n public int areaForRectangle(Rectangle rectangle) {\n return rectangle.width * rectangle.lenth;\n }\n\n public int areaForCircle(Circle circle) {\n return (22 / 7) * circle.radius * circle.radius;\n }\n}\n interface Shape{\n int area();\n}\n\nclass Rectangle implements Shape{\n public int width;\n public int lenth;\n\n @Override\n public int area() {\n return lenth * width;\n }\n}\n\nclass Cirle implements Shape{\n public int radius;\n\n @Override\n public int area() {\n return (22/7) * radius * radius;\n }\n}\n\nclass AreaService {\n int area(Shape shape) {\n return shape.area();\n }\n}\n"
},
{
"answer_id": 64537644,
"author": "Yogesh Umesh Vaity",
"author_id": 5925259,
"author_profile": "https://Stackoverflow.com/users/5925259",
"pm_score": 3,
"selected": false,
"text": "Bike Car Bike Car Garage Garage class Bike {\n public void service() {\n System.out.println(\"Bike servicing strategy performed.\");\n }\n}\n\nclass Car {\n public void service() {\n System.out.println(\"Car servicing strategy performed.\");\n }\n}\n\nclass Garage {\n public void serviceBike(Bike bike) {\n bike.service();\n }\n\n public void serviceCar(Car car) {\n car.service();\n }\n}\n Truck Bus Garage serviceTruck() serviceBus() Garage Bike Car Bus Truck Garage Bike Car interface Vehicle service() Garage Bus Truck Bike Car Garage Vehicle service(Vehicle vehicle) { } Vehicle Bike Car interface Vehicle {\n void service();\n}\n\nclass Bike implements Vehicle {\n @Override\n public void service() {\n System.out.println(\"Bike servicing strategy performed.\");\n }\n}\n\nclass Car implements Vehicle {\n @Override\n public void service() {\n System.out.println(\"Car servicing strategy performed.\");\n }\n}\n\nclass Garage {\n public void service(Vehicle vehicle) {\n vehicle.service();\n }\n}\n Garage Vehicle Vehicle Garage Garage Vehicle Garage Vehicle Vehicle Vehicle Vehicle Truck Bus"
},
{
"answer_id": 68566748,
"author": "Ramakrishna Joshi",
"author_id": 8956093,
"author_profile": "https://Stackoverflow.com/users/8956093",
"pm_score": 2,
"selected": false,
"text": "open class AppLogger {\n\n open fun logError(message: String) {\n // reporting error to Firebase\n FirebaseAnalytics.logException(message)\n }\n}\n fun logError(message: String, origin: String) {\n if (origin == \"Payment\") {\n //report to both Firebase and Instabug\n FirebaseAnalytics.logException(message)\n InstaBug.logException(message)\n } else {\n // otherwise report only to Firebase\n FirebaseAnalytics.logException(message)\n }\n}\n class InstaBugLogger : AppLogger() {\n\n override fun logError(message: String) {\n super.logError(message) // This uses AppLogger.logError to report to Firebase.\n InstaBug.logException(message) //Reporting to Instabug\n }\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3012/"
] |
59,022 |
<p>We are currently storing plain text passwords for a web app that we have. </p>
<p>I keep advocating moving to a password hash but another developer said that this would be less secure -- more passwords could match the hash and a dictionary/hash attack would be faster.</p>
<p>Is there any truth to this argument? </p>
|
[
{
"answer_id": 59054,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 1,
"selected": false,
"text": "String hashedPass=CryptUtils.MD5(\"alsdl;ksahglhkjfsdkjhkjhkfsdlsdf\" + user.getCreateDate().toString() + user.getPassword);\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5882/"
] |
59,044 |
<p>Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)</p>
|
[
{
"answer_id": 59055,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 8,
"selected": true,
"text": "a b UPDATE \n YourTable\nSET \n Column1 = REPLACE(Column1,'a','b')\nWHERE \n Column1 LIKE '%a%'\n"
},
{
"answer_id": 59057,
"author": "Jiaaro",
"author_id": 2908,
"author_profile": "https://Stackoverflow.com/users/2908",
"pm_score": 4,
"selected": false,
"text": "BEGIN TRANSACTION; \nUPDATE table_name\n SET column_name=REPLACE(column_name,'text_to_find','replace_with_this'); \nCOMMIT TRANSACTION;\n BEGIN TRANSACTION; UPDATE testdb\nSET title=REPLACE(title,'script','a'); COMMIT TRANSACTION;\n"
},
{
"answer_id": 9707239,
"author": "Brian Moeskau",
"author_id": 108348,
"author_profile": "https://Stackoverflow.com/users/108348",
"pm_score": 3,
"selected": false,
"text": "ntext nvarchar UPDATE YourTable\nSET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')\nWHERE Column1 LIKE '%a%'\n"
},
{
"answer_id": 31589027,
"author": "abc123",
"author_id": 1985032,
"author_profile": "https://Stackoverflow.com/users/1985032",
"pm_score": 2,
"selected": false,
"text": "'Search String' 'Replace String' --Getting all the databases and making a cursor\nDECLARE db_cursor CURSOR FOR \nSELECT name \nFROM master.dbo.sysdatabases \nWHERE name NOT IN ('master','model','msdb','tempdb') -- exclude these databases\n\nDECLARE @databaseName nvarchar(1000)\n--opening the cursor to move over the databases in this instance\nOPEN db_cursor\nFETCH NEXT FROM db_cursor INTO @databaseName \n\nWHILE @@FETCH_STATUS = 0 \nBEGIN\n PRINT @databaseName\n --Setting up temp table for the results of our search\n DECLARE @Results TABLE(TableName nvarchar(370), RealColumnName nvarchar(370), ColumnName nvarchar(370), ColumnValue nvarchar(3630))\n\n SET NOCOUNT ON\n\n DECLARE @SearchStr nvarchar(100), @ReplaceStr nvarchar(100), @SearchStr2 nvarchar(110)\n SET @SearchStr = 'Search String'\n SET @ReplaceStr = 'Replace String'\n SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')\n\n DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128)\n SET @TableName = ''\n\n --Looping over all the tables in the database\n WHILE @TableName IS NOT NULL\n BEGIN\n DECLARE @SQL nvarchar(2000)\n SET @ColumnName = ''\n DECLARE @result NVARCHAR(256)\n SET @SQL = 'USE ' + @databaseName + '\n SELECT @result = MIN(QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME))\n FROM [' + @databaseName + '].INFORMATION_SCHEMA.TABLES\n WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_CATALOG = ''' + @databaseName + '''\n AND QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) > ''' + @TableName + '''\n AND OBJECTPROPERTY(\n OBJECT_ID(\n QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME)\n ), ''IsMSShipped''\n ) = 0'\n EXEC master..sp_executesql @SQL, N'@result nvarchar(256) out', @result out\n\n SET @TableName = @result\n PRINT @TableName\n\n WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)\n BEGIN\n DECLARE @ColumnResult NVARCHAR(256)\n SET @SQL = '\n SELECT @ColumnResult = MIN(QUOTENAME(COLUMN_NAME))\n FROM [' + @databaseName + '].INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_SCHEMA = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 2)\n AND TABLE_NAME = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 1)\n AND DATA_TYPE IN (''char'', ''varchar'', ''nchar'', ''nvarchar'')\n AND TABLE_CATALOG = ''' + @databaseName + '''\n AND QUOTENAME(COLUMN_NAME) > ''' + @ColumnName + ''''\n PRINT @SQL\n EXEC master..sp_executesql @SQL, N'@ColumnResult nvarchar(256) out', @ColumnResult out\n SET @ColumnName = @ColumnResult \n\n PRINT @ColumnName\n\n IF @ColumnName IS NOT NULL\n BEGIN\n INSERT INTO @Results\n EXEC\n (\n 'USE ' + @databaseName + '\n SELECT ''' + @TableName + ''',''' + @ColumnName + ''',''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) \n FROM ' + @TableName + ' (NOLOCK) ' +\n ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2\n )\n END\n END\n END\n\n --Declaring another temporary table\n DECLARE @time_to_update TABLE(TableName nvarchar(370), RealColumnName nvarchar(370))\n\n INSERT INTO @time_to_update\n SELECT TableName, RealColumnName FROM @Results GROUP BY TableName, RealColumnName\n\n DECLARE @MyCursor CURSOR;\n BEGIN\n DECLARE @t nvarchar(370)\n DECLARE @c nvarchar(370)\n --Looping over the search results \n SET @MyCursor = CURSOR FOR\n SELECT TableName, RealColumnName FROM @time_to_update GROUP BY TableName, RealColumnName\n\n --Getting my variables from the first item\n OPEN @MyCursor \n FETCH NEXT FROM @MyCursor \n INTO @t, @c\n\n WHILE @@FETCH_STATUS = 0\n BEGIN\n -- Updating the old values with the new value\n DECLARE @sqlCommand varchar(1000)\n SET @sqlCommand = '\n USE ' + @databaseName + '\n UPDATE [' + @databaseName + '].' + @t + ' SET ' + @c + ' = REPLACE(' + @c + ', ''' + @SearchStr + ''', ''' + @ReplaceStr + ''') \n WHERE ' + @c + ' LIKE ''' + @SearchStr2 + ''''\n PRINT @sqlCommand\n BEGIN TRY\n EXEC (@sqlCommand)\n END TRY\n BEGIN CATCH\n PRINT ERROR_MESSAGE()\n END CATCH\n\n --Getting next row values\n FETCH NEXT FROM @MyCursor \n INTO @t, @c \n END;\n\n CLOSE @MyCursor ;\n DEALLOCATE @MyCursor;\n END;\n\n DELETE FROM @time_to_update\n DELETE FROM @Results\n\n FETCH NEXT FROM db_cursor INTO @databaseName\nEND \n\nCLOSE db_cursor \nDEALLOCATE db_cursor\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
] |
59,075 |
<p>How do I save each sheet in an Excel workbook to separate <code>CSV</code> files with a macro?</p>
<p>I have an excel with multiple sheets and I was looking for a macro that will save each sheet to a separate <code>CSV (comma separated file)</code>. Excel will not allow you to save all sheets to different <code>CSV</code> files.</p>
|
[
{
"answer_id": 59078,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 4,
"selected": false,
"text": "Private Sub SaveAllSheetsAsCSV()\nOn Error GoTo Heaven\n\n' each sheet reference\nDim Sheet As Worksheet\n' path to output to\nDim OutputPath As String\n' name of each csv\nDim OutputFile As String\n\nApplication.ScreenUpdating = False\nApplication.DisplayAlerts = False\nApplication.EnableEvents = False\n\n' ask the user where to save\nOutputPath = InputBox(\"Enter a directory to save to\", \"Save to directory\", Path)\n\nIf OutputPath <> \"\" Then\n\n ' save for each sheet\n For Each Sheet In Sheets\n\n OutputFile = OutputPath & \"\\\" & Sheet.Name & \".csv\"\n\n ' make a copy to create a new book with this sheet\n ' otherwise you will always only get the first sheet\n Sheet.Copy\n ' this copy will now become active\n ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False\n ActiveWorkbook.Close\n Next\n\nEnd If\n\nFinally:\nApplication.ScreenUpdating = True\nApplication.DisplayAlerts = True\nApplication.EnableEvents = True\n\nExit Sub\n\nHeaven:\nMsgBox \"Couldn't save all sheets to CSV.\" & vbCrLf & _\n \"Source: \" & Err.Source & \" \" & vbCrLf & _\n \"Number: \" & Err.Number & \" \" & vbCrLf & _\n \"Description: \" & Err.Description & \" \" & vbCrLf\n\nGoTo Finally\nEnd Sub\n"
},
{
"answer_id": 59114,
"author": "HigherAbstraction",
"author_id": 5945,
"author_profile": "https://Stackoverflow.com/users/5945",
"pm_score": 7,
"selected": true,
"text": "' ---------------------- Directory Choosing Helper Functions -----------------------\n' Excel and VBA do not provide any convenient directory chooser or file chooser\n' dialogs, but these functions will provide a reference to a system DLL\n' with the necessary capabilities\nPrivate Type BROWSEINFO ' used by the function GetFolderName\n hOwner As Long\n pidlRoot As Long\n pszDisplayName As String\n lpszTitle As String\n ulFlags As Long\n lpfn As Long\n lParam As Long\n iImage As Long\nEnd Type\n\nPrivate Declare Function SHGetPathFromIDList Lib \"shell32.dll\" _\n Alias \"SHGetPathFromIDListA\" (ByVal pidl As Long, ByVal pszPath As String) As Long\nPrivate Declare Function SHBrowseForFolder Lib \"shell32.dll\" _\n Alias \"SHBrowseForFolderA\" (lpBrowseInfo As BROWSEINFO) As Long\n\nFunction GetFolderName(Msg As String) As String\n ' returns the name of the folder selected by the user\n Dim bInfo As BROWSEINFO, path As String, r As Long\n Dim X As Long, pos As Integer\n bInfo.pidlRoot = 0& ' Root folder = Desktop\n If IsMissing(Msg) Then\n bInfo.lpszTitle = \"Select a folder.\"\n ' the dialog title\n Else\n bInfo.lpszTitle = Msg ' the dialog title\n End If\n bInfo.ulFlags = &H1 ' Type of directory to return\n X = SHBrowseForFolder(bInfo) ' display the dialog\n ' Parse the result\n path = Space$(512)\n r = SHGetPathFromIDList(ByVal X, ByVal path)\n If r Then\n pos = InStr(path, Chr$(0))\n GetFolderName = Left(path, pos - 1)\n Else\n GetFolderName = \"\"\n End If\nEnd Function\n'---------------------- END Directory Chooser Helper Functions ----------------------\n\nPublic Sub DoTheExport()\n Dim FName As Variant\n Dim Sep As String\n Dim wsSheet As Worksheet\n Dim nFileNum As Integer\n Dim csvPath As String\n\n\n Sep = InputBox(\"Enter a single delimiter character (e.g., comma or semi-colon)\", _\n \"Export To Text File\")\n 'csvPath = InputBox(\"Enter the full path to export CSV files to: \")\n\n csvPath = GetFolderName(\"Choose the folder to export CSV files to:\")\n If csvPath = \"\" Then\n MsgBox (\"You didn't choose an export directory. Nothing will be exported.\")\n Exit Sub\n End If\n\n For Each wsSheet In Worksheets\n wsSheet.Activate\n nFileNum = FreeFile\n Open csvPath & \"\\\" & _\n wsSheet.Name & \".csv\" For Output As #nFileNum\n ExportToTextFile CStr(nFileNum), Sep, False\n Close nFileNum\n Next wsSheet\n\nEnd Sub\n\n\n\nPublic Sub ExportToTextFile(nFileNum As Integer, _\n Sep As String, SelectionOnly As Boolean)\n\n Dim WholeLine As String\n Dim RowNdx As Long\n Dim ColNdx As Integer\n Dim StartRow As Long\n Dim EndRow As Long\n Dim StartCol As Integer\n Dim EndCol As Integer\n Dim CellValue As String\n\n Application.ScreenUpdating = False\n On Error GoTo EndMacro:\n\n If SelectionOnly = True Then\n With Selection\n StartRow = .Cells(1).Row\n StartCol = .Cells(1).Column\n EndRow = .Cells(.Cells.Count).Row\n EndCol = .Cells(.Cells.Count).Column\n End With\n Else\n With ActiveSheet.UsedRange\n StartRow = .Cells(1).Row\n StartCol = .Cells(1).Column\n EndRow = .Cells(.Cells.Count).Row\n EndCol = .Cells(.Cells.Count).Column\n End With\n End If\n\n For RowNdx = StartRow To EndRow\n WholeLine = \"\"\n For ColNdx = StartCol To EndCol\n If Cells(RowNdx, ColNdx).Value = \"\" Then\n CellValue = \"\"\n Else\n CellValue = Cells(RowNdx, ColNdx).Value\n End If\n WholeLine = WholeLine & CellValue & Sep\n Next ColNdx\n WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))\n Print #nFileNum, WholeLine\n Next RowNdx\n\nEndMacro:\n On Error GoTo 0\n Application.ScreenUpdating = True\n\nEnd Sub\n"
},
{
"answer_id": 59906,
"author": "Graham",
"author_id": 1826,
"author_profile": "https://Stackoverflow.com/users/1826",
"pm_score": 7,
"selected": false,
"text": "Public Sub SaveWorksheetsAsCsv()\nDim WS As Excel.Worksheet\nDim SaveToDirectory As String\n\n SaveToDirectory = \"C:\\\"\n\n For Each WS In ThisWorkbook.Worksheets\n WS.SaveAs SaveToDirectory & WS.Name, xlCSV\n Next\n\nEnd Sub\n"
},
{
"answer_id": 62301,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 4,
"selected": false,
"text": "Public Sub SaveWorksheetsAsCsv()\n\nDim WS As Excel.Worksheet\nDim SaveToDirectory As String\n\nDim CurrentWorkbook As String\nDim CurrentFormat As Long\n\n CurrentWorkbook = ThisWorkbook.FullName\n CurrentFormat = ThisWorkbook.FileFormat\n' Store current details for the workbook\n\n SaveToDirectory = \"C:\\\"\n\n For Each WS In ThisWorkbook.Worksheets\n WS.SaveAs SaveToDirectory & WS.Name, xlCSV\n Next\n\n Application.DisplayAlerts = False\n ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat\n Application.DisplayAlerts = True\n' Temporarily turn alerts off to prevent the user being prompted\n' about overwriting the original file.\n\nEnd Sub\n"
},
{
"answer_id": 845345,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Public Sub SaveAllSheetsAsCSV()\nOn Error GoTo Heaven\n\n' each sheet reference\nDim Sheet As Worksheet\n' path to output to\nDim OutputPath As String\n' name of each csv\nDim OutputFile As String\n\nApplication.ScreenUpdating = False\nApplication.DisplayAlerts = False\nApplication.EnableEvents = False\n\n' Save the file in current director\nOutputPath = ThisWorkbook.Path\n\n\nIf OutputPath <> \"\" Then\nApplication.Calculation = xlCalculationManual\n\n' save for each sheet\nFor Each Sheet In Sheets\n\n OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & \".csv\"\n\n ' make a copy to create a new book with this sheet\n ' otherwise you will always only get the first sheet\n\n Sheet.Copy\n ' this copy will now become active\n ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False\n ActiveWorkbook.Close\nNext\n\nApplication.Calculation = xlCalculationAutomatic\n\nEnd If\n\nFinally:\nApplication.ScreenUpdating = True\nApplication.DisplayAlerts = True\nApplication.EnableEvents = True\n\nExit Sub\n\nHeaven:\nMsgBox \"Couldn't save all sheets to CSV.\" & vbCrLf & _\n \"Source: \" & Err.Source & \" \" & vbCrLf & _\n \"Number: \" & Err.Number & \" \" & vbCrLf & _\n \"Description: \" & Err.Description & \" \" & vbCrLf\n\nGoTo Finally\nEnd Sub\n"
},
{
"answer_id": 27858854,
"author": "Luigi",
"author_id": 2766120,
"author_profile": "https://Stackoverflow.com/users/2766120",
"pm_score": 1,
"selected": false,
"text": " Sub asdf()\nDim ws As Worksheet, newWb As Workbook\n\nApplication.ScreenUpdating = False\nFor Each ws In Sheets(Array(\"EID Upload\", \"Wages with Locals Upload\", \"Wages without Local Upload\"))\n ws.Copy\n Set newWb = ActiveWorkbook\n With newWb\n .SaveAs ws.Name, xlCSV\n .Close (False)\n End With\nNext ws\nApplication.ScreenUpdating = True\n\nEnd Sub\n"
},
{
"answer_id": 61893912,
"author": "Żabojad",
"author_id": 1255091,
"author_profile": "https://Stackoverflow.com/users/1255091",
"pm_score": 2,
"selected": false,
"text": "Public Sub SaveWorksheetsAsCsv()\n\n Dim WS As Excel.Worksheet\n Dim SaveToDirectory As String\n\n SaveToDirectory = \"~/Library/Containers/com.microsoft.Excel/Data/\"\n\n For Each WS In ThisWorkbook.Worksheet\n WS.SaveAs SaveToDirectory & WS.Name & \".csv\", xlCSV\n Next\n\nEnd Sub\n\n"
},
{
"answer_id": 66285889,
"author": "Joshua Pinter",
"author_id": 293280,
"author_profile": "https://Stackoverflow.com/users/293280",
"pm_score": 2,
"selected": false,
"text": ".csv .xlsx Insert Module Public Sub SaveWorksheetsAsCsv()\n\n Dim WS As Excel.Worksheet\n Dim SaveToDirectory As String\n\n SaveToDirectory = \"./\"\n\n For Each WS In ThisWorkbook.Worksheets\n WS.SaveAs SaveToDirectory & WS.Name & \".csv\", xlCSV\n Next\n\nEnd Sub\n .csv ~/Library/Containers/com.microsoft.Excel/Data open ~/Library/Containers/com.microsoft.Excel/Data\n .xlsx .xlsx"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5790/"
] |
59,083 |
<h2>Question</h2>
<p>Alright, I'm confused by all the buzzwords and press release bingo going on.</p>
<ul>
<li>What is the relationship between flash and flex:
<ul>
<li>Replace flash (not really compatible)</li>
<li>Enhance flash</li>
<li>The next version of flash but still basically compatible</li>
<li>Separate technology altogether</li>
<li>???</li>
</ul></li>
<li>If I'm starting out in Flash now, should I just skip to Flex?</li>
</ul>
<h2>Follow up</h2>
<p>Ok, so what I'm hearing is that there's three different parts to the puzzle:</p>
<ul>
<li><strong>Flash</strong>
<ul>
<li>The graphical editor used to make "Flash Movies", ie it's an IDE that focuses on the visual aspect of "Flash" (Officially Flash CS3?)</li>
<li>The official name for the display plugins (ie, "Download Flash Now!")</li>
<li>A general reference to the entire technology stack</li>
<li>In terms of the editor, it's a linear timeline based editor, best used for animations with complex interactivity.</li>
</ul></li>
<li><strong>Actionscript</strong>
<ul>
<li>The "Flash" programming language</li>
</ul></li>
<li><strong>Flex</strong>
<ul>
<li>An Adobe Flash IDE that focuses on the coding/programming aspect of "Flash" (Flex Builder?)</li>
<li>A Flash library that enhances Flash and makes it easier to <em>program</em> for (Flex SDK?)</li>
<li>Is not bound to a timeline (as the Flash IDE is) and so "standard" applications are more easily accomplished.</li>
</ul></li>
</ul>
<p>Is this correct?</p>
<p>-Adam</p>
|
[
{
"answer_id": 2276350,
"author": "JD Isaacks",
"author_id": 46011,
"author_profile": "https://Stackoverflow.com/users/46011",
"pm_score": 2,
"selected": false,
"text": ".net"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] |
59,098 |
<p>We have some Win32 console applications running on Windows Server 2003 Service Pack 2 that regularly fail with this:</p>
<blockquote>
<p>Error 1450 (<code>ERROR_NO_SYSTEM_RESOURCES</code>): "Insufficient system resources exist to complete the requested service."</p>
</blockquote>
<p>All the documentation we've found suggests it is linked to the number of <strong>Free System Page Table Entries</strong> running out. We have 16GB RAM in these machines and use the <code>/3GB</code> Operating System switch to squeeze the Windows kernel into 1GB and allow our processes access to 3GB of address space. This drastically reduces the total number of Free System Page Table Entries, so combined with our heavy use of MapViewOfFile() it is perhaps not surprising that the kernel page table entries are running out.</p>
<p>However, when using Performance Monitor to view the Free System Page Table Entries counter, the value is around 36,000 on reboot and <strong>doesn't go down when our application starts</strong>. I find it hard to believe that our application, which opens many large memory-mapped files, doesn't have any effect on the kernel page table. If we can't believe the counter, it's much more difficult to test the effect of any system changes we make.</p>
<p>There is a promising Knowledge Base article, <a href="http://support.microsoft.com/kb/894067" rel="nofollow noreferrer">The Performance tool does not accurately show the available Free System Page Table entries in Windows Server 2003</a>, but it says the problem has been fixed in Service Pack 1, and we are already on Service Pack 2.</p>
<p>Has anyone else struggled with or solved this issue?</p>
<p><strong>Update:</strong> I have checked !sysptes in windbg (debugging the kernel) and the value matches the performance counter, around 36,000. I guess this is most likely to mean that there really are that many free page table entries and Windows <em>is</em> telling the truth. It does leave the question of why we're getting 1450 errors though, if the PTEs are not running out.</p>
<p><strong>Further update:</strong> We never did get to the bottom of why the 1450 errors were occurring. <em>However</em>, instead we upgraded the OS on these servers to 64-bit Windows. This allows the existing 32-bit applications (without recompilation) to access a full 4GB of virtual address space, and lets the kernel memory area with those pesky Page Table Entries be as big as it likes too. I don't think we've had a 1450 error since.</p>
|
[
{
"answer_id": 139529,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "ERROR_NO_SYSTEM_RESOURCES"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5536/"
] |
59,099 |
<p>Visually both of the following snippets produce the same UI. So why are there 2 controls..<br>
<strong>Snippet1</strong> </p>
<pre><code><TextBlock>Name:</TextBlock>
<TextBox Name="nameTextBox" />
</code></pre>
<p><strong>Snippet2</strong></p>
<pre><code><Label>Name:</Label>
<TextBox Name="nameTextBox" />
</code></pre>
<p>(<em>Well I am gonna answer this myself... thought this is a useful tidbit I learnt today from <a href="https://rads.stackoverflow.com/amzn/click/com/0596510373" rel="noreferrer" rel="nofollow noreferrer">Programming WPF</a></em>) </p>
|
[
{
"answer_id": 59104,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": false,
"text": "<Label Target=\"{Binding ElementName=nameTextBox}\">_Name:</Label>\n<TextBox x:Name=\"nameTextBox\" />\n"
},
{
"answer_id": 4058717,
"author": "Nam G VU",
"author_id": 248616,
"author_profile": "https://Stackoverflow.com/users/248616",
"pm_score": 2,
"selected": false,
"text": "TextBlock TextWrapping Label <AccessKey> TextBlock TextBlock BorderBrush"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
] |
59,102 |
<p>Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter?</p>
<p>Example 1 - separate parameters:
function convertTemperature("celsius", "fahrenheit", 22)</p>
<p>Example 2 - combined parameter:
function convertTemperature("c-f", 22)</p>
<p>The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow.</p>
<p>Thoughts?</p>
|
[
{
"answer_id": 59108,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 5,
"selected": true,
"text": "convertTemperature (TempScale.CELSIUS, TempScale.FAHRENHEIT, 22)\n"
},
{
"answer_id": 59117,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 1,
"selected": false,
"text": "enum Conversion\n{\n CelsiusToFahrenheit,\n FahrenheitToCelsius,\n KilosToPounds\n}\n\nConvert(Conversion conversion, X from);\n enum Units\n{\n Pounds,\n Kilos,\n Celcius,\n Farenheight\n}\n\nConvert(Unit from, Unit to, X fromAmount);\n Convert(Pounds, Celcius, 5, 10);\n"
},
{
"answer_id": 59118,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 1,
"selected": false,
"text": "\npublic void ConvertTemperature(TemperatureTypeEnum SourceTemp,\n TemperatureTypeEnum TargetTemp, \n decimal Temperature)\n{}\n"
},
{
"answer_id": 59176,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "interface ITemperature\n{\n CelciusTemperature ToCelcius();\n FarenheitTemperature ToFarenheit();\n}\n\nstruct FarenheitTemperature : ITemperature\n{\n public readonly int Value;\n public FarenheitTemperature(int value)\n {\n this.Value = value;\n }\n\n public FarenheitTemperature ToFarenheit() { return this; }\n public CelciusTemperature ToCelcius()\n {\n return new CelciusTemperature((this.Value - 32) * 5 / 9);\n }\n\n}\n\nstruct CelciusTemperature\n{\n public readonly int Value;\n public CelciusTemperature(int value)\n {\n this.Value = value;\n }\n\n public CelciusTemperature ToCelcius() { return this; }\n public FarenheitTemperature ToFarenheit()\n {\n return new FarenheitTemperature(this.Value * 9 / 5 + 32);\n }\n}\n // Freezing\n Debug.Assert(new FarenheitTemperature(32).ToCelcius().Equals(new CelciusTemperature(0)));\n Debug.Assert(new CelciusTemperature(0).ToFarenheit().Equals(new FarenheitTemperature(32)));\n\n // crossover\n Debug.Assert(new FarenheitTemperature(-40).ToCelcius().Equals(new CelciusTemperature(-40)));\n Debug.Assert(new CelciusTemperature(-40).ToFarenheit().Equals(new FarenheitTemperature(-40)));\n CelciusTemperature theOutbackInAMidnightOilSong = new CelciusTemperature(45);\n FarenheitTemperature x = theOutbackInAMidnightOilSong; // ERROR: Cannot implicitly convert type 'CelciusTemperature' to 'FarenheitTemperature'\n"
},
{
"answer_id": 59219,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 1,
"selected": false,
"text": "float LinearConvert(float in, float scale, float add, bool invert);\n"
},
{
"answer_id": 59275,
"author": "Joel Gauvreau",
"author_id": 4789,
"author_profile": "https://Stackoverflow.com/users/4789",
"pm_score": 1,
"selected": false,
"text": "public class Temperature\n{\n private double celcius;\n\n public static Temperature FromFarenheit(double farenheit)\n {\n return new Temperature { Farhenheit = farenheit };\n }\n\n public static Temperature FromCelcius(double celcius)\n {\n return new Temperature { Celcius = celcius };\n }\n\n public static Temperature FromKelvin(double kelvin)\n {\n return new Temperature { Kelvin = kelvin };\n }\n\n private double kelvinToCelcius(double kelvin)\n {\n return 1; // insert formula here\n }\n\n private double celciusToKelvin(double celcius)\n {\n return 1; // insert formula here\n }\n\n private double farhenheitToCelcius(double farhenheit)\n {\n return 1; // insert formula here\n }\n\n private double celciusToFarenheit(double kelvin)\n {\n return 1; // insert formula here\n }\n\n public double Kelvin\n {\n get { return celciusToKelvin(celcius); }\n set { celcius = kelvinToCelcius(value); }\n }\n\n public double Celcius\n {\n get { return celcius; }\n set { celcius = value; }\n }\n\n public double Farhenheit\n {\n get { return celciusToFarenheit(celcius); }\n set { celcius = farhenheitToCelcius(value); }\n }\n}\n"
},
{
"answer_id": 59536,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "$ units 'tempF(-40)' tempC\n -40\n use Convert::Temperature;\n\nmy $c = new Convert::Temperature();\n\nmy $res = $c->from_fahr_to_cel('59');\n double fahrtocel(double tempF){\n return ((tempF-32)*(5/9));\n}\n\ndouble celtofahr(double tempC){\n return ((9/5)*tempC + 32);\n}\n"
},
{
"answer_id": 4451615,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 1,
"selected": false,
"text": "function Temperature($value, $input, $output)\n{\n $value = floatval($value);\n\n if (isset($input, $output) === true)\n {\n switch ($input)\n {\n case 'K': $value = $value - 273.15; break; // Kelvin\n case 'F': $value = ($value - 32) * (5 / 9); break; // Fahrenheit\n case 'R': $value = ($value - 491.67) * (5 / 9); break; // Rankine\n }\n\n switch ($output)\n {\n case 'K': $value = $value + 273.15; break; // Kelvin\n case 'F': $value = $value * (9 / 5) + 32; break; // Fahrenheit\n case 'R': $value = ($value + 273.15) * (9 / 5); break; // Rankine\n }\n }\n\n return $value;\n}\n $input $output"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6126/"
] |
59,105 |
<p>Almost 5 years ago Joel Spolsky wrote this article, <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">"The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"</a>.</p>
<p>Like many, I read it carefully, realizing it was high-time I got to grips with this "replacement for ASCII". Unfortunately, 5 years later I feel I have slipped back into a few bad habits in this area. Have you?</p>
<p>I don't write many specifically international applications, however I have helped build many ASP.NET internet facing websites, so I guess that's not an excuse. </p>
<p>So for my benefit (and I believe many others) can I get some input from people on the following:</p>
<ul>
<li>How to "get over" ASCII once and for all</li>
<li>Fundamental guidance when working with Unicode.</li>
<li>Recommended (recent) books and websites on Unicode (for developers). </li>
<li>Current state of Unicode (5 years after Joels' article) </li>
<li>Future directions.</li>
</ul>
<p>I must admit I have a .NET background and so would also be happy for information on Unicode in the .NET framework. Of course this shouldn't stop anyone with a differing background from commenting though.</p>
<p>Update: See <a href="https://stackoverflow.com/questions/898/internationalization-in-your-projects">this related question</a> also asked on StackOverflow previously.</p>
|
[
{
"answer_id": 59225,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 2,
"selected": false,
"text": "StreamReader StreamWriter StringWriter Encoding.ASCII.GetBytes()"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023/"
] |
59,107 |
<p>I'm converting an application to use Java 1.5 and have found the following method:</p>
<pre><code> /**
* Compare two Comparables, treat nulls as -infinity.
* @param o1
* @param o2
* @return -1 if o1&lt;o2, 0 if o1==o2, 1 if o1&gt;o2
*/
protected static int nullCompare(Comparable o1, Comparable o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
} else {
return -1;
}
} else if (o2 == null) {
return 1;
} else {
return o1.compareTo(o2);
}
}
</code></pre>
<p>Ideally I would like to make the method take two Comparables of the same type, is it possible to convert this and how? </p>
<p>I thought the following would do the trick:</p>
<pre><code>protected static <T extends Comparable> int nullCompare(T o1, T o2) {
</code></pre>
<p>but it has failed to get rid of a warning in IntelliJ "Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'" on the line:</p>
<pre><code>return o1.compareTo(o2);
</code></pre>
|
[
{
"answer_id": 59119,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 5,
"selected": true,
"text": "protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) {\n"
},
{
"answer_id": 85739,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 3,
"selected": false,
"text": "static class A {\n ...\n}\n\nstatic class B extends A implements Comparable<A> {\n public int compareTo(A o) {\n return ...;\n }\n}\n protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) {\n"
},
{
"answer_id": 227885,
"author": "mjlee",
"author_id": 2829,
"author_profile": "https://Stackoverflow.com/users/2829",
"pm_score": 2,
"selected": false,
"text": "protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) {\n public static <T extends Comparable<? super T>> void sort(List<T> list) {\n"
},
{
"answer_id": 815484,
"author": "newacct",
"author_id": 86989,
"author_profile": "https://Stackoverflow.com/users/86989",
"pm_score": 0,
"selected": false,
"text": " /**\n * Compare two Comparables, treat nulls as -infinity.\n * @param o1\n * @param o2\n * @return -1 if o1<o2, 0 if o1==o2, 1 if o1>o2\n */\n protected static <T> int nullCompare(Comparable<? super T> o1, T o2) {\n if (o1 == null) {\n if (o2 == null) {\n return 0;\n } else {\n return -1;\n }\n } else if (o2 == null) {\n return 1;\n } else {\n return o1.compareTo(o2);\n }\n }\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4389/"
] |
59,120 |
<p>I am getting this error now that I hit version number 1.256.0:
Error 4 Invalid product version '1.256.0'. Must be of format '##.##.####'</p>
<p>The installer was fine with 1.255.0 but something with 256 (2^8) it doesn't like. I found this stated on msdn.com:
The Version property must be formatted as N.N.N, where each N represents at least one and no more than four digits. (<a href="http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx</a>)</p>
<p>Which would make me believe there is nothing wrong 1.256.0 because it meets the rules stated above.</p>
<p>Does anyone have any ideas on why this would be failing now?</p>
|
[
{
"answer_id": 59119,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 5,
"selected": true,
"text": "protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) {\n"
},
{
"answer_id": 85739,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 3,
"selected": false,
"text": "static class A {\n ...\n}\n\nstatic class B extends A implements Comparable<A> {\n public int compareTo(A o) {\n return ...;\n }\n}\n protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) {\n"
},
{
"answer_id": 227885,
"author": "mjlee",
"author_id": 2829,
"author_profile": "https://Stackoverflow.com/users/2829",
"pm_score": 2,
"selected": false,
"text": "protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) {\n public static <T extends Comparable<? super T>> void sort(List<T> list) {\n"
},
{
"answer_id": 815484,
"author": "newacct",
"author_id": 86989,
"author_profile": "https://Stackoverflow.com/users/86989",
"pm_score": 0,
"selected": false,
"text": " /**\n * Compare two Comparables, treat nulls as -infinity.\n * @param o1\n * @param o2\n * @return -1 if o1<o2, 0 if o1==o2, 1 if o1>o2\n */\n protected static <T> int nullCompare(Comparable<? super T> o1, T o2) {\n if (o1 == null) {\n if (o2 == null) {\n return 0;\n } else {\n return -1;\n }\n } else if (o2 == null) {\n return 1;\n } else {\n return o1.compareTo(o2);\n }\n }\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5967/"
] |
59,128 |
<p>What GUI should use to run my JUnit tests, and how exactly do I do that? My entire background is in .NET, so I'm used to just firing up my NUnit gui and running my unit tests. If the lights are green, I'm clean. </p>
<p>Now, I have to write some Java code and want to run something similar using JUnit. The JUnit documentation is nice and clear about adding the attributes necessary to create tests, but its pretty lean on how to fire up a runner and see the results of those tests.</p>
|
[
{
"answer_id": 11132066,
"author": "antonv",
"author_id": 472020,
"author_profile": "https://Stackoverflow.com/users/472020",
"pm_score": 1,
"selected": false,
"text": "junit.textui.TestRunner %your_class% junit.swingui.TestRunner [%your_class%]"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
59,154 |
<p>When I press F5 in Visual Studio 2008, I want Google Chrome launched as the browser that my ASP.NET app runs in. May I know how this can be done?</p>
|
[
{
"answer_id": 44865188,
"author": "Soenhay",
"author_id": 1339704,
"author_profile": "https://Stackoverflow.com/users/1339704",
"pm_score": 2,
"selected": false,
"text": "C:\\Users\\[UserName]\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe\n"
},
{
"answer_id": 72770808,
"author": "Swapnil Sourabh",
"author_id": 8070068,
"author_profile": "https://Stackoverflow.com/users/8070068",
"pm_score": 1,
"selected": false,
"text": "Browse With Set as default"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
59,166 |
<p>So I have an object which has some fields, doesn't really matter what.
I have a generic list of these objects.</p>
<pre><code>List<MyObject> myObjects = new List<MyObject>();
myObjects.Add(myObject1);
myObjects.Add(myObject2);
myObjects.Add(myObject3);
</code></pre>
<p>So I want to remove objects from my list based on some criteria.
For instance, <code>myObject.X >= 10.</code>
I would like to use the <code>RemoveAll(Predicate<T> match)</code> method for to do this.</p>
<p>I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.</p>
|
[
{
"answer_id": 59172,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 7,
"selected": true,
"text": "myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; });\n myObjects.RemoveAll(m => m.X >= 10);\n"
},
{
"answer_id": 59174,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": false,
"text": "myObjects.RemoveAll(m => m.x >= 10);\n myObjects.RemoveAll(delegate (MyObject m) {\n return m.x >= 10;\n});\n myObjects.RemoveAll(Function(m) m.x >= 10)\n"
},
{
"answer_id": 59177,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": " //C# 2.0\n RemoveAll(delegate(Foo o){ return o.X >= 10; });\n //C# 3.0\n RemoveAll(o => o.X >= 10);\n Predicate<Foo> matches = delegate(Foo o){ return o.X >= 10; });\n //or Predicate<Foo> matches = o => o.X >= 10;\n RemoveAll(matches);\n"
},
{
"answer_id": 47375389,
"author": "Nayas Subramanian",
"author_id": 4315441,
"author_profile": "https://Stackoverflow.com/users/4315441",
"pm_score": 1,
"selected": false,
"text": "RemoveAll(p=> p.x > 2);\n RemoveAll(delegate(myObject obj){\n\n return obj.x >=10;\n})\n Predicate<myObject> matches = new Predicate<myObject>(IsEmployeeIsValid);\nRemoveAll(matches);\n\nPredicate<Foo> matches = delegate(Foo o){ return o.X >= 20; });\nRemoveAll(matches);\n public delegate bool IsInValidEmployee (Employee emp);\n\nIsInValidEmployee invalidEmployeeDelegate = new IsInValidEmployee(IsEmployeeInValid);\nmyObjects.RemoveAll(myObject=>invalidEmployeeDelegate(myObject);\n public static bool IsEmployeeInValid(Employee emp)\n{\n if (emp.Id > 0 )\n return true;\n else\n return false;\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/454247/"
] |
59,181 |
<p>I have a WCF service that gets called from client side JavaScript. The call fails with a Service is null JavaScript error. WebDevelopment helper trace shows that the calls to load the jsdebug support file results in a 404 (file not found) error. </p>
<p>Restarting IIS or clearing out the Temp ASP.Net files or setting batch="false" on the compilation tag in web.config does not resolve the problem</p>
<p>From the browser </p>
<p><a href="https://Myserver/MyApp/Services/MyService.svc" rel="nofollow noreferrer">https://Myserver/MyApp/Services/MyService.svc</a> displays the service metadata</p>
<p>however </p>
<p><a href="https://Myserver/MyApp/Services/MyService.svc/jsdebug" rel="nofollow noreferrer">https://Myserver/MyApp/Services/MyService.svc/jsdebug</a> results in a 404.</p>
<p>The issue seems to be with the https protocol. With http /jsdebug downloads the supporting JS file.</p>
<p>Any ideas?</p>
<p>TIA</p>
|
[
{
"answer_id": 59764,
"author": "rams",
"author_id": 3635,
"author_profile": "https://Stackoverflow.com/users/3635",
"pm_score": 5,
"selected": true,
"text": "<services>\n <service name=\"MyService\">\n <endpoint address=\"\" behaviorConfiguration=\"MyServiceAspNetAjaxBehavior\" binding=\"webHttpBinding\" bindingConfiguration=\"webBinding\" contract=\"Services.MyService\" />\n </service>\n </services>\n <bindings>\n <webHttpBinding>\n <binding name=\"webBinding\">\n <security mode=\"Transport\">\n </security>\n </binding>\n </webHttpBinding>\n </bindings>\n"
},
{
"answer_id": 30665983,
"author": "garryp",
"author_id": 3395015,
"author_profile": "https://Stackoverflow.com/users/3395015",
"pm_score": 0,
"selected": false,
"text": "routes.IgnoreRoute(\"WCF/{*pathInfo}\");\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3635/"
] |
59,182 |
<p>What is the best way to keep an asp:button from displaying it's URL on the status bar of the browser? The button is currently defines like this:</p>
<pre><code><asp:button id="btnFind"
runat="server"
Text="Find Info"
onclick="btnFind_Click">
</asp:button>
</code></pre>
<p><strong>Update:</strong></p>
<p>This appears to be specific to IE7, IE6 and FF do not show the URL in the status bar.</p>
|
[
{
"answer_id": 59234,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "javascript:__doPostBack('btn','');\n btnFind.Attributes.Add(\"onmouseover\",\"window.status = '';\");\nbtnFind.Attributes.Add(\"onmouseout\",\"window.status = '';\");\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/206/"
] |
59,191 |
<p>I'm using a deploy project to deploy my ASP.net web application.
When I build the deploy project, all the .compiled files are re-created.</p>
<p>Do I need to FTP them to the production web server?<br>
If I do a small change do I need to copy all the web site again?</p>
|
[
{
"answer_id": 2142674,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 0,
"selected": false,
"text": ".compiled -r"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] |
59,213 |
<p>What's the easiest way to add a header and footer to a .Net PrintDocument object, either pragmatically or at design-time?</p>
<p>Specifically I'm trying to print a 3rd party grid control (Infragistics GridEx v4.3), which takes a PrintDocument object and draws itself into it.</p>
<p>The resulting page just contains the grid and it's contents - however I would like to add a header or title to identify the printed report, and possibly a footer to show who printed it, when, and ideally a page number and total pages.</p>
<p>I'm using VB.Net 2.0.</p>
<p>Thanks for your help!</p>
|
[
{
"answer_id": 224934,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 3,
"selected": false,
"text": "Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click\n\n Dim oDoc As New Printing.PrintDocument\n oDoc.DefaultPageSettings.Landscape = True\n AddHandler oDoc.PrintPage, AddressOf PrintPage\n\n oDoc.DocumentName = \"Printout\"\n\n InfragisticsWinGrid.PrintPreview(InfragisticsWinGrid.DisplayLayout, oDoc)\n\n End If\nEnd Sub\n\n\nPrivate Sub PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)\n\n ' Draw title\n e.Graphics.DrawString(\"Report Title\"), New Font(\"Arial\", 16), Brushes.Black, 95, 70)\n\n ' Draw footer\n e.Graphics.DrawImage(DirectCast(mResources.GetObject(\"footer_logo\"), Drawing.Bitmap), 95, e.PageBounds.Height - 87)\n Dim drawFont As New Font(\"Arial\", 8.75)\n\n e.Graphics.DrawString(\"Report Title\", drawFont, Brushes.Gray, 190, e.PageBounds.Height - 90)\n e.Graphics.DrawString(\"Printed\", drawFont, Brushes.Gray, 190, e.PageBounds.Height - 76)\n e.Graphics.DrawString(\"Printed By\", drawFont, Brushes.Gray, 190, e.PageBounds.Height - 62)\n\n ' Draw some grid lines to add structure to the footer information\n e.Graphics.DrawLine(Pens.Gray, 246, e.PageBounds.Height - 90, 246, e.PageBounds.Height - 48)\n e.Graphics.DrawLine(Pens.Gray, 188, e.PageBounds.Height - 75, 550, e.PageBounds.Height - 75)\n e.Graphics.DrawLine(Pens.Gray, 188, e.PageBounds.Height - 61, 550, e.PageBounds.Height - 61)\n\n e.Graphics.DrawString(\"Report\", drawFont, Brushes.Black, 250, e.PageBounds.Height - 90)\n e.Graphics.DrawString(Date.Now.ToShortDateString & \" \" & Date.Now.ToShortTimeString, drawFont, Brushes.Black, 250, e.PageBounds.Height - 76)\n e.Graphics.DrawString(\"Andrew\", drawFont, Brushes.Black, 250, e.PageBounds.Height - 62)\n\nEnd Sub\n e.PageBounds.Height - x"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
] |
59,217 |
<p>Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array?</p>
<p>The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format.</p>
<p>I'm looking to avoid writing my own function to accomplish this if possible.</p>
|
[
{
"answer_id": 59233,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "Array.Copy() List<T> .AddRange()"
},
{
"answer_id": 59246,
"author": "apandit",
"author_id": 6128,
"author_profile": "https://Stackoverflow.com/users/6128",
"pm_score": 0,
"selected": false,
"text": "public string[] merge(input1, input2)\n{\n string[] output = new string[input1.length + input2.length];\n for(int i = 0; i < output.length; i++)\n {\n if (i >= input1.length)\n output[i] = input2[i-input1.length];\n else\n output[i] = input1[i];\n }\n return output;\n}\n public ArrayList merge(input1, input2)\n{\n Arraylist output = new ArrayList();\n foreach(string val in input1)\n output.add(val);\n foreach(string val in input2)\n output.add(val);\n return output;\n}\n"
},
{
"answer_id": 59250,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 8,
"selected": true,
"text": "T[] array1 = getOneArray();\nT[] array2 = getAnotherArray();\nint array1OriginalLength = array1.Length;\nArray.Resize<T>(ref array1, array1OriginalLength + array2.Length);\nArray.Copy(array2, 0, array1, array1OriginalLength, array2.Length);\n T[] array1 = getOneArray();\nT[] array2 = getAnotherArray();\nT[] newArray = new T[array1.Length + array2.Length];\nArray.Copy(array1, newArray, array1.Length);\nArray.Copy(array2, 0, newArray, array1.Length, array2.Length);\n"
},
{
"answer_id": 59253,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "List<int>"
},
{
"answer_id": 59262,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 9,
"selected": false,
"text": "int[] front = { 1, 2, 3, 4 };\nint[] back = { 5, 6, 7, 8 };\nint[] combined = front.Concat(back).ToArray();\n int[] front = { 1, 2, 3, 4 };\nint[] back = { 5, 6, 7, 8 };\n\nint[] combined = new int[front.Length + back.Length];\nArray.Copy(front, combined, front.Length);\nArray.Copy(back, 0, combined, front.Length, back.Length);\n Concat"
},
{
"answer_id": 8770946,
"author": "namco",
"author_id": 591826,
"author_profile": "https://Stackoverflow.com/users/591826",
"pm_score": -1,
"selected": false,
"text": "ArrayLIst al = new ArrayList();\nal.AddRange(array_1);\nal.AddRange(array_2);\nal.AddRange(array_3);\narray_4 = al.ToArray();\n"
},
{
"answer_id": 15482599,
"author": "pasx",
"author_id": 683319,
"author_profile": "https://Stackoverflow.com/users/683319",
"pm_score": 1,
"selected": false,
"text": "int[] xSrc1 = new int[3] { 0, 1, 2 };\nint[] xSrc2 = new int[5] { 3, 4, 5, 6 , 7 };\n\nint[] xAll = new int[xSrc1.Length + xSrc2.Length];\nxSrc1.CopyTo(xAll, 0);\nxSrc2.CopyTo(xAll, xSrc1.Length);\n"
},
{
"answer_id": 15997813,
"author": "vikasse",
"author_id": 545620,
"author_profile": "https://Stackoverflow.com/users/545620",
"pm_score": 0,
"selected": false,
"text": "int [] SouceArray1 = new int[] {2,1,3};\nint [] SourceArray2 = new int[] {4,5,6};\nint [] targetArray = new int [SouceArray1.Length + SourceArray2.Length];\nSouceArray1.CopyTo(targetArray,0);\nSourceArray2.CopyTo(targetArray,SouceArray1.Length) ; \nforeach (int i in targetArray) Console.WriteLine(i + \" \"); \n"
},
{
"answer_id": 20531421,
"author": "Lorenz Lo Sauer",
"author_id": 901946,
"author_profile": "https://Stackoverflow.com/users/901946",
"pm_score": 2,
"selected": false,
"text": "//resides in IEnumerableStringExtensions.cs\npublic static class IEnumerableStringExtensions\n{\n public static IEnumerable<string> Append(this string[] arrayInitial, string[] arrayToAppend)\n {\n string[] ret = new string[arrayInitial.Length + arrayToAppend.Length];\n arrayInitial.CopyTo(ret, 0);\n arrayToAppend.CopyTo(ret, arrayInitial.Length);\n\n return ret;\n }\n}\n IEnumerable var someStringArray = new[]{\"a\", \"b\", \"c\"};\nvar someStringArray2 = new[]{\"d\", \"e\", \"f\"};\nsomeStringArray.Append(someStringArray2 ); //contains a,b,c,d,e,f\n"
},
{
"answer_id": 23822750,
"author": "Simon B.",
"author_id": 3667854,
"author_profile": "https://Stackoverflow.com/users/3667854",
"pm_score": 7,
"selected": false,
"text": "var arr1 = new[] { 1, 2, 3, 4, 5 };\nvar arr2 = new[] { 6, 7, 8, 9, 0 };\nvar arr = arr1.Union(arr2).ToArray();\n"
},
{
"answer_id": 24958986,
"author": "Angelo Ortega",
"author_id": 3877523,
"author_profile": "https://Stackoverflow.com/users/3877523",
"pm_score": 4,
"selected": false,
"text": "var array = new string[] { \"test\" }.ToList();\nvar array1 = new string[] { \"test\" }.ToList();\narray.AddRange(array1);\nvar result = array.ToArray();\n"
},
{
"answer_id": 27306348,
"author": "Lukas",
"author_id": 593388,
"author_profile": "https://Stackoverflow.com/users/593388",
"pm_score": 2,
"selected": false,
"text": " private void LoadImage()\n {\n string src = string.empty;\n byte[] mergedImageData = new byte[0];\n\n mergedImageData = MergeTwoImageByteArrays(watermarkByteArray, backgroundImageByteArray);\n src = \"data:image/png;base64,\" + Convert.ToBase64String(mergedImageData);\n MyImage.ImageUrl = src;\n }\n\n private byte[] MergeTwoImageByteArrays(byte[] imageBytes, byte[] imageBaseBytes)\n {\n byte[] mergedImageData = new byte[0];\n using (var msBase = new MemoryStream(imageBaseBytes))\n {\n System.Drawing.Image imgBase = System.Drawing.Image.FromStream(msBase);\n Graphics gBase = Graphics.FromImage(imgBase);\n using (var msInfo = new MemoryStream(imageBytes))\n {\n System.Drawing.Image imgInfo = System.Drawing.Image.FromStream(msInfo);\n Graphics gInfo = Graphics.FromImage(imgInfo);\n gBase.DrawImage(imgInfo, new Point(0, 0));\n //imgBase.Save(Server.MapPath(\"_____testImg.png\"), ImageFormat.Png);\n MemoryStream mergedImageStream = new MemoryStream();\n imgBase.Save(mergedImageStream, ImageFormat.Png);\n mergedImageData = mergedImageStream.ToArray();\n mergedImageStream.Close();\n }\n }\n return mergedImageData;\n }\n"
},
{
"answer_id": 29591722,
"author": "Rajkumar M",
"author_id": 4779984,
"author_profile": "https://Stackoverflow.com/users/4779984",
"pm_score": -1,
"selected": false,
"text": "int[] a1 ={3,4,5,6};\nint[] a2 = {4,7,9};\nint i = a1.Length-1;\nint j = a2.Length-1;\nint resultIndex= i+j+1;\nArray.Resize(ref a2, a1.Length +a2.Length);\nwhile(resultIndex >=0)\n{\n if(i != 0 && j !=0)\n {\n if(a1[i] > a2[j])\n {\n a2[resultIndex--] = a[i--];\n }\n else\n {\n a2[resultIndex--] = a[j--];\n }\n }\n else if(i>=0 && j<=0)\n { \n a2[resultIndex--] = a[i--];\n }\n else if(j>=0 && i <=0)\n {\n a2[resultIndex--] = a[j--];\n }\n}\n"
},
{
"answer_id": 35873378,
"author": "John Reilly",
"author_id": 761388,
"author_profile": "https://Stackoverflow.com/users/761388",
"pm_score": 3,
"selected": false,
"text": "var arr1 = new[] { 1, 2, 3, 4, 5 };\nvar arr2 = new[] { 6, 7, 8, 9, 0 };\nvar arr = Queryable.Concat(arr1, arr2).ToArray();\n"
},
{
"answer_id": 42333029,
"author": "Solomon Rutzky",
"author_id": 577765,
"author_profile": "https://Stackoverflow.com/users/577765",
"pm_score": 2,
"selected": false,
"text": "int[] front = { 1, 2, 3, 4 };\nint[] back = { 5, 6, 7, 8 };\n\nint[] combined = new int[front.Length + back.Length];\nBuffer.BlockCopy(front, 0, combined, 0, front.Length);\nBuffer.BlockCopy(back, 0, combined, front.Length, back.Length);\n Buffer.BlockCopy Array.Copy"
},
{
"answer_id": 43250371,
"author": "Smith",
"author_id": 362461,
"author_profile": "https://Stackoverflow.com/users/362461",
"pm_score": 6,
"selected": false,
"text": "var arr1 = new[] { 1, 2, 3, 4, 5 };\nvar arr2 = new[] { 6, 7, 8, 9, 0 };\nvar arr = arr1.Concat(arr2).ToArray();\n"
},
{
"answer_id": 46849562,
"author": "Lord Darth Vader",
"author_id": 2527116,
"author_profile": "https://Stackoverflow.com/users/2527116",
"pm_score": 0,
"selected": false,
"text": "public static class IEnumerableExtenions\n{\n public static IEnumerable<T> UnionIfNotNull<T>(this IEnumerable<T> list1, IEnumerable<T> list2)\n {\n if (list1 != null && list2 != null)\n return list1.Union(list2);\n else if (list1 != null)\n return list1;\n else if (list2 != null)\n return list2;\n else return null;\n }\n}\n"
},
{
"answer_id": 49230902,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 2,
"selected": false,
"text": "SelectMany params private static T[] Combine<T>(params IEnumerable<T>[] items) =>\n items.SelectMany(i => i).Distinct().ToArray();\n public string[] Reds = new [] { \"Red\", \"Crimson\", \"TrafficLightRed\" };\n public string[] Greens = new [] { \"Green\", \"LimeGreen\" };\n public string[] Blues = new [] { \"Blue\", \"SkyBlue\", \"Navy\" };\n\n public string[] Colors = Combine(Reds, Greens, Blues);\n"
},
{
"answer_id": 55578088,
"author": "cj.burrow",
"author_id": 6580072,
"author_profile": "https://Stackoverflow.com/users/6580072",
"pm_score": 3,
"selected": false,
"text": "public static T[] ConcatArrays<T>(params T[][] args)\n {\n if (args == null)\n throw new ArgumentNullException();\n\n var offset = 0;\n var newLength = args.Sum(arr => arr.Length); \n var newArray = new T[newLength];\n\n foreach (var arr in args)\n {\n Buffer.BlockCopy(arr, 0, newArray, offset, arr.Length);\n offset += arr.Length;\n }\n\n return newArray;\n }\n var header = new byte[] { 0, 1, 2};\nvar data = new byte[] { 3, 4, 5, 6 };\nvar checksum = new byte[] {7, 0};\nvar newArray = ConcatArrays(header, data, checksum);\n//output byte[9] { 0, 1, 2, 3, 4, 5, 6, 7, 0 }\n"
},
{
"answer_id": 59576666,
"author": "schoetbi",
"author_id": 108238,
"author_profile": "https://Stackoverflow.com/users/108238",
"pm_score": 2,
"selected": false,
"text": "var arrays = new[]{new[]{1, 2, 3}, new[]{4, 5, 6}};\nvar combined = arrays.SelectMany(a => a).ToArray();\nforeach (var v in combined) Console.WriteLine(v); \n 1\n2\n3\n4\n5\n6\n"
},
{
"answer_id": 66751270,
"author": "Dmitry Shashurov",
"author_id": 4309436,
"author_profile": "https://Stackoverflow.com/users/4309436",
"pm_score": -1,
"selected": false,
"text": "string[] arr1 = ...\nstring[] arr2 = ...\nstring[] arr3 = ... \nList<string> arr = new List<string>(arr1.Length + arr2.Length + arr3.Length);\narr.AddRange(arr1);\narr.AddRange(arr2);\narr.AddRange(arr3);\nstring[] result = arr.ToArray();\n"
},
{
"answer_id": 67243561,
"author": "Mondonno",
"author_id": 11824362,
"author_profile": "https://Stackoverflow.com/users/11824362",
"pm_score": -1,
"selected": false,
"text": "public static void ArrayPush<T>(ref T[] table, object value)\n{\n Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)\n table.SetValue(value, table.Length - 1); // Setting the value for the new element\n}\n\npublic static void MergeArrays<T>(ref T[] tableOne, T[] tableTwo) {\n foreach(var element in tableTwo) {\n ArrayPush(ref tableOne, element);\n }\n}\n"
},
{
"answer_id": 68940225,
"author": "Harjeet Singh",
"author_id": 4960384,
"author_profile": "https://Stackoverflow.com/users/4960384",
"pm_score": 0,
"selected": false,
"text": "string[] names1 = new string[] { \"Ava\", \"Emma\", \"Olivia\" };\nstring[] names2 = new string[] { \"Olivia\", \"Sophia\", \"Emma\" };\nList<string> arr = new List<string>(names1.Length + names2.Length);\narr.AddRange(names1);\narr.AddRange(names2);\nstring[] result = arr.Distinct().ToArray();\nforeach(string str in result)\n{\n Console.WriteLine(str.ToString());\n}\n\nConsole.ReadLine();\n"
},
{
"answer_id": 74140785,
"author": "ArrayFormula",
"author_id": 13501781,
"author_profile": "https://Stackoverflow.com/users/13501781",
"pm_score": 0,
"selected": false,
"text": "// Two for-loops\nprivate static int[] MergedArrays_1(int[] a, int[] b)\n{\n int[] result = new int[a.Length + b.Length];\n for (int i = 0; i < a.Length; i++)\n {\n result[i] = a[i];\n }\n for (int i = a.Length; i < result.Length; i++)\n {\n result[i] = b[i - a.Length];\n }\n return result;\n}\n\n// One for-loop\nprivate static int[] MergedArrays_2(int[] a, int[] b)\n{\n int[] results = new int[a.Length + b.Length];\n for (int i = 0; i < results.Length; i++)\n {\n results[i] = (i < a.Length) ? a[i] : b[i - a.Length];\n }\n return results;\n}\n\n// Array Method\nprivate static int[] MergedArrays_3(int[] a, int[] b)\n{\n int[] results = new int[a.Length + b.Length];\n a.CopyTo(results, 0);\n b.CopyTo(results, a.Length);\n return results;\n}\n int[] result = MultipleMergedArrays(arrayOne, arrayTwo, arrayThree);\n private static int[] MultipleMergedArrays(params int[][] a)\n{\n // Get Length\n int resultsLength = 0;\n for (int row = 0; row < a.GetLength(0); row++)\n {\n resultsLength += a.Length;\n }\n\n // Initialize\n int[] results = new int[resultsLength];\n\n // Add Items\n int index = 0;\n for (int row = 0; row < a.GetLength(0); row++)\n {\n a[row].CopyTo(results, index);\n index += a[row].Length;\n }\n return results;\n}\n private static int[] RemoveEmpty(int[] array)\n{\n int count = 0;\n for (int i = 0; i < array.Length; i++)\n {\n if (array[i] == 0) count++;\n }\n\n int[] result = new int[array.Length - count];\n\n count = 0;\n for (int i = 0; i < array.Length; i++)\n {\n if (array[i] == 0) continue;\n result[count] = array[i];\n count++;\n }\n\n return result;\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3058/"
] |
59,220 |
<p>I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use.</p>
<p>What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View.</p>
<p>As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done.</p>
<p>What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it:</p>
<pre><code>String FilePath = Path.GetDirectoryName(FileName);
System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName);
</code></pre>
<p>That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter:</p>
<pre><code>AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies();
</code></pre>
<p>That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case.</p>
<p>So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc.</p>
<p>I know that tools like Reflector do this, I just can't find the syntax for getting at it. </p>
|
[
{
"answer_id": 59243,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 5,
"selected": true,
"text": "AppDomain.AssemblyResolve LoadFile AppDomain AppDomain Assembly.ReflectionOnlyLoad"
},
{
"answer_id": 37060921,
"author": "mathume",
"author_id": 400694,
"author_profile": "https://Stackoverflow.com/users/400694",
"pm_score": 3,
"selected": false,
"text": "ResolveEventHandler MarshalByRefObject Serializable ApplicationBase AppDomain PrivateBinPath"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124/"
] |
59,221 |
<p>I am using ActiveScaffold in a Ruby on Rails app, and to save space in the table I have replaced the default "actions" text in the table (ie. "edit", "delete", "show") with icons using CSS. I have also added a couple of custom actions with action_link.add ("move" and "copy").</p>
<p>For clarity, <strong>I would like to have a tooltip pop up with the related action</strong> (ie. "edit", "copy") when I hover the mouse over the icon.</p>
<p>I thought I could do this by adding a simple "alt" definition to the tag, but that doesn't appear to work.</p>
<p>Can somebody point me in the right direction?</p>
|
[
{
"answer_id": 59226,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "alt background:url(...);"
},
{
"answer_id": 59228,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 1,
"selected": false,
"text": "alt title"
},
{
"answer_id": 59260,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": true,
"text": "alt alt title alt title"
},
{
"answer_id": 60008,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 3,
"selected": false,
"text": "<span title=\"Click here to edit the foo\">\n Edit\n</span>\n"
},
{
"answer_id": 67140054,
"author": "Maya",
"author_id": 9442717,
"author_profile": "https://Stackoverflow.com/users/9442717",
"pm_score": 0,
"selected": false,
"text": "<abbr tittle=\"some text\"> </abbr>"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] |
59,232 |
<p>What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table?</p>
<p>For example: I have a <code>JOBS</code> table with the column <code>JOB_NUMBER</code>. How can I find out if I have any duplicate <code>JOB_NUMBER</code>s, and how many times they're duplicated?</p>
|
[
{
"answer_id": 59242,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 10,
"selected": true,
"text": "SELECT column_name, COUNT(column_name)\nFROM table_name\nGROUP BY column_name\nHAVING COUNT(column_name) > 1;\n"
},
{
"answer_id": 59254,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 5,
"selected": false,
"text": "select job_number, count(*)\nfrom jobs\ngroup by job_number\nhaving count(*) > 1;\n"
},
{
"answer_id": 59261,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 3,
"selected": false,
"text": "SELECT <column>, count(*)\nFROM <table>\nGROUP BY <column> HAVING COUNT(*) > 1;\n SELECT job_number, count(*)\nFROM jobs\nGROUP BY job_number HAVING COUNT(*) > 1;\n"
},
{
"answer_id": 59278,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 2,
"selected": false,
"text": "select count(j1.job_number), j1.job_number, j1.id, j2.id\nfrom jobs j1 join jobs j2 on (j1.job_numer = j2.job_number)\nwhere j1.id != j2.id\ngroup by j1.job_number\n"
},
{
"answer_id": 60437,
"author": "Grrey",
"author_id": 6155,
"author_profile": "https://Stackoverflow.com/users/6155",
"pm_score": 6,
"selected": false,
"text": "SELECT *\nFROM TABLE A\nWHERE EXISTS (\n SELECT 1 FROM TABLE\n WHERE COLUMN_NAME = A.COLUMN_NAME\n AND ROWID < A.ROWID\n)\n column_name"
},
{
"answer_id": 60584,
"author": "Evan",
"author_id": 6277,
"author_profile": "https://Stackoverflow.com/users/6277",
"pm_score": 4,
"selected": false,
"text": "SELECT column_name\nFROM table\nGROUP BY column_name\nHAVING COUNT(*) > 1\n"
},
{
"answer_id": 12507836,
"author": "Jitendra Vispute",
"author_id": 772712,
"author_profile": "https://Stackoverflow.com/users/772712",
"pm_score": 3,
"selected": false,
"text": "select oed.empid, count(oed.empid) \nfrom emp_dept oed \nwhere exists ( select * \n from emp_dept ied \n where oed.rowid <> ied.rowid and \n ied.empid = oed.empid and \n ied.deptid = oed.deptid ) \n group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);\n select oed.empid, count(oed.empid) \nfrom emp_dept oed \nwhere exists ( select * \n from emp_dept ied \n where oed.id <> ied.id and \n ied.empid = oed.empid and \n ied.deptid = oed.deptid ) \n group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);\n"
},
{
"answer_id": 15827573,
"author": "Wahid Haidari",
"author_id": 2247937,
"author_profile": "https://Stackoverflow.com/users/2247937",
"pm_score": 2,
"selected": false,
"text": "SELECT SocialSecurity_Number, Count(*) no_of_rows\nFROM SocialSecurity \nGROUP BY SocialSecurity_Number\nHAVING Count(*) > 1\nOrder by Count(*) desc \n"
},
{
"answer_id": 35039925,
"author": "Stacker",
"author_id": 1348805,
"author_profile": "https://Stackoverflow.com/users/1348805",
"pm_score": -1,
"selected": false,
"text": "SELECT count(poid) \nFROM poitem \nWHERE poid = 50 \nAND rownum < any (SELECT count(*) FROM poitem WHERE poid = 50) \nGROUP BY poid \nMINUS\nSELECT count(poid) \nFROM poitem \nWHERE poid in (50)\nGROUP BY poid \nHAVING count(poid) > 1;\n"
},
{
"answer_id": 35312175,
"author": "DoOrDie",
"author_id": 5726548,
"author_profile": "https://Stackoverflow.com/users/5726548",
"pm_score": 0,
"selected": false,
"text": "select * from emp\n where rowid not in\n (select max(rowid) from emp group by empno);\n"
},
{
"answer_id": 46905493,
"author": "J. Chomel",
"author_id": 6019417,
"author_profile": "https://Stackoverflow.com/users/6019417",
"pm_score": 2,
"selected": false,
"text": "c1 c2 c3 ROWID ROW_NUMBER() >1 Select *\nFrom Table_With_Duplicates\nWhere Rowid In (Select Rowid\n From (Select ROW_NUMBER() Over (\n Partition By c1, c2, c3\n Order By c1, c2, c3\n ) nbLines\n From Table_With_Duplicates) t2\n Where nbLines > 1)\n"
},
{
"answer_id": 48224922,
"author": "Chaminda Dilshan",
"author_id": 9166453,
"author_profile": "https://Stackoverflow.com/users/9166453",
"pm_score": 1,
"selected": false,
"text": "select column_name, count(1)\nfrom table\ngroup by column_name\nhaving count (column_name) > 1;\n"
},
{
"answer_id": 51474054,
"author": "Parth Kansara",
"author_id": 9952631,
"author_profile": "https://Stackoverflow.com/users/9952631",
"pm_score": 2,
"selected": false,
"text": "select * from table where column_name in\n(select ing.column_name from table ing group by ing.column_name having count(*) > 1)\norder by column_name desc;\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
] |
59,267 |
<p>Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no longer supported.</p>
<p>The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases.</p>
|
[
{
"answer_id": 59271,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<input type=\"button\" ... />"
},
{
"answer_id": 59286,
"author": "Thunder3",
"author_id": 2832,
"author_profile": "https://Stackoverflow.com/users/2832",
"pm_score": -1,
"selected": false,
"text": "<asp:Button> <input type=\"button\">"
},
{
"answer_id": 59316,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 5,
"selected": true,
"text": "<form method=\"post\" action=\"<%= Html.AttributeEncode(Url.Action(\"CastUpVote\")) %>\">\n<input type=\"submit\" value=\"<%=ViewData.Model.UpVotes%> up votes\" />\n</form>\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
59,280 |
<p>I need to update a <code>combobox</code> with a new value so it changes the reflected text in it. The cleanest way to do this is after the <code>combobox</code>has been initialised and with a message.</p>
<p>So I am trying to craft a <code>postmessage</code> to the hwnd that contains the <code>combobox</code>.</p>
<p>So if I want to send a message to it, changing the currently selected item to the nth item, what would the <code>postmessage</code> look like?</p>
<p>I am guessing that it would involve <code>ON_CBN_SELCHANGE</code>, but I can't get it to work right.</p>
|
[
{
"answer_id": 59317,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 4,
"selected": true,
"text": "ComboBox_SetCurSel(hWndCombo, n);\n m_combo.SetCurSel(2);\n"
},
{
"answer_id": 59350,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "const int index = 0;\nm_comboBox.PostMessage(CBN_SELCHANGE, index);\n"
},
{
"answer_id": 98203,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 0,
"selected": false,
"text": "void onSelectChangeHandler(HWND hwnd)\n{\n static bool fInsideSelectChange = 0;\n\n //-- ignore the change message if this function generated it\n if (fInsideSelectChange == 0)\n {\n //-- turn on the sentinel\n fInsideSelectChange = 1;\n\n //-- make the selection changes as required\n .....\n\n //-- we are done so turn off the sentinel\n fInsideSelectChange = 0;\n }\n}\n"
},
{
"answer_id": 45231288,
"author": "serup",
"author_id": 3990012,
"author_profile": "https://Stackoverflow.com/users/3990012",
"pm_score": -1,
"selected": false,
"text": "ON_CBN_CLOSEUP(IDC_COMBO1, OnCloseupCombo)\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
] |
59,294 |
<p>I have the following query:</p>
<pre><code>select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;
</code></pre>
<p>What would be the difference if I replaced all calls to <code>count(column_name)</code> to <code>count(*)</code>?</p>
<p>This question was inspired by <a href="https://stackoverflow.com/questions/59232/how-do-i-find-duplicate-values-in-a-table-in-oracle">How do I find duplicate values in a table in Oracle?</a>.</p>
<hr>
<p>To clarify the accepted answer (and maybe my question), replacing <code>count(column_name)</code> with <code>count(*)</code> would return an extra row in the result that contains a <code>null</code> and the count of <code>null</code> values in the column.</p>
|
[
{
"answer_id": 59302,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 9,
"selected": true,
"text": "count(*) count(column) create table #bla(id int,id2 int)\ninsert #bla values(null,null)\ninsert #bla values(1,null)\ninsert #bla values(null,1)\ninsert #bla values(1,null)\ninsert #bla values(null,1)\ninsert #bla values(1,null)\ninsert #bla values(null,null)\n\nselect count(*),count(id),count(id2)\nfrom #bla\n"
},
{
"answer_id": 59369,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 5,
"selected": false,
"text": "select column_a, count(distinct column_b)\nfrom table\ngroup by column_a\nhaving count(distinct column_b) > 1;\n"
},
{
"answer_id": 3039334,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "-- count(column_name) vs. count(*)\n-- Illustrates the difference between counting a column\n-- that can hold null values, a 'not null' column, and count(*)\n\nselect count(WebsiteUrl), count(Id), count(*) from Users\n count(Id) count(*) Id null WebsiteUrl null"
},
{
"answer_id": 4925414,
"author": "Ali Adravi",
"author_id": 586227,
"author_profile": "https://Stackoverflow.com/users/586227",
"pm_score": -1,
"selected": false,
"text": "Count(1) in place of column name or * \n"
},
{
"answer_id": 9318012,
"author": "G21",
"author_id": 903005,
"author_profile": "https://Stackoverflow.com/users/903005",
"pm_score": 2,
"selected": false,
"text": "-- Variable table\nDECLARE @Table TABLE\n(\n CustomerId int NULL \n , Name nvarchar(50) NULL\n)\n\n-- Insert some records for tests\nINSERT INTO @Table VALUES( NULL, 'Pedro')\nINSERT INTO @Table VALUES( 1, 'Juan')\nINSERT INTO @Table VALUES( 2, 'Pablo')\nINSERT INTO @Table VALUES( 3, 'Marcelo')\nINSERT INTO @Table VALUES( NULL, 'Leonardo')\nINSERT INTO @Table VALUES( 4, 'Ignacio')\n\n-- Get all the collumns by indicating *\nSELECT COUNT(*) AS 'AllRowsCount'\nFROM @Table\n\n-- Get only content columns ( exluce NULLs )\nSELECT COUNT(CustomerId) AS 'OnlyNotNullCounts'\nFROM @Table\n"
},
{
"answer_id": 16378822,
"author": "Ahmedul Kabir",
"author_id": 1685054,
"author_profile": "https://Stackoverflow.com/users/1685054",
"pm_score": 2,
"selected": false,
"text": "COUNT(*) COUNT(COLUMN_NAME) COUNT(*) COUNT(COLUMN_NAME)"
},
{
"answer_id": 36987526,
"author": "Unna",
"author_id": 6083307,
"author_profile": "https://Stackoverflow.com/users/6083307",
"pm_score": -1,
"selected": false,
"text": "Count(*) NULL count(Columnname) * Select * count *"
},
{
"answer_id": 55327529,
"author": "Arun Solomon",
"author_id": 10654073,
"author_profile": "https://Stackoverflow.com/users/10654073",
"pm_score": 2,
"selected": false,
"text": "COUNT(*) COUNT(Column Name)"
},
{
"answer_id": 68799071,
"author": "Payel Senapati",
"author_id": 12118888,
"author_profile": "https://Stackoverflow.com/users/12118888",
"pm_score": 0,
"selected": false,
"text": "GROUP BY CREATE TABLE table1 ( \nid INT \n);\n INSERT INTO table1 VALUES \n(1), \n(2), \n(NULL), \n(2), \n(NULL), \n(3), \n(1), \n(4), \n(NULL), \n(2);\n SELECT * FROM table1;\n +------+\n| id |\n+------+\n| 1 |\n| 2 |\n| NULL |\n| 2 |\n| NULL |\n| 3 |\n| 1 |\n| 4 |\n| NULL |\n| 2 |\n+------+\n10 rows in set (0.00 sec)\n SELECT id, COUNT(*) FROM table1 GROUP BY id;\n +------+----------+\n| id | COUNT(*) |\n+------+----------+\n| 1 | 2 |\n| 2 | 3 |\n| NULL | 3 |\n| 3 | 1 |\n| 4 | 1 |\n+------+----------+\n5 rows in set (0.00 sec)\n COUNT(*) id NULL SELECT id, COUNT(id) FROM table1 GROUP BY id;\n +------+-----------+\n| id | COUNT(id) |\n+------+-----------+\n| 1 | 2 |\n| 2 | 3 |\n| NULL | 0 |\n| 3 | 1 |\n| 4 | 1 |\n+------+-----------+\n5 rows in set (0.00 sec)\n COUNT(id) id NULL SELECT id, COUNT(DISTINCT id) FROM table1 GROUP BY id;\n +------+--------------------+\n| id | COUNT(DISTINCT id) |\n+------+--------------------+\n| NULL | 0 |\n| 1 | 1 |\n| 2 | 1 |\n| 3 | 1 |\n| 4 | 1 |\n+------+--------------------+\n5 rows in set (0.00 sec)\n COUNT(DISTINCT id) id NULL"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
59,297 |
<p>When setting up foreign keys in SQL Server, under what circumstances should you have it cascade on delete or update, and what is the reasoning behind it?</p>
<p>This probably applies to other databases as well.</p>
<p>I'm looking most of all for concrete examples of each scenario, preferably from someone who has used them successfully.</p>
|
[
{
"answer_id": 216301,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 2,
"selected": false,
"text": " DELETE FROM table WHERE SomeDate < 7 years ago;\n FOR EACH R IN (SELECT FROM table WHERE SomeDate < 7 years ago) LOOP\n DELETE FROM ChildTable WHERE tableId = R.tableId;\n DELETE FROM table WHERE tableId = R.tableid;\n /* More child tables here */\n NEXT\n DELETE FROM CURRENCY WHERE CurrencyCode = 'USD'\n"
},
{
"answer_id": 73498113,
"author": "Jonas Kello",
"author_id": 2761797,
"author_profile": "https://Stackoverflow.com/users/2761797",
"pm_score": 0,
"selected": false,
"text": "Order OrderItems Order OrderItems"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
59,299 |
<p>I'm migrating a Hibernate application's cache from EHCache to JBoss TreeCache.
I'm trying to find how to configure the equivalent to maxElementsOnDisk to limit the cache size on disk, but I couldn't find anything similar to configure in a FileCacheLoader with passivation activated.</p>
<p>Thanks</p>
|
[
{
"answer_id": 61394,
"author": "Mat Mannion",
"author_id": 6282,
"author_profile": "https://Stackoverflow.com/users/6282",
"pm_score": 2,
"selected": false,
"text": "<attribute name=\"MaxCapacity\">20000</attribute>"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5425/"
] |
59,309 |
<p>What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.</p>
<p><img src="https://content.screencast.com/users/jessegavin/folders/Jing/media/ba5c2688-0aad-4e89-878a-8911946f8612/2008-09-12_1027.png" alt="alt text"></p>
|
[
{
"answer_id": 59324,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 4,
"selected": false,
"text": "position:table\\table-cell <div class=\"valign-outer\">\n <div class=\"valign-middle\">\n <div class=\"valign-inner\">\n Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.\n </div>\n </div>\n</div>\n\n<style>\n /* Non-structural styling */\n .valign-outer { height: 400px; border: 1px solid red; }\n .valign-inner { border: 1px solid blue; }\n</style>\n\n<!--[if lte IE 7]>\n<style>\n /* For IE7 and earlier */\n .valign-outer { position: relative; overflow: hidden; }\n .valign-middle { position: absolute; top: 50%; }\n .valign-inner { position: relative; top: -50% }\n</style>\n<![endif]-->\n<!--[if gt IE 7]> -->\n<style>\n /* For other browsers */\n .valign-outer { position: static; display: table; overflow: hidden; }\n .valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }\n</style>\n"
},
{
"answer_id": 13075912,
"author": "Fadi",
"author_id": 856921,
"author_profile": "https://Stackoverflow.com/users/856921",
"pm_score": 7,
"selected": false,
"text": "::before display: table table max-height .block {\n height: 300px;\n text-align: center;\n background: #c0c0c0;\n border: #a0a0a0 solid 1px;\n margin: 20px;\n}\n\n.block::before {\n content: '';\n display: inline-block;\n height: 100%; \n vertical-align: middle;\n margin-right: -0.25em; /* Adjusts for spacing */\n\n /* For visualization \n background: #808080; width: 5px;\n */\n}\n\n.centered {\n display: inline-block;\n vertical-align: middle;\n width: 300px;\n padding: 10px 15px;\n border: #a0a0a0 solid 1px;\n background: #f5f5f5;\n} <div class=\"block\">\n <div class=\"centered\">\n <h1>Some text</h1>\n <p>But he stole up to us again, and suddenly clapping his hand on my\n shoulder, said—\"Did ye see anything looking like men going\n towards that ship a while ago?\"</p>\n </div>\n</div>"
},
{
"answer_id": 20434170,
"author": "dougli",
"author_id": 3076093,
"author_profile": "https://Stackoverflow.com/users/3076093",
"pm_score": 3,
"selected": false,
"text": "contentCentered .contentCentered {\n text-align: center;\n}\n\n.contentCentered::before {\n content: '';\n display: inline-block;\n height: 100%; \n vertical-align: middle;\n margin-right: -.25em; /* Adjusts for spacing */\n}\n\n.contentCentered > * {\n display: inline-block;\n vertical-align: middle;\n} <div class=\"contentCentered\">\n <div>\n <h1>Some text</h1>\n <p>But he stole up to us again, and suddenly clapping his hand on my\n shoulder, said—\"Did ye see anything looking like men going\n towards that ship a while ago?\"</p>\n </div>\n</div>"
},
{
"answer_id": 26125596,
"author": "user3432605",
"author_id": 3432605,
"author_profile": "https://Stackoverflow.com/users/3432605",
"pm_score": 0,
"selected": false,
"text": "div .vertical_placer{\n background:red;\n position:absolute; \n height:43%; \n width:100%;\n display: table;\n}\n\n.inner_placer{ \n display: table-cell;\n vertical-align: middle;\n text-align:center;\n}\n\n.inner_placer svg{\n position:relative;\n color:#fff;\n background:blue;\n width:30%;\n min-height:20px;\n max-height:60px;\n height:20%;\n}\n <div class=\"footer\">\n <div class=\"vertical_placer\">\n <div class=\"inner_placer\">\n <svg> some Text here</svg>\n </div>\n </div>\n</div> \n"
},
{
"answer_id": 27663253,
"author": "BlackCetha",
"author_id": 4396938,
"author_profile": "https://Stackoverflow.com/users/4396938",
"pm_score": 8,
"selected": true,
"text": "position: relative;\ntop: 50%;\ntransform: translateY(-50%);\n top: 50%; transform: translateY(-50%) position: absolute relative transform translate"
},
{
"answer_id": 37294825,
"author": "Loïc G.",
"author_id": 953096,
"author_profile": "https://Stackoverflow.com/users/953096",
"pm_score": 2,
"selected": false,
"text": "body,\nhtml {\n height: 100%;\n margin: 0;\n}\n.site {\n height: 100%;\n display: flex;\n}\n.site .box {\n background: #0ff;\n max-width: 20vw;\n margin: auto;\n}\n <div class=\"site\">\n <div class=\"box\">\n <h1>blabla</h1>\n <p>blabla</p>\n <p>blablabla</p>\n <p>lbibdfvkdlvfdks</p>\n </div>\n</div>\n"
},
{
"answer_id": 40712796,
"author": "Leo Dimuccio",
"author_id": 7187602,
"author_profile": "https://Stackoverflow.com/users/7187602",
"pm_score": 2,
"selected": false,
"text": "position: absolute;\ntop: 50%;\ntransform: translateY(-50%);\nmargin: 0 auto;\nright: 0;\nleft: 0;\n"
},
{
"answer_id": 58139571,
"author": "Leandro Castro",
"author_id": 3594412,
"author_profile": "https://Stackoverflow.com/users/3594412",
"pm_score": 1,
"selected": false,
"text": ".container{\n position: relative;\n}\n\n.element{\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n"
},
{
"answer_id": 61923425,
"author": "hassan yousefi",
"author_id": 12637216,
"author_profile": "https://Stackoverflow.com/users/12637216",
"pm_score": 4,
"selected": false,
"text": ".example{\n background-color:red;\n height:90px;\n width:90px;\n display:flex;\n align-items:center; /*for vertically center*/\n justify-content:center; /*for horizontally center*/\n} <div class=\"example\">\n <h6>Some text</h6>\n</div>"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5651/"
] |
59,322 |
<p>I have the following code:</p>
<pre><code>SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;
</code></pre>
<p>Is there any difference to the results or performance if I replace the COUNT(*) with COUNT('x')?</p>
<p>(This question is related to a <a href="https://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count">previous one</a>)</p>
|
[
{
"answer_id": 59385,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 2,
"selected": false,
"text": "select count(*) from table\n"
},
{
"answer_id": 59412,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 5,
"selected": true,
"text": "SELECT COUNT(*) vs COUNT(1) SELECT COUNT(*), COUNT(1), COUNT('this is a silly conversation') SELECT(1) vs SELECT(*) SELECT( n ) into SELECT(*) SELECT(n) into SELECT(*)"
},
{
"answer_id": 59858,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "COUNT(*)"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
] |
59,331 |
<p>Suppose I have <code>fileA.h</code> which declares a class <code>classA</code> with template function <code>SomeFunc<T>()</code>. This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of <code>SomeFunc()</code> (like for <code>SomeFunc<int>()</code>) in <code>fileA.C</code> (ie. not in the header file).</p>
<p>If I now call <code>SomeFunc<int>()</code> from some other code (maybe also from another library), would it call the generic version, or the specialization?</p>
<p>I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.</p>
|
[
{
"answer_id": 59359,
"author": "Brandon",
"author_id": 5959,
"author_profile": "https://Stackoverflow.com/users/5959",
"pm_score": 0,
"selected": false,
"text": "SomeFunc<int>()"
},
{
"answer_id": 59361,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 3,
"selected": false,
"text": "template<> SomeFunc<int>();\n"
},
{
"answer_id": 59394,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "fileA.C export"
},
{
"answer_id": 59416,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 5,
"selected": false,
"text": "extern template<> SomeFunc<int>();\n extern"
},
{
"answer_id": 59458,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "extern extern template extern template extern template"
},
{
"answer_id": 787102,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "\n ----------header-----------------\n template < class A >\n void foobar(A& object)\n {\n std::cout << object;\n }\n\n template <> \n void foobar(int);\n\n ---------source------------------\n #include \"header.hpp\"\n\n template <>\n void foobar(int x)\n {\n std::cout << \"an int\";\n }\n\n"
},
{
"answer_id": 18742483,
"author": "CarLuva",
"author_id": 967077,
"author_profile": "https://Stackoverflow.com/users/967077",
"pm_score": 1,
"selected": false,
"text": "extern template namespace myNamespace {\n class classA {\n public:\n template <class T> void SomeFunc() { ... }\n };\n\n // The following line declares the specialization SomeFunc<int>().\n template <> void classA::SomeFunc<int>();\n\n // The following line externalizes the instantiation of the previously\n // declared specialization SomeFunc<int>(). If the preceding line is omitted,\n // the following line PREVENTS the specialization of SomeFunc<int>();\n // SomeFunc<int>() will not be usable unless it is manually instantiated\n // separately). When the preceding line is included, all the compilers I\n // tested this on, including gcc, behave exactly the same (throwing a link\n // error if the specialization of SomeFunc<int>() is not instantiated\n // separately), regardless of whether or not the following line is included;\n // however, my understanding is that nothing in the standard requires that\n // behavior if the following line is NOT included.\n extern template void classA::SomeFunc<int>();\n}\n #include \"fileA.h\"\n\ntemplate <> void myNamespace::classA::SomeFunc<int>() { ... }\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148773/"
] |
59,357 |
<p><strong>Edit</strong>: Let me completely rephrase this, because I'm not sure there's an XML way like I was originally describing.</p>
<p><strong>Yet another edit</strong>: This needs to be a repeatable process, and it has to be able to be set up in a way that it can be called in C# code.</p>
<p>In database A, I have a set of tables, related by PKs and FKs. A parent table, with child and grandchild tables, let's say.</p>
<p>I want to <strong>copy a set of rows from database A to database B</strong>, which has identically named tables and fields. For each table, I want to insert into the same table in database B. But I can't be constrained to use the same primary keys. <strong>The copy routine must create new PKs</strong> for each row in database B, and must propagate those to the child rows. I'm keeping the same relations between the data, in other words, but not the same exact PKs and FKs.</p>
<p>How would you solve this? I'm open to suggestions. SSIS isn't completely ruled out, but it doesn't look to me like it'll do this exact thing. I'm also open to a solution in LINQ, or using typed DataSets, or using some XML thing, or just about anything that'll work in SQL Server 2005 and/or C# (.NET 3.5). The best solution wouldn't require SSIS, and wouldn't require writing a lot of code. But I'll concede that this "best" solution may not exist.</p>
<p>(I didn't make this task up myself, nor the constraints; this is how it was given to me.)</p>
|
[
{
"answer_id": 59407,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 1,
"selected": false,
"text": "SELECT declare @xml xml \nset @xml='<People Key=\"1\" FirstName=\"Bob\" LastName=\"Smith\">\n <PeopleAddresses PeopleKey=\"1\" AddressesKey=\"1\">\n <Addresses Key=\"1\" Street=\"123 Main\" City=\"St Louis\" State=\"MO\" ZIP=\"12345\" />\n </PeopleAddresses>\n</People>\n<People Key=\"2\" FirstName=\"Harry\" LastName=\"Jones\">\n <PeopleAddresses PeopleKey=\"2\" AddressesKey=\"2\">\n <Addresses Key=\"2\" Street=\"555 E 5th St\" City=\"Chicago\" State=\"IL\" ZIP=\"23456\" />\n </PeopleAddresses>\n</People>\n<People Key=\"3\" FirstName=\"Sally\" LastName=\"Smith\">\n <PeopleAddresses PeopleKey=\"3\" AddressesKey=\"1\">\n <Addresses Key=\"1\" Street=\"123 Main\" City=\"St Louis\" State=\"MO\" ZIP=\"12345\" />\n </PeopleAddresses>\n</People>\n<People Key=\"4\" FirstName=\"Sara\" LastName=\"Jones\">\n <PeopleAddresses PeopleKey=\"4\" AddressesKey=\"2\">\n <Addresses Key=\"2\" Street=\"555 E 5th St\" City=\"Chicago\" State=\"IL\" ZIP=\"23456\" />\n </PeopleAddresses>\n</People>\n'\n\nselect t.b.value('./@Key', 'int') PeopleKey,\n t.b.value('./@FirstName', 'nvarchar(50)') FirstName,\n t.b.value('./@LastName', 'nvarchar(50)') LastName\nfrom @xml.nodes('//People') t(b)\n\nselect t.b.value('../../@Key', 'int') PeopleKey,\n t.b.value('./@Street', 'nvarchar(50)') Street,\n t.b.value('./@City', 'nvarchar(50)') City,\n t.b.value('./@State', 'char(2)') [State],\n t.b.value('./@Zip', 'char(5)') Zip\nfrom \[email protected]('//Addresses') t(b)\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5486/"
] |
59,380 |
<p>I have a wildcard subdomain enabled and dynamically parse the URL by passing it as-is to my <code>index.php</code> (ex. <code>somecity.domain.com</code>). </p>
<p>Now, I wish to create a few subdomains that are static where I can install different application and not co-mingle with my current one (ex. <code>blog.domain.com</code>).</p>
<p>My <code>.htaccess</code> currently reads:</p>
<pre><code>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</code></pre>
<p>Can I manipulate this <code>.htaccess</code> to achieve what I need? Can it be done through Apache?</p>
|
[
{
"answer_id": 59403,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "NameVirtualHost *:80\n\n# Begin virtual host directives.\n\n<VirtualHost *:80>\n\n# myblog.com virtual host.\n\nServerAdmin [email protected]\nDocumentRoot \"c:/apache_www/myblog.com/www\"\nServerName myblog.com\nServerAlias *.myblog.com\nErrorLog \"c:/apache_www/myblog.com/logs/log\"\nScriptAlias /cgi-bin/ \"c:/apache_www/myblog.com/cgi-bin/\"\n\n<Directory \"c:/apache_www/myblog.com/www\">\n Options Indexes FollowSymLinks\n AllowOverride All\n Order allow,deny\n Allow from all\n</Directory>\n\n</VirtualHost>\n"
},
{
"answer_id": 59773,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 0,
"selected": false,
"text": "* *.domain.com -> master.domain.com"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6140/"
] |
59,390 |
<p>In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?</p>
<p>Am I going to get myself into trouble if I change this:</p>
<pre><code><cfcomponent>
<cfset variables.foo = "a private instance variable">
<cffunction name = "doSomething">
<cfset var bar = "a function local variable">
<cfreturn "I have #variables.foo# and #bar#.">
</cffunction>
</cfcomponent>
</code></pre>
<p>to this?</p>
<pre><code><cfcomponent>
<cfset foo = "a private instance variable">
<cffunction name = "doSomething">
<cfset var bar = "a function local variable">
<cfreturn "I have #foo# and #bar#.">
</cffunction>
</cfcomponent>
</code></pre>
|
[
{
"answer_id": 59554,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 4,
"selected": true,
"text": "<cfcomponent>\n <cfset foo = \"a private instance variable\">\n\n <cffunction name=\"doSomething\">\n <cfargument name=\"foo\" required=\"yes\"/>\n <cfset var bar = \"a function local variable\">\n <cfreturn \"I have #foo# and #bar#.\">\n </cffunction>\n\n <cffunction name=\"doAnotherThing\">\n <cfargument name=\"foo\" required=\"yes\"/>\n <cfset var bar = \"a function local variable\">\n <cfreturn \"I have #variables.foo# and #bar#.\">\n </cffunction>\n\n</cfcomponent>\n"
},
{
"answer_id": 59566,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 2,
"selected": false,
"text": "<cfcomponent>\n <cfset foo = \"bar\" />\n <cffunction name=\"dumpit\" output=\"true\">\n <cfdump var=\"#variables#\" label=\"cfc variables scope\">\n <cfdump var=\"#this#\" label=\"cfc this scope\">\n </cffunction>\n</cfcomponent>\n <cfset createObject(\"component\", \"test\").dumpit() />\n <cfset foo = \"bar\" />\n"
},
{
"answer_id": 128842,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<cfset foo = \"bar\" />\n"
},
{
"answer_id": 131137,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<cfcomponent>\n <cfset variables.self = structNew()>\n <cfscript>\n structInsert(variables.self, <key>, <value>);\n ...\n </cfscript>\n\n <cffunction name=\"foo\">\n self.<key> = <value>\n <cfreturn self.<key> />\n </cffunction>\n\n ...\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] |
59,396 |
<p>I have a Data Access Object TransactionDao. When you call TransactionDao.Save(transaction) I would like for it to setting a transaction.IsSaved=true flag (this is a simplification the actual thing I'm trying to do is not quite so banal). So when mocking my TransactionDao with RhinoMocks how can I indicate that it should transform its input?</p>
<p>Ideally I would like to write something like this:</p>
<pre><code>Expect.Call(delegate {dao.Save(transaction);}).Override(x => x.IsSaved=true);
</code></pre>
<p>Does anyone know how to do this?</p>
<hr>
<p>Though I got a hint how to do it from the answer specified below the actual type signature is off, you have to do something like this:
Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:</p>
<pre><code>public delegate void FakeSave(Transaction t);
...
Expect.Call(delegate {dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.IsSaved = true; }));
</code></pre>
|
[
{
"answer_id": 59420,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": -1,
"selected": false,
"text": "ITransaction transaction = _Mocker.dynamicMock<ITransaction>;\nExpect.Call(transaction.IsSaved).IgnoreArguments.Return(true);\n_mocker.ReplayAll();\ndao.Save(transaction);\n"
},
{
"answer_id": 59429,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 1,
"selected": false,
"text": "Expect.Call(delegate {dao.Save(transaction);})\n .Do(x => x.IsSaved = true);\n"
},
{
"answer_id": 867435,
"author": "frantisek",
"author_id": 53332,
"author_profile": "https://Stackoverflow.com/users/53332",
"pm_score": 3,
"selected": true,
"text": "Expect.Call(() => dao.Save(transaction))\n .Do(new Action<Transaction>(x => x.IsSaved = true));\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
59,422 |
<p>Is accessing a <strong>bool</strong> field atomic in C#? In particular, do I need to put a lock around:</p>
<pre><code>class Foo
{
private bool _bar;
//... in some function on any thread (or many threads)
_bar = true;
//... same for a read
if (_bar) { ... }
}
</code></pre>
|
[
{
"answer_id": 59505,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 5,
"selected": false,
"text": "_bar _bar _bar volatile Thread.MemoryBarrier()"
},
{
"answer_id": 106301,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 6,
"selected": false,
"text": "bool if(b == false)\n{\n //do something\n}\n b if"
},
{
"answer_id": 16664812,
"author": "stux",
"author_id": 1581640,
"author_profile": "https://Stackoverflow.com/users/1581640",
"pm_score": 2,
"selected": false,
"text": "volatile bool b = false;\n\n.. rarely signal an update with a large state change...\n\nlock b_lock\n{\n b = true;\n //other;\n}\n\n... another thread ...\n\nif(b)\n{\n lock b_lock\n {\n if(b)\n {\n //other stuff\n b = false;\n }\n }\n}\n"
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] |
59,423 |
<p>I've got the following in my .css file creating a little image next to each link on my site:</p>
<pre class="lang-css prettyprint-override"><code>div.post .text a[href^="http:"]
{
background: url(../../pics/remote.gif) right top no-repeat;
padding-right: 10px;
white-space: nowrap;
}
</code></pre>
<p>How do I modify this snippet (or add something new) to exclude the link icon next to images that are links themselves?</p>
|
[
{
"answer_id": 59448,
"author": "Thunder3",
"author_id": 2832,
"author_profile": "https://Stackoverflow.com/users/2832",
"pm_score": 1,
"selected": false,
"text": "<a> div.post .text a.noimage{\n background:none;\n}\n"
},
{
"answer_id": 59454,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "a > span {\n background: url(../../pics/remote.gif) right top no-repeat;\n padding-right: 10px;\n white-space: nowrap;\n}\na > img {\n /* any specific styling for images wrapped in a link (e.g. polaroid like) */\n border: 1px solid #cccccc;\n padding: 4px 4px 25px 4px;\n}\n"
},
{
"answer_id": 59469,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 0,
"selected": false,
"text": "a a.external_link\n{\n background: url(../../pics/remote.gif) right top no-repeat;\n padding-right: 10px;\n white-space: nowrap;\n}\n a img href"
},
{
"answer_id": 59511,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 3,
"selected": true,
"text": "a[href^=\"http:\"] {\n background: url(http://en.wikipedia.org/skins-1.5/monobook/external.png) right center no-repeat;\n padding-right: 14px;\n white-space: nowrap;\n}\na[href^=\"http:\"] img {\n margin-right: -14px;\n border: medium none;\n background-color: red;\n} <a href=\"http://www.google.ca\">Google</a>\n<br/>\n<a href=\"http://www.google.ca\">\n <img src=\"http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/50px-Commons-logo.svg.png\" />\n</a> href^="
}
] |
2008/09/12
|
[
"https://Stackoverflow.com/questions/59423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.