qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
341,900 | <p>I'm matching ASP.Net generated elements by ID name, but I have some elements which may render as text boxes or labels depending on the page context. I need to figure out whether the match is to a textbox or label in order to know whether to get the contents by val() or by html().</p>
<pre><code>$("[id$=" + endOfIdToMatch + "]").each(function () {
//determine whether $(this) is a textbox or label
//do stuff
});
</code></pre>
<p>I found a solution that doesn't work, it just returns "undefined":</p>
<pre><code>$("[id$=" + endOfIdToMatch + "]").each(function () {
alert($(this).tagName);
});
</code></pre>
<p>What am I missing?</p>
| [
{
"answer_id": 341919,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 3,
"selected": false,
"text": "$(\"[id$=\" + endOfIdToMatch + \"]\").each(function () {\n alert($(this).attr(tagName));\n});\n"
},
{
"answer_id": 341922,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 8,
"selected": true,
"text": "$(\"[id$=\" + endOfIdToMatch + \"]\").each(function () {\n alert(this.tagName);\n});\n"
},
{
"answer_id": 1142846,
"author": "Christian Davén",
"author_id": 12534,
"author_profile": "https://Stackoverflow.com/users/12534",
"pm_score": 5,
"selected": false,
"text": "var elements = $(\"[id$=\" + endOfIdToMatch + \"]\");\nvar vals = elements.is(\"input\").val();\nvar htmls = elements.is(\"label\").html();\nvar contents = vals.concat(htmls);\n"
},
{
"answer_id": 2292066,
"author": "Jelgab",
"author_id": 127638,
"author_profile": "https://Stackoverflow.com/users/127638",
"pm_score": 5,
"selected": false,
"text": "if ($(this).is('input:checkbox'))\n"
},
{
"answer_id": 5820316,
"author": "Said",
"author_id": 729532,
"author_profile": "https://Stackoverflow.com/users/729532",
"pm_score": 1,
"selected": false,
"text": "function tgetelementType( elmentid )\n{\n\n var TypeName = $('#' + elmentid).get(0).tagName;\n var TypeName2 = $('#' + elmentid).get(0).type;\n\n\n if($('#' + elmentid).get(0).tagName== \"INPUT\")\n {\n return $('#' + elmentid).get(0).type.toUpperCase()\n }\n else \n {\n return $('#' + elmentid).get(0).tagName.toUpperCase() ; \n }\n}\n"
},
{
"answer_id": 6559745,
"author": "reco",
"author_id": 272127,
"author_profile": "https://Stackoverflow.com/users/272127",
"pm_score": 2,
"selected": false,
"text": "var el = $('body');\n\nif (el.prop('tagName') === 'BODY') {\n console.log('found body')\n}\n"
},
{
"answer_id": 6848755,
"author": "ProtectedVoid",
"author_id": 865914,
"author_profile": "https://Stackoverflow.com/users/865914",
"pm_score": 1,
"selected": false,
"text": "$(\"[id$=\" + endOfIdToMatch + \"]\").each(function(){\n var $this=jQuery(this),ri='';\n switch (this.tagName.toLowerCase()){\n case 'label':\n ri=$this.html();\n break;\n case 'input':\n if($this.attr('type')==='text'){ri=$this.val();}\n break;\n default:\n break;\n }\n return ri;\n})\n $(\"[id$=\" + endOfIdToMatch + \"]\")\n .find(\"input:text\")\n .each(function(){\n /* do something with all input:text elements */\n })\n .end()\n .find(\"label\")\n .each(function(){\n /* do something with label elements */\n })\n .end()\n each()"
},
{
"answer_id": 9405375,
"author": "jevon",
"author_id": 39531,
"author_profile": "https://Stackoverflow.com/users/39531",
"pm_score": 0,
"selected": false,
"text": "$(\"input#\" + id).each(function() { alert(this + \" is an input\"); });\n$(\"label#\" + id).each(function() { alert(this + \" is a label\"); });\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14894/"
] |
341,911 | <p>I'm trying to run the Camel Example "camel-example-spring-jms" (also at <a href="http://activemq.apache.org/camel/tutorial-jmsremoting.html" rel="nofollow noreferrer">http://activemq.apache.org/camel/tutorial-jmsremoting.html</a>).
However, when I try to start Camel using "org.apache.camel.spring.Main" class, I get the error saying</p>
<p><strong>"Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [<a href="http://activemq.apache.org/schema/core]" rel="nofollow noreferrer">http://activemq.apache.org/schema/core]</a>"</strong></p>
<p>[Note: I'm able to run the example just fine when I use Maven command "mvn exec:java -PCamelServer" ]</p>
<p>Can someone please help me understand what might be causing this. A potential resolution hint will not hurt either :)</p>
<p>++++++ Error Stack +++++</p>
<pre><code>Dec 4, 2008 12:45:01 PM org.apache.camel.util.MainSupport doStart
INFO: Apache Camel 1.5.0 starting
Dec 4, 2008 12:45:01 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1ac3c08: display name [org.springframework.context.support.ClassPathXmlApplicationContext@1ac3c08]; startup date [Thu Dec 04 12:45:01 EST 2008]; root of context hierarchy
Dec 4, 2008 12:45:01 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server-aop.xml]
Dec 4, 2008 12:45:02 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server.xml]
Dec 4, 2008 12:45:03 PM org.apache.camel.util.MainSupport run
SEVERE: Failed: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [camel-server.xml]
Offending resource: file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server-aop.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://activemq.apache.org/schema/core]
Offending resource: file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server.xml]
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [camel-server.xml]
Offending resource: file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server-aop.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://activemq.apache.org/schema/core]
Offending resource: file [C:\dev\camel-example-spring-jms\bin\META-INF\spring\camel-server.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:201)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:147)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:132)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:113)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:80)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:423)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:353)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at org.apache.camel.spring.Main.createDefaultApplicationContext(Main.java:189)
at org.apache.camel.spring.Main.doStart(Main.java:152)
at org.apache.camel.impl.ServiceSupport.start(ServiceSupport.java:47)
at org.apache.camel.util.MainSupport.run(MainSupport.java:121)
at org.apache.camel.util.MainSupport.run(MainSupport.java:310)
at org.apache.camel.spring.Main.main(Main.java:72)
</code></pre>
<p>++++++</p>
| [
{
"answer_id": 343237,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 2,
"selected": true,
"text": "mvn eclipse:eclipse\n mvn idea:idea\n mvn dependency:tree\n"
},
{
"answer_id": 404084,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate NamespaceHandler for namespace [http://activemq.apache.org/camel/schema/spring]\n"
},
{
"answer_id": 773488,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<dependency>\n <groupId>org.apache.camel</groupId>\n <artifactId>camel-core</artifactId>\n <version>1.6.0</version>\n <scope>compile</scope>\n</dependency>\n\n<dependency>\n <groupId>org.apache.camel</groupId>\n <artifactId>camel-jms</artifactId>\n <version>1.6.0</version>\n <scope>runtime</scope>\n</dependency>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/325613/"
] |
341,933 | <p>If I am inserting elements into a wrap panel and there is still space in the panel before it overflows on the next line, can I specifically make it wrap over so that the subsequent elements are on the next line?</p>
<p>I am looking for something like this:</p>
<pre><code><WrapPanel>
<Element/>
<Element/>
<NewLine???/>
<Element/>
<Element/>
<Element/>
</WrapPanel>
</code></pre>
| [
{
"answer_id": 341994,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 6,
"selected": true,
"text": "<WrapPanel>\n <TextBlock>1</TextBlock>\n <TextBlock>2</TextBlock>\n <TextBlock>3</TextBlock>\n <TextBlock>4</TextBlock>\n\n <TextBlock Width=\"10000\" Height=\"0\" />\n\n <TextBlock>5</TextBlock>\n <TextBlock>6</TextBlock>\n</WrapPanel>\n <StackPanel>\n <WrapPanel>\n <TextBlock>1</TextBlock>\n <TextBlock>2</TextBlock>\n <TextBlock>3</TextBlock>\n <TextBlock>4</TextBlock>\n </WrapPanel>\n <WrapPanel>\n <TextBlock>5</TextBlock>\n <TextBlock>6</TextBlock>\n </WrapPanel>\n</StackPanel>\n"
},
{
"answer_id": 51860064,
"author": "Wobbles",
"author_id": 3797778,
"author_profile": "https://Stackoverflow.com/users/3797778",
"pm_score": 1,
"selected": false,
"text": "<TextBlock Text=\"
\"/>\n"
},
{
"answer_id": 59183107,
"author": "Aaron Koehler",
"author_id": 3015038,
"author_profile": "https://Stackoverflow.com/users/3015038",
"pm_score": 0,
"selected": false,
"text": "<TextBlock Margin=\"0,20,0,0\">5</TextBlock>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24177/"
] |
341,942 | <p>This should be easy, but I'm not sure how to best go about it. I have a WinForms app that lets the user type in long descriptions. Occaisionally, they would type in URLs, and the RichTextBox would recognize them and make them clickable when displayed.</p>
<p>I'm moving the app to the web, and I'm not sure how to make those same URLs clickable. Is there some semi-automatic way to convert "<a href="http://www.google.com" rel="nofollow noreferrer">http://www.google.com</a>" or "www.google.com" to clickable links? Do I have to resort to RegEx matching?</p>
| [
{
"answer_id": 341960,
"author": "MrKurt",
"author_id": 35296,
"author_profile": "https://Stackoverflow.com/users/35296",
"pm_score": 5,
"selected": true,
"text": "\\b(?:(?:https?|ftp|file)://|www\\.|ftp\\.)\n (?:\\([-A-Z0-9+&@#/%=~_|$?!:,.]*\\)|[-A-Z0-9+&@#/%=~_|$?!:,.])*\n (?:\\([-A-Z0-9+&@#/%=~_|$?!:,.]*\\)|[A-Z0-9+&@#/%=~_|$])\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
341,952 | <p>I've got two Django projects on the same server. The first launched several months ago, and has since collected hundreds of user accounts. The second project is launching in a few days, and we'd like the second project to allow users of the first app to authenticate using the same credentials.</p>
<p>At first, I was going to simply dump the user table from the first project into the second project, but this would not allow for a synchronous solution (user creates account on project B, does not then have access to project A).</p>
<p>Does Django have some way of natively switching database names (since they're on the same server) for user authentication, and then back to the original database when finished with authentication?</p>
<p>If not, what do you think would be the best solution for my problem? Also - we're using MySQL.</p>
| [
{
"answer_id": 342161,
"author": "eliego",
"author_id": 39092,
"author_profile": "https://Stackoverflow.com/users/39092",
"pm_score": 2,
"selected": false,
"text": "DROP TABLE proj2.users;\nCREATE VIEW proj2.users AS SELECT * FROM proj1.users;\n"
},
{
"answer_id": 342303,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 3,
"selected": true,
"text": "from django.db import models\n\ndef user_post_save(sender, instance, **kwargs):\n ... run script to synchronize tables ...\nmodels.signals.post_save.connect(user_post_save, sender=User)\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22468/"
] |
341,953 | <p>I am a bit rusty on my Haskell and am looking to ramp back up. One thing I enjoy from F# is the F# Interactive shell integrated with Visual Studio: I can evaluate virtually anything (including function and class definitions) and use F# as a shell. Is there an equivalent in Haskell? When I use <code>ghci</code>, I cannot evaluate function definitions. How do you work around that?</p>
<p>My current preferred setting is using Emacs with haskell-mode and opening an interactive ghi interpreter. However, is there a way to evaluate just region of a file?</p>
| [
{
"answer_id": 342010,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 4,
"selected": true,
"text": "$ ghci\nPrelude> let double n = n + n\nPrelude> double 42\n84\n"
},
{
"answer_id": 342014,
"author": "J Cooper",
"author_id": 38803,
"author_profile": "https://Stackoverflow.com/users/38803",
"pm_score": 1,
"selected": false,
"text": "let"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34596/"
] |
341,957 | <p>I have a c# struct where I need to forbid calling the no args constructor on it.</p>
<pre><code>MyStruct a;
/// init a by members // OK
MyStruct b = MyStruct.Fact(args); // OK, inits by memebers
MyStruct s = new MyStruct(); // can't have that
</code></pre>
<p>I'm doing this mostly to force explicet values for all members as there are no valid default values and all members must have valid values.</p>
<p>In C++ this would be easy, add a private constructor but c# doesn't allow that.</p>
<p>Is there a way to prevent the above? </p>
<p>I really need to enforce using a factory so preventing all public constructor calls would work just as well.</p>
<hr>
<p>Full discloser: to avoid a mono dependency, the c# app is being automatically translated to D where <code>new Struct()</code> results in a pointer and this is mucking things up for me. However this question is relevant despite that so just ignore it.</p>
| [
{
"answer_id": 341977,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "MyStruct ms = new MyStruct(); MyStruct[] array = new MyStruct[1];\nMyStruct ms = array[0];\n"
},
{
"answer_id": 35088203,
"author": "Eljay",
"author_id": 4641116,
"author_profile": "https://Stackoverflow.com/users/4641116",
"pm_score": 0,
"selected": false,
"text": "using System;\n\nnamespace CrazyStruct\n{\n public struct MyStruct\n {\n private readonly int _height;\n private readonly bool _init; // Will be 'false' using default(MyStruct).\n\n /// <summary>\n /// Height in centimeters.\n /// </summary>\n public int Height\n {\n get\n {\n if (!_init)\n {\n // Alternatively, could have the preferred default value set here.\n // _height = 200; // cm\n // _heightInit = true;\n throw new InvalidOperationException(\"Height has not been initialized.\");\n }\n return _height;\n }\n // No set: immutable-ish.\n }\n\n private MyStruct(int height)\n {\n _height = height;\n _init = true;\n }\n\n public static MyStruct Factory(int height)\n {\n return new MyStruct(height);\n }\n }\n\n static class Program\n {\n static void Main(string[] args)\n {\n MyStruct my = MyStruct.Factory(195);\n Console.WriteLine(\"My height is {0} cm.\", my.Height);\n try\n {\n var array = new MyStruct[1];\n var ms = array[0];\n Console.WriteLine(\"My height is not {0} cm.\", ms.Height);\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Caught the expected exception: {0}.\", ex);\n }\n Console.ReadKey();\n }\n }\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
341,966 | <p>How is it that tools like this one can make an ajax style call back to a central site? basically they give you a " tag to put on your site where ever it is. So in this widget you have the ability to ask for an email to be sent to you for the page you're currently on. I assume this makes an ajax style call back to share this who sends out the email. But how can they do this with out a proxy on your server and without the browser blocking it as an XSS exploit?</p>
<p>Any answers on this would be greatly appreciated thank you for your help. I assume working with the Flickr API would present the same challenges?</p>
<p>Link from the title : <a href="http://sharethis.com/" rel="nofollow noreferrer">http://sharethis.com/</a></p>
| [
{
"answer_id": 342150,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "someFunction(\"Callback Data\");\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42987/"
] |
341,971 | <p>What is this "Execute Around" idiom (or similar) I've been hearing about?
Why might I use it, and why might I not want to use it?</p>
| [
{
"answer_id": 342016,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "public interface InputStreamAction\n{\n void useStream(InputStream stream) throws IOException;\n}\n\n// Somewhere else \n\npublic void executeWithFile(String filename, InputStreamAction action)\n throws IOException\n{\n InputStream stream = new FileInputStream(filename);\n try {\n action.useStream(stream);\n } finally {\n stream.close();\n }\n}\n\n// Calling it\nexecuteWithFile(\"filename.txt\", new InputStreamAction()\n{\n public void useStream(InputStream stream) throws IOException\n {\n // Code to use the stream goes here\n }\n});\n\n// Calling it with Java 8 Lambda Expression:\nexecuteWithFile(\"filename.txt\", s -> System.out.println(s.read()));\n\n// Or with Java 8 Method reference:\nexecuteWithFile(\"filename.txt\", ClassName::methodName);\n executeWithFile try-with-resources AutoClosable"
},
{
"answer_id": 342029,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 6,
"selected": false,
"text": "//... chunk of init/preparation code ...\ntask A\n//... chunk of cleanup/finishing code ...\n\n//... chunk of identical init/preparation code ...\ntask B\n//... chunk of identical cleanup/finishing code ...\n\n//... chunk of identical init/preparation code ...\ntask C\n//... chunk of identical cleanup/finishing code ...\n\n//... and so on. //pseudo-code:\nclass DoTask()\n{\n do(task T)\n {\n // .. chunk of prep code\n // execute task T\n // .. chunk of cleanup code\n }\n};\n\nDoTask.do(task A)\nDoTask.do(task B)\nDoTask.do(task C)"
},
{
"answer_id": 758678,
"author": "Florin",
"author_id": 34565,
"author_profile": "https://Stackoverflow.com/users/34565",
"pm_score": 0,
"selected": false,
"text": "//-- the target class\nclass Resource { \n def open () { // sensitive operation }\n def close () { // sensitive operation }\n //-- target method\n def doWork() { println \"working\";} }\n\n//-- the execute around code\ndef static use (closure) {\n def res = new Resource();\n try { \n res.open();\n closure(res)\n } finally {\n res.close();\n }\n}\n\n//-- using the code\nResource.use { res -> res.doWork(); }\n"
},
{
"answer_id": 758705,
"author": "Ben Liblit",
"author_id": 91929,
"author_profile": "https://Stackoverflow.com/users/91929",
"pm_score": 3,
"selected": false,
"text": "return"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/341971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4725/"
] |
342,031 | <p>Does anyone know of a way to monitor table record changes in a SQL Server (2005 or 2008) database from a .Net application? It needs to be able to support multiple clients at a time. Each client will "subscribe" when it starts, and "unsubscribe" when it exits. Multiple users could be accessing the system at once and I want to reflect their changes on the other users client. Then when the client handles the change event, it could update it's local object representing that record. Kind of similar to how Access updates records that are modified are reflected in each form referencing it.</p>
<p>I know microsoft has their Microsoft.SqlServer libraries for interacting with a SQL Server. But I'm not sure which concept applies to what I want to do (or what could be bent to apply to what I want to do). The ones that sound like they might be useful are the Management ones or the Replication one.</p>
<p>In anticipation of someone asking, "why don't you just requery the table occasionally to look for new information?" I have a large number of tables that I want to monitor and that would be a pain in the butt. Plus if I'm looking for something a bit more elegant.</p>
<p>I'm open to suggestions...</p>
| [
{
"answer_id": 895300,
"author": "Aaron",
"author_id": 2742,
"author_profile": "https://Stackoverflow.com/users/2742",
"pm_score": 3,
"selected": false,
"text": "void Initialization()\n{\n // Create a dependency connection.\n SqlDependency.Start(connectionString, queueName);\n}\n\nvoid SomeMethod()\n{\n // Assume connection is an open SqlConnection.\n\n // Create a new SqlCommand object.\n SqlCommand command=new SqlCommand(\n \"SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers\", \n connection);\n\n // Create a dependency and associate it with the SqlCommand.\n SqlDependency dependency=new SqlDependency(command);\n // Maintain the refence in a class member.\n\n // Subscribe to the SqlDependency event.\n dependency.OnChange+=new OnChangeEventHandler(OnDependencyChange);\n\n // Execute the command.\n command.ExecuteReader();\n // Process the DataReader.\n}\n\n// Handler method\nvoid OnDependencyChange(object sender, \n SqlNotificationsEventArgs e )\n{\n // Handle the event (for example, invalidate this cache entry).\n}\n\nvoid Termination()\n{\n // Release the dependency.\n SqlDependency.Stop(connectionString, queueName);\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34440/"
] |
342,032 | <p>I was trying to raise a post back event by div tag.
I don't know how to do that. AL I could think of is javascript, but that is not what I want.
I need to call function of a class inside a event handler. </p>
| [
{
"answer_id": 342253,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<div id=\"foo\" onclick=\"__doPostBack('foo','')\">\nClicky!\n</div>\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21918/"
] |
342,037 | <p>I put together a class yesterday to do some useful task. I started alpha testing, and at some point realized I was adding alpha test related methods to the class itself. It hit me that they don't belong there. After a bit of head scratching I derived a test class from the base class that has access to the protected members as well. I put all of the testing related methods, and set up and tear down in the test class, and left the base class lean and mean as the old saying goes.</p>
<p>After browsing around here awhile I found one comment that suggested using this sort of technique by making the testing class a friend of the real class.</p>
<p>In retrospect both of those techniques should have been obvious to me.</p>
<p><strong>What I am looking for, are techniques for specifically alpha testing/unit testing classes, without adding to the weight of the class being tested.</strong></p>
<p><strong>What techniques have you personally used, and recommend?</strong></p>
| [
{
"answer_id": 342066,
"author": "Jeff B",
"author_id": 25879,
"author_profile": "https://Stackoverflow.com/users/25879",
"pm_score": 0,
"selected": false,
"text": "class myClass\n{\nprivate:\n int foo;\npublic:\n myClass() { foo = 0; }\n}\n class test_myClass\n{\npublic:\n int foo;\npublic:\n test_myClass();\n};\n\nvoid test()\n{\n myClass *c = new myClass();\n test_myClass *t = (test_myClass*)c;\n // All methods are called on c.\n // White-box access is available through t.\n};\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734/"
] |
342,044 | <p>I'm selecting 1 field from 1 table and storing it into a temp table.</p>
<p>Sometimes that table ends up with 0 rows.</p>
<p>I want to add that field onto another table that has 20+ fields</p>
<p>Regular union won't work for me because of the field # mismatch.
Outer wont work for me because there is nothing to compare.
NVL doesn't work on the first temp table.</p>
<p>Anyone know how to do it?</p>
<p><strong>UPDATED:</strong></p>
<p>I failed to mention.... When the table that retrieves 1 field finds a match in other cases, this code that I'm using now works....</p>
<pre><code>SELECT DISTINCT reqhead_rec.resp_name<br>
FROM reqhead_rec, biglist<br>
WHERE reqhead_rec.req_no = biglist.req_no
AND reqhead_rec.frm = biglist.req_frm<br>
INTO TEMP grabname with no log;
SELECT biglist.*, grabname.resp_name<br>
FROM biglist, grabname<br>
ORDER BY prnt_item, account_amt<br>
INTO TEMP xxx with no log;
</code></pre>
| [
{
"answer_id": 342068,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "SELECT t20.*, t1.*\nFROM table_with_20_columns AS t20\n LEFT OUTER JOIN temp_table_with_1_column AS t1 ON (1=1);\n ON USING ON (1=1) SELECT COALESCE(reqhead_rec.resp_name, dflt.resp_name) AS resp_name\nFROM (SELECT 'default name' AS resp_name) dflt\n LEFT OUTER JOIN reqhead_rec ON (1=1)\nWHERE reqhead_rec.req_no = biglist.req_no AND reqhead_rec.frm = biglist.req_frm \nINTO TEMP grabname WITH NO LOG;\n reahead_rec ON WHERE COALESCE() SELECT b.*, COALESCE(r.resp_name, 'default name') AS resp_name\nFROM biglist AS b\n LEFT OUTER JOIN reqhead_rec AS r\n ON (b.req_no = r.req_no AND r.frm = b.req_frm)\nINTO TEMP xxx WITH NO LOG;\n"
},
{
"answer_id": 342079,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": true,
"text": "SELECT NULL, NULL, NULL, NULL, MySingleField, NULL, NULL, NULL... FROM #temp\nUNION ALL\nSELECT Col1, Col2, Col3, Col4, Col5, Col6,... FROM OtherTable\n SELECT\n *,\n (SELECT TOP 1 Name FROM Blah WHERE Blah.SomeID = MyTable.SomeID) AS ExtraCol\nFROM\n MyTable\n"
},
{
"answer_id": 4282528,
"author": "adam",
"author_id": 520893,
"author_profile": "https://Stackoverflow.com/users/520893",
"pm_score": 1,
"selected": false,
"text": "nvl(NULL,NULL)"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42229/"
] |
342,052 | <p>I need to increment a String in java from "aaaaaaaa" to "aaaaaab" to "aaaaaac" up through the alphabet, then eventually to "aaaaaaba" to "aaaaaabb" etc. etc.</p>
<p>Is there a trick for this?</p>
| [
{
"answer_id": 342090,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 0,
"selected": false,
"text": "public String(byte[] bytes, String charsetName)\n"
},
{
"answer_id": 342104,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 6,
"selected": false,
"text": "public static String base26(int num) {\n if (num < 0) {\n throw new IllegalArgumentException(\"Only positive numbers are supported\");\n }\n StringBuilder s = new StringBuilder(\"aaaaaaa\");\n for (int pos = 6; pos >= 0 && num > 0 ; pos--) {\n char digit = (char) ('a' + num % 26);\n s.setCharAt(pos, digit);\n num = num / 26;\n }\n return s.toString();\n}\n"
},
{
"answer_id": 342109,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "public static void incrementString(char[] str)\n{\n for(int pos = str.length - 1; pos >= 0; pos--)\n {\n if(Character.toUpperCase(str[pos]) != 'Z')\n {\n str[pos]++;\n break;\n }\n else\n str[pos] = 'a';\n }\n}\n"
},
{
"answer_id": 342110,
"author": "Clayton",
"author_id": 22201,
"author_profile": "https://Stackoverflow.com/users/22201",
"pm_score": -1,
"selected": true,
"text": "char array[] = new char[4];\nfor (char c0 = 'a'; c0 <= 'z'; c0++) {\n array[0] = c0;\n for (char c1 = 'a'; c1 <= 'z'; c1++) {\n array[1] = c1;\n for (char c2 = 'a'; c2 <= 'z'; c2++) {\n array[2] = c2;\n for (char c3 = 'a'; c3 <= 'z'; c3++) {\n array[3] = c3;\n String s = new String(array);\n System.out.println(s);\n }\n }\n }\n}\n"
},
{
"answer_id": 342401,
"author": "Ande Turner",
"author_id": 4857,
"author_profile": "https://Stackoverflow.com/users/4857",
"pm_score": 0,
"selected": false,
"text": "public class Permutator {\n\n private int permutation;\n\n private int permutations; \n\n private StringBuilder stringbuilder;\n\n public Permutator(final int LETTERS) {\n\n if (LETTERS < 1) {\n throw new IllegalArgumentException(\"Usage: Permutator( \\\"1 or Greater Required\\\" \\)\");\n }\n\n this.permutation = 0;\n\n // MAGIC NUMBER : 26 = Number of Letters in the English Alphabet \n this.permutations = (int) Math.pow(26, LETTERS);\n\n this.stringbuilder = new StringBuilder();\n\n for (int i = 0; i < LETTERS; ++i) {\n this.stringbuilder.append('a');\n }\n }\n\n public String getCount() {\n\n return String.format(\"Permutation: %s of %s Permutations.\", this.permutation, this.permutations);\n }\n\n public int getPermutation() {\n\n return this.permutation;\n }\n\n public int getPermutations() {\n\n return this.permutations;\n }\n\n private void permutate() {\n\n // TODO: Implement Utilising one of the Examples Posted.\n } \n\n public String toString() {\n\n this.permutate();\n\n return this.stringbuilder.toString();\n }\n} \n"
},
{
"answer_id": 342491,
"author": "Ray Tayek",
"author_id": 51292,
"author_profile": "https://Stackoverflow.com/users/51292",
"pm_score": 1,
"selected": false,
"text": "import java.math.BigInteger;\npublic class Strings {\n Strings(final int digits,final int radix) {\n this(digits,radix,BigInteger.ZERO);\n }\n Strings(final int digits,final int radix,final BigInteger number) {\n this.digits=digits;\n this.radix=radix;\n this.number=number;\n }\n void addOne() {\n number=number.add(BigInteger.ONE);\n }\n public String toString() {\n String s=number.toString(radix);\n while(s.length()<digits)\n s='0'+s;\n return s;\n }\n public char convert(final char c) {\n if('0'<=c&&c<='9')\n return (char)('a'+(c-'0'));\n else if('a'<=c&&c<='p')\n return (char)(c+10);\n else throw new RuntimeException(\"more logic required for radix: \"+radix);\n }\n public char convertInverse(final char c) {\n if('a'<=c&&c<='j')\n return (char)('0'+(c-'a'));\n else if('k'<=c&&c<='z')\n return (char)(c-10);\n else throw new RuntimeException(\"more logic required for radix: \"+radix);\n }\n void testFix() {\n for(int i=0;i<radix;i++)\n if(convert(convertInverse((char)('a'+i)))!='a'+i)\n throw new RuntimeException(\"testFix fails for \"+i);\n }\n public String toMyString() {\n String s=toString(),t=\"\";\n for(int i=0;i<s.length();i++)\n t+=convert(s.charAt(i));\n return t;\n }\n public static void main(String[] arguments) {\n Strings strings=new Strings(8,26);\n strings.testFix();\n System.out.println(strings.number.toString()+' '+strings+' '+strings.toMyString());\n for(int i=0;i<Math.pow(strings.radix,3);i++)\n try {\n strings.addOne();\n if(Math.abs(i-i/strings.radix*strings.radix)<2)\n System.out.println(strings.number.toString()+' '+strings+' '+strings.toMyString());\n } catch(Exception e) {\n System.out.println(\"\"+i+' '+strings+\" failed!\");\n }\n }\n final int digits,radix;\n BigInteger number;\n}\n"
},
{
"answer_id": 342666,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 1,
"selected": false,
"text": " public static void base26(int maxLength) {\n buildWord(maxLength, \"\");\n }\n public static void buildWord(int remaining, String word)\n {\n if (remaining == 0)\n {\n System.out.println(word);\n }\n else\n {\n for (char letter = 'A'; letter <= 'Z'; ++letter)\n {\n buildWord(remaining-1, word + letter);\n }\n }\n }\n\n public static void main(String[] args)\n {\n base26(8);\n }\n"
},
{
"answer_id": 2338415,
"author": "cyberz",
"author_id": 281681,
"author_profile": "https://Stackoverflow.com/users/281681",
"pm_score": 4,
"selected": false,
"text": "public class StringInc {\n public static void main(String[] args) {\n System.out.println(next(\"aaa\")); // Prints aab\n\n System.out.println(next(\"abcdzz\")); // Prints abceaa\n\n System.out.println(next(\"zzz\")); // Prints aaaa\n }\n\n public static String next(String s) {\n int length = s.length();\n char c = s.charAt(length - 1);\n\n if(c == 'z')\n return length > 1 ? next(s.substring(0, length - 1)) + 'a' : \"aa\";\n\n return s.substring(0, length - 1) + ++c;\n }\n}\n"
},
{
"answer_id": 34920219,
"author": "geoand",
"author_id": 2504224,
"author_profile": "https://Stackoverflow.com/users/2504224",
"pm_score": 0,
"selected": false,
"text": "static String next(String input) {\n return doNext(input, \"\")\n}\n\n@TailRecursive\n@CompileStatic\nstatic String doNext(String input, String result) {\n if(!self) {\n return result\n }\n\n final String last = input[-1]\n final String nonLast = self.substring(0, input.size()-1)\n if('z' == last) {\n return doNext(nonLast, (nonLast ? 'a' : 'aa') + result)\n }\n\n return doNext('', nonLast + (((last as Character) + 1) as Character).toString() + result)\n}\n"
},
{
"answer_id": 42480155,
"author": "Betalord",
"author_id": 7340677,
"author_profile": "https://Stackoverflow.com/users/7340677",
"pm_score": 0,
"selected": false,
"text": "/**\n * Increases the given String value by one. Examples (with min 'a' and max 'z'): <p>\n * \n * - \"aaa\" -> \"aab\" <br>\n * - \"aab\" -> \"aac\" <br>\n * - \"aaz\" -> \"aba\" <br>\n * - \"zzz\" -> \"aaaa\" <br>\n * \n * @param s\n * @param min lowest char (a zero)\n * @param max highest char (e.g. a 9, in a decimal system)\n * @return increased String by 1\n */\npublic static String incString(String s, char min, char max) {\n char last = s.charAt(s.length() - 1);\n if (++last > max)\n return s.length() > 1 ? incString(s.substring(0, s.length()-1), min, max) + min : \"\" + min + min;\n else\n return s.substring(0, s.length()-1) + last;\n}\n"
},
{
"answer_id": 53048097,
"author": "Rahul Ramamoorthy",
"author_id": 9962878,
"author_profile": "https://Stackoverflow.com/users/9962878",
"pm_score": 0,
"selected": false,
"text": "public static String incrementString(String string)\n{\n if(string.length()==1)\n {\n if(string.equals(\"z\"))\n return \"aa\";\n else if(string.equals(\"Z\"))\n return \"Aa\";\n else\n return (char)(string.charAt(0)+1)+\"\";\n } \n if(string.charAt(string.length()-1)!='z')\n {\n return string.substring(0, string.length()-1)+(char)(string.charAt(string.length()-1)+1);\n }\n return incrementString(string.substring(0, string.length()-1))+\"a\";\n}\n"
},
{
"answer_id": 65966251,
"author": "Vibhanshu",
"author_id": 9675605,
"author_profile": "https://Stackoverflow.com/users/9675605",
"pm_score": 0,
"selected": false,
"text": "import org.apache.commons.lang3.ArrayUtils;\npublic class StringInc {\n public static void main(String[] args) {\n System.out.println(next(\"aaa\")); // Prints aab\n\n System.out.println(next(\"abcdzz\")); // Prints abceaa\n\n System.out.println(next(\"zzz\")); // Prints aaaa\n }\n\n public static String next(String str) {\n boolean increment = true;\n char[] arr = str.toCharArray();\n for (int i = arr.length - 1; i >= 0 && increment; i--) {\n char letter = arr[i];\n if (letter != 'z') {\n letter++;\n increment = false;\n } else {\n letter = 'a';\n }\n arr[i] = letter;\n }\n if (increment) {\n arr = ArrayUtils.insert(0, arr, 'a');\n }\n return new String(arr);\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
342,057 | <p>This is a continuation of my question about <a href="https://stackoverflow.com/questions/339795/reading-the-superblock">reading the superblock</a>.</p>
<p>Let's say I want to target the HFS+ file system in Mac OS X. How could I read sector 2 of the boot disk? As far as I know Unix only provides system calls to read from files, which are never stored at that location.</p>
<p>Does this require either 1) the program to run kernel mode, or 2) the program to be written in Assembly? I would prefer to avoid either of these restrictions, particularly the latter.</p>
| [
{
"answer_id": 342077,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": true,
"text": "/dev/sda 2*SECTOR_SIZE SECTOR_SIZE /dev /dev/sda /dev/hda"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18091/"
] |
342,080 | <p>I have a little utility that does a search of a number of files. I had to create it because both Google & Windows desktop searches were not finding the appropriate lines in files. The searching works fine (I am willing to improve on it) but one of the things I would like to add to my util is a batch find/replace.</p>
<p>So how would be the best way to read a line from a file, compare it to a search term and if it passes, then update the line, and continue through the rest of the file?</p>
| [
{
"answer_id": 347668,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 0,
"selected": false,
"text": "'a string' dir *.txt | FindReplace 'a string'\n 'a string' dir *.txt | FindReplace 'a string' 'replacement string'\n FindReplace -path MyFile.txt 'a string' function FindReplace( [string]$search, [string]$replace, [string[]]$path ) {\n # Include paths from pipeline input.\n $path += @($input)\n\n # Find all matches in the specified files.\n $matches = Select-String -path $path -pattern $search -simpleMatch\n\n # If replacement value was given, perform replacements.\n if( $replace ) {\n # Group matches by file path.\n $matches | group -property Path | % {\n $content = Get-Content $_.Name\n\n # Replace all matching lines in current file.\n foreach( $match in $_.Group ) {\n $index = $match.LineNumber - 1\n $line = $content[$index]\n $updatedLine = $line -replace $search,$replace\n $content[$index] = $updatedLine\n\n # Update match with new line value.\n $match | Add-Member NoteProperty UpdatedLine $updatedLine\n }\n\n # Update file content.\n Set-Content $_.Name $content\n }\n }\n\n # Return matches.\n $matches\n}\n Select-String"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18821/"
] |
342,088 | <p>I have a web app on our intranet (VS 2005). There are a couple pages that don't require the user to be logged into the app (feedback and the default page). I am trying to get the domain and username to display and/or send with the feedback. Is there a way to do this without requiring the user to log in? I've tried <code>this.Request.ServerVariables["LOGON_USER"]</code> and <code>this.User.Identity.Name</code>, but neither of them worked.</p>
<p>Edit:<br>
I should have mentioned most of the users have Windows 2000 on their machines. It works on my development machine (XP), but not on the production network (where I have 2000).</p>
| [
{
"answer_id": 342123,
"author": "matt_dev",
"author_id": 39086,
"author_profile": "https://Stackoverflow.com/users/39086",
"pm_score": 2,
"selected": false,
"text": "AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\n\nWindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;\nWindowsIdentity identity = (WindowsIdentity)principal.Identity;\n\nString userName= principal.Identity.Name;\n"
},
{
"answer_id": 14359713,
"author": "Ryan McDonough",
"author_id": 442624,
"author_profile": "https://Stackoverflow.com/users/442624",
"pm_score": 0,
"selected": false,
"text": "public string user_Name\n{\n get\n {\n string x = Page.User.Identity.Name;\n\n x = x.Replace(\"YOURDOMAIN\\\\\", \"\");\n\n return x;\n }\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39355/"
] |
342,093 | <p>Here's my PS1 variable:</p>
<pre><code>PS1='\u:\W$(__git_ps1 "\e[32m\][%s]\e[0m\]")$ '
</code></pre>
<p>Works great for picking up my Git branch, but it has the unfortunate side-effect of wrapping the lines when the colours are active, so that they overlap when you use long commands.</p>
<p>Can anyone with magic PS1 skills help me out to fix this?</p>
| [
{
"answer_id": 342135,
"author": "Aupajo",
"author_id": 10407,
"author_profile": "https://Stackoverflow.com/users/10407",
"pm_score": 7,
"selected": true,
"text": "PS1='\\u:\\W$(__git_ps1 \"\\[\\e[32m\\][%s]\\[\\e[0m\\]\")$ '\n"
},
{
"answer_id": 1703567,
"author": "SiegeX",
"author_id": 207248,
"author_profile": "https://Stackoverflow.com/users/207248",
"pm_score": 5,
"selected": false,
"text": "BLACK=$(tput setaf 0)\nRED=$(tput setaf 1)\nGREEN=$(tput setaf 2)\nLIME_YELLOW=$(tput setaf 190)\nYELLOW=$(tput setaf 3)\nPOWDER_BLUE=$(tput setaf 153)\nBLUE=$(tput setaf 4)\nMAGENTA=$(tput setaf 5)\nCYAN=$(tput setaf 6)\nWHITE=$(tput setaf 7)\nBRIGHT=$(tput bold)\nNORMAL=$(tput sgr0)\nBLINK=$(tput blink)\nREVERSE=$(tput smso)\nUNDERLINE=$(tput smul)\n PS1=\"\\[${WHITE}\\](\\[${YELLOW}\\]\\u@\\h\\[${WHITE}\\])\\[${NORMAL}\\]$ \"\n"
},
{
"answer_id": 6675281,
"author": "Aesthir",
"author_id": 831970,
"author_profile": "https://Stackoverflow.com/users/831970",
"pm_score": 3,
"selected": false,
"text": "## ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ## ## ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ [ Aesthir's Color Functions ] ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ## ## ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ## Normal () { printf '\\e[m'\"$*\"; } ; Tblack () { printf '\\e[0;30m'\"$*\"'\\e[m'; } TNormal () { printf '\\e[m'\"$*\"; } ; Tred () { printf '\\e[0;31m'\"$*\"'\\e[m'; } Bold () { printf '\\e[1m'\"$*\"'\\e[m'; } ; Tgreen () { printf '\\e[0;32m'\"$*\"'\\e[m'; } TBold () { printf '\\e[1m'\"$*\"'\\e[m'; } ; Tbrown () { printf '\\e[0;33m'\"$*\"'\\e[m'; } Underline () { printf '\\e[4m'\"$*\"'\\e[m'; } ; Tyellow () { printf '\\e[0;33m'\"$*\"'\\e[m'; } TUnderline () { printf '\\e[4m'\"$*\"'\\e[m'; } ; Tblue () { printf '\\e[0;34m'\"$*\"'\\e[m'; } Flash () { printf '\\e[5m'\"$*\"'\\e[m'; } ; Tmagenta () { printf '\\e[0;35m'\"$*\"'\\e[m'; } TFlash () { printf '\\e[5m'\"$*\"'\\e[m'; } ; Tpurple () { printf '\\e[0;35m'\"$*\"'\\e[m'; } Invert () { printf '\\e[7m'\"$*\"'\\e[m'; } ; Taqua () { printf '\\e[0;36m'\"$*\"'\\e[m'; } TInvert () { printf '\\e[7m'\"$*\"'\\e[m'; } ; Tcyan () { printf '\\e[0;36m'\"$*\"'\\e[m'; } Invisible () { printf '\\e[8m'\"$*\"'\\e[m'; } ; Tgrey () { printf '\\e[0;37m'\"$*\"'\\e[m'; } TInvisible () { printf '\\e[8m'\"$*\"'\\e[m'; } ; Twhite () { printf '\\e[0;37m'\"$*\"'\\e[m'; } ## ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ Bold Color Text ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ## ∞∞∞∞∞∞∞∞∞∞∞∞ Underlined Color Text ∞∞∞∞∞∞∞∞∞∞∞∞∞ ## TblackB () { printf '\\e[1;30m'\"$*\"'\\e[m'; } ; TblackU () { printf '\\e[4;30m'\"$*\"'\\e[m'; } TgreyB () { printf '\\e[1;30m'\"$*\"'\\e[m'; } ; TredU () { printf '\\e[4;31m'\"$*\"'\\e[m'; } TredB () { printf '\\e[1;31m'\"$*\"'\\e[m'; } ; TgreenU () { printf '\\e[4;32m'\"$*\"'\\e[m'; } TgreenB () { printf '\\e[1;32m'\"$*\"'\\e[m'; } ; TbrownU () { printf '\\e[4;33m'\"$*\"'\\e[m'; } TbrownB () { printf '\\e[1;33m'\"$*\"'\\e[m'; } ; TyellowU () { printf '\\e[4;33m'\"$*\"'\\e[m'; } TyellowB () { printf '\\e[1;33m'\"$*\"'\\e[m'; } ; TblueU () { printf '\\e[4;34m'\"$*\"'\\e[m'; } TblueB () { printf '\\e[1;34m'\"$*\"'\\e[m'; } ; TmagentaU () { printf '\\e[4;35m'\"$*\"'\\e[m'; } TmagentaB () { printf '\\e[1;35m'\"$*\"'\\e[m'; } ; TpurpleU () { printf '\\e[4;35m'\"$*\"'\\e[m'; } TpurpleB () { printf '\\e[1;35m'\"$*\"'\\e[m'; } ; TaquaU () { printf '\\e[4;36m'\"$*\"'\\e[m'; } TaquaB () { printf '\\e[1;36m'\"$*\"'\\e[m'; } ; TcyanU () { printf '\\e[4;36m'\"$*\"'\\e[m'; } TcyanB () { printf '\\e[1;36m'\"$*\"'\\e[m'; } ; TgreyU () { printf '\\e[4;37m'\"$*\"'\\e[m'; } TwhiteB () { printf '\\e[1;37m'\"$*\"'\\e[m'; } ; TwhiteU () { printf '\\e[4;37m'\"$*\"'\\e[m'; } ## ∞∞∞∞∞∞∞∞∞∞∞∞∞ Flashing Color Text ∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ## ∞∞∞∞∞∞∞∞∞∞∞∞∞ Inverted Color Text ∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ## TblackF () { printf '\\e[5;30m'\"$*\"'\\e[m'; } ; TblackI () { printf '\\e[7;40m'\"$*\"'\\e[m'; } TredF () { printf '\\e[5;31m'\"$*\"'\\e[m'; } ; TredI () { printf '\\e[7;41m'\"$*\"'\\e[m'; } TgreenF () { printf '\\e[5;32m'\"$*\"'\\e[m'; } ; TgreenI () { printf '\\e[7;42m'\"$*\"'\\e[m'; } TbrownF () { printf '\\e[5;33m'\"$*\"'\\e[m'; } ; TbrownI () { printf '\\e[7;43m'\"$*\"'\\e[m'; } TyellowF () { printf '\\e[5;33m'\"$*\"'\\e[m'; } ; TyellowI () { printf '\\e[7;43m'\"$*\"'\\e[m'; } TblueF () { printf '\\e[5;34m'\"$*\"'\\e[m'; } ; TblueI () { printf '\\e[7;44m'\"$*\"'\\e[m'; } TmagentaF () { printf '\\e[5;35m'\"$*\"'\\e[m'; } ; TmagentaI () { printf '\\e[7;45m'\"$*\"'\\e[m'; } TpurpleF () { printf '\\e[5;35m'\"$*\"'\\e[m'; } ; TpurpleI () { printf '\\e[7;45m'\"$*\"'\\e[m'; } TaquaF () { printf '\\e[5;36m'\"$*\"'\\e[m'; } ; TaquaI () { printf '\\e[7;46m'\"$*\"'\\e[m'; } TcyanF () { printf '\\e[5;36m'\"$*\"'\\e[m'; } ; TcyanI () { printf '\\e[7;46m'\"$*\"'\\e[m'; } TgreyF () { printf '\\e[5;37m'\"$*\"'\\e[m'; } ; TgreyI () { printf '\\e[7;47m'\"$*\"'\\e[m'; } TwhiteF () { printf '\\e[5;37m'\"$*\"'\\e[m'; } ; TwhiteI () { printf '\\e[7;47m'\"$*\"'\\e[m'; } ## ∞∞∞∞∞∞∞∞∞∞∞∞∞ Invisible Color Text ∞∞∞∞∞∞∞∞∞∞∞∞∞ ## ∞∞∞∞∞∞∞∞ Plain Text on Color Background ∞∞∞∞∞∞∞∞ ## TblackV () { printf '\\e[8;30m'\"$*\"'\\e[m'; } ; Bblack () { printf '\\e[m'\"$*\"'\\e[m'; } TredV () { printf '\\e[8;31m'\"$*\"'\\e[m'; } ; Bred () { printf '\\e[0;41m'\"$*\"'\\e[m'; } TgreenV () { printf '\\e[8;32m'\"$*\"'\\e[m'; } ; Bgreen () { printf '\\e[0;42m'\"$*\"'\\e[m'; } TbrownV () { printf '\\e[8;33m'\"$*\"'\\e[m'; } ; Bbrown () { printf '\\e[0;43m'\"$*\"'\\e[m'; } TyellowV () { printf '\\e[8;33m'\"$*\"'\\e[m'; } ; Byellow () { printf '\\e[0;43m'\"$*\"'\\e[m'; } TblueV () { printf '\\e[8;34m'\"$*\"'\\e[m'; } ; Bblue () { printf '\\e[0;44m'\"$*\"'\\e[m'; } TmagentaV () { printf '\\e[8;35m'\"$*\"'\\e[m'; } ; Bmagenta () { printf '\\e[0;45m'\"$*\"'\\e[m'; } TpurpleV () { printf '\\e[8;35m'\"$*\"'\\e[m'; } ; Bpurple () { printf '\\e[0;45m'\"$*\"'\\e[m'; } TaquaV () { printf '\\e[8;36m'\"$*\"'\\e[m'; } ; Baqua () { printf '\\e[0;46m'\"$*\"'\\e[m'; } TcyanV () { printf '\\e[8;36m'\"$*\"'\\e[m'; } ; Bcyan () { printf '\\e[0;46m'\"$*\"'\\e[m'; } TgreyV () { printf '\\e[8;37m'\"$*\"'\\e[m'; } ; Bgrey () { printf '\\e[0;47m'\"$*\"'\\e[m'; } TwhiteV () { printf '\\e[8;37m'\"$*\"'\\e[m'; } ; Bwhite () { printf '\\e[0;47m'\"$*\"'\\e[m'; } ## ∞∞∞∞∞∞∞∞∞ Bold Text on Color Background ∞∞∞∞∞∞∞∞ ## ∞∞∞∞∞∞ Underlined Text on Color Background ∞∞∞∞∞ ## BblackB () { printf '\\e[1;40m'\"$*\"'\\e[m'; } ; BblackU () { printf '\\e[4;40m'\"$*\"'\\e[m'; } BredB () { printf '\\e[1;41m'\"$*\"'\\e[m'; } ; BredU () { printf '\\e[4;41m'\"$*\"'\\e[m'; } BgreenB () { printf '\\e[1;42m'\"$*\"'\\e[m'; } ; BgreenU () { printf '\\e[4;42m'\"$*\"'\\e[m'; } BbrownB () { printf '\\e[1;43m'\"$*\"'\\e[m'; } ; BbrownU () { printf '\\e[4;43m'\"$*\"'\\e[m'; } ByellowB () { printf '\\e[1;43m'\"$*\"'\\e[m'; } ; ByellowU () { printf '\\e[4;43m'\"$*\"'\\e[m'; } BblueB () { printf '\\e[1;44m'\"$*\"'\\e[m'; } ; BblueU () { printf '\\e[4;44m'\"$*\"'\\e[m'; } BmagentaB () { printf '\\e[1;45m'\"$*\"'\\e[m'; } ; BmagentaU () { printf '\\e[4;45m'\"$*\"'\\e[m'; } BpurpleB () { printf '\\e[1;45m'\"$*\"'\\e[m'; } ; BpurpleU () { printf '\\e[4;45m'\"$*\"'\\e[m'; } BaquaB () { printf '\\e[1;46m'\"$*\"'\\e[m'; } ; BaquaU () { printf '\\e[4;46m'\"$*\"'\\e[m'; } BcyanB () { printf '\\e[1;46m'\"$*\"'\\e[m'; } ; BcyanU () { printf '\\e[4;46m'\"$*\"'\\e[m'; } BgreyB () { printf '\\e[1;47m'\"$*\"'\\e[m'; } ; BgreyU () { printf '\\e[4;47m'\"$*\"'\\e[m'; } BwhiteB () { printf '\\e[1;47m'\"$*\"'\\e[m'; } ; BwhiteU () { printf '\\e[4;47m'\"$*\"'\\e[m'; } ## ∞∞∞∞∞∞∞ Flashing Text on Color Background ∞∞∞∞∞∞ ## ∞∞∞∞∞∞∞ Inverted Text on Color Background ∞∞∞∞∞∞ ## BblackF () { printf '\\e[5;40m'\"$*\"'\\e[m'; } ; BblackI () { printf '\\e[7;30m'\"$*\"'\\e[m'; } BredF () { printf '\\e[5;41m'\"$*\"'\\e[m'; } ; BredI () { printf '\\e[7;31m'\"$*\"'\\e[m'; } BgreenF () { printf '\\e[5;42m'\"$*\"'\\e[m'; } ; BgreenI () { printf '\\e[7;32m'\"$*\"'\\e[m'; } BbrownF () { printf '\\e[5;43m'\"$*\"'\\e[m'; } ; BbrownI () { printf '\\e[7;33m'\"$*\"'\\e[m'; } ByellowF () { printf '\\e[5;43m'\"$*\"'\\e[m'; } ; ByellowI () { printf '\\e[7;33m'\"$*\"'\\e[m'; } BblueF () { printf '\\e[5;44m'\"$*\"'\\e[m'; } ; BblueI () { printf '\\e[7;34m'\"$*\"'\\e[m'; } BmagentaF () { printf '\\e[5;45m'\"$*\"'\\e[m'; } ; BmagentaI () { printf '\\e[7;35m'\"$*\"'\\e[m'; } BpurpleF () { printf '\\e[5;45m'\"$*\"'\\e[m'; } ; BpurpleI () { printf '\\e[7;35m'\"$*\"'\\e[m'; } BaquaF () { printf '\\e[5;46m'\"$*\"'\\e[m'; } ; BaquaI () { printf '\\e[7;36m'\"$*\"'\\e[m'; } BcyanF () { printf '\\e[5;46m'\"$*\"'\\e[m'; } ; BcyanI () { printf '\\e[7;36m'\"$*\"'\\e[m'; } BgreyF () { printf '\\e[5;47m'\"$*\"'\\e[m'; } ; BgreyI () { printf '\\e[7;37m'\"$*\"'\\e[m'; } BwhiteF () { printf '\\e[5;47m'\"$*\"'\\e[m'; } ; BwhiteI () { printf '\\e[7;37m'\"$*\"'\\e[m'; } ## ∞∞∞∞∞∞ Invisible Text on Color Background ∞∞∞∞∞∞ ## ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ Color Code Notes ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ## BblackV () { printf '\\e[8;40m'\"$*\"'\\e[m'; } ## Unless I missed something or made a mistake, I ## BredV () { printf '\\e[8;41m'\"$*\"'\\e[m'; } ## calculate a total of 7681 different color codes, ## BgreenV () { printf '\\e[8;42m'\"$*\"'\\e[m'; } ## none of which produce a duplicate result. ## BbrownV () { printf '\\e[8;43m'\"$*\"'\\e[m'; } ## These will be fine for now. ## ByellowV () { printf '\\e[8;43m'\"$*\"'\\e[m'; } BblueV () { printf '\\e[8;44m'\"$*\"'\\e[m'; } BmagentaV () { printf '\\e[8;45m'\"$*\"'\\e[m'; } BpurpleV () { printf '\\e[8;45m'\"$*\"'\\e[m'; } BaquaV () { printf '\\e[8;46m'\"$*\"'\\e[m'; } BcyanV () { printf '\\e[8;46m'\"$*\"'\\e[m'; } BgreyV () { printf '\\e[8;47m'\"$*\"'\\e[m'; } BwhiteV () { printf '\\e[8;47m'\"$*\"'\\e[m'; } ## ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ## % \\ printf \"$(Tblue \"%%s\")\\n\" 'hi' Tblue \"%s\\n\" 'hi' printf \"$(Tblue \"%s\" 'hi')\\n\" printf \"hi $(Tred there) man $(BaquaI \"%c\" '!') $(Bold 'This \\\\t is %%s') %s\\n\" \"$(BgreenB 'super')\" \"$(Bblue mega Colorful)\" echo \"hi $(Tred there) man $(BaquaI \"%c\" '!') $(Bold 'This \\\\t is %s' \"$(BblackB 'super')\") $(Bblue mega Colorful)\" printf \"\\t%s Volume \\\"%s\\\" is not connected.\\n\" \"$(TwhiteB [)$(TredB Error)$(TwhiteB \\]:)\" \"$(Tbrown $Volume)\" eval \"echo 'This is OSX' | sed 's:OSX:$(Invert [)$(TaquaF OSX)$(Invert ]):'\" find . -exec stat -f \"Name: $(Tbrown %%N)%t%t$(Tpurple \"->\")%tPermissions: $(Tgreen %%Sp)\" {} \\;"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10407/"
] |
342,100 | <p>I have a Guid.NewGuid() call that is creating an Empty Guid. </p>
<p>What would cause such a problem and how can I fix it?</p>
<p><b>Edit:</b> The code:<br /></p>
<pre><code><WebMethod()> _
Public Function CreateRow(rowValue As String) as String
Dim rowPointer As Guid = System.Guid.NewGuid()
Dim rowPointerValue As String = rowPointer.ToString()
Try
Dim result as Integer = SqlHelper.ExecuteNonQuery(ConnectionString, "Sproc_Name", rowValue, rowPointer)
Return result
Catch ex as Exception
Throw ex
End Try
End Function
</code></pre>
<p><strong>Edit:</strong> Turns out that rowPointer was originally being passed to the SqlHelper and not rowPointerValue - This of course is passed as empty, as pointed out in the answers. Changing it to rowPointerValue/rowPointer.ToString() fixed the problem.</p>
| [
{
"answer_id": 993192,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Dim g As New Guid();\n\nDim whereDoYouWantToSeeIt As String = g.ToString();\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33226/"
] |
342,101 | <p>ok, ive a class and i pass an object as property.</p>
<p>the object that i pass is a <code>List<X></code></p>
<p>in my class im trying to access the Object index by reflection BUT I CAN'T!!! </p>
<p>Example:</p>
<p>this class works i just wrote down the part i want to show you and i need help.</p>
<pre><code>class MyClass
{
private object _recordSet;
public object RecordSet
{
get { return _recordSet; }
set { _recordSet = value; }
}
public string Draw()
{
system.reflection.Assembly asem = system.reflection.Assembly.getAssembly(_dataSource.GetType());
object instance;
instance = asem.CreateInstance(_dataSource.GetType().UnderlyingSystemType.FullName);
//to access de Count of my List
int recordcount = int.Parse(_dataSource.GetType().GetProperty("Count").GetValue(_dataSource,null));
//i need to do a
for(int cont = 0; cont < recordCount; cont++)
{
_dataSource[cont].Name; // <-- THIS PART IS NOT WORKING!!! because i cant access the Index Directly.... WHAT TO DO!! ???
}
}
}
</code></pre>
| [
{
"answer_id": 342114,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "object IList IList list = (IList)actualList;\nobject foo = list[17];\n Count int.Parse Count int"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,103 | <p>I have an SSRS report
where the date should be grouped by project category
the project code in the category is repeating in side the group how do I suppress the value</p>
<p>Please help me to get an idea.</p>
<p>Thanks,brijit</p>
| [
{
"answer_id": 10850941,
"author": "H B",
"author_id": 521443,
"author_profile": "https://Stackoverflow.com/users/521443",
"pm_score": 3,
"selected": false,
"text": "=Fields!ProductCode.Value = Previous(Fields!ProductCode.Value)\n"
},
{
"answer_id": 28763270,
"author": "NickyP",
"author_id": 4614213,
"author_profile": "https://Stackoverflow.com/users/4614213",
"pm_score": 1,
"selected": false,
"text": "=IIf(Fields!ProductCode.Value = Previous(Fields!ProductCode.Value), \"White\", \"Black\")\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,116 | <p>I have a Viewbox with <code>Stretch=Uniform</code> in order to not distort the content.
However, when the frame window is wider or taller than the content, the Viewbox content is always centered.</p>
<p>I cannot seem to find any content alignment options on the Viewbox.
Is there a way to do this?</p>
| [
{
"answer_id": 342548,
"author": "John Z",
"author_id": 43430,
"author_profile": "https://Stackoverflow.com/users/43430",
"pm_score": 5,
"selected": true,
"text": "VerticalAlignment=\"Top\" HorizontalAlignment=\"Left\" <Grid>\n <Viewbox VerticalAlignment=\"Top\" HorizontalAlignment=\"Left\">\n ...\n </Viewbox>\n</Grid>\n Stretch=\"UniformToFill\""
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25879/"
] |
342,119 | <p>I'm trying to use a generic list as a property of the users profile. I'll admit this is probably just making my life harder than it needs to be but I don't want to change the programming model just because the data store struggles.</p>
<p>I have this in my web.config</p>
<p>
</p>
<pre><code> </providers>
<properties>
.....
<add name="AListProperty" type="System.Collections.Generic.List`1[[System.Int32]]"/>
<add name="AnotherListProperty" type="System.Collections.Generic.List`1[[MyNamespace.Web.UI.MyReallySimpleClass]]">
</properties>
</profile>
</code></pre>
<p>The first property, "AListProperty" works fine. The second one throws a variety of exceptions depending on how I delcare it in the web.config. MyReallySimpleClass is public, serializable and consists of 2 public fields (at present)</p>
<p>So, my questions are
1. Does anyone know where the format for declaring these types in the web.config is documented.
2. What I'm doing wrong? It looks fine, I can't see any semantic difference between the two declarations.</p>
<p>Thanks</p>
| [
{
"answer_id": 342548,
"author": "John Z",
"author_id": 43430,
"author_profile": "https://Stackoverflow.com/users/43430",
"pm_score": 5,
"selected": true,
"text": "VerticalAlignment=\"Top\" HorizontalAlignment=\"Left\" <Grid>\n <Viewbox VerticalAlignment=\"Top\" HorizontalAlignment=\"Left\">\n ...\n </Viewbox>\n</Grid>\n Stretch=\"UniformToFill\""
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42975/"
] |
342,122 | <p>What are the best practices for naming ant targets? </p>
<p>For example, what would you expect the target "test" to run? All unit tests? All functional tests? Both?</p>
<p>What are the standard names used for running different types of tests (unit/functional/all)? Are there standards for target names to deploy software in J2SE? in J2EE?</p>
<p>My project uses ant for a java project with junit, Swing applications, and J2EE applications.</p>
| [
{
"answer_id": 342155,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "test test-integration dbtest test-all test tests"
},
{
"answer_id": 342255,
"author": "Rob Hruska",
"author_id": 29995,
"author_profile": "https://Stackoverflow.com/users/29995",
"pm_score": 2,
"selected": false,
"text": "ant -p"
},
{
"answer_id": 342284,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 1,
"selected": false,
"text": "run\nrunFast\ngetBackground\ngetFinalData\ncompareTo\nsetX\nisEmpty\n run-all-tests build clean test-and-release deploy run-code-coverage-metrics"
},
{
"answer_id": 342967,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 2,
"selected": false,
"text": "ant dist\nant test report\n ant compile create.distribution\nant test.data test.nondata report.junit.generate report .....\n"
},
{
"answer_id": 7527121,
"author": "david",
"author_id": 230825,
"author_profile": "https://Stackoverflow.com/users/230825",
"pm_score": 5,
"selected": true,
"text": "all Build and test everything; create a distribution, optionally install. \nclean Delete all generated files and directories. \ndeploy Deploy the code, usually to a remote server. \ndist Produce the distributables. \ndistclean Clean up the distribution files only. \ndocs Generate all documentation. \ninit Initialize the build: create directories, call <tstamp> and other common actions. \ninstall Perform a local installation. \njavadocs Generate the Javadoc pages. \nprinterdocs Generate printable documents. \ntest Run the unit tests. \nuninstall Remove a local installation. \n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] |
342,131 | <p>Is there a way to get Visual Studio to display strings as verbatim strings (prefixed with '@')? I'd like to easily cut strings containing file paths from Visual Studio into Explorer or other apps.</p>
<p>Clarification: when VS displays a string in the auto, watch, immediate, etc. window, I'd like it to be formatted as as verbatim string so that I can simple copy it for use elsewhere.</p>
| [
{
"answer_id": 342165,
"author": "a_hardin",
"author_id": 1497,
"author_profile": "https://Stackoverflow.com/users/1497",
"pm_score": 0,
"selected": false,
"text": "string s = @\"c:\\my folder\\\";\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43370/"
] |
342,140 | <p>I would like to keep a static counter in a garbage collected class and increment it using Interlocked::Increment. What's the C++/CLI syntax to do this?</p>
<p>I've been trying variations on the following, but no luck so far:</p>
<pre><code>ref class Foo
{
static __int64 _counter;
__int64 Next()
{
return System::Threading::Interlocked::Increment( &_counter );
}
};
</code></pre>
| [
{
"answer_id": 342283,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 4,
"selected": true,
"text": "_int64 ref class Bar\n{\n static __int64 _counter;\n\n __int64 Next()\n {\n __int64 %trackRefCounter = _counter;\n return System::Threading::Interlocked::Increment(trackRefCounter);\n }\n};\n"
},
{
"answer_id": 6738677,
"author": "Ben Voigt",
"author_id": 103167,
"author_profile": "https://Stackoverflow.com/users/103167",
"pm_score": 2,
"selected": false,
"text": "return System::Threading::Interlocked::Increment( _counter );\n InterlockedIncrement64 #include <windows.h> return ::InterlockedIncrement64(&_counter);\n"
},
{
"answer_id": 38909969,
"author": "Glenn Slayden",
"author_id": 147511,
"author_profile": "https://Stackoverflow.com/users/147511",
"pm_score": 0,
"selected": false,
"text": "InterlockedExchangePointer InterlockedXor64 C++/CLI Interlocked::* pin_ptr int i1 = 1, i2 = 2;\n\nint *pi1 = &i1, *pi2 = &i2, *pi3;\n\npi3 = (int*)Interlocked::Exchange((IntPtr%)pi1, IntPtr(pi2)).ToPointer();\n & pi1 ** &"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] |
342,151 | <p>I'm trying to perform a once-through read of a large file (~4GB) using Java 5.0 x64 (on Windows XP).</p>
<p>Initially the file read rate is very fast, but gradually the throughput slows down substantially, and my machine seems very unresponsive as time goes on.</p>
<p>I've used ProcessExplorer to monitor the File I/O statistics, and it looks like the process initially reads 500MB/sec, but this rate gradually drops to around 20MB/sec.</p>
<p>Any ideas on the the best way to maintain File I/O rates, especially with reading large files using Java?</p>
<p>Here's some test code that shows the "interval time" continuing to increase. Just pass Main a file that's at least 500MB.</p>
<pre><code>import java.io.File;
import java.io.RandomAccessFile;
public class MultiFileReader {
public static void main(String[] args) throws Exception {
MultiFileReader mfr = new MultiFileReader();
mfr.go(new File(args[0]));
}
public void go(final File file) throws Exception {
RandomAccessFile raf = new RandomAccessFile(file, "r");
long fileLength = raf.length();
System.out.println("fileLen: " + fileLength);
raf.close();
long startTime = System.currentTimeMillis();
doChunk(0, file, 0, fileLength);
System.out.println((System.currentTimeMillis() - startTime) + " ms");
}
public void doChunk(int threadNum, File file, long start, long end) throws Exception {
System.out.println("Starting partition " + start + " to " + end);
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(start);
long cur = start;
byte buf[] = new byte[1000];
int lastPercentPrinted = 0;
long intervalStartTime = System.currentTimeMillis();
while (true) {
int numRead = raf.read(buf);
if (numRead == -1) {
break;
}
cur += numRead;
if (cur >= end) {
break;
}
int percentDone = (int)(100.0 * (cur - start) / (end - start));
if (percentDone % 5 == 0) {
if (lastPercentPrinted != percentDone) {
lastPercentPrinted = percentDone;
System.out.println("Thread" + threadNum + " Percent done: " + percentDone + " Interval time: " + (System.currentTimeMillis() - intervalStartTime));
intervalStartTime = System.currentTimeMillis();
}
}
}
raf.close();
}
}
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 344054,
"author": "kohlerm",
"author_id": 26056,
"author_profile": "https://Stackoverflow.com/users/26056",
"pm_score": 0,
"selected": false,
"text": " // read from the file with buffering\n // and with direct access to the buffer\n\n MyTimer mt = new MyTimer();\n FileInputStream fis = \n new FileInputStream(TESTFILE);\n cnt3 = 0;\n final int BUFSIZE = 1024;\n byte buf[] = new byte[BUFSIZE];\n int len;\n while ((len = fis.read(buf)) != -1) {\n for (int i = 0; i < len; i++) {\n if (buf[i] == 'A') {\n cnt3++;\n }\n }\n }\n fis.close();\n System.out.println(\"read3 time = \" \n + mt.getElapsed());\n }\n"
},
{
"answer_id": 344154,
"author": "Ville Krumlinde",
"author_id": 43673,
"author_profile": "https://Stackoverflow.com/users/43673",
"pm_score": 1,
"selected": false,
"text": "public class MultiFileReader {\n\n private byte buf[] = new byte[256*1024];\n\n ...\n\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,152 | <p>I was working with a new C++ developer a while back when he asked the question: "Why can't variable names start with numbers?"</p>
<p>I couldn't come up with an answer except that some numbers can have text in them (123456L, 123456U) and that wouldn't be possible if the compilers were thinking everything with some amount of alpha characters was a variable name.</p>
<p>Was that the right answer? Are there any more reasons?</p>
<pre><code>string 2BeOrNot2Be = "that is the question"; // Why won't this compile?
</code></pre>
| [
{
"answer_id": 342176,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 7,
"selected": false,
"text": "int 2d = 42;\ndouble a = 2d;\n"
},
{
"answer_id": 342192,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 8,
"selected": true,
"text": "int 17 = 497;\nint 42 = 6 * 9;\nString 1111 = \"Totally text\";\n"
},
{
"answer_id": 5793730,
"author": "Roy Dictus",
"author_id": 651188,
"author_profile": "https://Stackoverflow.com/users/651188",
"pm_score": 6,
"selected": false,
"text": "10 V1=100\n20 PRINT V1\n 10V1=100\n20PRINTV1\n 101V=100\n 10 1V = 100\n 101 V = 100\n 1 01V = 100\n"
},
{
"answer_id": 14309691,
"author": "sbagdat",
"author_id": 518235,
"author_profile": "https://Stackoverflow.com/users/518235",
"pm_score": 3,
"selected": false,
"text": "int a = 2;\nint 2 = 5;\nint c = 2 * a; \n float 5 = 25;\nfloat b = 5.5;\n"
},
{
"answer_id": 26338723,
"author": "Jiayang",
"author_id": 3686410,
"author_profile": "https://Stackoverflow.com/users/3686410",
"pm_score": 6,
"selected": false,
"text": "Apple;\n 123apple;\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34183/"
] |
342,167 | <p>The function below is logging the "0", "z" and the "1" ok... but its not capturing the "Z" (shift-z)... any help would be appreciated...</p>
<pre><code>__declspec(dllexport)
LRESULT CALLBACK HookProc (UINT nCode, WPARAM wParam, LPARAM lParam)
{
if ((nCode == HC_ACTION) && (wParam == WM_KEYUP))
{
// This Struct gets infos on typed key
KBDLLHOOKSTRUCT hookstruct = *((KBDLLHOOKSTRUCT*)lParam);
// Bytes written counter for WriteFile()
DWORD Counter;
wchar_t Logger[1];
switch (hookstruct.vkCode)
{
case 060: Logger[0] = L'0'; break;
case 061: Logger[0] = L'1'; break;
case 90: Logger[0] = L'z'; break;
case 116: Logger[0] = L'Z'; break;
}
// Opening of a logfile. Creating it if it does not exists
HANDLE hFile = CreateFile(L"C:\\logfile.txt", GENERIC_WRITE,
FILE_SHARE_READ, NULL,OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// put the file pointer to the end
SetFilePointer(hFile,NULL,NULL,FILE_END);
// Write the hFile typed in logfile
WriteFile(hFile,&Logger,sizeof(Logger),&Counter,NULL);
//WriteFile(hFile,&hookstruct.vkCode,sizeof(hookstruct.vkCode),&Counter,NULL);
// Close the file
CloseHandle(hFile);
}
}
</code></pre>
| [
{
"answer_id": 342213,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 3,
"selected": false,
"text": " case 90:\n if(GetKeyState(VK_LSHIFT|VK_RSHIFT)\n Logger[0] = L'Z'; break;\n else\n Logger[0] = L'z'; break;\n"
},
{
"answer_id": 342260,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 5,
"selected": true,
"text": "GetAsyncKeyState GetKeyState"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37109/"
] |
342,171 | <p>I have a MFC dialog with 32 CComboBoxes on it that all have the same data in the listbox. Its taking a while to come up, and it looks like part of the delay is the time I need to spend using InsertString() to add all the data to the 32 controls. How can I subclass CComboBox so that the 32 instances share the same data?</p>
| [
{
"answer_id": 342372,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 2,
"selected": true,
"text": "m_wndCombo.SetRedraw(FALSE);\n// Fill combo here\n...\nm_wndCombo.SetRedraw(TRUE);\nm_wndCombo.Invalidate();\n"
},
{
"answer_id": 342373,
"author": "grepsedawk",
"author_id": 14388,
"author_profile": "https://Stackoverflow.com/users/14388",
"pm_score": 0,
"selected": false,
"text": "\n// Initialize the storage of the combo box to be 256 strings with\n// about 10 characters per string, performance improvement. \n\n int n = pmyComboBox->InitStorage(256, 10);\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701/"
] |
342,181 | <p>My application allows the user to enter a numeric value (currency) in a <code>UITextField</code> control, but the keyboard layout that I wish was available is unfortunately not one of the built-in options, so I had to choose the "Numbers & Punctuation" option in Interface Builder. Here's the corresponding dialog window in IB:</p>
<p><a href="https://i.stack.imgur.com/FbnvH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FbnvH.png" alt="enter image description here"></a></p>
<p>So when my application asks the user for the input, it is displaying the following:</p>
<p><a href="https://i.stack.imgur.com/u9tbB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u9tbB.png" alt="enter image description here"></a></p>
<p>Which is perfectly fine, but look at all of the extra keys available to the user! One could easily enter "12;56!" in the text field, and I assume I have to validate that somehow.</p>
<p>So my question is: how do I validate currency values entered into a <code>UITextField</code>?</p>
| [
{
"answer_id": 342231,
"author": "Marc Novakowski",
"author_id": 27020,
"author_profile": "https://Stackoverflow.com/users/27020",
"pm_score": 4,
"selected": true,
"text": "UITextFieldDelegate textField:shouldChangeCharactersInRange:replacementString:"
},
{
"answer_id": 342390,
"author": "Matt Gallagher",
"author_id": 36103,
"author_profile": "https://Stackoverflow.com/users/36103",
"pm_score": 3,
"selected": false,
"text": "textField:shouldChangeCharactersInRange:replacementString: NSNumberFormatter NSNumberFormatterCurrencyStyle"
},
{
"answer_id": 1018203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "\n- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string\n{\n NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@\"0123456789.\"] invertedSet];\n\nreturn ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);\n\n\n}\n return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);\n"
},
{
"answer_id": 3644053,
"author": "Gamma-Point",
"author_id": 275047,
"author_profile": "https://Stackoverflow.com/users/275047",
"pm_score": 0,
"selected": false,
"text": " -(BOOL) isPositiveNumber: (NSString *) numberString {\n\n NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];\n [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];\n\n NSNumber *aNumber = [numberFormatter numberFromString:numberString];\n [numberFormatter release];\n\n if ([aNumber floatValue] > 0) {\n NSLog( @\"Found positive number %4.2f\",[aNumber floatValue] );\n\n return YES;\n }\n else {\n return NO;\n }\n}\n"
},
{
"answer_id": 4850969,
"author": "Matthias Bauch",
"author_id": 457406,
"author_profile": "https://Stackoverflow.com/users/457406",
"pm_score": 5,
"selected": false,
"text": ", - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {\n static NSString *numbers = @\"0123456789\";\n static NSString *numbersPeriod = @\"01234567890.\";\n static NSString *numbersComma = @\"0123456789,\";\n\n //NSLog(@\"%d %d %@\", range.location, range.length, string);\n if (range.length > 0 && [string length] == 0) {\n // enable delete\n return YES;\n }\n\n NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];\n if (range.location == 0 && [string isEqualToString:symbol]) {\n // decimalseparator should not be first\n return NO;\n }\n NSCharacterSet *characterSet;\n NSRange separatorRange = [textField.text rangeOfString:symbol];\n if (separatorRange.location == NSNotFound) {\n if ([symbol isEqualToString:@\".\"]) {\n characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersPeriod] invertedSet];\n }\n else {\n characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersComma] invertedSet]; \n }\n }\n else {\n // allow 2 characters after the decimal separator\n if (range.location > (separatorRange.location + 2)) {\n return NO;\n }\n characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbers] invertedSet]; \n }\n return ([[string stringByTrimmingCharactersInSet:characterSet] length] > 0);\n}\n"
},
{
"answer_id": 4953792,
"author": "Ben Golding",
"author_id": 591690,
"author_profile": "https://Stackoverflow.com/users/591690",
"pm_score": 3,
"selected": false,
"text": "- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string\n{\n if ([string length] < 1) // non-visible characters are okay\n return YES;\n if ([string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]].length == 0)\n return YES;\n return ([string stringByTrimmingCharactersInSet:[self.characterSet invertedSet]].length > 0);\n}\n - (NSCharacterSet *)createCurrencyCharacterSet\n{\n NSLocale *locale = [NSLocale currentLocale];\n NSMutableCharacterSet *currencySet = [NSMutableCharacterSet decimalDigitCharacterSet];\n\n [currencySet addCharactersInString:@\"-\"]; // negative symbol, can't find a localised version\n [currencySet addCharactersInString:[locale objectForKey:NSLocaleCurrencySymbol]];\n [currencySet addCharactersInString:[locale objectForKey:NSLocaleGroupingSeparator]];\n [currencySet addCharactersInString:[locale objectForKey:NSLocaleDecimalSeparator]];\n\n return [[currencySet copy] autorelease];\n}\n [[currencySet copy] autorelease] [NSCharacterSet decimalDigitCharacterSet]"
},
{
"answer_id": 5970349,
"author": "Thomas Tempelmann",
"author_id": 43615,
"author_profile": "https://Stackoverflow.com/users/43615",
"pm_score": 3,
"selected": false,
"text": "NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];\n"
},
{
"answer_id": 7856809,
"author": "Brian L",
"author_id": 357019,
"author_profile": "https://Stackoverflow.com/users/357019",
"pm_score": 2,
"selected": false,
"text": "- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { \n\n NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];\n\n [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];\n [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];\n [numberFormatter setMaximumFractionDigits:2];\n [numberFormatter setMinimumFractionDigits:0];\n\n // Grab the contents of the text field\n NSString *text = [textField text]; \n\n // the appropriate decimalSeperator and currencySymbol for the current locale\n // can be found with help of the\n // NSNumberFormatter and NSLocale classes.\n NSString *decimalSeperator = numberFormatter.decimalSeparator; \n NSString *currencySymbol = numberFormatter.currencySymbol;\n\n NSString *replacementText = [text stringByReplacingCharactersInRange:range withString:string];\n NSMutableString *newReplacement = [[ NSMutableString alloc ] initWithString:replacementText];\n\n // whenever a decimalSeperator or currencySymobol is entered, we'll just update the textField.\n // whenever other chars are entered, we'll calculate the new number and update the textField accordingly.\n // If the number can't be computed, we ignore the new input.\n NSRange decimalRange = [text rangeOfString:decimalSeperator];\n if ([string isEqualToString:decimalSeperator] == YES && \n [text rangeOfString:decimalSeperator].length == 0) {\n [textField setText:newReplacement];\n } else if([string isEqualToString:currencySymbol] == YES&& \n [text rangeOfString:currencySymbol].length == 0) {\n [textField setText:newReplacement]; \n } else if([newReplacement isEqualToString:currencySymbol] == YES) {\n return YES;\n }else {\n\n NSString *currencyGroupingSeparator = numberFormatter.currencyGroupingSeparator;\n\n [newReplacement replaceOccurrencesOfString:currencyGroupingSeparator withString:@\"\" options:NSBackwardsSearch range:NSMakeRange(0, [newReplacement length])]; \n [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];\n\n NSNumber *number = [numberFormatter numberFromString:newReplacement];\n\n if([newReplacement length] == 1) {\n [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];\n number = [numberFormatter numberFromString:newReplacement];\n }\n\n if (number == nil) { \n [newReplacement release];\n return NO;\n }\n [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; \n text = [numberFormatter stringFromNumber:number];\n [textField setText:text]; \n }\n\n [newReplacement release];\n\n return NO; // we return NO because we have manually edited the textField contents.\n}\n"
},
{
"answer_id": 8891750,
"author": "supp-f",
"author_id": 1153470,
"author_profile": "https://Stackoverflow.com/users/1153470",
"pm_score": 1,
"selected": false,
"text": "- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {\n\n NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];\n\n //if there is empty string return YES\n if([proposedString length] == 0) {\n return YES;\n }\n\n //create inverted set for appripriate symbols\n NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@\"0123456789.,\"] invertedSet];\n\n //if side symbols is trimmed by nonNumberSet - return NO\n if([proposedString stringByTrimmingCharactersInSet:nonNumberSet].length != [proposedString length]) {\n return NO;\n }\n\n //if there is more than 1 symbol of '.' or ',' return NO\n if([[proposedString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@\".,\"]] count] > 2) {\n return NO;\n }\n\n //finally check is ok, return YES\n return YES;\n}\n"
},
{
"answer_id": 12293138,
"author": "drewish",
"author_id": 203673,
"author_profile": "https://Stackoverflow.com/users/203673",
"pm_score": 3,
"selected": false,
"text": " formatter = [NSNumberFormatter new];\n [formatter setNumberStyle: NSNumberFormatterCurrencyStyle];\n [formatter setLenient:YES];\n [formatter setGeneratesDecimalNumbers:YES];\n -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string\n{\n NSString *replaced = [textField.text stringByReplacingCharactersInRange:range withString:string];\n NSDecimalNumber *amount = (NSDecimalNumber*) [formatter numberFromString:replaced];\n if (amount == nil) {\n // Something screwed up the parsing. Probably an alpha character.\n return NO;\n }\n // If the field is empty (the initial case) the number should be shifted to\n // start in the right most decimal place.\n short powerOf10 = 0;\n if ([textField.text isEqualToString:@\"\"]) {\n powerOf10 = -formatter.maximumFractionDigits;\n }\n // If the edit point is to the right of the decimal point we need to do\n // some shifting.\n else if (range.location + formatter.maximumFractionDigits >= textField.text.length) {\n // If there's a range of text selected, it'll delete part of the number\n // so shift it back to the right.\n if (range.length) {\n powerOf10 = -range.length;\n }\n // Otherwise they're adding this many characters so shift left.\n else {\n powerOf10 = [string length];\n }\n }\n amount = [amount decimalNumberByMultiplyingByPowerOf10:powerOf10];\n\n // Replace the value and then cancel this change.\n textField.text = [formatter stringFromNumber:amount];\n return NO;\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35478/"
] |
342,189 | <p>I've written a fairly simple java application that allows you to drag your mouse and based on the length of the mouse drag you did, it will shoot a ball in that direction, bouncing off walls as it goes.</p>
<p>Here is a quick screenshot:<br>
<a href="http://img222.imageshack.us/img222/3179/ballbouncemf9.png">alt text http://img222.imageshack.us/img222/3179/ballbouncemf9.png</a></p>
<p>Each one of the circles on the screen is a Ball object. The balls movement is broken down into an x and y vector;</p>
<pre><code>public class Ball {
public int xPos;
public int yPos;
public int xVector;
public int yVector;
public Ball(int xPos, int yPos, int xVector, int yVector) {
this.xPos = xPos;
this.yPos = yPos;
this.xVector = xVector;
this.yVector = yVector;
}
public void step()
{
posX += xVector;
posY += yVector;
checkCollisions();
}
public void checkCollisions()
{
// Check if we have collided with a wall
// If we have, take the negative of the appropriate vector
// Depending on which wall you hit
}
public void draw()
{
// draw our circle at it's position
}
}
</code></pre>
<p>This works great. All the balls bounce around and around from wall to wall. </p>
<p>However, I have decided that I want to be able to include the effects of gravity. I know that objects accelerate toward the earth at 9.8m/s but I don't directly know how this should translate into code. I realize that the yVector will be affected but my experimentation with this didn't have the desired effect I wanted.</p>
<p>Ideally, <strong><em>I would like to be able to add some gravity effect to this program and also allow the balls to bounce a few times before settling to the "ground."</em></strong> </p>
<p>How can I create this bouncing-elastic, gravity effect? How must I manipulate the speed vectors of the ball on each step? What must be done when it hits the "ground" so that I can allow it to bounce up again, but somewhat shorter then the previous time?</p>
<p>Any help is appreciated in pointing me in the right direction.</p>
<hr>
<p>Thanks you for the comments everyone! It already is working great!</p>
<p>In my step() I am adding a gravity constant to my yVector like people suggested and this is my checkCollision():</p>
<pre><code>public void checkCollision()
{
if (posX - radius < 0) // Left Wall?
{
posX = radius; // Place ball against edge
xVector = -(xVector * friction);
}
else if (posX + radius > rightBound) // Right Wall?
{
posX = rightBound - radius; // Place ball against edge
xVector = -(xVector * friction);
}
// Same for posY and yVector here.
}
</code></pre>
<p>However, the balls will continue to slide around/roll on the floor. I assume this is because I am simply taking a percentage (90%) of their vectors each bounce and it is never truly zero. Should I add in a check that if the xVector becomes a certain absolute value I should just change it to zero?</p>
| [
{
"answer_id": 342233,
"author": "torb",
"author_id": 42986,
"author_profile": "https://Stackoverflow.com/users/42986",
"pm_score": 1,
"selected": false,
"text": "public void step()\n{\n posX += xVector;\n posY += yVector;\n\n yVector += g //some constant representing 9.8\n\n checkCollisions();\n}\n"
},
{
"answer_id": 342238,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 0,
"selected": false,
"text": "yVector *= 0.95;\nxVector *= 0.95;\nyVector -= 2.0;\n"
},
{
"answer_id": 342347,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 0,
"selected": false,
"text": " this.xVector = -this.xVector;\n this.yVector = -this.yVector;\n double loss_factor = 0.99;\n this.xVector = -(loss_factor * this.xVector);\n this.yVector = -(loss_factor * this.yVector;\n"
},
{
"answer_id": 4357479,
"author": "Giuliano",
"author_id": 502717,
"author_profile": "https://Stackoverflow.com/users/502717",
"pm_score": 1,
"selected": false,
"text": "y = y0 + v0 * t + (0.5)*a*t^2\n float speed = 10.0f, acceleration = -9.8f, y = [whatever position];\n\ny += speed*t + 0.5f*acceleration*t^2;\n v = sqrt(v0^2 + 2*acceleration*(y-y0));\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,218 | <p>What techniques are available for sending an email via a webpage or a form on a webpage? </p>
<p>I've got some background idea that you POST the form data to a script but I've don't really know what a cgi script is (I'd love to learn if this is the suggested method!) or what the current practice is.</p>
<p>This is just to provide some way for users to contact the operators. The in-page form seems like it would be easier on the user than ask them to open their mail client. I was also concerned about bots harvesting the contact email address (in the case of mailto: links).</p>
| [
{
"answer_id": 342240,
"author": "Matt Howell",
"author_id": 2321,
"author_profile": "https://Stackoverflow.com/users/2321",
"pm_score": 0,
"selected": false,
"text": "<a href=\"mailto:someperson@someaddress.com\">Please spam me, kthx</a>\n"
},
{
"answer_id": 343578,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 3,
"selected": true,
"text": "$_POST <input name=\"\"> // <form action=\"mailer.php\">[..]<input name=\"subject\" [..]><input name=\"content\" [..]></form>\necho(\"The subject is: \". $_POST['subject']);\necho(\"The content is:\" . $_POST['content']);\n mail() mail($to, $subject, $message);\n $to $subject $message $_POST[] mail(\"me@example.com\", $_POST['subject'], $_POST['content']); <textarea>"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40443/"
] |
342,219 | <p>I am trying to select a record out of the table1 by joining table2 and using table2 columns in the WHERE statement. Col1 and Col2 in table1 can be stored in col1 of table2. I need to join col1 of table2 with either the value of col1 or col2 in table1</p>
<p>here is the sql statement I created so (pseudo):</p>
<pre><code>SELECT
t1.Col1,
t1.Col2,
t1.Col3,
t1.Col4
FROM
table1 t1
JOIN table2 t2 on t2.Col1 = t1.Col1 or t2.Col1 = t1.Col2
</code></pre>
<p>What would be the best way to approach this?</p>
| [
{
"answer_id": 342241,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "... JOIN table2 t2 on t2.Col1 IN (t1.Col1, t1.Col2)\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
342,250 | <p>I need to read the value of a property from a file in an Ant script and strip off the first few characters. The property in question is</p>
<pre><code>path=file:C:/tmp/templates
</code></pre>
<p>This property is store in a file that I can access within the ant script via</p>
<pre><code><property file="${web.inf.dir}/config.properties"/>
</code></pre>
<p>I have two questions:</p>
<ol>
<li>How do I read the single 'path' property from the loaded property file?</li>
<li>How do I remove the leading 'file:' from the property value?</li>
</ol>
<p>Ultimately, I'd like to have access to the following name-value pair within the Ant script:</p>
<pre><code>path=C:/tmp/templates
</code></pre>
<p>Cheers,
Don</p>
| [
{
"answer_id": 342288,
"author": "Rob Hruska",
"author_id": 29995,
"author_profile": "https://Stackoverflow.com/users/29995",
"pm_score": 0,
"selected": false,
"text": "<target name=\"foo\">\n <property name=\"my.property\" value=\"file:C:/foo/bar\"/>\n <exec executable=\"/bin/cut\" inputstring=\"${my.property}\" outputproperty=\"new.property\">\n <arg line=\"-d':' -f2-\"/>\n </exec>\n <echo message=\"FOO: ${new.property}\"/>\n</target>\n"
},
{
"answer_id": 342412,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "LoadProperties FilterChain <loadproperties srcFile=\"${property.file.name}\">\n <filterchain>\n <tokenfilter>\n <containsstring contains=\"path=file:\"/>\n <replaceregex pattern=\"path=file:\" replace=\"path=\" flags=\"\"/>\n </tokenfilter>\n </filterchain>\n</loadproperties>\n path"
},
{
"answer_id": 1471772,
"author": "Brian Kelly",
"author_id": 8252,
"author_profile": "https://Stackoverflow.com/users/8252",
"pm_score": 2,
"selected": false,
"text": "path=C:/tmp/templates\nfullpath=file:${path}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
342,263 | <p>When I try to run the following code (from the REPL) in Clojure:</p>
<pre><code>(dotimes [i 5]
(.start
(Thread.
(fn []
(Thread/sleep (rand 1000))
(println (format "Finished %d on %s" i (Thread/currentThread)))))))
</code></pre>
<p>I get the following error:</p>
<pre><code>java.lang.Exception: Unable to resolve symbol: i in this context
clojure.lang.Compiler$CompilerException: NO_SOURCE_FILE:6: Unable to resolve symbol: i in this context
at clojure.lang.Compiler.analyze(Compiler.java:3713)
</code></pre>
<p>What am I doing wrong here?</p>
| [
{
"answer_id": 342454,
"author": "Brian Carper",
"author_id": 23070,
"author_profile": "https://Stackoverflow.com/users/23070",
"pm_score": 4,
"selected": true,
"text": "user> (dotimes [i 5] (.start (Thread. (fn [] (Thread/sleep (rand 1000)) (println (format \"Finished %d on %s\" i (Thread/currentThread)))))))\n\nFinished 0 on Thread[Thread-16,5,main]\nFinished 4 on Thread[Thread-20,5,main]\nFinished 3 on Thread[Thread-19,5,main]\nFinished 1 on Thread[Thread-17,5,main]\nFinished 2 on Thread[Thread-18,5,main]\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
] |
342,268 | <p>I am using the following method to browse for a file:</p>
<pre><code> OpenFileDialog.ShowDialog()
PictureNameTextEdit.Text = OpenFileDialog.FileName
</code></pre>
<p>Is there a way get ONLY the file name?</p>
<p>The <strong>FileName</strong> method returns the entire path and file name.</p>
<p>i.e. I want Foo.txt instead of C:\SomeDirectory\Foo.txt</p>
| [
{
"answer_id": 342272,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "Path.GetFileName(fullPath) OpenFileDialog.ShowDialog()\nPictureNameTextEdit.Text = System.IO.Path.GetFileName(OpenFileDialog.FileName)\n"
},
{
"answer_id": 1136501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "//Following code return file name only \n\nstring[] FileFullPath;\nstring FileName;\nobjOpenFileDialog.Title = \"Select Center Logo\";\nobjOpenFileDialog.ShowDialog();\n\nFileFullPath = objOpenFileDialog.FileNames[0].ToString().Split('\\\\');\nFileName = FileFullPath[FileFullPath.Length - 1]; //return only File Name\n\n//Use following code if u want save other folder , \n// following code save file to CenterLogo folder which inside bin folder//\n\nSystem.IO.File.Copy(OFD.FileName, Application.StartupPath + \n\"/CenterLogo/\" + FileName, true);\n"
},
{
"answer_id": 11199729,
"author": "Jayanthi Murugesan",
"author_id": 1481455,
"author_profile": "https://Stackoverflow.com/users/1481455",
"pm_score": 2,
"selected": false,
"text": "OpenFileDialog.ShowDialog()\nPictureNameTextEdit.Text = System.IO.Path.GetFileName(OpenFileDialog.FileName)\n"
},
{
"answer_id": 11422252,
"author": "MAM",
"author_id": 1516077,
"author_profile": "https://Stackoverflow.com/users/1516077",
"pm_score": 0,
"selected": false,
"text": "MsgBox(System.IO.Path.GetExtension(Opendlg.FileName))\n MsgBox(System.IO.Path.GetFileNameWithoutExtension(Opendlg.FileName))\n"
},
{
"answer_id": 33652949,
"author": "Rzgar",
"author_id": 5550996,
"author_profile": "https://Stackoverflow.com/users/5550996",
"pm_score": -1,
"selected": false,
"text": "OpenFileDialog.ShowDialog()\nPictureNameTextEdit.Text = OpenFileDialog.SafeFileName\n"
},
{
"answer_id": 43917431,
"author": "farzaneh",
"author_id": 7997878,
"author_profile": "https://Stackoverflow.com/users/7997878",
"pm_score": 1,
"selected": false,
"text": "textBox1->Text = OpenFileDialog1->FileName; //complete path\ntextBox1->Text = System::IO::Path::GetFileName(OpenFileDialog1->FileName); //filename"
},
{
"answer_id": 44956871,
"author": "Aladein",
"author_id": 6919022,
"author_profile": "https://Stackoverflow.com/users/6919022",
"pm_score": 0,
"selected": false,
"text": "Imports System.IO\n\n\nPictureNameTextEdit.Text = Path.GetFileNameWithoutExtension(OpenFileDialog1.FileName)\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964/"
] |
342,270 | <p>I have a large set of XML files of a propriatary schema -the XML files define binary communication protocol (message structure).</p>
<p>I'd like to leverage Google's protocol buffers technology. </p>
<p>I am using existing code to load the XML files into an object model (in memory).
I'd like to generate a .proto file from that object model. </p>
<p>so basically what I am looking for is code/library (in C#/.NET) that represents the .proto file format as an object model and can save that object model into a .proto file.</p>
<p>I took a look at Jon Skeet's dotnet-protobufs, I think I understand what it does (generate c# code based on .proto files) </p>
<p>However, I didn't figure out if I can use it for my project (it probably has the .proto format object model there, but probably only code that can parse this format and not write it out)</p>
| [
{
"answer_id": 342272,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "Path.GetFileName(fullPath) OpenFileDialog.ShowDialog()\nPictureNameTextEdit.Text = System.IO.Path.GetFileName(OpenFileDialog.FileName)\n"
},
{
"answer_id": 1136501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "//Following code return file name only \n\nstring[] FileFullPath;\nstring FileName;\nobjOpenFileDialog.Title = \"Select Center Logo\";\nobjOpenFileDialog.ShowDialog();\n\nFileFullPath = objOpenFileDialog.FileNames[0].ToString().Split('\\\\');\nFileName = FileFullPath[FileFullPath.Length - 1]; //return only File Name\n\n//Use following code if u want save other folder , \n// following code save file to CenterLogo folder which inside bin folder//\n\nSystem.IO.File.Copy(OFD.FileName, Application.StartupPath + \n\"/CenterLogo/\" + FileName, true);\n"
},
{
"answer_id": 11199729,
"author": "Jayanthi Murugesan",
"author_id": 1481455,
"author_profile": "https://Stackoverflow.com/users/1481455",
"pm_score": 2,
"selected": false,
"text": "OpenFileDialog.ShowDialog()\nPictureNameTextEdit.Text = System.IO.Path.GetFileName(OpenFileDialog.FileName)\n"
},
{
"answer_id": 11422252,
"author": "MAM",
"author_id": 1516077,
"author_profile": "https://Stackoverflow.com/users/1516077",
"pm_score": 0,
"selected": false,
"text": "MsgBox(System.IO.Path.GetExtension(Opendlg.FileName))\n MsgBox(System.IO.Path.GetFileNameWithoutExtension(Opendlg.FileName))\n"
},
{
"answer_id": 33652949,
"author": "Rzgar",
"author_id": 5550996,
"author_profile": "https://Stackoverflow.com/users/5550996",
"pm_score": -1,
"selected": false,
"text": "OpenFileDialog.ShowDialog()\nPictureNameTextEdit.Text = OpenFileDialog.SafeFileName\n"
},
{
"answer_id": 43917431,
"author": "farzaneh",
"author_id": 7997878,
"author_profile": "https://Stackoverflow.com/users/7997878",
"pm_score": 1,
"selected": false,
"text": "textBox1->Text = OpenFileDialog1->FileName; //complete path\ntextBox1->Text = System::IO::Path::GetFileName(OpenFileDialog1->FileName); //filename"
},
{
"answer_id": 44956871,
"author": "Aladein",
"author_id": 6919022,
"author_profile": "https://Stackoverflow.com/users/6919022",
"pm_score": 0,
"selected": false,
"text": "Imports System.IO\n\n\nPictureNameTextEdit.Text = Path.GetFileNameWithoutExtension(OpenFileDialog1.FileName)\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38265/"
] |
342,281 | <p>I have been tasked with creating a program that will generate an amortization schedule. I have only done a bit of research so far, but I need to calculate out payments, interest per payment and principal per payment. Can any one point me in the right direction to figure this out? While I will be writing this in RPG, I am sure others could make use of this algorithm in the future.</p>
<p>(Update) Okay, so how do I calculate based on a 365 day year?</p>
| [
{
"answer_id": 342338,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 3,
"selected": false,
"text": "var balance = 200000; // for example\nvar periods = 360; // 30 years\nvar monthlyRate = (0.065)/12; // 0.065= APR of 6.5% as decimal\nvar monthyPayment = (monthlyRate /(1-(Math.pow((1+monthlyRate),-(periods)))))*balance;\n\nfor (var i=0; i<360; i++) {\n var interestForMonth = balance * monthlyRate;\n var principalForMonth = monthlyPayment - interestForMonth;\n balance -= monthlyPayment; // probably should be -= principalForMonth see comments below\n // output as necessary.\n}\n"
},
{
"answer_id": 404004,
"author": "Mike Wills",
"author_id": 2535,
"author_profile": "https://Stackoverflow.com/users/2535",
"pm_score": 1,
"selected": true,
"text": " H ActGrp(*caller) BndDir('MODULES') DftActGrp(*no)\n //*********************************************************************\n // Program . . . . . AMORT\n //*********************************************************************\n // Printer/Display Files\n FAMORTDF CF E WORKSTN sfile(SFL01:rrn01)\n //*********************************************************************\n // Named Constants\n /copy modules/qcopysrc,statuscopy\n\n // Named Indicators\n D indicatorPtr S * Inz(%Addr(*IN))\n D DS Based(IndicatorPtr)\n /copy modules/qcopysrc,scrncopy\n\n // Subfile Fields\n D rrn01 S 4P 0 inz(0)\n\n //*********************************************************************\n // Misc Fields\n D* Monthly Payment\n D m S 12P 2 \n D* Principal\n D p S 12P 2 \n D* Interest\n D i S 5P 3 \n D* Length (in Years)\n D l S 3P 0 \n D* Monthly Interest\n D j S 10P10 \n D* # of Months\n D n S 5P 0 \n D* Current Monthly Int.\n D h S 12P 2 \n D* Current Principal\n D c S 12P 2 \n D* New Balance\n D q S 12P 2 \n\n //*********************************************************************\n // External Program Procedures\n\n // Internal Subprocedures\n D Init PR\n D Main PR\n D SubfileFilled PR N\n D ClearScreen PR\n D IsValidData PR N\n D LoanPayment PR 12P 2\n D principal 12P 2\n D interest 5P 3\n D loanPeriod 3P 0\n D paymentsYear 3P 0\n\n // External Subprocedures\n ///copy modules/qsrvsrc,p.string\n\n //*********************************************************************\n // Entry Parms\n D AMORT PR extpgm('AMORT')\n D AMORT PI\n //*********************************************************************\n /free\n Init();\n Main();\n\n *inlr = *on;\n /end-free\n\n P*--------------------------------------------------\n P* Procedure name: Init\n P* Purpose:\n P* Returns:\n P*--------------------------------------------------\n P Init B\n D Init PI\n\n /free\n\n pgm = 'AMORT';\n sflDsp = *off;\n\n return;\n\n /end-free\n P Init E\n\n\n P*--------------------------------------------------\n P* Procedure name: Main\n P* Purpose:\n P* Returns:\n P*--------------------------------------------------\n P Main B\n D Main PI\n\n /free\n\n dow (not F3) and (not F12);\n\n write OVR01;\n exfmt CTL01;\n ClearScreen();\n\n if (IsValidData()) and (not F3) and (not F12);\n\n // Fill the header information\n dPayment = LoanPayment(dLoanAmt:dIntRate:dLoanPrd:dPayYear);\n dNumPaymnt = dLoanPrd * dPayYear;\n m = dPayment + dExtraPay;\n p = dLoanAmt;\n q = p;\n\n // Fill the table\n if (SubfileFilled());\n sflDsp = *on;\n endif;\n endif;\n\n enddo;\n\n return;\n\n /end-free\n P Main E\n\n\n P*--------------------------------------------------\n P* Procedure name: SubfileFilled\n P* Purpose: Fill the subfile\n P* Returns:\n P*--------------------------------------------------\n P SubfileFilled B\n D SubfileFilled PI N\n\n D isFilled S N\n D x S 4P 0\n D intCume S 12P 2\n D extraPayCume S 12P 2\n D payDate S D\n D payment S 12P 2\n D extraPayment S 12P 2\n\n /free\n\n isFilled = *on;\n\n sflClear = *on;\n write CTL01;\n sflClear = *off;\n rrn01 = 0;\n x = 0;\n\n // Setup the work fields\n payment = dPayment;\n extraPayment = dExtraPay;\n payDate = dStartDate;\n\n // Create records until there is a zero balance\n dow (q > 0);\n\n x += 1;\n eval(h) h = p * j; // Monthly Interest\n\n // Adjust for final payment\n if (p < m);\n m = p + h;\n payment = p;\n extraPayment = h;\n endif;\n\n // Calulate Principal\n c = m - h;\n // Calulate the new balance\n q = p - c;\n\n // Accumulate the interest and extra payments\n intCume += h;\n extraPayCume += extraPayment;\n\n // Determine the next pay date\n select;\n when dTerms = '1'; //Yearly\n payDate += %years(1);\n when dTerms = '2'; //Semi-Annual\n payDate += %months(6);\n when dTerms = '3'; //Quarterly\n payDate += %months(3);\n when dTerms = '4'; //Monthly\n payDate += %months(1);\n when dTerms = '5'; //Bi-Weekly\n payDate += %days(14);\n endsl;\n\n // Fill the subfile\n sPayNum = x;\n sPayDate = payDate;\n sBegBal = p;\n sSchedPay = payment;\n sExtraPay = extraPayment;\n sTotPay = m;\n sInterest = h;\n sPrincipal = c;\n sEndBal = q;\n sCumeInt = intCume;\n\n // Move the End balance to the beginning balance\n p = q;\n\n rrn01 += 1;\n write SFL01;\n\n enddo;\n\n // Return the calculated information to the header\n dActPaymnt = x;\n dTotInt = intCume;\n dTotEPay = extraPayCume;\n\n if (rrn01 < 1);\n isFilled = *off;\n endif;\n\n return isFilled;\n\n /end-free\n P SubfileFilled E\n\n\n P*--------------------------------------------------\n P* Procedure name: ClearScreen\n P* Purpose:\n P* Returns:\n P*--------------------------------------------------\n P ClearScreen B\n D ClearScreen PI\n\n /free\n\n c = 0;\n h = 0;\n i = 0;\n j = 0;\n l = 0;\n m = 0;\n n = 0;\n p = 0;\n q = 0;\n dPayment = 0;\n dNumPaymnt = 0;\n dActPaymnt = 0;\n dTotEPay = 0;\n dTotInt = 0;\n\n return;\n\n /end-free\n P ClearScreen E\n\n\n P*--------------------------------------------------\n P* Procedure name: IsValidData\n P* Purpose: Validate the data on the screen\n P* Returns: True or False\n P*--------------------------------------------------\n P IsValidData B\n D IsValidData PI N\n\n D isValid S N\n\n /free\n\n if (dLoanAmt <> 0) and (dIntRate <> 0) and (dLoanPrd <> 0) and\n (dPayYear <> 0) and (dStartDate <> %date('0001-01-01'));\n isValid = *on;\n else;\n isValid = *off;\n endif;\n\n return isValid;\n\n /end-free\n P IsValidData E\n\n\n P*--------------------------------------------------\n P* Procedure name: LoanPayment\n P* Purpose: Calculates the payment\n P* Returns:\n P*--------------------------------------------------\n P LoanPayment B\n D LoanPayment PI 12P 2\n D principal 12P 2\n D interest 5P 3\n D loanPeriod 3P 0\n D paymentsYear 3P 0\n\n D retMonthlyPayment...\n D S 12P 2\n\n /free\n\n eval(h) n = loanPeriod * paymentsYear;\n eval(h) j = interest / (paymentsYear * 100);\n\n eval(h) m = principal * (j / (1 - (1 + j) ** -n));\n\n return m;\n\n /end-free\n P LoanPayment E\n"
},
{
"answer_id": 28621613,
"author": "Code Whisperer",
"author_id": 2299820,
"author_profile": "https://Stackoverflow.com/users/2299820",
"pm_score": 0,
"selected": false,
"text": "var annuity = P * (i + i / (Math.pow(1+i,n) -1));\n\n//P: principal, I: periodic interest rate, N: number of periods\n"
},
{
"answer_id": 37015458,
"author": "Rickferd",
"author_id": 6288097,
"author_profile": "https://Stackoverflow.com/users/6288097",
"pm_score": 2,
"selected": false,
"text": " numerator = i * principle * (Math.Pow(1 + i, n));\n denominator = (Math.Pow(1 + i, n) - 1);\n\n /* Calculation of Amortization Payment Amount */\n payment = numerator / denominator;\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
] |
342,285 | <p>I have a table in a SQL 2005 database that contains a column defined as a xml datatype. I'm trying to write stored proc that queries the xml and returns a resultset from a select statement. I've seen examples of returning scalar values or xml but not how to return a resultset.</p>
<p>Am I going to have to use openxml or is there another solution?</p>
| [
{
"answer_id": 342316,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 2,
"selected": false,
"text": "select xmlColumnName.value('XpathExpression', 'outputSqlType') from dataTable\n select xmlColumnName.value('/root/node[@name=\"myname\"]', 'varchar(60)')\n"
},
{
"answer_id": 342335,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 1,
"selected": false,
"text": "DECLARE @idoc int\nDECLARE @doc nvarchar(max)\n\nSET @doc = '\n<xml>\n <Entry Type=\"Error\" Start=\"2008-11-19 02:16:00\" End=\"2008-11-20 04:55:00\" />\n <Entry Type=\"Success\" Start=\"2008-11-25 12:45:00\" End=\"2008-11-25 13:01:00\" />\n</xml>'\n\n\nEXEC sp_xml_preparedocument @idoc OUTPUT, @xml\n\nSELECT [EventType]\n ,[EventStart]\n ,[EventEnd]\nFROM OPENXML (@idoc, '//Event',1)\n WITH ([Type] varchar(30)\n ,[Start] varchar(30)\n ,[End] varchar(30)\n)\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27714/"
] |
342,290 | <p>I'm looking to inspect SQL statements in Java/jdbc code to ensure that the SQL to be executed is of acceptable quality. Neither PMD not Findbugs appears to have JDBC or sql rules. I could use p6spy to log the SQL and look at that way, but this is manual. </p>
<p>I'm wondering if the strategy of of using PMD/Findbugs/etc to create a rule that any string passed to PreparedStatement where there is an "=" or "in" has only parametrized vars on the compare side.</p>
<p>Has anyone done this? Or done this by other means?</p>
| [
{
"answer_id": 342321,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": true,
"text": "= IN() != <> < <= > >= LIKE String sql = \"SELECT *, \" + someJavaVar + \" AS constant_column FROM mytable\";\n String sql = \"SELECT * FROM mytable ORDER BY \" + columnname;\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13753/"
] |
342,293 | <p>I think the question says it all. I have several monthly processes in stored procedures which take anywhere from a minute to an hour. If I declare them <code>WITH RECOMPILE</code>, an execution plan will be generated each time.</p>
<p>If the underlying indexes or statistics or views are changed by the DBA, I don't want anyone to have to go in and force a recompile the SPs with an ALTER or whatever.</p>
<p>Is there any downside to this?</p>
| [
{
"answer_id": 342319,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "WITH RECOMPILE"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18255/"
] |
342,320 | <p>I have a very complicated .NET application that contains cut/copy/paste functionality. I want to enable/disable cut/copy/paste buttons depending on the selected control/content. The app has many user controls. What is the best way to achieve this?</p>
<p>Thanks</p>
| [
{
"answer_id": 342336,
"author": "grepsedawk",
"author_id": 14388,
"author_profile": "https://Stackoverflow.com/users/14388",
"pm_score": 0,
"selected": false,
"text": "textBox.GotFocus += myFunctionalityEnabler;"
},
{
"answer_id": 342349,
"author": "Mike Hall",
"author_id": 18202,
"author_profile": "https://Stackoverflow.com/users/18202",
"pm_score": 1,
"selected": false,
"text": "selectedControl1.AddObserver(button1);\nselectedControl1.AddObserver(button2);\nselectedControl1.AddObserver(textBox1);\n\nselectedControl2.AddObserver(button1);\nselectedControl2.AddObserver(textbox3);\n foreach(Control ctl in selectedControl1.Observers)\n{\n ctl.Enabled = true;\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,333 | <p>I see the following code in the attribute_fu plugin:</p>
<pre><code>module AttributeFu
module Associations #:nodoc:
def self.included(base) #:nodoc:
base.class_eval do
extend ClassMethods
class << self; alias_method_chain :has_many, :association_option; end
class_inheritable_accessor :managed_association_attributes
write_inheritable_attribute :managed_association_attributes, []
after_update :save_managed_associations
end
end
...
end
end
</code></pre>
<p>When I try to replace</p>
<pre><code>class << self; alias_method_chain :has_many, :association_option; end
</code></pre>
<p>with:
alias_method_chain :has_many, :association_option?</p>
<p>I get the following error</p>
<pre><code>/usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method': undefined method `has_many' for class `ActiveRecord::Base' (NameError)
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method_chain'
from /home/twong/git/physpace/vendor/plugins/attribute_fu/lib/attribute_fu/associations.rb:9:in `included'
</code></pre>
<p>I thought those two lines would do the same thing, but it looks like I'm wrong. Can somebody explain my error?</p>
| [
{
"answer_id": 342341,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 0,
"selected": false,
"text": "self class << self\n ...\nend\n alias_method_chain has_many has_many_without_association_options has_many_with_association_options has_many SomeThing.bar_method\n assoc = SomeThing.new\nassoc.foo_method\n class SomeThing\n def foo_method\n ...\n end\n class << self\n def bar_method\n ...\n end\n end\nend\n AttributeFu::Associations alias_method_chain class << self extends ClassMethods def self.has_many_with_association_options\n ...\nend\n class << self\n def has_many_with_association_options\n ...\n end\nend\n"
},
{
"answer_id": 344864,
"author": "Matt Burke",
"author_id": 29691,
"author_profile": "https://Stackoverflow.com/users/29691",
"pm_score": 3,
"selected": true,
"text": "# init.rb\nActiveRecord::Base.class_eval { include AttributeFu::Associations }\n\nmodule AttributeFu\n module Associations\n def self.included(base)\n # base == ActiveRecord::Base (the class)\n base.class_eval do\n # class_eval makes self == ActiveRecord::Base, and makes def define instance methods.\n extend ClassMethods\n\n # If has_many were an instance method, we could do this\n # alias_method_chain :has_many, :association_option; end\n # but it's a class method, so we have to do the alias_method_chain on\n # the meta-class for ActiveRecord::Base, which is what class << self does.\n class << self; alias_method_chain :has_many, :association_option; end\n end\n end\n end\nend\n class A ; end\nA.class_eval { puts self.inspect ; class << self ; puts self.inspect ; end }\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
342,365 | <p>What are some good examples of coding guidelines. I'm not really looking for anything specific to a single language.</p>
<p>But what should I be doing/evaluating as I write coding guidelines? Such as how flexible should the guidelines and how much should decisions be left to the programmer or to someone else or even pre-decided by the guidelines.</p>
<p>This set of guidelines that I am working on is supposed to cover a wide range of topics: comments, database design, and even some user interface guidelines.</p>
| [
{
"answer_id": 342408,
"author": "John MacIntyre",
"author_id": 29043,
"author_profile": "https://Stackoverflow.com/users/29043",
"pm_score": 3,
"selected": false,
"text": "if( !codingGuidelines.Followed)\n{\n reason = programmer.WhyNot();\n if( reason.Acceptable)\n {\n codingGuidelines.Integrate( reason);\n }\n else\n {\n team.GiveAssKicking(programmer);\n }\n}\n"
},
{
"answer_id": 342704,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 6,
"selected": true,
"text": "m_member m_member2 member2_ m_lpcstrMember2"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/657/"
] |
342,371 | <p>Linux 2.6.18-92.el5, ruby 1.8.7, Rails 2.2.2, mysql gem 2.7</p>
<p>I installed the MySQL binary distribution under /usr/local, then installed the mysql gem like this:</p>
<pre><code>gem install mysql --no-rdoc --no-ri \
-- --with-mysql-include=/usr/local/mysql/include \
--with-mysql-lib=/usr/local/mysql/lib \
--with-mysql-config=/usr/local/mysql/bin/mysql_config
</code></pre>
<p>When I run <code>irb> require 'mysql'</code> I get the error shown below:</p>
<pre><code>irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'mysql'
LoadError: libmysqlclient.so.16: cannot open shared object file:
No such file or directory -
/usr/local/lib/ruby/gems/1.8/gems/mysql-2.7/lib/mysql.so
from /usr/local/lib/ruby/gems/1.8/gems/mysql-2.7/lib/mysql.so
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/
custom_require.rb:36:in `require' from (irb):2
</code></pre>
<p>After some Googling I found that I could use <code>ldconfig</code> to configure
mysql.so to be available to the whole system. Once I added "/usr/local/
mysql/lib" to /etc/ld.so.conf and ran ldconfig, it worked fine:</p>
<pre><code>irb(main):002:0> require 'rubygems'
=> true
irb(main):003:0> require 'mysql'
=> true
</code></pre>
<p>OK, so I got it to work. But my question is, why was I getting that error? You used to be able to just <code>gem install mysql</code> and it would work. Has anyone else encountered the same error? Using <code>ldconfig</code> seems kind of brittle and unmaintainable. Is there a better solution?</p>
<p>Any insight would be greatly appreciated.</p>
<p>Thanks,</p>
<p>Ethan</p>
| [
{
"answer_id": 353586,
"author": "bradheintz",
"author_id": 40093,
"author_profile": "https://Stackoverflow.com/users/40093",
"pm_score": 3,
"selected": true,
"text": "gem install mysql gem install foo"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42595/"
] |
342,378 | <p>We offer a number of online services. We are required to develop a system which provides a quick/simple experience for users if they are transferred from one service (on <code>domain1.com</code>) to another service (on <code>domain2.com</code>).</p>
<p>Is there a safe and secure way to log a user in automatically once he has been transferred to the new service?</p>
<p>Yell at me if the solution below is completely insecure/wrong.</p>
<p>We were considering a system similar to that provided by a number of online services for password recovery - they are emailed a link with a unique hash which expires, that allows them to change their password.</p>
<p>The <code>domain1.com</code> site would generate a unique hash and store it in a database with the hash linked to a user along with an expire datetime field.</p>
<p>The user will be transferred to <code>domain2.com/auto/?hash=d41d8cd98f00b204e9800998ecf8427e</code></p>
<p><code>domain2.com</code> would next make a request to <code>domain1.com</code> with the hash to get the information about the user. <code>domain1.com</code> would then remove the hash from the database. <code>domain2.com</code> would log the user in and set cookies, etc.</p>
<p>Could something based on OpenID or OAuth achieve the same results?</p>
| [
{
"answer_id": 342387,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 3,
"selected": false,
"text": "domain1.com domain2.com domain1.com domain2.com domain2.com domain2.com"
},
{
"answer_id": 342498,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 7,
"selected": false,
"text": "domain1.com domain1.com domain1.com sso.com sso.com sso.com sso.com domain1 domain1.com/ssologin ssologin sso.com domain1.com domain1 domain2.com domain1 sso.com sso.com sso.com domain2.com domain2.com domain1 domain2"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35293/"
] |
342,409 | <p>I have binary data in an unsigned char variable.
I need to convert them to PEM base64 in c.
I looked in openssl library but i could not find any function.
Does any body have any idea?</p>
| [
{
"answer_id": 342439,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 5,
"selected": false,
"text": "openssl enc BIO_f_base64()"
},
{
"answer_id": 342755,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 4,
"selected": false,
"text": "char base64_digit (n) unsigned n; {\n if (n < 10) return n - '0';\n else if (n < 10 + 26) return n - 'a';\n else if (n < 10 + 26 + 26) return n - 'A';\n else assert(0);\n return 0;\n}\n\nunsigned char base64_decode_digit(char c) {\n switch (c) {\n case '=' : return 62;\n case '.' : return 63;\n default :\n if (isdigit(c)) return c - '0';\n else if (islower(c)) return c - 'a' + 10;\n else if (isupper(c)) return c - 'A' + 10 + 26;\n else assert(0);\n }\n return 0xff;\n}\n\nunsigned base64_decode(char *s) {\n char *p;\n unsigned n = 0;\n\n for (p = s; *p; p++)\n n = 64 * n + base64_decode_digit(*p);\n\n return n;\n}\n"
},
{
"answer_id": 426485,
"author": "LarryF",
"author_id": 18518,
"author_profile": "https://Stackoverflow.com/users/18518",
"pm_score": 3,
"selected": false,
"text": " static const char table[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n static const int BASE64_INPUT_SIZE = 57;\n\n BOOL isbase64(char c)\n {\n return c && strchr(table, c) != NULL;\n }\n\n inline char value(char c)\n {\n const char *p = strchr(table, c);\n if(p) {\n return p-table;\n } else {\n return 0;\n }\n }\n\n int UnBase64(unsigned char *dest, const unsigned char *src, int srclen)\n {\n *dest = 0;\n if(*src == 0) \n {\n return 0;\n }\n unsigned char *p = dest;\n do\n {\n\n char a = value(src[0]);\n char b = value(src[1]);\n char c = value(src[2]);\n char d = value(src[3]);\n *p++ = (a << 2) | (b >> 4);\n *p++ = (b << 4) | (c >> 2);\n *p++ = (c << 6) | d;\n if(!isbase64(src[1])) \n {\n p -= 2;\n break;\n } \n else if(!isbase64(src[2])) \n {\n p -= 2;\n break;\n } \n else if(!isbase64(src[3])) \n {\n p--;\n break;\n }\n src += 4;\n while(*src && (*src == 13 || *src == 10)) src++;\n }\n while(srclen-= 4);\n *p = 0;\n return p-dest;\n }\n"
},
{
"answer_id": 4763640,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "_UINT8 unsigned char /** Static Base64 character encoding lookup table */\nconst char CBase64::encodeCharacterTable[65] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/** Static Base64 character decoding lookup table */\nconst char CBase64::decodeCharacterTable[256] = {\n -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21\n ,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,\n -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n -1,-1,-1}; \n\n/*!\n\\brief Encodes binary data to base 64 character data\n\\param in The data to encode\n\\param out The encoded data as characters\n*/\nvoid CBase64::Encode(std::istream &in, std::ostringstream &out)\n{\n char buff1[3];\n char buff2[4];\n _UINT8 i=0, j;\n while(in.readsome(&buff1[i++], 1))\n if (i==3)\n {\n out << encodeCharacterTable[(buff1[0] & 0xfc) >> 2];\n out << encodeCharacterTable[((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4)];\n out << encodeCharacterTable[((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6)];\n out << encodeCharacterTable[buff1[2] & 0x3f];\n i=0;\n }\n\n if (--i)\n {\n for(j=i;j<3;j++) buff1[j] = '\\0';\n\n buff2[0] = (buff1[0] & 0xfc) >> 2;\n buff2[1] = ((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4);\n buff2[2] = ((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6);\n buff2[3] = buff1[2] & 0x3f;\n\n for (j=0;j<(i+1);j++) out << encodeCharacterTable[buff2[j]];\n\n while(i++<3) out << '=';\n }\n\n}\n\n/*!\n\\brief Decodes base 64 character data to binary data\n\\param in The character data to decode\n\\param out The decoded data\n*/\nvoid CBase64::Decode(std::istringstream &in, std::ostream &out)\n{\n char buff1[4];\n char buff2[4];\n _UINT8 i=0, j;\n\n while(in.readsome(&buff2[i], 1) && buff2[i] != '=')\n {\n if (++i==4)\n {\n for (i=0;i!=4;i++)\n buff2[i] = decodeCharacterTable[buff2[i]];\n\n out << (char)((buff2[0] << 2) + ((buff2[1] & 0x30) >> 4));\n out << (char)(((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2));\n out << (char)(((buff2[2] & 0x3) << 6) + buff2[3]);\n\n i=0;\n }\n }\n\n if (i) \n {\n for (j=i;j<4;j++) buff2[j] = '\\0';\n for (j=0;j<4;j++) buff2[j] = decodeCharacterTable[buff2[j]];\n\n buff1[0] = (buff2[0] << 2) + ((buff2[1] & 0x30) >> 4);\n buff1[1] = ((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2);\n buff1[2] = ((buff2[2] & 0x3) << 6) + buff2[3];\n\n for (j=0;j<(i-1); j++) out << (char)buff1[j];\n }\n}\n"
},
{
"answer_id": 6782480,
"author": "ryyst",
"author_id": 282635,
"author_profile": "https://Stackoverflow.com/users/282635",
"pm_score": 7,
"selected": false,
"text": "#include <stdint.h>\n#include <stdlib.h>\n\n\nstatic char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\n 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\n 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z', '0', '1', '2', '3',\n '4', '5', '6', '7', '8', '9', '+', '/'};\nstatic char *decoding_table = NULL;\nstatic int mod_table[] = {0, 2, 1};\n\n\nchar *base64_encode(const unsigned char *data,\n size_t input_length,\n size_t *output_length) {\n\n *output_length = 4 * ((input_length + 2) / 3);\n\n char *encoded_data = malloc(*output_length);\n if (encoded_data == NULL) return NULL;\n\n for (int i = 0, j = 0; i < input_length;) {\n\n uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;\n uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;\n uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;\n\n uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;\n\n encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];\n }\n\n for (int i = 0; i < mod_table[input_length % 3]; i++)\n encoded_data[*output_length - 1 - i] = '=';\n\n return encoded_data;\n}\n\n\nunsigned char *base64_decode(const char *data,\n size_t input_length,\n size_t *output_length) {\n\n if (decoding_table == NULL) build_decoding_table();\n\n if (input_length % 4 != 0) return NULL;\n\n *output_length = input_length / 4 * 3;\n if (data[input_length - 1] == '=') (*output_length)--;\n if (data[input_length - 2] == '=') (*output_length)--;\n\n unsigned char *decoded_data = malloc(*output_length);\n if (decoded_data == NULL) return NULL;\n\n for (int i = 0, j = 0; i < input_length;) {\n\n uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n\n uint32_t triple = (sextet_a << 3 * 6)\n + (sextet_b << 2 * 6)\n + (sextet_c << 1 * 6)\n + (sextet_d << 0 * 6);\n\n if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;\n if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;\n if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;\n }\n\n return decoded_data;\n}\n\n\nvoid build_decoding_table() {\n\n decoding_table = malloc(256);\n\n for (int i = 0; i < 64; i++)\n decoding_table[(unsigned char) encoding_table[i]] = i;\n}\n\n\nvoid base64_cleanup() {\n free(decoding_table);\n}\n"
},
{
"answer_id": 15880038,
"author": "Wookie88",
"author_id": 979987,
"author_profile": "https://Stackoverflow.com/users/979987",
"pm_score": 4,
"selected": false,
"text": "/* \n base64.cpp and base64.h\n\n Copyright (C) 2004-2008 René Nyffenegger\n\n This source code is provided 'as-is', without any express or implied\n warranty. In no event will the author be held liable for any damages\n arising from the use of this software.\n\n Permission is granted to anyone to use this software for any purpose,\n including commercial applications, and to alter it and redistribute it\n freely, subject to the following restrictions:\n\n 1. The origin of this source code must not be misrepresented; you must not\n claim that you wrote the original source code. If you use this source code\n in a product, an acknowledgment in the product documentation would be\n appreciated but is not required.\n\n 2. Altered source versions must be plainly marked as such, and must not be\n misrepresented as being the original source code.\n\n 3. This notice may not be removed or altered from any source distribution.\n\n René Nyffenegger rene.nyffenegger@adp-gmbh.ch\n\n*/\n\n#include \"base64.h\"\n#include <iostream>\n\nstatic const std::string base64_chars = \n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789+/\";\n\n\nstatic inline bool is_base64(unsigned char c) {\n return (isalnum(c) || (c == '+') || (c == '/'));\n}\n\nstd::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {\n std::string ret;\n int i = 0;\n int j = 0;\n unsigned char char_array_3[3];\n unsigned char char_array_4[4];\n\n while (in_len--) {\n char_array_3[i++] = *(bytes_to_encode++);\n if (i == 3) {\n char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;\n char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);\n char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);\n char_array_4[3] = char_array_3[2] & 0x3f;\n\n for(i = 0; (i <4) ; i++)\n ret += base64_chars[char_array_4[i]];\n i = 0;\n }\n }\n\n if (i)\n {\n for(j = i; j < 3; j++)\n char_array_3[j] = '\\0';\n\n char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;\n char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);\n char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);\n char_array_4[3] = char_array_3[2] & 0x3f;\n\n for (j = 0; (j < i + 1); j++)\n ret += base64_chars[char_array_4[j]];\n\n while((i++ < 3))\n ret += '=';\n\n }\n\n return ret;\n\n}\n\nstd::string base64_decode(std::string const& encoded_string) {\n int in_len = encoded_string.size();\n int i = 0;\n int j = 0;\n int in_ = 0;\n unsigned char char_array_4[4], char_array_3[3];\n std::string ret;\n\n while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {\n char_array_4[i++] = encoded_string[in_]; in_++;\n if (i ==4) {\n for (i = 0; i <4; i++)\n char_array_4[i] = base64_chars.find(char_array_4[i]);\n\n char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);\n char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);\n char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];\n\n for (i = 0; (i < 3); i++)\n ret += char_array_3[i];\n i = 0;\n }\n }\n\n if (i) {\n for (j = i; j <4; j++)\n char_array_4[j] = 0;\n\n for (j = 0; j <4; j++)\n char_array_4[j] = base64_chars.find(char_array_4[j]);\n\n char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);\n char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);\n char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];\n\n for (j = 0; (j < i - 1); j++) ret += char_array_3[j];\n }\n\n return ret;\n}\n #include <string>\n\nstd::string base64_encode(unsigned char const* , unsigned int len);\nstd::string base64_decode(std::string const& s);\n const std::string s = \"test\";\nstd::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());\n std::string decoded = base64_decode(encoded);\n"
},
{
"answer_id": 16511093,
"author": "schulwitz",
"author_id": 1423189,
"author_profile": "https://Stackoverflow.com/users/1423189",
"pm_score": 4,
"selected": false,
"text": "/* A BASE-64 ENCODER AND DECODER USING OPENSSL */\n#include <openssl/pem.h>\n#include <string.h> //Only needed for strlen().\n\nchar *base64encode (const void *b64_encode_this, int encode_this_many_bytes){\n BIO *b64_bio, *mem_bio; //Declares two OpenSSL BIOs: a base64 filter and a memory BIO.\n BUF_MEM *mem_bio_mem_ptr; //Pointer to a \"memory BIO\" structure holding our base64 data.\n b64_bio = BIO_new(BIO_f_base64()); //Initialize our base64 filter BIO.\n mem_bio = BIO_new(BIO_s_mem()); //Initialize our memory sink BIO.\n BIO_push(b64_bio, mem_bio); //Link the BIOs by creating a filter-sink BIO chain.\n BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL); //No newlines every 64 characters or less.\n BIO_write(b64_bio, b64_encode_this, encode_this_many_bytes); //Records base64 encoded data.\n BIO_flush(b64_bio); //Flush data. Necessary for b64 encoding, because of pad characters.\n BIO_get_mem_ptr(mem_bio, &mem_bio_mem_ptr); //Store address of mem_bio's memory structure.\n BIO_set_close(mem_bio, BIO_NOCLOSE); //Permit access to mem_ptr after BIOs are destroyed.\n BIO_free_all(b64_bio); //Destroys all BIOs in chain, starting with b64 (i.e. the 1st one).\n BUF_MEM_grow(mem_bio_mem_ptr, (*mem_bio_mem_ptr).length + 1); //Makes space for end null.\n (*mem_bio_mem_ptr).data[(*mem_bio_mem_ptr).length] = '\\0'; //Adds null-terminator to tail.\n return (*mem_bio_mem_ptr).data; //Returns base-64 encoded data. (See: \"buf_mem_st\" struct).\n}\n\nchar *base64decode (const void *b64_decode_this, int decode_this_many_bytes){\n BIO *b64_bio, *mem_bio; //Declares two OpenSSL BIOs: a base64 filter and a memory BIO.\n char *base64_decoded = calloc( (decode_this_many_bytes*3)/4+1, sizeof(char) ); //+1 = null.\n b64_bio = BIO_new(BIO_f_base64()); //Initialize our base64 filter BIO.\n mem_bio = BIO_new(BIO_s_mem()); //Initialize our memory source BIO.\n BIO_write(mem_bio, b64_decode_this, decode_this_many_bytes); //Base64 data saved in source.\n BIO_push(b64_bio, mem_bio); //Link the BIOs by creating a filter-source BIO chain.\n BIO_set_flags(b64_bio, BIO_FLAGS_BASE64_NO_NL); //Don't require trailing newlines.\n int decoded_byte_index = 0; //Index where the next base64_decoded byte should be written.\n while ( 0 < BIO_read(b64_bio, base64_decoded+decoded_byte_index, 1) ){ //Read byte-by-byte.\n decoded_byte_index++; //Increment the index until read of BIO decoded data is complete.\n } //Once we're done reading decoded data, BIO_read returns -1 even though there's no error.\n BIO_free_all(b64_bio); //Destroys all BIOs in chain, starting with b64 (i.e. the 1st one).\n return base64_decoded; //Returns base-64 decoded data with trailing null terminator.\n}\n\n/*Here's one way to base64 encode/decode using the base64encode() and base64decode functions.*/\nint main(void){\n char data_to_encode[] = \"Base64 encode this string!\"; //The string we will base-64 encode.\n\n int bytes_to_encode = strlen(data_to_encode); //Number of bytes in string to base64 encode.\n char *base64_encoded = base64encode(data_to_encode, bytes_to_encode); //Base-64 encoding.\n\n int bytes_to_decode = strlen(base64_encoded); //Number of bytes in string to base64 decode.\n char *base64_decoded = base64decode(base64_encoded, bytes_to_decode); //Base-64 decoding.\n\n printf(\"Original character string is: %s\\n\", data_to_encode); //Prints our initial string.\n printf(\"Base-64 encoded string is: %s\\n\", base64_encoded); //Prints base64 encoded string.\n printf(\"Base-64 decoded string is: %s\\n\", base64_decoded); //Prints base64 decoded string.\n\n free(base64_encoded); //Frees up the memory holding our base64 encoded data.\n free(base64_decoded); //Frees up the memory holding our base64 decoded data.\n}\n"
},
{
"answer_id": 17923102,
"author": "Amit Bens",
"author_id": 225121,
"author_profile": "https://Stackoverflow.com/users/225121",
"pm_score": -1,
"selected": false,
"text": " char *base64_encode(const unsigned char *data,\n size_t input_length,\n size_t *output_length,\n bool addLineBreaks)\n\n *output_length = 4 * ((input_length + 2) / 3);\n if (addLineBreaks) *output_length += *output_length / 38; // CRLF after each 76 chars\n\n char *encoded_data = malloc(*output_length);\n if (encoded_data == NULL) return NULL;\n\n UInt32 octet_a;\n UInt32 octet_b;\n UInt32 octet_c;\n UInt32 triple;\n int lineCount = 0;\n int sizeMod = size - (size % 3); // check if there is a partial triplet\n // adding all octet triplets, before partial last triplet\n for (; offset < sizeMod; ) \n {\n octet_a = data[offset++];\n octet_b = data[offset++];\n octet_c = data[offset++];\n\n triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;\n\n encoded_data[mBufferPos++] = encoding_table[(triple >> 3 * 6) & 0x3F];\n encoded_data[mBufferPos++] = encoding_table[(triple >> 2 * 6) & 0x3F];\n encoded_data[mBufferPos++] = encoding_table[(triple >> 1 * 6) & 0x3F];\n encoded_data[mBufferPos++] = encoding_table[(triple >> 0 * 6) & 0x3F];\n if (addLineBreaks)\n {\n if (++lineCount == 19)\n {\n encoded_data[mBufferPos++] = 13;\n encoded_data[mBufferPos++] = 10;\n lineCount = 0;\n }\n }\n }\n\n // last bytes\n if (sizeMod < size)\n {\n octet_a = data[offset++]; // first octect always added\n octet_b = offset < size ? data[offset++] : (UInt32)0; // conditional 2nd octet\n octet_c = (UInt32)0; // last character is definitely padded\n\n triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;\n\n encoded_data[mBufferPos++] = encoding_table[(triple >> 3 * 6) & 0x3F];\n encoded_data[mBufferPos++] = encoding_table[(triple >> 2 * 6) & 0x3F];\n encoded_data[mBufferPos++] = encoding_table[(triple >> 1 * 6) & 0x3F];\n encoded_data[mBufferPos++] = encoding_table[(triple >> 0 * 6) & 0x3F];\n\n // add padding '='\n sizeMod = size % 3; \n // last character is definitely padded\n encoded_data[mBufferPos - 1] = (byte)'=';\n if (sizeMod == 1) encoded_data[mBufferPos - 2] = (byte)'=';\n }\n }\n"
},
{
"answer_id": 21158326,
"author": "Homer6",
"author_id": 278976,
"author_profile": "https://Stackoverflow.com/users/278976",
"pm_score": 2,
"selected": false,
"text": "#include <openssl/bio.h>\n#include <openssl/evp.h>\n#include <stdlib.h>\n\nstring base64_encode( const string &str ){\n\n BIO *base64_filter = BIO_new( BIO_f_base64() );\n BIO_set_flags( base64_filter, BIO_FLAGS_BASE64_NO_NL );\n\n BIO *bio = BIO_new( BIO_s_mem() );\n BIO_set_flags( bio, BIO_FLAGS_BASE64_NO_NL );\n\n bio = BIO_push( base64_filter, bio );\n\n BIO_write( bio, str.c_str(), str.length() );\n\n BIO_flush( bio );\n\n char *new_data;\n\n long bytes_written = BIO_get_mem_data( bio, &new_data );\n\n string result( new_data, bytes_written );\n BIO_free_all( bio );\n\n return result;\n\n}\n\n\n\nstring base64_decode( const string &str ){\n\n BIO *bio, *base64_filter, *bio_out;\n char inbuf[512];\n int inlen;\n base64_filter = BIO_new( BIO_f_base64() );\n BIO_set_flags( base64_filter, BIO_FLAGS_BASE64_NO_NL );\n\n bio = BIO_new_mem_buf( (void*)str.c_str(), str.length() );\n\n bio = BIO_push( base64_filter, bio );\n\n bio_out = BIO_new( BIO_s_mem() );\n\n while( (inlen = BIO_read(bio, inbuf, 512)) > 0 ){\n BIO_write( bio_out, inbuf, inlen );\n }\n\n BIO_flush( bio_out );\n\n char *new_data;\n long bytes_written = BIO_get_mem_data( bio_out, &new_data );\n\n string result( new_data, bytes_written );\n\n BIO_free_all( bio );\n BIO_free_all( bio_out );\n\n return result;\n\n}\n"
},
{
"answer_id": 34201175,
"author": "anton_rh",
"author_id": 5447906,
"author_profile": "https://Stackoverflow.com/users/5447906",
"pm_score": 0,
"selected": false,
"text": "#include <openssl/bio.h>\n\nstd::string base64_encode(const std::string &input)\n{\n BIO *p_bio_b64 = nullptr;\n BIO *p_bio_mem = nullptr;\n\n try\n {\n // make chain: p_bio_b64 <--> p_bio_mem\n p_bio_b64 = BIO_new(BIO_f_base64());\n if (!p_bio_b64) { throw std::runtime_error(\"BIO_new failed\"); }\n BIO_set_flags(p_bio_b64, BIO_FLAGS_BASE64_NO_NL); //No newlines every 64 characters or less\n\n p_bio_mem = BIO_new(BIO_s_mem());\n if (!p_bio_mem) { throw std::runtime_error(\"BIO_new failed\"); }\n BIO_push(p_bio_b64, p_bio_mem);\n\n // write input to chain\n // write sequence: input -->> p_bio_b64 -->> p_bio_mem\n if (BIO_write(p_bio_b64, input.c_str(), input.size()) <= 0)\n { throw std::runtime_error(\"BIO_write failed\"); }\n\n if (BIO_flush(p_bio_b64) <= 0)\n { throw std::runtime_error(\"BIO_flush failed\"); }\n\n // get result\n char *p_encoded_data = nullptr;\n auto encoded_len = BIO_get_mem_data(p_bio_mem, &p_encoded_data);\n if (!p_encoded_data) { throw std::runtime_error(\"BIO_get_mem_data failed\"); }\n\n std::string result(p_encoded_data, encoded_len);\n\n // clean\n BIO_free_all(p_bio_b64);\n\n return result;\n }\n catch (...)\n {\n if (p_bio_b64) { BIO_free_all(p_bio_b64); }\n throw;\n }\n}\n\nstd::string base64_decode(const std::string &input)\n{\n BIO *p_bio_mem = nullptr;\n BIO *p_bio_b64 = nullptr;\n\n try\n {\n // make chain: p_bio_b64 <--> p_bio_mem\n p_bio_b64 = BIO_new(BIO_f_base64());\n if (!p_bio_b64) { throw std::runtime_error(\"BIO_new failed\"); }\n BIO_set_flags(p_bio_b64, BIO_FLAGS_BASE64_NO_NL); //Don't require trailing newlines\n\n p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());\n if (!p_bio_mem) { throw std::runtime_error(\"BIO_new failed\"); }\n BIO_push(p_bio_b64, p_bio_mem);\n\n // read result from chain\n // read sequence (reverse to write): buf <<-- p_bio_b64 <<-- p_bio_mem\n std::vector<char> buf((input.size()*3/4)+1);\n std::string result;\n for (;;)\n {\n auto nread = BIO_read(p_bio_b64, buf.data(), buf.size());\n if (nread < 0) { throw std::runtime_error(\"BIO_read failed\"); }\n if (nread == 0) { break; } // eof\n\n result.append(buf.data(), nread);\n }\n\n // clean\n BIO_free_all(p_bio_b64);\n\n return result;\n }\n catch (...)\n {\n if (p_bio_b64) { BIO_free_all(p_bio_b64); }\n throw;\n }\n}\n"
},
{
"answer_id": 41094722,
"author": "GaspardP",
"author_id": 4660481,
"author_profile": "https://Stackoverflow.com/users/4660481",
"pm_score": 7,
"selected": false,
"text": "jounimalinen 25.1544\napache 25.5309\nNibbleAndAHalf 38.4165\ninternetsoftwareconsortium 48.2879\npolfosol 48.7955\nwikibooks_org_c 51.9659\ngnome 74.8188\nelegantdice 118.899\nlibb64 120.601\nmanuelmartinez 120.801\narduino 126.262\ndaedalusalpha 126.473\nCppCodec 151.866\nwikibooks_org_cpp 343.2\nadp_gmbh 381.523\nLihO 406.693\nlibcurl 3246.39\nuser152949 4828.21\n /*\n* Base64 encoding/decoding (RFC1341)\n* Copyright (c) 2005-2011, Jouni Malinen <j@w1.fi>\n*\n* This software may be distributed under the terms of the BSD license.\n* See README for more details.\n*/\n\n// 2016-12-12 - Gaspard Petit : Slightly modified to return a std::string \n// instead of a buffer allocated with malloc.\n\n#include <string>\n\nstatic const unsigned char base64_table[65] =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/**\n* base64_encode - Base64 encode\n* @src: Data to be encoded\n* @len: Length of the data to be encoded\n* @out_len: Pointer to output length variable, or %NULL if not used\n* Returns: Allocated buffer of out_len bytes of encoded data,\n* or empty string on failure\n*/\nstd::string base64_encode(const unsigned char *src, size_t len)\n{\n unsigned char *out, *pos;\n const unsigned char *end, *in;\n\n size_t olen;\n\n olen = 4*((len + 2) / 3); /* 3-byte blocks to 4-byte */\n\n if (olen < len)\n return std::string(); /* integer overflow */\n\n std::string outStr;\n outStr.resize(olen);\n out = (unsigned char*)&outStr[0];\n\n end = src + len;\n in = src;\n pos = out;\n while (end - in >= 3) {\n *pos++ = base64_table[in[0] >> 2];\n *pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];\n *pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];\n *pos++ = base64_table[in[2] & 0x3f];\n in += 3;\n }\n\n if (end - in) {\n *pos++ = base64_table[in[0] >> 2];\n if (end - in == 1) {\n *pos++ = base64_table[(in[0] & 0x03) << 4];\n *pos++ = '=';\n }\n else {\n *pos++ = base64_table[((in[0] & 0x03) << 4) |\n (in[1] >> 4)];\n *pos++ = base64_table[(in[1] & 0x0f) << 2];\n }\n *pos++ = '=';\n }\n\n return outStr;\n}\n polfosol 45.2335\nwikibooks_org_c 74.7347\napache 77.1438\nlibb64 100.332\ngnome 114.511\nmanuelmartinez 126.579\nelegantdice 138.514\ndaedalusalpha 151.561\njounimalinen 206.163\narduino 335.95\nwikibooks_org_cpp 350.437\nCppCodec 526.187\ninternetsoftwareconsortium 862.833\nlibcurl 1280.27\nLihO 1852.4\nadp_gmbh 1934.43\nuser152949 5332.87\n static const int B64index[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63, 52, 53, 54, 55,\n56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6,\n7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0,\n0, 0, 0, 63, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\n41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };\n\nstd::string b64decode(const void* data, const size_t len)\n{\n unsigned char* p = (unsigned char*)data;\n int pad = len > 0 && (len % 4 || p[len - 1] == '=');\n const size_t L = ((len + 3) / 4 - pad) * 4;\n std::string str(L / 4 * 3 + pad, '\\0');\n\n for (size_t i = 0, j = 0; i < L; i += 4)\n {\n int n = B64index[p[i]] << 18 | B64index[p[i + 1]] << 12 | B64index[p[i + 2]] << 6 | B64index[p[i + 3]];\n str[j++] = n >> 16;\n str[j++] = n >> 8 & 0xFF;\n str[j++] = n & 0xFF;\n }\n if (pad)\n {\n int n = B64index[p[L]] << 18 | B64index[p[L + 1]] << 12;\n str[str.size() - 1] = n >> 16;\n\n if (len > L + 2 && p[L + 2] != '=')\n {\n n |= B64index[p[L + 2]] << 6;\n str.push_back(n >> 8 & 0xFF);\n }\n }\n return str;\n}\n"
},
{
"answer_id": 48818578,
"author": "OGCJN",
"author_id": 2852000,
"author_profile": "https://Stackoverflow.com/users/2852000",
"pm_score": 3,
"selected": false,
"text": "const char encoding_table[] = { \n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\n 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\n 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z', '0', '1', '2', '3',\n '4', '5', '6', '7', '8', '9', '+', '/' };\n\nunsigned char decoding_table[256];\n\nfor (int i = 0; i < 256; i++)\n decoding_table[i] = '\\0';\n\nfor (int i = 0; i < 64; i++)\n decoding_table[(unsigned char)encoding_table[i]] = i;\n\nfor (int i = 0; i < 256; i++)\n cout << \"0x\" << (int(decoding_table[i]) < 16 ? \"0\" : \"\") << hex << int(decoding_table[i]) << (i != 255 ? \",\" : \"\") << ((i+1) % 16 == 0 ? '\\n' : '\\0');\n\ncin.ignore();\n static const char encoding_table[] = { \n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\n 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\n 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z', '0', '1', '2', '3',\n '4', '5', '6', '7', '8', '9', '+', '/' };\n\n static const unsigned char decoding_table[256] = {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x3f,\n 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,\n 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,\n 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n char* base64_encode(const unsigned char *data, size_t input_length, size_t &output_length) {\n\n const int mod_table[] = { 0, 2, 1 };\n\n output_length = 4 * ((input_length + 2) / 3);\n\n char *encoded_data = (char*)malloc(output_length);\n\n if (encoded_data == nullptr)\n return nullptr;\n\n for (int i = 0, j = 0; i < input_length;) {\n\n uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;\n uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;\n uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;\n\n uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;\n\n encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];\n\n }\n\n for (int i = 0; i < mod_table[input_length % 3]; i++)\n encoded_data[output_length - 1 - i] = '=';\n\n return encoded_data;\n\n };\n\n unsigned char* base64_decode(const char *data, size_t input_length, size_t &output_length) { \n\n if (input_length % 4 != 0)\n return nullptr;\n\n output_length = input_length / 4 * 3;\n\n if (data[input_length - 1] == '=') (output_length)--;\n if (data[input_length - 2] == '=') (output_length)--;\n\n unsigned char* decoded_data = (unsigned char*)malloc(output_length);\n\n if (decoded_data == nullptr)\n return nullptr;\n\n for (int i = 0, j = 0; i < input_length;) {\n\n uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n\n uint32_t triple = (sextet_a << 3 * 6)\n + (sextet_b << 2 * 6)\n + (sextet_c << 1 * 6)\n + (sextet_d << 0 * 6);\n\n if (j < output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;\n if (j < output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;\n if (j < output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;\n\n }\n\n return decoded_data;\n\n };\n"
},
{
"answer_id": 57743807,
"author": "Brian",
"author_id": 2850957,
"author_profile": "https://Stackoverflow.com/users/2850957",
"pm_score": 1,
"selected": false,
"text": "void datauriBase64EncodeBufferless(int (*putchar_fcptr)(int), const char* type_strptr, const void* data_buf, const size_t dataLength)\n{\n const char base64chars[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n const uint8_t *data = (const uint8_t *)data_buf;\n size_t x = 0;\n uint32_t n = 0;\n int padCount = dataLength % 3;\n uint8_t n0, n1, n2, n3;\n\n size_t outcount = 0;\n size_t line = 0;\n\n putchar_fcptr((int)'d');\n putchar_fcptr((int)'a');\n putchar_fcptr((int)'t');\n putchar_fcptr((int)'a');\n putchar_fcptr((int)':');\n outcount += 5;\n\n while (*type_strptr != '\\0')\n {\n putchar_fcptr((int)*type_strptr);\n type_strptr++;\n outcount++;\n }\n\n putchar_fcptr((int)';');\n putchar_fcptr((int)'b');\n putchar_fcptr((int)'a');\n putchar_fcptr((int)'s');\n putchar_fcptr((int)'e');\n putchar_fcptr((int)'6');\n putchar_fcptr((int)'4');\n putchar_fcptr((int)',');\n outcount += 8;\n\n /* increment over the length of the string, three characters at a time */\n for (x = 0; x < dataLength; x += 3)\n {\n /* these three 8-bit (ASCII) characters become one 24-bit number */\n n = ((uint32_t)data[x]) << 16; //parenthesis needed, compiler depending on flags can do the shifting before conversion to uint32_t, resulting to 0\n\n if((x+1) < dataLength)\n n += ((uint32_t)data[x+1]) << 8;//parenthesis needed, compiler depending on flags can do the shifting before conversion to uint32_t, resulting to 0\n\n if((x+2) < dataLength)\n n += data[x+2];\n\n /* this 24-bit number gets separated into four 6-bit numbers */\n n0 = (uint8_t)(n >> 18) & 63;\n n1 = (uint8_t)(n >> 12) & 63;\n n2 = (uint8_t)(n >> 6) & 63;\n n3 = (uint8_t)n & 63;\n\n /*\n * if we have one byte available, then its encoding is spread\n * out over two characters\n */\n\n putchar_fcptr((int)base64chars[n0]);\n putchar_fcptr((int)base64chars[n1]);\n outcount += 2;\n\n /*\n * if we have only two bytes available, then their encoding is\n * spread out over three chars\n */\n if((x+1) < dataLength)\n {\n putchar_fcptr((int)base64chars[n2]);\n outcount += 1;\n }\n\n /*\n * if we have all three bytes available, then their encoding is spread\n * out over four characters\n */\n if((x+2) < dataLength)\n {\n putchar_fcptr((int)base64chars[n3]);\n outcount += 1;\n }\n\n /* Breaking up the line so it's easier to copy and paste */\n int curr_line = (outcount/80);\n if( curr_line != line )\n {\n line = curr_line;\n putchar_fcptr((int)'\\r');\n putchar_fcptr((int)'\\n');\n }\n }\n\n /*\n * create and add padding that is required if we did not have a multiple of 3\n * number of characters available\n */\n if (padCount > 0)\n {\n for (; padCount < 3; padCount++)\n {\n putchar_fcptr((int)'=');\n }\n }\n\n putchar_fcptr((int)'\\r');\n putchar_fcptr((int)'\\n');\n}\n #include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n\nint main(void)\n{\n char str[] = \"test\";\n datauriBase64EncodeBufferless(putchar, \"text/plain;charset=utf-8\", str, strlen(str));\n return 0;\n}\n data:text/plain;charset=utf-8;base64,dGVzdA=="
},
{
"answer_id": 60581068,
"author": "mtrw",
"author_id": 120261,
"author_profile": "https://Stackoverflow.com/users/120261",
"pm_score": 3,
"selected": false,
"text": "EVP_EncodeBlock EVP_DecodeBlock #include <stdio.h>\n#include <stdlib.h>\n#include <openssl/evp.h>\n\nchar *base64(const unsigned char *input, int length) {\n const int pl = 4*((length+2)/3);\n char *output = calloc(pl+1, 1); //+1 for the terminating null that EVP_EncodeBlock adds on\n const int ol = EVP_EncodeBlock(output, input, length);\n if (ol != pl) { fprintf(stderr, \"Whoops, encode predicted %d but we got %d\\n\", pl, ol); }\n return output;\n}\n\nunsigned char *decode64(const char *input, int length) {\n const int pl = 3*length/4;\n unsigned char *output = calloc(pl+1, 1);\n const int ol = EVP_DecodeBlock(output, input, length);\n if (pl != ol) { fprintf(stderr, \"Whoops, decode predicted %d but we got %d\\n\", pl, ol); }\n return output;\n}\n"
},
{
"answer_id": 64856489,
"author": "Yu Jiaao",
"author_id": 1484621,
"author_profile": "https://Stackoverflow.com/users/1484621",
"pm_score": 1,
"selected": false,
"text": " #include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n \nstatic char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\n 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\n 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z', '0', '1', '2', '3',\n '4', '5', '6', '7', '8', '9', '-', '_'};\nstatic char *decoding_table = NULL;\nstatic int mod_table[] = {0, 2, 1};\n \nvoid build_decoding_table() {\n \n decoding_table = malloc(256);\n \n for (int i = 0; i < 64; i++)\n decoding_table[(unsigned char) encoding_table[i]] = i;\n}\n \n \nvoid base64_cleanup() {\n free(decoding_table);\n} \n \nchar *base64_encode(const char *data,\n size_t input_length,\n size_t *output_length) {\n \n *output_length = 4 * ((input_length + 2) / 3);\n \n char *encoded_data = malloc(*output_length);\n if (encoded_data == NULL) return NULL;\n \n for (int i = 0, j = 0; i < input_length;) {\n \n uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;\n uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;\n uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;\n \n uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;\n \n encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];\n }\n \n //int i=0;\n for (int i = 0; i < mod_table[input_length % 3]; i++)\n encoded_data[*output_length - 1 - i] = '=';\n \n *output_length = *output_length -2 + mod_table[input_length % 3];\n encoded_data[*output_length] =0;\n\n return encoded_data;\n}\n \n \nunsigned char *base64_decode(const char *data,\n size_t input_length,\n size_t *output_length) {\n \n if (decoding_table == NULL) build_decoding_table();\n \n if (input_length % 4 != 0) return NULL;\n \n *output_length = input_length / 4 * 3;\n if (data[input_length - 1] == '=') (*output_length)--;\n if (data[input_length - 2] == '=') (*output_length)--;\n \n unsigned char *decoded_data = malloc(*output_length);\n if (decoded_data == NULL) return NULL;\n \n for (int i = 0, j = 0; i < input_length;) {\n \n uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];\n \n uint32_t triple = (sextet_a << 3 * 6)\n + (sextet_b << 2 * 6)\n + (sextet_c << 1 * 6)\n + (sextet_d << 0 * 6);\n \n if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;\n if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;\n if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;\n }\n \n return decoded_data;\n}\n \nint main(){\n \n const char * data = \"Hello World! 您好!世界!\";\n size_t input_size = strlen(data);\n printf(\"Input size: %ld \\n\",input_size);\n char * encoded_data = base64_encode(data, input_size, &input_size);\n printf(\"After size: %ld \\n\",input_size);\n printf(\"Encoded Data is: %s \\n\",encoded_data);\n \n size_t decode_size = strlen(encoded_data);\n printf(\"Output size: %ld \\n\",decode_size);\n unsigned char * decoded_data = base64_decode(encoded_data, decode_size, &decode_size);\n printf(\"After size: %ld \\n\",decode_size);\n printf(\"Decoded Data is: %s \\n\",decoded_data);\n return 0;\n}\n"
},
{
"answer_id": 65175139,
"author": "Wirelessr",
"author_id": 5287769,
"author_profile": "https://Stackoverflow.com/users/5287769",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include \"b64.h\"\n\nint\nmain (void) {\n unsigned char *str = \"brian the monkey and bradley the kinkajou are friends\";\n char *enc = b64_encode(str, strlen(str));\n\n printf(\"%s\\n\", enc); // YnJpYW4gdGhlIG1vbmtleSBhbmQgYnJhZGxleSB0aGUga2lua2Fqb3UgYXJlIGZyaWVuZHM=\n\n char *dec = b64_decode(enc, strlen(enc));\n\n printf(\"%s\\n\", dec); // brian the monkey and bradley the kinkajou are friends\n free(enc);\n free(dec);\n return 0;\n}\n"
},
{
"answer_id": 70857728,
"author": "Jirka Justra",
"author_id": 2628312,
"author_profile": "https://Stackoverflow.com/users/2628312",
"pm_score": 0,
"selected": false,
"text": "/* Character list for url-safe base64 encoding */\n//char cl[]=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n/* Character list for url-unsafe base64 encoding */\nchar cl[]=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/**\n * @brief Encodes s_in into base64 and writes it to s_out.\n * @param s_in Pointer to input buffer.\n * @param s_out Pointer to output buffer.\n * @return Pointer to end of output buffer\n * @usage b64e(\"ABC\",buf);\n */\nchar *b64e(char *s_in, char *s_out){\n int i=0;\n if (s_in[i]==0) return s_out;\n if (s_in[i+1]==0 || s_in[i+2]==0) {\n *s_out++= b64_cl[ s_in[i] >> 2 ];\n if (s_in[i+1]==0) {\n *s_out++ = b64_cl[ ( ( s_in[i] & 0b000011 ) << 4 ) ];\n } else\n if (s_in[i+2]==0) {\n *s_out++ = b64_cl[ ( ( s_in[i] & 0b000011 ) << 4 ) + ( ( s_in[i+1] >> 4 ) & 0b001111 ) ];\n *s_out++ = b64_cl[ ( ( s_in[i+1] & 0b001111 ) << 2 ) ];\n }\n return s_out;\n }\n *s_out++ = b64_cl[ s_in[i] >> 2 ];\n *s_out++ = b64_cl[ ( (s_in[i] & 0b000011 ) << 4 ) + ( (s_in[i+1] >> 4) & 0b001111 ) ];\n *s_out++ = b64_cl[ ( (s_in[i+1] & 0b001111 ) << 2 ) + ( (s_in[i+2] >> 6) & 0b000011 ) ];\n *s_out++ = b64_cl[ ( s_in[i+2] & 0b111111 ) ];\n return b64e( s_in+3, s_out );\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,411 | <p>I want some of the items to be bold depending on a property of an object i'm putting into the listbox.</p>
<p>I think you can do it with changing templates but can't seem to find an example.</p>
<p>Thanks!</p>
| [
{
"answer_id": 342460,
"author": "a_hardin",
"author_id": 1497,
"author_profile": "https://Stackoverflow.com/users/1497",
"pm_score": 3,
"selected": false,
"text": "<ListView x:Name=\"Notes\" Margin=\"4,4,4,4\" \n ItemsSource=\"{Binding Path=CurrentCustomer.CustomerNotes}\"\n ItemTemplate=\"{DynamicResource CustomerNotesDataTemplate}\" \n Style=\"{DynamicResource ListViewStyle1}\" />\n <DataTemplate x:Key=\"CustomerNotesDataTemplate\">\n <Grid MinWidth=\"400\" Style=\"{DynamicResource NotesRowTriggers}\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"74\"/>\n <ColumnDefinition Width=\"400\"/>\n <ColumnDefinition Width=\"125\"/>\n <ColumnDefinition Width=\"Auto\"/>\n <ColumnDefinition Width=\"Auto\"/>\n </Grid.ColumnDefinitions>\n <TextBlock HorizontalAlignment=\"Stretch\" VerticalAlignment=\"Top\" Text=\"{Binding Path=NoteDate, Converter={StaticResource ShortDateConverter}}\" Margin=\"0,0,4,0\" />\n <TextBlock Text=\"{Binding Path=FreeNote}\" Grid.Column=\"1\" HorizontalAlignment=\"Stretch\" Margin=\"4,0,0,0\" Grid.ColumnSpan=\"1\" TextWrapping=\"Wrap\" />\n <TextBlock HorizontalAlignment=\"Left\" VerticalAlignment=\"Top\" Text=\"{Binding Path=NoteUser}\" Grid.Column=\"2\" Width=\"110\" d:LayoutOverrides=\"Width\" Margin=\"4,0,0,0\" Grid.ColumnSpan=\"1\" />\n <CheckBox HorizontalAlignment=\"Left\" IsChecked=\"{Binding Path=Highlight}\" VerticalAlignment=\"Top\" Content=\"Important\" Grid.Column=\"3\" Margin=\"4,0,4,0\"/>\n <CheckBox HorizontalAlignment=\"Left\" IsChecked=\"{Binding Path=Important}\" VerticalAlignment=\"Top\" Content=\"Alert\" Grid.Column=\"4\" Margin=\"4,0,4,0\"/>\n </Grid>\n </DataTemplate>\n <Style x:Key=\"NotesRowTriggers\" TargetType=\"{x:Type Grid}\">\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding Path=Important}\" Value=\"True\">\n <Setter Property=\"Background\">\n <Setter.Value>\n <SolidColorBrush Color=\"Red\" Opacity=\"0.3\" />\n </Setter.Value>\n </Setter>\n </DataTrigger>\n <DataTrigger Binding=\"{Binding Path=Highlight}\" Value=\"True\">\n <Setter Property=\"Background\">\n <Setter.Value>\n <SolidColorBrush Color=\"Red\" Opacity=\"0.6\" />\n </Setter.Value>\n </Setter>\n </DataTrigger>\n </Style.Triggers>\n</Style>\n"
},
{
"answer_id": 342503,
"author": "Donnelle",
"author_id": 28074,
"author_profile": "https://Stackoverflow.com/users/28074",
"pm_score": 3,
"selected": true,
"text": " <DataTemplate x:Key=\"BoldTemplate\">\n <TextBlock\n FontWeight=\"{Binding Path=Position, Converter={StaticResource IntToFontWeightConverter}}\"\n Text=\"{Binding Path=Name}\" \n />\n</DataTemplate> \n class IntToFontWeightConverter :IValueConverter \n{\n #region IValueConverter Members\n\n public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n if ((int)value == 1)\n {\n return FontWeights.Bold;\n }\n\n return FontWeights.Normal;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n}\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,434 | <p>I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.</p>
<p>I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file:</p>
<pre><code>sviewlog = logging.getLogger('MyApp.views.scans')
view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log')
view_log_handler.setLevel(logging.INFO)
view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'))
sviewlog.addHandler(view_log_handler)
</code></pre>
<p>Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this?</p>
<p>Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.</p>
| [
{
"answer_id": 343575,
"author": "Philippe F",
"author_id": 13618,
"author_profile": "https://Stackoverflow.com/users/13618",
"pm_score": 4,
"selected": false,
"text": "def init_logging():\n stdoutHandler = logging.StreamHandler( sys.stdout )\n stdoutHandler.setLevel( DEBUG )\n stdoutHandler.setFormatter( logging.Formatter( LOG_FORMAT_WITH_TIME ) )\n logging.getLogger( LOG_AREA1 ).addHandler( stdoutHandler )\n\nlogInitDone=False #global variable controlling the singleton.\nif not logInitDone:\n logInitDone = True\n init_logging()\n"
},
{
"answer_id": 343701,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 0,
"selected": false,
"text": "MyApp.views.scans __init__.py settings.py"
},
{
"answer_id": 345669,
"author": "Jeff",
"author_id": 33775,
"author_profile": "https://Stackoverflow.com/users/33775",
"pm_score": 6,
"selected": true,
"text": "# file logconfig.py\nif not hasattr(logging, \"set_up_done\"):\n logging.set_up_done=False\n\ndef set_up(myhome):\n if logging.set_up_done:\n return\n # set up your logging here\n # ...\n logging.set_up_done=True\n"
},
{
"answer_id": 346474,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "def init_logging():\n stdoutHandler = logging.StreamHandler( sys.stdout )\n stdoutHandler.setLevel( DEBUG )\n stdoutHandler.setFormatter( logging.Formatter( LOG_FORMAT_WITH_TIME ) )\n logger = logging.getLogger( LOG_AREA1 )\n if len(logger.handlers) < 1:\n logger.addHandler( stdoutHandler )\n from django.http import HttpResponse\nfrom magic import makeLogger\nfrom magic import getLogger\n\nmakeLogger('myLogName', '/path/to/myLogName.log')\ndef testLogger(request):\n logger = getLogger('myLogName')\n logger.debug('this worked')\n return HttpResponse('TEXT, HTML or WHATEVER')\n"
},
{
"answer_id": 3983086,
"author": "Tobu",
"author_id": 229753,
"author_profile": "https://Stackoverflow.com/users/229753",
"pm_score": 5,
"selected": false,
"text": "LOGGING"
},
{
"answer_id": 4933153,
"author": "Brad Shuttleworth",
"author_id": 533695,
"author_profile": "https://Stackoverflow.com/users/533695",
"pm_score": 2,
"selected": false,
"text": "from django.conf import settings\nfrom django.core.exceptions import MiddlewareNotUsed\nimport logging\nimport logging.handlers\nimport logging.config\n\n__all__ = ('LoggingConfigMiddleware',)\n\n\nclass LoggingConfigMiddleware:\n def __init__(self):\n '''Initialise the logging setup from settings, called on first request.'''\n if hasattr(settings, 'LOGGING'):\n logging.config.dictConfig(settings.LOGGING)\n elif getattr(settings, 'DEBUG', False):\n print 'No logging configured.'\n raise MiddlewareNotUsed('Logging setup only.')\n"
},
{
"answer_id": 5889904,
"author": "A Lee",
"author_id": 93370,
"author_profile": "https://Stackoverflow.com/users/93370",
"pm_score": 4,
"selected": false,
"text": "disable_existing_loggers propagate logger propagate=False 'loggers': {\n 'django': {\n 'handlers':['null'],\n 'propagate': True,\n 'level':'INFO',\n },\n 'django.request': {\n 'handlers': ['console'],\n 'level': 'ERROR',\n 'propagate': False,\n },\n 'project': {\n 'handlers': ['console', 'project-log-file'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'project.customapp': {\n 'handlers': ['console', 'customapp-log-file'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n}\n project.customapp propagate=False project"
},
{
"answer_id": 7658823,
"author": "aisbaa",
"author_id": 698512,
"author_profile": "https://Stackoverflow.com/users/698512",
"pm_score": 0,
"selected": false,
"text": "propagate == False"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33775/"
] |
342,435 | <p>Given an instance <code>x</code> of <code>Callable<T></code>, how can I run <code>x</code> in a separate process such that I can redirect the standard input and output of the process? For example, is there a way to build a <code>Process</code> from a <code>Callable</code>? Is there a standard <code>Executor</code> that gives control over input and output?</p>
<p>[UPDATE] It's not important that the <code>Callable</code> execute in a new process as opposed to a new thread. What I want is to put the <code>Callable</code> instance in a "harness", so that I can control its stdin/stdout. AFAIK, this calls for a new process.</p>
| [
{
"answer_id": 342476,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 3,
"selected": true,
"text": "import java.io.InputStream;\nimport java.io.PrintStream;\nimport java.util.concurrent.Callable;\n\n\npublic interface MyCallable<V> extends Callable<V> {\n void setStdIn(InputStream in);\n void setStdOut(PrintStream out); \n}\n import java.io.InputStream;\nimport java.io.PrintStream;\n\n\npublic class CallableTask implements MyCallable<Object> {\n\n private InputStream in = System.in;\n private PrintStream out = System.out;\n\n public void setStdIn(InputStream in) {\n this.in = in;\n }\n\n public void setStdOut(PrintStream out) {\n this.out = out;\n }\n\n public Object call() throws Exception {\n out.write(in.read());\n return null;\n }\n"
},
{
"answer_id": 343606,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "System.in/out/err System.set(In/Out/Err) ThreadLocal"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
342,437 | <p>Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This:</p>
<pre><code>if sys.version_info[:2] >= (2, 5):
from string import Template
else:
from our.compat.string import Template
</code></pre>
<p>or this</p>
<pre><code>try:
from string import Template
except ImportError:
from our.compat.string import Template
</code></pre>
<p>I know that either case is equally correct and works correctly but which one is preferable?</p>
| [
{
"answer_id": 342484,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 6,
"selected": true,
"text": "Template try: import elementtree.ElementTree as ET\nexcept ImportError:\n try: import cElementTree as ET\n except ImportError:\n try: import lxml.etree as ET\n except ImportError:\n import xml.etree.ElementTree as ET # Python 2.5 and up\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33786/"
] |
342,438 | <p>I have many requires and includes and i was wondering if there's something that can help me look at the whole of php code when a webpage is loaded. the reason i'm asking is that after fiddling with some code i cannot put any php code anymore as it will not be "sensed" by the compiler. like if i put anything inside the php tags </p>
<p>it won't give me an error saying the function doesn't exist.
Thanks to anyone taking the time reading this.</p>
| [
{
"answer_id": 342463,
"author": "benlumley",
"author_id": 39161,
"author_profile": "https://Stackoverflow.com/users/39161",
"pm_score": 3,
"selected": true,
"text": "error_reporting(E_ALL);\nini_set('display_errors', 1);\n"
},
{
"answer_id": 1738880,
"author": "mattbasta",
"author_id": 205229,
"author_profile": "https://Stackoverflow.com/users/205229",
"pm_score": 0,
"selected": false,
"text": "<?php ?>"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419730/"
] |
342,443 | <p>I work with an application which uses rather big numbers and I need to store data as an unsigned 64-bit integer. I prefer to just store it without worrying about bit manipulation or anything like that so different programs can use the data in different ways. </p>
| [
{
"answer_id": 342467,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": false,
"text": "NUMERIC scale integer NUMERIC precision NUMERIC 2**64 NUMERIC(19,0)"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
] |
342,455 | <p>I'm developing a script that involves creating an email contact and forwarding mail to that contact. Last part of the script is to automatically send a test email to the address to make sure the forwarding works.</p>
<p>So I use the following code:</p>
<pre><code>[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Core")
[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Outlook")
$olApp = New-Object Microsoft.Office.Interop.Outlook.ApplicationClass
$msg = $olApp.CreateItem(0)
$msg.Recipients.Add("me@example.com")
$msg.Subject = "test"
$msg.Body = "test"
$msg.Send()
</code></pre>
<p>I get an error at line 6: <code>"You cannot call a method on a null-valued expression."</code></p>
<p>I run the code at home, it works just fine. Difference: on a domain at work, using Exchange Server at work, using domain account at work.</p>
<p>I am using the same version of Powershell and Outlook on both machines. It's preferable to use Outlook to send the message because I already have Outlook open and that way the message will show up in my Sent Items folder.</p>
| [
{
"answer_id": 38535871,
"author": "nickdmax",
"author_id": 2524721,
"author_profile": "https://Stackoverflow.com/users/2524721",
"pm_score": 1,
"selected": false,
"text": "$msg.Recipients.Add(\"me@example.com\") $msg.Display() Add-Type -LiteralPath \"C:\\Program Files\\Microsoft\\Exchange\\Web Services\\2.2\\Microsoft.Exchange.WebServices.dll\"\n$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2010_SP1\n$service.AutodiscoverUrl(‘me@mydomain.com’, {$true})\n\n$msg = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)\n$msg.Subject = \"Sent from Powershell EWS\"\n$msg.Body = \"<html><body><h1>TESTING</h1><p>This is a test message sent from Powershell!</p></body></html>\"\n$msg.ToRecipients.Add(\"me@mydomain.com\")\n$msg.SendAndSaveCopy()\n $emptySecStr = New-Object System.Security.SecureString\n$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList \"NT AUTHORITY\\ANONYMOUS LOGON\", $emptySecStr\nSend-MailMessage -SmtpServer $smtpServerName -Credential $creds -From $sendingAddr -to $sendToArray -Cc $sendCCArray -BodyAsHtml -body $htmlBody -Subject $subject\n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456628/"
] |
342,468 | <p>I've been benchmarking the performance of a framework I'm writing in Perl and I'm getting a 50% decrease in requests per second over our existing codebase (some hit is understandable, because we're going from procedural spaghetti code to an OOP MVC framework).</p>
<p>The application is running under mod_perl, and I've added <a href="http://search.cpan.org/dist/Moose/" rel="noreferrer">Moose</a> and all my framework code into the <a href="http://perl.apache.org/docs/2.0/user/config/config.html#C_PerlPostConfigRequire_" rel="noreferrer">startup.pl script</a>, which itself doubled my requests per second amount. I'm looking to further enhance this number to get it as close as possible to the existing amount. The argument is there that this is premature optimisation, but there are a couple of glaring inefficiencies that I'd like to fix and see how it effects performance.</p>
<p>Like most frameworks, I have a configuration file and a dispatcher. The config part is handled by <a href="http://search.cpan.org/dist/Config-General/" rel="noreferrer">Config::General</a>, so a bit of IO and parsing is involved to get my config file loaded into the app. The biggest problem I see here is that I'm doing this for EVERY REQUEST that comes in! </p>
<p>Running Devel::Dprof on my app points to Config::General::BEGIN and a bunch of related IO modules as one of the major slow points that isn't Moose. So what I'd like to do, and what makes a lot more sense in hindsight is take advantage of mod_perl's persistence and the startup.pl compilation stuff to only do the work to load in the config file once - when the server starts.</p>
<p>The problem is that I'm not too familiar with how this would work. </p>
<p>Currently each project has a PerlHandler bootstrapping class which is pretty lean and looks like this:</p>
<pre><code>use MyApp;
MyApp->new(config_file => '/path/to/site.config')->run();
</code></pre>
<p>MyApp.pm inherits from the framework Project module, which has this code:</p>
<pre><code>my $config = Config::General->new(
-ConfigFile => $self->config_file,
-InterPolateVars => 1,
);
$self->config({$config->getall});
</code></pre>
<p>To only do this at compile time, both my bootstrap and Project base modules will have to change (I think), but I'm pretty unsure as to what changes to make and still keep the code nice and lean. Can anyone point me in the right direction here? </p>
<p><strong>UPDATE</strong></p>
<p>I tried the BEGIN BLOCK in each project module approach as described by ysth in his answer. So I now have:</p>
<pre><code>package MyApp::bootstrap;
use MyApp;
my $config;
BEGIN
{
$config = {Config::General->new(...)->getall};
}
sub handler { ..etc.
MyApp->new(config => $config)->run();
</code></pre>
<p>This quick change alone gave me a <strong>50%</strong> increase in requests per second, confirming my thoughts that the config file was a major bottleneck worth fixing. The benchmark figure on our crotchety old dev machine is 60rps, and my framework has went from 30rps to 45rps with this change alone. For those who say Moose is slow and has a compile time hit.. I got the same (50%) increase when compiling all my Moose code at start-up as I did from pre-compiling my config file.</p>
<p>The only problem I have now is that this violates the DRY principal since the same Config::General->new code is in every BEGIN block with only the path to the config file differing. I have a few different strategies to limit this, but I just wanted to post the results of this change.</p>
| [
{
"answer_id": 342482,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 4,
"selected": true,
"text": "# this code goes at file scope\nmy $config;\nBEGIN {\n $config = { Config::General->new( ... )->getall }\n}\n\n# when creating a new instance\n$self->config( $config );\n"
},
{
"answer_id": 342572,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 1,
"selected": false,
"text": "PerlRequire handler.pl\n<FilesMatch \"\\.mhtml$\">\n SetHandler perl-script\n PerlHandler YourModule::Mason\n</FilesMatch>\n handler"
},
{
"answer_id": 386525,
"author": "mjy",
"author_id": 2128202,
"author_profile": "https://Stackoverflow.com/users/2128202",
"pm_score": 0,
"selected": false,
"text": "use vars qw ($config);\n# ...\n$config = Config::General->new( ... )->getall\n unless blessed($config); # add more suitable test here\n"
},
{
"answer_id": 1138688,
"author": "Danny",
"author_id": 26630,
"author_profile": "https://Stackoverflow.com/users/26630",
"pm_score": 2,
"selected": false,
"text": "$config package Foo_Config;\nuse English qw(-no_match_vars);\nsub import {\n my ($self, @cfg) = @ARG;\n my $call_pkg = caller;\n my $config = {Config::General->new(@cfg)->getall};\n do{ # this will create the $config variable in the calling package.\n no strict 'refs';\n ${$call_pkg . '::config'} = $config;\n };\n return;\n}\n\npackage MyApp;\n# will execute Foo_Config->import('/path/to/site.config') at compile time.\nuse Foo_Config '/path/to/site.config'; \n"
}
] | 2008/12/04 | [
"https://Stackoverflow.com/questions/342468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404/"
] |
342,509 | <p>Is it possible to read the data in the php $_SESSION array in the .htaccess file in Apache? So say I have the following:</p>
<pre><code>$_SESSION['foo'] = 'bar';
</code></pre>
<p>could I then in .htaccess do something like:</p>
<pre><code>RewriteRule bla.png folder/{the php session var foo}/file.png
</code></pre>
<p>Is that possible?</p>
<p>I already have a working workaround but if this is possible it would be way nicer.</p>
| [
{
"answer_id": 25286371,
"author": "jave.web",
"author_id": 1835470,
"author_profile": "https://Stackoverflow.com/users/1835470",
"pm_score": 4,
"selected": false,
"text": ".ht access .htaccess bla.php <?php\n session_start();\n header(\"Location: folder/\".$_SESSION['foo'].\"/file.png\");\n exit();\n?>\n bla.png bla.php if/elseif/else case $url = \"example.com/bla.png?foo=\".$_SESSION['foo']; .htaccess $url = \"example.com/folder/\".$_SESSION['foo'].\"/file.png\"; HTTP_COOKIE foo RewriteCond %{HTTP_COOKIE} ^(.*)foo=([-_a-zA-Z0-9]+)(.*)$ [NC] \nRewriteRule ^bla.png$ /folder/%2/file.png [R=307,NC,L] \n#possibly use 302 if you like dinosaurs\n HTTP_COOKIE HTTP_COOKIE name=value; name2=value2\n HTTP_SESSION HTTP_SESSION RewriteMap SSL_SESSION_ID $_GET/$_POST"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35197/"
] |
342,518 | <p><em>Problem:</em> There are a bunch of .lnk files on the C drive that point to the J: drive, but the J: drive is gone, and the P: drive has replaced it. Various tricks have been done to get the .lnk files to still work anyway, but it's getting annoying, and it's time to just fix the things.</p>
<p>Using Ruby, Python, WSH.JScript or Perl, can you iterate through an entire directory tree of .lnk files and change them so they point to p:/* instead of j:/*? How would you go about it?</p>
<p><em>Note:</em> This is not a total unknown to me, but I ask the question anyway because the API for managing .lnk files in the ways I've found so far seem too cumbersome to be the best known way of doing this. This is one of those desparate "there's got to be a better way" type questions.</p>
| [
{
"answer_id": 1211860,
"author": "Program.X",
"author_id": 76037,
"author_profile": "https://Stackoverflow.com/users/76037",
"pm_score": 2,
"selected": false,
"text": " dim onlyFolder\n Set onlyFolder =fso.GetFolder(\"C:\\\") \n SearchFolder onlyFolder\n\n' for each aDrive in fso.Drives \n' if aDrive.DriveType = 2 then\n' SearchFolder aDrive.RootFolder\n' end if\n' next\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42223/"
] |
342,528 | <p>Can all .NET exception objects be serialized?</p>
| [
{
"answer_id": 342534,
"author": "Matt Briggs",
"author_id": 10771,
"author_profile": "https://Stackoverflow.com/users/10771",
"pm_score": 2,
"selected": false,
"text": "System.Exception ISerializable"
},
{
"answer_id": 342541,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 3,
"selected": false,
"text": "System.Exception ISerializable (SerializationInfo,StreamingContext)"
},
{
"answer_id": 13732522,
"author": "drwatsoncode",
"author_id": 1874682,
"author_profile": "https://Stackoverflow.com/users/1874682",
"pm_score": 4,
"selected": false,
"text": "ctor(SerializationInfo, StreamingContext) class MyNewException : Exception { }\n MyNewField class MyNewException : Exception \n{\n public MyNewField { get; set; }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
342,529 | <p>Anybody ever had the error "Installation of the "Microsoft Expression Web 2" product has reported the following error: -2147024873.. " when trying to install Microsoft Expression Web 2 or Microsoft Expression Studio? This is the error I'm getting, but I can't figure out what the problem is. I have no beta or RC or pre beta software installed. I'm using office 2003, already have silverlight and .net 1 ,2 3, 3.5 frameworks installed. I also have 3.6g hd space free.</p>
<p>Errors I found in the log file are as follows:</p>
<pre><code>LIS: wait for package "{90120000-0115-0409-0000-0000000FF1CE}" to complete caching<br>
LIS failed to cache download "{90120000-0115-0409-0000-0000000FF1CE}-C" resource "Setup.xml". Cache Error 0x80070017<br>
Source Resolution aborted<br>
LIS: start caching file "Setup.xml"<br>
LIS failed to cache download "{90120000-0115-0409-0000-0000000FF1CE}-C" resource "branding.xml". Cache Error 0x80070017<br>
Source Resolution aborted<br>
LIS: start caching file "branding.xml"<br>
LIS failed to cache download "{90120000-0115-0409-0000-0000000FF1CE}-C" resource "ShellUI.MST". Cache Error 0x80070017<br>
Source Resolution aborted<br>
LIS: start caching file "ShellUI.MST"<br>
LIS failed to cache download "{90120000-0115-0409-0000-0000000FF1CE}-C" resource "osetupui.dll". Cache Error 0x80070017<br>
Source Resolution aborted<br>
LIS: start caching file "osetupui.dll"
LIS failed to cache download "{90120000-0115-0409-0000-0000000FF1CE}-C" resource "Setup.xml". Cache Error 0x80070017<br>
Source Resolution aborted<br>
Log level changed from: Standard to: Verbose<br>
Error: LIS: Failed to cache download "{90120000-0115-0409-0000-0000000FF1CE}-C" resource "Setup.xml". HResult: 0x80070017. <br>
Rolling back chain<br>
12/04/2008 16:11:48 Rolling back package: OfficeMUI.en-us<br>
There appears to be no rollback work to do for package: OfficeMUI.en-us path: C:\Documents and Settings\chaj17\Local Settings\Temp\XSetup_Web_2008_12_4_16_1_21\438d1ac8_d88e_46eb_ba69_11fef34cce74\Office.en-us\OfficeMUI.MSI<br>
Stopping running ose<br>
LIS: start uncaching for download "{90120000-0010-0409-0000-0000000FF1CE}-C"<br>
LIS: finished uncaching for download "{90120000-0010-0409-0000-0000000FF1CE}-C"<br>
LIS: start uncaching for download "{90120000-002C-0409-0000-0000000FF1CE}-C"<br>
LIS: finished uncaching for download "{90120000-002C-0409-0000-0000000FF1CE}-C"<br>
LIS: start uncaching for download "{90120000-0045-0000-0000-0000000FF1CE}-C"<br>
LIS: finished uncaching for download "{90120000-0045-0000-0000-0000000FF1CE}-C"<br>
LIS: start uncaching for download "{90120000-0045-0409-0000-0000000FF1CE}-C"<br>
LIS: finished uncaching for download "{90120000-0045-0409-0000-0000000FF1CE}-C"<br>
LIS: start uncaching for download "{90120000-0115-0409-0000-0000000FF1CE}-C"<br>
LIS: finished uncaching for download "{90120000-0115-0409-0000-0000000FF1CE}-C"<br>
Stopping running ose<br>
Not showing completion dialog because it was not requested.<br>
Catalyst execution finished: 12/04/2008 16:11:52. Return code: -2147024873.<br>
PERF: TickCount=3954562 Name=RunSetup Description=End function<br>
=========================================================================<br>
Error: Installation of the "Microsoft Expression Web 2" product has reported the following error: -2147024873.<br>
Info: Config_Products_InstallNew: End installation of new product: Microsoft Expression Web 2<br>
Error: Config_Products_Install: Installation of Product Microsoft Expression Web 2 (failed): Installation of the "Microsoft Expression Web 2" product has reported the following error: -2147024873. Stack: at XSetup.OfficePackage.ConfigureNewInstall(Product product) at XSetup.Product.ConfigureNewProduct()<br>
Info: Config_Products_InstallNew: End installation of new product: Microsoft Expression Web 2<br>
Info: Expecting to find local release notes at 'http://go.microsoft.com/fwlink/?LinkId=114830'.<br>
Error: XSetup_DoTasks:: Installation of the "Microsoft Expression Web 2" product has reported the following error: Installation of the "Microsoft Expression Web 2" product has reported the following error: -2147024873.. Stack: at XSetup.XSetupSession.OnDoTasksThreadDoWork(Object sender, DoWorkEventArgs e)<br>
Error: Installation of the "Microsoft Expression Web 2" product has reported the following error: Installation of the "Microsoft Expression Web 2" product has reported the following error: -2147024873..<br>
Info: End Setup session<br>
-------------------------------------------------------------------------------------------------<br>
Error: XSetup_DoTasks:: Installation of the "Microsoft Expression Web 2" product has reported the following error: Installation of the "Microsoft Expression Web 2" product has reported the following error: -2147024873.. Stack: at XSetup.XSetupSession.OnDoTasksThreadDoWork(Object sender, DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)<br>
</code></pre>
| [
{
"answer_id": 342534,
"author": "Matt Briggs",
"author_id": 10771,
"author_profile": "https://Stackoverflow.com/users/10771",
"pm_score": 2,
"selected": false,
"text": "System.Exception ISerializable"
},
{
"answer_id": 342541,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 3,
"selected": false,
"text": "System.Exception ISerializable (SerializationInfo,StreamingContext)"
},
{
"answer_id": 13732522,
"author": "drwatsoncode",
"author_id": 1874682,
"author_profile": "https://Stackoverflow.com/users/1874682",
"pm_score": 4,
"selected": false,
"text": "ctor(SerializationInfo, StreamingContext) class MyNewException : Exception { }\n MyNewField class MyNewException : Exception \n{\n public MyNewField { get; set; }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
342,532 | <p>I'm trying to animate a block level element using jQuery. The page loads with the element styled with <code>display: none</code>. Id like it to <code>slideDown</code> whilst transparent and then <code>fadeIn</code> the content using the callback, however <code>slideDown</code> appears to set the visibility to full before <code>fadeIn</code> is called, resulting in the content being visible during the <code>slideDown</code> animation.</p>
<p>Does anyone know of a way to accomplish this?</p>
| [
{
"answer_id": 342569,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 0,
"selected": false,
"text": "$('#hiddenElement').css(\"opacity\", 0).slideDown().animate({opacity:1})\n"
},
{
"answer_id": 342574,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "fadeIn slideDown fadeIn slideDown $('div').hide(); // make sure you hide both container/content\n\n$('#container').slideDown('slow', function() {\n $('#content').fadeIn('slow'); // fade in of content happens after slidedown\n});\n <div id=\"container\">\n <div id=\"content\">stuff</div>\n</div>\n"
},
{
"answer_id": 14914793,
"author": "Aaron Hoffman",
"author_id": 47226,
"author_profile": "https://Stackoverflow.com/users/47226",
"pm_score": 0,
"selected": false,
"text": "li ul slideDown fadeIn .hide() slideDown() li ul $(content).hide().css(\"opacity\", 0).appendTo(\"#ListItems\").slideDown(500, function () { $(this).animate({ \"opacity\": 1 }, { queue: false, duration: 500 }); });\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199/"
] |
342,543 | <p>I'm using .net's PrintPreviewDialog and whenever it's generating a preview, it locks up my GUI in the background and makes it look like it has crashed until the preview is finished. Seeing how the .net's page progress window that pops up isn't a dialog, the back ground can be selected which then comes to the front in a half drawn, locked up manner. This also happens when the user clicks the actual "Print" button on the preview dialog, and when I just run PrintDocument.Print(). Is there an easy way to modify the following code to stop the GUI from hanging when the user is waiting for .net to draw the print pages:</p>
<pre><code>//just showing a preview, hangs up background GUI on generating the preview
// and when user prints straight from the preview
this.printPreviewDialog.ShowDialog(this);
//just trying to print a .net PrintDocument class, GUI hangs in background
// when .net is drawing the pages
this.printDocument.Print();
</code></pre>
| [
{
"answer_id": 373428,
"author": "Matthew Savage",
"author_id": 18434,
"author_profile": "https://Stackoverflow.com/users/18434",
"pm_score": 2,
"selected": false,
"text": "ThreadStart ts = () =>\n{\n printDocument.Print();\n\n // Start the message loop to prevent the thread from finishing straight away.\n System.Windows.Forms.Application.Run();\n};\nThread t = new Thread(ts);\nt.SetApartmentState(ApartmentState.STA);\nt.Start();\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24571/"
] |
342,546 | <p>What would be the fastest way, to merge 2 XML files, so I would locate a node in first one, empty it, take all children from the same tag (same node) in second XML and put it in the first one.</p>
| [
{
"answer_id": 342564,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 0,
"selected": false,
"text": "try\n{\n XmlTextReader xmlreader1 = new XmlTextReader(\"C:\\\\Books1.xml\");\n XmlTextReader xmlreader2 = new XmlTextReader(\"C:\\\\Books2.xml\");\n\n DataSet ds = new DataSet();\n ds.ReadXml(xmlreader1);\n DataSet ds2 = new DataSet();\n ds2.ReadXml(xmlreader2);\n ds.Merge(ds2);\n ds.WriteXml(\"C:\\\\Books.xml\");\n Console.WriteLine(\"Completed merging XML documents\");\n}\ncatch (System.Exception ex)\n{\n Console.Write(ex.Message);\n}\nConsole.Read(); \n"
},
{
"answer_id": 342817,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 3,
"selected": true,
"text": "XElement var nodes1 = XDocument.Parse(file1).Element(\"test\").Element(\"nodes\");\nvar nodes2 = XDocument.Parse(file2).Element(\"test\").Element(\"nodes\");\n\nnodes1.Nodes().Remove();\nnodes1.Add(nodes2.Nodes());\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24839/"
] |
342,554 | <p>Is it possible to create an HTML email signature for <strong>Outlook 2003</strong> or above that doesn't reference external images?</p>
<p>That is, using those special "cid" reference but embed the image itself in the signature and not on the file system or network.</p>
<p>This is for an web application that generates a "standard" email signature based on various input from a user. It has worked fine so far with a single "embedded" image. But a new feature is going to require the possible addition of multiple tiny images.</p>
<p>Getting to user to save one email signature template and one image to the user's machine is about the limit of what I'd like to require of the user. But forcing the user to save multiple images seem to be pushing things a little to far in my opinion.</p>
<p>So my problem is trying to embed the images into without having to inconvenience the user with multiple downloads first.</p>
| [
{
"answer_id": 343276,
"author": "Oliver Giesen",
"author_id": 9784,
"author_profile": "https://Stackoverflow.com/users/9784",
"pm_score": 4,
"selected": true,
"text": "file:/// cid: <img src=\"file://///ServerName/ShareName/FileName.png\" />\n"
},
{
"answer_id": 2458592,
"author": "Adam Patterson",
"author_id": 295219,
"author_profile": "https://Stackoverflow.com/users/295219",
"pm_score": 3,
"selected": false,
"text": "<a href=\"http://www.britblog.com/\">\n <img\n src=\"data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPbWLrc/jDKSVe4OOvNu/9gqA /..../NcV9/j5+g4JADs=\"\n alt=\"Signature\" width=\"80\" height=\"15\">\n</a>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19377/"
] |
342,556 | <p>I am experimenting with the new multiprocessing module in Python 2.6. I am creating several processes each with its own multiprocessor.JoinableQueue instance. Each process spawns one or more worker threads (subclasses of threading.Thread) which share the JoinableQueue instance (passed in through each Thread's <code>__init__</code> method). It seems to generally work but occasionally and unpredictably fails with the following error:</p>
<pre><code> File "C:\Documents and Settings\Brian\Desktop\testscript.py", line 49, in run
self.queue.task_done()
File "C:\Python26\lib\multiprocessing\queues.py", line 293, in task_done
raise ValueError('task_done() called too many times')
ValueError: task_done() called too many times
</code></pre>
<p>My Queue get() and task_done() calls are right after each other so they should be equal. Anecdotally this seems to occur only when the work done between the get() and the task_done() is VERY quick. Inserting a small <code>time.sleep(0.01)</code> seems to alleviate the problem.</p>
<p>Any ideas what is going on? Can I use a multiprocessor Queue with threads instead of the more traditional (Queue.Queue)?</p>
<p>Thanks!</p>
<p>-brian</p>
| [
{
"answer_id": 342586,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "from multiprocessing import Process, Queue\n\ndef f(q):\n q.put([42, None, 'hello'])\n\n if __name__ == '__main__':\n q = Queue()\n p = Process(target=f, args=(q,))\n p.start()\n print q.get() # prints \"[42, None, 'hello']\"\n p.join()\n"
},
{
"answer_id": 342713,
"author": "JV.",
"author_id": 33612,
"author_profile": "https://Stackoverflow.com/users/33612",
"pm_score": 2,
"selected": false,
"text": ">>> from processing.managers import BaseManager, CreatorMethod\n>>> import Queue\n>>> queue = Queue.Queue()\n>>> class QueueManager(BaseManager):\n... get_proxy = CreatorMethod(callable=lambda:queue, typeid='get_proxy')\n...\n>>> m = QueueManager(address=('foo.bar.org', 50000), authkey='none')\n>>> m.serve_forever()\n >>> from processing.managers import BaseManager, CreatorMethod\n>>> class QueueManager(BaseManager):\n... get_proxy = CreatorMethod(typeid='get_proxy')\n...\n>>> m = QueueManager.from_address(address=('foo.bar.org', 50000), authkey='none')\n>>> queue = m.get_proxy()\n>>> queue.put('hello')\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43233/"
] |
342,576 | <p>There are a number of run-time differences in compatible code between these two versions of .NET.</p>
<p>Here is a list of differences so far:</p>
<ul>
<li>Graphics.DrawRectangle - differs by 1 pixel</li>
<li>Graphics.DrawString - Loses the line wrap if used with a StringFormat with both StringAlignments set to Center.</li>
<li>Most file operations - compact framework needs a full path</li>
<li><a href="http://blog.opennetcf.com/ctacke/CommentView,guid,80a1fabe-e206-4b93-a0e1-25bfc2185959.aspx" rel="noreferrer">The status of a socket after BeginAccept</a></li>
<li>(In WinCE 5 at least) you cannot use a socket to send data synchronously with a timeout (without is okay but you risk hangs)</li>
<li>Bitmaps (all Image-derived classes really) behave differently in <a href="http://blog.opennetcf.com/ctacke/2006/08/22/BitmapsInTheCompactFramework.aspx" rel="noreferrer">how their resources are cleaned up</a>. - ctacke</li>
<li>The default font for labels and treeviews in the CF was larger - Darwyn</li>
<li>When a label is disabled in CF it is just grayed out (the full .net framewark outlines the text with another color) - Darwyn</li>
<li>Assembly paths are returned in a different format on the desktop from System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase - Qwertie</li>
</ul>
<p>Do we also have any more to add?</p>
| [
{
"answer_id": 391900,
"author": "Qwertie",
"author_id": 22820,
"author_profile": "https://Stackoverflow.com/users/22820",
"pm_score": 1,
"selected": false,
"text": "System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase\n System.Reflection.Assembly.GetExecutingAssembly().Location\n public static string AppFolder\n{\n get {\n #if !WindowsCE && !PocketPC\n string exeFile = System.Reflection.Assembly.GetExecutingAssembly().Location;\n #else\n // This returns a normal path under CE, but gives a URL (file:/...) on the desktop\n string exeFile = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;\n if (exeFile.StartsWith(\"file:///\"))\n exeFile = exeFile.Substring(\"file:///\".Length);\n #endif\n return System.IO.Path.GetDirectoryName(exeFile);\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143/"
] |
342,577 | <p>If I have an NSString with a text file in it, how do I get an NSArray of NSString with each NSString containing a line of the file.</p>
<p>In 10.5 I did this:</p>
<pre><code>NSArray* lines = [str componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
</code></pre>
<p>But that doesn't work in 10.4, and my program needs to work in 10.4.</p>
<p>As well, it needs to work with \r, \n and \r\n line endings. </p>
| [
{
"answer_id": 342595,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 4,
"selected": true,
"text": "unsigned length = [string length];\nunsigned paraStart = 0, paraEnd = 0, contentsEnd = 0;\nNSMutableArray *array = [NSMutableArray array];\nNSRange currentRange;\nwhile (paraEnd < length)\n{\n [string getParagraphStart:¶Start end:¶End\n contentsEnd:&contentsEnd forRange:NSMakeRange(paraEnd, 0)];\n currentRange = NSMakeRange(paraStart, contentsEnd - paraStart);\n [array addObject:[string substringWithRange:currentRange]];\n}\n"
},
{
"answer_id": 342673,
"author": "Rich Catalano",
"author_id": 4103,
"author_profile": "https://Stackoverflow.com/users/4103",
"pm_score": 2,
"selected": false,
"text": " NSString * fileContents = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];\n NSMutableArray * fileLines = [[NSMutableArray alloc] initWithArray:[fileContents componentsSeparatedByString:@\"\\r\\n\"] copyItems: YES];\n"
},
{
"answer_id": 342684,
"author": "Heng-Cheong Leong",
"author_id": 6904,
"author_profile": "https://Stackoverflow.com/users/6904",
"pm_score": 3,
"selected": false,
"text": "\\r \\n \\n\\n \\n componentsSeparatedByString:@\"\\n\""
},
{
"answer_id": 34217380,
"author": "Vineet Choudhary",
"author_id": 4558367,
"author_profile": "https://Stackoverflow.com/users/4558367",
"pm_score": 3,
"selected": false,
"text": "enumerateLinesUsingBlock: [yourString enumerateLinesUsingBlock:^(NSString * _Nonnull line, BOOL * _Nonnull stop) {\n //line\n}];\n - (void)enumerateLinesUsingBlock:(void (^)(NSString *line,\n BOOL *stop))block\n block line stop OS 10.6 iOS 4.0"
},
{
"answer_id": 43508118,
"author": "siburb",
"author_id": 994976,
"author_profile": "https://Stackoverflow.com/users/994976",
"pm_score": 0,
"selected": false,
"text": "enumerateSubstringsInRange: NSStringEnumerationByLines NSStringEnumerationByParagraphs [myString enumerateSubstringsInRange:NSMakeRange(0, myString.length) options:NSStringEnumerationByLines | NSStringEnumerationByParagraphs usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {\n\n}];\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39138/"
] |
342,578 | <p>How can the OpenFileDialog View Menu be set to Detail View?</p>
| [
{
"answer_id": 342611,
"author": "DaEagle",
"author_id": 43024,
"author_profile": "https://Stackoverflow.com/users/43024",
"pm_score": 0,
"selected": false,
"text": "Dim OpenFileDialog1 As New OpenFileDialog\nSendKeys.Send(\"{tab}{tab}{tab}{tab}{tab}{right}{right}{down}{up}{enter}\")\nOpenFileDialog1.ShowDialog()\n"
},
{
"answer_id": 342618,
"author": "Fredou",
"author_id": 40868,
"author_profile": "https://Stackoverflow.com/users/40868",
"pm_score": 2,
"selected": false,
"text": "DefaultViewMode:\n\nThis property lets you choose which view the OpenFileDialog should \nstart in; by default, it opens using the “Details view”. Here you \ncan specify a different default view like Icons, List, Thumbnail, Detail, etc\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964/"
] |
342,579 | <p>A few quick searches discovered that I'm obviously <a href="http://morethanseven.net/2008/10/13/unit-testing-css-looking-solution/" rel="noreferrer">not the</a> <a href="http://www.thoughtballoon.co.uk/blog/2008/11/11/example-css-style-guide-unit-testing-for-css" rel="noreferrer">first person</a> to have the thought <strong>"Can I unit test my CSS?"</strong>. </p>
<p>I'm wondering if anyone here has taken on CSS Unit Testing successfully? If you've tried and failed, or just have your own theories, please tell me why it (apparently) hasn't been done yet?</p>
| [
{
"answer_id": 22340521,
"author": "boudu",
"author_id": 2608997,
"author_profile": "https://Stackoverflow.com/users/2608997",
"pm_score": 2,
"selected": false,
"text": "Ex : base.css / form.css / article.css etc.\n LESS SASS"
},
{
"answer_id": 24869064,
"author": "Heroselohim",
"author_id": 1372973,
"author_profile": "https://Stackoverflow.com/users/1372973",
"pm_score": 2,
"selected": false,
"text": ".test1\n.test2\n#test3\n CSSAttribute1, CSSFinalValue1\nCSSAttribute2, CSSFinalValue2\nCSSAttribute3, CSSFinalValue3\n addCSSUnitTest(\".test1, .test2, #test3\", \"margin-left: 4px; font-size: 8px\");\n"
},
{
"answer_id": 37224868,
"author": "tomekwi",
"author_id": 2816199,
"author_profile": "https://Stackoverflow.com/users/2816199",
"pm_score": 1,
"selected": false,
"text": "getBoundingClientRect getComputedStyle"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
342,590 | <p>Has anyone implemented sorting a list of domain names?</p>
<p>I have seen some applications sort them as flat strings, but the problem is that you end up scattering all the related hosts in a domain:</p>
<p>a.me.com
a.you.com
b.me.com
b.you.com</p>
<p>So, the basic logic I came up with reverse the order of the labels, then sort.</p>
<p>FQDNs of one label should be treated as hostnames, and probably sorted separately, maybe at the top.</p>
<p>Ideally I am looking for javascript and java versions.</p>
<p>I also don't know if this design works well for the newer internationalized domain names.</p>
| [
{
"answer_id": 342667,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 2,
"selected": false,
"text": "hosts = [\"a.foo.com\", \"b.foo.com\", \"foo.com\", \"c.bar.com\"]\n\nsplit_hosts = []\nfor h in hosts:\n segments = h.split('.')\n segments.reverse()\n split_hosts.append(segments)\n\nsplit_hosts.sort()\nfor segments in split_hosts:\n segments.reverse()\n print \".\".join(segments)\n c.bar.com\nfoo.com\na.foo.com\nb.foo.com\n"
},
{
"answer_id": 342768,
"author": "Stobor",
"author_id": 43452,
"author_profile": "https://Stackoverflow.com/users/43452",
"pm_score": 2,
"selected": false,
"text": "\nhosts = new Array( \"a.foo.com\", \"b.foo.com\", \"foo.com\", \"c.bar.com\" );\n\n//print(\"Unsorted:\");\n//for (host in hosts )\n// print(hosts[host]);\n\nsorted_hosts = new Array();\nsplit_hosts = new Array();\n\nfor(h in hosts)\n{\n segments = hosts[h].split('.');\n segments.reverse(); \n split_hosts.push(segments);\n}\n\nsplit_hosts.sort()\n\nfor(h in split_hosts)\n{\n split_hosts[h].reverse()\n sorted_hosts.push(split_hosts[h].join(\".\"))\n}\n\n//print(\"Sorted:\");\n//for (host in sorted_hosts )\n// print(sorted_hosts[host]);\n"
},
{
"answer_id": 4785975,
"author": "cmanley_nl",
"author_id": 587984,
"author_profile": "https://Stackoverflow.com/users/587984",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/perl -w\nuse strict;\n\nmy @hosts = qw(\n bar.org\n a.foo.com\n b.foo.com\n foo.com\n c.bar.com\n);\n\nprint join(\"\\n\", sort {\n $a = lc($a);\n $b = lc($b);\n if ($a eq $b) {\n return 0;\n }\n my @a = reverse(split(/\\./, $a));\n my @b = reverse(split(/\\./, $b));\n my $max = (scalar(@a), scalar(@b))[@a < @b];\n for (my $i=0; $i < $max; $i++) {\n if (($i < @a) && ($i < @b)) {\n if (my $c = $a[$i] cmp $b[$i]) {\n return $c;\n }\n }\n else {\n return scalar(@a) <=> scalar(@b);\n }\n }\n return 0;\n} @hosts) . \"\\n\";\n"
},
{
"answer_id": 44053962,
"author": "Matthias Simon",
"author_id": 306692,
"author_profile": "https://Stackoverflow.com/users/306692",
"pm_score": 0,
"selected": false,
"text": "function* reverseIterateParts(domain) {\n let currentEnd = domain.length;\n for (let index = currentEnd-1; index >= -1; index--) {\n if (index == -1 || domain[index] == '.') {\n yield domain.substring(index + 1, currentEnd);\n currentEnd = index;\n }\n }\n}\n\narrayOfDomainNames.sort((domainA, domainB) => {\n let partsOfA = reverseIterateParts(domainA);\n let partsOfB = reverseIterateParts(domainB);\n while (true) {\n let partA = partsOfA.next();\n let partB = partsOfB.next();\n\n if (partA.done) {\n if (partB.done) {\n return 0;\n }\n return -1;\n }\n if (partB.done) {\n return 1;\n }\n if (partA.value > partB.value) {\n return 1;\n }\n if (partA.value < partB.value) {\n return -1;\n }\n }\n});\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910/"
] |
342,596 | <p>I have a very simple problem and a solution that will work, but I'm looking for a simpler one.</p>
<p>I'd like to prevent rows from being added to a database when multiple values equal existing values. For example, if a2=a1 AND b2=b1 then the data gets rejected. If only a2=a1 or only b2=b1 it is allowed. Basically I want it to act like a primary key that requires both values to match.</p>
<p>I know I can do this through validation before I write to the database--ex. select * where a='a2' and b='b2' and then avoid writing new data when I get results. What I'd rather do is enable a MySQL setting, like primary key, that will block data like this automatically. </p>
<p>I'm not very familiar with MySQL outside of basic features, so apologies if this is trivially easy. Googling for all sorts of things around unique index and primary key did not help.</p>
| [
{
"answer_id": 342607,
"author": "gcores",
"author_id": 40256,
"author_profile": "https://Stackoverflow.com/users/40256",
"pm_score": 4,
"selected": true,
"text": "CREATE UNIQUE INDEX index_name ON table(col1, col2);\n"
},
{
"answer_id": 342615,
"author": "Stewart Johnson",
"author_id": 6408,
"author_profile": "https://Stackoverflow.com/users/6408",
"pm_score": 0,
"selected": false,
"text": "CONSTRAINT"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30098/"
] |
342,609 | <p>I'm writing what will be an intranet application, and one of its features is roughly analogous to content voting - not unlike what SO, Amazon, and many other sites do.</p>
<p>Assuming each votable piece of content has a unique ID, and each user (they're authenticated) has a unique ID, the easiest way would seem to be to have a "votes" table...</p>
<pre><code>ContentID int
UserID int
VoteValue int
</code></pre>
<p>But this creates one row per vote - with millions of pieces of content and tens of thousands of users, that table's gonna be huge huge huge. Is this the best way to do it? I mean, if an int takes 4 bytes, each row takes 12 bytes. If a million pieces of content get a hundred votes, that's 400MB+ in storage, yeah? Seems... like a lot :). Even if the VoteValue is a tinyint (which is probably fine) and only 1 byte, that's still a couple hundred megabytes in the table. I mean sheesh.</p>
<p>Is there a smarter way? Should I store this "votes" table in a separate database (ignoring potential data integrity issues) to partition it from the "main" data in terms of storage and performance?</p>
<p>(I do realize that in today's world 400MB ain't a ton - but it seems like a LOT just to store votes, yeah?)</p>
| [
{
"answer_id": 342825,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": " `vote_id` int(11) NOT NULL default '0',\n `voter_user` int(11) NOT NULL default '0',\n `voted_user` int(11) default NULL,\n `weight` int(11) NOT NULL default '0',\n `votetime` datetime NOT NULL default '0000-00-00 00:00:00',\n `ip` varchar(16) default NULL,\n PRIMARY KEY (`vote_id`,`voter_user`),\n KEY `voter_user_idx` (`voter_user`,`votetime`),\n KEY `voted_user_idx` (`voted_user`,`votetime`)\n"
},
{
"answer_id": 17315369,
"author": "anatoly techtonik",
"author_id": 239247,
"author_profile": "https://Stackoverflow.com/users/239247",
"pm_score": 0,
"selected": false,
"text": "id1:id2:id3: len(issue.votes)/len(id) myid in issue.votes select issue.id from issues where issue.votes contains(myid) select issue.id from issues order by len(issue.votes) desc limit 10 issue.votes"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40405/"
] |
342,613 | <p>How do you manage your database connections in your ASP.Net application?</p>
<p>My understanding tells me the "best" way is to open a connection, make a query, close the connection - and do that multiple times because connection pooling makes the cost negligable.</p>
<p>The problem comes when I have a DAL where each method looks after its own connection. E.G.</p>
<pre>
User x = DAL.GetUserDetails();
Customer y = DAL.GetCustomer();
</pre>
<p>This is fine until we start talking about TransactionScope</p>
<pre>
using (TransactionScope t....
{
DAL.UpdateCustomer(y);
DAL.UpdateUser(x);
t.Complete();
}
</pre>
<p>ASP.Net wants to now use DTC because (I'm guessing) there are multiple connections involved.</p>
<p>Someone is going to say "Cache the connection somwhere" but I need to explicitly destroy the connection because of the way I am managing security (execute as / revert) and I don't want to have to make a call on every page to do that because someone will forget to make the call. I could also pass the connection into each method but thats not ideal because the page has to manage a connection.</p>
<p>Am I making sense or have I missed something fundamental here?</p>
| [
{
"answer_id": 342636,
"author": "JoshBerke",
"author_id": 26160,
"author_profile": "https://Stackoverflow.com/users/26160",
"pm_score": 2,
"selected": true,
"text": "using (CustomTS.New())\n{\n CustomerDal.Update()\n userDal.Update()\n}\n"
},
{
"answer_id": 342759,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 0,
"selected": false,
"text": "public class MyConnectionManager : IDisposable\n{\n [ThreadStatic] // static per thread\n private static SqlConnection con;\n\n public static SqlConnection Connection\n {\n get\n {\n if (con == null)\n {\n con = new SqlConnection();\n con.Open();\n }\n return con;\n }\n }\n\n public void Dispose()\n {\n if (con != null)\n {\n con.Close();\n }\n }\n}\n\npublic class Program\n{\n public void Run()\n {\n using(new MyConnectionManager())\n {\n MakeCall();\n MakeCall();\n } // Disposal happens here\n }\n\n public void MakeCall()\n {\n // The property can be accessed from anywhere\n SqlCommand cmd = new SqlCommand(\"SELECT 1\", MyConnectionManager.Connection);\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42975/"
] |
342,619 | <p>I've been using the Rome API to parse data from an XML feed pretty successfully so for, but have run in to a bit of a snag. </p>
<p>Given the following snippet of XML:</p>
<p><entry><br> <id>uniqueId</id><br> <updated>2008-11-05T01:32:35Z</updated><br> <mm:status xmlns:mm="<a href="http://contentprovider.com&quot" rel="nofollow noreferrer">http://contentprovider.com&quot</a>; available="true"/><br> <title>Title</title><br> ...<br> ...<br></entry></p>
<p>Using the SyndEntryImpl class I'm able to use its standard methods (getTitle, getPublishedDate, etc) to pull the title, id, updated date, etc, but havent figured out a way to get the metadata tag (<mm:status ...). </p>
<p>Getting a string representation of the feed entry would be an acceptable solution as I'd be able to use string functions to retrieve the information, but even with that I havent found an easy method. </p>
<p>Has anyone run in to this in the past?</p>
<p>Thanks. </p>
| [
{
"answer_id": 763083,
"author": "Pat",
"author_id": 20161,
"author_profile": "https://Stackoverflow.com/users/20161",
"pm_score": 1,
"selected": false,
"text": "import com.sun.syndication.io.ModuleGenerator;\nimport com.sun.syndication.io.impl.DateParser;\nimport com.sun.syndication.feed.module.Module;\n\nimport java.util.Collections;\nimport java.util.Set;\nimport java.util.HashSet;\n\nimport org.jdom.Element;\nimport org.jdom.Namespace;\n\n/**\n * Generates mp content in atom.\n */\npublic class ModuleGenerator implements ModuleGenerator {\n\n private static final Namespace NAMESPACE = Namespace.getNamespace(\"mp\", Module.URI);\n private static final Set<Namespace> NAMESPACES;\n\n static {\n Set<Namespace> namespaces = new HashSet<Namespace>();\n namespaces.add(NAMESPACE);\n NAMESPACES = Collections.unmodifiableSet(namespaces);\n }\n\n public String getNamespaceUri() {\n return Module.URI;\n }\n\n public Set<Namespace> getNamespaces() {\n return NAMESPACES;\n }\n\n public void generate(Module module, Element element) {\n Module myModule = (Module) module;\n if (myModule.getStartDate() != null) {\n Element myElement = new Element(\"startDate\", NAMESPACE);\n myElement.setText(DateParser.formatW3CDateTime(myModule.getStartDate()));\n element.addContent(myElement);\n }\n if (myModule.getEndDate() != null) {\n Element myElement = new Element(\"endDate\", NAMESPACE);\n myElement.setText(DateParser.formatW3CDateTime(myModule.getEndDate()));\n element.addContent(myElement);\n }\n }\n}\n\nimport com.sun.syndication.feed.module.Module;\n\nimport java.util.Date;\n\n/**\n * Module for mp atom extension.\n */\npublic interface Module extends Module {\n public static final String URI = \"http://www.mp.com/namespace\";\n\n public Date getStartDate();\n public void setStartDate(Date date);\n\n public Date getEndDate();\n public void setEndDate(Date date);\n}\n\npublic class ModuleImpl extends ModuleImpl implements Module {\n\n private Date startDate;\n private Date endDate;\n\n public ModuleImpl() {\n super(Module.class, Module.URI);\n }\n\n @Override\n public Class getInterface() {\n return Module.class;\n }\n\n @Override\n public void copyFrom(Object obj) {\n Module module = (Module) obj;\n setStartDate(module.getStartDate());\n setEndDate(module.getEndDate());\n }\n\n @Override\n public Date getStartDate() {\n return startDate;\n }\n\n @Override\n public void setStartDate(Date date) {\n startDate = date;\n }\n\n @Override\n public Date getEndDate() {\n return endDate;\n }\n\n @Override\n public void setEndDate(Date date) {\n endDate = date;\n }\n\n @Override\n public String toString() {\n return \"ModuleImpl{\" +\n \"startDate=\" + startDate +\n \", endDate=\" + endDate +\n '}';\n }\n}\n\npackage com.mp.core.iomanagement.contentanalyzers.modules;\n\nimport java.util.Date;\n\nimport org.jdom.Element;\nimport org.jdom.Namespace;\n\nimport com.sun.syndication.feed.module.Module;\nimport com.sun.syndication.io.ModuleParser;\nimport com.sun.syndication.io.impl.DateParser;\n\n/**\n * Parses mp content from atom.\n */\npublic class ModuleParser implements ModuleParser {\n\n public String getNamespaceUri() {\n return Module.URI;\n }\n\n public Module parse(Element element) {\n Namespace myNamespace = Namespace.getNamespace(Module.URI);\n Module module = null;\n Date start = null;\n Date end = null;\n final Element startChild = element.getChild(\"startDate\", myNamespace);\n if (startChild!=null) {\n start = DateParser.parseDate(startChild.getText());\n }\n final Element endChild = element.getChild(\"endDate\", myNamespace);\n if (endChild!=null) {\n end = DateParser.parseDate(endChild.getText());\n }\n\n if (start!=null || end!=null) {\n module = new ModuleImpl();\n module.setStartDate(start);\n module.setEndDate(end);\n }\n return module;\n }\n}\n atom_1.0.item.ModuleParser.classes=\\\ncom.mp.core.iomanagement.contentanalyzers.modules.ModuleParser\n\natom_1.0.item.ModuleGenerator.classes=\\\ncom.mp.core.iomanagement.contentanalyzers.modules.ModuleGenerator\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,632 | <p>Any idea why the following code doesn't print the amount of characters in the input?
I've taken this straight from the K&R book. Learning C at the moment and this is really confusing, looks to me like I'm never reaching EOF. If that's the case then why would this be used as an example?</p>
<pre><code>#include <stdio.h>
main()
{
double nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf("%d\n", nc);
}
</code></pre>
| [
{
"answer_id": 342642,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "stdin EOF EOF printf"
},
{
"answer_id": 342645,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": true,
"text": "EOF EOF EOF '\\n'"
},
{
"answer_id": 342672,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 3,
"selected": false,
"text": "nc printf(\"%lf\", nc) #include <stdio.h>\n\nint main(void)\n{\n int nc;\n\n for (nc = 0; getchar() != EOF; ++nc)\n ;\n printf(\"%d\\n\", nc);\n\n return 0;\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,638 | <p>I'm coming from a .net background and want to know the accepted way of creating a method that returns a boolean and modifies a string that was passed in via parameter. I understand Strings are immutable in Java so the below snippet will always produce an empty string. I am constrained to return boolean only. Exceptions can't be thrown. If I need to wrap the String class in, say, a StringHolder, what package could I find this in.</p>
<pre><code>public static void DoStuff()
{
String msg = "";
if (GetMessage(msg))
{
System.out.println(msg);
}
}
</code></pre>
| [
{
"answer_id": 342652,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": " class StringHolder\n {\n String msg;\n }\n\n StringHolder sMsg = new StringHolder();\n sMsg.msg = \"\";\n if (GetMessage(sMsg))\n {\n System.out.println(sMsg.msg);\n }\n"
},
{
"answer_id": 342728,
"author": "Stobor",
"author_id": 43452,
"author_profile": "https://Stackoverflow.com/users/43452",
"pm_score": 1,
"selected": false,
"text": "\nbool GetMessage(String[] output)\n{\n if(output.length < 1)\n throw new Exception(\"Output must be a String[1]\");\n output[0] = \"You win!\";\n}\n\npublic static void DoStuff()\n{\n String[] msg = new String[1];\n if(GetMessage(msg))\n {\n System.out.println(msg[0]);\n }\n}\n"
},
{
"answer_id": 342783,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "public static void doStuff(){\n String msg = \"\";\n StringBuilder sb = new StringBuilder();\n if ( getMessage( sb ) ) {\n System.out.println( sb );\n }\n}\n\npublic static boolean getMessage( StringBuilder sb ) {\n if ( \"\".equals( sb.toString() )) {\n sb.delete( 0, sb.length() );\n sb.append(\"It was empty\");\n return true;\n } else {\n return false;\n }\n}\n public static void doStuff(){\n String msg = \"\";\n String [] holder = { msg };\n if ( getMessage( holder ) ){\n System.out.println( holder[0] );\n }\n}\npublic static boolean getMessage( String [] holder ) {\n if ( \"\".equals( holder[0] )) {\n holder[0] = \"It was empty\";\n return true;\n } else {\n return false;\n }\n}\n public void doStuff() { \n String msg = \"\";\n String result = getMessage( msg );\n if ( result != msg ) {\n System.out.println( result );\n }\n}\npublic static String getMessage( String msg ) {\n if ( \"\".equals(msg){\n return \"It was empty\";\n }\n return msg\n}\n"
},
{
"answer_id": 342947,
"author": "J. A. Faucett",
"author_id": 18503,
"author_profile": "https://Stackoverflow.com/users/18503",
"pm_score": 2,
"selected": false,
"text": "public class Holder<T> {\n T item;\n public Holder( T item) { set( item);}\n public T get( ) { return item;}\n public void set( T item) { this.item = item;}\n}\n DoStuff( ) public static void DoStuff( ) {\n String msg = \"\";\n Holder<String> holder = new Holder<String>( msg);\n if ( getMessage( holder)) { System.out.println( holder.get( ));}\n}\n GetMessage( ) holder.set( a_string)"
},
{
"answer_id": 343583,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 3,
"selected": false,
"text": "public class ResultContainer {\n private final boolean success;\n private final String result;\n public ResultContainer(boolean success, String result) {\n this.success = success;\n this.result = result;\n }\n public boolean isSuccess() { return success; }\n public String getResult() { return result; }\n}\n ResultContainer resultContainer = GetMessage(message);\nif (resultContainer.isSuccess()) {\n System.out.println(resultContainer.getResult());\n}\n GetMessage() ResultContainer ResultContainer"
},
{
"answer_id": 343649,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 3,
"selected": false,
"text": "String userMessage = thing.doStuff(new StuffHandler<String>() {\n public String stuff(boolean success, String message) {\n return message+\" was \"+(success ? \"succesful\" : \"unsuccesful\");\n }\n});\n public interface StuffHandler<T> {\n T stuff(boolean success, String message);\n}\n\n[...]\n\n public <T> T doStuff(StuffHandler<T> handler) {\n handler.stuff(isSuccess(), getMessage());\n }\n"
},
{
"answer_id": 382750,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\npublic boolean doStuff(String msg)\n{\n boolean boolTest = false;\n msg += \"Appending something to msg\";\n int msgLength = msg.length();\n if ( msgLength > 80 )\n {\n boolTest = true;\n return boolTest;\n }\n return boolTest;\n}\n"
},
{
"answer_id": 382780,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Process p = Runtime.exec(\"java GetMessage.class \" + String);\n if (p.returnCode() = 1) \n Out.printWord(\"1 made back\"):\nelse \n {\n Out.printWord(\"B Made back\");\n }\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4458/"
] |
342,641 | <p>I'm looking for guidance on how to use PHP's Mailparse pecl extension. The <a href="http://us2.php.net/manual/en/book.mailparse.php" rel="noreferrer">documentation</a> on the PHP website isn't very helpful. </p>
<p>Does anyone have experience with this and care to share a few pointers?</p>
| [
{
"answer_id": 342652,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": " class StringHolder\n {\n String msg;\n }\n\n StringHolder sMsg = new StringHolder();\n sMsg.msg = \"\";\n if (GetMessage(sMsg))\n {\n System.out.println(sMsg.msg);\n }\n"
},
{
"answer_id": 342728,
"author": "Stobor",
"author_id": 43452,
"author_profile": "https://Stackoverflow.com/users/43452",
"pm_score": 1,
"selected": false,
"text": "\nbool GetMessage(String[] output)\n{\n if(output.length < 1)\n throw new Exception(\"Output must be a String[1]\");\n output[0] = \"You win!\";\n}\n\npublic static void DoStuff()\n{\n String[] msg = new String[1];\n if(GetMessage(msg))\n {\n System.out.println(msg[0]);\n }\n}\n"
},
{
"answer_id": 342783,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "public static void doStuff(){\n String msg = \"\";\n StringBuilder sb = new StringBuilder();\n if ( getMessage( sb ) ) {\n System.out.println( sb );\n }\n}\n\npublic static boolean getMessage( StringBuilder sb ) {\n if ( \"\".equals( sb.toString() )) {\n sb.delete( 0, sb.length() );\n sb.append(\"It was empty\");\n return true;\n } else {\n return false;\n }\n}\n public static void doStuff(){\n String msg = \"\";\n String [] holder = { msg };\n if ( getMessage( holder ) ){\n System.out.println( holder[0] );\n }\n}\npublic static boolean getMessage( String [] holder ) {\n if ( \"\".equals( holder[0] )) {\n holder[0] = \"It was empty\";\n return true;\n } else {\n return false;\n }\n}\n public void doStuff() { \n String msg = \"\";\n String result = getMessage( msg );\n if ( result != msg ) {\n System.out.println( result );\n }\n}\npublic static String getMessage( String msg ) {\n if ( \"\".equals(msg){\n return \"It was empty\";\n }\n return msg\n}\n"
},
{
"answer_id": 342947,
"author": "J. A. Faucett",
"author_id": 18503,
"author_profile": "https://Stackoverflow.com/users/18503",
"pm_score": 2,
"selected": false,
"text": "public class Holder<T> {\n T item;\n public Holder( T item) { set( item);}\n public T get( ) { return item;}\n public void set( T item) { this.item = item;}\n}\n DoStuff( ) public static void DoStuff( ) {\n String msg = \"\";\n Holder<String> holder = new Holder<String>( msg);\n if ( getMessage( holder)) { System.out.println( holder.get( ));}\n}\n GetMessage( ) holder.set( a_string)"
},
{
"answer_id": 343583,
"author": "Bombe",
"author_id": 43582,
"author_profile": "https://Stackoverflow.com/users/43582",
"pm_score": 3,
"selected": false,
"text": "public class ResultContainer {\n private final boolean success;\n private final String result;\n public ResultContainer(boolean success, String result) {\n this.success = success;\n this.result = result;\n }\n public boolean isSuccess() { return success; }\n public String getResult() { return result; }\n}\n ResultContainer resultContainer = GetMessage(message);\nif (resultContainer.isSuccess()) {\n System.out.println(resultContainer.getResult());\n}\n GetMessage() ResultContainer ResultContainer"
},
{
"answer_id": 343649,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 3,
"selected": false,
"text": "String userMessage = thing.doStuff(new StuffHandler<String>() {\n public String stuff(boolean success, String message) {\n return message+\" was \"+(success ? \"succesful\" : \"unsuccesful\");\n }\n});\n public interface StuffHandler<T> {\n T stuff(boolean success, String message);\n}\n\n[...]\n\n public <T> T doStuff(StuffHandler<T> handler) {\n handler.stuff(isSuccess(), getMessage());\n }\n"
},
{
"answer_id": 382750,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\npublic boolean doStuff(String msg)\n{\n boolean boolTest = false;\n msg += \"Appending something to msg\";\n int msgLength = msg.length();\n if ( msgLength > 80 )\n {\n boolTest = true;\n return boolTest;\n }\n return boolTest;\n}\n"
},
{
"answer_id": 382780,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Process p = Runtime.exec(\"java GetMessage.class \" + String);\n if (p.returnCode() = 1) \n Out.printWord(\"1 made back\"):\nelse \n {\n Out.printWord(\"B Made back\");\n }\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103/"
] |
342,655 | <p>I have a strange encounter when creating a GridView using <code>SELECT..WHERE..<field> IN (value1, val2...)</code>.</p>
<p>In the "Configure datasource" tab, if i hard code the values <code>SELECT .... WHERE field1 in ('AAA', 'BBB', 'CCC')</code>, the system works well.</p>
<p>However, if I define a new parameter and pass in a concatenated string of values using a variable; be it a @session, Control or querystring; e.g. <code>SELECT .... WHERE field1 in @SESSION</code> the result is always empty.</p>
<p>I did another experiment by reducing the parameter content to only one single value, it works well.</p>
<p>in short,
if I hardcode a string of values, it works,
if I pass a variable with single value only, it works,
but if i pass a varialbe with two values; it failed.</p>
<p>Pls advise if I have make any mistake or it is a known bug.</p>
<p>BR
SDIGI</p>
| [
{
"answer_id": 12667285,
"author": "Hutcho",
"author_id": 1710769,
"author_profile": "https://Stackoverflow.com/users/1710769",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE [dbo].[get_bars_in_foo]\n @bars varchar(255)\nAS\nBEGIN\n DECLARE @query AS varchar(MAX)\n SET @query = 'SELECT * FROM [foo] WHERE bar IN (' + @bars + ')'\n exec(@query)\nEND\n\n-- exec [get_bars_in_foo] '1,2,3,4'\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,665 | <p>We are using verisign's time stamp service currently, but every so often the time stamp server becomes unavailable - mostly due to our ISP failing.</p>
<p>We now timestamp everything we build, even simple dev builds as we had a lot of trouble with Vista not running the unsigned/unstamped files properly.</p>
<p>Can we setup a time stamp service to do the same? I've looked around and not really found any information at my current level of knowledge that tells me this can or cannot be done.</p>
| [
{
"answer_id": 12667285,
"author": "Hutcho",
"author_id": 1710769,
"author_profile": "https://Stackoverflow.com/users/1710769",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE [dbo].[get_bars_in_foo]\n @bars varchar(255)\nAS\nBEGIN\n DECLARE @query AS varchar(MAX)\n SET @query = 'SELECT * FROM [foo] WHERE bar IN (' + @bars + ')'\n exec(@query)\nEND\n\n-- exec [get_bars_in_foo] '1,2,3,4'\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37558/"
] |
342,675 | <p>I've got a number of WebService methods that all include some very boilerplate code of wrapping the actual work in a try/catch/finally and performing the same tasks in the catch/finally. So as a way to encapsulate all of the shared catch/finally stuff I wrote a simple generic.</p>
<p>This works and really eliminates a bunch of repetitive code but feels klunky, and the syntax is very obtuse. Every time I come back to this my brain gets twisted trying to figure it out (a clear sign it is not a good design). I'm looking for feedback on whether this is a crazy thing to do, and if there is a better way to approach it.</p>
<p>Here is my template:</p>
<pre><code>public delegate T2 RestfulServiceRequest<T1, T2>(T1 req);
static class RestfulService
{
public static T2 ExceptionHandler<T1, T2>(RestfulServiceRequest<T1, T2> serviceCall, T1 req)
{
if (req == null)
throw new BadRequestException(new ArgumentNullException("Invalid or missing request object"));
try
{
return serviceCall(req);
}
catch (RestfulException e)
{
// log it and rethrow
Logger.Write(e);
throw;
}
catch (Exception e)
{
Logger.Error(e);
// wrap in a consistent exception for propagation back to caller
throw new InternalServerException(e);
}
finally
{
Logger.Debug("Complete");
}
}
}
</code></pre>
<p>}</p>
<p>And here is a usage of it:</p>
<pre><code>public class Initialization : IInitialization
{
// MyMethod thas uses the template
public ApplianceInitResp CreateApplianceServer(ApplianceInitReq req)
{
return RestfulService.ExceptionHandler<ApplianceInitReq, ApplianceInitResp>(delegate(ApplianceInitReq x)
{
// do some work
return new ApplianceInitResp();
}, req);
}
}
</code></pre>
<p>}</p>
| [
{
"answer_id": 342709,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "public interface IServiceResponse { ... }\npublic class ApplianceInitResp : IServiceResponse { ... }\npublic interface IServiceRequest { ... }\npublic class ApplianceInitReq : IServiceRequest { ... }\n\npublic delegate IServiceResponse RestfulServiceRequest( IServiceRequest req );\n\nstatic class RestfulService\n{\n public static IServiceResponse\n Invoke( RestfulServiceRequest serviceCall, IServiceRequest req) \n {\n if (req == null)\n throw new BadRequestException( ...inner-exception... );\n try\n {\n return serviceCall(req);\n }\n catch (RestfulException e)\n {\n Logger.Write(e);\n throw; \n }\n catch (Exception e)\n {\n Logger.Error(e);\n throw new InternalServerException(e);\n }\n finally\n {\n Logger.Debug(\"Complete\");\n }\n }\n}\n\npublic class Initialization : IInitialization\n{\n // MyMethod thas uses the template \n public ApplianceInitResp CreateApplianceServer(ApplianceInitReq req) \n {\n return RestfulService.Invoke(\n delegate(ApplianceInitReq x)\n {\n // do some work\n return new ApplianceInitResp();\n },\n req );\n }\n}\n"
},
{
"answer_id": 342712,
"author": "wasker",
"author_id": 21952,
"author_profile": "https://Stackoverflow.com/users/21952",
"pm_score": 1,
"selected": false,
"text": "public ApplianceInitResp CreateApplianceServer(ApplianceInitReq req)\n{\n // Do some work\n return new ApplianceInitResp();\n}\n"
},
{
"answer_id": 343000,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 3,
"selected": true,
"text": "public static T2 ExceptionHandler<T1, T2>(RestfulServiceRequest<T1, T2> serviceCall, T1 req)\n public static T2 Invoke<T1, T2>( this T1 req, RestfulServiceRequest<T1, T2> serviceCall)\n public class Initialization :IInitialization {\n public ApplianceInitResp CreateApplianceServer( ApplianceInitReq req ) {\n return req.Invoke( r => {\n // do some work\n return new ApplianceInitResp();\n });\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43406/"
] |
342,687 | <h2>Context</h2>
<ul>
<li>Take a look at Wordle: <a href="http://www.wordle.net/" rel="noreferrer">http://www.wordle.net/</a></li>
<li>It's much better looking than any other word cloud generators I've seen</li>
<li>Note: the source is not available - read the FAQ: <a href="http://www.wordle.net/faq#code" rel="noreferrer">http://www.wordle.net/faq#code</a></li>
</ul>
<h2>My Questions</h2>
<ul>
<li>Is there an algorithm available that does what Wordle does?</li>
<li>If no, what are some alternatives that produces similar kinds of output?</li>
</ul>
<h2>Why I'm asking</h2>
<ul>
<li>just curious</li>
<li>want to learn</li>
</ul>
| [
{
"answer_id": 1478314,
"author": "Jonathan Feinberg",
"author_id": 143938,
"author_profile": "https://Stackoverflow.com/users/143938",
"pm_score": 10,
"selected": true,
"text": "place the word where it wants to be\nwhile it intersects any of the previously placed words\n move it one step along an ever-increasing spiral\n"
},
{
"answer_id": 6310032,
"author": "Zasz",
"author_id": 626084,
"author_profile": "https://Stackoverflow.com/users/626084",
"pm_score": 2,
"selected": false,
"text": "<a>"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13477/"
] |
342,708 | <p>Wondering the most efficent way to make a binary search tree into a spell checker by reading in say 1000 word dictionary file and then having it check another document that say has a couple paragraphs. </p>
| [
{
"answer_id": 342806,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "- C\n - A\n - R\n - end\n - T\n - T\n - end\n - U\n - P\n - end\n - T\n - end\n Check for \"cat\"\nDoes \"C\" exist at the root level? Yes, move to the next letter.\nDoes \"A\" exist underneath C? Yes, move on.\nDoes \"T\" exist underneath A? Yes, move on.\nIs there a word ending after the T? Yes. Word exists.\n\nCheck for \"cu\"\nDoes \"C\" exist at the root level? Yes, move to the next letter.\nDoes \"U\" exist at the root level? Yes, move to the next letter.\nIs there a word ending after the U? No. Word does not exist.\n"
},
{
"answer_id": 5736224,
"author": "Andre Artus",
"author_id": 122742,
"author_profile": "https://Stackoverflow.com/users/122742",
"pm_score": 0,
"selected": false,
"text": "private static IEnumerable<T> BinaryTreeOrder<T>(IList<T> range, int first, int last)\n{\n if (first > last)\n {\n yield break;\n }\n\n int mid = (first + last) / 2;\n yield return range[mid];\n foreach (var item in BinaryTreeOrder(range, first, mid - 1))\n {\n yield return item;\n }\n foreach (var item in BinaryTreeOrder(range, mid + 1, last))\n {\n yield return item;\n } \n}\n\nprivate static void BinaryTreeOrder<T>(IList<T> range, int first, int last, \n ref IList<T> outList)\n{\n if (first > last)\n {\n return;\n }\n\n int mid = (first + last) / 2;\n outList.Add(range[mid]);\n BinaryTreeOrder(range, first, mid - 1, ref outList);\n BinaryTreeOrder(range, mid + 1, last, ref outList);\n}\n\nprivate static void BinaryTreeOrder<T>(IList<T> range, int first, int last, \n ref BinaryTree<T> tree) where T : IComparable<T>\n{\n if (first > last)\n {\n return;\n }\n\n int mid = (first + last) / 2;\n tree.Add(range[mid]);\n BinaryTreeOrder(range, first, mid - 1, ref tree);\n BinaryTreeOrder(range, mid + 1, last, ref tree);\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,737 | <p>When creating links for an an html based email, how critical is it to use absolute links? Also, What are the benefits in using relative links in general?</p>
| [
{
"answer_id": 342751,
"author": "balexandre",
"author_id": 28004,
"author_profile": "https://Stackoverflow.com/users/28004",
"pm_score": 1,
"selected": false,
"text": "/portal/images/myImage.png\n ../images/myImage.png\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39781/"
] |
342,758 | <p>I'd like to implement a UITableView which displays say 20 rows at a time. But given the fact that I might actually have say 120 items to present, I'd like to handle this using some sort of paging:</p>
<p>Populate table with first 20 items. When the user does a right-to-left swipe, reload the UITableView with the next 20 items. A left-to-right swipe would show the previous 20 items.</p>
<p>I think subclassing UITableView and handle UITouches there is the way to go, but I'm not sure how to handle the touches correctly in order not to interfer with the standard event handling. </p>
<p>Eg. if the user just touches (clicks) a row, I want the row to hightlight (selected) and then switch to a detail view presenting data corresponding to the selected row. But if the user does a horizontal swipe, I don't want the row below the swipe to be highlighted (and therefore selected), instead, i want to trigger my loadprevious page / loadnext page handling, which wil reload the table with the according 20 previous or next items, depending on the swipe direction. </p>
<p>Any suggestions?</p>
| [
{
"answer_id": 698824,
"author": "Bingosabi",
"author_id": 84800,
"author_profile": "https://Stackoverflow.com/users/84800",
"pm_score": 2,
"selected": false,
"text": "- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;\n\n- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,767 | <p>Hypothetical situation:</p>
<p>Suppose I ran a hosting firm where I hosted subdomains for people. You could sign up and give me a few bucks a month, and I'd give you yourname.mycompany.com.</p>
<p>Now, say I wanted mail.*.mycompany.com to point to one server and www.*.mycompany.com to point to another.</p>
<p>Is this possible? The RFC seems to think not, <a href="http://en.wikipedia.org/wiki/Wildcard_DNS_record" rel="nofollow noreferrer">Wikipedia</a> seems to think not, but what's stopping a DNS server from having enough logic to return the right thing?</p>
<p>And if so, are there DNS hosting providers that will do this for me so I don't have to run my own DNS?</p>
| [
{
"answer_id": 698824,
"author": "Bingosabi",
"author_id": 84800,
"author_profile": "https://Stackoverflow.com/users/84800",
"pm_score": 2,
"selected": false,
"text": "- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;\n\n- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6010/"
] |
342,772 | <p>Would anyone happen to know how to convert type <code>LPTSTR</code> to <code>char *</code> in C++?</p>
| [
{
"answer_id": 342786,
"author": "John Z",
"author_id": 43430,
"author_profile": "https://Stackoverflow.com/users/43430",
"pm_score": 3,
"selected": false,
"text": "LPTSTR szString = _T(\"Testing\");\nchar* pBuffer;\n USES_CONVERSION;\npBuffer = T2A(szString);\n CStringA cstrText(szString);\n WideCharToMultiByte UNICODE"
},
{
"answer_id": 343038,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "char * pCopy = NULL;\nif (sizeof(TCHAR) == sizeof(char))\n{\n size_t size = strlen(pOriginal);\n pCopy = new char[size + 1];\n strcpy(pCopy, pOriginal);\n}\nelse\n{\n size_t size = wcstombs(NULL, pOriginal, 0);\n pCopy = new char[size + 1];\n wcstombs(pCopy, pOriginal, size + 1);\n}\n"
},
{
"answer_id": 5233669,
"author": "vahapt",
"author_id": 581401,
"author_profile": "https://Stackoverflow.com/users/581401",
"pm_score": 3,
"selected": false,
"text": "#include <windows.h>\n\n/* string consisting of several Asian characters */\nLPTSTR wcsString = L\"\\u9580\\u961c\\u9640\\u963f\\u963b\\u9644\";\n//LPTSTR wcsString = L\"OnlyAsciiCharacters\";\n\nchar* encode(const wchar_t* wstr, unsigned int codePage)\n{\n int sizeNeeded = WideCharToMultiByte(codePage, 0, wstr, -1, NULL, 0, NULL, NULL);\n char* encodedStr = new char[sizeNeeded];\n WideCharToMultiByte(codePage, 0, wstr, -1, encodedStr, sizeNeeded, NULL, NULL);\n return encodedStr;\n}\n\nwchar_t* decode(const char* encodedStr, unsigned int codePage)\n{\n int sizeNeeded = MultiByteToWideChar(codePage, 0, encodedStr, -1, NULL, 0);\n wchar_t* decodedStr = new wchar_t[sizeNeeded ];\n MultiByteToWideChar(codePage, 0, encodedStr, -1, decodedStr, sizeNeeded );\n return decodedStr;\n}\n\nint main(int argc, char* argv[])\n{\n char* str = encode(wcsString, CP_UTF8); //UTF-8 encoding\n wchar_t* wstr = decode(str, CP_UTF8);\n //If the wcsString is UTF-8 encodable, then this comparison will result to true.\n //(As i remember some of the Chinese dialects cannot be UTF-8 encoded \n bool ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0; \n delete str;\n delete wstr;\n\n str = encode(wcsString, 20127); //US-ASCII (7-bit) encoding\n wstr = decode(str, 20127);\n //If there were non-ascii characters existing on wcsString, \n //we cannot return back, since some of the data is lost\n ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0; \n delete str;\n delete wstr;\n}\n LPTSTR x = \"test\";\nchar* y;\ny = x;\n"
},
{
"answer_id": 16266828,
"author": "gorth",
"author_id": 1470847,
"author_profile": "https://Stackoverflow.com/users/1470847",
"pm_score": -1,
"selected": false,
"text": "string mfc_to_zstring (CString &sref)\n{\n char nojoy[65536];\n char *ptr, *psin = NULL;\n string sot;\n LPCTSTR p = sref;\n\n\n#if UNICODE\n if (sizeof(TCHAR) != sizeof(char))\n {\n size_t n = wcstombs(NULL, p, 0);\n if (n > 65530)\n {\n psin = new char[n + 1];\n wcstombs(psin, p, n + 1);\n ptr = psin;\n }\n else\n {\n wcstombs(nojoy, p, n + 1);\n ptr = nojoy;\n }\n\n sot = ptr;\n if (psin != NULL)\n delete psin;\n }\n else\n { std::cerr << \"Aaargh! Microsoft horror.\\n\"; exit(1); }\n#else\n if (sizeof(TCHAR) == sizeof(char))\n {\n const char *ptr = p;\n sot = ptr;\n }\n else\n { std::cerr << \"Aaargh! You should never see this line\\n\"; exit(1); }\n#endif\n\n return sot;\n}\n"
},
{
"answer_id": 21998389,
"author": "maxtuzz",
"author_id": 3326795,
"author_profile": "https://Stackoverflow.com/users/3326795",
"pm_score": 0,
"selected": false,
"text": "const std::wstring &wstring = AcctName; // AcctName being my LPTSTR string\nint size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(), NULL, 0, NULL, NULL);\nstd::string strTo(size_needed, 0);\n\nWideCharToMultiByte(CP_UTF8, 0, & wstring[0], (int)wstring[0], &strTo[0], size_needed, NULL, NULL);\n\nchar* charUserName = new char[strTo.size() + 1];\n\n// Set charUserName via copying\nstd::copy(strTo.begin(), strTo.end(), charUserName);\ncharUserName[strTo.size()] = '\\0';\n\nSetUPI(charUserName); // charUserName being my converted char * - \n// You don't need this last part - but this is an example of passing to method\n// that takes a string\n"
},
{
"answer_id": 35187926,
"author": "polfosol ఠ_ఠ",
"author_id": 5358284,
"author_profile": "https://Stackoverflow.com/users/5358284",
"pm_score": 0,
"selected": false,
"text": "LPTSTR TCHAR* <tchar.h> TCHAR TCHAR wchar_t char char wcstombs #include <cstring>\n#include <algorithm>\n#include <tchar.h>\n\nvoid lptstr2str(LPTSTR tch, char* &pch) // or (TCHAR* tch, char* &pch)\n{\n#ifndef UNICODE\n std::memcpy(pch, tch, strlen(tch) + 1);\n#else\n size_t n =\n sizeof(TCHAR) / sizeof(char)* wcsnlen(tch, std::string::npos);\n pch = new char[n + 1];\n std::memcpy(pch, tch, n + 1);\n int len = n - std::count(pch, pch + n, NULL);\n std::remove(pch, pch + n, NULL);\n pch[len] = NULL;\n#endif\n}\n"
},
{
"answer_id": 39961071,
"author": "Racky",
"author_id": 457128,
"author_profile": "https://Stackoverflow.com/users/457128",
"pm_score": 0,
"selected": false,
"text": "LPCTSTR myLPCTSTR = getLPCTSTR();\nTCHAR myT[500];\nwcscpy(myT,myLPCTSTR);\nchar myC[500];\nsprintf(myC, \"%S\", myT);\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37875/"
] |
342,777 | <p>I'm working on a Zend Framework (1.7) project with a structure loosely based on the structure of the quickstart application - front controller, action controllers, views & models that use Zend_Db_Table to get to the database. One of my main models relies on some expensive joins to pull up its primary listing, so I'm looking into using Zend_Paginator to reduce the number of rows brought back from the database. My problem is that Zend_Paginator only comes with 4 adaptors, none of which really seem to be a good fit for me.</p>
<ul>
<li><strong>Array</strong> : Building the array to feed to ZP would involve fetching all the records which is what I'm trying to avoid</li>
<li><strong>Iterator</strong> : A dumb iterator would present the same problems as an array and a smart one feels like it would be a poor fit for the Model</li>
<li><strong>DbSelect</strong> : Getting a DbSelect object up to the Controller would uncomfortably tie the Controller to the inner workings of my DB (not to mention producing raw result rows rather than encapsulated objects)</li>
<li><strong>DbTableSelect</strong> : same as DbSelect</li>
<li><strong>Null Adapter</strong> : pass all the details back and forth manually.</li>
</ul>
<p>Passing the paginator into the model feels like it, too, would violate the MVC separation. Is the problem that I've built my model incorrectly, that I'm being to dogmatic about maintaining MVC separation or am I missing a clean, elegant way of sticking all the moving parts together?</p>
| [
{
"answer_id": 342912,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 0,
"selected": false,
"text": "$select = $db->from('users')->order('name'); \n$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));\n$paginator->setCurrentPageNumber($this->_getParam('page', 1));\n$paginator->setItemCountPerPage(25);\n$this->view->paginator = $paginator;\n"
},
{
"answer_id": 344706,
"author": "dcousineau",
"author_id": 20265,
"author_profile": "https://Stackoverflow.com/users/20265",
"pm_score": 3,
"selected": true,
"text": "$current_page $per_page class Model\n{\n //...\n /**\n * @return array Array in the form: array( 'paginator' => obj, 'resultset' => obj )\n */\n public function getAll( $where = array(), $current_page = null, $per_page = null );\n //...\n}\n"
},
{
"answer_id": 346886,
"author": "Akeem",
"author_id": 35505,
"author_profile": "https://Stackoverflow.com/users/35505",
"pm_score": 0,
"selected": false,
"text": "$items = new Items();//setup model as usual in controller\n$this->view->paginator = Zend_Paginator::factory($items->getAll()); //initialize the pagination in the view NB getAll is just a custom function to encapsulate my query in the model that returns a Zend_Db_Table_Rowset\n$this->view->paginator->setCurrentPageNumber($page); //$page is just the page number that could be passed in as a param in the request\n$this->view->paginator->setView($this->view);\n <?php foreach($this->paginator as $item):?>\n <?=$item->someProperty?>\n<?php endforeach;?>\n"
},
{
"answer_id": 2321238,
"author": "Troy",
"author_id": 23322,
"author_profile": "https://Stackoverflow.com/users/23322",
"pm_score": 2,
"selected": false,
"text": "class Model_UserDataMapper {\n public function getUsers($select, $page) {\n $pager = Zend_Paginator::factory($select);\n $pager->setItemCountPerPage(10)\n >setCurrentPageNumber($page)\n ->setFilter(new Zend_Filter_Callback(array($this,'getUserObjects')));\n }\n\n public function getUserObjects($rows) {\n $users = array();\n\n foreach($rows as $row) {\n $user = new Model_User($row->toArray());\n\n $users[] = $user;\n }\n\n return $users;\n }\n}\n"
},
{
"answer_id": 2324037,
"author": "Elmo",
"author_id": 82943,
"author_profile": "https://Stackoverflow.com/users/82943",
"pm_score": 0,
"selected": false,
"text": "class ModelSet extends Zend_Paginator_Adapter_DbSelect\n{\n public function __construct( ... )\n {\n // Create a new Zend_Db_Select ($select) representing the desired\n // data set using incoming criteria\n parent::__construct($select);\n }\n ...\n}\n $modelSet = new ModelSet( ... );\n...\n$pager = new Zend_Paginator( $modelSet );\n$pager->setItemCountPerPage( ... );\n$pager->setCurrentPageNumber( ... );\n...\n// The first time the record set is actually retrieved will be at the beginning\n// of the first traversal\nforeach ($pager as $record)\n{\n // ... do stuff with the record ...\n}\n"
},
{
"answer_id": 20833639,
"author": "axiom82",
"author_id": 886354,
"author_profile": "https://Stackoverflow.com/users/886354",
"pm_score": 1,
"selected": false,
"text": "<?php\n\n /* /zend/Paginator/Adapter/DbTableMethod.php */ \n class Zend_Paginator_Adapter_DbTableMethod implements Zend_Paginator_Adapter_Interface {\n\n protected $_class;\n protected $_method;\n protected $_parameters;\n protected $_rowCount = null;\n\n public function __construct($class, $method, array $parameters = array()){\n\n $reflectionClass = new ReflectionClass($class);\n $reflectionMethod = $reflectionClass->getMethod($method);\n $reflectionParameters = $reflectionMethod->getParameters();\n\n $_parameters = array();\n\n foreach ($reflectionParameters as $reflectionParameter){\n\n $_parameters[$reflectionParameter->name] = ($reflectionParameter->isDefaultValueAvailable()) ? $reflectionParameter->getDefaultValue() : null;\n\n } \n\n foreach ($parameters as $parameterName => $parameterValue){\n\n if (array_key_exists($parameterName, $_parameters)) $_parameters[$parameterName] = $parameterValue;\n\n }\n\n $this->_class = $class;\n $this->_method = $method;\n $this->_parameters = $_parameters;\n\n }\n\n public function count(){\n\n if (is_null($this->_rowCount)){\n\n $parameters = $this->_parameters;\n $parameters['count'] = true;\n\n $this->_rowCount = call_user_func_array(array($this->_class, $this->_method), $parameters);\n\n } \n\n return $this->_rowCount;\n\n }\n\n public function getItems($offset, $itemCountPerPage){\n\n $parameters = $this->_parameters;\n $parameters['limit'] = $itemCountPerPage;\n $parameters['offset'] = $offset;\n\n $items = call_user_func_array(array($this->_class, $this->_method), $parameters);\n\n return $items;\n }\n\n }\n\n?>\n <?php\n\n class StoreController extends Zend_Controller_Action {\n\n public function storeCustomersAction(){\n\n $model = new Default_Model_Store();\n $method = 'getStoreCustomers';\n $parameters = array('storeId' => 1);\n\n $paginator = new Zend_Paginator(new Site_Paginator_Adapter_DbTableMethod($model, $method, $parameters));\n $paginator->setCurrentPageNumber($this->_request->getParam('page', 1));\n $paginator->setItemCountPerPage(20);\n\n $this->view->paginator = $paginator;\n\n }\n\n }\n\n?>\n <?php\n\n class Default_Model_Store extends Zend_Db_Table {\n\n public function getStoreCustomers($storeId, $includeCustomerOrders = false, $limit = 0, $offset = 0, $count = false){\n\nif ($count) /* return SELECT COUNT(*) ... */ \n\n /* ... run primary query, get result */\n $select = $this->_db->select(...)->limit($limit, $offset);\n\n\n $rows = $this->_db->fetchAll($select);\n\n if ($includeCustomerOrders){\n\n foreach ($rows as &$row){\n\n $customerId = $row['id'];\n $row['orders'] = $this->getCustomerOrders($customerId);\n\n }\n\n }\n\n return $rows; \n\n }\n\n }\n\n ?>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39413/"
] |
342,829 | <p>OK I'm redoing this since I messed it up. :) here's the xaml.</p>
<pre><code><Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ucWaitIndicator.Window1"
x:Name="Window"
Title="Window1"
Width="640" Height="480">
<Window.Resources>
<Storyboard x:Key="OnLoaded1">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="path" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)" RepeatBehavior="Forever">
<SplineDoubleKeyFrame KeyTime="00:00:00.5000000" Value="360"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource OnLoaded1}"/>
</EventTrigger>
</Window.Triggers>
<Grid x:Name="LayoutRoot">
<Path Data="M180.99244,64C116.37543,64 63.992443,116.38299 63.992443,181 63.992443,245.61742 116.37549,298 180.99244,298 245.60981,298 297.99244,245.61737 297.99244,181 297.99244,116.38304 245.60986,64 180.99244,64z M180.99244,0.5C205.91427,0.5 229.65641,5.5507355 251.25119,14.684582 256.64987,16.968037 261.91435,19.506668 267.02946,22.285378 307.95065,44.515015 339.31398,82.108706 353.37751,127.32482 356.89353,138.6289 359.32811,150.40922 360.56053,162.54492 361.79308,174.68071 361.79307,187.31935 360.56053,199.45508 355.63085,247.99793 331.46539,290.85483 295.8072,320.28259 277.97817,334.9964 257.2756,346.35331 234.66763,353.38507 223.36361,356.90106 211.58325,359.33566 199.44752,360.56808 187.31179,361.80063 174.67315,361.80063 162.53737,360.56808 113.99482,355.63844 71.137715,331.47319 41.70987,295.81476 26.995966,277.98571 15.63918,257.28314 8.6073667,234.67519 5.0914601,223.37117 2.6567941,211.59082 1.4243458,199.45508 0.19188775,187.31935 0.19188165,174.68071 1.4243458,162.54492 6.3541056,114.00227 30.519295,71.145355 66.177677,41.717426 84.006863,27.003489 104.70924,15.646738 127.31726,8.6149235 138.62133,5.0989907 150.40165,2.6643478 162.53737,1.4319025 168.60525,0.81567122 174.76199,0.5 180.99244,0.5z" Margin="10,10,0,0" x:Name="path" RenderTransformOrigin="0.5,0.5" Stretch="Fill" Stroke="Black" Height="77" HorizontalAlignment="Left" VerticalAlignment="Top" Width="77" MouseLeftButtonDown="path_MouseLeftButtonDown" MouseRightButtonDown="path_MouseRightButtonDown">
<Path.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1" />
<SkewTransform AngleX="0" AngleY="0" />
<RotateTransform Angle="0" />
<TranslateTransform X="0" Y="0" />
</TransformGroup>
</Path.RenderTransform>
<Path.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="#FF7E7E7E" Offset="1" />
</LinearGradientBrush>
</Path.Fill>
</Path>
</Grid>
</Window>
</code></pre>
<p>It's a continuous animation. In the codebehind I have the following:</p>
<pre><code>public partial class Window1 : Window
{
public Storyboard myStoryboard;
public Window1()
{
this.InitializeComponent();
// Insert code required on object creation below this point.
myStoryboard = (Storyboard)TryFindResource("OnLoaded1");
myStoryboard.Begin();
}
private void path_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
myStoryboard.Begin();
}
private void path_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
myStoryboard.Stop();
}
}
</code></pre>
<p>I get really sporadic control using the start and stop methods. Sometimes a stop works, but only if I've done the rightclick start first. I don't understand why STOP is not stopping it, and start is not starting it?</p>
<p>Thanks guys.</p>
| [
{
"answer_id": 342891,
"author": "discorax",
"author_id": 30408,
"author_profile": "https://Stackoverflow.com/users/30408",
"pm_score": 3,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Shapes;\nusing System.Media.Animation;\nusing System.Windows.Resources;\nusing System.Windows.Markup;\n// Make sure to include this reference to use Storyboard Class\nusing System.Windows.Media.Animation;\n\n\nnamespace StoryboardSample\n{\n public partial class Window1 : Window\n {\n // Set up the Storyboard variable\n public Storyboard myStoryboard;\n public Window1()\n {\n this.InitializeComponent();\n\n // Assign the Storyboard to the variable.\n myStoryboard = (Storyboard)TryFindResource(\"myStoryboard\");\n myFunction();\n\n }\n public void myFunction()\n {\n // Begin the Animation\n myStoryboard.Begin();\n }\n }\n}\n\n\n<Window\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n x:Class=\"StoryboardSample.Window1\"\n x:Name=\"Window\"\n Title=\"Window1\"\n Width=\"640\" Height=\"480\">\n <Window.Resources>\n <Storyboard x:Key=\"myStoryboard\">\n <DoubleAnimationUsingKeyFrames BeginTime=\"00:00:00\" Storyboard.TargetName=\"myRect\" Storyboard.TargetProperty=\"(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)\">\n <SplineDoubleKeyFrame KeyTime=\"00:00:00\" Value=\"0\"/>\n <SplineDoubleKeyFrame KeyTime=\"00:00:01\" Value=\"-71\"/>\n </DoubleAnimationUsingKeyFrames>\n </Storyboard>\n </Window.Resources>\n <Grid x:Name=\"LayoutRoot\">\n <Rectangle x:Name=\"myRect\" Fill=\"Black\" Width=\"300\" Height=\"150\" RenderTransformOrigin=\"0.5,0.5\" >\n <Rectangle.RenderTransform>\n <TransformGroup>\n <ScaleTransform ScaleX=\"1\" ScaleY=\"1\"/>\n <SkewTransform AngleX=\"0\" AngleY=\"0\"/>\n <RotateTransform Angle=\"0\"/>\n <TranslateTransform X=\"0\" Y=\"0\"/>\n </TransformGroup>\n </Rectangle.RenderTransform>\n </Rectangle>\n </Grid>\n</Window>\n"
},
{
"answer_id": 342903,
"author": "Robert Claypool",
"author_id": 23566,
"author_profile": "https://Stackoverflow.com/users/23566",
"pm_score": 0,
"selected": false,
"text": "<!-- Created by Chris Anderson: http://chrisa.wordpress.com -->\n<UserControl x:Class=\"SilverlightLOBFramework.Controls.Layout.WaitIndicator\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" \n Width=\"30\" Height=\"30\">\n\n <UserControl.Resources>\n <Storyboard x:Name=\"IndicatorStoryboard\">\n <ColorAnimationUsingKeyFrames \n Storyboard.TargetName=\"Ellipse1\"\n Storyboard.TargetProperty=\"(Fill).(SolidBrush.Color)\"\n BeginTime=\"0\" RepeatBehavior=\"Forever\">\n\n <LinearColorKeyFrame Value=\"#CCFFFFFF\" KeyTime=\"00:00:00\" />\n <LinearColorKeyFrame Value=\"#9CFFFFFF\" KeyTime=\"00:00:00.15\" />\n <LinearColorKeyFrame Value=\"#6DFFFFFF\" KeyTime=\"00:00:00.3\" />\n <LinearColorKeyFrame Value=\"#3EFFFFFF\" KeyTime=\"00:00:00.45\" />\n <LinearColorKeyFrame Value=\"#2EFFFFFF\" KeyTime=\"00:00:00.60\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.75\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.90\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:01.05\" />\n </ColorAnimationUsingKeyFrames>\n\n <ColorAnimationUsingKeyFrames \n Storyboard.TargetName=\"Ellipse2\"\n Storyboard.TargetProperty=\"(Fill).(SolidBrush.Color)\"\n BeginTime=\"0\" RepeatBehavior=\"Forever\">\n\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00\" />\n <LinearColorKeyFrame Value=\"#CCFFFFFF\" KeyTime=\"00:00:00.15\" />\n <LinearColorKeyFrame Value=\"#9CFFFFFF\" KeyTime=\"00:00:00.3\" />\n <LinearColorKeyFrame Value=\"#6DFFFFFF\" KeyTime=\"00:00:00.45\" />\n <LinearColorKeyFrame Value=\"#3EFFFFFF\" KeyTime=\"00:00:00.60\" />\n <LinearColorKeyFrame Value=\"#2EFFFFFF\" KeyTime=\"00:00:00.75\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.90\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:01.05\" />\n </ColorAnimationUsingKeyFrames>\n\n <ColorAnimationUsingKeyFrames \n Storyboard.TargetName=\"Ellipse3\"\n Storyboard.TargetProperty=\"(Fill).(SolidBrush.Color)\"\n BeginTime=\"0\" RepeatBehavior=\"Forever\">\n\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.15\" />\n <LinearColorKeyFrame Value=\"#CCFFFFFF\" KeyTime=\"00:00:00.3\" />\n <LinearColorKeyFrame Value=\"#9CFFFFFF\" KeyTime=\"00:00:00.45\" />\n <LinearColorKeyFrame Value=\"#6DFFFFFF\" KeyTime=\"00:00:00.60\" />\n <LinearColorKeyFrame Value=\"#3EFFFFFF\" KeyTime=\"00:00:00.75\" />\n <LinearColorKeyFrame Value=\"#2EFFFFFF\" KeyTime=\"00:00:00.90\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:01.05\" />\n </ColorAnimationUsingKeyFrames>\n\n <ColorAnimationUsingKeyFrames \n Storyboard.TargetName=\"Ellipse4\"\n Storyboard.TargetProperty=\"(Fill).(SolidBrush.Color)\"\n BeginTime=\"0\" RepeatBehavior=\"Forever\">\n\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.15\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.3\" />\n <LinearColorKeyFrame Value=\"#CCFFFFFF\" KeyTime=\"00:00:00.45\" />\n <LinearColorKeyFrame Value=\"#9CFFFFFF\" KeyTime=\"00:00:00.60\" />\n <LinearColorKeyFrame Value=\"#6DFFFFFF\" KeyTime=\"00:00:00.75\" />\n <LinearColorKeyFrame Value=\"#3EFFFFFF\" KeyTime=\"00:00:00.90\" />\n <LinearColorKeyFrame Value=\"#2EFFFFFF\" KeyTime=\"00:00:01.05\" />\n </ColorAnimationUsingKeyFrames>\n\n <ColorAnimationUsingKeyFrames \n Storyboard.TargetName=\"Ellipse5\"\n Storyboard.TargetProperty=\"(Fill).(SolidBrush.Color)\"\n BeginTime=\"0\" RepeatBehavior=\"Forever\">\n\n <LinearColorKeyFrame Value=\"#2EFFFFFF\" KeyTime=\"00:00:00\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.15\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.3\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.45\" />\n <LinearColorKeyFrame Value=\"#CCFFFFFF\" KeyTime=\"00:00:00.60\" />\n <LinearColorKeyFrame Value=\"#9CFFFFFF\" KeyTime=\"00:00:00.75\" />\n <LinearColorKeyFrame Value=\"#6DFFFFFF\" KeyTime=\"00:00:00.90\" />\n <LinearColorKeyFrame Value=\"#3EFFFFFF\" KeyTime=\"00:00:01.05\" />\n </ColorAnimationUsingKeyFrames>\n\n <ColorAnimationUsingKeyFrames \n Storyboard.TargetName=\"Ellipse6\"\n Storyboard.TargetProperty=\"(Fill).(SolidBrush.Color)\"\n BeginTime=\"0\" RepeatBehavior=\"Forever\">\n\n <LinearColorKeyFrame Value=\"#3EFFFFFF\" KeyTime=\"00:00:00\" />\n <LinearColorKeyFrame Value=\"#2EFFFFFF\" KeyTime=\"00:00:00.15\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.3\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.45\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.60\" />\n <LinearColorKeyFrame Value=\"#CCFFFFFF\" KeyTime=\"00:00:00.75\" />\n <LinearColorKeyFrame Value=\"#9CFFFFFF\" KeyTime=\"00:00:00.90\" />\n <LinearColorKeyFrame Value=\"#6DFFFFFF\" KeyTime=\"00:00:01.05\" />\n </ColorAnimationUsingKeyFrames>\n\n <ColorAnimationUsingKeyFrames \n Storyboard.TargetName=\"Ellipse7\"\n Storyboard.TargetProperty=\"(Fill).(SolidBrush.Color)\"\n BeginTime=\"0\" RepeatBehavior=\"Forever\">\n\n <LinearColorKeyFrame Value=\"#6DFFFFFF\" KeyTime=\"00:00:00\" />\n <LinearColorKeyFrame Value=\"#3EFFFFFF\" KeyTime=\"00:00:00.15\" />\n <LinearColorKeyFrame Value=\"#2EFFFFFF\" KeyTime=\"00:00:00.3\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.45\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.60\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.75\" />\n <LinearColorKeyFrame Value=\"#CCFFFFFF\" KeyTime=\"00:00:00.90\" />\n <LinearColorKeyFrame Value=\"#9CFFFFFF\" KeyTime=\"00:00:01.05\" />\n </ColorAnimationUsingKeyFrames>\n\n <ColorAnimationUsingKeyFrames \n Storyboard.TargetName=\"Ellipse8\"\n Storyboard.TargetProperty=\"(Fill).(SolidBrush.Color)\"\n BeginTime=\"0\" RepeatBehavior=\"Forever\">\n\n <LinearColorKeyFrame Value=\"#9CFFFFFF\" KeyTime=\"00:00:00\" />\n <LinearColorKeyFrame Value=\"#6DFFFFFF\" KeyTime=\"00:00:00.15\" />\n <LinearColorKeyFrame Value=\"#3EFFFFFF\" KeyTime=\"00:00:00.3\" />\n <LinearColorKeyFrame Value=\"#2EFFFFFF\" KeyTime=\"00:00:00.45\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.60\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.75\" />\n <LinearColorKeyFrame Value=\"#1EFFFFFF\" KeyTime=\"00:00:00.90\" />\n <LinearColorKeyFrame Value=\"#CCFFFFFF\" KeyTime=\"00:00:01.05\" />\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n </UserControl.Resources>\n\n <Canvas x:Name=\"LayoutRoot\">\n <Ellipse x:Name=\"Ellipse1\" Fill=\"#1EFFFFFF\" Canvas.Left=\"0\" Canvas.Top=\"11\" Height=\"8\" Width=\"8\"></Ellipse>\n <Ellipse x:Name=\"Ellipse2\" Fill=\"#1EFFFFFF\" Canvas.Left=\"3\" Canvas.Top=\"3\" Height=\"8\" Width=\"8\"></Ellipse>\n <Ellipse x:Name=\"Ellipse3\" Fill=\"#1EFFFFFF\" Canvas.Left=\"11\" Canvas.Top=\"0\" Height=\"8\" Width=\"8\"></Ellipse>\n <Ellipse x:Name=\"Ellipse4\" Fill=\"#2EFFFFFF\" Canvas.Left=\"19\" Canvas.Top=\"3\" Height=\"8\" Width=\"8\"></Ellipse>\n <Ellipse x:Name=\"Ellipse5\" Fill=\"#3EFFFFFF\" Canvas.Left=\"22\" Canvas.Top=\"11\" Height=\"8\" Width=\"8\"></Ellipse>\n <Ellipse x:Name=\"Ellipse6\" Fill=\"#6DFFFFFF\" Canvas.Left=\"19\" Canvas.Top=\"19\" Height=\"8\" Width=\"8\"></Ellipse>\n <Ellipse x:Name=\"Ellipse7\" Fill=\"#9CFFFFFF\" Canvas.Left=\"11\" Canvas.Top=\"22\" Height=\"8\" Width=\"8\"></Ellipse>\n <Ellipse x:Name=\"Ellipse8\" Fill=\"#CCFFFFFF\" Canvas.Left=\"3\" Canvas.Top=\"19\" Height=\"8\" Width=\"8\"></Ellipse>\n </Canvas>\n</UserControl>\n using System.Windows;\nusing System.Windows.Controls;\n\nnamespace SilverlightLOBFramework.Controls.Layout\n{\n public partial class WaitIndicator : UserControl\n {\n #region Constructor\n public WaitIndicator()\n {\n InitializeComponent();\n\n if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))\n LayoutRoot.Visibility = Visibility.Collapsed;\n } \n #endregion\n\n #region Public Functions\n public void Start()\n {\n LayoutRoot.Visibility = Visibility.Visible;\n IndicatorStoryboard.Begin();\n }\n\n public void Stop()\n {\n LayoutRoot.Visibility = Visibility.Collapsed;\n IndicatorStoryboard.Stop();\n } \n #endregion\n }\n}\n"
},
{
"answer_id": 350119,
"author": "discorax",
"author_id": 30408,
"author_profile": "https://Stackoverflow.com/users/30408",
"pm_score": 2,
"selected": false,
"text": "// Silverlight ONLY \nstoryboard.Stop(); \nstoryboard.Begin();\n public partial class Window1 : Window\n {\n public Storyboard myStoryboard;\n\n public Window1()\n {\n this.InitializeComponent();\n\n // Insert code required on object creation below this point.\n myStoryboard = (Storyboard)TryFindResource(\"OnLoaded1\");\n // This will loop your storyboard endlessly so you can use the Pause/Resume functions\n myStoryboard.Completed += new EventHandler(myStoryboard_Completed);\n // Begin the animation and immediately Pause it.\n myStoryboard.Begin();\n myStoryboard.Pause();\n }\n\n void myStoryboard_Completed(object sender, EventArgs e)\n {\n myStoryboard.Begin();\n\n }\n\n private void path_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n // Start the spinning again \n myStoryboard.Resume();\n }\n\n\n private void path_MouseRightButtonDown(object sender, MouseButtonEventArgs e)\n {\n // Pause the Spinning.\n myStoryboard.Pause();\n\n }\n\n }\n <Window.Triggers>\n <EventTrigger RoutedEvent=\"FrameworkElement.Loaded\">\n <!-- REMOVE THIS LINE\n <BeginStoryboard Storyboard=\"{StaticResource OnLoaded1}\"/>\n -->\n </EventTrigger>\n </Window.Triggers>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22451/"
] |
342,843 | <p>I want to calculate what is $x percentage of a $total. $x could be 15%, 20%, etc, and $total could be 1000, 2000, etc. So I'd want the 15% of 1000, for example.</p>
<p>What is the formula for calculating this? (I know this isn't <em>exactly</em> a coding question but I'm coding this feature and need help!</p>
| [
{
"answer_id": 342851,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "percentage = partialAmount / totalAmount\ntotalAmount = partialAmount / percentage\npartialAmount = percentage * totalAmount\n"
},
{
"answer_id": 342857,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 6,
"selected": true,
"text": "(actual / available) * 100 = percent // start\n\nactual / available = percent / 100\n\nactual = (percent / 100) * available // finish\n actual = (15 / 100) * 1000\nactual = 0.15 * 1000\nactual = 150\n"
},
{
"answer_id": 18817307,
"author": "bryan",
"author_id": 2756060,
"author_profile": "https://Stackoverflow.com/users/2756060",
"pm_score": -1,
"selected": false,
"text": "$x = 15;\n$total = 1000;\n$answer = $total * $x / 100\n"
},
{
"answer_id": 28463623,
"author": "Dave Berry",
"author_id": 4249988,
"author_profile": "https://Stackoverflow.com/users/4249988",
"pm_score": -1,
"selected": false,
"text": "#A Perl one liner to to do this is:\n$pc=$tot>0 ? sprintf('%.0f', $x/$tot*100 ).'%' : 'N/A';\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,844 | <p>I'm designing an html email for a Holiday Art Market. The request is simply for graphic design, make it pretty-put the date/time etc., but I'm wondering if I can also implement an RSVP form in the email: Are you coming, yes or no? Can this be done in an email, or do I need to redirect to a website? If it can be done, how?</p>
<p>Thanks again SOF community! </p>
| [
{
"answer_id": 342860,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": true,
"text": "http://www.yourdomain.com/rsvp.aspx?by=email@receiver.com&response=no\n\nhttp://www.yourdomain.com/rsvp.aspx?by=email@receiver.com&response=yes\n"
},
{
"answer_id": 342894,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<a href = \"www.yoursite.com/submit?from={$SenderEmailAddress}&answer=yes\">Yes</a>\n\n<a href = \"www.yoursite.com/submit?from={$SenderEmailAddress}&answer=no\">No</a>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39781/"
] |
342,862 | <p>I've been trying to refactor a "bit" of code that I'd previously developed. Basically, the project was my response to not knowing how to use XSLT effectively, so I developed an XML transformation system in PHP. The program reads through the tags of an XML file and does something along these lines to convert it to HTML:</p>
<pre><code>private function getTemplate(...) {
switch ($nodeName) {
case "a" :
// code here to generate a link tag
break;
case "box" :
// code here to generate the divs and whatnot to create a box
break;
case "ref" :
// look up an external reference file and include a bibliography
break;
default :
// do the default thing
}
}
</code></pre>
<p>That was all working great, except that I ended up with 26 branches to my switch, and that once switch block was over 1000 lines of code. Needless to say, it made maintenance slightly more difficult.</p>
<p>What I've done now is to pull the code of each branch out into its own file (named "a.php", "box.php", "ref.php" ...) and <code>include</code> that file each time:</p>
<pre><code>if (file_exists("templates/$nodeName.php")) {
include "templates/$nodeName.php";
} else {
// do the default thing
}
</code></pre>
<p>Again, this works, but benchmarking it shows that it has slowed down processing times by 50%. I'm assuming that this is because there's now up to 4000 <code>include</code>s being done now.</p>
<p>What I was considering was to put the code for each template into a function, and if the function hasn't been declared then include the file, and then run the function - the only problem with that is that the existing code has been written in the scope of the original function, using <code>$this</code>, etc.</p>
<p>Given that this code is not run in real time (eg: it merely processes the XML into static HTML files which are stored - it's not done on the fly), do you have any advice for me here?</p>
| [
{
"answer_id": 342877,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "private function getTemplate(...) \n{\n $func = $nodeName + \"_converter\";\n if (function_exists($func)) //see if function is defined, somehow...\n {\n $func(); //call conversion function (pass whatever is needed)\n }\n}\n"
},
{
"answer_id": 343627,
"author": "Amr Mostafa",
"author_id": 43597,
"author_profile": "https://Stackoverflow.com/users/43597",
"pm_score": 1,
"selected": false,
"text": "NodeProcessor ANodeProcessor RefNodeProcessor NodeProcessor processTag $this->processNode($tag); $name = 'process'. $tag; return $this->nodeProcessor->{$name}; NodeProcessor __call() processTag"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
342,896 | <p>I am planning to use this to poll a database which can take close to 10-15 minutes or more, so should I be using timers for this.</p>
| [
{
"answer_id": 343766,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "java.util.concurrent.ScheduledThreadPoolExecutor java.util.Timer Timer TimerTask"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,910 | <p>This is the trace of my app,when I updated my device to 2.2.</p>
<p>any idea to get rid of this leak? because I think that's the culprit who keep crashing my application.<br>
This is trace when I run my application in os2.2,see the image which show the part which might be generating leak,and if you can give me some hints to resolve it, will be greatly appreciated.</p>
<p><a href="http://origindata.wapfly.com.au/extra/Picture%204.png" rel="nofollow noreferrer">alt text http://origindata.wapfly.com.au/extra/Picture%204.png</a></p>
<p><a href="http://origindata.wapfly.com.au/extra/Picture%203.png" rel="nofollow noreferrer">alt text http://origindata.wapfly.com.au/extra/Picture%203.png</a>
This is trace when I run my application in os2.1.it's very wired issue.
<a href="http://origindata.wapfly.com.au/extra/Picture%205.png" rel="nofollow noreferrer">alt text http://origindata.wapfly.com.au/extra/Picture%205.png</a></p>
| [
{
"answer_id": 346038,
"author": "wisequark",
"author_id": 33159,
"author_profile": "https://Stackoverflow.com/users/33159",
"pm_score": 1,
"selected": false,
"text": "scan-build xcodebuild scan-view /tmp/logs/..."
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451867/"
] |
342,933 | <p>I'd like to put in an UIButton in the center of the navigation bar. Based on the document, it appears I need to set title view, and make sure the leftBarButtonItem is nil. But it is not work for me. Here is the code.</p>
<pre><code>UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"List" forState:UIControlStateNormal];
self.navigationItem.leftBarButtonItem = nil;
[self.navigationItem.titleView addSubview:btn];
</code></pre>
| [
{
"answer_id": 342952,
"author": "August",
"author_id": 30966,
"author_profile": "https://Stackoverflow.com/users/30966",
"pm_score": 3,
"selected": false,
"text": "self.navigationItem.titleView = btn;\n"
},
{
"answer_id": 346035,
"author": "wisequark",
"author_id": 33159,
"author_profile": "https://Stackoverflow.com/users/33159",
"pm_score": 6,
"selected": true,
"text": "frame UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];\nbtn.frame = CGRectMake(0, 0, 400, kCustomButtonHeight);\n[btn setTitle:@\"list\" forState:UIControlStateNormal];\nself.navigationItem.titleView = btn;\n"
},
{
"answer_id": 28743076,
"author": "Robert",
"author_id": 296446,
"author_profile": "https://Stackoverflow.com/users/296446",
"pm_score": 4,
"selected": false,
"text": "self.parentViewController.navigationItem.titleView = titleView;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32096/"
] |
342,954 | <p>A bit of a neophyte haskell question, but I came across this example in Haskell's <a href="http://www.haskell.org/haskellwiki/99_questions/1_to_10" rel="noreferrer">tutorial examples</a>. For "find the last element of a list" there are some obvious versions, like </p>
<pre><code>last' [x] = x
last' (_:xs) = last' xs
</code></pre>
<p>But I can't make sense of an alternate version presented: </p>
<pre><code>myLast' = foldr1 (const id)
</code></pre>
<p>So, in trying to make sense of what the application of the id function is doing, I tried in ghci:</p>
<pre><code>const id 1 2 -> gives 2
</code></pre>
<p>This binds like this:</p>
<pre><code>(const id) 1 2 -> gives 2
</code></pre>
<p>And not like this:</p>
<pre><code> const (id 1) 2 -> gives 1
</code></pre>
<p>But I'm not making sense of this. <code>(const id)</code> should translate to something like </p>
<pre><code>`(\x y->x) (\x->x)`
</code></pre>
<p>Shouldn't this return a function that simply returns the id of its first element? Or, how is the function order making (const id) behave differently than const? </p>
| [
{
"answer_id": 343036,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": true,
"text": "const const x = \\_ -> x\n (const id) id const id 1 2 = (\\_ -> id) 1 2\n = id 2\n = 2\n foldr1 foldr1 f [x] = x\nfoldr1 f (x:xs) = f x (foldr1 f xs)\n myLast' = foldr1 (const id)\n myLast' [x] = foldr1 (const id) [x]\n {- definition of foldr1 -}\n = x\n myLast' (x:xs) = foldr1 (const id) (x:xs)\n {- definition of foldr1 -}\n = (const id) x (foldr1 (const id) xs)\n {- definition of const -} \n = (\\_ -> id) x (foldr1 (const id) xs)\n {- function application -} \n = id (foldr1 (const id) xs)\n {- definition of id -} \n = foldr1 (const id) xs\n {- definition of myLast' -} \n = myLast' xs\n last'"
},
{
"answer_id": 348064,
"author": "Magnus",
"author_id": 34996,
"author_profile": "https://Stackoverflow.com/users/34996",
"pm_score": 3,
"selected": false,
"text": ":t Prelude> :t const id\nconst id :: b -> a -> a"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19479/"
] |
342,961 | <p>When you are developing a web-based application and you want to allow richly formatted text from the user you have to make a choice about how to allow that input. Many different markup languages have been created because it is arguably more difficult to sanitize HTML.</p>
<p>What are the advantages and disadvantages of the various different markup languages like:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/HTML" rel="noreferrer">HTML</a> </li>
<li><a href="http://daringfireball.net/projects/markdown/" rel="noreferrer">Markdown</a></li>
<li><a href="http://en.wikipedia.org/wiki/BBCode" rel="noreferrer">BBCode</a></li>
<li><a href="http://www.textism.com/tools/textile/" rel="noreferrer">Textile</a></li>
<li><a href="http://www.mediawiki.org/" rel="noreferrer">MediaWiki markup</a></li>
<li><a href="http://en.wikipedia.org/wiki/Lightweight_markup_language" rel="noreferrer">other</a></li>
</ul>
<p>Or to put it differently, what factors do you consider when choosing to use a particular markup language.</p>
| [
{
"answer_id": 17640402,
"author": "Community",
"author_id": 2327283,
"author_profile": "https://Stackoverflow.com/users/2327283",
"pm_score": 0,
"selected": false,
"text": "<li> <strong> htmlspecialchars() strip_tags()"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20267/"
] |
342,964 | <p>Suppose I have this interface</p>
<pre><code>public interface IFoo
{
///<summary>
/// Foo method
///</summary>
void Foo();
///<summary>
/// Bar method
///</summary>
void Bar();
///<summary>
/// Situation normal
///</summary>
void Snafu();
}
</code></pre>
<p>And this class</p>
<pre><code>public class Foo : IFoo
{
public void Foo() { ... }
public void Bar() { ... }
public void Snafu() { ... }
}
</code></pre>
<p>Is there a way, or is there a tool that can let me automatically put in the comments of each member in a base class or interface?</p>
<p>Because I hate re-writing the same comments for each derived sub-class!</p>
| [
{
"answer_id": 342968,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": true,
"text": "FlingThing() \"Flings the Thing\""
},
{
"answer_id": 343072,
"author": "Dennis",
"author_id": 73025,
"author_profile": "https://Stackoverflow.com/users/73025",
"pm_score": 5,
"selected": false,
"text": "/// <inheritdoc/>"
},
{
"answer_id": 3910463,
"author": "JeffHeaton",
"author_id": 173355,
"author_profile": "https://Stackoverflow.com/users/173355",
"pm_score": 4,
"selected": false,
"text": "/**\n * {@inheritDoc}\n */\n <inheritDoc/>\n"
},
{
"answer_id": 7571614,
"author": "Vadim",
"author_id": 82005,
"author_profile": "https://Stackoverflow.com/users/82005",
"pm_score": 8,
"selected": false,
"text": "<inheritdoc /> public class Foo : IFoo\n{\n /// <inheritdoc />\n public void Foo() { ... }\n /// <inheritdoc />\n public void Bar() { ... }\n /// <inheritdoc />\n public void Snafu() { ... }\n}\n cref public class Foo\n{\n /// <inheritdoc cref=\"System.String.IndexOf\" />\n public void Bar() { ... } // this method will now have the documentation of System.String.IndexOf\n}\n"
},
{
"answer_id": 41937649,
"author": "Mathias Rotter",
"author_id": 5126465,
"author_profile": "https://Stackoverflow.com/users/5126465",
"pm_score": 3,
"selected": false,
"text": "<see /> /// <summary>\n/// Implementation of <see cref=\"IFoo\"/>.\n/// </summary>\npublic class Foo : IFoo\n{\n /// <summary>\n /// See <see cref=\"IFoo\"/>.\n /// </summary>\n public void Foo() { ... }\n\n /// <summary>\n /// See <see cref=\"IFoo.Bar\"/>\n /// </summary>\n public void Bar() { ... }\n\n /// <summary>\n /// This implementation of <see cref=\"IFoo.Snafu\"/> uses the a caching algorithm for performance optimization.\n /// </summary>\n public void Snafu() { ... }\n}\n /// <inheritdoc/>"
},
{
"answer_id": 47899917,
"author": "K Johnson",
"author_id": 6728598,
"author_profile": "https://Stackoverflow.com/users/6728598",
"pm_score": 1,
"selected": false,
"text": "<inheritdoc/>"
},
{
"answer_id": 52399537,
"author": "gatsby",
"author_id": 5775048,
"author_profile": "https://Stackoverflow.com/users/5775048",
"pm_score": 4,
"selected": false,
"text": "/// <inheritdoc cref=\"YourClass.YourMethod\"/> --> For methods inheritance\n /// <inheritdoc cref=\"YourClass\"/> --> For directly class inheritance\n /// <summary>\n /// This method is awesome!\n /// </summary>\n /// <param name=\"awesomeParam\">The awesome parameter of the month!.</param>\n /// <returns>A <see cref=\"AwesomeObject\"/> that is also awesome...</returns>\n AwesomeObject CreateAwesome(WhateverObject awesomeParam);\n"
},
{
"answer_id": 57467928,
"author": "Konard",
"author_id": 710069,
"author_profile": "https://Stackoverflow.com/users/710069",
"pm_score": 0,
"selected": false,
"text": "<include> <GenerateDocumentationFile>true</GenerateDocumentationFile> .csproj namespace YourNamespace\n{\n /// <summary>\n /// Represents interface for a type.\n /// </summary>\n public interface IType\n {\n /// <summary>\n /// Executes an action in read access mode.\n /// </summary>\n void ExecuteAction();\n }\n}\n using System;\n\nnamespace YourNamespace\n{\n /// <summary>\n /// A type inherited from <see cref=\"IType\"/> interface.\n /// </summary>\n public class InheritedType : IType\n {\n /// <include file='bin\\Release\\netstandard2.0\\YourNamespace.xml' path='doc/members/member[@name=\"M:YourNamespace.IType.ExecuteAction()\"]/*'/>\n public void ExecuteAction() => Console.WriteLine(\"Action is executed.\");\n }\n}\n YourNamespace.xml Debug Release Debug file include member name Documentation.xml <inheritdoc/> <include/> /// <inheritdoc />\n /// <include file='bin\\Release\\netstandard2.0\\Platform.Threading.xml' path='doc/members/member[@name=\"M:Platform.Threading.Synchronization.ISynchronization.ExecuteReadOperation(System.Action)\"]/*'/>\n public void ExecuteReadOperation(Action action) => action();\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18731/"
] |
342,966 | <p>How do I group search results returned by Lucene by fields (similar to SQL Server's)?</p>
| [
{
"answer_id": 343120,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 0,
"selected": false,
"text": "org.apache.lucene.search.Sort Sort"
},
{
"answer_id": 7517135,
"author": "mihaicc",
"author_id": 648904,
"author_profile": "https://Stackoverflow.com/users/648904",
"pm_score": 2,
"selected": false,
"text": "doc1: monday, 1pm, 3min \ndoc2: monday, 1pm, 4min \ndoc3: monday, 2pm, 3min\n monday :3\nmonday/1pm :2\nmonday/1pm/3min :1\nmonday/1pm/4min :1\nmonday/2pm :1\nmonday/2pm/3min :1\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43478/"
] |
342,969 | <p>Case in point: </p>
<p>I'm a on mac with bash v3.2.17, I'm using git installed via macports with the bash_completion variant.</p>
<p>When I type <code>git checkout m<tab></code>. for example, I get it completed to <code>master</code>.</p>
<p>However, I've got an alias to <code>git checkout</code>, <code>gco</code>. When I type <code>gco m<tab></code>, I don't get the branch name autocompleted.</p>
<p>Ideally I'd like autocompletion to just magically work for all my aliases. Is it possible? Failing that, I'd like to manually customize it for each alias. So, how do I go about either?</p>
| [
{
"answer_id": 343013,
"author": "Chris Lloyd",
"author_id": 42413,
"author_profile": "https://Stackoverflow.com/users/42413",
"pm_score": 4,
"selected": false,
"text": "git-completion.bash complete -o default -o nospace -F _git git\n .bash_profile complete -o default -o nospace -F _git_checkout gco\n"
},
{
"answer_id": 344211,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 3,
"selected": false,
"text": "~/.gitconfig [alias]\n co = checkout\n git co m<TAB> git co master git checkout"
},
{
"answer_id": 1793178,
"author": "Hesky Fisher",
"author_id": 1406713,
"author_profile": "https://Stackoverflow.com/users/1406713",
"pm_score": 6,
"selected": false,
"text": "# wrap_alias takes three arguments:\n# $1: The name of the alias\n# $2: The command used in the alias\n# $3: The arguments in the alias all in one string\n# Generate a wrapper completion function (completer) for an alias\n# based on the command and the given arguments, if there is a\n# completer for the command, and set the wrapper as the completer for\n# the alias.\nfunction wrap_alias() {\n [[ \"$#\" == 3 ]] || return 1\n\n local alias_name=\"$1\"\n local aliased_command=\"$2\"\n local alias_arguments=\"$3\"\n local num_alias_arguments=$(echo \"$alias_arguments\" | wc -w)\n\n # The completion currently being used for the aliased command.\n local completion=$(complete -p $aliased_command 2> /dev/null)\n\n # Only a completer based on a function can be wrapped so look for -F\n # in the current completion. This check will also catch commands\n # with no completer for which $completion will be empty.\n echo $completion | grep -q -- -F || return 0\n\n local namespace=alias_completion::\n\n # Extract the name of the completion function from a string that\n # looks like: something -F function_name something\n # First strip the beginning of the string up to the function name by\n # removing \"* -F \" from the front.\n local completion_function=${completion##* -F }\n # Then strip \" *\" from the end, leaving only the function name.\n completion_function=${completion_function%% *}\n\n # Try to prevent an infinite loop by not wrapping a function\n # generated by this function. This can happen when the user runs\n # this twice for an alias like ls='ls --color=auto' or alias l='ls'\n # and alias ls='l foo'\n [[ \"${completion_function#$namespace}\" != $completion_function ]] && return 0\n\n local wrapper_name=\"${namespace}${alias_name}\"\n\n eval \"\nfunction ${wrapper_name}() {\n let COMP_CWORD+=$num_alias_arguments\n args=( \\\"${alias_arguments}\\\" )\n COMP_WORDS=( $aliased_command \\${args[@]} \\${COMP_WORDS[@]:1} )\n $completion_function\n }\n\"\n\n # To create the new completion we use the old one with two\n # replacements:\n # 1) Replace the function with the wrapper.\n local new_completion=${completion/-F * /-F $wrapper_name }\n # 2) Replace the command being completed with the alias.\n new_completion=\"${new_completion% *} $alias_name\"\n\n eval \"$new_completion\"\n}\n\n# For each defined alias, extract the necessary elements and use them\n# to call wrap_alias.\neval \"$(alias -p | sed -e 's/alias \\([^=][^=]*\\)='\\''\\([^ ][^ ]*\\) *\\(.*\\)'\\''/wrap_alias \\1 \\2 '\\''\\3'\\'' /')\"\n\nunset wrap_alias\n"
},
{
"answer_id": 2078422,
"author": "hcs42",
"author_id": 17916,
"author_profile": "https://Stackoverflow.com/users/17916",
"pm_score": 3,
"selected": false,
"text": ".bashrc .bash_profile # Author.: Ole J\n# Date...: 23.03.2008\n# License: Whatever\n\n# Wraps a completion function\n# make-completion-wrapper <actual completion function> <name of new func.>\n# <command name> <list supplied arguments>\n# eg.\n# alias agi='apt-get install'\n# make-completion-wrapper _apt_get _apt_get_install apt-get install\n# defines a function called _apt_get_install (that's $2) that will complete\n# the 'agi' alias. (complete -F _apt_get_install agi)\n#\nfunction make-completion-wrapper () {\n local function_name=\"$2\"\n local arg_count=$(($#-3))\n local comp_function_name=\"$1\"\n shift 2\n local function=\"\nfunction $function_name {\n ((COMP_CWORD+=$arg_count))\n COMP_WORDS=( \"$@\" \\${COMP_WORDS[@]:1} )\n \"$comp_function_name\"\n return 0\n}\"\n eval \"$function\"\n}\n\n# and now the commands that are specific to this SO question\n\nalias gco='git checkout'\n\n# we create a _git_checkout_mine function that will do the completion for \"gco\"\n# using the completion function \"_git\"\nmake-completion-wrapper _git _git_checkout_mine git checkout\n\n# we tell bash to actually use _git_checkout_mine to complete \"gco\"\ncomplete -o bashdefault -o default -o nospace -F _git_checkout_mine gco\n"
},
{
"answer_id": 10707579,
"author": "wonderfulthunk",
"author_id": 8232,
"author_profile": "https://Stackoverflow.com/users/8232",
"pm_score": 4,
"selected": false,
"text": "$ g co <branchname>\n __git_complete git _git\n __git_complete g _git\n"
},
{
"answer_id": 15009611,
"author": "chris_sutter",
"author_id": 498995,
"author_profile": "https://Stackoverflow.com/users/498995",
"pm_score": 9,
"selected": true,
"text": "complete -o default -o nospace -F _git_checkout gco\n __git_complete __git_complete gco _git_checkout\n"
},
{
"answer_id": 35659508,
"author": "kub1x",
"author_id": 336753,
"author_profile": "https://Stackoverflow.com/users/336753",
"pm_score": 3,
"selected": false,
"text": "~/.bash_completion gco git checkout _xfunc git __git_complete gco _git_checkout\n ~/.bashrc alias gco='git checkout'\n ~/bash_completion /usr/share/bash-completion/bash_completion _xfunc git git-completion ~/.bashrc .git-completion.sh ~/.bashrc git-completion"
},
{
"answer_id": 40463700,
"author": "luckydonald",
"author_id": 3423324,
"author_profile": "https://Stackoverflow.com/users/3423324",
"pm_score": 2,
"selected": false,
"text": "complete alias d-m=\"docker-machine\" d-m docker-machine cd `brew --prefix`/etc/bash_completion.d/ docker-machine complete -F _docker_machine docker-machine\n complete -F _docker_machine docker-machine\ncomplete -F _docker_machine d-m\n"
},
{
"answer_id": 51548508,
"author": "wisbucky",
"author_id": 1081043,
"author_profile": "https://Stackoverflow.com/users/1081043",
"pm_score": 2,
"selected": false,
"text": "$ complete | grep git\n\ncomplete -o bashdefault -o default -o nospace -F __git_wrap__git_main git\n # copy the original statement, but replace the last command (git) with your alias (g)\ncomplete -o bashdefault -o default -o nospace -F __git_wrap__git_main g\n\n# load dynamically loaded completion functions (may not be required)\n_completion_loader git\n _completion_loader TAB TAB"
},
{
"answer_id": 55241227,
"author": "Sukima",
"author_id": 227176,
"author_profile": "https://Stackoverflow.com/users/227176",
"pm_score": 1,
"selected": false,
"text": "alias g=git g brew install git # Alias g to git\n\ng() {\n if [[ $# > 0 ]]; then\n git \"$@\"\n else\n git status -sb\n fi\n}\n\n# Preload git completion in Ubuntu which is normally lazy loaded but we need\n# the __git_wrap__git_main function available for our completion.\nif [[ -e /usr/share/bash-completion/completions/git ]]; then\n source /usr/share/bash-completion/completions/git\nelif [[ -e /usr/local/etc/bash_completion.d/git-completion.bash ]]; then\n source /usr/local/etc/bash_completion.d/git-completion.bash\nfi\n\nif command_exists __git_complete; then\n __git_complete g _git\nelif command_exists __git_wrap__git_main; then\n complete -o bashdefault -o default -o nospace -F __git_wrap__git_main g\nfi\n"
},
{
"answer_id": 55734269,
"author": "Druta Ruslan",
"author_id": 7003620,
"author_profile": "https://Stackoverflow.com/users/7003620",
"pm_score": -1,
"selected": false,
"text": "alias g='git' .bash_aliases complete -o default -o nospace -F _git g\n"
},
{
"answer_id": 65486082,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "git_complete gf git_fetch\n git_complete _git_complete _GIT_complete __git_complete gf _git_fetch\n __git_complete gk __gitk_main\n __git_complete gf git_fetch\n__git_complete gk gitk\n $2 __$2_main _$2"
},
{
"answer_id": 66564954,
"author": "Quasímodo",
"author_id": 8133920,
"author_profile": "https://Stackoverflow.com/users/8133920",
"pm_score": 0,
"selected": false,
"text": "alias-expand-line complete ~/.inputrc \"\\M-z\":alias-expand-line\n\"\\M-x\":complete\nTAB:\"\\M-z\\M-x\"\n man 3 readline gco m<TAB>\n git checkout master\n"
},
{
"answer_id": 71904065,
"author": "Raz Luvaton",
"author_id": 5923666,
"author_profile": "https://Stackoverflow.com/users/5923666",
"pm_score": -1,
"selected": false,
"text": "# For each defined alias, extract the necessary elements and use them\n# to call wrap_alias.\neval \"$(alias -p | sed -e 's/alias \\([^=][^=]*\\)='\\''\\([^ ][^ ]*\\) *\\(.*\\)'\\''/wrap_alias \\1 \\2 '\\''\\3'\\'' /')\"\n # For each defined alias, extract the necessary elements and use them\n# to call wrap_alias.\neval \"$(alias | sd '^([^=]+)=(.+)' 'wrap_alias $1=$2')\"\n sd sed sd alias -p alias alias <something>=<value>\n <something>=<value>\n .zlogin"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
] |
342,973 | <p>We use Perl for GUI test automation. It has been very successful. We have written a very lightweight DSL kind of language for GUI testing. The DSL is very similar to a object model.</p>
<p>For example, we have an Application object at the root. Each property sheet in the application is a View object. Each page under the page is called Page object itself.
From Perl we send commands to a GUI application and the GUI interpret the command and respond to the command nicely. To send a command we do the following:</p>
<pre><code>socket_object->send_command("App.View2.Page2.Activate()")
socket_object->send_command("App.View1.Page3.OKBtn.Click()")
</code></pre>
<p>This is not very readable. Instead, I want to write a Perl DSL for App, View and Page.
Does Perl provide some sort of DSL structure where I can do the following?</p>
<pre><code>App.View2.Page2.Activate();
App.View1.Page2.Click();
</code></pre>
<p>Where App shall be an instance of the Application class. I have to get the object of View2 at run time.</p>
<p>How to use such a things?</p>
| [
{
"answer_id": 343026,
"author": "derobert",
"author_id": 27727,
"author_profile": "https://Stackoverflow.com/users/27727",
"pm_score": 2,
"selected": false,
"text": "-> . App->View2->Page2->Activate() $App->View2->Page2->Active() sub _new_view {\n my ($view, $view_num);\n\n # ...\n # ... (code to create $view object)\n # ...\n\n my $sym = \"App::View$view_num\";\n *$sym = sub { return $view }; # can also use Symbol package\n}\n AUTOLOAD send_command"
},
{
"answer_id": 343054,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 5,
"selected": true,
"text": "AUTOLOAD . App->View2->Page2->Activate(); \nApp->View1->Page2->Click();\n App View2 AUTOLOAD Page2 Activate Click"
},
{
"answer_id": 345461,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": false,
"text": "package RemoteAppScript;\nuse Filter::Simple; # The basis of many a sane source filter\nuse Smart::Comments; # treat yourself and install this if you don't have \n # it... or just comment it out.\n\n# Simple test sub\nsub send_command { \n my $cmd = shift;\n print qq(Command \"$cmd\" sent.\\n);\n return;\n}\n\n# The list of commands\nmy @script_list;\n\n# The interface to Filter::Simple's method of source filters.\nFILTER { \n # Save $_, because Filter::Simple doesn't like you reading more than once.\n my $mod = $_;\n\n # v-- Here a Smart::Comment.\n ### $mod\n\n # Allow for whole-line perl style comments in the script\n $mod =~ s/^\\s*#.*$//m;\n\n # 1. Break the package up into commands by split\n # 2. Trim the strings, if needed\n # 3. lose the entries that are just blank strings.\n @script_list \n = grep { length } \n map { s/^\\s+|\\s+$//g; $_ } \n split /;/, $mod\n ;\n ### @script_list\n\n # Replace the whole script with a command to run the steps.\n $_ = __PACKAGE__ . '::run_script();';\n # PBP.\n return;\n};\n\n# Here is the sub that performs each action.\nsub run_script { \n ### @script_list\n foreach my $command ( @script_list ) {\n #send_command( $command );\n socket_object->send_command( $command );\n }\n}\n\n1;\n RemoteAppScript.pm perl -MData::Dumper -e 'print Dumper( \\@INC ), \"\\n\"' use RemoteAppScript;\nApp.View2.Page2.Activate();\nApp.View1.Page2.Click();\n FILTER App.View2.Page2.Activate();\nApp.View1.Page2.Click();\n #!/bin/perl -w \n\nmy $script = do { \n local $/;\n <ARGV>;\n};\n\n$script =~ s/^\\s*#.*$//m;\n\nforeach my $command ( \n grep { length() } map { s/^\\s+|\\s+$//g; $_ } split /;/, $script \n) { \n socket_object->send_command( $command );\n}\n perl run_remote_script.pl remote_app_script.ras\n"
},
{
"answer_id": 3990157,
"author": "MkV",
"author_id": 46235,
"author_profile": "https://Stackoverflow.com/users/46235",
"pm_score": 0,
"selected": false,
"text": "'.' -> package App::DSL;\nuse strict; \nuse warnings;\n# use to avoid *{\"App::View::$view::method\"} = \\&sub and friends\nuse Package::Stash;\n\nsub new_view(%);\nour %views;\n\n# use App::DSL (View1 => {attr1 => 'foo', attr2 => 'bar'}); \nsub import {\n my $class = shift;\n my %new_views = @_ or die 'No view specified';\n\n foreach my $view (keys %new_views) {\n my $stash = Package::Stash->new(\"App::View::$view\");\n # In our AUTOLOAD we create a closure over the right\n # App::View object and call the right method on it\n # for this example I just used _api_\\L$method as the\n # internal method name (Activate => _api_activate)\n $stash->add_package_symbol('&AUTOLOAD' => \n sub { \n our $AUTOLOAD;\n my ($method) = \n $AUTOLOAD =~ m{App::View::\\Q$view\\E::(.*)};\n my $api_method = \"_api_\\L$method\";\n die \"Invalid method $method on App::View::$view\"\n unless my $view_sub = App::View->can($api_method);\n my $view_obj = $views{$view}\n or die \"Invalid View $view\";\n my $sub = sub {\n $view_obj->$view_sub();\n };\n # add the function to the package, so that AUTOLOAD\n # won't need to be called for this method again\n $stash->add_package_symbol(\"\\&$method\" => $sub);\n goto $sub;\n });\n $views{$view} = bless $new_views{$view}, 'App::View';\n }\n}\n\npackage App::View;\n\n# API Method App::View::ViewName::Activate;\nsub _api_activate {\n my $self = shift;\n # do something with $self here, which is the view \n # object created by App::DSL\n warn $self->{attr1};\n}\n\n1;\n use strict;\nuse warnings;\n# Create App::View::View1 and App::View::View2\nuse App::DSL (View1 => {attr1 => 'hello'}, View2 => {attr1 => 'bye'});\nApp::View::View1::Activate();\nApp::View::View2::Activate();\nApp::View::View1::Activate();\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43056/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.