qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
357,323
<p>I have a page that renders slowly. The trip across the net is quick. The initial load of the page is quick. You can actually see (if your machine is slow enough), the initial layout of the html components. Then some javascript stuff runs, making some of those components all ajaxy. Then finally the css gets applied.</p> <p>I can't do anything about the javascript that's slowing everything to a crawl. So I need a throbber to tell the user to hold up, the browser is working. Is there any way to trap the browser is done rendering event? Is there even such an event? Is there another way to do this?</p>
[ { "answer_id": 357346, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "document.observe(\"dom:loaded\", function() {\n //your code\n});\n $(document).ready(function() {\n //your code\n});\n" }, { "answer_id": 417710, "author": "ONODEVO", "author_id": 40440, "author_profile": "https://Stackoverflow.com/users/40440", "pm_score": 3, "selected": true, "text": "$(\"#throbber\").show();\n/* Your AJAX calls */\n$(\"#throbber\").hide();\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45108/" ]
357,328
<p>I have four tables (A,B,C,D) where A is the parent of one to many relationships with B and C. C and D are parents to a one to many relationship with table D. Conceptually, the primary keys of these tables could be:</p> <ul> <li>A: Aid </li> <li>B: Aid, bnum (with foreign key to A)</li> <li>C: Aid, cnum (with foreign key to A)</li> <li>D: Aid, bnum, cnum (with foreign keys to B and C)</li> </ul> <p>Where the 'num' columns auto increment based on each parent id in the relationship rather then on each record. I used this approach on a previous application, and it was not an issue since the creation of B and C records was done by a sequential process by generating a new 'num' value via a 'select max()' query. I was never really satisfied with the approach, but it got the job done. </p> <p>For the specific case I am working on now, records in tables A and B are entered by users so auto-generation of id's is not an issue. In the case of tables C and D, records in these tables are being generated by multiple concurrent batch processes so their identifiers will need to be generated some how. The previous method I listed will not work do to the race condition. </p> <p>Note that this is for an Oracle database so I will be using sequences and not auto-increment columns.</p> <p>Given the constraints above, how you would you design tables to represent A,B,C, and D so that the relationships between the entities are properly enforced AND application code would not be required to generate any identifiers?</p>
[ { "answer_id": 357346, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "document.observe(\"dom:loaded\", function() {\n //your code\n});\n $(document).ready(function() {\n //your code\n});\n" }, { "answer_id": 417710, "author": "ONODEVO", "author_id": 40440, "author_profile": "https://Stackoverflow.com/users/40440", "pm_score": 3, "selected": true, "text": "$(\"#throbber\").show();\n/* Your AJAX calls */\n$(\"#throbber\").hide();\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
357,353
<p>What happens when I do the following?</p> <pre><code>(define ((func x) y) (if (zero? y) ((func x) 1) 12)) </code></pre> <p>I understand that I can do this:</p> <pre><code>(define curried (func 5)) </code></pre> <p>And now I can use curried. What I'm curious about is in the definition of the function. Does the line</p> <pre><code>((func x) 1) </code></pre> <p>create a new lambda with x as the argument, and then invoke it on 1? Or is it smarter than that and it just re-uses the existing one. (For example, if I do <code>(curried 0)</code>, the <code>((func x) 1)</code> line would be equivalent to <code>(curried 1)</code> - does PLAI Scheme do this?)</p>
[ { "answer_id": 359637, "author": "soegaard", "author_id": 23567, "author_profile": "https://Stackoverflow.com/users/23567", "pm_score": 4, "selected": true, "text": "(define (f x) 42) is short for (define f (lambda (x) 42)) .\n (define ((f x) y) (list x y)) is short for (define (f x) (lambda (y) (list x y)))\n which is short for (define f (lambda (x) (lambda (y) (list x y))))\n" }, { "answer_id": 360244, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "(define ((substitute lv value) e)\n (cond [(LogicVar? e)\n (type-case LogicVar e\n [lv-any (id) (if (symbol=? id (lv-any-id lv))\n value\n e)]\n [lv-cons (f r) \n (lv-cons ((substitute lv value) f)\n ((substitute lv value) r))])]\n [(cons? e)\n (cons ((substitute lv value) (car e))\n ((substitute lv value) (cdr e)))]\n [else e]))\n (define (substitute lv value)\n (local ([define inner\n (lambda (e)\n (cond [(LogicVar? e)\n (type-case LogicVar e\n [lv-any (id) (if (symbol=? id (lv-any-id lv))\n value\n e)]\n [lv-cons (f r) \n (lv-cons (inner f)\n (inner r))])]\n [(cons? e)\n (cons (inner (car e))\n (inner (cdr e)))]\n [else e]))])\n inner))\n (define (substitute lv value)\n (local ([define inner\n (lambda (e)\n (cond [(LogicVar? e)\n (type-case LogicVar e\n [lv-any (id) (if (symbol=? id (lv-any-id lv))\n value\n e)]\n [lv-cons (f r) \n (lv-cons ((substitute lv value) f)\n ((substitute lv value) r))])]\n [(cons? e)\n (cons ((substitute lv value) (car e))\n ((substitute lv value) (cdr e)))]\n [else e]))])\n inner))\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
357,355
<p>I see this in a stack trace:</p> <blockquote> <p>myorg.vignettemodules.customregistration.NewsCategoryVAPDAO.getEmailContentByID(I)Lmyorg/pushemail/model/EmailContent;</p> </blockquote> <p>What does the "<code>(I)L</code>" mean?</p>
[ { "answer_id": 357362, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": true, "text": "int myorg.pushemail.model.EmailContent serialVersionUID Serializable" }, { "answer_id": 357386, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "Z boolean B byte C char S short I int J long F float D double L ; [ V void (I)Lmyorg/pushemail/model/EmailContent; int myorg.pushemail.model.EmailContent" }, { "answer_id": 34760756, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 0, "selected": false, "text": "myorg.vignettemodules.customregistration.NewsCategoryVAPDAO getEmailContentByID int myorg/pushemail/model/EmailContent" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543/" ]
357,363
<p>I'm looking for a macro which can be run to select a consistent range of cells so that I can easily copy them to another spreadsheet. The range would be F3:BJ3.</p>
[ { "answer_id": 357377, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 2, "selected": false, "text": "Public Sub selectCells()\n Range(\"F3:BJ3\").Select\nEnd Sub Public Sub selectCellsAndCopy()\n Range(\"F3:BJ3\").Select\n Selection.Copy\nEnd Sub" }, { "answer_id": 9972614, "author": "Lalit Bhudiya", "author_id": 1304448, "author_profile": "https://Stackoverflow.com/users/1304448", "pm_score": -1, "selected": false, "text": "Sub On_Click()\n ActiveSheet.Range(\"A1:E1\").Select\nEnd Sub\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
357,364
<p>Is a string actually a character array (is-a), or does it have a character array as an internal store (has-a), or is it's own object which can expose itself as a with an array of characters?</p> <p>I am more inclined to say it is it's own object, but then why are we so inclined to always say "A string is an array of characters..."? </p>
[ { "answer_id": 357390, "author": "mmx", "author_id": 33708, "author_profile": "https://Stackoverflow.com/users/33708", "pm_score": 3, "selected": false, "text": "System.String string char[]" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ]
357,370
<p>I would like to store my FreeMarker templates in a database table that looks something like:</p> <pre><code>template_name | template_content --------------------------------- hello |Hello ${user} goodbye |So long ${user} </code></pre> <p>When a request is received for a template with a particular name, this should cause a query to be executed, which loads the relevant template content. This template content, together with the data model (the value of the 'user' variable in the examples above), should then be passed to FreeMarker.</p> <p>However, the <a href="http://freemarker.sourceforge.net/docs/api/index.html" rel="noreferrer">FreeMarker API</a> seems to assume that each template name corresponds to a file of the same name within a particular directory of the filesystem. Is there any way I can easily have my templates loaded from the DB instead of the filesystem?</p> <p><strong>EDIT:</strong> I should have mentioned that I would like to be able to add templates to the database while the application is running, so I can't simply load all templates at startup into a new StringTemplateLoader (as suggested below).</p>
[ { "answer_id": 357508, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 4, "selected": false, "text": "setTemplateLoader()" }, { "answer_id": 357663, "author": "Ulf Lindback", "author_id": 30354, "author_profile": "https://Stackoverflow.com/users/30354", "pm_score": 5, "selected": false, "text": "StringTemplateLoader stringLoader = new StringTemplateLoader();\nString firstTemplate = \"firstTemplate\";\nstringLoader.putTemplate(firstTemplate, freemarkerTemplate);\n// It's possible to add more than one template (they might include each other)\n// String secondTemplate = \"<#include \\\"greetTemplate\\\"><@greet/> World!\";\n// stringLoader.putTemplate(\"greetTemplate\", secondTemplate);\nConfiguration cfg = new Configuration();\ncfg.setTemplateLoader(stringLoader);\nTemplate template = cfg.getTemplate(firstTemplate);\n" }, { "answer_id": 36470320, "author": "Jasper de Vries", "author_id": 880619, "author_profile": "https://Stackoverflow.com/users/880619", "pm_score": 3, "selected": false, "text": "Template public Template(String name,\n String sourceCode,\n Configuration cfg)\n throws IOException\n Template(name, new StringReader(sourceCode), cfg)" }, { "answer_id": 43700491, "author": "Andres", "author_id": 2079513, "author_profile": "https://Stackoverflow.com/users/2079513", "pm_score": 2, "selected": false, "text": "@Entity\npublic class DBTemplate implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @Id\n private long templateId;\n\n private String content; // Here's where the we store the template\n\n private LocalDateTime modifiedOn;\n\n}\n public class TemplateLoaderImpl implements TemplateLoader {\n\n public TemplateLoaderImpl() { }\n\n /**\n * Retrieves the associated template for a given id.\n *\n * When Freemarker calls this function it appends a locale\n * trying to find a specific version of a file. For example,\n * if we need to retrieve the layout with id = 1, then freemarker\n * will first try to load layoutId = 1_en_US, followed by 1_en and\n * finally layoutId = 1.\n * That's the reason why we have to catch NumberFormatException\n * even if it is comes from a numeric field in the database.\n *\n * @param layoutId\n * @return a template instance or null if not found.\n * @throws IOException if a severe error happens, like not being\n * able to access the database.\n */\n @Override\n public Object findTemplateSource(String templateId) throws IOException {\n\n EntityManager em = null;\n\n try {\n long id = Long.parseLong(templateId);\n em = EMF.getInstance().getEntityManager();\n DBTemplateService service = new DBTemplateService(em);\n Optional<DBTemplate> result = service.find(id);\n if (result.isPresent()) {\n return result.get();\n } else {\n return null;\n }\n } catch (NumberFormatException e) {\n return null;\n } catch (Exception e) {\n throw new IOException(e);\n } finally {\n if (em != null && em.isOpen()) {\n em.close();\n }\n }\n }\n\n\n /**\n * Returns the last modification date of a given template.\n * If the item does not exist any more in the database, this\n * method will return Long's MAX_VALUE to avoid freemarker's\n * from recompiling the one in its cache.\n *\n * @param templateSource\n * @return\n */\n @Override\n public long getLastModified(Object templateSource) {\n EntityManager em = null;\n try {\n em = EMF.getInstance().getEntityManager();\n DBTemplateService service = new DBTemplateService(em);\n // Optimize to only retrieve the date\n Optional<DBTemplate> result = service.find(((DBTemplate) templateSource).getTemplateId());\n if (result.isPresent()) {\n return result.get().getModifiedOn().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();\n } else {\n return Long.MAX_VALUE;\n }\n } finally {\n if (em != null && em.isOpen()) {\n em.close();\n }\n }\n }\n\n /**\n * Returns a Reader from a template living in Freemarker's cache.\n */\n @Override\n public Reader getReader(Object templateSource, String encoding) throws IOException {\n return new StringReader(((DBTemplate) templateSource).getContent());\n }\n\n @Override\n public void closeTemplateSource(Object templateSource) throws IOException {\n // Nothing to do here...\n }\n\n}\n ...\nTemplateLoaderImpl loader = new TemplateLoaderImpl();\n\ntemplateConfig = new Configuration(Configuration.VERSION_2_3_25);\ntemplateConfig.setTemplateLoader(loader);\n...\n ...\nlong someId = 3L;\nTemplate template = templateConfig.getTemplate(\"\" + someId);\n...\n <#import \"1\" as layout> <!-- Use a template id. -->\n<@layout.mainLayout>\n...\n <#include \"3\"> <!-- Use a template id. -->\n...\n" }, { "answer_id": 52973795, "author": "Krystian Fiertek", "author_id": 9256512, "author_profile": "https://Stackoverflow.com/users/9256512", "pm_score": 0, "selected": false, "text": "@Configuraton\npublic class FreemarkerConfig {\n\n@Autowired\nTemplateRepository tempRepo;\n\n@Autowired\nTemplateUtils tempUtils;\n\n@Primary\n@Bean \npublic FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() {\n // Create new configuration bean\n FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();\n // Create template loader\n StringTemplateLoader sTempLoader = new StringTemplateLoader();\n // Find all templates\n Iterable<TemplateDb> ite = tempRepo.findAll();\n ite.forEach((template) -> {\n // Put them in loader\n sTempLoader.putTemplate(template.getFilename(), template.getContent()); \n });\n // Set loader\n bean.setPreTemplateLoaders(sTempLoader);\n return bean;\n}\n @Autowired\nprivate Configuration freemarkerConfig;\n\n Template template = freemarkerConfig.getTemplate(templateFilePath);\n String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, mapTemplate);\n" }, { "answer_id": 57510344, "author": "Lucas Basquerotto", "author_id": 4850646, "author_profile": "https://Stackoverflow.com/users/4850646", "pm_score": 2, "selected": false, "text": "<p>Hello <b>${params.user}</b>!</p>\n content <#assign inlineTemplate = content?interpret>\n<@inlineTemplate />\n interpret String content = getFromDatabase(); \nConfiguration cfg = getConfiguration(); \nString filePath = \"dynamic.ftlh\";\n\nMap<String, Object> params = new HashMap<String, Object>();\nparams.put(\"user\", \"World\");\n\nMap<String, Object> root = new HashMap<>();\nroot.put(\"content\", content); \nroot.put(\"params\", params); \n\nTemplate template = cfg.getTemplate(filePath);\n\ntry (Writer out = new StringWriter()) {\n template.process(root, out);\n String result = out.toString();\n System.out.println(result);\n}\n getFromDatabase() getConfiguration() <p>Hello <b>World</b>!</p>\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
357,388
<p>I would class myself as a typical small developer/independant designer and I recently purchased some new hardware for the office and thought I better organise myself better than I have in the past.</p> <p>So I am wondering how you all organise all your files etc so that you can find them easily enough, and relate them together.</p> <p>Currently I have a webserver running on the desktop, and I have a folders called Projects, closed projects, etc and these each contain a folder with the client/website name and it contains their web folders structure. But what do you do with all the other files, typically I receive PSD's, zip files with CSS layouts, images, content documentation, emails, logos, specs, project documentation, PDFs to upload to the site etc.</p> <p>Do you use another single folder (my documents) with a client name for each or is there a better way to keep control of all your client folders.</p> <p>This is aimed particularly at programmers who get lots of information/resources from clients/managers and so I think its an important programming question on how you set yourself up, because a clean setup results in better coding. </p>
[ { "answer_id": 357508, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 4, "selected": false, "text": "setTemplateLoader()" }, { "answer_id": 357663, "author": "Ulf Lindback", "author_id": 30354, "author_profile": "https://Stackoverflow.com/users/30354", "pm_score": 5, "selected": false, "text": "StringTemplateLoader stringLoader = new StringTemplateLoader();\nString firstTemplate = \"firstTemplate\";\nstringLoader.putTemplate(firstTemplate, freemarkerTemplate);\n// It's possible to add more than one template (they might include each other)\n// String secondTemplate = \"<#include \\\"greetTemplate\\\"><@greet/> World!\";\n// stringLoader.putTemplate(\"greetTemplate\", secondTemplate);\nConfiguration cfg = new Configuration();\ncfg.setTemplateLoader(stringLoader);\nTemplate template = cfg.getTemplate(firstTemplate);\n" }, { "answer_id": 36470320, "author": "Jasper de Vries", "author_id": 880619, "author_profile": "https://Stackoverflow.com/users/880619", "pm_score": 3, "selected": false, "text": "Template public Template(String name,\n String sourceCode,\n Configuration cfg)\n throws IOException\n Template(name, new StringReader(sourceCode), cfg)" }, { "answer_id": 43700491, "author": "Andres", "author_id": 2079513, "author_profile": "https://Stackoverflow.com/users/2079513", "pm_score": 2, "selected": false, "text": "@Entity\npublic class DBTemplate implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @Id\n private long templateId;\n\n private String content; // Here's where the we store the template\n\n private LocalDateTime modifiedOn;\n\n}\n public class TemplateLoaderImpl implements TemplateLoader {\n\n public TemplateLoaderImpl() { }\n\n /**\n * Retrieves the associated template for a given id.\n *\n * When Freemarker calls this function it appends a locale\n * trying to find a specific version of a file. For example,\n * if we need to retrieve the layout with id = 1, then freemarker\n * will first try to load layoutId = 1_en_US, followed by 1_en and\n * finally layoutId = 1.\n * That's the reason why we have to catch NumberFormatException\n * even if it is comes from a numeric field in the database.\n *\n * @param layoutId\n * @return a template instance or null if not found.\n * @throws IOException if a severe error happens, like not being\n * able to access the database.\n */\n @Override\n public Object findTemplateSource(String templateId) throws IOException {\n\n EntityManager em = null;\n\n try {\n long id = Long.parseLong(templateId);\n em = EMF.getInstance().getEntityManager();\n DBTemplateService service = new DBTemplateService(em);\n Optional<DBTemplate> result = service.find(id);\n if (result.isPresent()) {\n return result.get();\n } else {\n return null;\n }\n } catch (NumberFormatException e) {\n return null;\n } catch (Exception e) {\n throw new IOException(e);\n } finally {\n if (em != null && em.isOpen()) {\n em.close();\n }\n }\n }\n\n\n /**\n * Returns the last modification date of a given template.\n * If the item does not exist any more in the database, this\n * method will return Long's MAX_VALUE to avoid freemarker's\n * from recompiling the one in its cache.\n *\n * @param templateSource\n * @return\n */\n @Override\n public long getLastModified(Object templateSource) {\n EntityManager em = null;\n try {\n em = EMF.getInstance().getEntityManager();\n DBTemplateService service = new DBTemplateService(em);\n // Optimize to only retrieve the date\n Optional<DBTemplate> result = service.find(((DBTemplate) templateSource).getTemplateId());\n if (result.isPresent()) {\n return result.get().getModifiedOn().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();\n } else {\n return Long.MAX_VALUE;\n }\n } finally {\n if (em != null && em.isOpen()) {\n em.close();\n }\n }\n }\n\n /**\n * Returns a Reader from a template living in Freemarker's cache.\n */\n @Override\n public Reader getReader(Object templateSource, String encoding) throws IOException {\n return new StringReader(((DBTemplate) templateSource).getContent());\n }\n\n @Override\n public void closeTemplateSource(Object templateSource) throws IOException {\n // Nothing to do here...\n }\n\n}\n ...\nTemplateLoaderImpl loader = new TemplateLoaderImpl();\n\ntemplateConfig = new Configuration(Configuration.VERSION_2_3_25);\ntemplateConfig.setTemplateLoader(loader);\n...\n ...\nlong someId = 3L;\nTemplate template = templateConfig.getTemplate(\"\" + someId);\n...\n <#import \"1\" as layout> <!-- Use a template id. -->\n<@layout.mainLayout>\n...\n <#include \"3\"> <!-- Use a template id. -->\n...\n" }, { "answer_id": 52973795, "author": "Krystian Fiertek", "author_id": 9256512, "author_profile": "https://Stackoverflow.com/users/9256512", "pm_score": 0, "selected": false, "text": "@Configuraton\npublic class FreemarkerConfig {\n\n@Autowired\nTemplateRepository tempRepo;\n\n@Autowired\nTemplateUtils tempUtils;\n\n@Primary\n@Bean \npublic FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() {\n // Create new configuration bean\n FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();\n // Create template loader\n StringTemplateLoader sTempLoader = new StringTemplateLoader();\n // Find all templates\n Iterable<TemplateDb> ite = tempRepo.findAll();\n ite.forEach((template) -> {\n // Put them in loader\n sTempLoader.putTemplate(template.getFilename(), template.getContent()); \n });\n // Set loader\n bean.setPreTemplateLoaders(sTempLoader);\n return bean;\n}\n @Autowired\nprivate Configuration freemarkerConfig;\n\n Template template = freemarkerConfig.getTemplate(templateFilePath);\n String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, mapTemplate);\n" }, { "answer_id": 57510344, "author": "Lucas Basquerotto", "author_id": 4850646, "author_profile": "https://Stackoverflow.com/users/4850646", "pm_score": 2, "selected": false, "text": "<p>Hello <b>${params.user}</b>!</p>\n content <#assign inlineTemplate = content?interpret>\n<@inlineTemplate />\n interpret String content = getFromDatabase(); \nConfiguration cfg = getConfiguration(); \nString filePath = \"dynamic.ftlh\";\n\nMap<String, Object> params = new HashMap<String, Object>();\nparams.put(\"user\", \"World\");\n\nMap<String, Object> root = new HashMap<>();\nroot.put(\"content\", content); \nroot.put(\"params\", params); \n\nTemplate template = cfg.getTemplate(filePath);\n\ntry (Writer out = new StringWriter()) {\n template.process(root, out);\n String result = out.toString();\n System.out.println(result);\n}\n getFromDatabase() getConfiguration() <p>Hello <b>World</b>!</p>\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
357,396
<p>I have two classes: Media and Container.</p> <p>I have two lists <code>List&lt;Media&gt;</code> and <code>List&lt;Container&gt;</code></p> <p>I'm passing these lists to another function (one at a time);</p> <p>it can be one or another; </p> <p>what's the proper way to check for the "template" type of the list so i can call an asssociated method depending on the list type?</p> <p>or should i just try casting to the List&lt;> and put Try/Catch blocks around it ?</p> <pre><code> Object tagObj = mediaFlow1.BackButton.Tag; if (tagObj == Media) //do this else if (tagObj == Container) //do this else throw new Exception("Not a recognized type"); </code></pre>
[ { "answer_id": 357407, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": false, "text": "public void MyMethod(List<Media> source)\n{\n //do stuff with a Media List\n}\n\npublic void MyMethod(List<Container> source)\n{\n //do stuff with a Container List\n}\n" }, { "answer_id": 357416, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "typeof" }, { "answer_id": 357473, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "public interface ICanDoThis { void DoThis(); }\n public class Media: ICanDoThis { // }\npublic class Container: ICanDoThis { // }\n public void OtherFunction(List<ICanDoThis> list)\n {\n foreach(ICanDoThis obj in list)\n obj.DoThis();\n }\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33082/" ]
357,399
<p>I have a import directive in my inline .aspx page (no code-behind).</p> <p>Getting an error: The type or namespace name 'Dts' does not exist in the namespace 'Microsoft.SqlServer' (are you missing an assembly reference?)</p> <p>What is the issue? Do I need a /bin directory with the .dll in it or something?</p>
[ { "answer_id": 357430, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<%@ Assembly > <%@ Assembly Name=\"microsoft.sqlserver.manageddts.dll\" %>\n<%@ Import namespace=\"Microsoft.SqlServer.Dts.Runtime\" %>\n" }, { "answer_id": 811406, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<%@ Assembly Name=\"System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" %>\n<%@ Import Namespace=\"System.Data.OracleClient\" %>\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
357,404
<p>I just joined a new C++ software project and I'm trying to understand the design. The project makes frequent use of unnamed namespaces. For example, something like this may occur in a class definition file:</p> <pre><code>// newusertype.cc namespace { const int SIZE_OF_ARRAY_X; const int SIZE_OF_ARRAY_Y; bool getState(userType*,otherUserType*); } newusertype::newusertype(...) {... </code></pre> <p>What are the design considerations that might cause one to use an unnamed namespace? What are the advantages and disadvantages?</p>
[ { "answer_id": 357427, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 7, "selected": false, "text": "static namespace __unique_compiler_generated_identifer0x42 {\n ...\n}\nusing namespace __unique_compiler_generated_identifer0x42;\n" }, { "answer_id": 357464, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 9, "selected": true, "text": "namespace unique { /* empty */ }\nusing namespace unique;\nnamespace unique { /* namespace body. stuff in here */ }\n ::name help static namespace { int a1; }\nstatic int a2;\n a a1" }, { "answer_id": 1178977, "author": "Marc Mutz - mmutz", "author_id": 134841, "author_profile": "https://Stackoverflow.com/users/134841", "pm_score": 4, "selected": false, "text": "namespace {\n const int SIZE_OF_ARRAY_X;\n const int SIZE_OF_ARRAY_Y;\n const bool getState(userType*,otherUserType*);\n}\n getState() static bool getState(/*...*/);\n" }, { "answer_id": 25565298, "author": "xioxox", "author_id": 351771, "author_profile": "https://Stackoverflow.com/users/351771", "pm_score": 4, "selected": false, "text": "#include <iostream>\n\nnamespace {\n double a;\n void b(double x)\n {\n a -= x;\n }\n void add_val(double x)\n {\n a += x;\n if(x==0.01) b(0);\n if(x==0.02) b(0.6);\n if(x==0.03) b(-0.1);\n if(x==0.04) b(0.4);\n }\n}\n\nint main()\n{\n a = 0;\n for(int i=0; i<1000000000; ++i)\n {\n add_val(i*1e-10);\n }\n std::cout << a << '\\n';\n return 0;\n}\n" }, { "answer_id": 37466922, "author": "Sachin", "author_id": 4685453, "author_profile": "https://Stackoverflow.com/users/4685453", "pm_score": 5, "selected": false, "text": "static static static static static int x; // Correct \n static class xyz {/*Body of class*/} //Wrong\nstatic structure {/*Body of structure*/} //Wrong\n namespace {\n class xyz {/*Body of class*/}\n static structure {/*Body of structure*/}\n } //Correct\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6688/" ]
357,410
<p>Is there a way to bypass the following IE popup box:</p> <blockquote> <p>The webapge you are viewing is trying to close the window. Do you want to close this window? Yes|No</p> </blockquote> <p>This is occurring when I add window.close() to the onclick event of an asp.net button control.</p>
[ { "answer_id": 357588, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 3, "selected": false, "text": "window.open('close.html', '_self');\n <script>window.close();</script>\n" }, { "answer_id": 8135456, "author": "d-coder", "author_id": 900390, "author_profile": "https://Stackoverflow.com/users/900390", "pm_score": 5, "selected": false, "text": "var objWin = window.self;\nobjWin.open('','_self','');\nobjWin.close();\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
357,415
<p>I'm sure this is really simple if you know anything about binary files, but I'm a newbie on that score.</p> <p>How would I extract the data from NASA .hgt files? Here is a description from www2.jpl.nasa.gov/srtm/faq.html:</p> <blockquote> <p><b>The SRTM data files have names like "N34W119.hgt". What do the letters and numbers refer to, and what is ".hgt" format?</b></p> <p>Each data file covers a one-degree-of-latitude by one-degree-of-longitude block of Earth's surface. The first seven characters indicate the southwest corner of the block, with N, S, E, and W referring to north, south, east, and west. Thus, the "N34W119.hgt" file covers latitudes 34 to 35 North and longitudes 118-119 West (this file includes downtown Los Angeles, California). The filename extension ".hgt" simply stands for the word "height", meaning elevation. It is NOT a format type. These files are in "raw" format (no headers and not compressed), 16-bit signed integers, elevation measured in meters above sea level, in a "geographic" (latitude and longitude array) projection, with data voids indicated by -32768. International 3-arc-second files have 1201 columns and 1201 rows of data, with a total filesize of 2,884,802 bytes ( = 1201 x 1201 x 2). United States 1-arc-second files have 3601 columns and 3601 rows of data, with a total filesize of 25,934,402 bytes ( = 3601 x 3601 x 2). For more information read the text file "SRTM_Topo.txt" at http://edcftp.cr.usgs.gov/pub/data/srtm/Readme.html</p> </blockquote> <p>Thanks for any help! I am going to use this data in a python script, so if you could not use any language-specific tricks for any other languages, that would be awesome.</p>
[ { "answer_id": 357469, "author": "codelogic", "author_id": 43427, "author_profile": "https://Stackoverflow.com/users/43427", "pm_score": 3, "selected": false, "text": "from struct import unpack,calcsize\n\n# 'row_length' being 1201 or 3601 and 'row' being the raw data for one row\ndef read_row( row, row_length ):\n format = 'h' # h stands for signed short\n\n for i in range(0, row_length):\n offset = i * calcsize(format)\n (height,) = unpack(format, row[offset : offset+calcsize(format))\n # do something with the height\n" }, { "answer_id": 14625237, "author": "user532954", "author_id": 532954, "author_profile": "https://Stackoverflow.com/users/532954", "pm_score": 3, "selected": false, "text": "from array import array\n\nf = open(filename, 'rb')\nformat = 'h'\nrow_length = 1201\ndata = array(format)\ndata.fromfile(f, row_length*row_length)\ndata.byteswap()\nf.close()\n" }, { "answer_id": 17095113, "author": "hruske", "author_id": 478237, "author_profile": "https://Stackoverflow.com/users/478237", "pm_score": 4, "selected": false, "text": "import os\nimport math\nimport numpy\n\nfn = 'DMV/N51E000.hgt'\n\nsiz = os.path.getsize(fn)\ndim = int(math.sqrt(siz/2))\n\nassert dim*dim*2 == siz, 'Invalid file size'\n\ndata = numpy.fromfile(fn, numpy.dtype('>i2'), dim*dim).reshape((dim, dim))\n" }, { "answer_id": 57413000, "author": "Ramesh K Banagar", "author_id": 8158404, "author_profile": "https://Stackoverflow.com/users/8158404", "pm_score": 1, "selected": false, "text": " Input_HGT = 'N30E120.hgt'\n import gdal\n Raster = gdal.Open(Input_HGT) \n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
357,421
<p>I have an Array of Objects that need the duplicates removed/filtered. I was going to just override equals &amp; hachCode on the Object elements, and then stick them in a Set... but I figured I should at least poll stackoverflow to see if there was another way, perhaps some clever method of some other API?</p>
[ { "answer_id": 357444, "author": "brabster", "author_id": 2362, "author_profile": "https://Stackoverflow.com/users/2362", "pm_score": 5, "selected": true, "text": "hashCode() equals() Set" }, { "answer_id": 357446, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 0, "selected": false, "text": "Set" }, { "answer_id": 357449, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 2, "selected": false, "text": "equals hashCode LinkedHashSet" }, { "answer_id": 357454, "author": "Markus Lausberg", "author_id": 39062, "author_profile": "https://Stackoverflow.com/users/39062", "pm_score": 3, "selected": false, "text": "/** List order not maintained **/\npublic static void removeDuplicate(ArrayList arlList)\n{\n HashSet h = new HashSet(arlList);\n arlList.clear();\n arlList.addAll(h);\n}\n /** List order maintained **/\npublic static void removeDuplicateWithOrder(ArrayList arlList)\n{\n Set set = new HashSet();\n List newList = new ArrayList();\n for (Iterator iter = arlList.iterator(); iter.hasNext();) {\n Object element = iter.next();\n if (set.add(element))\n newList.add(element);\n }\n arlList.clear();\n arlList.addAll(newList);\n}\n" }, { "answer_id": 357459, "author": "TravisO", "author_id": 35116, "author_profile": "https://Stackoverflow.com/users/35116", "pm_score": 0, "selected": false, "text": "foreach ( array as source )\n{\n // keep track where we are in the array\n place++;\n // loop the array starting at the entry AFTER the current one we are comparing to\n for ( i=place+1; i < max(array); i++ )\n {\n if ( source === array[place] )\n {\n destroy(array[i]);\n }\n }\n}\n" }, { "answer_id": 357710, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 1, "selected": false, "text": "Set SortedSet LinkedHashSet" }, { "answer_id": 357772, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 1, "selected": false, "text": "Map<CustomObject, Integer>" }, { "answer_id": 358102, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 2, "selected": false, "text": "LinkedHashSet<T> List<T> public class LinkedHashSetList<T> extends LinkedHashSet<T> implements List<T> { // Implementations for List<T> methods here ... } List<T> LinkedHashSet<T> List<T>" }, { "answer_id": 11094123, "author": "didxga", "author_id": 231010, "author_profile": "https://Stackoverflow.com/users/231010", "pm_score": 2, "selected": false, "text": " distinctList iterator private List removeDups(List list) {\n Set tempSet = new HashSet();\n List distinctList = new ArrayList();\n for(Iterator it = list.iterator(); it.hasNext();) {\n Object next = it.next();\n if(tempSet.add(next)) {\n distinctList.add(next);\n } \n }\n return distinctList;\n } \n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32142/" ]
357,425
<p>I have several Models and want to return a queryset of all the Models belonging to a User, I'm wondering if its possible to return one Queryset from multiple Models?</p>
[ { "answer_id": 361340, "author": "Wayne Werner", "author_id": 4080, "author_profile": "https://Stackoverflow.com/users/4080", "pm_score": 4, "selected": true, "text": "qs = getattr(user, '%s_set' % model_name.lower());\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041708/" ]
357,440
<p>I imagine I can compile a C# DLL and then expose it as a COM object so that it can be CreateObject'd from VBscript. I'm just not sure the steps involved in doing this...</p>
[ { "answer_id": 357456, "author": "mmx", "author_id": 33708, "author_profile": "https://Stackoverflow.com/users/33708", "pm_score": 3, "selected": false, "text": "regasm regsvr32 [ComVisible(true)]" }, { "answer_id": 357458, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "Properties Application Assembly Information..." }, { "answer_id": 357682, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 4, "selected": true, "text": "regasm /codebase regasm Guid MarshalAs InterfaceType" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245/" ]
357,445
<p>I'm trying to debug the MSBuild Customtask, that I have just created, but for some reason it never stops at the breakpoint. I've even tried this:</p> <pre><code> public override bool Execute() { System.Diagnostics.Debugger.Break(); </code></pre> <p>And added a break point on that line... I even eliminated all the other code in the method and that didn't change anything.</p> <p>Is there anything special required to be able to debug the creation of custom tasks for MSBuild ?</p>
[ { "answer_id": 357544, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 6, "selected": true, "text": "System.Diagnostics.Debugger.Launch();\n" }, { "answer_id": 69756244, "author": "Rainer Sigwald", "author_id": 145200, "author_profile": "https://Stackoverflow.com/users/145200", "pm_score": 2, "selected": false, "text": "MSBUILDDEBUGONSTART=1 MSBuild.exe Debugger.Launch() -m -m:1" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17787/" ]
357,447
<p>I think the direct answer to the question is 'No' but I'm hoping that someone has written a real simple library to do this (or I can do it...ugh...)</p> <p>Let me demonstrate what I am looking for with an example. Suppose I had the following:</p> <pre><code>class Person { string Name {get; set;} int NumberOfCats {get; set;} DateTime TimeTheyWillDie {get; set;} } </code></pre> <p>I would like to be able to do something like this:</p> <pre><code>static void Main() { var p1 = new Person() {Name="John", NumberOfCats=0, TimeTheyWillDie=DateTime.Today}; var p2 = new Person() {Name="Mary", NumberOfCats=50, TimeTheyWIllDie=DateTime.Max}; var str = String.Format( "{0:Name} has {0:NumberOfCats} cats and {1:Name} has {1:NumberOfCats} cats. They will die {0:TimeTheyWillDie} and {1:TimeTheyWillDie} respectively ", p1, p2); Console.WriteLine(str); } </code></pre> <p>Does anyone know if theres a format for doing something like this or if someone has written a library to do it? I know it shouldn't be too hard, but I'd rather not be reimplementing the wheel.</p>
[ { "answer_id": 357462, "author": "Paolo Tedesco", "author_id": 15622, "author_profile": "https://Stackoverflow.com/users/15622", "pm_score": 2, "selected": false, "text": "class Person : IFormattable\n{\n public override string ToString()\n {\n return \"Person\";\n }\n\n public string ToString(string format, IFormatProvider formatProvider)\n {\n if (format == \"Name\")\n {\n return \"John\";\n }\n if (format == \"NumberOfCats\")\n {\n return \"12\";\n }\n return \"Unknown format string\";\n }\n\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Person p = new Person();\n Console.WriteLine(string.Format(\"Name = {0:Name}\",p));\n Console.WriteLine(string.Format(\"NumberOfCats = {0:NumberOfCats}\", p));\n }\n}\n" }, { "answer_id": 357471, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\"{0:Name} has {0:NumberOfCats} cats and {1:Name} has {1:NumberOfCats} cats. They will die {0:TimeTheyWillDie} and {1:TimeTheyWillDie} respectively\", p1, p2);\n \"{0} has {1} cats and {2} has {3} cats. They will die {4} and {5} respectively\n\", p1.Name, p1.NumberOfCats, p2.Name, p2.NumberOfCats, p1.TimeTheyWillDie, p2.TimeTheyWillDie);\n" }, { "answer_id": 357489, "author": "mookid8000", "author_id": 6560, "author_profile": "https://Stackoverflow.com/users/6560", "pm_score": 0, "selected": false, "text": "var person = new Person { Name = \"joe\", Email = new Email { Address = \"joe@joe.com\" } };\n\nvar message = string.Format(\"{0}'s e-mail is {1}\",\n ExpressionEvaluator.GetValue(person, \"Name\"), \n ExpressionEvaluator.GetValue(person, \"Email.Address\"));\n" }, { "answer_id": 357780, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "public class ReflectionFormatProvider : IFormatProvider, ICustomFormatter {\n public object GetFormat(Type formatType) {\n return formatType == typeof(ICustomFormatter) ? this : null;\n }\n\n public string Format(string format, object arg, IFormatProvider formatProvider) {\n string[] formats = (format ?? string.Empty).Split(new char[] { ':' }, 2);\n string propertyName = formats[0].TrimEnd('}');\n string suffix = formats[0].Substring(propertyName.Length);\n string propertyFormat = formats.Length > 1 ? formats[1] : null;\n\n PropertyInfo pi = arg.GetType().GetProperty(propertyName);\n if (pi == null || pi.GetGetMethod() == null) {\n // Pass thru\n return (arg is IFormattable) ? \n ((IFormattable)arg).ToString(format, formatProvider) \n : arg.ToString();\n }\n\n object value = pi.GetGetMethod().Invoke(arg, null);\n return (propertyFormat == null) ? \n (value ?? string.Empty).ToString() + suffix\n : string.Format(\"{0:\" + propertyFormat + \"}\", value);\n }\n}\n var p1 = new Person() {Name=\"John\", NumberOfCats=0, TimeTheyWillDie=DateTime.Today};\nvar p2 = new Person() {Name=\"Mary\", NumberOfCats=50, TimeTheyWillDie=DateTime.MaxValue};\n\nvar str = string.Format(\n new ReflectionFormatProvider(),\n @\"{0:Name} has {0:NumberOfCats} cats and {1:Name} has {1:NumberOfCats} cats. \n They will die {0:TimeTheyWillDie:MM/dd/yyyy} and {1:TimeTheyWillDie} respectively.\n This is a currency: {2:c2}.\", \n p1, \n p2,\n 8.50M\n);\n\nConsole.WriteLine(str);\n John has 0 cats and Mary has 50 cats. \nThey will die 12/10/2008 and 12/31/9999 11:59:59 PM respectively.\nThis is a currency: $8.50.\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
357,461
<p>Does anyone know of any eclipe plugin that lets you easily change and use file encodings? I sometimes need to edit template files to do small tweaks, but the files are sometimes ISO, sometimes UTF8, sometimes others, so using eclipse for this leads to disaster :)</p>
[ { "answer_id": 14571816, "author": "Smair", "author_id": 2019711, "author_profile": "https://Stackoverflow.com/users/2019711", "pm_score": 4, "selected": false, "text": "ctrl+c cmd+c ctrl-a cmd-a ctrl-v cmd-v" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21240/" ]
357,465
<p>Is there a way where I can add a connection string to the ConnectionStringCollection returned by the ConfigurationManager at runtime in an Asp.Net application?</p> <p>I have tried the following but am told that the configuration file is readonly.</p> <pre><code>ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings(params)); </code></pre> <p>Is there another way to do this at runtime? I know at design time I can add a connection string to the web.config; however, I'm looking to add something to that collection at run time.</p> <p>Thanks</p> <p>EDIT: One of the reasons why I'm attempting to do this is due to a security requirement that prevents me from placing ConnectionStrings in the web.config (even encrypted). I would like to use elements like Membership and Profiles on my project; however, I am looking into an alternative to doing such w/o writing a custom provider. Custom Provider's aren't all that bad, but if I can find an easier solution, I'm all for it.</p>
[ { "answer_id": 357558, "author": "joshperry", "author_id": 30587, "author_profile": "https://Stackoverflow.com/users/30587", "pm_score": 3, "selected": false, "text": "class ConnectionStringProvider\n{\n Dictionary<string, System.Configuration.ConnectionStringSettings> _localStrings = new Dictionary<string, System.Configuration.ConnectionStringSettings>();\n\n public void AddLocalConnectionString(string name, string connstring)\n {\n System.Configuration.ConnectionStringSettings cs = new System.Configuration.ConnectionStringSettings(name, connstring);\n _localStrings.Add(name, cs);\n }\n\n public void RemoveLocalConnectionString(string name)\n {\n _localStrings.Remove(name);\n }\n\n public System.Configuration.ConnectionStringSettings this[string name] {\n get \n { \n return _localStrings.ContainsKey(name) ? _localStrings[name] : System.Configuration.ConfigurationManager.ConnectionStrings[name]; \n }\n }\n}\n" }, { "answer_id": 357570, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 5, "selected": true, "text": "var cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(@\"/\");\ncfg.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(params));\n\ncfg.Save();\n" }, { "answer_id": 357589, "author": "Scott Isaacs", "author_id": 1664, "author_profile": "https://Stackoverflow.com/users/1664", "pm_score": 2, "selected": false, "text": "ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings(params));\n ConfigurationManager.ConnectionStrings[\"myconnection\"].ConnectionString = \"something\";\n <add name=\"myconnection\" connectionString=\"SET AT RUNTIME\" ... />\n" }, { "answer_id": 358238, "author": "joshperry", "author_id": 30587, "author_profile": "https://Stackoverflow.com/users/30587", "pm_score": 1, "selected": false, "text": "aspnet_regiis -pe \"connectionStrings\" -app \"/MyCoolWebApplication\" -prov \"DataProtectionConfigurationProvider\"\n" }, { "answer_id": 8494274, "author": "user423430", "author_id": 423430, "author_profile": "https://Stackoverflow.com/users/423430", "pm_score": 5, "selected": false, "text": "typeof(ConfigurationElementCollection)\n .GetField(\"bReadOnly\", BindingFlags.Instance | BindingFlags.NonPublic)\n .SetValue(ConfigurationManager.ConnectionStrings, false);\nConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings());\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28540/" ]
357,470
<p>I am in charge of providing a theme functionality for a site using a big CSS file (thousands of elements) I've just inherited. Basically we want to allow the user to be able to change the colors on the screen.</p> <p>Every CSS element, besides color definition also have lots of other attributes - size, font, float, etc... As well a specific color appears in various CSS elements.</p> <p>If I use the Theme functionality of ASP.NET to have a different CSS file per theme, I have to duplicate my CSS file across all the themes, and it becomes a maintenance nightmare. </p> <p>Optimally I would like to have a single CSS file (for maintenance) and be able to change the color attributes only.</p> <p>What are the options here?</p>
[ { "answer_id": 357484, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 3, "selected": true, "text": "a:hover\n{\n text-decoration:none;\n color:Black;\n display:block \n}\n a:hover\n{\n color:Red;\n}\n" }, { "answer_id": 357494, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 1, "selected": false, "text": "<body class=\"dark\">\n <a ...>some text</a>\n</body>\n /* default */\nbody { color:white }\n a { color:blue }\n\n/* dark theme */\nbody.dark { color:black }\n .dark a { color:white }\n" }, { "answer_id": 357531, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": ".DefaultBackgroundColor { background-color: white; }\n\n.PrimaryColor { background-color: #123456; }\n.PrimaryAsForeground { color: #123456; }\n\n.AccentColor { background-color: #654321; }\n.AccentAsForeground { color: #654321; }\n\n.ComplementColor { background-color: #333333; }\n.ComplementAsForeground { color: #333333; }\n\n.DefaultTextColor { color:black; }\n.HighlightTextColor { color:black; font-style:bold; }\n.ComplementTextColor { color:white; }\n <div class=\"nav ComplementTextColor\">\n <ul class=\"primarynav\">\n <li class=\"PrimaryColor\"><a href=\"/questions\">Questions</a></li> <!-- selected -->\n <li class=\"ComplementColor\"><a href=\"/tags\">Tags</a></li>\n <li class=\"ComplementColor\"><a href=\"/users\">Users</a></li> \n <li class=\"ComplementColor\"><a href=\"/badges\">Badges</a></li>\n <li class=\"ComplementColor\"><a href=\"/unanswered\">Unanswered</a></li>\n </ul>\n</div>\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37955/" ]
357,481
<p>I'm trying to write a 2d array into an output file, it's all working fine except in creating the .getline function to draw the array back out of the file. My issue is putting the string length. My current code for the line is;</p> <p>inputFile.getline(myArray, [10][10], '\n');</p> <p>but it doesn't like having the string length in square brackets it seems, what should I do?</p> <p>thanks in advance</p>
[ { "answer_id": 357551, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": true, "text": "myArray char char* std::istream::getline char" }, { "answer_id": 361362, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 0, "selected": false, "text": " inputFile.write( (const char *)myArray, sizeof(myArray) );\n inputFile.read( (char *)myArray, sizeof(myArray) );\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33061/" ]
357,491
<p>I would like to verify that an app I am writing is running on an iPhone. What would be perfect is this: Apple baked an SSL client certificate into each iphone which can be authenticated by a receiving server. I this the case?</p> <p>I have not started researching this yet, I will update with anything I find.</p> <p>UPDATE: <a href="http://developer.apple.com/DOCUMENTATION/Security/Conceptual/SecureCodingGuide/Articles/SecuritySvcs.html" rel="nofollow noreferrer">Here</a> is some Apple documentation on certificates and keychains. So:</p> <blockquote> <p>In iPhone OS, Keychain Services checks an application’s signature before giving it access to a keychain, and lets an application have access only to its own keychain items (with the possible exception of items for which the application has obtained persistent references). In iPhone OS, the user is never asked to authenticate and no Keychain Access utility is provided by Apple.</p> </blockquote>
[ { "answer_id": 358218, "author": "Rob", "author_id": 386102, "author_profile": "https://Stackoverflow.com/users/386102", "pm_score": 0, "selected": false, "text": "NSMutableURLRequest *request;\nNSMutableDictionary *headers;\nheaders = [[[NSMutableDictionary allocWithZone:[self zone]] init] autorelease];\n[headers setValue:@\"YourApp/1.0 (iPhone)\" forKey:@\"User-Agent\"];\n[request setAllHTTPHeaderFields:headers];\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30541/" ]
357,499
<p>I am trying to create a simple page that enters data in to a database and my code is below.</p> <pre><code>&lt;%@ LANGUAGE="VBSCRIPT" %&gt; &lt;% Option Explicit %&gt; &lt;!--#include FILE=dbcano.inc--&gt; &lt;% dim username,password,f_name,l_name,objConn,objs,query username = Request.Form("user") password = Request.Form("pass") f_name = Request.Form("fname") l_name = Request.Form("lname") if((f_name &lt;&gt; null) or (f_name &lt;&gt; "")) then response.redirect("patti_account.asp") else Set objConn = ConnectDB() query = "INSERT INTO user (username,password,f_name,l_name) VALUES ('"&amp; username &amp;"','"&amp; password &amp;"','"&amp; f_name &amp;"','"&amp; l_name &amp;"')" Set objs = objConn.Execute(query) Response.Redirect ("thankyou.asp") end if %&gt; </code></pre> <p>I am getting this error when I run my page:</p> <blockquote> <p>Microsoft OLE DB Provider for SQL Server error '80040e14'</p> <p>Incorrect syntax near the keyword 'user'.</p> <p>create_account.asp, line 18</p> </blockquote> <p>I have checked everything, my field names exist and my table name is correct as well.</p> <p>Any suggestions?</p>
[ { "answer_id": 357525, "author": "Scott Isaacs", "author_id": 1664, "author_profile": "https://Stackoverflow.com/users/1664", "pm_score": 0, "selected": false, "text": "query = \"INSERT INTO [user] (username,password,f_name,l_name) VALUES ('\"& username &\"','\"& password &\"','\"& f_name &\"','\"& l_name &\"')\"\n" }, { "answer_id": 357615, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "');DROP Table [user];--\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
357,500
<p>I can't create a NT account for everyone that need access to the reports. Does anyone know or have a link to the info to allow anonymous access to reporting services reports ?</p> <p>Thanks</p>
[ { "answer_id": 6976820, "author": "Adam Butler", "author_id": 417721, "author_profile": "https://Stackoverflow.com/users/417721", "pm_score": 0, "selected": false, "text": "Domain Users" }, { "answer_id": 10329807, "author": "Fasil", "author_id": 1358147, "author_profile": "https://Stackoverflow.com/users/1358147", "pm_score": 0, "selected": false, "text": "SSRS 2008 RSWindowsKerberos RSWindowsNegotiate RSWindowsNTLM" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6704/" ]
357,505
<p>I have a web forum that I have coded in Python for the App Engine platform. I have noticed that it is not being indexed well by Google and I am trying to fix that.<br> I have used Google Webmaster to submit a sitemap with almost 400 URLs but apparently only 8 were indexed!<br> I even get a warning stating:</p> <blockquote> <p>All the URLs in your Sitemap are marked as having dynamic content (the value of is "always"). Because dynamic content is difficult for search engines to crawl and index, this may impact your site's performance in search results. Check your Sitemap to make sure your site information is correct.</p> </blockquote> <p>One thing I am considering is the way my URLs are formed. Almost all URLs use arguments and I allocate each post, thread, forum, user etc... an ID.</p> <p>So for example one of my forums is:</p> <p><a href="http://silicon.appspot.com/readforum?id=2075" rel="nofollow noreferrer">http://silicon.appspot.com/readforum?id=2075</a></p> <p>Where the forum's ID is 2075. I have heard this is bad practice so I am considering changing this but I am not sure whether it will make any difference. Could someone give me some hints in relation to how to get Google to index my <em>entire</em> site?</p>
[ { "answer_id": 357624, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 1, "selected": true, "text": " http://www.example.com/forum.py?thread=1000\n http://www.example.com/forum.py?thread=1000&mode=printer\n" }, { "answer_id": 487087, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 0, "selected": false, "text": "site:silicon.appspot.com\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
357,537
<p>I have a class Pkg and I need to use it under form of QVariant. </p> <p>At the end of my Pkg.h I have:</p> <pre><code>Q_DECLARE_METATYPE(Pkg) </code></pre> <p>and this does not give compile errors, but in my main.cpp I have to do:</p> <pre><code>qRegisterMetaType&lt;Pkg&gt;("Pkg"); </code></pre> <p>and this does not give errors too, but when I try to create a QVariant(Pkg) I get lots of errors like:</p> <pre><code>In member function 'void MainWindow::FillPackagesList()': mainWin.cpp:233: error: 'qRegisterMetaType' isnot a member of 'QMetaType' mainWin.cpp:234: error: no matching function for call to QVariant::QVariant(Pkg&amp;)' /usr/lib/qt/include/QtCore/qvariant.h:208: note: QVariant::QVariant(Qt::GlobalColor) /usr/lib/qt/include/QtCore/qvariant.h:206: note: QVariant::QVariant(const QRegExp&amp;) /usr/lib/qt/include/QtCore/qvariant.h:204: note: QVariant::QVariant(const QLocale&amp;) /usr/lib/qt/include/QtCore/qvariant.h:203: note: QVariant::QVariant(const QUrl&amp;) /usr/lib/qt/include/QtCore/qvariant.h:201: note: QVariant::QVariant(const QRectF&amp;) /usr/lib/qt/include/QtCore/qvariant.h:200: note: QVariant::QVariant(const QRect&amp;) </code></pre> <p>and errors over errors again...</p>
[ { "answer_id": 360503, "author": "JuanDeLosMuertos", "author_id": 39339, "author_profile": "https://Stackoverflow.com/users/39339", "pm_score": 0, "selected": false, "text": " item->data(1,Qt::UserRole).value<Pkg>();\n connect(packList,SIGNAL(itemClicked(QTreeWidgetItem*, int)), SLOT(setActualPackage(QTreeWidgetItem*)));\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39339/" ]
357,543
<p>Working on an app with notification via e-mail. I'd like to run test with out sending e-mails to production servers and clients. A couple years ago I remember someone bringing down our exchange server with a bad e-mail loop and would prefer to not repeat... </p> <p>Any suggestion for a dev setup? Currently think a simple SMTP server will do the job but I'm not familiar with that space. I would need the ability to see all the emails sent to the server but they should never be delivered.</p> <p>Thanks.</p>
[ { "answer_id": 358133, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 1, "selected": false, "text": "MessageSender EmailMessageSender FileMessageSender EmailMessageSender MessageSender FileMessageSender FileMessageSender EmailMessageSender" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293/" ]
357,560
<p>I have potentially large files that need to be sorted by 1-n keys. Some of these keys might be numeric and some of them might not be. This is a fixed-width columnar file so there are no delimiters.</p> <p>Is there a good way to do this with Unix sort? With one key it is as simple as using '-n'. I have read the man page and searched Google briefly, but didn't find a good example. How would I go about accomplishing this?</p> <p>Note: I have ruled out Perl because of the file size potential. It would be a last resort.</p>
[ { "answer_id": 357582, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 7, "selected": true, "text": "-k --key=POS1[,POS2] n" }, { "answer_id": 357603, "author": "Clinton Pierce", "author_id": 8173, "author_profile": "https://Stackoverflow.com/users/8173", "pm_score": 7, "selected": false, "text": "-k 1.4,1.5n -k 1.14,1.15n\n dir | \\cygwin\\bin\\sort.exe -k 1.4,1.5n -k 1.40,1.60r\n 12/10/2008 01:10 PM 1,564,990 outfile.txt\n" }, { "answer_id": 357625, "author": "Dong Hoon", "author_id": 31330, "author_profile": "https://Stackoverflow.com/users/31330", "pm_score": 4, "selected": false, "text": "sort -t@ -k1.1,1.4 -k1.5,1.7 ... <inputfile\n" }, { "answer_id": 6709427, "author": "andras", "author_id": 212013, "author_profile": "https://Stackoverflow.com/users/212013", "pm_score": 8, "selected": false, "text": "sort -k 3,3 -k 2,2 < inputfile\n sort -k 3 -k 2 < inputfile -k, --key=POS1[,POS2] start a key at POS1 (origin 1), end it at POS2\n (default end of line)\n" }, { "answer_id": 7240774, "author": "ron", "author_id": 180258, "author_profile": "https://Stackoverflow.com/users/180258", "pm_score": 3, "selected": false, "text": "-s" }, { "answer_id": 22261360, "author": "JayS", "author_id": 1812942, "author_profile": "https://Stackoverflow.com/users/1812942", "pm_score": 5, "selected": false, "text": "~/test>sort -t, -k1,1n -k2,2n -k3,3d -k4,4n -k5d sort.csv\n1,10,b,22,Ga\n2,2,b,20,F\n2,2,b,22,Ga\n2,2,c,19,Ga\n2,2,c,19,Gb,hi\n2,2,c,19,Gb,hj\n2,3,a,9,C\n\n~/test>cat sort.csv\n2,3,a,9,C\n2,2,b,20,F\n2,2,c,19,Gb,hj\n2,2,c,19,Gb,hi\n2,2,c,19,Ga\n2,2,b,22,Ga\n1,10,b,22,Ga\n ~/test>sort -t, -k1,2n -k3,3 -k4,4n -k5d sort.csv\n2,2,b,20,F\n2,2,b,22,Ga\n2,2,c,19,Ga\n2,2,c,19,Gb,hi\n2,2,c,19,Gb,hj\n2,3,a,9,C\n1,10,b,22,Ga\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28714/" ]
357,564
<p>Someone asserted on SO today that you should never use anonymous namespaces in header files. Normally this is correct, but I seem to remember once someone told me that one of the standard libraries uses anonymous namespaces in header files to perform some sort of initialization.</p> <p>Am I remembering correctly? Can someone fill in the details?</p>
[ { "answer_id": 357671, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 0, "selected": false, "text": "iostream istream ios" }, { "answer_id": 357701, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "tuple // A class (and instance) which can be used in 'tie' when an element\n // of a tuple is not required\n struct _Swallow_assign\n {\n template<class _Tp>\n _Swallow_assign&\n operator=(const _Tp&)\n { return *this; }\n };\n\n // TODO: Put this in some kind of shared file.\n namespace\n {\n _Swallow_assign ignore;\n }; // anonymous namespace\n std::tie(a, std::ignore, b) = some_tuple;\n extern _Swallow_assign ignore;\n" }, { "answer_id": 358823, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 6, "selected": true, "text": "ignore _1 _2" }, { "answer_id": 32452720, "author": "Jacqui Gurto", "author_id": 2752818, "author_profile": "https://Stackoverflow.com/users/2752818", "pm_score": 3, "selected": false, "text": "namespace\n{\n const char name[] = \"default\";\n}\n// This macro will hide the anonymous variable \"name\"\n#define SET_NAME(newname) \\\nstatic const char name[] = newname;\n #include \"a.hpp\"\nSET_NAME(\"file b\") // name is \"file b\" in this translation unit\n #include \"a.hpp\"\nSET_NAME(\"file c\") // name is \"file c\" in this translation unit\n #include \"a.hpp\"\n// name is \"default\" in this translation unit\n #include \"a.hpp\"\nstatic const char name[] = \"unintended\";\n// accidently hiding anonymous name\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34502/" ]
357,567
<p>The <a href="http://specs.xmlsoap.org/ws/2005/04/discovery/ws-discovery.pdf" rel="nofollow noreferrer">ws-discovery specifications</a> explains how to protect your network from </p> <ol> <li>message alteration</li> <li>Denial of service</li> <li>replay</li> <li>spoofing</li> </ol> <p>but what about man-in-the-middle attack?</p>
[ { "answer_id": 357671, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 0, "selected": false, "text": "iostream istream ios" }, { "answer_id": 357701, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "tuple // A class (and instance) which can be used in 'tie' when an element\n // of a tuple is not required\n struct _Swallow_assign\n {\n template<class _Tp>\n _Swallow_assign&\n operator=(const _Tp&)\n { return *this; }\n };\n\n // TODO: Put this in some kind of shared file.\n namespace\n {\n _Swallow_assign ignore;\n }; // anonymous namespace\n std::tie(a, std::ignore, b) = some_tuple;\n extern _Swallow_assign ignore;\n" }, { "answer_id": 358823, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 6, "selected": true, "text": "ignore _1 _2" }, { "answer_id": 32452720, "author": "Jacqui Gurto", "author_id": 2752818, "author_profile": "https://Stackoverflow.com/users/2752818", "pm_score": 3, "selected": false, "text": "namespace\n{\n const char name[] = \"default\";\n}\n// This macro will hide the anonymous variable \"name\"\n#define SET_NAME(newname) \\\nstatic const char name[] = newname;\n #include \"a.hpp\"\nSET_NAME(\"file b\") // name is \"file b\" in this translation unit\n #include \"a.hpp\"\nSET_NAME(\"file c\") // name is \"file c\" in this translation unit\n #include \"a.hpp\"\n// name is \"default\" in this translation unit\n #include \"a.hpp\"\nstatic const char name[] = \"unintended\";\n// accidently hiding anonymous name\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459737/" ]
357,571
<p>the object of the game in this case is to use a Treeview with a sitemap provider - and implement using CSS. I'm guessing the way to do this is with the CSS adapter kit. </p> <p>I've plugged in the adapters using the DLL implementation and there i get my basic treeview but it seems to pull in all sorts of js that lets me click on nodes and such. In my case I just want to display a hierarchy with nested UL and LI's. I dont want any js clicky clicky!! </p> <p>Is there anyway to accomplish this without having to use a seperate adapter project and rewriting the code to transform/render the treeview?</p> <p>I'm also open to other options with the goal being a simple hierarchy on a treeview/menu, and a breadcrumb, coming out of an XML file.</p> <p>thanks!</p>
[ { "answer_id": 357694, "author": "Nathan Prather", "author_id": 44595, "author_profile": "https://Stackoverflow.com/users/44595", "pm_score": 2, "selected": true, "text": "<asp:Repeater runat=\"server\" ID=\"menu\" DataSourceID=\"SiteMapDataSource1\">\n <ItemTemplate>\n <li>\n <asp:HyperLink runat=\"server\"\n NavigateUrl='<%# Eval(\"Url\") %>'>\n <%# Eval(\"Title\") %></asp:HyperLink>\n\n <asp:Repeater runat=\"server\"\n DataSource=\"<%# CType(Container.DataItem,\n SiteMapNode).ChildNodes %>\">\n <HeaderTemplate>\n <ul>\n </HeaderTemplate>\n\n <ItemTemplate>\n <li>\n <asp:HyperLink runat=\"server\"\n NavigateUrl='<%# Eval(\"Url\") %>'>\n <%# Eval(\"Title\") %></asp:HyperLink>\n </li>\n </ItemTemplate>\n\n <FooterTemplate>\n </ul>\n </FooterTemplate>\n </asp:Repeater>\n </li>\n </ItemTemplate>\n</asp:Repeater>\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45131/" ]
357,578
<p>I want to add a single model object that has been instantiated <em>once</em> in XAML, and add it to two different collections (in xaml).</p> <p>The following code renders fine in Blend's Design Time, but I get the following errors at run time:</p> <p><em>For "Post1"</em><br> Object of type 'WpfBlog.Models.Tag' cannot be converted to type 'System.Collections.ObjectModel.ObservableCollection`1[WpfBlog.Models.Tag]'. Error at object 'WpfBlog.Admin' in markup file 'WpfBlog;component/Admin.xaml' Line XX Position YY.</p> <p><em>If I comment out "Post1", I'll get this error on "Post2"</em><br> Cannot add element to property 'Tags', because the property can have only one child element if it uses an explicit collection tag. Error at object 'System.Windows.StaticResourceExtension' in markup file 'WpfBlog;component/Admin.xaml' Line AA Position BB.</p> <pre><code>&lt;Window.Resources&gt; &lt;model:Tag x:Key="TDD" Name="TDD" ForeColor="Black" BackColor="White" /&gt; &lt;model:Tag x:Key="Agile" Name="Agile" ForeColor="White" BackColor="Black" /&gt; &lt;model:Tag x:Key="Waterfail" Name="Waterfail" ForeColor="Red" BackColor="White" /&gt; &lt;/Window.Resources&gt; &lt;Window.DataContext&gt; &lt;local:AdminViewModel&gt; &lt;local:AdminViewModel.AllTags&gt; &lt;StaticResource ResourceKey="TDD"/&gt; &lt;StaticResource ResourceKey="Agile"/&gt; &lt;StaticResource ResourceKey="Waterfail"/&gt; &lt;/local:AdminViewModel.AllTags&gt; &lt;local:AdminViewModel.Posts&gt; &lt;local:PostViewModel Title="Post1"&gt; &lt;local:PostViewModel.Tags&gt; &lt;StaticResource ResourceKey="TDD" /&gt; &lt;/local:PostViewModel.Tags&gt; &lt;/local:PostViewModel&gt; &lt;local:PostViewModel Title="Post2"&gt; &lt;local:PostViewModel.Tags&gt; &lt;StaticResource ResourceKey="TDD" /&gt; &lt;StaticResource ResourceKey="Agile" /&gt; &lt;StaticResource ResourceKey="Waterfail" /&gt; &lt;/local:PostViewModel.Tags&gt; &lt;/local:PostViewModel&gt; &lt;/local:AdminViewModel.Posts&gt; &lt;/local:AdminViewModel&gt; &lt;Window.DataContext&gt; </code></pre> <p>The following code compiles and runs fine, but two tags named "TDD" get created, so if I try to rename the tag, I have to do it for all of the posts, instead of just the one Tag object.</p> <pre><code>&lt;Window.Resources&gt; &lt;model:Tag x:Key="TDD" Name="TDD" ForeColor="Black" BackColor="White" /&gt; &lt;model:Tag x:Key="Agile" Name="Agile" ForeColor="White" BackColor="Black" /&gt; &lt;model:Tag x:Key="Waterfail" Name="Waterfail" ForeColor="Red" BackColor="White" /&gt; &lt;/Window.Resources&gt; &lt;Window.DataContext&gt; &lt;local:AdminViewModel&gt; &lt;local:AdminViewModel.AllTags&gt; &lt;StaticResource ResourceKey="TDD"/&gt; &lt;StaticResource ResourceKey="Agile"/&gt; &lt;StaticResource ResourceKey="Waterfail"/&gt; &lt;/local:AdminViewModel.AllTags&gt; &lt;local:AdminViewModel.Posts&gt; &lt;local:PostViewModel Title="Post1"&gt; &lt;local:PostViewModel.Tags&gt; &lt;model:Tag Name="TDD" ForeColor="Black" BackColor="White" /&gt; &lt;/local:PostViewModel.Tags&gt; &lt;/local:PostViewModel&gt; &lt;local:PostViewModel Title="Post2"&gt; &lt;local:PostViewModel.Tags&gt; &lt;model:Tag Name="TDD" ForeColor="Black" BackColor="White" /&gt; &lt;model:Tag Name="Agile" ForeColor="White" BackColor="Black" /&gt; &lt;model:Tag Name="Waterfail" ForeColor="Red" BackColor="White" /&gt; &lt;/local:PostViewModel.Tags&gt; &lt;/local:PostViewModel&gt; &lt;/local:AdminViewModel.Posts&gt; &lt;/local:AdminViewModel&gt; &lt;Window.DataContext&gt; </code></pre> <p>Any ideas? I'd be able to ignore it and work around it if Blend didn't render it correctly, but it does!</p>
[ { "answer_id": 484322, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 3, "selected": false, "text": "<local:PostViewModel Title=\"Post1\">\n <local:PostViewModel.Tags>\n <model:TagCollection>\n <StaticResource ResourceKey=\"TDD\" />\n </model:TagCollection>\n </local:PostViewModel.Tags>\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4572/" ]
357,593
<p>How come the iPhone Interface Builder doesn't let me set the X,Y coordinates of a top-level UIView? (Meaning, a view whose direct parent is a UIViewController.) The X and Y boxes on the View Size tab are grayed out. I can change the X,Y values in code at runtime, so why not in the Interface Builder?</p> <p>Thanks.</p>
[ { "answer_id": 361157, "author": "Alex", "author_id": 35999, "author_profile": "https://Stackoverflow.com/users/35999", "pm_score": 3, "selected": true, "text": "UIViewController UIWindow UINavigationController UITabBarController UIViewController" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44003/" ]
357,594
<pre><code>SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn) as Row, hrl.unq, hrl.LcnsId, hc.Business,hc.Name,hc.Phone, hrl.Frn,hrl.CallSign, hrl.gsamarkettypeid, gmt.[Market Type Code] + ' - ' + gmt.gsamarkettype, hrl.gsalatitude,hrl.gsalongitude, rsc.RadioServiceCode + ' - ' + rsc.RadioService, GrantDt, ExpirationDt, EffectiveDt, CancellationDt FROM dbo.sbi_f_HldrRgstrtnLcns hrl INNER JOIN dbo.sbi_f_HldrCntcts hc on hc.CallSign = hrl.CallSign INNER JOIN dbo.sbi_l_radioservicecodes rsc on rsc.radioservicecodeid = hrl.radioservicecodeid LEFT OUTER JOIN dbo.sbi_l_GSAMarketTypes gmt on gmt.GSAMarketTypeId = hrl.GSAMarketTypeId WHERE hc.Entity_Type = 'L' AND hrl.LicenseStatusId IN (1) and Row &gt;=1 and Row &lt;= 20) -- The error occurs here, -- it says incorrect syntax near ) </code></pre>
[ { "answer_id": 357605, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "Where ((SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn)) < 20,\n Where (Select Count(*) \nFrom dbo.sbi_f_HldrRgstrtnLcns \nWhere Frn < hrl.Frn) < 20\n" }, { "answer_id": 357611, "author": "Ted Elliott", "author_id": 16501, "author_profile": "https://Stackoverflow.com/users/16501", "pm_score": 4, "selected": true, "text": "SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn) as Row,\n ...\n WHERE hc.Entity_Type = 'L' AND hrl.LicenseStatusId IN (1)\n ) T\nWHERE T.Row >=1 and T.Row <= 20)\n" }, { "answer_id": 357621, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 1, "selected": false, "text": "WITH NumberedRows AS\n(\n SELECT \n ROW_NUMBER() OVER (ORDER BY hrn.Frl) AS RowNum,\n ...\n WHERE \n hc.Entity_Type = 'L'\n AND hrl.LicenseStatusId IN (1)\n)\nSELECT\n *\nFROM\n NumberedRows\nWHERE\n RowNum <= 20\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
357,600
<p>I can't find much information on <code>const_cast</code>. The only info I could find (on Stack Overflow) is:</p> <blockquote> <p>The <code>const_cast&lt;&gt;()</code> is used to add/remove const(ness) (or volatile-ness) of a variable.</p> </blockquote> <p>This makes me nervous. Could using a <code>const_cast</code> cause unexpected behavior? If so, what?</p> <p>Alternatively, when is it okay to use <code>const_cast</code>?</p>
[ { "answer_id": 357607, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 8, "selected": true, "text": "const_cast const const char * char * const_cast char * const const_cast void func(const char *param, size_t sz, bool modify)\n{\n if(modify)\n strncpy(const_cast<char *>(param), sz, \"new string\");\n printf(\"param: %s\\n\", param);\n}\n\n...\n\nchar buffer[16];\nconst char *unmodifiable = \"string constant\";\nfunc(buffer, sizeof(buffer), true); // OK\nfunc(unmodifiable, strlen(unmodifiable), false); // OK\nfunc(unmodifiable, strlen(unmodifiable), true); // UNDEFINED BEHAVIOR\n" }, { "answer_id": 357645, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "struct sample {\n T& getT() { \n return const_cast<T&>(static_cast<const sample*>(this)->getT()); \n }\n\n const T& getT() const { \n /* possibly much code here */\n return t; \n }\n\n T t;\n};\n this getT t getT" }, { "answer_id": 357660, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 5, "selected": false, "text": "void log(char* text); // Won't change text -- just const-incorrect\n\nvoid my_func(const std::string& message)\n{\n log(const_cast<char*>(&message.c_str()));\n}\n class MyClass\n{\n char cached_data[10000]; // should be mutable\n bool cache_dirty; // should also be mutable\n\n public:\n\n char getData(int index) const\n {\n if (cache_dirty)\n {\n MyClass* thisptr = const_cast<MyClass*>(this);\n update_cache(thisptr->cached_data);\n }\n return cached_data[index];\n }\n};\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10606/" ]
357,627
<p>Is there a way to view the register contents in each stack frame in a crash dump? The registers window seems to contain the registers when the exception occurred but it would be useful to be able to see their contents in each stack frame.</p>
[ { "answer_id": 1493528, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "kn .frame /c [frame] .frame /r [frame] .hh" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
357,629
<p>The size and range of the integer value types in C++ are platform specific. Values found on most 32-bit systems can be found at <a href="http://www.cplusplus.com/doc/tutorial/variables.html" rel="noreferrer">Variables. Data Types. - C++ Documentation</a>. How do you determine what the actual size and range are for your specific system?</p>
[ { "answer_id": 357637, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 3, "selected": false, "text": "boost::uint32_t\nboost::int32_t\n" }, { "answer_id": 357638, "author": "Adam", "author_id": 1366, "author_profile": "https://Stackoverflow.com/users/1366", "pm_score": 6, "selected": true, "text": "#include <limits.h> // C header\n#include <climits> // C++ header\n\n// Constant containing the minimum value of a signed integer (–2,147,483,648)\nINT_MIN; \n\n// Constant containing the maximum value of a signed integer (+2,147,483,647)\nINT_MAX;\n #include <limits>\n\n std::numeric_limits\n std::numeric_limits<int>::max();\n // Number of digits for decimal (base 10)\n std::numeric_limits<char>::digits10;\n\n // Number of digits for binary\n std::numeric_limits<char>::digits;\n\n std::numeric_limits<unsigned int>::is_signed;\n" }, { "answer_id": 357646, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 3, "selected": false, "text": "std::numeric_limits" }, { "answer_id": 357651, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "sizeof() #include <stdlib.h>\n#include <iostream>\n#include <limits>\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n\n cout << \"\\nCharacter Types\" << endl;\n cout << \"Size of character type is \" << sizeof(char) << \" byte.\" << endl;\n cout << \"Signed char min: \" << SCHAR_MIN << endl;\n cout << \"Signed char max: \" << SCHAR_MAX << endl;\n cout << \"Unsigned char min: 0\" << endl;\n cout << \"Unsigned char max: \" << UCHAR_MAX << endl;\n\n cout << \"\\nShort Int Types\" << endl;\n cout << \"Size of short int type is \" << sizeof(short) << \" bytes.\" << endl;\n cout << \"Signed short min: \" << SHRT_MIN << endl;\n cout << \"Signed short max: \" << SHRT_MAX << endl;\n cout << \"Unsigned short min: 0\" << endl;\n cout << \"Unsigned short max: \" << USHRT_MAX << endl;\n\n cout << \"\\nInt Types\" << endl;\n cout << \"Size of int type is \" << sizeof(int) << \" bytes.\" << endl;\n cout << \"Signed int min: \" << INT_MIN << endl;\n cout << \"Signed int max: \" << INT_MAX << endl;\n cout << \"Unsigned int min: 0\" << endl;\n cout << \"Unsigned int max: \" << UINT_MAX << endl;\n\n cout << \"\\nLong Int Types\" << endl;\n cout << \"Size of long int type is \" << sizeof(long) << \" bytes.\" << endl;\n cout << \"Signed long min: \" << LONG_MIN << endl;\n cout << \"Signed long max: \" << LONG_MAX << endl;\n cout << \"Unsigned long min: 0\" << endl;\n cout << \"Unsigned long max: \" << ULONG_MAX << endl;\n\n return (EXIT_SUCCESS);\n}\n" }, { "answer_id": 357713, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": -1, "selected": false, "text": "sizeof(int)\n" }, { "answer_id": 13833006, "author": "Th.Srinivas", "author_id": 1896685, "author_profile": "https://Stackoverflow.com/users/1896685", "pm_score": 1, "selected": false, "text": "#include<stdio.h> \n#include<limits.h> \nvoid main() \n{ \n printf(\" signed data types \" ); \n printf(\" int min : %d \", INT_MIN); // INT_MIN, INT_MAX, SCHAR_MIN, SCHAR_MAX ....etc \n printf(\" int max : %d \",INT_MAX);// pre defined constants to get the values of datatypes \n printf(\" signed char min : %d \", SCHAR_MIN); \n printf(\" signed char max : %d \", SCHAR_MAX); \n// similarly for un_signed \n// use %u for control charter, and UINT_MAX, UCHAR_MAX, USHRT_MAX, ULONG_MAX. \n}\n" }, { "answer_id": 20044438, "author": "Shaohong Li", "author_id": 2117042, "author_profile": "https://Stackoverflow.com/users/2117042", "pm_score": 0, "selected": false, "text": " #include <iostream>\n\n using namespace std;\n\n\n void print_int_range() {\n int i=1;\n\n int nOfBits=0;\n while (i != 0) {\n i = i << 1;\n nOfBits++;\n }\n\n cout << \"int has \" << nOfBits << \" bits\" << endl;\n\n cout << \"mininum int: \" << (1 << (nOfBits - 1)) << \", maximum int: \" << ~(1 << (nOfBits - 1)) << endl;\n\n }\n\n void print_unsigned_int_range() {\n unsigned int i=1;\n\n int nOfBits=0;\n while (i != 0) {\n i = i << 1;\n nOfBits++;\n }\n\n cout << \"unsigned int has \" << nOfBits << \" bits\" << endl;\n\n cout << \"mininum int: \" << (0) << \", maximum int: \" << (unsigned int) (~0) << endl;\n }\n\n\n int main() {\n print_int_range();\n\n print_unsigned_int_range();\n }\n int has 32 bits \nmininum int: -2147483648, maximum int: 2147483647 \nunsigned int has 32 bits \nmininum int: 0, maximum int: 4294967295\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
357,639
<p>I'm trying to write a script that will create a file on the server then use <code>header()</code> to redirect the user to that file. Then, after about 10 seconds I want to delete the file. I've tried this:</p> <pre><code>header('Location: '.$url); flush(); sleep(10); unlink($url); </code></pre> <p>But the browser just waits for the script to complete then gets redirected, but the file hes been deleted by that time. Is there someway to tell the browser "end of file", then keep computing? Or maybe have PHP start another script, but not wait for that script to finish?</p>
[ { "answer_id": 357670, "author": "pbrodka", "author_id": 33093, "author_profile": "https://Stackoverflow.com/users/33093", "pm_score": 0, "selected": false, "text": "<iframe src=\"<?=$url?>\"></iframe>\n\n....\n<?\nsleep(10);\nunlink($url);\n?>\n" }, { "answer_id": 357681, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "header(\"Content-Length: 0\");\n" }, { "answer_id": 358305, "author": "lo_fye", "author_id": 3407, "author_profile": "https://Stackoverflow.com/users/3407", "pm_score": -1, "selected": false, "text": "<?php\n$file_contents = 'these are the contents of your file';\n$random_filename = md5(time()+rand(0,10000)).'.txt';\n$public_directory = '/www';\n$the_file = $public_directory.'/'.$random_filename;\nfile_put_contents($the_file, $file_contents);\necho file_get_contents($the_file);\nunlink($the_file);\n?>\n <?php\n$file_contents = 'these are the contents of your file';\necho $file_contents;\n?>\n <?php\n$file_contents = file_get_contents($filename_or_url);\necho $file_contents;\n?>\n" }, { "answer_id": 32520085, "author": "nkamm", "author_id": 1793639, "author_profile": "https://Stackoverflow.com/users/1793639", "pm_score": 0, "selected": false, "text": "\\Symfony\\Component\\HttpFoundation\\Response::send /**\n * Sends HTTP headers and content.\n *\n * @return Response\n *\n * @api\n */\npublic function send()\n{\n $this->sendHeaders();\n $this->sendContent();\n\n if (function_exists('fastcgi_finish_request')) {\n fastcgi_finish_request();\n } elseif ('cli' !== PHP_SAPI) {\n // ob_get_level() never returns 0 on some Windows configurations, so if\n // the level is the same two times in a row, the loop should be stopped.\n $previous = null;\n $obStatus = ob_get_status(1);\n while (($level = ob_get_level()) > 0 && $level !== $previous) {\n $previous = $level;\n if ($obStatus[$level - 1]) {\n if (version_compare(PHP_VERSION, '5.4', '>=')) {\n if (isset($obStatus[$level - 1]['flags']) && ($obStatus[$level - 1]['flags'] & PHP_OUTPUT_HANDLER_REMOVABLE)) {\n ob_end_flush();\n }\n } else {\n if (isset($obStatus[$level - 1]['del']) && $obStatus[$level - 1]['del']) {\n ob_end_flush();\n }\n }\n }\n }\n flush();\n }\n\n return $this;\n}\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13557/" ]
357,643
<h2>Repetitive Dates:</h2> <p>Billing cycles come in a lot of different formats, for example: "the first of the month", "third Friday of the month", or "first weekday on or after 21st day after the 13th of the month" (thanks visa!). My goal is to be able to represent these different billing cycles in one easily parsed database text field. </p>
[ { "answer_id": 1712228, "author": "alumb", "author_id": 80, "author_profile": "https://Stackoverflow.com/users/80", "pm_score": 1, "selected": true, "text": "YYYY/MM/DD+YY/MM/DD+DOW\n + [m,t,w,r,f,s,d,b]" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80/" ]
357,648
<p>I use Intellij Idea 7 for Java dev. My dev is 'limited' to all J2SE features plus light JSP, Servlets, and super light usage of JPA. No J2EE, no massive use of random frameworks, etc.</p> <p>Is it worth upgrading to ver 8? "Worth it" to me means better "core functionality" in terms of speed (ESPECIALLY startup speed), memory utilization (seems like it starts having serious problems with four or more projects open), and auto bug-finding. More frameworks supported and more languages supported (other than perhaps Haskell and C++), and more refactorings don't interest me at this time.</p> <p>A while back, I installed a preview version of 8 and it seemed -exactly- the same as 7, as far as my needs were concerned.</p> <p>Anyone loving the upgrade to 8, and if so, why?</p> <p>Thanks</p>
[ { "answer_id": 736350, "author": "Jonik", "author_id": 56285, "author_profile": "https://Stackoverflow.com/users/56285", "pm_score": 0, "selected": false, "text": "svn" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
357,650
<p>I currently have a button called Edit and a text box call blah on a ajax updatepanel. is it possible to set the asp.net's textbox Readonly via trigger? </p>
[ { "answer_id": 357689, "author": "GregD", "author_id": 38317, "author_profile": "https://Stackoverflow.com/users/38317", "pm_score": 0, "selected": false, "text": "protected void btnEdit_Click(object sender, EventArgs e)\n {\n\n }\n txtbox.ReadOnly = true;\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
357,656
<p>(I'm using the <a href="http://developer.berlios.de/projects/pyprocessing" rel="nofollow noreferrer">pyprocessing</a> module in this example, but replacing processing with multiprocessing should probably work if you run <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow noreferrer">python 2.6</a> or use the <a href="http://code.google.com/p/python-multiprocessing/" rel="nofollow noreferrer">multiprocessing backport</a>)</p> <p>I currently have a program that listens to a unix socket (using a processing.connection.Listener), accept connections and spawns a thread handling the request. At a certain point I want to quit the process gracefully, but since the accept()-call is blocking and I see no way of cancelling it in a nice way. I have one way that works here (OS X) at least, setting a signal handler and signalling the process from another thread like so:</p> <pre><code>import processing from processing.connection import Listener import threading import time import os import signal import socket import errno # This is actually called by the connection handler. def closeme(): time.sleep(1) print 'Closing socket...' listener.close() os.kill(processing.currentProcess().getPid(), signal.SIGPIPE) oldsig = signal.signal(signal.SIGPIPE, lambda s, f: None) listener = Listener('/tmp/asdf', 'AF_UNIX') # This is a thread that handles one already accepted connection, left out for brevity threading.Thread(target=closeme).start() print 'Accepting...' try: listener.accept() except socket.error, e: if e.args[0] != errno.EINTR: raise # Cleanup here... print 'Done...' </code></pre> <p>The only other way I've thought about is reaching deep into the connection (listener._listener._socket) and setting the non-blocking option...but that probably has some side effects and is generally really scary.</p> <p>Does anyone have a more elegant (and perhaps even correct!) way of accomplishing this? It needs to be portable to OS X, Linux and BSD, but Windows portability etc is not necessary.</p> <p><strong>Clarification</strong>: Thanks all! As usual, ambiguities in my original question are revealed :)</p> <ul> <li>I need to perform cleanup after I have cancelled the listening, and I don't always want to actually exit that process.</li> <li>I need to be able to access this process from other processes not spawned from the same parent, which makes Queues unwieldy</li> <li>The reasons for threads are that: <ul> <li>They access a shared state. Actually more or less a common in-memory database, so I suppose it could be done differently.</li> <li>I must be able to have several connections accepted at the same time, but the actual threads are blocking for something most of the time. Each accepted connection spawns a new thread; this in order to not block all clients on I/O ops.</li> </ul></li> </ul> <p>Regarding threads vs. processes, I use threads for making my blocking ops non-blocking and processes to enable multiprocessing.</p>
[ { "answer_id": 358392, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 1, "selected": false, "text": "from multiprocessing import Process\nfrom multiprocessing.connection import Listener\n\n\nclass ListenForConn(Process):\n\n def run(self):\n listener = Listener('/tmp/asdf', 'AF_UNIX')\n listener.accept()\n\n # do your other handling here\n\n\nlisten_process = ListenForConn()\nlisten_process.start()\n\nprint listen_process.is_alive()\n\nlisten_process.terminate()\nlisten_process.join()\n\nprint listen_process.is_alive()\nprint 'No more listen process.'\n" }, { "answer_id": 465361, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 2, "selected": false, "text": "from processing import connection\nconnection.Listener.fileno = lambda self: self._listener._socket.fileno()\n\nimport select\n\nl = connection.Listener('/tmp/x', 'AF_UNIX')\nr, w, e = select.select((l, ), (), ())\nif l in r:\n print \"Accepting...\"\n c = l.accept()\n # ...\n" }, { "answer_id": 50655251, "author": "MikeyE", "author_id": 1615978, "author_profile": "https://Stackoverflow.com/users/1615978", "pm_score": 0, "selected": false, "text": "def start(self):\n \"\"\"\n Start listening\n \"\"\"\n # set the command being executed\n self.command = self.COMMAND_RUN\n\n # startup the 'listener_main' method as a daemon thread\n self.listener = Listener(address=self.address, authkey=self.authkey)\n self._thread = threading.Thread(target=self.listener_main, daemon=True)\n self._thread.start()\n\ndef listener_main(self):\n \"\"\"\n The main application loop\n \"\"\"\n\n while self.command == self.COMMAND_RUN:\n # block until a client connection is recieved\n with self.listener.accept() as conn:\n\n # receive the subscription request from the client\n message = conn.recv()\n\n # if it's a shut down command, return to stop this thread\n if isinstance(message, str) and message == self.COMMAND_STOP:\n return\n\n # process the message\n\ndef stop(self):\n \"\"\"\n Stops the listening thread\n \"\"\"\n self.command = self.COMMAND_STOP\n client = Client(self.address, authkey=self.authkey)\n client.send(self.COMMAND_STOP)\n client.close()\n\n self._thread.join()\n multiprocessing.connection.Listener stop()" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2010/" ]
357,672
<p>I want to dynamically create variables with dynamic names for later use in my transform, but to do this I'd need to dynamically generate XSL and then run it in the same script.</p> <p>This is just a rough pseudo code example of what I'm looking for.</p> <pre><code> &lt;xsl:for-each select="//constants/constant" &gt; &lt;xsl:variable &gt; &lt;xsl:attribute name="name"&gt; &lt;xsl:value-of select="@name"/&gt; &lt;/xsl:attribute&gt; &lt;xsl:attribute name="select"&gt; &lt;xsl:value-of select="@value"/&gt; &lt;/xsl:attribute&gt; &lt;/xsl:variable&gt; &lt;/xsl:for-each&gt; </code></pre> <p>Can I use XSL to dynamically build XSL to be run later in the same script?</p> <p>Note: our XML is transformed via a batch process running a CL XSL transform engine; so just referencing an XSL stylesheet in the XSL document isn't an option.</p>
[ { "answer_id": 358154, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 4, "selected": false, "text": "<xsl:namespace-alias> xsl:namespace-alias xsl:namespace-alias stylesheet-prefix result-prefix stylesheet-prefix result-prefix xsl:stylesheet xsl:variable <v name=\"myVarName\">myValue</v>" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10922/" ]
357,721
<p>I have a client that want to have a web app I'm building for them display <a href="http://en.wikipedia.org/wiki/Heat_map" rel="nofollow noreferrer">heat maps</a> of the data.</p> <p>I haven't worked with heat maps at all and I was wondering if anyone knew of some good tools for generating them.</p> <p>Thanks.</p>
[ { "answer_id": 15800188, "author": "Larsenal", "author_id": 337, "author_profile": "https://Stackoverflow.com/users/337", "pm_score": 0, "selected": false, "text": "<!-- Coloring elements is easy! -->\n<ul id=\"example1\">\n <li>1<li>\n <li>2<li>\n <li>3<li>\n <li>4<li>\n <li>5<li>\n</ul>\n\n$('ul#example1 li').hottie();\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
357,739
<p>For my application, I want a <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html" rel="nofollow noreferrer">Combo Box</a> that displays its elements when dropped down as a <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html" rel="nofollow noreferrer">Tree</a>. Problem is, I'm not versed well enough in Swing to know how to go about doing this. At least without ending up writing a new widget from scratch, or something to that effect.</p> <p>How would I do something like this without creating one from scratch?</p>
[ { "answer_id": 357770, "author": "Markus Lausberg", "author_id": 39062, "author_profile": "https://Stackoverflow.com/users/39062", "pm_score": 0, "selected": false, "text": "public Component getListCellRendererComponent(\n JList list,\n Object value,\n int index,\n boolean isSelected,\n boolean cellHasFocus) {\n //Get the selected index. (The index param isn't\n //always valid, so just use the value.)\n int selectedIndex = ((Integer)value).intValue();\n\n if (isSelected) {\n setBackground(list.getSelectionBackground());\n setForeground(list.getSelectionForeground());\n } else {\n setBackground(list.getBackground());\n setForeground(list.getForeground());\n }\n\n //Set the icon and text. If icon was null, say so.\n ImageIcon icon = images[selectedIndex];\n String pet = petStrings[selectedIndex];\n setIcon(icon);\n if (icon != null) {\n setText(pet);\n setFont(list.getFont());\n } else {\n setUhOhText(pet + \" (no image available)\",\n list.getFont());\n }\n\n return this;\n}\n" }, { "answer_id": 357777, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "import javax.swing.*;\nimport javax.swing.event.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class ComboTree {\n public static void main( String [] args ) { \n JComboBox c = new JComboBox( new String [] { \"Hello\", \"there\"});\n c.setModel( new CustomComboModel() );\n c.setEditor( new TreeComboEditor() );\n c.setRenderer( new TreeComboEditor() );\n JFrame frame = new JFrame();\n frame.add( c , BorderLayout.NORTH ) ;\n frame.pack();\n frame.setVisible( true );\n\n }\n}\n\nclass CustomComboModel implements ComboBoxModel {\n public Object getSelectedItem() { return \":P\"; }\n public void setSelectedItem(Object anItem) {}\n public void addListDataListener(ListDataListener l) {}\n public Object getElementAt(int index) { return \"at \" + index ; }\n public int getSize() { return 2; }\n public void removeListDataListener(ListDataListener l) {}\n}\nclass TreeComboEditor implements ComboBoxEditor, ListCellRenderer {\n\n // Editor interface\n public void addActionListener(ActionListener l) {}\n public Component getEditorComponent() {\n return new JTree() ;\n }\n public Object getItem() { return \"\";}\n public void removeActionListener(ActionListener l) {}\n public void selectAll() {}\n public void setItem(Object anObject) {}\n\n // Render interface\n public Component getListCellRendererComponent(JList list,\n Object value,\n int index,\n boolean isSelected,\n boolean cellHasFocus) {\n return new JTree();\n }\n}\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825/" ]
357,752
<p>I have a web application that uses the current version of JQuery that needs to get some JSON objects back from a REST web service. I'm using the following call to $.getJSON:</p> <p>$.getJSON("<a href="http://localhost:17245/Service.svc/?format=json" rel="nofollow noreferrer">http://localhost:17245/Service.svc/?format=json</a>", function(data) {alert(data.id);});</p> <p>This call works fine in IE7 and I can call the service with no problem in Fiddler. I've stepped through this in Firebug, but when Firefox gets to this line the javascript execution just seems to "die" with no error, no call back, no nothing.</p> <p>I've also used $.ajax and have the same issue; works fine in IE, nothing in Firefox.</p> <p>Anyone have any ideas? I'm VERY new to JQuery, so please be gentle.</p> <p>Thanks, James</p>
[ { "answer_id": 357767, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 3, "selected": true, "text": "$.getJSON(\"http://localhost:17245/Service.svc/?format=json\", {}, function(data) {alert(data.id);});\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22848/" ]
357,754
<p>In Ruby, <code>Dir.glob("**/*.rb")</code> (for instance) doesn't traverse symlinked directories. Is it possible to get the <code>**</code> to traverse symlinks?</p> <p>I'm using two gems which find files this way, but I need them to see files within a symlinked directory.</p>
[ { "answer_id": 357798, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 4, "selected": false, "text": "Dir.glob(\"**/*/**/b\")" }, { "answer_id": 2724048, "author": "Tim Harper", "author_id": 183863, "author_profile": "https://Stackoverflow.com/users/183863", "pm_score": 6, "selected": true, "text": "Dir.glob(\"**{,/*/**}/*.rb\")\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4937/" ]
357,785
<p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p> <p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p> <ul> <li>Do you have a particular Vim plugin that you use and like?</li> <li>Do you use manual folding or do you place markers in comments?</li> <li>Any other recommended ways to do code folding for Python in Vim?</li> </ul>
[ { "answer_id": 357826, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "#Toggle fold methods \\fo\nlet g:FoldMethod = 0\nmap <leader>fo :call ToggleFold()<cr>\nfun! ToggleFold()\n if g:FoldMethod == 0\n exe 'set foldmethod=indent'\n let g:FoldMethod = 1\n else\n exe 'set foldmethod=marker'\n let g:FoldMethod = 0\n endif\nendfun\n#Add markers (trigger on class Foo line)\nnnoremap ,f2 ^wywO#<c-r>0 {{{2<esc>\nnnoremap ,f3 ^wywO#<c-r>0 {{{3<esc> \nnnoremap ,f4 ^wywO#<c-r>0 {{{4<esc>\nnnoremap ,f1 ^wywO#<c-r>0 {{{1<esc>\n" }, { "answer_id": 357833, "author": "Nick Presta", "author_id": 40906, "author_profile": "https://Stackoverflow.com/users/40906", "pm_score": 3, "selected": false, "text": "python_ifold" }, { "answer_id": 360634, "author": "Walter", "author_id": 23840, "author_profile": "https://Stackoverflow.com/users/23840", "pm_score": 8, "selected": true, "text": "set foldmethod=indent\nnnoremap <space> za\nvnoremap <space> zf\n" }, { "answer_id": 21112061, "author": "Genma", "author_id": 1305175, "author_profile": "https://Stackoverflow.com/users/1305175", "pm_score": 2, "selected": false, "text": "class def ~/.vim/syntax python.vim syn match pythonDefStatement /^\\s*\\%(def\\|class\\)/\n \\ nextgroup=pythonFunction skipwhite\nsyn region pythonFunctionFold start=\"^\\z(\\s*\\)\\%(def\\|class\\)\\>\"\n \\ end=\"\\ze\\%(\\s*\\n\\)\\+\\%(\\z1\\s\\)\\@!.\" fold transparent\n\nhi link pythonDefStatement Statement\n :set foldmethod=syntax" }, { "answer_id": 59572950, "author": "Tinmarino", "author_id": 2544873, "author_profile": "https://Stackoverflow.com/users/2544873", "pm_score": 2, "selected": false, "text": ".vimrc set foldmethod=indent\nset shiftwidth=4\n zM zR nnoremap <space> za\nvnoremap <space> zf\nmap z1 :set foldlevel=0<CR><Esc>\nmap z2 :set foldlevel=1<CR><Esc>\nmap z3 :set foldlevel=2<CR><Esc>\nmap z4 :set foldlevel=3<CR><Esc>\nmap z5 :set foldlevel=4<CR><Esc>\nmap z6 :set foldlevel=5<CR><Esc>\nmap z7 :set foldlevel=6<CR><Esc>\nmap z8 :set foldlevel=7<CR><Esc>\nmap z9 :set foldlevel=8<CR><Esc>\n z1 z2" }, { "answer_id": 62452911, "author": "Grant Buster", "author_id": 10300977, "author_profile": "https://Stackoverflow.com/users/10300977", "pm_score": 2, "selected": false, "text": "alt+1 alt+2 alt+0 za ^[0 ^[ alt \" Python folding\nnnoremap ^[0 zR<CR>\nnnoremap ^[1 :call Fold(0)<CR>\nnnoremap ^[2 :call Fold(1)<CR>\nfunction Fold(level)\n :let b:max = a:level + 1\n :set foldmethod=indent\n :execute 'set foldnestmax='.b:max\n :execute 'set foldlevel='.a:level\nendfunction\n" }, { "answer_id": 70543756, "author": "Jorengarenar", "author_id": 10247460, "author_profile": "https://Stackoverflow.com/users/10247460", "pm_score": 0, "selected": false, "text": ".vim/after/syntax/python.vim syn keyword pythonStatement class def\nsyn match pythonFunction \"\\h\\w*\" containedin=pythonFold\nsyn region pythonFold fold transparent\n \\ start = \"\\(^\\z(\\s*\\)\\v%(def|class|if|elif|else|for|while|try|except|finally|with)>)@<=\"\n \\ end = \"\\v\\ze%(\\s*\\n)+%(\\z1\\s)@!.\"\n\nsyn region pythonCurlyBrace start=\"{\" end=\"}\" fold transparent\nsyn region pythonSquareBrace start=\"\\[\" end=\"\\]\" fold transparent\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045/" ]
357,790
<p>I have a small calculator that I am creating in C# (Sharp Develop). The user enters two values and the code returns the third. I am having trouble rounding the third value once it is returned. I have been through a couple of forums and the msdn site and I understand the code that is posted there, but I cant seem to make it work in my situation. Can anyone provide a little help? Reference the code below.</p> <pre><code>int y; decimal x, z; x = int.Parse(tb2_fla.Text); y = int.Parse(tb2_e.Text); z = (x * y * 1.732050808m) / 1000; tb2_kva.Text = z.ToString(); </code></pre> <p>I welcome both assistance and criticism<br> Greg</p>
[ { "answer_id": 357801, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 1, "selected": true, "text": "tb2_kva.Text = Math.Round(z, # Places).ToString();\n" }, { "answer_id": 357805, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 0, "selected": false, "text": "tb2_kva.Text = String.Format(\"{0:d2}\", z);\n" }, { "answer_id": 357806, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "Math.Round(z, 2).ToString();\nz.ToString(\"0.00\");\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45151/" ]
357,803
<p>Basically what I need is an automated way to update the product version number in WiX (3.0 with Votive etc), and then get that version number into an Inno Setup "bootstrapper"</p> <p>I pretty much have the process mostly automated, however version numbers still need to be updated manually which obviously isn't ideal, but I couldn't find how to pass in values to Inno Setup at compile time (and how to reference them), and in the WiX project I need to know how to reference the version number of a different project in the same solution in Visual Studio 2008</p>
[ { "answer_id": 357820, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 1, "selected": false, "text": "<include>" }, { "answer_id": 358668, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 1, "selected": false, "text": "VersionInfoVersion=1.2.3.12345\nAppVerName=My App v1.2.3.12345\n [Setup]\nAppId={{...}}\n...\n\n#include \"version.iss\"\n createInnoSetupIncludeFile(\"My App\", 1, 2, 3, 12345, \"version.iss\");\n\nfunction createInnoSetupIncludeFile(appName, verMajor, verMinor, verSubMinor, buildNumber, headerFileName)\n{\n var versionString = verMajor + \".\" + verMinor + \".\" + verSubMinor + \".\" + buildNumber;\n var fileSystemObject = WScript.CreateObject(\"Scripting.FileSystemObject\");\n var fileObject = fileSystemObject.CreateTextFile(headerFileName, true);\n fileObject.WriteLine(\"VersionInfoVersion=\" + versionString);\n fileObject.WriteLine(\"AppVerName=\" + appName + \" v\" + versionString);\n fileObject.Close();\n fileObject = null;\n fileSystemObject = null;\n}\n cscript version.js //NoLogo\n" }, { "answer_id": 358720, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 6, "selected": true, "text": "#define AppName \"My App\"\n#define SrcApp \"MyApp.exe\"\n#define FileVerStr GetFileVersion(SrcApp)\n#define StripBuild(str VerStr) Copy(VerStr, 1, RPos(\".\", VerStr)-1)\n#define AppVerStr StripBuild(FileVerStr)\n\n[Setup]\nAppName={#AppName}\nAppVersion={#AppVerStr}\nAppVerName={#AppName} {#AppVerStr}\nUninstallDisplayName={#AppName} {#AppVerStr}\nVersionInfoVersion={#FileVerStr}\nVersionInfoTextVersion={#AppVerStr}\nOutputBaseFilename=MyApp-{#FileVerStr}-setup\n" }, { "answer_id": 360447, "author": "Rob Mensching", "author_id": 23852, "author_profile": "https://Stackoverflow.com/users/23852", "pm_score": 3, "selected": false, "text": "<Product Version=\"$(var.FileVersion.FileId)\">\n <Product Version=\"$(var.VersionFromCommandLine)\">\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23822/" ]
357,804
<p>Today I found out that putting strings in a resource file will cause them to be treated as literals, i.e putting "Text for first line \n Text for second line" will cause the escape character itself to become escaped, and so what's stored is "Text for first line \n Text for second line" - and then these come out in the display, instead of my carriage returns and tabs</p> <p>So what I'd like to do is use string.replace to turn <code>\\</code> into <code>\</code> - this doesn't seem to work.</p> <pre>s.Replace("\\\\", "\\"); </pre> <p>doesn't change the string at all because the string thinks there's only 1 backslash</p> <pre>s.Replace("\\", "");</pre> <p>replaces all the double quotes and leaves me with just n instead of \n</p> <p>also, using <code>@</code> and half as many <code>\</code> chars or the <code>Regex.Replace</code> method give the same result</p> <p>anyone know of a good way to do this without looping through character by character?</p>
[ { "answer_id": 357811, "author": "codelogic", "author_id": 43427, "author_profile": "https://Stackoverflow.com/users/43427", "pm_score": 5, "selected": true, "text": "\\n \\ s.Replace(\"\\\\n\", \"\\n\");\ns.Replace(\"\\\\t\", \"\\t\");\netc\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45139/" ]
357,810
<p>I am a beginner of python and have a question, very confusing for me. If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function? for example:</p> <pre><code>def hello(x,y): good=hi(iy,ix) "then do somethings,and use the parameter'good'." return something def hi(iy,ix): "code" return good </code></pre>
[ { "answer_id": 357853, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 2, "selected": false, "text": "def hello(x,y):\n good=hi(iy,ix)\n \"then do somethings,and use the parameter'good'.\"\n return something\n\ndef hi(iy,ix):\n \"code\"\n return great\n" }, { "answer_id": 357855, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": true, "text": "hello hi hi(x,y) good hello good hello good hi good hi hello hello def hello(x,y):\n fordf150 = hi(y,x)\n \"then do somethings,and use the variable 'fordf150'.\"\n return something\n\ndef hi( ix, iy ):\n \"compute some value, good.\"\n return good\n hello( 2, 3) hello hello x 2 hello y 3 hello fordf150 = hi( y, x ) y x hi hi ix 3 hi iy 2 hi good 3.1415926 hi return hi good 3.1415926 hi good ix iy 3.1415926 hi hello fordf150 = hi( y, x ) y x hi 3.1415926 fordf150 hi 3.1415926 hello something 2.718281828459045 hello return hello something 2.718281828459045 fordf150 something x y 2.718281828459045 hello hello" }, { "answer_id": 358013, "author": "Zoomulator", "author_id": 44563, "author_profile": "https://Stackoverflow.com/users/44563", "pm_score": 2, "selected": false, "text": "varA = 5 #A normal declaration of an integer in the main \"global\" namespace\n\ndef funcA():\n print varA #This works, because the variable was defined in the global namespace\n #and functions have read access to this.\ndef changeA():\n varA = 2 #This however, defines a variable in the function's own namespace\n #Because of this, it's not accessible by other functions.\n #It has also replaced the global variable, though only inside this function\ndef newVar():\n global varB #By using the global keyword, you assign this variable to the global namespace\n varB = 5\n\ndef funcB():\n print varB #Making it accessible to other functions\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44354/" ]
357,814
<p>It seems that the choice to use string parsing vs. regular expressions comes up on a regular basis for me anytime a situation arises that I need part of a string, information about said string, etc.</p> <p>The reason that this comes up is that we're evaluating a soap header's action, <strong>after</strong> it has been parsed into something manageable via the OperationContext object for WCF and <em>then</em> making decisions on that. Right now, the simple solution seems to be basic substring'ing to keep the implementation simple, but part of me wonders if RegEx would be better or more robust. The other part of me wonders if it'd be like using a shotgun to kill a fly in our particular scenario.</p> <p>So I have to ask, what's the typical threshold that people use when trying to decide to use RegEx over typical string parsing. Note that I'm not very strong in Regular Expressions, and because of this, I try to shy away unless it's absolutely vital to avoid introducing more complication than I need.</p> <p>If you couldn't tell by my choice of abbreviations, this is in .NET land (C#), but I believe that doesn't have much bearing on the question.</p> <hr> <p><strong>EDIT</strong>: It seems as per my typical Raybell charm, I've been too wordy or misleading in my question. I want to apologize. I was giving some background to help give clues as to what I was doing, not mislead people. </p> <p>I'm basically looking for a guideline as to when to use substring, and variations thereof, over Regular Expressions and vice versa. And while some of the answers may have missed this (and again, my fault), I've genuinely appreciated them and up-voted as accordingly.</p>
[ { "answer_id": 357863, "author": "benjismith", "author_id": 22979, "author_profile": "https://Stackoverflow.com/users/22979", "pm_score": 6, "selected": true, "text": "1 + 2\n5 * (10 - 6)\n((1 + 1) / (2 + 2)) / 3\n DIGIT := [\"0\"-\"9\"]\nNUMBER := (DIGIT)+\nOPERATOR := (\"+\" | \"-\" | \"*\" | \"/\" )\nEXPRESSION := (NUMBER | GROUP) (OPERATOR EXPRESSION)?\nGROUP := \"(\" EXPRESSION \")\"\n if (str.equals(\"DooWahDiddy\")) // No problemo.\n\nif (str.contains(\"destroy the earth\")) // Okay.\n\nif (str.indexOf(\";\") < str.length / 2) // Not bad.\n if (str.startsWith(\"I\") && str.endsWith(\"Widget\") &&\n (!str.contains(\"Monkey\") || !str.contains(\"Pox\"))) // Madness.\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14409/" ]
357,822
<p>This is more an observation than a real question: MS-Access (and VBA in general) is desperately missing a tool where error handling code can be generated automatically, and where the line number can be displayed when an error occurs. Did you find a solution? What is it? I just realized how many hundreds of hours I spared since I found the right answer to this basic problem a few years ago, and I'd like to see what are your ideas and solutions on this very important issue. </p>
[ { "answer_id": 357872, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 3, "selected": false, "text": "On Error GoTo ErrorHandler\n ErrorHandler:\n Call MyErrorhandler Err.Number, Err.Description, Err.LineNumber\n" }, { "answer_id": 357882, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 4, "selected": true, "text": "On Error GoTo {PROCEDURE_NAME}_Error\n{PROCEDURE_BODY}\nOn Error GoTo 0\nExit {PROCEDURE_TYPE}\n\n{PROCEDURE_NAME}_Error:\ndebug.print \"#\" & Err.Number, Err.description, \"l#\" & erl, \"{PROCEDURE_NAME}\", \"{MODULE_NAME}\"\n #91, Object variable or With block variable not set, l# 30, addNewField, Utilities\n" }, { "answer_id": 357888, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 3, "selected": false, "text": "Private Sub mySUB()\nOn Error GoTo Err_mySUB\n10:\n Dim stDocName As String\n Dim stLinkCriteria As String\n20:\n stDocName = \"MyDoc\"\n30:\n DoCmd.openform stDocName, acFormDS, , stLinkCriteria \nExit_mySUB:\n Exit Sub\nErr_mySUB:\n MsgBox Err.Number & \": \" & Err.Description & \" (\" & Erl & \")\"\n Resume Exit_mySUB\nEnd Sub\n" }, { "answer_id": 24493605, "author": "RubberDuck", "author_id": 3198973, "author_profile": "https://Stackoverflow.com/users/3198973", "pm_score": 2, "selected": false, "text": "On Error GoTo ErrHandler" }, { "answer_id": 54619478, "author": "Vlado", "author_id": 7526564, "author_profile": "https://Stackoverflow.com/users/7526564", "pm_score": 2, "selected": false, "text": "Public Sub InsertErrHandling(modName As String)\n Dim Component As Object\n Dim Name As String\n Dim Kind As Long\n Dim FirstLine As Long\n Dim ProcLinesCount As Long\n Dim Declaration As String\n Dim ProcedureType As String\n Dim Index As Long, i As Long\n Dim LastLine As Long\n Dim StartLines As Collection, LastLines As Collection, ProcNames As Collection, ProcedureTypes As Collection\n Dim gotoErr As Boolean\n\n Kind = 0\n Set StartLines = New Collection\n Set LastLines = New Collection\n Set ProcNames = New Collection\n Set ProcedureTypes = New Collection\n\n Set Component = Application.VBE.ActiveVBProject.VBComponents(modName)\n With Component.CodeModule\n\n ' Remove empty lines on the end of the code\n For i = .CountOfLines To 1 Step -1\n If Component.CodeModule.Lines(i, 1) = \"\" Then\n Component.CodeModule.DeleteLines i, 1\n Else\n Exit For\n End If\n Next i\n\n Index = .CountOfDeclarationLines + 1\n Do While Index < .CountOfLines\n gotoErr = False\n Name = .ProcOfLine(Index, Kind)\n FirstLine = .ProcBodyLine(Name, Kind)\n ProcLinesCount = .ProcCountLines(Name, Kind)\n Declaration = Trim(.Lines(FirstLine, 1))\n LastLine = FirstLine + ProcLinesCount - 2\n If InStr(1, Declaration, \"Function \", vbBinaryCompare) > 0 Then\n ProcedureType = \"Function\"\n Else\n ProcedureType = \"Sub\"\n End If\n Debug.Print Component.Name & \".\" & Name, \"First: \" & FirstLine, \"Lines:\" & ProcLinesCount, \"Last: \" & LastLine, Declaration\n Debug.Print \"Declaration: \" & Component.CodeModule.Lines(FirstLine, 1), FirstLine\n Debug.Print \"Closing Proc: \" & Component.CodeModule.Lines(LastLine, 1), LastLine\n\n ' do not insert error handling if there is one already:\n For i = FirstLine To LastLine Step 1\n If Component.CodeModule.Lines(i, 1) Like \"*On Error*\" Then\n gotoErr = True\n Exit For\n End If\n Next i\n If Not gotoErr Then\n StartLines.Add FirstLine\n LastLines.Add LastLine\n ProcNames.Add Name\n ProcedureTypes.Add ProcedureType\n End If\n\n Index = FirstLine + ProcLinesCount + 1\n Loop\n\n For i = LastLines.Count To 1 Step -1\n If Not (Component.CodeModule.Lines(StartLines.Item(i) + 1, 1) Like \"*On Error GoTo *\") Then\n Component.CodeModule.InsertLines LastLines.Item(i), \"ExitProc_:\"\n Component.CodeModule.InsertLines LastLines.Item(i) + 1, \" Exit \" & ProcedureTypes.Item(i)\n Component.CodeModule.InsertLines LastLines.Item(i) + 2, \"ErrHandler_:\"\n Component.CodeModule.InsertLines LastLines.Item(i) + 3, \" Call LogError(Err, Me.Name, \"\"\" & ProcNames.Item(i) & \"\"\")\"\n Component.CodeModule.InsertLines LastLines.Item(i) + 4, \" Resume ExitProc_\"\n Component.CodeModule.InsertLines LastLines.Item(i) + 5, \" Resume ' use for debugging\"\n\n Component.CodeModule.InsertLines StartLines.Item(i) + 1, \" On Error GoTo ErrHandler_\"\n End If\n Next i\n End With\nEnd Sub\n MyModule.InsertErrHandling \"Form_Form1\"\n Private Function CloseIt()\n DoCmd.Close acForm, Me.Name\nEnd Function\n Private Function CloseIt()\n On Error GoTo ErrHandler_\n DoCmd.Close acForm, Me.Name\nExitProc_:\nExit Function\nErrHandler_:\n Call LogError(Err, Me.Name, \"CloseIt\")\n Resume ExitProc_\n Resume ' use for debugging\nEnd Function\n Public Sub LogError(ByVal objError As ErrObject, moduleName As String, Optional procName As String = \"\")\n On Error GoTo ErrHandler_\n Dim sql As String\n MsgBox \"Error \" & Err.Number & \" Module \" & moduleName & Switch(procName <> \"\", \" in \" & procName) & vbCrLf & \" (\" & Err.Description & \") \", vbCritical\nExit_:\n Exit Sub\nErrHandler_:\n MsgBox \"Error in LogError procedure \" & Err.Number & \", \" & Err.Description\n Resume Exit_\n Resume ' use for debugging\nEnd Sub\n" }, { "answer_id": 74367958, "author": "Erik68", "author_id": 20454048, "author_profile": "https://Stackoverflow.com/users/20454048", "pm_score": 1, "selected": false, "text": "Sub AddErrorHandlingToAllProcs()\nDim VBProj As VBIDE.VBProject\nDim VBComp As VBIDE.VBComponent\nDim lCtr As Long\n\nStartNewWorksheetLog\n\nSet VBProj = Workbooks(\"LabViewAnalysisTools.xla\").VBProject\nFor Each VBComp In VBProj.VBComponents\n If VBComp.Type <> vbext_ct_ActiveXDesigner Then\n If VBComp.Name <> \"modVBAChecks\" And VBComp.Name <> \"modLogToWorksheet\" Then\n AddToWksLog \"============ Looking at Module \"\"\" & VBComp.Name & \"\"\"\"\n 'InsertErrHandling VBComp.Name \n AddToWksLog\n AddToWksLog\n End If\n End If\nNext\nMsgBox \"Done!\", vbSystemModal\nEnd Sub\n Public Sub InsertErrHandling(modsProcName As String)\n ' Modified from code submitted to StackOverflow by user Vlado, originally found\n ' here: https://stackoverflow.com/questions/357822/automatically-generating-handling-of-issues\n \n Dim vbcmA As VBIDE.CodeModule\n Dim ProcKind As VBIDE.vbext_ProcKind\n Dim LineProcKind As VBIDE.vbext_ProcKind\n Dim sProcName As String\n Dim sLineProcName As String\n Dim lFirstLine As Long\n Dim lProcLinesCount As Long\n Dim lLastLine As Long\n Dim sDeclaration As String\n Dim sProcType As String\n Dim lLine As Long, lLine2 As Long\n Dim sLine As String\n Dim lcStartLines As Collection, lcLastlines As Collection, scProcsProcNames As Collection, scProcTypes As Collection\n Dim bAddHandler As Boolean\n Dim lLinesAbove As Long\n\n Set lcStartLines = New Collection\n Set lcLastlines = New Collection\n Set scProcsProcNames = New Collection\n Set scProcTypes = New Collection\n\n Set vbcmA = Application.VBE.ActiveVBProject.VBComponents(modsProcName).CodeModule\n \n ' Remove empty lines on the end of the module. Cleanup, not error handling. \n lLine = vbcmA.CountOfLines\n If lLine = 0 Then Exit Sub ' Nothing to do!\n Do\n If Trim(vbcmA.Lines(lLine, 1)) <> \"\" Then Exit Do\n vbcmA.DeleteLines lLine, 1\n lLine = lLine - 1\n Loop\n\n lLine = vbcmA.CountOfDeclarationLines + 1\n Do While lLine < vbcmA.CountOfLines\n bAddHandler = False\n\n ' NOTE: ProcKind is RETRUNED from ProcOfLine!\n sProcName = vbcmA.ProcOfLine(lLine, ProcKind)\n \n ' Fortunately ProcBodyLine ALWAYS returns the first line of the procedure declaration!\n lFirstLine = vbcmA.ProcBodyLine(sProcName, ProcKind)\n sDeclaration = Trim(vbcmA.Lines(lFirstLine, 1))\n \n Select Case ProcKind\n Case VBIDE.vbext_ProcKind.vbext_pk_Proc\n If sDeclaration Like \"*Function *\" Then\n sProcType = \"Function\"\n ElseIf sDeclaration Like \"*Sub *\" Then\n sProcType = \"Sub\"\n End If\n Case VBIDE.vbext_ProcKind.vbext_pk_Get, VBIDE.vbext_ProcKind.vbext_pk_Let, VBIDE.vbext_ProcKind.vbext_pk_Set\n sProcType = \"Property\"\n End Select\n \n ' The \"lProcLinesCount\" function will sometimes return ROWS ABOVE \n ' the procedure, possibly up until the prior procedure,\n ' and often rows BELOW the procedure as well!!!\n \n lProcLinesCount = vbcmA.ProcCountLines(sProcName, ProcKind)\n lLinesAbove = 0\n lLine2 = lFirstLine - 1\n If lLine2 > 0 Then\n Do\n sLineProcName = vbcmA.ProcOfLine(lLine2, LineProcKind)\n If Not (sLineProcName = sProcName And LineProcKind = ProcKind) Then Exit Do\n lLinesAbove = lLinesAbove + 1\n lLine2 = lLine2 - 1\n If lLine2 = 0 Then Exit Do\n Loop\n End If\n lLastLine = lFirstLine + lProcLinesCount - lLinesAbove - 1\n \n ' Now need to trim off any follower lines!\n Do\n sLine = Trim(vbcmA.Lines(lLastLine, 1))\n If sLine = \"End \" & sProcType Or sLine Like \"End \" & sProcType & \" '*\" Then Exit Do\n lLastLine = lLastLine - 1\n Loop\n \n AddToWksLog modsProcName & \".\" & sProcName, \"First: \" & lFirstLine, \"Lines:\" & lProcLinesCount, \"Last: \" & lLastLine\n AddToWksLog \"sDeclaration: \" & vbcmA.Lines(lFirstLine, 1), lFirstLine\n AddToWksLog \"Closing Proc: \" & vbcmA.Lines(lLastLine, 1), lLastLine\n\n If lLastLine - lFirstLine < 8 Then\n AddToWksLog \" --------------- Too Short to bother!\"\n Else\n bAddHandler = True\n ' do not insert error handling if there is one already:\n For lLine2 = lFirstLine To lLastLine Step 1\n If vbcmA.Lines(lLine2, 1) Like \"*On Error GoTo *\" And Not vbcmA.Lines(lLine2, 1) Like \"*On Error GoTo 0\" Then\n bAddHandler = False\n Exit For\n End If\n Next lLine2\n If bAddHandler Then\n lcStartLines.Add lFirstLine\n lcLastlines.Add lLastLine\n scProcsProcNames.Add sProcName\n scProcTypes.Add sProcType\n End If\n End If\n \n AddToWksLog\n \n lLine = lFirstLine + lProcLinesCount + 1\n Loop\n\n For lLine = lcLastlines.Count To 1 Step -1\n vbcmA.InsertLines lcLastlines.Item(lLine), \"ExitProc:\"\n vbcmA.InsertLines lcLastlines.Item(lLine) + 1, \" Exit \" & scProcTypes.Item(lLine)\n vbcmA.InsertLines lcLastlines.Item(lLine) + 2, \"ErrHandler:\"\n vbcmA.InsertLines lcLastlines.Item(lLine) + 3, \" ShowErrorMsg Err, \"\"\" & scProcsProcNames.Item(lLine) & \"\"\", \"\"\" & modsProcName & \"\"\"\"\n vbcmA.InsertLines lcLastlines.Item(lLine) + 4, \" Resume ExitProc\"\n ' Now replace any \"On Error Goto 0\" lines with \"IF ErrorTrapping Then On Error Goto ErrHandler\"\n For lLine2 = lcStartLines(lLine) To lcLastlines(lLine)\n sLine = vbcmA.Lines(lLine2, 1)\n If sLine Like \"On Error GoTo 0\" Then\n vbcmA.ReplaceLine lLine2, Replace(sLine, \"On Error Goto 0\", \"IF ErrorTrapping Then On Error Goto ErrHandler\")\n End If\n Next\n lLine2 = lcStartLines.Item(lLine)\n Do\n sLine = vbcmA.Lines(lLine2, 1)\n If Not sLine Like \"* _\" Then Exit Do\n lLine2 = lLine2 + 1\n Loop\n vbcmA.InsertLines lLine2 + 1, \" If ErrorTrapping Then On Error GoTo ErrHandler\"\n Next lLine\nEnd Sub\n Option Explicit\n\nPrivate wksLog As Worksheet\nPrivate lRow As Long\n\nPublic Sub StartNewWorksheetLog()\n Dim bNewSheet As Boolean\n \n bNewSheet = True\n If ActiveSheet.Type = xlWorksheet Then\n Set wksLog = ActiveSheet\n bNewSheet = Not (wksLog.UsedRange.Cells.Count = 1 And wksLog.Range(\"A1\").Formula = \"\")\n End If\n If bNewSheet Then Set wksLog = ActiveWorkbook.Worksheets.Add\n lRow = 1\nEnd Sub\n\nPublic Sub AddToWksLog(ParamArray sMsg() As Variant)\n Dim lCol As Long\n\n If wksLog Is Nothing Or lRow = 0 Then StartNewWorksheetLog\n \n If Not (IsNull(sMsg)) Then\n For lCol = 0 To UBound(sMsg)\n If sMsg(lCol) <> \"\" Then wksLog.Cells(lRow, lCol + 1).Value = \"'\" & sMsg(lCol)\n Next\n End If\n lRow = lRow + 1\nEnd Sub\n\n Public Sub ShowErrorMsg(errThis As ErrObject, strSubName As String, strModName As String _\n , Optional vbMBStyle As VbMsgBoxStyle = vbCritical, Optional sTitle As String = APP_TITLE)\n If errThis.Number <> 0 Then\n MsgBox \"An Error Has Occurred in the Add-in. Please inform \" & ADMINS & \" of this problem.\" _\n & vbCrLf & vbCrLf _\n & \"Error #: \" & errThis.Number & vbCrLf _\n & \"Description: \" & \" \" & errThis.Description & vbCrLf _\n & \"Subroutine: \" & \" \" & strSubName & vbCrLf _\n & \"Module: \" & \" \" & strModName & vbCrLf _\n & \"Source: \" & \" \" & errThis.Source & vbCrLf & vbCrLf _\n & \"Click OK to continue.\", vbMBStyle Or vbSystemModal, sTitle\n End If\nEnd Sub\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11436/" ]
357,824
<p>I would like to automatically align lines of python variable assignments in vim.</p> <p>For example I would like to change this:</p> <pre><code>a = 1 banana = 2 </code></pre> <p>into this</p> <pre><code>a = 1 banana = 2 </code></pre> <p>automatically in vim.</p> <p>Is there a way to do this?</p>
[ { "answer_id": 23134827, "author": "odessos", "author_id": 3545533, "author_profile": "https://Stackoverflow.com/users/3545533", "pm_score": 0, "selected": false, "text": "vap\n\n:!column -t\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045/" ]
357,825
<p>Have you found such a tool and used it successfully?</p>
[ { "answer_id": 358268, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 1, "selected": false, "text": "getTimer() refreshAfterUpdate" }, { "answer_id": 444328, "author": "David Hanak", "author_id": 42136, "author_profile": "https://Stackoverflow.com/users/42136", "pm_score": 4, "selected": false, "text": "flash.utils.getTimer() package {\n public class Profiler {\n private static var instance:Profiler;\n\n public static function get profiler():Profiler {\n if (!Profiler.instance) Profiler.instance = new Profiler;\n return Profiler.instance;\n }\n\n private var data:Object = {};\n\n public function profile(fn:String, dur:int):void {\n if (!data.hasOwnProperty(fn)) data[fn] = new Number(0);\n data[fn] += dur / 1000.0;\n }\n\n public function clear():void {\n data = { };\n }\n\n public function get stats():String {\n var st:String = \"\";\n for (var fn:String in data) {\n st += fn + \":\\t\" + data[fn] + \"\\n\";\n }\n return st;\n }\n }\n}\n import sre, sys\n\nrePOI = sre.compile(r'''\\bclass\\b|\\bfunction\\b|\\breturn\\b|[\"'/{}]''')\nreFun = sre.compile(r'\\bfunction\\b\\s*((?:[gs]et\\s+)?\\w*)\\s*\\(')\nreCls = sre.compile(r'class\\s+(\\w+)[\\s{]')\nreStr = sre.compile(r'''([\"'/]).*?(?<!\\\\)\\1''')\n\ndef addProfilingCalls(body):\n stack = []\n pos = 0\n depth = 0\n retvar = 0\n klass = \"\"\n match = rePOI.search(body, pos)\n while match:\n poi = match.group(0)\n pos = match.start(0)\n endpos = match.end(0)\n\n if poi in '''\"'/''':\n strm = reStr.match(body, pos)\n if strm and (poi != '/' or sre.search('[=(,]\\s*$', body[:pos])):\n endpos = strm.end(0)\n\n elif poi == 'class':\n klass = reCls.match(body, pos).group(1)\n sys.stderr.write('class ' + klass + '\\n')\n\n elif poi == 'function':\n fname = reFun.match(body, pos)\n if fname.group(1):\n fname = klass + '.' + fname.group(1)\n else:\n lastf = stack[-1]\n lastf['anon'] += 1\n fname = lastf['name'] + '.anon' + str(lastf['anon'])\n sys.stderr.write('function ' + fname + '\\n')\n stack.append({'name':fname, 'depth':depth, 'anon':0})\n\n brace = body.find('{', pos) + 1\n line = \"\\nvar __start__:int = flash.utils.getTimer();\"\n body = body[:brace] + line + body[brace:]\n depth += 1\n endpos = brace + len(line)\n\n elif poi == '{':\n depth += 1\n\n elif poi == 'return':\n lastf = stack[-1]\n semicolon = body.find(';', pos) + 1\n if sre.match('return\\s*;', body[pos:]):\n line = \"{ Profiler.profiler.profile('\" + lastf['name'] + \\\n \"', flash.utils.getTimer() - __start__); return; }\"\n else:\n retvar += 1\n line = \"{ var __ret\" + str(retvar) + \"__:* =\" + body[pos+6:semicolon] + \\\n \"\\nProfiler.profiler.profile('\" + lastf['name'] + \\\n \"', flash.utils.getTimer() - __start__); return __ret\" + str(retvar) + \"__; }\"\n body = body[:pos] + line + body[semicolon:]\n endpos = pos + len(line)\n\n elif poi == '}':\n depth -= 1\n if len(stack) > 0 and stack[-1]['depth'] == depth:\n lastf = stack.pop()\n line = \"Profiler.profiler.profile('\" + lastf['name'] + \\\n \"', flash.utils.getTimer() - __start__);\\n\"\n body = body[:pos] + line + body[pos:]\n endpos += len(line)\n\n pos = endpos\n match = rePOI.search(body, pos)\n return body\n\ndef main():\n if len(sys.argv) >= 2: inf = open(sys.argv[1], 'rU')\n else: inf = sys.stdin\n if len(sys.argv) >= 3: outf = open(sys.argv[2], 'wU')\n else: outf = sys.stdout\n outf.write(addProfilingCalls(inf.read()))\n inf.close()\n outf.close()\n\nif __name__ == \"__main__\":\n main()\n" }, { "answer_id": 8889880, "author": "StapleGun", "author_id": 475042, "author_profile": "https://Stackoverflow.com/users/475042", "pm_score": 1, "selected": false, "text": "this.addChild(new TheMiner(true));\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30741/" ]
357,851
<p>My application is receiving email through SMTP server. There are one or more attachments in the email and email attachment return as byte[] (using sun javamail api).</p> <p>I am trying to zip the attachment files on the fly without writing them to disk first.</p> <p>What is/are possible way to achieve this outcome?</p>
[ { "answer_id": 357856, "author": "Eric", "author_id": 6367, "author_profile": "https://Stackoverflow.com/users/6367", "pm_score": 0, "selected": false, "text": "int read(byte[] b, int off, int len)\n Reads up to len bytes of data into an array of bytes from this input stream.\n ZipInputStream This class implements an input stream filter for reading files in the ZIP file format.\n" }, { "answer_id": 357892, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 8, "selected": true, "text": "public static byte[] zipBytes(String filename, byte[] input) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ZipOutputStream zos = new ZipOutputStream(baos);\n ZipEntry entry = new ZipEntry(filename);\n entry.setSize(input.length);\n zos.putNextEntry(entry);\n zos.write(input);\n zos.closeEntry();\n zos.close();\n return baos.toByteArray();\n}\n" }, { "answer_id": 42721500, "author": "Maciej", "author_id": 3497380, "author_profile": "https://Stackoverflow.com/users/3497380", "pm_score": 1, "selected": false, "text": "public StreamedContent getXMLFile() {\n try {\n byte[] blobFromDB= null;\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ZipOutputStream zos = new ZipOutputStream(baos);\n String fileName= \"fileName\";\n ZipEntry entry = new ZipEntry(fileName+\".xml\");\n entry.setSize(byteArray.length);\n zos.putNextEntry(entry);\n zos.write(byteArray);\n zos.closeEntry();\n zos.close();\n InputStream is = new ByteArrayInputStream(baos.toByteArray());\n StreamedContent zipedFile= new DefaultStreamedContent(is, \"application/zip\", fileName+\".zip\", Charsets.UTF_8.name());\n return fileDownload;\n } catch (IOException e) {\n LOG.error(\"IOException e:{} \",e.getMessage());\n } catch (Exception ex) {\n LOG.error(\"Exception ex:{} \",ex.getMessage());\n }\n}\n" }, { "answer_id": 53056226, "author": "Jesús Sánchez", "author_id": 5377223, "author_profile": "https://Stackoverflow.com/users/5377223", "pm_score": 4, "selected": false, "text": " protected byte[] listBytesToZip(Map<String, byte[]> mapReporte) throws IOException {\n String extension = \".pdf\";\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ZipOutputStream zos = new ZipOutputStream(baos);\n for (Entry<String, byte[]> reporte : mapReporte.entrySet()) {\n ZipEntry entry = new ZipEntry(reporte.getKey() + extension);\n entry.setSize(reporte.getValue().length);\n zos.putNextEntry(entry);\n zos.write(reporte.getValue());\n }\n zos.closeEntry();\n zos.close();\n return baos.toByteArray();\n}\n" }, { "answer_id": 62929748, "author": "Alptekin T.", "author_id": 6878003, "author_profile": "https://Stackoverflow.com/users/6878003", "pm_score": 0, "selected": false, "text": "ByteArrayInputStream bais = new ByteArrayInputStream(retByte);\n \nZipInputStream zis = new ZipInputStream(bais);\n \nzis.getNextEntry();\n\nScanner sc = new Scanner(zis);\nwhile (sc.hasNextLine()) {\n System.out.println(\"-->:\" +sc.nextLine());\n}\n\nzis.closeEntry();\nzis.close();\n" }, { "answer_id": 64553578, "author": "Leketo", "author_id": 6179208, "author_profile": "https://Stackoverflow.com/users/6179208", "pm_score": 1, "selected": false, "text": " byte[] createReport() {\n try {\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n ZipArchiveOutputStream zipOutputStream = new \n ZipArchiveOutputStream(byteArrayOutputStream);\n \n zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);\n zipOutputStream.setEncoding(ENCODING);\n\n String text= \"text\";\n byte[] textBytes = text.getBytes(StandardCharsets.UTF_8);\n\n ArchiveEntry zipEntryReportObject = newStoredEntry(\"file.txt\", textBytes);\n zipOutputStream.putArchiveEntry(zipEntryReportObject);\n zipOutputStream.write(textBytes);\n\n zipOutputStream.closeArchiveEntry();\n zipOutputStream.close();\n \n return byteArrayOutputStream.toByteArray();\n } catch (IOException e) {\n return null;\n }\n ArchiveEntry newStoredEntry(String name, byte[] data) {\n ZipArchiveEntry zipEntry = new ZipArchiveEntry(name);\n zipEntry.setSize(data.length);\n zipEntry.setCompressedSize(zipEntry.getSize());\n CRC32 crc32 = new CRC32();\n crc32.update(data);\n zipEntry.setCrc(crc32.getValue());\n return zipEntry;\n }\n" }, { "answer_id": 65545964, "author": "sudhansu", "author_id": 14921458, "author_profile": "https://Stackoverflow.com/users/14921458", "pm_score": 0, "selected": false, "text": "public static void createZip(byte[] data) throws ZipException {\n ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(data));\n ZipParameters parameters = new ZipParameters();\n parameters.setFileNameInZip(\"bank.zip\");\n new ZipFile(\"F:\\\\ssd\\\\bank.zip\").addStream(new ByteArrayInputStream(data), parameters);\n}\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44534/" ]
357,864
<p>What is the best way of handling trying to get data from a DataReader that has more than one column with the same name?</p> <p>Because of the amount of work involved and because we don't want to lose support from a vendor by changing the stored procedures we are using to retrieve the data, I am trying to find another way to get access to a column that shows up more than once in a datareader without having to rewrite the stored procedures.</p> <p>Any Ideas?</p> <p>EDIT: Ok, the function that actually populates from a datareader is used in multiple places so there is a possibility that the function can be called by different stored procedures. What I did was to do a GetName using the index to check if it is the correct column, and if it is, then pull its value.</p>
[ { "answer_id": 58977443, "author": "mrrrk", "author_id": 155791, "author_profile": "https://Stackoverflow.com/users/155791", "pm_score": 1, "selected": false, "text": "using System;\n\nnamespace WhateverProject {\n\n internal static class Extentions {\n\n // If a query returns MULTIPLE columns with the SAME name, this allows us to get the Nth value of a given name.\n public static object NamedValue(this System.Data.IDataRecord reader, string name, int index) {\n if (string.IsNullOrWhiteSpace(name)) return null;\n if (reader == null) return null;\n var foundIndex = 0;\n for (var i = 0; i < reader.FieldCount; i++) {\n if (!reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) continue;\n if (index == foundIndex) return reader[i];\n foundIndex++;\n }\n return false;\n }\n }\n}\n var value1 = reader.NamedValue(\"duplicatedColumnName\", 0);\nvar value2 = reader.NamedValue(\"duplicatedColumnName\", 1);\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8534/" ]
357,903
<p>I am creating a script on the fly to ftp some files from a remote computer. I create a file which is then called from the command line with</p> <pre><code>ftp -s:filename proxy </code></pre> <p>where filename is the file I just created. The file has code similar to the following:</p> <pre><code>anonymous@ip address username prompt off binary cd c:\destination directory mget c:\source directory\*.* quit </code></pre> <p>That doesn't work. Neither does the following:</p> <pre><code>anonymous@ip address username prompt off binary cd c:\source directory mput c:\destination directory quit </code></pre> <p>Obviously, I'm not so good at ftp. How, in what order, where in my file do I specify the place where I want the files to be put (destination directory, and also from where the ftp process is running), and where I want the files to come from (ip address computer which has files I want). Do I need to set the directory before starting the ftp process?</p> <p>I'm running this in an SSIS package, and I'm not using the SSIS ftp task, because I don't want a failure if no files are found. If there's nothing there, that's cool. If there is something there, I want a copy.</p> <p>(It was working in my development area, and now, when I'm trying to get files from a server that I truely have no access to except ftp, I'm not getting anything. See <a href="https://stackoverflow.com/questions/140850/the-best-way-for-a-ssis-ftp-task-to-not-fail-when-there-are-no-files-to-copy">How to avoid SSIS FTP task from failing when there are no files to download?</a> for an earlier, related question.)</p> <p><strong>Update:</strong> Both of the answers below, listing lcd and cd, are correct. However, my example still failed, until I replaced the backslashes with forward slashes. In other words, my final, working result is as follows:</p> <pre><code>anonymous@ip address username prompt off binary lcd /destination directory cd /source directory mget *.* quit </code></pre>
[ { "answer_id": 357934, "author": "DaEagle", "author_id": 43024, "author_profile": "https://Stackoverflow.com/users/43024", "pm_score": 2, "selected": false, "text": "LCD c:\\destination directory\nmget c:\\source directory\\*.*\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22523/" ]
357,911
<p>I have an application with several files that contain configuration parameters and other data that changes as the user uses the application. These files can change with newer versions of my software, but the user can also modify them (or they may be changed by the application itself). Basically, I'm looking for a solution to prevent the users' changes to these files from being overwritten but also a way to install the potentially updated files when the user upgrades my software. </p> <p>With RPM on *NIX you could use the %config function to define a file as a configuration file and RPM would then rename the existing file (if it existed) and install the new one on an upgrade (maybe not ideal, but I could live with something like this for WiX).</p> <p>I'd like to install my config files to a subdirectory or even a different name (e.g. default.cfg) and then use the <code>&lt;CopyFile&gt;</code> element in WiX to copy the files to their correct locations. This way, the default files would get removed on install and overwritten on an upgrade, but the actual user files would stay the same. Unfortunately with <code>&lt;CopyFile&gt;</code>, Windows Installer still wants to manage (and remove) the destination file.</p> <p>I've also considered using the QtExec action in WixUtilExtension to basically do "copy default.cfg reallocation.cfg" but this wouldn't quite work and it is a bit of a hack.</p> <p>What is the correct way to handle this?</p>
[ { "answer_id": 360509, "author": "wimh", "author_id": 33499, "author_profile": "https://Stackoverflow.com/users/33499", "pm_score": 2, "selected": false, "text": "<Directory Id=\"MYDIR\" Name=\"MyDir\">\n <Component Id=\"update.cmd\" Guid=\"YOUR-GUID\">\n <File Id=\"update.cmd\" Name=\"update.cmd\" KeyPath=\"yes\" \n Source=\"source\\update.cmd\" />\n </Component>\n</Directory>\n\n<CustomAction Id='RunUpdate' Directory='MYDIR' \n ExeCommand='[SystemFolder]cmd.exe /c update.cmd' Return='ignore'/>\n\n<InstallExecuteSequence>\n <Custom Action='RunUpdate' After='InstallFinalize'>NOT Installed</Custom>\n</InstallExecuteSequence>\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26302/" ]
357,923
<p>In an application I'm developing, someone thought it would be ok idea to include commas in the values of a csv file. So what I'm trying to do select these values and then strip the commas out of these values. But the Regex I've built won't match to anything. </p> <p><strong><em>The Regex pattern is:</em></strong> <code>.*,\"&lt;money&gt;(.+,.+)\",?.*</code> </p> <p>And the sort of values I'm trying to match would be the <code>2700, 2650 and 2600 in "2,700","2,650","2,600"</code>.</p>
[ { "answer_id": 357978, "author": "Ryan Cook", "author_id": 43029, "author_profile": "https://Stackoverflow.com/users/43029", "pm_score": 2, "selected": false, "text": "string ResultString = null;\ntry {\n ResultString = Regex.Replace(myString, \"([0-9]{1,3})(?:(,)?([0-9]{3})?)\", \"$1$3\");\n} catch (ArgumentException ex) {\n // Syntax error in the regular expression\n}\n" }, { "answer_id": 358000, "author": "Twisted Mentat", "author_id": 41492, "author_profile": "https://Stackoverflow.com/users/41492", "pm_score": 1, "selected": true, "text": "\\\"(?<money>[0-9,.$]*)\\\" \\\"([0-9.$]+(,[0-9.]+)+)\\\"" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41492/" ]
357,929
<p>Ought I to unit test constructors? Say I have a constructor like this:</p> <pre><code>IMapinfoWrapper wrapper; public SystemInfo(IMapinfoWrapper mapinfoWrapper) { this.wrapper = mapinfoWrapper; } </code></pre> <p>Do I need to write a unit test for this construtor? I don't have any getters for the wrapper variable, so I don't need to test that.</p>
[ { "answer_id": 358006, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 0, "selected": false, "text": "SystemInfo wrapper IMapinfoWrapper" }, { "answer_id": 24241701, "author": "Zoran Horvat", "author_id": 2279448, "author_profile": "https://Stackoverflow.com/users/2279448", "pm_score": 3, "selected": false, "text": "[TestMethod]\npublic void Constructor_FullTest()\n{\n\n IDrawingContext context = new Mock<IDrawingContext>().Object; \n\n ConstructorTests<Frame>\n .For(typeof(int), typeof(int), typeof(IDrawingContext))\n .Fail(new object[] { -3, 5, context }, typeof(ArgumentException), \"Negative length\")\n .Fail(new object[] { 0, 5, context }, typeof(ArgumentException), \"Zero length\")\n .Fail(new object[] { 5, -3, context }, typeof(ArgumentException), \"Negative width\")\n .Fail(new object[] { 5, 0, context }, typeof(ArgumentException), \"Zero width\")\n .Fail(new object[] { 5, 5, null }, typeof(ArgumentNullException), \"Null drawing context\")\n .Succeed(new object[] { 1, 1, context }, \"Small positive length and width\")\n .Succeed(new object[] { 3, 4, context }, \"Larger positive length and width\")\n .Assert();\n\n}\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
357,956
<p>In reading Haskell-related stuff I sometimes come across the expression “tying the knot”, I think I understand <em>what</em> it does, but not <em>how</em>.</p> <p>So, are there any good, basic, and simple to understand explanations of this concept?</p>
[ { "answer_id": 393953, "author": "Paul Johnson", "author_id": 49220, "author_profile": "https://Stackoverflow.com/users/49220", "pm_score": 7, "selected": true, "text": "alternates = x where\n x = 0 : y\n y = 1 : x\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34996/" ]
357,963
<p>I am developing a prototype for a game, and certain gameplay rules are to be defined in an ini file so that the game designers can tweak the game parameters without requiring help from me in addition to a re-compile. This is what I'm doing currently:</p> <pre><code>std::ifstream stream; stream.open("rules.ini"); if (!stream.is_open()) { throw new std::exception("Rule file could not be opened"); } // read file contents here stream.close(); </code></pre> <p>However, my stream never opens succesfully. Diving deep into the STL source during debugging reveals that _getstream() (as defined in stream.c) keeps on returning NULL, but I just can't figure out why this is. Help, anyone?</p> <p>Edit: Rules.ini is in the same directory as the .exe file.</p>
[ { "answer_id": 358115, "author": "Drew Dormann", "author_id": 16287, "author_profile": "https://Stackoverflow.com/users/16287", "pm_score": 4, "selected": true, "text": "argv[0] main() GetModuleFileName()" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37472/" ]
357,968
<p>I am working on <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow noreferrer">Conway's Game of Life</a> currently and have gotten stuck. My code doesn't work.</p> <p>When I run my code in GUI, it says:</p> <pre> [[0 0 0 0] [0 1 1 0] [0 1 0 0] [0 0 0 0]] Traceback (most recent call last): File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in b= apply_rules(a) File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules neighbours=number_neighbours(universe_array,iy,ix) File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours neighbours+=1 UnboundLocalError: local variable 'neighbours' referenced before assignment </pre> <p>Here is my code:</p> <pre><code>'''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1 If a cell is alive at time T with less than two living neighbours it dies at T+1 If a cell is alive at time T with more than three live neighbours it dies at T+1 If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1''' import numpy def apply_rules (universe_array): height, width = universe_array.shape # create a new array for t+1 evolved_array = numpy.zeros((height, width),numpy.uint8) for iy in range(1, height-1): for ix in range(1,width-1): neighbours=number_neighbours(universe_array,iy,ix) if universe_array[iy,ix]==0 and neighbours==3: evolved_array[iy,ix]==1 elif universe_array[iy,ix]==1 and neighbours&lt;2: evolved_array[iy,ix]==0 elif universe_array[iy,ix]==1 and neighbours&gt;3: evolved_array[iy,ix]==0 elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3: evolved_array[iy,ix]=universe_array[iy,ix] return evolved_array def number_neighbours(universe_array,iy,ix): neighbours=0 #fixed this line,thanks:) if universe_array[iy-1,ix-1]==1: neighbours+=1 if universe_array[iy,ix-1]==1: neighbours+=1 if universe_array[iy+1,ix-1]==1: neighbours+=1 if universe_array[iy-1,ix]==1: neighbours+=1 if universe_array[iy+1,ix]==1: neighbours+=1 if universe_array[iy-1,ix+1]==1: neighbours+=1 if universe_array[iy,ix+1]==1: neighbours+=1 if universe_array[iy+1,ix+1]==1: neighbours+=1 else: neighbours=neighbours return neighbours if __name__ == "__main__": a = numpy.zeros((4,4),numpy.uint8) a[1,1]=1 a[1,2]=1 a[2,1]=1 print a b= apply_rules(a) print b </code></pre> <p>I am a beginner at Python, and I don't know how to fix the error. I am a little bit confused about <code>import "neighbours"</code> to <code>function "apply_rules"</code>, is that right way to do this?</p>
[ { "answer_id": 357982, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 2, "selected": false, "text": "number_neighbors neighbors def number_neighbours(universe_array,iy,ix):\n if universe_array[iy,ix-1]==1:\n neighbours+=1\n if universe_array[iy,ix-1]==1:\n neighbours+=1\n if universe_array[iy+1,ix-1]==1:\n neighbours+=1\n neighbors +=1 neighbors apply_rules" }, { "answer_id": 358020, "author": "David Locke", "author_id": 1447, "author_profile": "https://Stackoverflow.com/users/1447", "pm_score": 2, "selected": false, "text": "neighbours = 0\n" }, { "answer_id": 358029, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 5, "selected": true, "text": "number_neighbours neighbours+=1 UnboundLocalError: local variable 'neighbours' referenced before assignment += neighbours neighbours neighbours = 0" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44354/" ]
357,969
<p>I am trying to combine some of my CSS and it is kind of an easy questions but I am kind of having some trouble, i have this code:</p> <pre><code>h2.post-title, h2.post-title a{ display:block; background-color:#000; padding:3px; color:#ffffff; text-decoration:none; text-transform:uppercase; font:lighter 130% Georgia, Arial; } </code></pre> <p>Do I need to have both of those selectors there? The only time I will be using the <code>h2.post-title</code> it will be a link. Any suggestions, I tried removing the first one, but it made it HUGE.</p> <p>Thoughts?</p>
[ { "answer_id": 357992, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 3, "selected": true, "text": "h2.post-title {\n font-size:130%;\n}\n" }, { "answer_id": 357999, "author": "qualbeen", "author_id": 36975, "author_profile": "https://Stackoverflow.com/users/36975", "pm_score": -1, "selected": false, "text": "<h2 class=\"post-title\"><a href=\"#\">Clickable title</a></h2>\n <h2><a class=\"post-title\" href=\"#\">Clickable title</a></h2>\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
357,997
<p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p> <p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p> <pre><code>new OptionParser () { public void exit() { // body of the method } }; </code></pre> <p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p> <p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
[ { "answer_id": 358012, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 4, "selected": false, "text": "def printStuff():\n print \"hello\"\n\ndef doit(what):\n what()\n\ndoit(printStuff) \n" }, { "answer_id": 358035, "author": "rob", "author_id": 43927, "author_profile": "https://Stackoverflow.com/users/43927", "pm_score": 2, "selected": false, "text": "class a(object):\n def meth_a(self):\n print \"a\"\n\ndef meth_b(obj):\n print \"b\"\n\nb = a()\nb.__class__.meth_a = meth_b\n" }, { "answer_id": 358042, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 3, "selected": false, "text": "lambda object.method1 = alternative_impl1" }, { "answer_id": 358055, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 4, "selected": false, "text": "import types\nclass someclass(object):\n val = \"Value\"\n def some_method(self):\n print self.val\n\ndef some_method_upper(self):\n print self.val.upper()\n\nobj = someclass()\nobj.some_method()\n\nobj.some_method = types.MethodType(some_method_upper, obj)\nobj.some_method()\n" }, { "answer_id": 358062, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 4, "selected": false, "text": "from optparse import OptionParser\ndef make_custom_op(i):\n class MyOP(OptionParser):\n def exit(self):\n print 'custom exit called', i\n return MyOP\n\ncustom_op_class = make_custom_op(3)\ncustom_op = custom_op_class()\n\ncustom_op.exit() # prints 'custom exit called 3'\ndir(custom_op) # shows all the regular attributes of an OptionParser\n __init__" }, { "answer_id": 359651, "author": "davidavr", "author_id": 8247, "author_profile": "https://Stackoverflow.com/users/8247", "pm_score": 3, "selected": false, "text": "class MyOptionParser(OptionParser):\n def exit(self, status=0, msg=None):\n # body of method\n\np = MyOptionParser()\n" }, { "answer_id": 3915434, "author": "Joe Hildebrand", "author_id": 8388, "author_profile": "https://Stackoverflow.com/users/8388", "pm_score": 7, "selected": true, "text": "type(name, bases, dict) op = type(\"MyOptionParser\", (OptionParser,object), {\"foo\": lambda self: \"foo\" })\nop().foo()\n object" }, { "answer_id": 6175128, "author": "Maciej Piechotka", "author_id": 49107, "author_profile": "https://Stackoverflow.com/users/49107", "pm_score": 0, "selected": false, "text": " class var(...):\n pass\n var = var()\n var = new ...() {};\n" }, { "answer_id": 54321110, "author": "grepit", "author_id": 717630, "author_profile": "https://Stackoverflow.com/users/717630", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python3\nclass ExmapleClass:\n def exit(self):\n print('this should NOT print since we are going to override')\n\nExmapleClass= type('', (ExmapleClass,), {'exit': lambda self: print('you should see this printed only')})()\nExmapleClass.exit()\n" }, { "answer_id": 55614004, "author": "g4borg", "author_id": 2528379, "author_profile": "https://Stackoverflow.com/users/2528379", "pm_score": 0, "selected": false, "text": "class SomeSerializer():\n class __Paginator(Paginator):\n page_size = 10\n\n # defining it for e.g. Rest:\n pagination_class = __Paginator\n\n # you could also be accessing it to e.g. create an instance via method:\n def get_paginator(self):\n return self.__Paginator()\n SomeSerializer._SomeSerializer__Paginator" }, { "answer_id": 65893807, "author": "otterrisk", "author_id": 5984810, "author_profile": "https://Stackoverflow.com/users/5984810", "pm_score": 0, "selected": false, "text": "_ class _(OptionParser):\n\n def exit(self):\n pass # your override impl\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/357997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36131/" ]
358,003
<p>Is there a function in the C Library under Linux which can set the length of a file? Under Windows I know there is a SetFileLength() function. If there is not, what is the best way of shortening a file without deleting and rewriting it?</p>
[ { "answer_id": 358007, "author": "codelogic", "author_id": 43427, "author_profile": "https://Stackoverflow.com/users/43427", "pm_score": 4, "selected": true, "text": "int truncate(const char *path, off_t length);" }, { "answer_id": 358008, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": " #include <unistd.h>\n #include <sys/types.h>\n\n int truncate(const char *path, off_t length);\n int ftruncate(int fd, off_t length);\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/358003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44952/" ]
358,025
<p>I need to keep the arrow keys from being able to scroll through my various tabs. Anyone know of a way to do this?</p>
[ { "answer_id": 358030, "author": "Eric", "author_id": 6367, "author_profile": "https://Stackoverflow.com/users/6367", "pm_score": -1, "selected": true, "text": "System::Windows::Forms::KeyPressEventArgs^ e\n if (e->KeyChar == [find the number representing the arrow key])\n e->Handled = true; // Meaning that no one will receive it afterwards\n" }, { "answer_id": 361144, "author": "Matt", "author_id": 19802, "author_profile": "https://Stackoverflow.com/users/19802", "pm_score": 0, "selected": false, "text": "string tempstring = e.KeyValue.ToString();\nif (tempstring == \"37\" || tempstring == \"38\" || tempstring == \"39\" || tempstring == \"40\")\n{\n e.Handled = true;\n}\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/358025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19802/" ]
358,037
<p>I am using a program that talks to my COMM port, but I have made another program that I want to "sniff" the comm port messages and perform it's own actions against those messages in addition. Is this possible in .NET c#?</p>
[ { "answer_id": 25639355, "author": "jbutler483", "author_id": 3436942, "author_profile": "https://Stackoverflow.com/users/3436942", "pm_score": 0, "selected": false, "text": "void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)\n{\n int dataLength = _serialPort.BytesToRead;\n byte[] data = new byte[dataLength];\n int nbrDataRead = _serialPort.Read(data, 0, dataLength);\n if (nbrDataRead == 0)\n return;\n\n // Send data to whom ever interested\n if (NewSerialDataRecieved != null)\n NewSerialDataRecieved(this, new SerialDataEventArgs(data));\n}\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/358037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ]
358,039
<p>What is the meaning, and where is the Ruby documentation for the syntax of: </p> <pre><code>Array(phrases) </code></pre> <p>which I found browsing the Rails source here:</p> <pre><code># File actionpack/lib/action_view/helpers/text_helper.rb, line 109 ... 119: match = Array(phrases).map { |p| Regexp.escape(p) }.join('|') </code></pre> <p>I thought that Array.new would normally be used to create an array, so something different must be going on here. BTW from the context around this code, the <code>phrases</code> variable can be either a string or an array of strings.</p>
[ { "answer_id": 358078, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 5, "selected": true, "text": "Kernel#Array Array.new to_ary to_a" }, { "answer_id": 358085, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 2, "selected": false, "text": "Array(1..5) » [1, 2, 3, 4, 5] \n" }, { "answer_id": 13027411, "author": "Daniel Rikowski", "author_id": 23368, "author_profile": "https://Stackoverflow.com/users/23368", "pm_score": 2, "selected": false, "text": "Kernel#Array to_ary to_a Array([1,2,3]) -> [1,2,3]\nArray(1..3) -> [1,2,3]\nArray({ a: 1, b: 2 }) -> [[:a, 1],[:b,2]]\nArray(\"Hello World\") -> [\"Hello World\"]\nArray(1) -> [1]\n Kernel#Array # data can be nil, a single value or an array\ndef handle(data)\n data ||= Array.new #Case 1: Data is nil\n data = [data] unless data.is_a?(Array) #Case 2: Data is a single value\n data.each { |d| ... }\nend\n Kernel#Array def handle(data)\n Array(data).each { |d| ... }\nend\n data to_ary to_a" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/358039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37572/" ]
358,048
<p>I am using a third party application and would like to change one of its files. The file is stored in XML but with an invalid doctype.</p> <p>When I try to read use a it errors out becuase the doctype contains "file:///ReportWiz.dtd" (as shown, with quotes) and I get an exception for cannot find file. Is there a way to tell the docbuilder to ignore this? I have tried setValidate to false and setNamespaceAware to false for the DocumentBuilderFactory. </p> <p>The only solutions I can think of are</p> <ul> <li>copy file line by line into a new file, omitting the offending line, doing what i need to do, then copying into another new file and inserting the offending line back in, or </li> <li>doing mostly the same above but working with a FileStream of some sort (though I am not clear on how I could do this..help?)</li> </ul> <pre>DocumentBuilderFactory docFactory = DocumentBuilderFactory .newInstance(); docFactory.setValidating(false); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file);</pre>
[ { "answer_id": 358104, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": " EntityResolver er = new EntityResolver() {\n @Override\n public InputSource resolveEntity(String publicId, String systemId)\n throws SAXException, IOException {\n if (\"file:///ReportWiz.dtd\".equals(systemId)) {\n System.out.println(systemId);\n InputStream zeroData = new ByteArrayInputStream(new byte[0]);\n return new InputSource(zeroData);\n }\n return null;\n }\n };\n" }, { "answer_id": 358112, "author": "Sophie Gage", "author_id": 37134, "author_profile": "https://Stackoverflow.com/users/37134", "pm_score": 3, "selected": true, "text": "docFactory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n org.jdom.input.SAXBuilder builder = new SAXBuilder();\nbuilder.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\norg.jdom.Document doc = builder.build(file);\n" } ]
2008/12/10
[ "https://Stackoverflow.com/questions/358048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ]
358,069
<p>I just bought Visual Studio 2008 Professional and it came with SQL Server 2005 Developer Edition. I'm used to using SQL Server 2005 at work, but the Developer edition doesn't seem to come with Server Management Studio, so I'm at a bit of a loss. A few questions:</p> <ol> <li>What resources are there for configuring and setting up SQL Server 2005 Developer Edition?</li> <li>What are some resources for managing databases (I know that I can have Multiple Databases with SQL Server 2005), and what 'extras' are provided by Developer Edition?</li> <li>Are there any funky things I need to know about if I were to create a database and move it from Developer Edition to an actual deployment server?</li> <li>Are there any other 'gotchas'?</li> </ol> <hr> <p>Edit: I've answered the 'Why isn't SQL Server Management Studio showing up' question below. Resources for the other questions are still appreciated.</p> <p>Any other insights?</p>
[ { "answer_id": 358158, "author": "George Stocker", "author_id": 16587, "author_profile": "https://Stackoverflow.com/users/16587", "pm_score": 2, "selected": false, "text": "D:\\SQL Server x86\\Servers\\setup.exe -SKUUPGRADE=1" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16587/" ]
358,072
<p>I have a javascript heavy app which has widgets like autocomplete dropdowns and tabs and so forth. Sometimes when dropdowns appear and disappear, or when you switch between tabs, it changes the height of the document. This can cause annoyances if the scrollbar appears and disappears rapidly, because it shifts the page. I would like to detect when a page changes its height, so I can fix the height to the maximum so far, so that if the scrollbar appears it won't disappear only a second later. Any suggestions?</p> <p><em>Update: onresize won't work because that's for changes in the size of the viewport/window - I want changes in the length of the document. I hadn't known about the watch function, looks like it will work at least for FF, but IE doesn't support it.</em></p>
[ { "answer_id": 358190, "author": "ng.mangine", "author_id": 37784, "author_profile": "https://Stackoverflow.com/users/37784", "pm_score": -1, "selected": false, "text": "document.body.watch(\"clientHeight\", function(property, oldHeight, newHeight) {\n // what you want to do when the height changes\n});\n" }, { "answer_id": 28984636, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "$(window).resize(function(){\n // your code to check sizes and take action\n }\n);\n $(document).resize(function(){\n // your code to check sizes and take action\n }\n);\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5304/" ]
358,092
<p>Is the following possible in SQL Server 2000?</p> <pre><code>CREATE FUNCTION getItemType (@code varchar(18)) RETURNS int AS BEGIN Declare @Type tinyint Select @Type = case len(@code) WHEN 12,14,17 THEN 1 WHEN 13,15,18 THEN 2 WHEN 8,10 THEN 3 ELSE 0 END RETURN (@Type) END </code></pre> <p>Thanks.</p>
[ { "answer_id": 358097, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": " try \n SELECT CASE\n WHEN LEN(@gcode) IN(x, y, z) THEN a \n END\n etc.\n SELECT CASE LEN(@gcode) \n WHEN x THEN a \n WHEN y THEN a \n END\n" }, { "answer_id": 358101, "author": "keithwarren7", "author_id": 40714, "author_profile": "https://Stackoverflow.com/users/40714", "pm_score": 3, "selected": true, "text": "Select @Type = \n(select case \nWHEN len(@code) IN (12,14,17) THEN 1\nWHEN len(@code) IN (13,15,18) THEN 2\nWHEN len(@code) IN (8,10) THEN 3\nELSE 0\nEND)\n" }, { "answer_id": 358107, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION getItemType(@code VARCHAR(18))\nRETURNS INT\nAS\nBEGIN\n RETURN CASE \n WHEN LEN(@code) IN (12,14,17) THEN 1\n WHEN LEN(@code) IN (13,15,18) THEN 2\n WHEN LEN(@code) IN (8,100) THEN 3\n ELSE 0\n END\nEND\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
358,120
<p>On Internet Explorer, the standard HTML file upload form also allows for direct input of the file name (instead of using the file selector dialog). This makes it possible to enter non-existing files. On other browsers (which do not let you do that) I suppose this case can still occur if you delete the file after having selected it.</p> <p>In order to deal with bugs arising from this problem (like <a href="http://dev.fckeditor.net/ticket/2716" rel="nofollow noreferrer">this one</a>), I need to add some validation code on the server-side (which is only possible if the request actually goes to the server, of which I am not sure at this point), or on the client-side (which cannot be very straightforward, as you cannot access the actual file from the JavaScript sandbox). Other than that, the only (and possibly best) option seems to be to hide the input box with CSS magic, like GMail does for attachment files.</p> <p>So, what happens when you try to upload a non-existing file? Is there still a POST request being sent? Or will the browser abort, and if it does, how can I detect that?</p>
[ { "answer_id": 361947, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 2, "selected": false, "text": "try{\n form.submit();\n}\ncatch (e){\n// show some error message\n}\nreturn false;\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14955/" ]
358,136
<p>What is the most efficient way to remove duplicate items from an array under the constraint that axillary memory usage must be to a minimum, preferably small enough to not even require any heap allocations? Sorting seems like the obvious choice, but this is clearly not asymptotically efficient. Is there a better algorithm that can be done in place or close to in place? If sorting is the best choice, what kind of sort would be best for something like this?</p>
[ { "answer_id": 358171, "author": "Doug Currie", "author_id": 33252, "author_profile": "https://Stackoverflow.com/users/33252", "pm_score": 0, "selected": false, "text": "function removedups (t)\n local result = {}\n local count = 0\n local found\n for i,v in ipairs(t) do\n found = false\n if count > 0 then\n for j = 1,count do\n if v == result[j] then found = true; break end\n end\n end\n if not found then \n count = count + 1\n result[count] = v \n end\n end\n return result, count\nend\n" }, { "answer_id": 358353, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 0, "selected": false, "text": "// returns the new size\nint bubblesqueeze(int* a, int size) {\n for (int j = 0; j < size - 1; ++j) {\n for (int i = j + 1; i < size; ++i) {\n // when a dupe is found, move the end value to index j\n // and shrink the size of the array\n while (i < size && a[i] == a[j]) {\n a[i] = a[--size];\n }\n if (i < size && a[i] < a[j]) {\n int tmp = a[j];\n a[j] = a[i];\n a[i] = tmp;\n }\n }\n }\n return size;\n}\n" }, { "answer_id": 358752, "author": "eaanon01", "author_id": 36986, "author_profile": "https://Stackoverflow.com/users/36986", "pm_score": 0, "selected": false, "text": "#define ARRAY_LENGTH 15\nint stop = 1;\nint scan_sort[ARRAY_LENGTH] = {5,2,3,5,1,2,5,4,3,5,4,8,6,4,1};\n\nvoid step_relocate(char tmp,char s,int *dataset)\n{\n for(;tmp<s;s--)\n dataset[s] = dataset[s-1];\n}\nint exists(int var,int *dataset)\n{\n int tmp=0;\n for(;tmp < stop; tmp++)\n {\n if( dataset[tmp] == var)\n return 1;/* value exsist */\n if( dataset[tmp] > var)\n tmp=stop;/* Value not in array*/\n }\n return 0;/* Value not in array*/\n}\nvoid main(void)\n{\n int tmp1=0;\n int tmp2=0;\n int index = 1;\n while(index < ARRAY_LENGTH)\n {\n if(exists(scan_sort[index],scan_sort))\n ;/* Dismiss all values currently in the final dataset */\n else if(scan_sort[stop-1] < scan_sort[index])\n {\n scan_sort[stop] = scan_sort[index];/* Insert the value as the highest one */\n stop++;/* One more value adde to the final dataset */\n }\n else\n {\n for(tmp1=0;tmp1<stop;tmp1++)/* find where the data shall be inserted */\n {\n if(scan_sort[index] < scan_sort[tmp1])\n {\n index = index;\n break;\n }\n }\n tmp2 = scan_sort[index]; /* Store in case this value is the next after stop*/\n step_relocate(tmp1,stop,scan_sort);/* Relocated data already in the dataset*/\n scan_sort[tmp1] = tmp2;/* insert the new value */\n stop++;/* One more value adde to the final dataset */\n }\n index++;\n }\n printf(\"Result: \");\n for(tmp1 = 0; tmp1 < stop; tmp1++)\n printf( \"%d \",scan_sort[tmp1]);\n printf(\"\\n\");\n system( \"pause\" );\n}\n" }, { "answer_id": 359778, "author": "dsimcha", "author_id": 23903, "author_profile": "https://Stackoverflow.com/users/23903", "pm_score": 2, "selected": false, "text": "void uniqueInPlace(T)(ref T[] dataIn) {\n uniqueInPlaceImpl(dataIn, 0);\n}\n\nvoid uniqueInPlaceImpl(T)(ref T[] dataIn, size_t start) {\n if(dataIn.length - start < 2)\n return;\n\n invariant T sentinel = dataIn[start];\n T[] data = dataIn[start + 1..$];\n\n static hash_t getHash(T elem) {\n static if(is(T == uint) || is(T == int)) {\n return cast(hash_t) elem;\n } else static if(__traits(compiles, elem.toHash)) {\n return elem.toHash;\n } else {\n static auto ti = typeid(typeof(elem));\n return ti.getHash(&elem);\n }\n }\n\n for(size_t index = 0; index < data.length;) {\n if(data[index] == sentinel) {\n index++;\n continue;\n }\n\n auto hash = getHash(data[index]) % data.length;\n if(index == hash) {\n index++;\n continue;\n }\n\n if(data[index] == data[hash]) {\n data[index] = sentinel;\n index++;\n continue;\n }\n\n if(data[hash] == sentinel) {\n swap(data[hash], data[index]);\n index++;\n continue;\n }\n\n auto hashHash = getHash(data[hash]) % data.length;\n if(hashHash != hash) {\n swap(data[index], data[hash]);\n if(hash < index)\n index++;\n } else {\n index++;\n }\n }\n\n\n size_t swapPos = 0;\n foreach(i; 0..data.length) {\n if(data[i] != sentinel && i == getHash(data[i]) % data.length) {\n swap(data[i], data[swapPos++]);\n }\n }\n\n size_t sentinelPos = data.length;\n for(size_t i = swapPos; i < sentinelPos;) {\n if(data[i] == sentinel) {\n swap(data[i], data[--sentinelPos]);\n } else {\n i++;\n }\n }\n\n dataIn = dataIn[0..sentinelPos + start + 1];\n uniqueInPlaceImpl(dataIn, start + swapPos + 1);\n}\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23903/" ]
358,147
<p>I have two computers. Both running WinXP SP2 (I don't really know ho similar they are beyond that). I am running MS Visual C# 2008 express edition on both and that's what I'm currently using to program.</p> <p>I made an application that loads in an XML file and displays the contents in a DataGridView.</p> <p>The first line of my xml file is:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; </code></pre> <p>...and really... it's utf-8 (at least according to MS VS C# when I just open the file there).</p> <p>I compile the code and run it on one computer, and the contents of my DataGridView appears normal. No funny characters. I compile the code and run it on the other computer (or just take the published version from computer #1 and install it on computer #2 - I tried this both ways) and in the datagridview, where there are line breaks/new lines in the xml file, I see funny square characters.</p> <p>I'm a novice to encoding... so the only thing I really tried to troubleshoot was to use that same program to write the contents of my xml to a new xml file (but I'm actually writing it to a text file, with the xml tags in it) since the default writing to a text file seems to be utf-8. Then I read this new file back in to my program. I get the same results.</p> <p>I don't know what else to do or how to troubleshoot this or what I might fundamentally be doing wrong in the first place.</p> <p>-Adeena</p>
[ { "answer_id": 358164, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "0D 0A" }, { "answer_id": 358165, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 2, "selected": false, "text": "(0A) (0D0A) (0D) Environment.NewLine strInput = Regex.Replace(strInput, \"\\\\r?\\\\n?\", Environment.NewLine)\n" }, { "answer_id": 361450, "author": "adeena", "author_id": 44004, "author_profile": "https://Stackoverflow.com/users/44004", "pm_score": 0, "selected": false, "text": "XElement xe1 = XElement.Load(filePath);\n\nDataTable myTable = new DataTable();\nmyTable = mkTable(); // calls a function that makes the table\nvar _categories = (from p1 in xe1.Descendants(\"category\") select p1);\nint numCat = _categories.Count();\nint i = 0;\n\nwhile (i < numCat)\n{\n DataRow newrow;\n newrow = myTable.NewRow();\n\n if (_categories.ElementAt(i).Parent.Name == \"topic\")\n {\n string att1 = _categories.ElementAt(i).Parent.Attribute(\"name\").Value.ToString();\n newrow[\"topic\"] = att1.ToString();\n }\n // repeat the above for the different things in my document\n myTable.Rows.Add(newrow);\n\n i++;\n}\nmyDataSet.Merge(myTable);\nbindingSourceIn.DataSource = myDataSet;\nmyDataGridView.DataSource = bindingSourceIn;\nmyDataGridView.DataMember = \"xmlthing\";\n" }, { "answer_id": 362034, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": true, "text": "TrimEnd(null) newrow[\"topic\"] = att1.ToString().TrimEnd(null);\n TrimEnd newrow[\"topic\" = att1.ToString().TrimEnd(new Char[]{'\\r'});\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44004/" ]
358,160
<p>I've isolated the behaviour into the following test case. I'd be grateful to anyone who can tell me how to expect/verify a property set for a <code>List&lt;T&gt;</code> property - it appears there's something going on inside <code>It.Is&lt;T&gt;(predicate)</code> that isn't making a whole lot of sense to me right now. Sample code will run as a console app from VS2008 - you'll need to add a reference to Moq 2.6 (I'm on 2.6.1014.1) - please try uncommenting the different ExpectSet statements to see what's happening...</p> <pre><code>using System; using Moq; using System.Collections.Generic; namespace MoqDemo { public interface IView { List&lt;string&gt; Names { get; set; } } public class Controller { private IView view; public Controller(IView view) { this.view = view; } public void PopulateView() { List&lt;string&gt; names = new List&lt;string&gt;() { "Hugh", "Pugh", "Barney McGrew" }; view.Names = names; } public class MyApp { public static void Main() { Mock&lt;IView&gt; mockView = new Mock&lt;IView&gt;(); // This works - and the expectation is verifiable. mockView.ExpectSet(mv =&gt; mv.Names); // None of the following can be verified. // mockView.ExpectSet(mv =&gt; mv.Names, It.Is&lt;Object&gt;(o =&gt; o != null)); // mockView.ExpectSet(mv =&gt; mv.Names, It.Is&lt;List&lt;string&gt;&gt;(names =&gt; names.Count == 3)); // mockView.ExpectSet(mv =&gt; mv.Names, It.IsAny&lt;IList&lt;String&gt;&gt;()); Controller controller = new Controller(mockView.Object); controller.PopulateView(); try { mockView.VerifyAll(); Console.WriteLine("Verified OK!"); } catch (MockException ex) { Console.WriteLine("Verification failed!"); Console.WriteLine(ex.Message); } Console.ReadKey(false); } } } } </code></pre>
[ { "answer_id": 358202, "author": "Mike Scott", "author_id": 43649, "author_profile": "https://Stackoverflow.com/users/43649", "pm_score": 1, "selected": false, "text": "It.Is<T> var mockView = new Mock<IView>();\nvar list = new List<string> { \"Hugh\", \"Pugh\", \"Barney McGrew\" };\n\nmockView.ExpectSet(mv => mv.Names, list);\n\nmockView.Object.Names = list;\n" }, { "answer_id": 358237, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": true, "text": "mockView.ExpectSet(mv => mv.Names).Callback(n => Assert.That(n != null));\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5017/" ]
358,168
<p>Ok, I'm doing a bunch of RIA/AJAX stuff and need to create a "pretty", custom confirm box which is a DIV (not the built-in javascript confirm). I'm having trouble determining how to accomplish a pause in execution to give the user a chance to accept or decline the condition before either resuming or halting execution. (depending upon their answer) </p> <p>So here's the general flow of logic I'm dealing with:</p> <ol> <li>User selects an item from dropdown and clicks button.</li> <li>In client-side javascript eventhandler for button, I need to check a (this is the key) SERIES of conditions for the item they chose in dropdown. </li> <li>These conditions could possibly result in not showing any confirmation at all or possibly only some of the conditions may evaluate to true which means I'll need to ask the user to accept or decline the condition before proceeding. Only one confirmation should be show at a time.</li> </ol> <p>To demonstrate the logic:</p> <pre><code>function buttonEventHandler() { if (condition1) { if(!showConfirmForCondition1) // want execution to pause while waiting for user response. return; // discontinue execution } if (condition2) { if (!showConfirmForCondition2) // want execution to pause while waiting for user response. return; // discontinue execution } if (condition3) { if (!showConfirmForCondition3) // want execution to pause while waiting for user response. return; // discontinue execution } ... } </code></pre> <p>If anybody has dealt with this challenge before and found a solution, help would be greatly appreciated. As a note, I'm also using the <b>MS Ajax</b> and <b>jQuery</b> libraries although I haven't found any functionality that may already be included in those for this problem.</p>
[ { "answer_id": 473778, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "customConfirm // obtain the element(we will call it targetObject) that triggered the event\n\ntargetObject = (event.target==undefined ? event.srcElement : event.target);\n\n// include a call to _doPostBack in the onclick event of OK/YES button ONLY\n\n(targetObject.href!=undefined){ eval(targetObject.href); } else{ _doPostBack(targetObject.name,''); // it is assumed that name is available\n __doPostBack" }, { "answer_id": 1137100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function BeforeDelete(controlUniqueId) {\n confirmPopup('question...?', function() { __doPostBack(controlUniqueId, ''); });\n return false;\n}\n\nfunction confirmPopup(message, okCallback) {\n $('#popup-buttons-confirm').click(okCallback);\n // set message\n // show popup\n}\n" }, { "answer_id": 3502417, "author": "Romas", "author_id": 365407, "author_profile": "https://Stackoverflow.com/users/365407", "pm_score": 3, "selected": false, "text": "confirmBox(text,\ncallback) callback(true) callback(false) confirmBox(\"Are you sure\", function(callback){\n if (callback) {\n // do something if user pressed yes\n } \n else {\n // do something if user pressed no\n }\n});\n" }, { "answer_id": 18316500, "author": "katesky8", "author_id": 1403723, "author_profile": "https://Stackoverflow.com/users/1403723", "pm_score": 0, "selected": false, "text": " showAlert = function (msg, header, callback) {\n var mydiv = $(\"<div id='mydiv'> </div>\");\n mydiv.alertBox({\n message: msg,\n header: header,\n callback: callback\n });\n\n },\n\n $('#show').click(function () {\n var m = $('#message').val();\n var h = $('#header').val();\n var callback = function () {\n alert(\"I can do anything here\");\n }\n showAlert(m, h, callback);\n\n });\n\n $.widget(\"MY.alertBox\", {\n options: {\n message: \"\",\n header: \"\",\n callback: ''\n },\n\n _create: function () {\n var self = this;\n self.callback = self.options.callback;\n\n self.container = $(\".alert-messagebox\");\n var header = self.container.find(\".alert-header\");\n header.html(self.options.header);\n\n var message = self.container.find(\".alert-message\");\n message.html(self.options.message);\n\n var closeButton = self.container.find(\"button.modal-close-button\");\n closeButton.click(function () {\n self.close();\n });\n\n self.show();\n },\n\n show: function () {\n var self = this;\n self.container.modal({\n maxWidth: 500\n });\n },\n\n close: function () {\n\n if (this.callback != null) {\n this.callback();\n $.modal.close();\n return;\n }\n $.modal.close();\n\n },\n\n destroy: function () {\n $.Widget.prototype.destroy.call(this);\n }\n\n });\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
358,185
<p><strong>Background:</strong><br> I have an old web CMS that stored content in XML files, one XML file per page. I am in the process of importing content from that CMS into a new one, and I know I'm going to need to massage the existing XML in order for the import process to work properly.</p> <p>Existing XML:</p> <pre><code>&lt;page&gt; &lt;audience1&gt;true&lt;/audience&gt; &lt;audience2&gt;false&lt;/audience&gt; &lt;audience3&gt;true&lt;/audience&gt; &lt;audience4&gt;false&lt;/audience&gt; &lt;audience5&gt;true&lt;/audience&gt; &lt;/page&gt; </code></pre> <p>Desired XML:</p> <pre><code>&lt;page&gt; &lt;audience1&gt;true&lt;/audience&gt; &lt;audience2&gt;false&lt;/audience&gt; &lt;audience3&gt;true&lt;/audience&gt; &lt;audience4&gt;false&lt;/audience&gt; &lt;audience5&gt;true&lt;/audience&gt; &lt;audiences&gt;1,3,5&lt;/audiences&gt; &lt;/page&gt; </code></pre> <p><strong>Question:</strong><br> The desired XML adds the node, with a comma-delimited list of the other nodes that have a "true" value. I need to achieve the desired XML for several files, so what is the best way to accomplish this? Some of my ideas:</p> <ul> <li>Use a text editor with a regex find/replace. But what expression? I wouldn't even know where to begin.</li> <li>Use a programming language like ASP.NET to parse the files and append the desired node. Again, not sure where to begin here as my .NET skills are only average.</li> </ul> <p>Suggestions?</p>
[ { "answer_id": 473778, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "customConfirm // obtain the element(we will call it targetObject) that triggered the event\n\ntargetObject = (event.target==undefined ? event.srcElement : event.target);\n\n// include a call to _doPostBack in the onclick event of OK/YES button ONLY\n\n(targetObject.href!=undefined){ eval(targetObject.href); } else{ _doPostBack(targetObject.name,''); // it is assumed that name is available\n __doPostBack" }, { "answer_id": 1137100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function BeforeDelete(controlUniqueId) {\n confirmPopup('question...?', function() { __doPostBack(controlUniqueId, ''); });\n return false;\n}\n\nfunction confirmPopup(message, okCallback) {\n $('#popup-buttons-confirm').click(okCallback);\n // set message\n // show popup\n}\n" }, { "answer_id": 3502417, "author": "Romas", "author_id": 365407, "author_profile": "https://Stackoverflow.com/users/365407", "pm_score": 3, "selected": false, "text": "confirmBox(text,\ncallback) callback(true) callback(false) confirmBox(\"Are you sure\", function(callback){\n if (callback) {\n // do something if user pressed yes\n } \n else {\n // do something if user pressed no\n }\n});\n" }, { "answer_id": 18316500, "author": "katesky8", "author_id": 1403723, "author_profile": "https://Stackoverflow.com/users/1403723", "pm_score": 0, "selected": false, "text": " showAlert = function (msg, header, callback) {\n var mydiv = $(\"<div id='mydiv'> </div>\");\n mydiv.alertBox({\n message: msg,\n header: header,\n callback: callback\n });\n\n },\n\n $('#show').click(function () {\n var m = $('#message').val();\n var h = $('#header').val();\n var callback = function () {\n alert(\"I can do anything here\");\n }\n showAlert(m, h, callback);\n\n });\n\n $.widget(\"MY.alertBox\", {\n options: {\n message: \"\",\n header: \"\",\n callback: ''\n },\n\n _create: function () {\n var self = this;\n self.callback = self.options.callback;\n\n self.container = $(\".alert-messagebox\");\n var header = self.container.find(\".alert-header\");\n header.html(self.options.header);\n\n var message = self.container.find(\".alert-message\");\n message.html(self.options.message);\n\n var closeButton = self.container.find(\"button.modal-close-button\");\n closeButton.click(function () {\n self.close();\n });\n\n self.show();\n },\n\n show: function () {\n var self = this;\n self.container.modal({\n maxWidth: 500\n });\n },\n\n close: function () {\n\n if (this.callback != null) {\n this.callback();\n $.modal.close();\n return;\n }\n $.modal.close();\n\n },\n\n destroy: function () {\n $.Widget.prototype.destroy.call(this);\n }\n\n });\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2614/" ]
358,195
<p>What's the best way to extract the key and value from a string like this:</p> <pre><code>var myString = 'A1234=B1234'; </code></pre> <p>I originally had something like this:</p> <pre><code>myString.split('='); </code></pre> <p>And that works fine, BUT an equal (=) sign could be used as a key or value within the string plus the string could have quotes, like this:</p> <pre><code>var myString = '"A123=1=2=3=4"="B1234"'; </code></pre> <p>The string could also only have one pair of quotes and spaces:</p> <pre><code>var myString = ' "A123=1=2=3=4" = B1234 '; </code></pre> <p>I'm not very good at regular expressions but I'm guessing that's the way forward?</p> <p>What I want to end up with is two variables, key and value, in the case above, the key variable would end up being <em>A123=1=2=3=4</em> and the value variable would be <em>B1234</em>.</p> <p>If there is no value present, for example if this were the original string:</p> <pre><code>var myString = 'A1234'; </code></pre> <p>Then I would want the key variable to be 'A1234' and for the value variable to be null or false - or something I can test against.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 358201, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 2, "selected": false, "text": "var inQuote = false;\nfor(i=0; i<str.length; i++) {\n if (str.charAt(i) == '\"') {\n inQuote = !inQuote;\n }\n if (!inQuote && str.charAt(i)=='=') {\n key = str.slice(0,i);\n value = str.slice(i+1);\n break;\n }\n}\n" }, { "answer_id": 358326, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 2, "selected": false, "text": "/^(\\\"[^\"]*\\\"|.*?)=(\\\"[^\"]*\\\"|.*?)$/\n" }, { "answer_id": 358597, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 2, "selected": false, "text": "/ ^ # Beginning of line\n \\s* # Any number of spaces\n ( \" ( [^\"]+) \" # A quote followed by any number of non-quotes, \n # and a closing quote\n | [^=]* # OR any number of not equals signs \n [^ =] # and at least one character that is not a equal or a space\n ) \n \\s* # any number of spaces between the key and the operator\n = # the assignment operator\n \\s* # Any number of spaces \n (.*?\\S) # Then any number of any characters, stopping at the last non-space\n \\s* # Before spaces and...\n $ # The end of line. \n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21677/" ]
358,196
<p>I'm new to unit testing and I'm trying to figure out if I should start using more of <code>internal</code> access modifier. I know that if we use <code>internal</code> and set the assembly variable <code>InternalsVisibleTo</code>, we can test functions that we don't want to declare public from the testing project. This makes me think that I should just always use <code>internal</code> because at least each project (should?) have its own testing project. Can you guys tell me why I shouldn't do this? When should I use <code>private</code>?</p>
[ { "answer_id": 358526, "author": "Brian Rasmussen", "author_id": 38206, "author_profile": "https://Stackoverflow.com/users/38206", "pm_score": 7, "selected": false, "text": "PrivateObject PrivateType Microsoft.VisualStudio.TestTools.UnitTesting" }, { "answer_id": 358572, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "internal void DoThisForTest(string name)\n{\n DoThis(name);\n}\n\nprivate void DoThis(string name)\n{\n // Real implementation\n}\n" }, { "answer_id": 1809482, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 11, "selected": true, "text": "using System.Runtime.CompilerServices;\n\n[assembly:InternalsVisibleTo(\"MyTests\")]\n Properties\\AssemblyInfo.cs" }, { "answer_id": 55882384, "author": "galdin", "author_id": 1678053, "author_profile": "https://Stackoverflow.com/users/1678053", "pm_score": 7, "selected": false, "text": "csproj <ItemGroup>\n <AssemblyAttribute Include=\"System.Runtime.CompilerServices.InternalsVisibleTo\">\n <_Parameter1>MyTests</_Parameter1>\n </AssemblyAttribute>\n</ItemGroup>\n Directory.Build.props <ItemGroup>\n <AssemblyAttribute Include=\"System.Runtime.CompilerServices.InternalsVisibleTo\">\n <_Parameter1>$(MSBuildProjectName).Test</_Parameter1>\n </AssemblyAttribute>\n</ItemGroup>\n" }, { "answer_id": 60108202, "author": "Floating Sunfish", "author_id": 7824245, "author_profile": "https://Stackoverflow.com/users/7824245", "pm_score": 4, "selected": false, "text": ".NET Core 3.1.101 .csproj <PropertyGroup>\n <!-- Explicitly generate Assembly Info -->\n <GenerateAssemblyInfo>true</GenerateAssemblyInfo>\n</PropertyGroup>\n\n<ItemGroup>\n <AssemblyAttribute Include=\"System.Runtime.CompilerServices.InternalsVisibleToAttribute\">\n <_Parameter1>MyProject.Tests</_Parameter1>\n </AssemblyAttribute>\n</ItemGroup>\n" }, { "answer_id": 64105425, "author": "balintn", "author_id": 6104083, "author_profile": "https://Stackoverflow.com/users/6104083", "pm_score": 2, "selected": false, "text": "using ...\nusing System.Runtime.CompilerServices;\n\n[assembly: InternalsVisibleTo(\"MyAssembly.Unit.Tests\")]\n\nnamespace\n{\n...\n" }, { "answer_id": 67148995, "author": "Black_Rider", "author_id": 1421328, "author_profile": "https://Stackoverflow.com/users/1421328", "pm_score": 0, "selected": false, "text": "InternalsVisibleTo.cs .csproj InternalsVisibleTo.cs using System.Runtime.CompilerServices;\n\n[assembly: InternalsVisibleTo(\"AssemblyName.WhichNeedAccess.Example.UnitTests\")]\n" }, { "answer_id": 67989544, "author": "Amit Sood", "author_id": 3520389, "author_profile": "https://Stackoverflow.com/users/3520389", "pm_score": 2, "selected": false, "text": "using System.Runtime.CompilerServices;\n[assembly: InternalsVisibleTo(\"Applications.ExampleApp.Tests\")]\nnamespace Applications.ExampleApp\n internal sealed class ASampleClass : IDisposable\n {\n private const string ApiVersionPath = @\"api/v1/\";\n ......\n ......\n ......\n }\n }\n" }, { "answer_id": 73261024, "author": "ihebiheb", "author_id": 1546137, "author_profile": "https://Stackoverflow.com/users/1546137", "pm_score": 4, "selected": false, "text": "csproj <ItemGroup>\n <InternalsVisibleTo Include=\"MyProject.Tests\" />\n </ItemGroup>\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381/" ]
358,207
<p>What is the best way to get the current system time milliseconds?</p>
[ { "answer_id": 358219, "author": "codelogic", "author_id": 43427, "author_profile": "https://Stackoverflow.com/users/43427", "pm_score": 9, "selected": true, "text": "[[NSDate date] timeIntervalSince1970];\n" }, { "answer_id": 2742378, "author": "Allan Simonsen", "author_id": 246981, "author_profile": "https://Stackoverflow.com/users/246981", "pm_score": 8, "selected": false, "text": "double CurrentTime = CACurrentMediaTime();\n NSDate let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)\n" }, { "answer_id": 5546211, "author": "Chris", "author_id": 59198, "author_profile": "https://Stackoverflow.com/users/59198", "pm_score": 0, "selected": false, "text": "[NSDate timeIntervalSinceReferenceDate]" }, { "answer_id": 7885923, "author": "Tristan Lorach", "author_id": 1005892, "author_profile": "https://Stackoverflow.com/users/1005892", "pm_score": 5, "selected": false, "text": "gettimeofday #include <sys/time.h>\nstruct timeval time;\ngettimeofday(&time, NULL);\nlong millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);\n" }, { "answer_id": 12020300, "author": "darrinm", "author_id": 707320, "author_profile": "https://Stackoverflow.com/users/707320", "pm_score": 7, "selected": false, "text": "CACurrentMediaTime timeIntervalSince1970 NSDate CACurrentMediaTime gettimeofday CACurrentMediaTime: 1.33 µs/call\ngettimeofday: 1.38 µs/call\n[NSDate timeIntervalSinceReferenceDate]: 1.45 µs/call\nCFAbsoluteTimeGetCurrent: 1.48 µs/call\n[[NSDate date] timeIntervalSince1970]: 4.93 µs/call\n CACurrentMediaTime: 1.25 µs/call\ngettimeofday: 1.33 µs/call\nCFAbsoluteTimeGetCurrent: 1.34 µs/call\n[NSDate timeIntervalSinceReferenceDate]: 1.37 µs/call\n[[NSDate date] timeIntervalSince1970]: 3.47 µs/call\n" }, { "answer_id": 16495741, "author": "mmackh", "author_id": 1091044, "author_profile": "https://Stackoverflow.com/users/1091044", "pm_score": 3, "selected": false, "text": "NSNumber [[NSDate date] timeIntervalSince1970] NSDate #include <sys/time.h>\nstruct timeval tv;\ngettimeofday(&tv,NULL);\ndouble perciseTimeStamp = tv.tv_sec + tv.tv_usec * 0.000001;\n [[NSDate date] timeIntervalSince1970]" }, { "answer_id": 26016939, "author": "Fatima Arshad", "author_id": 4050160, "author_profile": "https://Stackoverflow.com/users/4050160", "pm_score": 3, "selected": false, "text": "// Timestamp after converting to milliseconds.\n\nNSString * timeInMS = [NSString stringWithFormat:@\"%lld\", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];\n" }, { "answer_id": 32914388, "author": "Rajan Maheshwari", "author_id": 2545465, "author_profile": "https://Stackoverflow.com/users/2545465", "pm_score": 6, "selected": false, "text": "func getCurrentMillis()->Int64{\n return Int64(NSDate().timeIntervalSince1970 * 1000)\n}\n\nvar currentTime = getCurrentMillis()\n Date NSDate func getCurrentMillis()->Int64 {\n return Int64(Date().timeIntervalSince1970 * 1000)\n}\n\nvar currentTime = getCurrentMillis()\n" }, { "answer_id": 34044977, "author": "ΩlostA", "author_id": 3581620, "author_profile": "https://Stackoverflow.com/users/3581620", "pm_score": 2, "selected": false, "text": "NSDate * timestamp = [NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970]];\n\nNSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];\n[dateFormatter setDateFormat:@\"YYYY-MM-dd HH:mm:ss.SSS\"];\n\nNSString *newDateString = [dateFormatter stringFromDate:timestamp];\ntimestamp = (NSDate*)newDateString;\n" }, { "answer_id": 34775705, "author": "DG7", "author_id": 5582574, "author_profile": "https://Stackoverflow.com/users/5582574", "pm_score": 1, "selected": false, "text": "var date = NSDate()\nlet currentTime = Int64(date.timeIntervalSince1970 * 1000)\n\nprint(\"Time in milliseconds is \\(currentTime)\")\n" }, { "answer_id": 34857325, "author": "quemeful", "author_id": 3933502, "author_profile": "https://Stackoverflow.com/users/3933502", "pm_score": 4, "selected": false, "text": "let seconds = NSDate().timeIntervalSince1970\nlet milliseconds = seconds * 1000.0\n let currentTimeInMiliseconds = Date().timeIntervalSince1970.milliseconds\n" }, { "answer_id": 41355514, "author": "RenniePet", "author_id": 253938, "author_profile": "https://Stackoverflow.com/users/253938", "pm_score": 3, "selected": false, "text": " /// Method to get Unix-style time (Java variant), i.e., time since 1970 in milliseconds. This \n /// copied from here: http://stackoverflow.com/a/24655601/253938 and here:\n /// http://stackoverflow.com/a/7885923/253938\n /// (This should give good performance according to this: \n /// http://stackoverflow.com/a/12020300/253938 )\n ///\n /// Note that it is possible that multiple calls to this method and computing the difference may \n /// occasionally give problematic results, like an apparently negative interval or a major jump \n /// forward in time. This is because system time occasionally gets updated due to synchronization \n /// with a time source on the network (maybe \"leap second\"), or user setting the clock.\n public static func currentTimeMillis() -> Int64 {\n var darwinTime : timeval = timeval(tv_sec: 0, tv_usec: 0)\n gettimeofday(&darwinTime, nil)\n return (Int64(darwinTime.tv_sec) * 1000) + Int64(darwinTime.tv_usec / 1000)\n }\n" }, { "answer_id": 48206046, "author": "PANKAJ VERMA", "author_id": 4132714, "author_profile": "https://Stackoverflow.com/users/4132714", "pm_score": 1, "selected": false, "text": "NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); //double\nlong digits = (long)time; //first 10 digits \nint decimalDigits = (int)(fmod(time, 1) * 1000); //3 missing digits\n/*** long ***/\nlong timestamp = (digits * 1000) + decimalDigits;\n/*** string ***/\nNSString *timestampString = [NSString stringWithFormat:@\"%ld%03d\",digits ,decimalDigits];\n" }, { "answer_id": 49703452, "author": "Softlabsindia", "author_id": 3343083, "author_profile": "https://Stackoverflow.com/users/3343083", "pm_score": 2, "selected": false, "text": " func currentmicrotimeTimeMillis() -> Int64{\nlet nowDoublevaluseis = NSDate().timeIntervalSince1970\nreturn Int64(nowDoublevaluseis*1000)\n" }, { "answer_id": 51259183, "author": "Rajesh Loganathan", "author_id": 2611413, "author_profile": "https://Stackoverflow.com/users/2611413", "pm_score": 5, "selected": false, "text": "func currentTimeInMilliSeconds()-> Int\n {\n let currentDate = Date()\n let since1970 = currentDate.timeIntervalSince1970\n return Int(since1970 * 1000)\n }\n" }, { "answer_id": 55843732, "author": "lazyTank", "author_id": 8717854, "author_profile": "https://Stackoverflow.com/users/8717854", "pm_score": 2, "selected": false, "text": "let timeInMiliSecDate = Date()\nlet timeInMiliSec = Int (timeInMiliSecDate.timeIntervalSince1970 * 1000)\nprint(timeInMiliSec)\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
358,209
<p>Greetings!</p> <p>I have a DropDownList within a FormView which are bound to XmlDataSources:</p> <pre><code>&lt;asp:FormView ID="MyFormView" runat="server" DataSourceID="MyXmlDataSource"&gt; &lt;ItemTemplate&gt; &lt;h1&gt;&lt;%# XPath("SomeNode")%&gt;&lt;/h1&gt; &lt;asp:Label ID="MyLabel" runat="server" AssociatedControlID="MyDdl" Text='&lt;%# XPath("SomeOtherNode")%&gt;' /&gt; &lt;asp:DropDownList ID="MyDdl" runat="server" DataSourceID="MyDdlDataSource" DataTextField="name" DataValueField="value" AutoPostBack="true" OnSelectedIndexChanged="MyDdl_SelectedIndexChanged"&gt; &lt;/asp:DropDownList&gt; &lt;/ItemTemplate&gt; &lt;/asp:FormView&gt; &lt;asp:XmlDataSource ID="MyXmlDataSource" runat="server" XPath="Root/MainSection" /&gt; &lt;asp:XmlDataSource ID="MyDdlDataSource" runat="server" XPath="Root/MainSection/Areas/*" /&gt; </code></pre> <p>In the page's codebehind, I have the following OnLoad() method as well as the method for getting the selected value dropdownlist during postback:</p> <pre><code>private m_key; protected override void OnLoad(EventArgs e) { base.OnLoad(e); string xml_data; if (!IsPostBack) { xml_data = GetMyXml(0); // default value MyXmlDataSource.Data = xml_data; MyDdlDataSource.Data = xml_data; } else { GetSelections(); xml_data = GetMyXml(m_key); MyXmlDataSource.Data = xml_data; MyXmlDataSource.DataBind(); } } private void GetSelections() { DropDownList l_MyDdl = FindMyControl&lt;DropDownList&gt;("MyDdl"); if (l_MyDdl != null) if (!Int32.TryParse(l_MyDdl.SelectedItem.Value, out m_key)) m_key = 0; } </code></pre> <p>Everything works great, up until a postback as a result of the dropdown list changing occurs. When this happens, I get the value of the selected item in the dropdown list, pass it to my GetMyXml() method with the value from the dropdown list as a parameter and then set the FormView's datasource to the newly returned XML data from GetMyXml(). I've looked at the value of "xml_data" during postback and it's definitely correct. However, the values displayed on the page the FormView (like XPath("SomeNode")) are the values from before the postback happened and not the ones returned in xml_data. Why would this happen and how would I go about resolving it? Thanks in advance.</p>
[ { "answer_id": 358588, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 0, "selected": false, "text": "MyFormView.DataBind() MyXmlDataSource.DataBind();" }, { "answer_id": 408729, "author": "Kishh", "author_id": 51109, "author_profile": "https://Stackoverflow.com/users/51109", "pm_score": 0, "selected": false, "text": "formView.Databind();\nthis.page.databind();\n" }, { "answer_id": 1849649, "author": "Jan Aagaard", "author_id": 37147, "author_profile": "https://Stackoverflow.com/users/37147", "pm_score": 0, "selected": false, "text": "GetSelections EventArg" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
358,213
<p>How can I mock the database calls to make my application logic been tested without database?</p>
[ { "answer_id": 358235, "author": "thursdaysgeek", "author_id": 22523, "author_profile": "https://Stackoverflow.com/users/22523", "pm_score": 0, "selected": false, "text": "procedure GetData (output arrayOfData)\n arrayOfData.record1.field1 = \"dataA\"\n arrayOfData.record1.field2 = \"dataAB\"\n arrayOfData.record2.field1 = \"dataB\"\n arrayOfData.record2.field2 = \"dataBB\"\n return arrayOfData)\nend procedure\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43049/" ]
358,220
<p>Just flicking through one of my favourite books (Ellen Ullman's The Bug) and there is a small bit where one programmer confronts another over three levels of indirection:</p> <pre><code>***object_array = ***winarray; </code></pre> <p>I get the idea of double indirection - a way of passing a pointer into a function, and allowing it to point to an object created within the function.</p> <p>But have you come across any reason to use three (or more) levels of indirection?</p>
[ { "answer_id": 358267, "author": "mcherm", "author_id": 14570, "author_profile": "https://Stackoverflow.com/users/14570", "pm_score": 2, "selected": false, "text": "int x = 3;\n" }, { "answer_id": 359514, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 2, "selected": false, "text": "struct Foo{\n struct greater{\n bool operator()(Foo const *a, Foo const *b) const{\n return a->place > b->place ||\n a->place == b->place && a->holder > b->holder;\n }\n };\n\n int place;\n int holder;\n};\n\ntemplate<typename T, typename Comparer>\nvoid Sort(T const *unorderedList, int count, T const ***orderedList, Comparer &cmp);\n\nvoid UseOrderedList(Foo const **orderedList, int count);\n\nint main(){\n Foo list[] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};\n Foo const **orderedList;\n\n Sort(list, sizeof list / sizeof *list, &orderedList, Foo::greater());\n UseOrderedList(orderedList, sizeof list / sizeof *list);\n delete[] orderedList;\n return 0;\n}\n\nvoid UseOrderedList(Foo const **orderedList, int count){/*...*/}\n\ntemplate<typename T, typename Comparer>\nvoid Sort(T const *unorderedList, int count, T const ***orderedList, Comparer &cmp){\n /*\n * The result array stores pointers to the items in the original array.\n * This way, the original array is unmodified, and the result array\n * doesn't create duplicate items. This makes sense if the objects\n * are large and copying them would be slow (another argument against\n * in-place sorting), or if duplicating them violates some design\n * principle.\n */\n *orderedList = new const T*[count];\n\n for(int i = 0; i < count; i++)\n (*orderedList)[i] = unorderedList + i;\n\n std::sort(*orderedList, &(*orderedList)[count], cmp);\n}\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41116/" ]
358,225
<p>this is my log output</p> <pre><code>INFO main digestemails - process inbox INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source INFO main digestemails - digesting 003d01c95a7b_3446880_0202fea9@xxxx.com.eml INFO main digestemails - extracting attachments INFO main digestemails - no attachments or no attachments supported INFO main digestemails - updating database INFO main digestemails - email -&gt; COMPLETED folder INFO main digestemails - </code></pre> <p>I would like a time stamp per log message ie</p> <pre><code>INFO 2008-12-25 13:14:00 digestemails - email -&gt; COMPLETED folder </code></pre> <p>here is my log4j config file</p> <pre><code>log4j.rootLogger=debug, stdout, R log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=c:\\development\\DCMail\\logs\\digestlogfolder\\digest-logfile.log log4j.appender.R.MaxFileSize=100KB # Keep one backup file log4j.appender.R.MaxBackupIndex=1 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n </code></pre> <p>How do I do it?</p>
[ { "answer_id": 358247, "author": "joshperry", "author_id": 30587, "author_profile": "https://Stackoverflow.com/users/30587", "pm_score": 8, "selected": true, "text": "%d %d %d{dd MMM yyyy HH:mm:ss,SSS}" }, { "answer_id": 358641, "author": "Markus Lausberg", "author_id": 39062, "author_profile": "https://Stackoverflow.com/users/39062", "pm_score": 4, "selected": false, "text": "log4j.rootLogger=INFO, stdout, logfile\n\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\nlog4j.appender.stdout.layout=org.apache.log4j.PatternLayout\nlog4j.appender.stdout.layout.ConversionPattern=%d %p (%t) [%c] - %m%n\n\nlog4j.appender.logfile=org.apache.log4j.RollingFileAppender\nlog4j.appender.logfile.File=C:/log/client.log\nlog4j.appender.logfile.MaxFileSize=5MB\nlog4j.appender.logfile.MaxBackupIndex=0\nlog4j.appender.logfile.layout=org.apache.log4j.PatternLayout\nlog4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21537/" ]
358,230
<p>Can jQuery be extended so that I can use the above syntax?</p> <p>I can't figure out how to prototype whatever it is $() returns, so that I can call $().$()</p> <p>Thanks.</p>
[ { "answer_id": 358234, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "find() $('.superset').find('.within'); $('.superset .within');" }, { "answer_id": 25343642, "author": "1j01", "author_id": 2624876, "author_profile": "https://Stackoverflow.com/users/2624876", "pm_score": 0, "selected": false, "text": "$.fn.$ = $.fn.find;\n .$()" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43005/" ]
358,240
<p>Is there anything better than a <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow noreferrer">Trie</a> for this situation?</p> <ul> <li>Storing a list of ~100k English words</li> <li>Needs to use minimal memory</li> <li>Lookups need to be reasonable, but don't have to be lightning fast</li> </ul> <p>I'm working with Java, so my first attempt was to just use a Set&lt;String&gt;. However, I'm targeting a mobile device and already running low on memory. Since many English words share common prefixes, a trie seems like a decent bet to save some memory -- anyone know some other good options?</p> <p>EDIT - More info - The data structure will be used for two operations</p> <ul> <li>Answering: Is some word XYZ in the list?</li> <li>Generating the neighborhood of words around XYZ with one letter different</li> </ul> <p>Thanks for the good suggestions</p>
[ { "answer_id": 358281, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "HERE would encode as THIS\nsanctimonious 0,sanctimonious\nsanction 6,on\nsanguine 3,guine\ntrivial 0,trivial\n zwiebacks -> zygote common= old=1044662 new=469762 55.0%\nzygote -> zygotes common=zygote old=1044670 new=469765 55.0%\nzygotes -> zygotic common=zygot old=1044678 new=469769 55.0%\nzygotic -> zymase common=zy old=1044685 new=469775 55.0%\nzymase -> zymogenic common=zym old=1044695 new=469783 55.0%\nzymogenic -> zymology common=zymo old=1044704 new=469789 55.0%\nzymology -> zymolysis common=zymol old=1044714 new=469795 55.0%\nzymolysis -> zymoplastic common=zymo old=1044726 new=469804 55.0%\nzymoplastic -> zymoscope common=zymo old=1044736 new=469811 55.0%\nzymoscope -> zymurgy common=zym old=1044744 new=469817 55.0%\nzymurgy -> zyzzyva common=zy old=1044752 new=469824 55.0%\nzyzzyva -> zyzzyvas common=zyzzyva old=1044761 new=469827 55.0%\n" }, { "answer_id": 358435, "author": "Chris Nava", "author_id": 45163, "author_profile": "https://Stackoverflow.com/users/45163", "pm_score": 1, "selected": false, "text": " . .\n / /\n r-p-s-.\n /\\\\\n a \\s-.\n / t-.\nc \\\n s-.\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23977/" ]
358,251
<p>I have made a C# application and I am trying to figure out if I can tap into build events of cctray (cruise control tray)? I don't want to re-invent the wheel, I just want to know when my builds fail or succeed (on a client machine) so than my custom C# application may execute a specific set of routines.</p>
[ { "answer_id": 359967, "author": "Alex", "author_id": 26564, "author_profile": "https://Stackoverflow.com/users/26564", "pm_score": 1, "selected": true, "text": "ProjectStatus[] currentStatuses = managerFactory.GetCruiseManager(ServerUri).GetProjectStatus();\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ]
358,263
<p>I have a website where all requests are redirected silently (via <code>.htaccess</code>) to <code>index.php</code> and then PHP is used to show the correct page (by parsing the <code>REQUEST_URI</code>).</p> <p>I was wondering if it's possible to submit POST data to a fake address too?</p> <p>I've currently got my form like so...</p> <pre><code>&lt;form action="/send-mail" method="post"&gt; </code></pre> <p>And my <code>.htaccess</code> rule is...</p> <pre><code># redirect mail posting to index RewriteRule send-mail index.php?send-mail [NC,L] </code></pre> <p>My <code>index.php</code> checks <code>isset($_GET['send-mail'])</code> which works fine.</p> <p>This however seems to drop off all the POST data that should be sent to it.</p> <p>Is there a way to keep the post data? I don't want to use GET because it can't send as much information, though it might not be an issue with a simple inquiry form.</p> <p>Here is my <code>.htaccess</code> for redirecting to <code>index.php</code></p> <pre><code># serve files and dirs if they exist please, otherwise send to index RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . index.php </code></pre>
[ { "answer_id": 358334, "author": "Tautologistics", "author_id": 44481, "author_profile": "https://Stackoverflow.com/users/44481", "pm_score": 7, "selected": true, "text": "# redirect mail posting to index\nRewriteRule send-mail index.php?send-mail [NC,P]\n" }, { "answer_id": 358335, "author": "mcrumley", "author_id": 17287, "author_profile": "https://Stackoverflow.com/users/17287", "pm_score": 0, "selected": false, "text": "RewriteRule ^(.*)$ index.php/$1 [L]\n" }, { "answer_id": 358339, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "index.php $_SERVER['REQUEST_URI'] /delete_user?id=1234" }, { "answer_id": 28765894, "author": "Kamal Kumar", "author_id": 3060099, "author_profile": "https://Stackoverflow.com/users/3060099", "pm_score": 1, "selected": false, "text": "RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\\s/user_login\\.php [NC]\nRewriteRule ^ user-login [QSA,R=301]\nRewriteRule ^user-login$ user_login.php [QSA,L]\n <form action=\"<?php $siteurl;?>/user-login\" method=\"post\" id=\"user_login\">\n" }, { "answer_id": 40965082, "author": "Alex Pop", "author_id": 6162727, "author_profile": "https://Stackoverflow.com/users/6162727", "pm_score": 1, "selected": false, "text": "POST Content-Length: 0 GET POST curl -X POST https://example.com/api/user/123456789\n Content-Length curl -X POST https://example.com/api/user/123456789 -H 'Content-Length: 0'\n curl -X POST https://example.com/api/user/123456789 -d ''\n" }, { "answer_id": 68547792, "author": "Mat Lipe", "author_id": 3944788, "author_profile": "https://Stackoverflow.com/users/3944788", "pm_score": 3, "selected": false, "text": "307 RewriteRule send-mail index.php?send-mail [R=307,L]\n POST POST 301 POST # POST requests.\nRewriteCond %{REQUEST_METHOD} POST\nRewriteRule send-mail index.php?send-mail [R=307,L]\n\n# Standard GET requests.\nRewriteRule send-mail index.php?send-mail [R=301,L]\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
358,278
<p>I have a bunch of tables in a sql server database (all with a certain prefix, e.g. ABC_table1), and I want to move ALL tables with this prefix to another database.</p> <p>Is there a way in which this can be done?</p> <p>I am using SQL Server 2k5.</p> <p>Thanks</p>
[ { "answer_id": 358330, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 1, "selected": false, "text": "SELECT * from sys.schemas\n SELECT \n 'SELECT * INTO OtherDB.ABC.' + name +\n ' FROM ABC.' + name\nFROM \n sysobjects \nWHERE \n xtype = 'U' \n AND uid = 5\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32484/" ]
358,297
<p>I have the following HTML</p> <pre><code>&lt;div&gt; &lt;img id="image1" src="http://valleywag.com/assets/resources/2008/03/BlackGoogleLogo.jpg" alt="Why doesn't this float correcly?" style="border-width: 0px; float: left;" /&gt; &lt;div id="divText" style="font-family: Arial, Helvetica, sans-serif; font-size: 11px;" class="txt-Normal"&gt; &lt;div style="background-color: Green; color: White;"&gt; &lt;p&gt; &lt;strong&gt;&lt;span style="font-size: xx-large;"&gt;This is going to be big title&lt;/span&gt;&lt;/strong&gt; &lt;/p&gt; &lt;ul&gt; &lt;li&gt; &lt;span style="font-size: small;"&gt;Foo&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span style="font-size: small;"&gt;Bar&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span style="font-size: small;"&gt;FooBar&lt;/span&gt; &lt;/li&gt; &lt;li&gt; &lt;span style="font-size: small;"&gt;BarFoo&lt;/span&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The text does not float around the image. It does not matter whether the browser IE or Firefox.</p> <p>How can I fix this to float around the image?</p>
[ { "answer_id": 358316, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 0, "selected": false, "text": "<ul style=\"margin-left: 291px;\">" }, { "answer_id": 358343, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 3, "selected": true, "text": "<div id=\"divText\" style=\"font-family: Arial, Helvetica, sans-serif; font-size: 11px; float:left;\" class=\"txt-Normal\">\n" }, { "answer_id": 358349, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "margin-right list-style-position: inside" }, { "answer_id": 358400, "author": "John T", "author_id": 36457, "author_profile": "https://Stackoverflow.com/users/36457", "pm_score": 1, "selected": false, "text": "<ul> style=\"margin-top: 70px\"\n <p> * {\nborder: 1px solid black;\n}\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ]
358,307
<p>I am wondering if there is a "best" way to shuffle a list of elements that contains duplicates such that the case where array[i] == array[i+1] is avoided as much as possible.</p> <p>I am working on a weighted advertising display (I can adjust the number of displays per rotation for any given advertiser) and would like to avoid the same advertister appearing twice in a row.</p>
[ { "answer_id": 358346, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 1, "selected": true, "text": "var advertisers = getAdvertisers();\nvar returnList = new List();\nint totalWeight = sumOfAllAdvertisersWeight();\nwhile (totalWeight > 0)\n{\n for (int i=0; i<advertisers.Count; i++)\n {\n if (advertisers[i].Weight > 0)\n {\n returnList.add(advertisers[i]);\n advertisers[i].Weight--;\n totalWeight--;\n }\n }\n}\nreturn returnList;\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
358,318
<p>I want to access Microsoft SQL Server Compact Edition databases from Java. How can I do that? I searched for JDBC driver for SQLCE, but I didn't find any.</p>
[ { "answer_id": 378636, "author": "Mark Jaeger", "author_id": 335648, "author_profile": "https://Stackoverflow.com/users/335648", "pm_score": 1, "selected": false, "text": "Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\"); \nConnection con = DriverManager.getConnection(\"jdbc:odbc:<yourODBC_DSN>\"); \n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11238/" ]
358,344
<p>I was reading the great article about binding and unbinding events (because I am a js beginner using jQuery) on <a href="http://www.learningjquery.com/2008/05/working-with-events-part-2" rel="nofollow noreferrer">Karl Swedberg's blog</a>, and I became totally puzzled at this part of the code (simplified for brevity):</p> <pre><code> function addItemUnbind() { $Add a button but it won't have it's event added; addItemUnbind(); }); </code></pre> <p>Why is it that by putting the same function within itself it doesn't keep executing into an infinite loop? However, it is used to re-bind the event to the element...!?</p>
[ { "answer_id": 358359, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 3, "selected": false, "text": "function addItemUnbind() {\n $('#list6 li.special button')\n .unbind('click')\n .bind('click', function() {\n var $newLi = $('<li class=\"special\">special and new <button>I am new</button></li>');\n $(this).parent().after($newLi);\n addItemUnbind();\n });\n}\n" }, { "answer_id": 358363, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 3, "selected": true, "text": ".bind('click', function() {\n var $newLi = $('<li class=\"special\">special and new <button>I am new</button></li>');\n $(this).parent().after($newLi);\n addItemUnbind();\n }\n" }, { "answer_id": 358375, "author": "Moss Collum", "author_id": 13210, "author_profile": "https://Stackoverflow.com/users/13210", "pm_score": 0, "selected": false, "text": "function addItemUnbind() {\n bind('click', function() {\n addItemUnbind();\n });\n}\n function bind(eventName, eventHandler) {\n eventHandler();\n}\n function bind(eventName, eventHandler) {\n this.events[eventName] = eventHandler; // save the event handler to call when an event happens\n}\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43465/" ]
358,345
<p>I'm having an issue with the following code:</p> <pre><code> private void DataPortal_Fetch(TaskCriteria criteria) { using (var ctx = ContextManager&lt;Gimli.Data.GimliDataContext&gt; .GetManager(Database.ApplicationConnection, false)) { this.RaiseListChangedEvents = false; this.IsReadOnly = false; IQueryable&lt;Data.Task&gt; query = ctx.DataContext.Tasks; if (criteria.ReadyForPricing) { query = query.Where(row =&gt; row.IsPriced != true); query = query.Where(row =&gt; row.Status == (int)TaskStatus.Closed); query = query.Where(row =&gt; row.InvoiceId == Guid.Empty); } if (criteria.ReadyForInvoicing) { query = query.Where(row =&gt; row.IsPriced == true); query = query.Where(row =&gt; row.Status == (int)TaskStatus.Closed); query = query.Where(row =&gt; row.InvoiceId == Guid.Empty); } var data = query.Select(row =&gt; TaskInfo.FetchTaskInfo(row)); this.AddRange(data); this.IsReadOnly = true; this.RaiseListChangedEvents = true; } } </code></pre> <p>My web application, when it calls this method, always hangs if I don't comment out the following line:</p> <pre><code>query = query.Where(row =&gt; row.InvoiceId == Guid.Empty) </code></pre> <p>Any idea why this would be happening?</p>
[ { "answer_id": 358351, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 0, "selected": false, "text": "query.Where(row => object.Equals(row.InvoiceId, Guid.Empty))\n" }, { "answer_id": 358371, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 0, "selected": false, "text": "from t in Tasks\nwhere t.IsPriced == false\n&& t.IsNotInvoiceable == false\n&& t.Status == 5\n&& t.InvoiceId == Guid.Empty\nselect t\n if (criteria.ProjectId != Guid.Empty)\n query = query.Where(row => row.ProjectId == criteria.ProjectId);\n" }, { "answer_id": 358380, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 3, "selected": true, "text": "query = query.Where(row => row.InvoiceId == new Guid(\"00000000-0000-0000-0000-000000000000\"));\n" }, { "answer_id": 358496, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "Guid empty = Guid.Empty;\nquery = query.Where(row => row.InvoiceId == empty);\n Guid ctx.Log = Console.Out;\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
358,347
<p>I'm writing some Java code that uses a FileReader to load data from a few input files. I'm using TDD pretty heavily, and I'd like to add some tests that ensure that I'm cleaning up properly by calling close() on the reader when I'm done with it. Unfortunately, I can't come up with a good way to test for this. Anyone have any insights?</p> <p>Edited to add: I know I can test explicitly for the close call using mock objects, but I'd like to avoid it if possible, partly because I find they lead to somewhat brittler code, and partly because I'm curious whether it's possible to write code that can recognize the effects of not closing a file.)</p>
[ { "answer_id": 358390, "author": "Chris B.", "author_id": 45176, "author_profile": "https://Stackoverflow.com/users/45176", "pm_score": 2, "selected": false, "text": "FileReader fr = new FileReader(\"somefile\");\n// ... file reader activity\nfr.close();\n\n// After closing the reader, the ready() method should cause an IOException:\nboolean isOpen = true;\ntry {\n isOpen = fr.ready();\n} catch (IOException e) {\n isOpen = false;\n}\nassertFalse(\"FileReader is still open\", isOpen);\n" } ]
2008/12/11
[ "https://Stackoverflow.com/questions/358347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13210/" ]