qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
335,781 | <p>We are in the process of converting our main build process from ant to maven. We use TeamCity for our Continuous Integration server (CI).</p>
<p>We'd like to use the CI server to kick off (nightly) builds whose version contain a build number, as in 1.0.0.build#. These builds would be installed in our local maven repository to be used by other projects. So the CI server would manage the versions, maven would build the project, and the maven repository would make the builds accessible to other projects.</p>
<p>I intended to initiate the build from the CI server using the following command:</p>
<pre><code>mvn -Dversion=1.0.0.25 install
</code></pre>
<p>The project's pom would have a bogus version number, and the -D flag would override it, as in:</p>
<pre><code><version>0.0.0.0</version>
</code></pre>
<p>The problem with this method is that the maven install plugin only uses the version in the pom file, not the version passed in on the command line. This is noted in <a href="http://jira.codehaus.org/browse/MINSTALL-30" rel="noreferrer">this maven issue</a>.</p>
<p>So since this issue has existed since 08/2006 and has not been fixed, I assume that this is somehow not '<em>the maven way</em>'. So my question is, how can maven be used in a continuous integration situation to install versioned artifacts in the repository?</p>
| [
{
"answer_id": 336080,
"author": "shek",
"author_id": 40618,
"author_profile": "https://Stackoverflow.com/users/40618",
"pm_score": 4,
"selected": true,
"text": "<version>#.#.#-SNAPSHOT</version>\n <snapshotRepository>\n <uniqueVersion>true</uniqueVersion>\n <id>your-snapshot-repo-id</id>\n <name>Your Snapshots</name>\n <url>http://your-snapshot-repo-url/maven</url>\n</snapshotRepository>\n"
},
{
"answer_id": 350865,
"author": "Matthew Jaskula",
"author_id": 4356,
"author_profile": "https://Stackoverflow.com/users/4356",
"pm_score": 2,
"selected": false,
"text": "<project xmlns=\"...\" xmlns:xsi=\"...\" xsi:schemaLocation=\"...\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.stackoverflow</groupId>\n <artifactId>stackoverflow</artifactId>\n <version>${ciVersion}</version>\n <packaging>jar</packaging>\n <name>StackOverflow</name>\n\n <properties>\n <ciVersion>0.0.0.0</ciVersion>\n </properties>\n\n ...\n\n</project>\n mvn -DciVersion=1.0.0.25 install\n"
},
{
"answer_id": 12312736,
"author": "Joern",
"author_id": 933106,
"author_profile": "https://Stackoverflow.com/users/933106",
"pm_score": 3,
"selected": false,
"text": "${ciVersion} <project xmlns=\"...\" xmlns:xsi=\"...\" xsi:schemaLocation=\"...\">\n <modelVersion>4.0.0</modelVersion>\n <parent>\n <artifactId>myParent</artifactId>\n <groupId>com.stackoverflow</groupId>\n <version>${ciVersion}</version>\n </parent>\n <artifactId>myChild</artifactId>\n ...\n</project>\n myChild myParent ${ciVersion} ...\n<build>\n <plugins>\n <plugin>\n <groupId>com.sap.prd.mobile.ios.maven.plugins</groupId>\n <artifactId>resolve-pom-maven-plugin</artifactId>\n <version>1.0</version>\n <executions>\n <execution>\n <id>resolve-pom-props</id>\n <goals>\n <goal>resolve-pom-props</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n</build>\n...\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4356/"
] |
335,792 | <p>In visual studio 2008, when I drag a database table into my dbml screen, any tables that end with the letter s automatcially get the s removed from the dbml object. Is there any way to disable this?</p>
<p>Also, the collection of rows also gets an s appended to the collection property name. Is there a way to change that as well?</p>
<p>Thanks</p>
| [
{
"answer_id": 27265070,
"author": "Nicholas Petersen",
"author_id": 264031,
"author_profile": "https://Stackoverflow.com/users/264031",
"pm_score": 0,
"selected": false,
"text": " [Table(\"QTPhotos\")]\n public class QTPhoto \n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,799 | <p>Is there an HTML editor which automatically changes the end tag when you edit the start tag?</p>
| [
{
"answer_id": 29274948,
"author": "ROMANIA_engineer",
"author_id": 3885376,
"author_profile": "https://Stackoverflow.com/users/3885376",
"pm_score": 0,
"selected": false,
"text": "div span <div> Text </div>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6691/"
] |
335,805 | <p>I have a 'reference' SQL Server 2005 database that is used as our global standard. We're all set up for keeping general table schema and data properly synchronized, but don't yet have a good solution for other objects like views, stored procedures, and user-defined functions.</p>
<p>I'm aware of products like <a href="http://www.red-gate.com/products/SQL_Compare/index.htm" rel="nofollow noreferrer">Redgate's SQL Compare</a>, but we don't really want to rely on (any further) 3rd-party tools right now.</p>
<p>Is there a way to ensure that a given stored procedure or view on the reference database, for example, is up to date on the target databases? Can this be scripted?</p>
<p>Edit for clarification: when I say 'scripted', I mean running a script that pushes out any changes to the target servers. Not running the same CREATE/ALTER script multiple times on multiple servers.</p>
<p>Any advice/experience on how to approach this would be much appreciated.</p>
| [
{
"answer_id": 456196,
"author": "Nathan",
"author_id": 24954,
"author_profile": "https://Stackoverflow.com/users/24954",
"pm_score": 3,
"selected": true,
"text": "select * from sys.syscomments\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354/"
] |
335,807 | <p>I was working on some code recently and came across a method that had 3 for-loops that worked on 2 different arrays. </p>
<p>Basically, what was happening was a foreach loop would walk through a vector and convert a DateTime from an object, and then another foreach loop would convert a long value from an object. Each of these loops would store the converted value into lists.</p>
<p>The final loop would go through these two lists and store those values into yet another list because one final conversion needed to be done for the date. </p>
<p>Then after all that is said and done, The final two lists are converted to an array using ToArray().</p>
<p>Ok, bear with me, I'm finally getting to my question. </p>
<p>So, I decided to make a single for loop to replace the first two foreach loops and convert the values in one fell swoop (the third loop is quasi-necessary, although, I'm sure with some working I could also put it into the single loop). </p>
<p>But then I read the article "What your computer does while you wait" by Gustav Duarte and started thinking about memory management and what the data was doing while it's being accessed in the for-loop where two lists are being accessed simultaneously. </p>
<p>So my question is, what is the best approach for something like this? Try to condense the for-loops so it happens in as little loops as possible, causing multiple data access for the different lists. Or, allow the multiple loops and let the system bring in data it's anticipating. These lists and arrays can be potentially large and looping through 3 lists, perhaps 4 depending on how ToArray() is implemented, can get very costy (O(n^3) ??). But from what I understood in said article and from my CS classes, having to fetch data can be expensive too. </p>
<p>Would anyone like to provide any insight? Or have I completely gone off my rocker and need to relearn what I have unlearned?</p>
<p>Thank you</p>
| [
{
"answer_id": 335859,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 2,
"selected": false,
"text": "for (...){\n // Do A\n}\n\nfor (...){\n // Do B\n}\n\nfor (...){\n // Do C\n}\n for (...){\n // Do A\n // Do B\n}\nfor (...){\n // Do C\n}\n"
},
{
"answer_id": 335944,
"author": "Ape-inago",
"author_id": 42082,
"author_profile": "https://Stackoverflow.com/users/42082",
"pm_score": 1,
"selected": false,
"text": "for(i=0, i<10, i++ ) {\n myObject object = array[i];\n myObject.functionreallybig1(); // pushes functionreallybig2 out of cache\n myObject.functionreallybig2(); // pushes functionreallybig1 out of cache\n}\n for(i=0, i<10, i++ ) {\n myObject object = array[i];\n myObject.functionreallybig1(); // this stays in the cache next time through loop\n}\n\n\nfor(i=0, i<10, i++ ) {\n myObject object = array[i];\n myObject.functionreallybig2(); // this stays in the cache next time through loop\n}\n"
},
{
"answer_id": 335977,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 1,
"selected": false,
"text": "// if this compiles down to a raw memory copy with a bitmask...\nDate morningOf(Date d) { return Date(d.year, d.month, d.day, 0, 0, 0); }\n\nDate timestamps[N];\nDate mornings[N];\n\n// ... then this can be parallelized using SSE or other SIMD instructions\nfor (int i = 0; i != N; ++i)\n mornings[i] = morningOf(timestamps[i]);\n\n// ... and this will just run like normal\nfor (int i = 0; i != N; ++i)\n doOtherCrap(mornings[i]);\n"
},
{
"answer_id": 346937,
"author": "Emmanuel F",
"author_id": 13064,
"author_profile": "https://Stackoverflow.com/users/13064",
"pm_score": 1,
"selected": false,
"text": " PrepareData(vectorA, VectorB, xArray, yArray):\n listA\n listB\n foreach(value in vectorA)\n convert values insert in listA\n foreach(value in vectorB)\n convert values insert in listB\n listC\n listD\n for(int i = 0; i < listB.count; i++)\n listC[i] = listB[i] converted to something\n listD[i] = listA[i]\n xArray = listC.ToArray()\n yArray = listD.ToArray()\n\n PrepareData(vectorA, vectorB, ref xArray, ref yArray):\n listA\n listB\n for(int i = 0; i < vectorA.count && vectorB.count; i++)\n convert values insert in listA\n convert values insert in listB\n listC\n listD\n for(int i = 0; i < listB.count; i++)\n listC[i] = listB[i] converted to something\n listD[i] = listA[i]\n xArray = listC.ToArray()\n yArray = listD.ToArray()\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13064/"
] |
335,812 | <p>I'm having an issue with CruiseControl.net where the web dashboard just won't work in IIS. I have tried switching ASP.Net between 64 and 32 bit modes and reinstalling cruise control, but nothing seems to work. Has anyone else had issues with CruiseControl.Net on 64 bit platforms?</p>
<p>Cheers,
Jamie</p>
<p>[Edit]</p>
<p>Thought I should clarify, I am getting a 404 error when I try access the website. I am using the correct address because it asks for authentication. The .aspx handler is working because I don't see the default.aspx page from the ccnet directory.</p>
<p>[Edit2]</p>
<p>I am using the default web.config that comes with ccnet, but here it is:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- Change this if (for example) you want to keep your dashboard config file under source control -->
<add key="DashboardConfigLocation" value="dashboard.config" />
</appSettings>
<system.web>
<httpHandlers>
<!-- Yes, we are overriding .aspx - don't delete this! We are using .aspx since we know it is already bound to ASP.NET. In future we might use a
different extension so that people can add their own ASP.NET pages if they want to, but we should make sure in that case to change how
URLs are created -->
<add verb="*" path="*.aspx" type="ThoughtWorks.CruiseControl.WebDashboard.MVC.ASPNET.HttpHandler,ThoughtWorks.CruiseControl.WebDashboard"/>
<add verb="*" path="*.xml" type="ThoughtWorks.CruiseControl.WebDashboard.MVC.ASPNET.HttpHandler,ThoughtWorks.CruiseControl.WebDashboard"/>
</httpHandlers>
<compilation defaultLanguage="c#" debug="true" />
<customErrors mode="RemoteOnly" />
<authentication mode="Windows" />
<!-- APPLICATION-LEVEL TRACE LOGGING
Application-level tracing enables trace log output for every page within an application.
Set trace enabled="true" to enable application trace logging. If pageOutput="true", the
trace information will be displayed at the bottom of each page. Otherwise, you can view the
application trace log by browsing the "trace.axd" page from your web application
root.
-->
<trace
enabled="false"
requestLimit="10"
pageOutput="true"
traceMode="SortByTime"
localOnly="true"
/>
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false" timeout="20" />
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
</system.web>
</code></pre>
<p></p>
| [
{
"answer_id": 335821,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<add verb=\"*\" path=\"*.aspx\" type=\"ThoughtWorks.CruiseControl.WebDashboard.MVC.ASPNET.HttpHandler,ThoughtWorks.CruiseControl.WebDashboard\"/>\n"
},
{
"answer_id": 3967143,
"author": "laurens",
"author_id": 209449,
"author_profile": "https://Stackoverflow.com/users/209449",
"pm_score": 0,
"selected": false,
"text": "\"C:\\WINDOWS\\Microsoft.NET\\Framework64\\v2.0.50727\\aspnet_regiis.exe\" -s \"W3SVC/1/ROOT/ccnet\"\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68230/"
] |
335,817 | <p>Is there a way to access the DOM of the document in an iframe from parent doc if the doc in the iframe is on another domain? I can easily access it if both parent and child pages are on the same domain, but I need to be able to do that when they are on different domains.</p>
<p>If not, maybe there is some other way to READ the contents of an iframe (one consideration was to create an ActiveX control, since this would be for internal corporate use only, but I would prefer it to be cross-browser compatible)?</p>
| [
{
"answer_id": 335877,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": true,
"text": "document.domain my.example.com/proxy?url=otherdomain.com/page\n"
},
{
"answer_id": 523944,
"author": "Luca Tettamanti",
"author_id": 42448,
"author_profile": "https://Stackoverflow.com/users/42448",
"pm_score": 0,
"selected": false,
"text": "postMessage"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41877/"
] |
335,833 | <p>I'd appreciate some feedback on a particular approach I'm thinking of using. The scenario is below.</p>
<p>I have an object (lets call it MObject) that has a number of properties, say, x and y coordinates, height and width. The properties are named according to the KVC guidelines (MObject.x; MObject.height, etc). My next task, is to read in an XML file that describes this MObject. Unfortunately, the XML elements are named differently -- X and Y, Height and Width (note the capitalization). </p>
<p>Ideally, the XML elements would match up with MObject's properties. In this case, I could use KVC and avoid a whole whack of code:</p>
<pre><code>for (xmlProperty in xmlElement)
{
[MObject setValue:xmlProperty.value forKey:xmlProperty.name].
}
</code></pre>
<p>One way of approaching this would be to make use of case-insensitive keys. Where would I start with that? Are there any other, better solutions?</p>
<p>Suggestions very much appreciated.</p>
| [
{
"answer_id": 335904,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 2,
"selected": false,
"text": "lowercaseString"
},
{
"answer_id": 336014,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 1,
"selected": false,
"text": "-valueForKey: -setValue:forKey: super"
},
{
"answer_id": 336143,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 2,
"selected": false,
"text": "-valueForUndefinedKey: -setValue:forUndefinedKey: super"
},
{
"answer_id": 336156,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": true,
"text": "-[NSObject valueForKey:] -[NSObject setValue:forKey:] - (NSString *)keyForName:(NSString *)name {\n // _nameToKeyCache is an NSMutableDictionary that caches the key\n // generated for a given name so it's only generated once per name\n NSString *key = [_nameToKeyCache objectForKey:name];\n if (key == nil) {\n // ...generate key...\n [_nameToKeyCache setObject:key forKey:name];\n }\n return key;\n}\n\n- (void)foo:xmlElement {\n for (xmlProperty in xmlElement) {\n [myObject setValue:xmlProperty.value forKey:[self keyForName:xmlProperty.name]].\n }\n}\n"
},
{
"answer_id": 12429490,
"author": "Cody C",
"author_id": 176755,
"author_profile": "https://Stackoverflow.com/users/176755",
"pm_score": 1,
"selected": false,
"text": "static NSMutableDictionary *keyCache;\n\n+ (NSString *)keyForClass:(Class)klass column:(NSString *)column {\n if (!keyCache) { keyCache = [NSMutableDictionary dictionary]; }\n\n NSString *className = NSStringFromClass(klass);\n\n NSMutableDictionary *tableKeyCache = [keyCache objectForKey:className];\n\n if (!tableKeyCache) {\n tableKeyCache = [NSMutableDictionary dictionary];\n\n unsigned int numMethods = 0;\n Method *methods = class_copyMethodList(klass, &numMethods);\n NSMutableArray * selectors = [NSMutableArray array];\n for (int i = 0; i < numMethods; ++i) {\n SEL selector = method_getName(methods[i]);\n [selectors addObject:NSStringFromSelector(selector)];\n }\n [tableKeyCache setValue:selectors forKey:@\"allSelectors\"];\n free(methods);\n [keyCache setValue:tableKeyCache forKey:className];\n }\n\n NSString *keyToReturn = [tableKeyCache valueForKey:column];\n if (!keyToReturn) {\n for (NSString *columnKey in [tableKeyCache valueForKey:@\"allSelectors\"]) {\n if ( [column caseInsensitiveCompare:columnKey] == NSOrderedSame) {\n [tableKeyCache setValue:columnKey forKey:column];\n keyToReturn = columnKey;\n break;\n }\n }\n }\n\n if (!keyToReturn) { // Taking a guess here...\n NSLog(@\"Selector not found for %@: %@ \", className, column);\n keyToReturn = [Utils keyForClass:[klass superclass] column:column];\n }\n\n return keyToReturn;\n}\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38753/"
] |
335,839 | <p>Note that this function does not have a "{" and "}" body. Just a try/catch block:</p>
<pre><code>void func( void )
try
{
...
}
catch(...)
{
...
}
</code></pre>
<p>Is this intentionally part of C++, or is this a g++ extension?</p>
<p>Is there any purpose to this other than bypass 1 level of {}?</p>
<p>I'd never heard of this until I ran into <a href="http://stupefydeveloper.blogspot.com/2008/10/c-function-try-catch-block.html" rel="noreferrer">http://stupefydeveloper.blogspot.com/2008/10/c-function-try-catch-block.html</a></p>
| [
{
"answer_id": 335860,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "return x; struct f {\n g member;\n f() try { \n // empty\n } catch(...) { \n std::cerr << \"thrown from constructor of g\"; \n }\n};\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13022/"
] |
335,841 | <p>I've tried this both with and without the 'ExceptionType' parameter. I have an Error.aspx page in both the Views/Shared folder and the Views/thisController folder. But everytime I run this I get a "Server Error in '/' Application." error page, rather than the nice one in Views/Shared.</p>
<p>Any idea what could be going wrong here?</p>
<pre><code>[HandleError(View="Error",ExceptionType=typeof(FormatException))]
public ActionResult Create()
{
throw new Exception();
//int breakMe = int.Parse("not a number");
return View();
}
</code></pre>
| [
{
"answer_id": 335982,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 1,
"selected": false,
"text": "// If custom errors are disabled, we need to let the normal ASP.NET exception handler\n// execute so that the user can see useful debugging information.\nif (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) {\n return;\n}\n"
},
{
"answer_id": 336002,
"author": "Schotime",
"author_id": 29376,
"author_profile": "https://Stackoverflow.com/users/29376",
"pm_score": 3,
"selected": true,
"text": "<customErrors mode=\"On\"></customErrors>\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40814/"
] |
335,847 | <p>This is not to be confused with <a href="https://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible">"How to tell if a DOM element is visible?"</a></p>
<p>I want to determine if a given DOM element is visible on the page.
E.g. if the element is a child of a parent which has <code>display:none;</code> set, then it won't be visible.</p>
<p>(This has nothing to do with whether the element is in the viewport or not)</p>
<p>I could iterate through each parent of the element, checking the <code>display</code> style, but I'd like to know if there is a more direct way?</p>
| [
{
"answer_id": 335864,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "display:none"
},
{
"answer_id": 335961,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 1,
"selected": false,
"text": "if($('someDiv').visible) {...}\n"
},
{
"answer_id": 340709,
"author": "EoghanM",
"author_id": 6691,
"author_profile": "https://Stackoverflow.com/users/6691",
"pm_score": 0,
"selected": false,
"text": "getElementPosition('mydiv').y != 0\n y = getElementPosition('mydiv').y\n(y < getViewportPosition().y + getViewportDimensions().h &&\n getViewportPosition().y < y)\n"
},
{
"answer_id": 6153548,
"author": "Guy Bedford",
"author_id": 773243,
"author_profile": "https://Stackoverflow.com/users/773243",
"pm_score": 0,
"selected": false,
"text": "var elementShown = function(e){\n if (e == document) \n return true;\n\n if ($(e).css('display') == 'none') //or whatever your css function is\n return false;\n\n return elementShown(e.parentNode);\n}\n"
},
{
"answer_id": 50051637,
"author": "Emmanuel Sellier",
"author_id": 4787477,
"author_profile": "https://Stackoverflow.com/users/4787477",
"pm_score": 0,
"selected": false,
"text": ".getClientRects() display=\"none\""
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6691/"
] |
335,849 | <p>I have run into an issue with WPF and Commands that are bound to a Button inside the DataTemplate of an ItemsControl. The scenario is quite straight forward. The ItemsControl is bound to a list of objects, and I want to be able to remove each object in the list by clicking a Button. The Button executes a Command, and the Command takes care of the deletion. The CommandParameter is bound to the Object I want to delete. That way I know what the user clicked. A user should only be able to delete their "own" objects - so I need to do some checks in the "CanExecute" call of the Command to verify that the user has the right permissions.</p>
<p>The problem is that the parameter passed to CanExecute is NULL the first time it's called - so I can't run the logic to enable/disable the command. However, if I make it allways enabled, and then click the button to execute the command, the CommandParameter is passed in correctly. So that means that the binding against the CommandParameter is working.</p>
<p>The XAML for the ItemsControl and the DataTemplate looks like this:</p>
<pre><code><ItemsControl
x:Name="commentsList"
ItemsSource="{Binding Path=SharedDataItemPM.Comments}"
Width="Auto" Height="Auto">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button
Content="Delete"
FontSize="10"
Command="{Binding Path=DataContext.DeleteCommentCommand, ElementName=commentsList}"
CommandParameter="{Binding}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</code></pre>
<p>So as you can see I have a list of Comments objects. I want the CommandParameter of the DeleteCommentCommand to be bound to the Command object.</p>
<p>So I guess my question is: have anyone experienced this problem before? CanExecute gets called on my Command, but the parameter is always NULL the first time - why is that?</p>
<p><strong>Update:</strong> I was able to narrow the problem down a little. I added an empty Debug ValueConverter so that I could output a message when the CommandParameter is data bound. Turns out the problem is that the CanExecute method is executed before the CommandParameter is bound to the button. I have tried to set the CommandParameter before the Command (like suggested) - but it still doesn't work. Any tips on how to control it.</p>
<p><strong>Update2:</strong> Is there any way to detect when the binding is "done", so that I can force re-evaluation of the command? Also - is it a problem that I have multiple Buttons (one for each item in the ItemsControl) that bind to the same instance of a Command-object?</p>
<p><strong>Update3:</strong> I have uploaded a reproduction of the bug to my SkyDrive: <a href="http://cid-1a08c11c407c0d8e.skydrive.live.com/self.aspx/Code%20samples/CommandParameterBinding.zip" rel="noreferrer">http://cid-1a08c11c407c0d8e.skydrive.live.com/self.aspx/Code%20samples/CommandParameterBinding.zip</a></p>
| [
{
"answer_id": 340755,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "CommandParameter=\n \"{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},\n Path=PlacementTarget.SelectedItem,\n Mode=TwoWay}\"\n"
},
{
"answer_id": 516626,
"author": "David Liersch",
"author_id": 62947,
"author_profile": "https://Stackoverflow.com/users/62947",
"pm_score": 5,
"selected": true,
"text": "public class TriggerConverter : IMultiValueConverter\n{\n #region IMultiValueConverter Members\n\n public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n // First value is target value.\n // All others are update triggers only.\n if (values.Length < 1) return Binding.DoNothing;\n return values[0];\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n}\n <ItemsControl \n x:Name=\"commentsList\"\n ItemsSource=\"{Binding Path=SharedDataItemPM.Comments}\"\n Width=\"Auto\" Height=\"Auto\">\n <ItemsControl.ItemTemplate>\n <DataTemplate>\n <StackPanel Orientation=\"Horizontal\">\n <Button \n Content=\"Delete\"\n FontSize=\"10\"\n CommandParameter=\"{Binding}\">\n <Button.Command>\n <MultiBinding Converter=\"{StaticResource TriggerConverter}\">\n <Binding Path=\"DataContext.DeleteCommentCommand\"\n ElementName=\"commentsList\" />\n <Binding />\n </MultiBinding> \n </Button.Command>\n </Button>\n </StackPanel> \n </DataTemplate>\n </ItemsControl.ItemTemplate>\n</ItemsControl>\n"
},
{
"answer_id": 561544,
"author": "Swythan",
"author_id": 67880,
"author_profile": "https://Stackoverflow.com/users/67880",
"pm_score": 3,
"selected": false,
"text": "CommandParameterBehavior CommandParameter Command PropertyDescriptor.AddValueChanged PropertyDescriptor.RemoveValueChanged IDelegateCommand RoutedCommand DelegateCommand<T> CommandManager.InvalidateRequerySuggested using System;\nusing System.ComponentModel;\nusing System.Windows;\nusing System.Windows.Input;\n\nnamespace Microsoft.Practices.Composite.Wpf.Commands\n{\n /// <summary>\n /// This class provides an attached property that, when set to true, will cause changes to the element's CommandParameter to \n /// trigger the CanExecute handler to be called on the Command.\n /// </summary>\n public static class CommandParameterBehavior\n {\n /// <summary>\n /// Identifies the IsCommandRequeriedOnChange attached property\n /// </summary>\n /// <remarks>\n /// When a control has the <see cref=\"IsCommandRequeriedOnChangeProperty\" />\n /// attached property set to true, then any change to it's \n /// <see cref=\"System.Windows.Controls.Primitives.ButtonBase.CommandParameter\" /> property will cause the state of\n /// the command attached to it's <see cref=\"System.Windows.Controls.Primitives.ButtonBase.Command\" /> property to \n /// be reevaluated.\n /// </remarks>\n public static readonly DependencyProperty IsCommandRequeriedOnChangeProperty =\n DependencyProperty.RegisterAttached(\"IsCommandRequeriedOnChange\",\n typeof(bool),\n typeof(CommandParameterBehavior),\n new UIPropertyMetadata(false, new PropertyChangedCallback(OnIsCommandRequeriedOnChangeChanged)));\n\n /// <summary>\n /// Gets the value for the <see cref=\"IsCommandRequeriedOnChangeProperty\"/> attached property.\n /// </summary>\n /// <param name=\"target\">The object to adapt.</param>\n /// <returns>Whether the update on change behavior is enabled.</returns>\n public static bool GetIsCommandRequeriedOnChange(DependencyObject target)\n {\n return (bool)target.GetValue(IsCommandRequeriedOnChangeProperty);\n }\n\n /// <summary>\n /// Sets the <see cref=\"IsCommandRequeriedOnChangeProperty\"/> attached property.\n /// </summary>\n /// <param name=\"target\">The object to adapt. This is typically a <see cref=\"System.Windows.Controls.Primitives.ButtonBase\" />, \n /// <see cref=\"System.Windows.Controls.MenuItem\" /> or <see cref=\"System.Windows.Documents.Hyperlink\" /></param>\n /// <param name=\"value\">Whether the update behaviour should be enabled.</param>\n public static void SetIsCommandRequeriedOnChange(DependencyObject target, bool value)\n {\n target.SetValue(IsCommandRequeriedOnChangeProperty, value);\n }\n\n private static void OnIsCommandRequeriedOnChangeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (!(d is ICommandSource))\n return;\n\n if (!(d is FrameworkElement || d is FrameworkContentElement))\n return;\n\n if ((bool)e.NewValue)\n {\n HookCommandParameterChanged(d);\n }\n else\n {\n UnhookCommandParameterChanged(d);\n }\n\n UpdateCommandState(d);\n }\n\n private static PropertyDescriptor GetCommandParameterPropertyDescriptor(object source)\n {\n return TypeDescriptor.GetProperties(source.GetType())[\"CommandParameter\"];\n }\n\n private static void HookCommandParameterChanged(object source)\n {\n var propertyDescriptor = GetCommandParameterPropertyDescriptor(source);\n propertyDescriptor.AddValueChanged(source, OnCommandParameterChanged);\n\n // N.B. Using PropertyDescriptor.AddValueChanged will cause \"source\" to never be garbage collected,\n // so we need to hook the Unloaded event and call RemoveValueChanged there.\n HookUnloaded(source);\n }\n\n private static void UnhookCommandParameterChanged(object source)\n {\n var propertyDescriptor = GetCommandParameterPropertyDescriptor(source);\n propertyDescriptor.RemoveValueChanged(source, OnCommandParameterChanged);\n\n UnhookUnloaded(source);\n }\n\n private static void HookUnloaded(object source)\n {\n var fe = source as FrameworkElement;\n if (fe != null)\n {\n fe.Unloaded += OnUnloaded;\n }\n\n var fce = source as FrameworkContentElement;\n if (fce != null)\n {\n fce.Unloaded += OnUnloaded;\n }\n }\n\n private static void UnhookUnloaded(object source)\n {\n var fe = source as FrameworkElement;\n if (fe != null)\n {\n fe.Unloaded -= OnUnloaded;\n }\n\n var fce = source as FrameworkContentElement;\n if (fce != null)\n {\n fce.Unloaded -= OnUnloaded;\n }\n }\n\n static void OnUnloaded(object sender, RoutedEventArgs e)\n {\n UnhookCommandParameterChanged(sender);\n }\n\n static void OnCommandParameterChanged(object sender, EventArgs ea)\n {\n UpdateCommandState(sender);\n }\n\n private static void UpdateCommandState(object target)\n {\n var commandSource = target as ICommandSource;\n\n if (commandSource == null)\n return;\n\n var rc = commandSource.Command as RoutedCommand;\n if (rc != null)\n {\n CommandManager.InvalidateRequerySuggested();\n }\n\n var dc = commandSource.Command as IDelegateCommand;\n if (dc != null)\n {\n dc.RaiseCanExecuteChanged();\n }\n\n }\n }\n}\n"
},
{
"answer_id": 2602311,
"author": "Joe Bako",
"author_id": 312154,
"author_profile": "https://Stackoverflow.com/users/312154",
"pm_score": 1,
"selected": false,
"text": "public event EventHandler CanExecuteChanged\n{\n add\n {\n WeakEventHandlerManager.AddWeakReferenceHandler( ref _canExecuteChangedHandlers, value, 2 );\n // add this line\n CommandManager.RequerySuggested += value;\n }\n remove\n {\n WeakEventHandlerManager.RemoveWeakReferenceHandler( _canExecuteChangedHandlers, value );\n // add this line\n CommandManager.RequerySuggested -= value;\n }\n}\n protected virtual void OnCanExecuteChanged()\n{\n // add this line\n CommandManager.InvalidateRequerySuggested();\n WeakEventHandlerManager.CallWeakReferenceHandlers( this, _canExecuteChangedHandlers );\n}\n"
},
{
"answer_id": 4047384,
"author": "Travis Weber",
"author_id": 490653,
"author_profile": "https://Stackoverflow.com/users/490653",
"pm_score": 6,
"selected": false,
"text": "Command=\"{Binding DataContext.MyCommand, ElementName=myWindow}\"\n Command=\"{Binding DataContext.MyCommand, RelativeSource={RelativeSource AncestorType=Views:MyView}}\"\n CommandParameter=\"{Binding Groups}\"\nCommand=\"{Binding StartCommand}\"\n"
},
{
"answer_id": 24669638,
"author": "Ed Downs",
"author_id": 1623625,
"author_profile": "https://Stackoverflow.com/users/1623625",
"pm_score": 4,
"selected": false,
"text": "public static class ButtonHelper\n{\n public static DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached(\n \"CommandParameter\",\n typeof(object),\n typeof(ButtonHelper),\n new PropertyMetadata(CommandParameter_Changed));\n\n private static void CommandParameter_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var target = d as ButtonBase;\n if (target == null)\n return;\n\n target.CommandParameter = e.NewValue;\n var temp = target.Command;\n // Have to set it to null first or CanExecute won't be called.\n target.Command = null;\n target.Command = temp;\n }\n\n public static object GetCommandParameter(ButtonBase target)\n {\n return target.GetValue(CommandParameterProperty);\n }\n\n public static void SetCommandParameter(ButtonBase target, object value)\n {\n target.SetValue(CommandParameterProperty, value);\n }\n}\n <Button \n Content=\"Press Me\"\n Command=\"{Binding}\" \n helpers:ButtonHelper.CommandParameter=\"{Binding MyParameter}\" />\n"
},
{
"answer_id": 25965525,
"author": "Julio Nobre",
"author_id": 378115,
"author_profile": "https://Stackoverflow.com/users/378115",
"pm_score": -1,
"selected": false,
"text": "private bool OnDeleteSelectedItemsCanExecute(object SelectedItems) \n{\n // Your goes heres\n}\n"
},
{
"answer_id": 33981843,
"author": "kkCosmo",
"author_id": 1374375,
"author_profile": "https://Stackoverflow.com/users/1374375",
"pm_score": 1,
"selected": false,
"text": "public event EventHandler CanExecuteChanged;\n public event EventHandler CanExecuteChanged\n{\n add { CommandManager.RequerySuggested += value; }\n remove { CommandManager.RequerySuggested -= value; }\n}\n public void RaiseCanExecuteChanged()\n protected virtual void OnCanExecuteChanged()\n Application.Current?.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)CommandManager.InvalidateRequerySuggested);\n"
},
{
"answer_id": 37956111,
"author": "TravisWhidden",
"author_id": 1004187,
"author_profile": "https://Stackoverflow.com/users/1004187",
"pm_score": 0,
"selected": false,
"text": "public DelegateCommand<objectToBePassed> CommandShowReport\n {\n get\n {\n // create the command, or pass what is already created.\n var command = _commandShowReport ?? (_commandShowReport = new DelegateCommand<object>(OnCommandShowReport, OnCanCommandShowReport));\n\n // For the item template, the OnCanCommand will first pass in null. This will tell the command to re-pass the command param to validate if it can execute.\n Dispatcher.BeginInvoke((Action) delegate { command.RaiseCanExecuteChanged(); }, DispatcherPriority.DataBind);\n\n return command;\n }\n }\n"
},
{
"answer_id": 38961061,
"author": "Simon Smith",
"author_id": 1444821,
"author_profile": "https://Stackoverflow.com/users/1444821",
"pm_score": 4,
"selected": false,
"text": "CommandParameter=\"{Binding .}\"\n CommandParameter=\"{Binding DataContext, RelativeSource={RelativeSource Self}}\"\n"
},
{
"answer_id": 56077890,
"author": "Ralf Stauder",
"author_id": 4008142,
"author_profile": "https://Stackoverflow.com/users/4008142",
"pm_score": 3,
"selected": false,
"text": "<MenuItem Header=\"Open file\" Command=\"{Binding Tag.CommandOpenFile, IsAsync=True, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}\" CommandParameter=\"{Binding Name}\" />\n Tag CommandParameter Command IsAsync=True CanExecute"
},
{
"answer_id": 73667704,
"author": "StayOnTarget",
"author_id": 3195477,
"author_profile": "https://Stackoverflow.com/users/3195477",
"pm_score": 0,
"selected": false,
"text": "CanExecute() CommandParameter CanExecute() CommandParameter null ICommand"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] |
335,855 | <p>I'm writing a GUI application that will let users interact with command-line programs. The programs are crystallography programs, in this case. They take a long time to run.</p>
<p>There's a certain common workflow using the command-line programs. The output from one program is typically processed and then is used by other programs. The user needs to be able to fill in various text boxes and select options that are sent to the command-line programs.</p>
<p>As I'm lazy and don't want to do more work than I need to, what tools are out there that will help me in doing this? The software needs to work initially on Linux, but also running on Windows at some point would be neat. </p>
<p>Would also be neat if there was some sort of DSL for non-programmers to be able to extend/modify the GUI application (to add new programs and change the options and so on).</p>
| [
{
"answer_id": 335878,
"author": "Din",
"author_id": 41214,
"author_profile": "https://Stackoverflow.com/users/41214",
"pm_score": -1,
"selected": false,
"text": "object console = WShell.Exec(cmdLine);\nif (console.StdOut.AtEndOfStream)\n s = Pipe.StdOut.ReadLine();\n"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17076/"
] |
335,863 | <p>/dev/md1 6068992 5204648 551080 91% /</p>
<p>I have 91% taken and am trying to discover what files are taking up space. I'm using linux. Does any one know the command?</p>
<p>thanks</p>
| [
{
"answer_id": 335865,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": false,
"text": "du -k -S -x / | sort -n -r | head -10 -S -x"
},
{
"answer_id": 335869,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "# du -k -S -x / | sort -r -n\n -S -x /proc /dev /sys du"
},
{
"answer_id": 335870,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 1,
"selected": false,
"text": "find find / -size 100M -print\n -mount find / -mount -size 100M -print\n"
},
{
"answer_id": 336811,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 0,
"selected": false,
"text": "du -x / | sort -ns\n"
},
{
"answer_id": 336962,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 0,
"selected": false,
"text": "--max-depth=1 du home home"
}
] | 2008/12/02 | [
"https://Stackoverflow.com/questions/335863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,873 | <p>Is there a limitation in the length of a query that SQL Server can handle?</p>
<p>I have a normal SqlCommand object and pass a very long select statement as a string. </p>
<p>The query seems to be fine when running against an SQL Server 2005/2008 engine but doesn't execute against an SQL Server 2000 engine. </p>
<p>I don't have any error details as I only have this information 3rd hand but my application isn't working as expected. I could go to the trouble of installing an SQL Server 2000 instance but I was just wondering if anyone has a quick. Yes there is a 4K or 8K limit in SQL Server 2000 but not in 2005 type answer.</p>
<p>I'm aware that I could use stored procedures but lets assume I have a valid reason for not using them :-)</p>
| [
{
"answer_id": 335912,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "SQLCommand command = new SqlCommand(\"exec sp_executeSQL @CMD\");\ncommand.Parameters.Add(new SqlParameter(\"@CMD\",YourDynamicSQL, VARCHAR);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403/"
] |
335,885 | <p>I am looking for a way to slide a UIPickerView (and UIDatePickerView) up over a view (UITableView in particular) when a particular button press takes place.</p>
<p>I understand how to get the events for clicks into the UITableView, but there doesn't seem to be a good way to have the UIPickerView slide up on top of it...</p>
<p>All the examples I have seen so far just have it snapped to the bottom of another view and I am able to do this without issue.</p>
<p>Thoughts?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 501019,
"author": "Brad Parks",
"author_id": 26510,
"author_profile": "https://Stackoverflow.com/users/26510",
"pm_score": 2,
"selected": false,
"text": "UIWindow *window = [[Director sharedDirector] window];\n\n[UIView beginAnimations:nil context:nil];\n[UIView setAnimationDuration:0.75];\n[UIView setAnimationTransition:(UIViewAnimationTransitionCurlDown)\n forView:window\n cache:YES];\n[window addSubview:aView];\n[UIView commitAnimations]; \n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
335,886 | <p>I want to do something like</p>
<pre><code>select * from tvfHello(@param) where @param in (Select ID from Users)
</code></pre>
| [
{
"answer_id": 335895,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM dbo.tvfHello(@param) WHERE @param IN (SELECT ID FROM Users)\n"
},
{
"answer_id": 335903,
"author": "JoshBerke",
"author_id": 26160,
"author_profile": "https://Stackoverflow.com/users/26160",
"pm_score": 3,
"selected": false,
"text": "CREATE FUNCTION dbo.EmployeeByID(@employeeID int)\nRETURNS TABLE\nAS RETURN\n(\n SELECT * FROM HumanResources.Employee WHERE EmployeeID = @employeeID\n)\nGO\n\n\nDECLARE @employeeId int\n\nset @employeeId=10\n\nselect * from \nEmployeeById(@employeeId) \nWHERE @EmployeeId in (SELECT EmployeeId FROM HumanResources.Employee)\n select * \nfrom HumanResources.Employee e\nCROSS APPLY EmployeeById(e.EmployeeId)\nWHERE e.EmployeeId in (5,6,7,8)\n"
},
{
"answer_id": 336773,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 6,
"selected": true,
"text": "select \n f.* \nfrom \n users u\n cross apply dbo.tvfHello(u.ID) f\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30546/"
] |
335,888 | <p>I have a user table in my mysql database that has a password column. Currently, I use the MD5 algorithm to hash the users' password for storage in the database. Now I like to think that I am a security conscience person. I noticed while reading the MySQL docs that they don't recommend MD5 or the SHA/SHA1 hashing methods, but don't offer an alternative. </p>
<p>What would be the best way to hash my passwords in MySQL? A function that is natively supported in both PHP and MySQL would be ideal and necessary with my current implementation.</p>
<p>Thanks!</p>
| [
{
"answer_id": 335913,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "hash()"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42135/"
] |
335,891 | <p>I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down.</p>
<pre><code>#!/bin/bash
cd /Users/stuartcw/Documents/Wiki/moin-1.7.2
/usr/bin/python wikiserver.py >> logs/`date +"%d%b%Y"`.log 2>&1 &
</code></pre>
<p>I would really like the Wiki to be available after restarting so any help in understanding this would be appreciated.</p>
| [
{
"answer_id": 336239,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 3,
"selected": true,
"text": "/Library/LaunchDaemons com.you.wiki.plist <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>com.you.wiki</string>\n <key>LowPriorityIO</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>RunAtLoad</key>\n <true/>\n <key>Nice</key>\n <integer>1</integer>\n <key>WorkingDirectory</key>\n <string>/Users/stuartcw/Documents/Wiki/moin-1.7.2</string> \n <key>UserName</key>\n <string>user to run this as</string>\n <key>ProgramArguments</key>\n <array>\n <string>/usr/bin/python</string>\n <string>wikiserver.py</string>\n </array>\n</dict>\n</plist>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27065/"
] |
335,896 | <p>I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.</p>
<p>I have this code now, which should be pretty much ok, but propably needs some modification:</p>
<pre><code>import os
import Image
def filmstripOfImages():
imgpath = '/path/here/'
files = glob.glob(imgpath + '*.jpg')
imgwidth = files[0].size[0]
imgheight = files[0].size[1]
totalheight = imgheight * len(files)
filename = 'filmstrip.jpg'
filmstrip_url = imgpath + filename
# Create the new image. The background doesn't have to be white
white = (255,255,255)
filmtripimage = Image.new('RGB',(imgwidth, totalheight),white)
row = 0
for file in files:
img = Image.open(file)
left = 0
right = left + imgwidth
upper = row*imgheight
lower = upper + imgheight
box = (left,upper,right,lower)
row += 1
filmstripimage.paste(img, box)
try:
filmstripimage.save(filename, 'jpg', quality=90, optimize=1)
except:
filmstripimage.save(miniature_filename, 'jpg', quality=90)")
</code></pre>
<p>How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?</p>
<p>Related question: <a href="https://stackoverflow.com/questions/334827/how-to-generate-a-filmstrip-image-in-python-from-a-folder-of-images">How to generate a filmstrip image in python from a folder of images?</a></p>
| [
{
"answer_id": 335916,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 1,
"selected": false,
"text": "try filmstripimage.save(filmstrip_url, 'jpg', quality=90, optimize=1)\n"
},
{
"answer_id": 335921,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "glob.glob() files[0].size[0]"
},
{
"answer_id": 336001,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": true,
"text": "#!/usr/bin/env python\nfrom PIL import Image\n\ndef makefilmstrip(images, mode='RGB', color='white'):\n \"\"\"Return a combined (filmstripped, each on top of the other) image of the images.\n\n \"\"\"\n width = max(img.size[0] for img in images)\n height = sum(img.size[1] for img in images)\n \n image = Image.new(mode, (width, height), color) \n \n left, upper = 0, 0\n for img in images:\n image.paste(img, (left, upper))\n upper += img.size[1]\n\n return image\n\nif __name__=='__main__':\n # Here's how it could be used:\n from glob import glob\n from optparse import OptionParser\n\n # process command-line args\n parser = OptionParser()\n parser.add_option(\"-o\", \"--output\", dest=\"file\",\n help=\"write combined image to OUTPUT\")\n\n options, filepatterns = parser.parse_args()\n outfilename = options.file\n \n filenames = []\n for files in map(glob, filepatterns):\n if files:\n filenames += files\n\n # construct image\n images = map(Image.open, filenames) \n img = makefilmstrip(images)\n img.save(outfilename) \n $ python filmstrip.py -o output.jpg *.jpg\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] |
335,928 | <p>I am attempting to link an application with g++ on this Debian lenny system. ld is complaining it cannot find specified libraries. The specific example here is ImageMagick, but I am having similar problems with a few other libraries too.</p>
<p>I am calling the linker with:</p>
<pre><code>g++ -w (..lots of .o files/include directories/etc..) \
-L/usr/lib -lmagic
</code></pre>
<p>ld complains:</p>
<pre><code>/usr/bin/ld: cannot find -lmagic
</code></pre>
<p>However, libmagic exists:</p>
<pre><code>$ locate libmagic.so
/usr/lib/libmagic.so.1
/usr/lib/libmagic.so.1.0.0
$ ls -all /usr/lib/libmagic.so.1*
lrwxrwxrwx 1 root root 17 2008-12-01 03:52 /usr/lib/libmagic.so.1 -> libmagic.so.1.0.0
-rwxrwxrwx 1 root root 84664 2008-09-09 00:05 /usr/lib/libmagic.so.1.0.0
$ ldd /usr/lib/libmagic.so.1.0.0
linux-gate.so.1 => (0xb7f85000)
libz.so.1 => /usr/lib/libz.so.1 (0xb7f51000)
libc.so.6 => /lib/i686/cmov/libc.so.6 (0xb7df6000)
/lib/ld-linux.so.2 (0xb7f86000)
$ sudo ldconfig -v | grep "libmagic"
libmagic.so.1 -> libmagic.so.1.0.0
</code></pre>
<p>How do I diagnose this problem further, and what could be wrong? Am I doing something completely stupid?</p>
| [
{
"answer_id": 335958,
"author": "grepsedawk",
"author_id": 14388,
"author_profile": "https://Stackoverflow.com/users/14388",
"pm_score": 9,
"selected": true,
"text": "libmagic.so libmagic.so.1 libmagic.so.1 libmagic.so"
},
{
"answer_id": 335960,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 2,
"selected": false,
"text": "libmagic -lmagic g++ program.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs` -o \"prog\"\n"
},
{
"answer_id": 335968,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 6,
"selected": false,
"text": "-l g++ ld g++ -l:libmagic.so.1 [...] g++ -lmagic [...]"
},
{
"answer_id": 4030167,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 5,
"selected": false,
"text": "libmagic1: /usr/lib/libmagic.so.1 → libmagic.so.1.0.0 libmagic-dev: /usr/lib/libmagic.so → … libmagic.so.1 -lmagic libmagic.so apt-get install libmagic-dev libmagic.so /usr/include/magic.h"
},
{
"answer_id": 10716813,
"author": "Mr Ed",
"author_id": 699240,
"author_profile": "https://Stackoverflow.com/users/699240",
"pm_score": 3,
"selected": false,
"text": "libtool $ sudo apt-get install libtool\n ltdl libltdl.so.7 -lltdl"
},
{
"answer_id": 37286031,
"author": "Miguel Ignacio Iglesias",
"author_id": 6347783,
"author_profile": "https://Stackoverflow.com/users/6347783",
"pm_score": 3,
"selected": false,
"text": "libmagic.so libmagic.so.1 ldconfig -v \n $ ldconfig -p | grep libmagic\n"
},
{
"answer_id": 68281352,
"author": "nft3000",
"author_id": 16396772,
"author_profile": "https://Stackoverflow.com/users/16396772",
"pm_score": 1,
"selected": false,
"text": "sudo apt-get install libgmp3-dev\n"
},
{
"answer_id": 74656818,
"author": "thd",
"author_id": 586981,
"author_profile": "https://Stackoverflow.com/users/586981",
"pm_score": 0,
"selected": false,
"text": "-devel libabc.so libabc.so.1 -devel libabc-devel libabc.so.1 libabc.so"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10733/"
] |
335,930 | <p>Suppose there´s a template function in C++ that does some useful work but also outputs a sequence of values via an output iterator. Now suppose that that sequence of values sometimes is interesting, but at others is not useful. Is there a ready-to-use iterator class in the STL that can be instantiated and passed to the function and will ignore any values the function tries to assign to the output iterator? To put in another way, send all data to /dev/null?</p>
| [
{
"answer_id": 335950,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "template<typename T>\nclass NullOutputIterator\n{\npublic:\n NullOutputIterator() {}\n NullOutputIterator& operator++() { return *this; }\n NullOutputIterator& operator++(int) { return *this; }\n T& operator*() { return m; }\n T* operator->() { return &m; }\nprivate:\n T m;\n};\n"
},
{
"answer_id": 335972,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "struct null_output_iterator : \n std::iterator< std::output_iterator_tag,\n null_output_iterator > {\n /* no-op assignment */\n template<typename T>\n void operator=(T const&) { }\n\n null_output_iterator & operator++() { \n return *this; \n }\n\n null_output_iterator operator++(int) { \n return *this;\n }\n\n null_output_iterator & operator*() { return *this; }\n};\n operator* *it = x; void operator* *it = t;\n*it++ = t;\n null_output_iterator it;\n*it; // returns a null_output_iterator& per definition of the `operator*`.\n*it = some_value; // returns void per definition of the templated `operator=`. \n operator*"
},
{
"answer_id": 44419764,
"author": "Nemo",
"author_id": 768469,
"author_profile": "https://Stackoverflow.com/users/768469",
"pm_score": 1,
"selected": false,
"text": "#include <iterator>\n\ntemplate<typename T>\nclass NullOutputIter\n : public std::iterator<std::output_iterator_tag,void,void,void,void>\n{\npublic:\n NullOutputIter &operator=(const T &) { return *this; }\n NullOutputIter &operator*() { return *this; }\n NullOutputIter &operator++() { return *this; }\n NullOutputIter operator++(int) { return *this; }\n};\n operator= *it = wrong_type_thing void std::iterator std::iterator"
},
{
"answer_id": 73189051,
"author": "WaterFox",
"author_id": 10360134,
"author_profile": "https://Stackoverflow.com/users/10360134",
"pm_score": 1,
"selected": false,
"text": " ///\n /// @brief Allows to discard the output of functions that requires an output iterator\n ///\n template<typename T>\n struct null_output_iterator\n {\n using iterator_category = std::forward_iterator_tag;\n using value_type = T;\n using difference_type = T;\n using pointer = T*;\n using reference = T&;\n ///\n /// @brief No-op assignment\n ///\n void operator=(T const&) {}\n ///\n /// @brief Can be pre-incremented\n ///\n null_output_iterator & operator++()\n {\n return *this;\n }\n ///\n /// @brief Can be post-incremented\n ///\n null_output_iterator operator++(int)\n {\n return *this;\n }\n ///\n /// @brief Can be dereferenced\n ///\n null_output_iterator & operator*()\n {\n return *this;\n }\n };\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78828/"
] |
335,932 | <p>I am working on an ASP.NET MVC application that contains a header and menu on each page. The menu and header are dynamic. In other words, the menu items and header information are determined at runtime.</p>
<p>My initial thought is to build a base Controller from which all other controllers derive. In the base controller, I will obtain the menu and header data and insert the required information into the ViewData. Finally, I will use a ViewUserControl to display the header and menu through a master page template.</p>
<p>So, I'm trying to determine the best practice for building such functionality. Also, if this is the recommended approach, which method should I override (I'm guessing Execute) when obtaining the data for insertion into the ViewData.</p>
<p>I'm sure this is a common scenario, so any advice/best-practices would be appreciated! Thanks in advance!</p>
<p>EDIT:
I did find the following resources after posting this (of course), but any additional anecdotes would be awesome!</p>
<p><a href="http://www.singingeels.com/Blogs/Nullable/2008/08/14/How_to_Handle_Side_Content_in_ASPNET_MVC.aspx" rel="nofollow noreferrer">http://www.singingeels.com/Blogs/Nullable/2008/08/14/How_to_Handle_Side_Content_in_ASPNET_MVC.aspx</a></p>
<p><a href="https://stackoverflow.com/questions/326987/how-do-you-use-usercontrols-in-aspnet-mvc-that-display-an-island-of-data">How do you use usercontrols in asp.net mvc that display an "island" of data?</a></p>
| [
{
"answer_id": 3465822,
"author": "Anthony Johnston",
"author_id": 122232,
"author_profile": "https://Stackoverflow.com/users/122232",
"pm_score": 1,
"selected": false,
"text": "public static HtmlString MainMenu(this HtmlHelper helper)\n"
},
{
"answer_id": 3503876,
"author": "Christian13467",
"author_id": 150629,
"author_profile": "https://Stackoverflow.com/users/150629",
"pm_score": 1,
"selected": false,
"text": "OnAuthorization Initialize Initialize"
},
{
"answer_id": 3508115,
"author": "Ching Chang",
"author_id": 409010,
"author_profile": "https://Stackoverflow.com/users/409010",
"pm_score": 1,
"selected": false,
"text": "OnActionExecuting ViewData ViewData [HandleError] ViewData ViewData ViewData"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2657/"
] |
335,933 | <p>I traditionally deploy a set of web pages which allow for manual validation of core application functionality. One example is LoggerTest.aspx which generates and logs a test exception. I've always chosen to raise a DivideByZeroException using an approach similar to the following code snippet: </p>
<pre><code>try
{
int zero = 0;
int result = 100 / zero;
}
catch (DivideByZeroException ex)
{
LogHelper.Error("TEST EXCEPTION", ex);
}
</code></pre>
<p>The code works just fine but I feel like there must be a more elegant solution. Is there a best way to raise an exception in C#?</p>
| [
{
"answer_id": 335936,
"author": "Jesse Millikan",
"author_id": 7526,
"author_profile": "https://Stackoverflow.com/users/7526",
"pm_score": 5,
"selected": false,
"text": "throw new Exception(\"Test Exception\");\n using System;\n"
},
{
"answer_id": 335939,
"author": "asleep",
"author_id": 29445,
"author_profile": "https://Stackoverflow.com/users/29445",
"pm_score": 2,
"selected": false,
"text": " if (args.Length == 0)\n {\n throw new ArgumentException(\"A start-up parameter is required.\");\n }\n"
},
{
"answer_id": 335940,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 1,
"selected": false,
"text": "throw new DivideByZeroException(\"some message\");"
},
{
"answer_id": 335943,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 7,
"selected": true,
"text": "try\n{\n throw new DivideByZeroException();\n}\ncatch (DivideByZeroException ex)\n{\n LogHelper.Error(\"TEST EXCEPTION\", ex);\n}\n"
},
{
"answer_id": 335983,
"author": "Collin K",
"author_id": 1369,
"author_profile": "https://Stackoverflow.com/users/1369",
"pm_score": 1,
"selected": false,
"text": "LogHelper.Error(\"TEST EXCEPTION\", new Exception(\"This is a test exception\"));\n"
},
{
"answer_id": 336029,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "DivideByZeroException NullRefernceException ArgumentNullException"
},
{
"answer_id": 336194,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": " [Serializable]\n public class TestException: ApplicationException\n {\n public TestException(string Message, \n Exception innerException): base(Message,innerException) {}\n public TestException(string Message) : base(Message) {}\n public TestException() {}\n\n #region Serializeable Code\n public TestException(SerializationInfo info, \n StreamingContext context): base(info, context) { }\n #endregion Serializeable Code\n }\n try\n { \n throw new TestException();\n }\n catch( TestException eX)\n { \n LogHelper.Error(\"TEST EXCEPTION\", eX);\n }\n"
},
{
"answer_id": 8054025,
"author": "Steve Pitchers",
"author_id": 7255,
"author_profile": "https://Stackoverflow.com/users/7255",
"pm_score": 0,
"selected": false,
"text": "System.Diagnostics.Debug.Assert(condition);\n catch (AssertionException) { }\n"
},
{
"answer_id": 40777996,
"author": "Sunil Patil",
"author_id": 7203181,
"author_profile": "https://Stackoverflow.com/users/7203181",
"pm_score": 3,
"selected": false,
"text": " try\n {\n string a=\"asd\";\n int s = Convert.ToInt32(a);\n }\n catch (Exception ex)\n {\n\n Response.Write(ex.Message);\n }\n"
},
{
"answer_id": 53225497,
"author": "Muzafar Hasan",
"author_id": 5423078,
"author_profile": "https://Stackoverflow.com/users/5423078",
"pm_score": 1,
"selected": false,
"text": "public class CustomException: Exception\n{\n public CustomException(string message)\n : base(message) { }\n\n}\n if(something == anything)\n{\n throw new CustomException(\" custom text message\");\n}"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115/"
] |
335,951 | <p>For a web application, when creating the user which will connect to the MySQL database, you have the choice of privileges. Assuming that the only actions intended to be done by that user are SELECT/INSERT/UPDATE/DELETE, it seems to make sense to only provide those privileges, however I've never seen that recommended anywhere - what are the reasons for and against this method?</p>
| [
{
"answer_id": 335964,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "SELECT * FROM mytable, mytable, mytable, mytable, mytable ORDER BY 1;\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
335,955 | <p>I've been slowly working my way through the list of Project Euler problems, and I've come to one that I know how to solve, but it seems like I can't (given the way my solution was written).</p>
<p>I am using Common Lisp to do this with and my script has been running for over 24 hours (well over their one minute goal).</p>
<p>For the sake of conciseness, here's my solution (it's a spoiler, but only if you have one hell of a fast processor):</p>
<pre><code>(defun square? (num)
(if (integerp (sqrt num)) T))
(defun factors (num)
(let ((l '()))
(do ((current 1 (1+ current)))
((> current (/ num current)))
(if (= 0 (mod num current))
(if (= current (/ num current))
(setf l (append l (list current)))
(setf l (append l (list current (/ num current)))))))
(sort l #'< )))
(defun o_2 (n)
(reduce #'+ (mapcar (lambda (x) (* x x)) (factors n))))
(defun sum-divisor-squares (limit)
(loop for i from 1 to limit when (square? (o_2 i)) summing i))
(defun euler-211 ()
(sum-divisor-squares 64000000))
</code></pre>
<p>The time required to solve the problem using smaller, more friendly, test arguments seems to grow larger than exponentialy... which is a real problem.</p>
<p>It took:</p>
<ul>
<li>0.007 seconds to solve for 100</li>
<li>0.107 seconds to solve for 1000</li>
<li>2.020 seconds to solve for 10000</li>
<li>56.61 seconds to solve for 100000</li>
<li>1835.385 seconds to solve for 1000000</li>
<li>24+ hours to solve for 64000000</li>
</ul>
<p>I'm really trying to figure out which part(s) of the script is causing it to take so long. I've put some thought into memoizing the factors function, but I'm at a loss as to how to actually implement that.</p>
<p>For those that want to take a look at the problem itself, <a href="http://projecteuler.net/index.php?section=problems&id=211" rel="nofollow noreferrer">here it be</a>.</p>
<p>Any ideas on how to make this thing go faster would be greatly appreciated.</p>
<p>**sorry if this is a spoiler to anyone, it's not meant to be.... but if you have the computing power to run this in a decent amount of time, more power to you.</p>
| [
{
"answer_id": 336020,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 2,
"selected": false,
"text": "l l l (> current (/ num current)) l"
},
{
"answer_id": 336322,
"author": "Josh Sandlin",
"author_id": 13293,
"author_profile": "https://Stackoverflow.com/users/13293",
"pm_score": 0,
"selected": false,
"text": "$ (factors 10) => (1 2 5 10)\n $ (factors 10) => ((2 5) (1 10))\n (defun o_2 (n)\n\"sum of squares of divisors\"\n (reduce #'+ (mapcar (lambda (x) (* x x)) (reduce #'append (factors n)))))\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13293/"
] |
335,963 | <p>I'm using VSTS Database Edition GDR Version 9.1.31024.02</p>
<p>I've got a project where we will be creating multiple databases with identical schema, on the fly, as customers are added to the system. It's one DB per customer. I thought I should be able to use the deploy script to do this. Unfortunately I always get the full filenames specified on the CREATE DATABASE statement. For example:</p>
<pre><code>CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [targetDBName], FILENAME = N'$(DefaultDataPath)targetDBName.mdf')
LOG ON (NAME = [targetDBName_log], FILENAME = N'$(DefaultDataPath)targetDBName_log.ldf')
GO
</code></pre>
<p>I'd expected something more like this </p>
<pre><code>CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [targetDBName], FILENAME = N'$(DefaultDataPath)$(DatabaseName).mdf')
LOG ON (NAME = [targetDBName_log], FILENAME = N'$(DefaultDataPath)$(DatabaseName)_log.ldf')
GO
</code></pre>
<p>Or even </p>
<pre><code>CREATE DATABASE [$(DatabaseName)]
</code></pre>
<p>I'm not going to be running this on an on-going basis so I'd like to make it as simple as possible, for the next guy. There are a bunch of options for deployment in the project properties, but I can't get this to work the way I'd like.</p>
<p>Any one know how to set this up?</p>
| [
{
"answer_id": 1690719,
"author": "Rory MacLeod",
"author_id": 1016,
"author_profile": "https://Stackoverflow.com/users/1016",
"pm_score": 2,
"selected": false,
"text": "$(DefaultDataPath)$(DatabaseName) ALTER DATABASE [$(DatabaseName)]\nADD FILE (NAME = [$(DatabaseName)], \n FILENAME = '$(DefaultDataPath)$(DatabaseName).mdf',\n SIZE = 2304 KB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024 KB) \n TO FILEGROUP [PRIMARY];\n ALTER DATABASE [$(DatabaseName)]\n ADD LOG FILE (NAME = [$(DatabaseName)_log], \n FILENAME = '$(DefaultDataPath)$(DatabaseName)_log.ldf', \n SIZE = 1024 KB, MAXSIZE = 2097152 MB, FILEGROWTH = 10 %);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5130/"
] |
335,965 | <p>I am working on adding in a settings bundle for my application as a cheap way of getting a GUI on my preferences. Is it possible to launch this from a button in my application or will my users always have to access it manually via the built in settings application?</p>
| [
{
"answer_id": 446430,
"author": "Rhubarb",
"author_id": 20479,
"author_profile": "https://Stackoverflow.com/users/20479",
"pm_score": 2,
"selected": false,
"text": "// Invoked after the application has been launched and initialized but before it has received its first event.\n- (void)applicationDidFinishLaunching:(UIApplication *)application {\n // Set up the level view controller\n levelViewController = [[LevelViewController alloc] init];\n [window addSubview:levelViewController.view];\n\n // Restore calibration for device\n float restoredOffset = [[NSUserDefaults standardUserDefaults] floatForKey:BubbleLevelCalibrationOffsetKey];\n levelViewController.calibrationOffset = restoredOffset;\n}\n\n\n// Invoked immediately before the application terminates.\n- (void)applicationWillTerminate:(UIApplication *)application {\n float calibrationOffset = levelViewController.calibrationOffset;\n NSNumber *offset = [NSNumber numberWithFloat:calibrationOffset];\n [[NSUserDefaults standardUserDefaults] setObject:offset forKey:BubbleLevelCalibrationOffsetKey];\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8918/"
] |
335,966 | <p>Here's the scenario</p>
<p>I have a Grid with some TextBlock controls, each in a separate cell in the grid. Logically I want to be able to set the Visibility on them bound to a property in my ViewModel. But since they're each in a separate cell in the grid, I have to set each TextBlock's Visibility property.</p>
<p>Is there a way of having a non-visual group on which I can set common properties of its children? Or am I dreaming?</p>
| [
{
"answer_id": 336005,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 2,
"selected": false,
"text": "public class Singleton :INotifyPropertyChanged\n{\n private Singleton() { }\n public static Singleton Instance\n {\n get\n {\n if (instance == null){ instance = new Singleton(); }\n return instance;\n }\n }\n private Visibility _visibility;\n public Visibility Visibility\n {\n get { return _visibility; }\n set \n { \n _visibility = value; \n PropertyChanged( this, new PropertyChangedEventArgs(\"Visibility\") );\n }\n }\n public event PropertyChangedEventHandler PropertyChanged;\n private static Singleton instance;\n }\n"
},
{
"answer_id": 16031464,
"author": "PitAttack76",
"author_id": 731127,
"author_profile": "https://Stackoverflow.com/users/731127",
"pm_score": 1,
"selected": false,
"text": " <Style TargetType=\"{x:Type GroupBox}\"\n x:Key=\"HiddenGroupBox\">\n<Setter Property=\"BorderThickness\"\n Value=\"0\" />\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14537/"
] |
335,971 | <p>Are there instances where switch(case) is is a good design choice (except for simplicity) over strategy or similar patterns... </p>
| [
{
"answer_id": 335995,
"author": "lacker",
"author_id": 2652,
"author_profile": "https://Stackoverflow.com/users/2652",
"pm_score": 3,
"selected": false,
"text": "\nvector<string> possible_forms;\npossible_forms.push_back(word);\nchar last_letter = word[word.size() - 1];\nswitch (last_letter) {\n case 's':\n case 'i':\n case 'z':\n possible_forms.push_back(word + \"es\");\n break;\n case 'y':\n possible_forms.push_back(word.substr(0, word.size() - 1) + \"ies\");\n break;\n default:\n possible_forms.push_back(word + \"s\");\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30917/"
] |
335,987 | <p>A few times already, I got into situations where one of my SVN repository got corrupt and we could do anything with some versions or branches of the project without really knowing what we did. So I'm asking what can cause a repository to become corrupt?</p>
<hr>
<p>It seems that incompatibilities between clients may cause problems, more specifically with character sets.</p>
| [
{
"answer_id": 336011,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "kill -9 svnadmin cleanup"
},
{
"answer_id": 336135,
"author": "PostMan",
"author_id": 18405,
"author_profile": "https://Stackoverflow.com/users/18405",
"pm_score": 0,
"selected": false,
"text": "file://"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/335987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39057/"
] |
336,018 | <p>I have a class <code>Page</code> that creates an instance of <code>DB</code>, which is named <code>$db</code>.</p>
<p>In the <code>__construct()</code> of <code>Page</code>, I create the new <code>$db</code> object and I pull a bunch of config data from a file.</p>
<p>Now the DB class has a method <code>_connectToDB()</code> which (attempts) to connect to the database.</p>
<p>Is there a way in the DB class to call the parent class's config array? I don't want to make global variables if I don't have to and I don't want to grab the config data twice.</p>
<p>Pseudo code might look something like this...</p>
<pre><code>$dbUsername = get_calling_class_vars(configArray['dbUserName']);
</code></pre>
| [
{
"answer_id": 336036,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "debug_backtrace()"
},
{
"answer_id": 336041,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 0,
"selected": false,
"text": "class Parent {\n function __construct() {\n $this->myChild = new Child($this);\n }\n public function doSomething() {}\n}\n\nclass Child {\n function __construct(Parent $parent) {\n $parent->doSomething()\n }\n}\n"
},
{
"answer_id": 336046,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "/* Code to get config variables here */\n$DB = new DB($config);\n/* You might want to delete the database password from $config here */\n$Page = new Page($config, $DB);\n class Page {\n function __construct(array $config, DBClass $db) { }\n}\n"
},
{
"answer_id": 45077836,
"author": "T30",
"author_id": 1677209,
"author_profile": "https://Stackoverflow.com/users/1677209",
"pm_score": 2,
"selected": false,
"text": "static class page{\n static $configArray = [];\n function doWhatever(){\n $db = new DB();\n $db->connectToDB();\n }\n}\nclass DB{\n function connectToDB(){\n $dbUsername = page::$configArray['dbUserName'];\n }\n}\n static static"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
336,035 | <p>I have a DataGridViewComboBoxColumn in a DataGridView that's based on a lookup table.</p>
<p>The ValueMember and DisplayMember fields are bound to string columns in the DataTable. All rows have a value for both fields - except for a special record where the value field is deliberately set to NULL.</p>
<p>However, when I choose this record an empty string is used instead of DBNull.Value in the DataTable bound to the DataGridView. This is happening at data entry time, before the data is pushed to the database. </p>
<p>I've checked out the DataGridViewComboBoxColumn and DataGridView classes - there appears to be no simple way to customise this behaviour. Does anybody know if this is possible?</p>
| [
{
"answer_id": 336569,
"author": "Mitkins",
"author_id": 23401,
"author_profile": "https://Stackoverflow.com/users/23401",
"pm_score": 3,
"selected": true,
"text": "void Schedule_ColumnChanging(object sender, DataColumnChangeEventArgs e)\n{\n if \n ( \n e.Column.ColumnName == \"Site\" &&\n e.ProposedValue is string && \n e.ProposedValue as string == \"\"\n )\n e.ProposedValue = DBNull.Value;\n}\n"
},
{
"answer_id": 1197048,
"author": "RichardHowells",
"author_id": 84228,
"author_profile": "https://Stackoverflow.com/users/84228",
"pm_score": 0,
"selected": false,
"text": "// Fill dt from datatable...\nvar nullRow = rv.NewRunDropDownEntryRow();\nnullRow.SetIDNull();\nnullRow.Title = \"None\";\nrv.AddRunDropDownEntryRow(nullRow);\nrv.AcceptChanges();\n"
},
{
"answer_id": 4188190,
"author": "DeveloperDan",
"author_id": 381082,
"author_profile": "https://Stackoverflow.com/users/381082",
"pm_score": 0,
"selected": false,
"text": "//' Add a 'None' row to allow the user to un-select a lookup item\n//' The insert and update stored procedure translates a 'None' entry to NULL.\nDim newRow As MyLookupDataset.MyTableRow = Me.MyLookupDataset.MyTable.NewMyTableRow\nnewRow.MyID = \"None\" \nnewRow.MyDesc = \"None\"\nMe.MyLookupDataset.MyTable.Rows.InsertAt(newRow, 0)\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23401/"
] |
336,073 | <p>I keep finding that if I have nested divs inside each other, and one of the inner ones is floated, the outer one won't expand around it.</p>
<p>Example:</p>
<pre><code><div style='background-color:red; '>
asdfasdf
<div style='float:left; background-color:blue; width:400px; height:400px;'>
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
asdfasdfasdfasdfasdfasdfasdf<br />
</div>
asdfasdf
</div>
</code></pre>
<p>What do I need to do to the outer div to make it cover the inner one? IE: Put it's border/background color all the way around it?</p>
<p>Also, is there a general principle I am bumping up against here? If so, what should I look up to get a solid understanding of what it is?</p>
<p>Thanks!</p>
<p><strong>Edit</strong></p>
<p>Hi All, </p>
<p>Thanks for the answers, semantically correct and no, and for the links.</p>
<p>Though I will end up using overflow in the final work, I will leave Ant P's answer as accepted, as it was the first one that really worked, and got me out of a short term jam, even though it offends semantic sensibilities.</p>
<p>As a long-time html hack trying to move to decent css layouts, I can certainly understand, and sympathize with, using semantically incorrect hack that gets the job done, though I am sure he will change that habit after this =o)</p>
| [
{
"answer_id": 336177,
"author": "themis",
"author_id": 42706,
"author_profile": "https://Stackoverflow.com/users/42706",
"pm_score": 5,
"selected": true,
"text": "<div style='background-color:red;overflow:hidden;'>\n...\n</div>\n"
},
{
"answer_id": 336301,
"author": "Darko",
"author_id": 32943,
"author_profile": "https://Stackoverflow.com/users/32943",
"pm_score": 2,
"selected": false,
"text": "overflow:hidden"
},
{
"answer_id": 337490,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 1,
"selected": false,
"text": "div\n{\n border-width: thin !important;\n border-color: Orange !important;\n border-style: solid !important;\n}\n\nlabel, span, /* whatever else you might want to see */\n{\n border-width: thin !important;\n border-color: Blue !important;\n border-style: solid !important;\n}\n <br> clear: both <div>"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27580/"
] |
336,078 | <p>I use <em>lazy connection</em> to connect to my DB within my DB object. This basically means that it doesn't call mysql_connect() until the first query is handed to it, and it subsequently skips reconnecting from then on after.</p>
<p>Now I have a method in my DB class called <code>disconnectFromDB()</code> which pretty much calls <code>mysql_close()</code> and sets <code>$_connected = FALSE</code> (so the <code>query()</code> method will know to connect to the DB again). Should this be called after every query (as a private function) or externally via the object... because I was thinking something like (code is an example only)</p>
<pre><code>$students = $db->query('SELECT id FROM students');
$teachers = $db->query('SELECT id FROM teachers');
</code></pre>
<p>Now if it was closing after every query, would this slow it down a lot as opposed to me just adding this line to the end</p>
<pre><code>$db->disconnectFromDB();
</code></pre>
<p>Or should I just include that line above at the very end of the page?</p>
<p>What advantages/disadvantages do either have? What has worked best in your situation? Is there anything really wrong with forgetting to close the mySQL connection, besides a small loss of performance?</p>
<p>Appreciate taking your time to answer.</p>
<p>Thank you!</p>
| [
{
"answer_id": 336109,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 3,
"selected": false,
"text": "$_connected $db->disconnectFromDB(); $_connected $_connected"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
336,127 | <p>I need a method for adding "business days" in PHP. For example, Friday 12/5 + 3 business days = Wednesday 12/10.</p>
<p>At a minimum I need the code to understand weekends, but ideally it should account for US federal holidays as well. I'm sure I could come up with a solution by brute force if necessary, but I'm hoping there's a more elegant approach out there. Anyone?</p>
<p>Thanks.</p>
| [
{
"answer_id": 336155,
"author": "Tim",
"author_id": 33914,
"author_profile": "https://Stackoverflow.com/users/33914",
"pm_score": 4,
"selected": false,
"text": "$busDays = 3;\n$day = date(\"w\");\nif( $day > 2 && $day <= 5 ) { /* if between Wed and Fri */\n $day += 2; /* add 2 more days for weekend */\n}\n$day += $busDays;\n"
},
{
"answer_id": 336167,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "// I know, these aren't holidays\n$holidays = array(\n 'Jan 2',\n 'Feb 3',\n 'Mar 5',\n 'Apr 7',\n // ...\n);\n $day_of_year = date('M j', $timestamp);\n$is_holiday = in_array($day_of_year, $holidays);\n"
},
{
"answer_id": 336175,
"author": "flamingLogos",
"author_id": 8161,
"author_profile": "https://Stackoverflow.com/users/8161",
"pm_score": 8,
"selected": true,
"text": "<?php\n//The function returns the no. of business days between two dates and it skips the holidays\nfunction getWorkingDays($startDate,$endDate,$holidays){\n // do strtotime calculations just once\n $endDate = strtotime($endDate);\n $startDate = strtotime($startDate);\n\n\n //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24\n //We add one to inlude both dates in the interval.\n $days = ($endDate - $startDate) / 86400 + 1;\n\n $no_full_weeks = floor($days / 7);\n $no_remaining_days = fmod($days, 7);\n\n //It will return 1 if it's Monday,.. ,7 for Sunday\n $the_first_day_of_week = date(\"N\", $startDate);\n $the_last_day_of_week = date(\"N\", $endDate);\n\n //---->The two can be equal in leap years when february has 29 days, the equal sign is added here\n //In the first case the whole interval is within a week, in the second case the interval falls in two weeks.\n if ($the_first_day_of_week <= $the_last_day_of_week) {\n if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;\n if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;\n }\n else {\n // (edit by Tokes to fix an edge case where the start day was a Sunday\n // and the end day was NOT a Saturday)\n\n // the day of the week for start is later than the day of the week for end\n if ($the_first_day_of_week == 7) {\n // if the start date is a Sunday, then we definitely subtract 1 day\n $no_remaining_days--;\n\n if ($the_last_day_of_week == 6) {\n // if the end date is a Saturday, then we subtract another day\n $no_remaining_days--;\n }\n }\n else {\n // the start date was a Saturday (or earlier), and the end date was (Mon..Fri)\n // so we skip an entire weekend and subtract 2 days\n $no_remaining_days -= 2;\n }\n }\n\n //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder\n//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it\n $workingDays = $no_full_weeks * 5;\n if ($no_remaining_days > 0 )\n {\n $workingDays += $no_remaining_days;\n }\n\n //We subtract the holidays\n foreach($holidays as $holiday){\n $time_stamp=strtotime($holiday);\n //If the holiday doesn't fall in weekend\n if ($startDate <= $time_stamp && $time_stamp <= $endDate && date(\"N\",$time_stamp) != 6 && date(\"N\",$time_stamp) != 7)\n $workingDays--;\n }\n\n return $workingDays;\n}\n\n//Example:\n\n$holidays=array(\"2008-12-25\",\"2008-12-26\",\"2009-01-01\");\n\necho getWorkingDays(\"2008-12-22\",\"2009-01-02\",$holidays)\n// => will return 7\n?>\n"
},
{
"answer_id": 1830206,
"author": "Bobbin",
"author_id": 222560,
"author_profile": "https://Stackoverflow.com/users/222560",
"pm_score": 3,
"selected": false,
"text": " function add_business_days($startdate,$buisnessdays,$holidays,$dateformat){\n $i=1;\n $dayx = strtotime($startdate);\n while($i < $buisnessdays){\n $day = date('N',$dayx);\n $date = date('Y-m-d',$dayx);\n if($day < 6 && !in_array($date,$holidays))$i++;\n $dayx = strtotime($date.' +1 day');\n }\n return date($dateformat,$dayx);\n }\n\n //Example\n date_default_timezone_set('Europe\\London');\n $startdate = '2012-01-08';\n $holidays=array(\"2012-01-10\");\n echo '<p>Start date: '.date('r',strtotime( $startdate));\n echo '<p>'.add_business_days($startdate,7,$holidays,'r');\n date_default_timezone_set('Europe\\London');\n //Example:\n $holidays = array('2012-01-10');\n $startDate = '2012-01-08';\n $endDate = '2012-01-13';\n echo getWorkingDays( $startDate,$endDate,$holidays);\n Sun, 08 Jan 2012 00:00:00 +0000 weekend\nMon, 09 Jan 2012 00:00:00 +0000\nTue, 10 Jan 2012 00:00:00 +0000 holiday\nWed, 11 Jan 2012 00:00:00 +0000\nThu, 12 Jan 2012 00:00:00 +0000\nFri, 13 Jan 2012 00:00:00 +0000 \n function get_working_days($startDate,$endDate,$holidays){\n $debug = true;\n $work = 0;\n $nowork = 0;\n $dayx = strtotime($startDate);\n $endx = strtotime($endDate);\n if($debug){\n echo '<h1>get_working_days</h1>';\n echo 'startDate: '.date('r',strtotime( $startDate)).'<br>';\n echo 'endDate: '.date('r',strtotime( $endDate)).'<br>';\n var_dump($holidays);\n echo '<p>Go to work...';\n }\n while($dayx <= $endx){\n $day = date('N',$dayx);\n $date = date('Y-m-d',$dayx);\n if($debug)echo '<br />'.date('r',$dayx).' ';\n if($day > 5 || in_array($date,$holidays)){\n $nowork++;\n if($debug){\n if($day > 5)echo 'weekend';\n else echo 'holiday';\n }\n } else $work++;\n $dayx = strtotime($date.' +1 day');\n }\n if($debug){\n echo '<p>No work: '.$nowork.'<br>';\n echo 'Work: '.$work.'<br>';\n echo 'Work + no work: '.($nowork+$work).'<br>';\n echo 'All seconds / seconds in a day: '.floatval(strtotime($endDate)-strtotime($startDate))/floatval(24*60*60);\n }\n return $work;\n }\n\n date_default_timezone_set('Europe\\London');\n //Example:\n $holidays=array(\"2012-01-10\");\n $startDate = '2012-01-08';\n $endDate = '2012-01-13';\n//broken\n echo getWorkingDays( $startDate,$endDate,$holidays);\n//works\n echo get_working_days( $startDate,$endDate,$holidays);\n"
},
{
"answer_id": 2567529,
"author": "Richard Varno",
"author_id": 214891,
"author_profile": "https://Stackoverflow.com/users/214891",
"pm_score": 0,
"selected": false,
"text": "// $start_date will default to today \n\nif ($start_date=='') { $start_date = date(\"Y-m-d\"); }\n\n$business_day_ct = 0;\n\n$max_days = 10000 + $num_days; // to avoid any possibility of an infinite loop\n\n\n// define holidays, this currently only goes to 2012 because, well, you know... ;-)\n// if the world is still here after that, you can find more at\n// http://www.opm.gov/Operating_Status_Schedules/fedhol/2013.asp\n// always add holidays in order, because the iteration will stop when the holiday is > date being tested\n\n$fed_holidays=array(\n \"2010-01-01\",\n \"2010-01-18\",\n \"2010-02-15\",\n \"2010-05-31\",\n \"2010-07-05\",\n \"2010-09-06\",\n \"2010-10-11\",\n \"2010-11-11\",\n \"2010-11-25\",\n \"2010-12-24\",\n\n \"2010-12-31\",\n \"2011-01-17\",\n \"2011-02-21\",\n \"2011-05-30\",\n \"2011-07-04\",\n \"2011-09-05\",\n \"2011-10-10\",\n \"2011-11-11\",\n \"2011-11-24\",\n \"2011-12-26\",\n\n \"2012-01-02\",\n \"2012-01-16\",\n \"2012-02-20\",\n \"2012-05-28\",\n \"2012-07-04\",\n \"2012-09-03\",\n \"2012-10-08\",\n \"2012-11-12\",\n \"2012-11-22\",\n \"2012-12-25\",\n );\n\n$curr_date_ymd = date('Y-m-d', strtotime($start_date)); \n\nfor ($x=1;$x<$max_days;$x++)\n{\n if (intval($num_days)==intval($business_day_ct)) { return(date($rtn_fmt, strtotime($curr_date_ymd))); } // date found - return\n\n // get next day to check\n\n $curr_date_ymd = date('Y-m-d', (strtotime($start_date)+($x * 86400))); // add 1 day to the current date\n\n $is_business_day = 1;\n\n // check if this is a weekend 1 (for Monday) through 7 (for Sunday)\n\n if ( intval(date(\"N\",strtotime($curr_date_ymd))) > 5) { $is_business_day = 0; }\n\n //check for holiday\n foreach($fed_holidays as $holiday)\n {\n if (strtotime($holiday)==strtotime($curr_date_ymd)) // holiday found\n {\n $is_business_day = 0;\n break 1;\n }\n\n if (strtotime($holiday)>strtotime($curr_date_ymd)) { break 1; } // past date, stop searching (always add holidays in order)\n\n\n }\n\n $business_day_ct = $business_day_ct + $is_business_day; // increment if this is a business day\n\n} \n\n// if we get here, you are hosed\nreturn (\"ERROR\");\n"
},
{
"answer_id": 3076240,
"author": "Alex",
"author_id": 371102,
"author_profile": "https://Stackoverflow.com/users/371102",
"pm_score": 2,
"selected": false,
"text": "function dateFromBusinessDays($days, $dateTime=null) {\n $dateTime = is_null($dateTime) ? time() : $dateTime;\n $_day = 0;\n $_direction = $days == 0 ? 0 : intval($days/abs($days));\n $_day_value = (60 * 60 * 24);\n\n while($_day !== $days) {\n $dateTime += $_direction * $_day_value;\n\n $_day_w = date(\"w\", $dateTime);\n if ($_day_w > 0 && $_day_w < 6) {\n $_day += $_direction * 1; \n }\n }\n\n return $dateTime;\n}\n echo date(\"m/d/Y\", dateFromBusinessDays(-7));\necho date(\"m/d/Y\", dateFromBusinessDays(3, time() + 3*60*60*24));\n"
},
{
"answer_id": 3142251,
"author": "mcgrailm",
"author_id": 234670,
"author_profile": "https://Stackoverflow.com/users/234670",
"pm_score": 1,
"selected": false,
"text": " function add_business_days($startdate,$buisnessdays,$holidays=array(),$dateformat){\n $enddate = strtotime($startdate);\n $day = date('N',$enddate);\n while($buisnessdays > 1){\n $enddate = strtotime(date('Y-m-d',$enddate).' +1 day');\n $day = date('N',$enddate);\n if($day < 6 && !in_array($enddate,$holidays))$buisnessdays--;\n }\n return date($dateformat,$enddate);\n }\n"
},
{
"answer_id": 3884141,
"author": "Vijay",
"author_id": 469392,
"author_profile": "https://Stackoverflow.com/users/469392",
"pm_score": 1,
"selected": false,
"text": "<?php\n// $today is the UNIX timestamp for today's date\n$today = time();\necho \"<strong>Today is (ORDER DATE): \" . '<font color=\"red\">' . date('l, F j, Y', $today) . \"</font></strong><br/><br/>\";\n\n//The numerical representation for day of week (Ex. 01 for Monday .... 07 for Sunday\n$today_numerical = date(\"N\",$today);\n\n//leadtime_days holds the numeric value for the number of business days \n$leadtime_days = $_POST[\"leadtime\"];\n\n//leadtime is the adjusted date for shipdate\n$shipdate = time();\n\nwhile ($leadtime_days > 0) \n{\n if ($today_numerical != 5 && $today_numerical != 6)\n {\n $shipdate = $shipdate + (60*60*24);\n $today_numerical = date(\"N\",$shipdate);\n $leadtime_days --;\n }\n else\n $shipdate = $shipdate + (60*60*24);\n $today_numerical = date(\"N\",$shipdate);\n}\n\necho '<strong>Estimated Ship date: ' . '<font color=\"green\">' . date('l, F j, Y', $shipdate) . \"</font></strong>\";\n?>\n"
},
{
"answer_id": 4789658,
"author": "FAOM",
"author_id": 588447,
"author_profile": "https://Stackoverflow.com/users/588447",
"pm_score": -1,
"selected": false,
"text": "function add_business_days($startdate,$buisnessdays,$holidays,$dateformat){\n $enddate = strtotime($startdate);\n $day = date('N',$enddate);\n while($buisnessdays > 0){ // compatible with 1 businessday if I'll need it\n $enddate = strtotime(date('Y-m-d',$enddate).' +1 day');\n $day = date('N',$enddate);\n if($day < 6 && !in_array(date('Y-m-d',$enddate),$holidays))$buisnessdays--;\n }\n return date($dateformat,$enddate);\n}\n\n// as a parameter in in_array function we should use endate formated to \n// compare correctly with the holidays array.\n"
},
{
"answer_id": 4895891,
"author": "Pratik Thakkar",
"author_id": 480165,
"author_profile": "https://Stackoverflow.com/users/480165",
"pm_score": 0,
"selected": false,
"text": "function add_business_days($startdate, $buisnessdays, $holidays = array(), $dateformat = 'Y-m-d'){\n$i= 1;\n$dayx= strtotime($startdate);\n$buisnessdays= ceil($buisnessdays);\n\nwhile($i < $buisnessdays)\n{\n $day= date('N',$dayx);\n\n $date= date('Y-m-d',$dayx);\n if($day < 6 && !in_array($date,$holidays))\n $i++;\n\n $dayx= strtotime($date.' +1 day');\n}\n\n## If the calculated day falls on a weekend or is a holiday, then add days to the next business day\n$day= date('N',$dayx);\n$date= date('Y-m-d',$dayx);\n\nwhile($day >= 6 || in_array($date,$holidays))\n{\n $dayx= strtotime($date.' +1 day');\n $day= date('N',$dayx);\n $date= date('Y-m-d',$dayx);\n}\n\nreturn date($dateformat, $dayx);}\n"
},
{
"answer_id": 5172063,
"author": "pawpro",
"author_id": 641790,
"author_profile": "https://Stackoverflow.com/users/641790",
"pm_score": 1,
"selected": false,
"text": "<?php\n/*\n * Does not count current day, the date returned is the last business day\n * Requires PHP 5.1 (Using ISO-8601 week)\n */\n\nfunction businessDays($timestamp = false, $bDays = 2) {\n if($timestamp === false) $timestamp = time();\n while ($bDays>0) {\n $timestamp += 86400;\n if (date('N', $timestamp)<6) $bDays--;\n }\n return $timestamp;\n}\n <?php\n/*\n * Does not count current day, the date returned is a business day \n * following the last business day\n * Requires PHP 5.1 (Using ISO-8601 week)\n */\n\nfunction businessDays($timestamp = false, $bDays = 2) {\n if($timestamp === false) $timestamp = time();\n while ($bDays+1>0) {\n $timestamp += 86400;\n if (date('N', $timestamp)<6) $bDays--;\n }\n return $timestamp;\n}\n <?php\n/*\n * Does not count current day, the date returned is \n * a date following the last business day (can be weekend or not. \n * See above for alternatives)\n * Requires PHP 5.1 (Using ISO-8601 week)\n */\n\nfunction businessDays($timestamp = false, $bDays = 2) {\n if($timestamp === false) $timestamp = time();\n while ($bDays>0) {\n $timestamp += 86400;\n if (date('N', $timestamp)<6) $bDays--;\n }\n return $timestamp += 86400;\n}\n $holidays = array_flip(strtotime('2011-01-01'),strtotime('2011-12-25'));\n if (date('N', $timestamp)<6) $bDays--;\n if (date('N', $timestamp)<6 && !isset($holidays[$timestamp])) $bDays--;\n <?php\n/*\n * Does not count current day, the date returned is the last business day\n * Requires PHP 5.1 (Using ISO-8601 week)\n */\n\nfunction businessDays($timestamp = false, $bDays = 2) {\n if($timestamp === false) $timestamp = strtotime(date('Y-m-d',time()));\n $holidays = array_flip(strtotime('2011-01-01'),strtotime('2011-12-25'));\n while ($bDays>0) {\n $timestamp += 86400;\n if (date('N', $timestamp)<6 && !isset($holidays[$timestamp])) $bDays--;\n }\n return $timestamp;\n}\n"
},
{
"answer_id": 5581800,
"author": "marve",
"author_id": 696877,
"author_profile": "https://Stackoverflow.com/users/696877",
"pm_score": 1,
"selected": false,
"text": "<?php \nfunction AddWorkDays(){\n$i = 0;\n$d = 5; // Number of days to add\n\n while($i <= $d) {\n $i++;\n if(date('N', mktime(0, 0, 0, date(m), date(d)+$i, date(Y))) < 5) {\n $d++;\n }\n }\n return date(Y).','.date(m).','.(date(d)+$d);\n}\n?>\n"
},
{
"answer_id": 7766408,
"author": "Craig Francis",
"author_id": 6632,
"author_profile": "https://Stackoverflow.com/users/6632",
"pm_score": 2,
"selected": false,
"text": "function business_days_add($start_date, $business_days, $holidays = array()) {\n $current_date = strtotime($start_date);\n $business_days = intval($business_days); // Decrement does not work on strings\n while ($business_days > 0) {\n if (date('N', $current_date) < 6 && !in_array(date('Y-m-d', $current_date), $holidays)) {\n $business_days--;\n }\n if ($business_days > 0) {\n $current_date = strtotime('+1 day', $current_date);\n }\n }\n return $current_date;\n}\n function business_days_diff($start_date, $end_date, $holidays = array()) {\n $business_days = 0;\n $current_date = strtotime($start_date);\n $end_date = strtotime($end_date);\n while ($current_date <= $end_date) {\n if (date('N', $current_date) < 6 && !in_array(date('Y-m-d', $current_date), $holidays)) {\n $business_days++;\n }\n if ($current_date <= $end_date) {\n $current_date = strtotime('+1 day', $current_date);\n }\n }\n return $business_days;\n}\n"
},
{
"answer_id": 8424240,
"author": "atis",
"author_id": 1086714,
"author_profile": "https://Stackoverflow.com/users/1086714",
"pm_score": 2,
"selected": false,
"text": "if (date('N')<6 && date('G')>8 && date('G')<16) {\n // we have a working time (or check for holidays)\n}\n"
},
{
"answer_id": 9813397,
"author": "shepardtone",
"author_id": 1011784,
"author_profile": "https://Stackoverflow.com/users/1011784",
"pm_score": 1,
"selected": false,
"text": "// Returns a $numBusDays-sized array of all business dates, \n// starting from and including $currentDate. \n// Any date in $holidays will be skipped over.\n\nfunction getWorkingDays($currentDate, $numBusDays, $holidays = array(), \n $resultDates = array())\n{\n // exit when we have collected the required number of business days\n if ($numBusDays === 0) {\n return $resultDates;\n }\n\n // add current date to return array, if not a weekend or holiday\n $date = date(\"w\", strtotime($currentDate));\n if ( $date != 0 && $date != 6 && !in_array($currentDate, $holidays) ) {\n $resultDates[] = $currentDate;\n $numBusDays -= 1;\n }\n\n // set up the next date to test\n $currentDate = new DateTime(\"$currentDate + 1 day\");\n $currentDate = $currentDate->format('Y-m-d');\n\n return getWorkingDays($currentDate, $numBusDays, $holidays, $resultDates);\n}\n\n// test\n$days = getWorkingDays('2008-12-05', 4);\nprint_r($days);\n"
},
{
"answer_id": 10837433,
"author": "James",
"author_id": 1428919,
"author_profile": "https://Stackoverflow.com/users/1428919",
"pm_score": 1,
"selected": false,
"text": "date_default_timezone_set('America/New_York');\n\n\n/** Given a number days out, what day is that when counting by 'business' days\n * get the next business day. by default it looks for next business day\n * ie calling $date = get_next_busines_day(); on monday will return tuesday\n * $date = get_next_busines_day(2); on monday will return wednesday\n * $date = get_next_busines_day(2); on friday will return tuesday\n *\n * @param $number_of_business_days (integer) how many business days out do you want\n * @param $start_date (string) strtotime parseable time value\n * @param $ignore_holidays (boolean) true/false to ignore holidays\n * @param $return_format (string) as specified in php.net/date\n */\nfunction get_next_business_day($number_of_business_days=1,$start_date='today',$ignore_holidays=false,$return_format='m/d/y') {\n\n // get the start date as a string to time\n $result = strtotime($start_date);\n\n // now keep adding to today's date until number of business days is 0 and we land on a business day\n while ($number_of_business_days > 0) {\n // add one day to the start date\n $result = strtotime(date('Y-m-d',$result) . \" + 1 day\");\n\n // this day counts if it's a weekend and not a holiday, or if we choose to ignore holidays\n if (is_weekday(date('Y-m-d',$result)) && (!(is_holiday(date('Y-m-d',$result))) || $ignore_holidays) ) \n $number_of_business_days--;\n\n }\n\n // when my $number of business days is exausted I have my final date\n\n return(date($return_format,$result));\n}\n\n function is_weekend($date) {\n // return if this is a weekend date or not.\n return (date('N', strtotime($date)) >= 6);\n}\n\nfunction is_weekday($date) {\n // return if this is a weekend date or not.\n return (date('N', strtotime($date)) < 6);\n}\n\nfunction is_holiday($date) {\n // return if this is a holiday or not.\n\n // what are my holidays for this year\n $holidays = array(\"New Year's Day 2011\" => \"12/31/10\",\n \"Good Friday\" => \"04/06/12\",\n \"Memorial Day\" => \"05/28/12\",\n \"Independence Day\" => \"07/04/12\",\n \"Floating Holiday\" => \"12/31/12\",\n \"Labor Day\" => \"09/03/12\",\n \"Thanksgiving Day\" => \"11/22/12\",\n \"Day After Thanksgiving Day\" => \"11/23/12\",\n \"Christmas Eve\" => \"12/24/12\",\n \"Christmas Day\" => \"12/25/12\",\n \"New Year's Day 2012\" => \"01/02/12\",\n \"New Year's Day 2013\" => \"01/01/13\"\n );\n\n return(in_array(date('m/d/y', strtotime($date)),$holidays));\n}\n\n\nprint get_next_business_day(1) . \"\\n\";\n"
},
{
"answer_id": 13633743,
"author": "James Pasta",
"author_id": 1864384,
"author_profile": "https://Stackoverflow.com/users/1864384",
"pm_score": 4,
"selected": false,
"text": "/**\n * National American Holidays\n * @param string $year\n * @return array\n */\npublic static function getNationalAmericanHolidays($year) {\n\n\n // January 1 - New Year’s Day (Observed)\n // Calc Last Monday in May - Memorial Day strtotime(\"last Monday of May 2011\");\n // July 4 Independence Day\n // First monday in september - Labor Day strtotime(\"first Monday of September 2011\")\n // November 11 - Veterans’ Day (Observed)\n // Fourth Thursday in November Thanksgiving strtotime(\"fourth Thursday of November 2011\");\n // December 25 - Christmas Day \n $bankHolidays = array(\n $year . \"-01-01\" // New Years\n , \"\". date(\"Y-m-d\",strtotime(\"last Monday of May \" . $year) ) // Memorial Day\n , $year . \"-07-04\" // Independence Day (corrected)\n , \"\". date(\"Y-m-d\",strtotime(\"first Monday of September \" . $year) ) // Labor Day\n , $year . \"-11-11\" // Veterans Day\n , \"\". date(\"Y-m-d\",strtotime(\"fourth Thursday of November \" . $year) ) // Thanksgiving\n , $year . \"-12-25\" // XMAS\n );\n\n return $bankHolidays;\n}\n"
},
{
"answer_id": 14319003,
"author": "Tony",
"author_id": 1977364,
"author_profile": "https://Stackoverflow.com/users/1977364",
"pm_score": -1,
"selected": false,
"text": "// January 1 - New Year's Day (Observed)\n// Third Monday in January - Birthday of Martin Luther King, Jr.\n// Third Monday in February - Washington’s Birthday / President's Day\n// Last Monday in May - Memorial Day\n// July 4 - Independence Day\n// First Monday in September - Labor Day\n// Second Monday in October - Columbus Day\n// November 11 - Veterans’ Day (Observed)\n// Fourth Thursday in November Thanksgiving Day\n// December 25 - Christmas Day\n$bankHolidays = array(\n ['New Years Day'] => $year . \"-01-01\",\n ['Martin Luther King Jr Birthday'] => \"\". date(\"Y-m-d\",strtotime(\"third Monday of January \" . $year) ),\n ['Washingtons Birthday'] => \"\". date(\"Y-m-d\",strtotime(\"third Monday of February \" . $year) ),\n ['Memorial Day'] => \"\". date(\"Y-m-d\",strtotime(\"last Monday of May \" . $year) ),\n ['Independance Day'] => $year . \"-07-04\",\n ['Labor Day'] => \"\". date(\"Y-m-d\",strtotime(\"first Monday of September \" . $year) ),\n ['Columbus Day'] => \"\". date(\"Y-m-d\",strtotime(\"second Monday of October \" . $year) ),\n ['Veterans Day'] => $year . \"-11-11\",\n ['Thanksgiving Day'] => \"\". date(\"Y-m-d\",strtotime(\"fourth Thursday of November \" . $year) ),\n ['Christmas Day'] => $year . \"-12-25\"\n);\n\nreturn $bankHolidays;\n"
},
{
"answer_id": 17559605,
"author": "Dustin W",
"author_id": 2566152,
"author_profile": "https://Stackoverflow.com/users/2566152",
"pm_score": 0,
"selected": false,
"text": "<?php\nfunction count_business_days($date, $days, $holidays) {\n $date = strtotime($date);\n\n for ($i = 1; $i <= intval($days); $i++) { //Loops each day count\n\n //First, find the next available weekday because this might be a weekend/holiday\n while (date('N', $date) >= 6 || in_array(date('Y-m-d', $date), $holidays)){\n $date = strtotime(date('Y-m-d',$date).' +1 day');\n }\n\n //Now that we know we have a business day, add 1 day to it\n $date = strtotime(date('Y-m-d',$date).' +1 day');\n\n //If this day that was previously added falls on a weekend/holiday, then find the next business day\n while (date('N', $date) >= 6 || in_array(date('Y-m-d', $date), $holidays)){\n $date = strtotime(date('Y-m-d',$date).' +1 day');\n }\n }\n return date('Y-m-d', $date);\n}\n\n//Also add in the code from Tony and James Pasta to handle holidays...\n\nfunction getNationalAmericanHolidays($year) {\n$bankHolidays = array(\n 'New Years Day' => $year . \"-01-01\",\n 'Martin Luther King Jr Birthday' => \"\". date(\"Y-m-d\",strtotime(\"third Monday of January \" . $year) ),\n 'Washingtons Birthday' => \"\". date(\"Y-m-d\",strtotime(\"third Monday of February \" . $year) ),\n 'Memorial Day' => \"\". date(\"Y-m-d\",strtotime(\"last Monday of May \" . $year) ),\n 'Independance Day' => $year . \"-07-04\",\n 'Labor Day' => \"\". date(\"Y-m-d\",strtotime(\"first Monday of September \" . $year) ),\n 'Columbus Day' => \"\". date(\"Y-m-d\",strtotime(\"second Monday of October \" . $year) ),\n 'Veterans Day' => $year . \"-11-11\",\n 'Thanksgiving Day' => \"\". date(\"Y-m-d\",strtotime(\"fourth Thursday of November \" . $year) ),\n 'Christmas Day' => $year . \"-12-25\"\n);\nreturn $bankHolidays;\n\n}\n\n//Now to call it... since we're working with business days, we should\n//also be working with business hours so check if it's after 5 PM\n//and go to the next day if necessary.\n\n//Go to next day if after 5 pm (5 pm = 17)\nif (date(G) >= 17) {\n $start_date = date(\"Y-m-d\", strtotime(\"+ 1 day\")); //Tomorrow\n} else {\n $start_date = date(\"Y-m-d\"); //Today\n}\n\n//Get the holidays for the current year and also for the next year\n$this_year = getNationalAmericanHolidays(date('Y'));\n$next_year = getNationalAmericanHolidays(date('Y', strtotime(\"+12 months\")));\n$holidays = array_merge($this_year, $next_year);\n\n//The number of days to count\n$days_count = 10;\n\necho count_business_days($start_date, $days_count, $holidays);\n\n?>\n"
},
{
"answer_id": 19221403,
"author": "Glavić",
"author_id": 67332,
"author_profile": "https://Stackoverflow.com/users/67332",
"pm_score": 7,
"selected": false,
"text": "echo number_of_working_days('2013-12-23', '2013-12-29');\n 3\n function number_of_working_days($from, $to) {\n $workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...)\n $holidayDays = ['*-12-25', '*-01-01', '2013-12-23']; # variable and fixed holidays\n\n $from = new DateTime($from);\n $to = new DateTime($to);\n $to->modify('+1 day');\n $interval = new DateInterval('P1D');\n $periods = new DatePeriod($from, $interval, $to);\n\n $days = 0;\n foreach ($periods as $period) {\n if (!in_array($period->format('N'), $workingDays)) continue;\n if (in_array($period->format('Y-m-d'), $holidayDays)) continue;\n if (in_array($period->format('*-m-d'), $holidayDays)) continue;\n $days++;\n }\n return $days;\n}\n"
},
{
"answer_id": 20685682,
"author": "DevlshOne",
"author_id": 408318,
"author_profile": "https://Stackoverflow.com/users/408318",
"pm_score": 0,
"selected": false,
"text": "function onlyWorkDays( $d ) {\n $holidays = array('2013-12-25','2013-12-31','2014-01-01','2014-01-20','2014-02-17','2014-05-26','2014-07-04','2014-09-01','2014-10-13','2014-11-11','2014-11-27','2014-12-25','2014-12-31');\n while (in_array($d->format(\"Y-m-d\"), $holidays)) { // HOLIDAYS\n $d->sub(new DateInterval(\"P1D\"));\n }\n if ($d->format(\"w\") == 6) { // SATURDAY\n $d->sub(new DateInterval(\"P1D\"));\n }\n if ($d->format(\"w\") == 0) { // SUNDAY\n $d->sub(new DateInterval(\"P2D\"));\n }\n return $d;\n}\n new"
},
{
"answer_id": 25309304,
"author": "Big Joe",
"author_id": 3664702,
"author_profile": "https://Stackoverflow.com/users/3664702",
"pm_score": 0,
"selected": false,
"text": "function getBusinessDays($date1, $date2){\n\n if(!is_numeric($date1)){\n $date1 = strtotime($date1);\n }\n\n if(!is_numeric($date2)){\n $date2 = strtotime($date2);\n }\n\n if($date2 < $date1){\n $temp_date = $date1;\n $date1 = $date2;\n $date2 = $temp_date;\n unset($temp_date);\n }\n\n $diff = $date2 - $date1;\n\n $days_diff = intval($diff / (3600 * 24));\n $current_day_of_week = intval(date(\"N\", $date1));\n $business_days = 0;\n\n for($i = 1; $i <= $days_diff; $i++){\n if(!in_array($current_day_of_week, array(\"Sunday\" => 1, \"Saturday\" => 7))){\n $business_days++;\n }\n\n $current_day_of_week++;\n if($current_day_of_week > 7){\n $current_day_of_week = 1;\n }\n }\n\n return $business_days;\n}\n\necho \"Business days: \" . getBusinessDays(\"8/15/2014\", \"8/8/2014\");\n"
},
{
"answer_id": 25658165,
"author": "Suresh Kamrushi",
"author_id": 1900692,
"author_profile": "https://Stackoverflow.com/users/1900692",
"pm_score": 4,
"selected": false,
"text": "$startDate = new DateTime( '2013-04-01' ); //intialize start date\n$endDate = new DateTime( '2013-04-30' ); //initialize end date\n$holiday = array('2013-04-11','2013-04-25'); //this is assumed list of holiday\n$interval = new DateInterval('P1D'); // set the interval as 1 day\n$daterange = new DatePeriod($startDate, $interval ,$endDate);\nforeach($daterange as $date){\nif($date->format(\"N\") <6 AND !in_array($date->format(\"Y-m-d\"),$holiday))\n$result[] = $date->format(\"Y-m-d\");\n}\necho \"<pre>\";print_r($result);\n"
},
{
"answer_id": 30346100,
"author": "Ian Carter",
"author_id": 4917270,
"author_profile": "https://Stackoverflow.com/users/4917270",
"pm_score": 1,
"selected": false,
"text": "/**\n * @param days, int\n * @param $format, string: dateformat (if format defined OTHERWISE int: timestamp) \n * @param start, int: timestamp (mktime) default: time() //now\n * @param $wk, bit[]: flags for each workday (0=SUN, 6=SAT) 1=workday, 0=day off\n * @param $holiday, string[]: list of dates, YYYY-MM-DD, MM-DD \n */\nfunction working_days($days, $format='', $start=null, $week=[0,1,1,1,1,1,0], $holiday=[])\n{\n if(is_null($start)) $start = time();\n if($days <= 0) return $start;\n if(count($week) != 7) trigger_error('workweek must contain bit-flags for 7 days');\n if(array_sum($week) == 0) trigger_error('workweek must contain at least one workday');\n $wd = date('w', $start);//0=sun, 6=sat\n $time = $start;\n while($days)\n {\n if(\n $week[$wd]\n && !in_array(date('Y-m-d', $time), $holiday)\n && !in_array(date('m-d', $time), $holiday)\n ) --$days; //decrement on workdays\n $wd = date('w', $time += 86400); //add one day in seconds\n }\n $time -= 86400;//include today\n return $format ? date($format, $time): $time;\n}\n\n//simple usage\n$ten_days = working_days(10, 'D F d Y');\necho '<br>ten workingdays (MON-FRI) disregarding holidays: ',$ten_days;\n\n//work on saturdays and add new years day as holiday\n$ten_days = working_days(10, 'D F d Y', null, [0,1,1,1,1,1,1], ['01-01']);\necho '<br>ten workingdays (MON-SAT) disregarding holidays: ',$ten_days;\n"
},
{
"answer_id": 32459659,
"author": "George John",
"author_id": 2885831,
"author_profile": "https://Stackoverflow.com/users/2885831",
"pm_score": 3,
"selected": false,
"text": "function getWorkingDays($startDate, $endDate)\n{\n $begin = strtotime($startDate);\n $end = strtotime($endDate);\n if ($begin > $end) {\n\n return 0;\n } else {\n $no_days = 0;\n while ($begin <= $end) {\n $what_day = date(\"N\", $begin);\n if (!in_array($what_day, [6,7]) ) // 6 and 7 are weekend\n $no_days++;\n $begin += 86400; // +1 day\n };\n\n return $no_days;\n }\n}\n"
},
{
"answer_id": 36052826,
"author": "easycodingclub",
"author_id": 5700389,
"author_profile": "https://Stackoverflow.com/users/5700389",
"pm_score": 2,
"selected": false,
"text": "<?php\n$holiday_date_array = array(\"2016-01-26\", \"2016-03-07\", \"2016-03-24\", \"2016-03-25\", \"2016-04-15\", \"2016-08-15\", \"2016-09-12\", \"2016-10-11\", \"2016-10-31\");\n$date_required = \"2016-03-01\";\n\nfunction increase_date($date_required, $holiday_date_array=array(), $days = 15){\n if(!empty($date_required)){\n $counter_1=0;\n $incremented_date = '';\n for($i=1; $i <= $days; $i++){\n $date = strtotime(\"+$i day\", strtotime($date_required));\n $day_name = date(\"D\", $date);\n $incremented_date = date(\"Y-m-d\", $date);\n if($day_name=='Sat'||$day_name=='Sun'|| in_array($incremented_date ,$holiday_date_array)==true){\n $counter_1+=1;\n }\n }\n if($counter_1 > 0){\n return increase_date($incremented_date, $holiday_date_array, $counter_1);\n }else{\n return $incremented_date;\n }\n }else{\n return 'invalid';\n }\n}\n\necho increase_date($date_required, $holiday_date_array, 15);\n?>\n\n//output after adding 15 business working days in 2016-03-01 will be \"2016-03-23\"\n"
},
{
"answer_id": 40674843,
"author": "Enrico",
"author_id": 7177665,
"author_profile": "https://Stackoverflow.com/users/7177665",
"pm_score": 1,
"selected": false,
"text": "/**\n * Function to calculate the working days between two days, considering holidays.\n * @param string $startDate -- Start date of the range (included), formatted as Y-m-d.\n * @param string $endDate -- End date of the range (included), formatted as Y-m-d.\n * @param array(string) $holidayDates -- OPTIONAL. Array of holidays dates, formatted as Y-m-d. (e.g. array(\"2016-08-15\", \"2016-12-25\"))\n * @return int -- Number of working days.\n */\nfunction getWorkingDays($startDate, $endDate, $holidayDates=array()){\n $dateRange = new DatePeriod(new DateTime($startDate), new DateInterval('P1D'), (new DateTime($endDate))->modify(\"+1day\"));\n foreach ($dateRange as $dr) { if($dr->format(\"N\")<6){$workingDays[]=$dr->format(\"Y-m-d\");} }\n return count(array_diff($workingDays, $holidayDates));\n}\n"
},
{
"answer_id": 41749922,
"author": "Nicolas Giszpenc",
"author_id": 3727524,
"author_profile": "https://Stackoverflow.com/users/3727524",
"pm_score": 1,
"selected": false,
"text": "//Usage\n$days = 30;\n$next_working_date = nextWorkingDay($days, $somedate);\n\n//add date function\nfunction DateAdd($interval, $number, $date) {\n\n $date_time_array = getdate($date);\n //die(print_r($date_time_array));\n\n $hours = $date_time_array[\"hours\"];\n $minutes = $date_time_array[\"minutes\"];\n $seconds = $date_time_array[\"seconds\"];\n $month = $date_time_array[\"mon\"];\n $day = $date_time_array[\"mday\"];\n $year = $date_time_array[\"year\"];\n\n switch ($interval) {\n\n case \"yyyy\":\n $year+=$number;\n break;\n case \"q\":\n $year+=($number*3);\n break;\n case \"m\":\n $month+=$number;\n break;\n case \"y\":\n case \"d\":\n case \"w\":\n $day+=$number;\n break;\n case \"ww\":\n $day+=($number*7);\n break;\n case \"h\":\n $hours+=$number;\n break;\n case \"n\":\n $minutes+=$number;\n break;\n case \"s\":\n $seconds+=$number; \n break; \n }\n // echo \"day:\" . $day;\n $timestamp= mktime($hours,$minutes,$seconds,$month,$day,$year);\n return $timestamp;\n}\n\n// the following function get_holiday() is based on the work done by\n// Marcos J. Montes\nfunction get_holiday($year, $month, $day_of_week, $week=\"\") {\n if ( (($week != \"\") && (($week > 5) || ($week < 1))) || ($day_of_week > 6) || ($day_of_week < 0) ) {\n // $day_of_week must be between 0 and 6 (Sun=0, ... Sat=6); $week must be between 1 and 5\n return FALSE;\n } else {\n if (!$week || ($week == \"\")) {\n $lastday = date(\"t\", mktime(0,0,0,$month,1,$year));\n $temp = (date(\"w\",mktime(0,0,0,$month,$lastday,$year)) - $day_of_week) % 7;\n } else {\n $temp = ($day_of_week - date(\"w\",mktime(0,0,0,$month,1,$year))) % 7;\n }\n\n if ($temp < 0) {\n $temp += 7;\n }\n\n if (!$week || ($week == \"\")) {\n $day = $lastday - $temp;\n } else {\n $day = (7 * $week) - 6 + $temp;\n }\n //echo $year.\", \".$month.\", \".$day . \"<br><br>\";\n return format_date($year, $month, $day);\n }\n}\n\nfunction observed_day($year, $month, $day) {\n // sat -> fri & sun -> mon, any exceptions?\n //\n // should check $lastday for bumping forward and $firstday for bumping back,\n // although New Year's & Easter look to be the only holidays that potentially\n // move to a different month, and both are accounted for.\n\n $dow = date(\"w\", mktime(0, 0, 0, $month, $day, $year));\n\n if ($dow == 0) {\n $dow = $day + 1;\n } elseif ($dow == 6) {\n if (($month == 1) && ($day == 1)) { // New Year's on a Saturday\n $year--;\n $month = 12;\n $dow = 31;\n } else {\n $dow = $day - 1;\n }\n } else {\n $dow = $day;\n }\n\n return format_date($year, $month, $dow);\n}\n\nfunction calculate_easter($y) {\n // In the text below, 'intval($var1/$var2)' represents an integer division neglecting\n // the remainder, while % is division keeping only the remainder. So 30/7=4, and 30%7=2\n//\n // This algorithm is from Practical Astronomy With Your Calculator, 2nd Edition by Peter\n // Duffett-Smith. It was originally from Butcher's Ecclesiastical Calendar, published in\n // 1876. This algorithm has also been published in the 1922 book General Astronomy by\n // Spencer Jones; in The Journal of the British Astronomical Association (Vol.88, page\n // 91, December 1977); and in Astronomical Algorithms (1991) by Jean Meeus. \n\n $a = $y%19;\n $b = intval($y/100);\n $c = $y%100;\n $d = intval($b/4);\n $e = $b%4;\n $f = intval(($b+8)/25);\n $g = intval(($b-$f+1)/3);\n $h = (19*$a+$b-$d-$g+15)%30;\n $i = intval($c/4);\n $k = $c%4;\n $l = (32+2*$e+2*$i-$h-$k)%7;\n $m = intval(($a+11*$h+22*$l)/451);\n $p = ($h+$l-7*$m+114)%31;\n $EasterMonth = intval(($h+$l-7*$m+114)/31); // [3 = March, 4 = April]\n $EasterDay = $p+1; // (day in Easter Month)\n\n return format_date($y, $EasterMonth, $EasterDay);\n}\n\n\nfunction nextWorkingDay($number_days, $start_date = \"\") {\n $day_counter = 0;\n $intCounter = 0; \n\n if ($start_date==\"\") {\n $today = mktime(0, 0, 0, date(\"m\") , date(\"d\"), date(\"Y\"));\n } else {\n $start_time = strtotime($start_date);\n $today = mktime(0, 0, 0, date(\"m\", $start_time) , date(\"d\", $start_time), date(\"Y\", $start_time));\n }\n\n while($day_counter < $number_days) {\n $working_time = DateAdd(\"d\", 1, $today);\n $working_date = date(\"Y-m-d\", $working_date);\n if (!isWeekend($working_date) && !confirm_holiday(date(\"Y-m-d\", strtotime($working_date))) ) {\n $day_counter++;\n }\n $intCounter++;\n $today = $working_time;\n if ($intCounter > 1000) {\n //just in case out of control?\n break;\n }\n }\n\n return $working_date;\n}\nfunction isWeekend($check_date) {\n return (date(\"N\", strtotime($check_date)) > 5);\n}\nfunction confirm_holiday($somedate=\"\") {\n if ($somedate==\"\") {\n $somedate = date(\"Y-m-d\");\n }\n $year = date(\"Y\", strtotime($somedate));\n $blnHoliday = false;\n //newyears\n if ($somedate == observed_day($year, 1, 1)) {\n $blnHoliday = true;\n }\n if ($somedate == format_date($year, 1, 1)) {\n $blnHoliday = true;\n }\n if ($somedate == format_date($year, 12, 31)) {\n $blnHoliday = true;\n }\n //Martin Luther King\n if ($somedate == get_holiday($year, 1, 1, 3)) {\n $blnHoliday = true;\n }\n //President's\n if ($somedate == get_holiday($year, 2, 1, 3)) {\n $blnHoliday = true;\n }\n //easter\n if ($somedate == calculate_easter($year)) {\n $blnHoliday = true;\n }\n //Memorial\n if ($somedate == get_holiday($year, 5, 1)) {\n $blnHoliday = true;\n }\n //july4\n if ($somedate == observed_day($year, 7, 4)) {\n $blnHoliday = true;\n }\n //labor\n if ($somedate == get_holiday($year, 9, 1, 1)) {\n $blnHoliday = true;\n }\n //columbus\n if ($somedate == get_holiday($year, 10, 1, 2)) {\n $blnHoliday = true;\n }\n //thanks\n if ($somedate == get_holiday($year, 11, 4, 4)) {\n $blnHoliday = true;\n }\n //xmas\n if ($somedate == format_date($year, 12, 24)) {\n $blnHoliday = true;\n }\n if ($somedate == format_date($year, 12, 25)) {\n $blnHoliday = true;\n }\n return $blnHoliday;\n}\n"
},
{
"answer_id": 45431633,
"author": "Mahmoud Obaid",
"author_id": 8397980,
"author_profile": "https://Stackoverflow.com/users/8397980",
"pm_score": 2,
"selected": false,
"text": "function getWorkingDays($startDate,$endDate,$offdays,$holidays){\n$endDate = strtotime($endDate);\n$startDate = strtotime($startDate);\n$days = ($endDate - $startDate) / 86400 + 1;\n$counter=0;\nfor ($i = 1; $i <= $days; $i++) {\n $the_first_day_of_week = date(\"N\", $startDate);\n $startDate+=86400;\nif (!in_array($the_first_day_of_week, $offdays) && !in_array(date(\"Y-m-\nd\",$startDate), $holidays)) {\n$counter++;\n}\n\n} \nreturn $counter;\n}\n//example to use\n$holidays=array(\"2017-07-03\",\"2017-07-20\");\n$offdays=array(5,6);//weekend days Monday=1 .... Sunday=7\necho getWorkingDays(\"2017-01-01\",\"2017-12-31\",$offdays,$holidays)\n"
},
{
"answer_id": 47652387,
"author": "Laird",
"author_id": 6155720,
"author_profile": "https://Stackoverflow.com/users/6155720",
"pm_score": 2,
"selected": false,
"text": "$from = new DateTime($first_date);\n$to = new DateTime($second_date);\n\n$to->modify('+1 day');\n$interval = $from->diff($to);\n$days = $interval->format('%a');\n\n$extra_days = fmod($days, 7);\n$workdays = ( ( $days - $extra_days ) / 7 ) * 5;\n\n$first_day = date('N', strtotime($first_date));\n$last_day = date('N', strtotime(\"1 day\", strtotime($second_date)));\n$extra = 0;\nif($first_day > $last_day) {\n if($first_day == 7) {\n $first_day = 6;\n }\n\n $extra = (6 - $first_day) + ($last_day - 1);\n if($extra < 0) {\n $extra = $extra * -1;\n }\n}\nif($last_day > $first_day) {\n $extra = $last_day - $first_day;\n}\n$days = $workdays + $extra\n"
},
{
"answer_id": 57176727,
"author": "Max Luzhkov",
"author_id": 4105687,
"author_profile": "https://Stackoverflow.com/users/4105687",
"pm_score": 0,
"selected": false,
"text": "$diffInSeconds = $this->datesCounter->getDifferenceInSeconds(Carbon::create(2019, 1, 1), Carbon::now(), DateCounter::COUNTRY_FR); $date1 = Carbon::create(2019, 1, 1)->endOfDay();\n$date2 = $dt->copy()->startOfDay();\n$diff = $date1->diffFiltered(CarbonInterval::minute(), function(Carbon $date) {\n return !$date->isWeekend();\n}, $date2, true);\n"
},
{
"answer_id": 64453559,
"author": "Abkarino",
"author_id": 3399564,
"author_profile": "https://Stackoverflow.com/users/3399564",
"pm_score": 0,
"selected": false,
"text": "Θ(1) <?php\nfunction getWorkingHours($start_date, $end_date) {\n // validate input\n if(!validateDate($start_date) || !validateDate($end_date)) return ['error' => 'Invalid Date'];\n if($end_date < $start_date) return ['error' => 'End date must be greater than or equal Start date'];\n\n //We save timezone and switch to UTC to prevent issues\n $old_timezone = date_default_timezone_get();\n date_default_timezone_set(\"UTC\");\n\n $startDate = strtotime($start_date);\n $endDate = strtotime($end_date);\n\n //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24\n //We add one to include both dates in the interval.\n $days = ($endDate - $startDate) / 86400 + 1;\n $no_full_weeks = ceil($days / 7);\n //we get only missing days count to complete full weeks\n //we take modulo 7 in case it was already full weeks\n $no_of_missing_days = (7 - ($days % 7)) % 7;\n\n $workingDays = $no_full_weeks * 5;\n //Next we remove the working days we added, this loop will have max of 6 iterations.\n for ($i = 1; $i <= $no_of_missing_days; $i++){\n if(date('N', $endDate + $i * 86400) < 6) $workingDays--;\n }\n\n $holidays = getHolidays(date('Y', $startDate), date('Y', $endDate));\n\n //We subtract the holidays\n foreach($holidays as $holiday){\n $time_stamp=strtotime($holiday);\n //If the holiday doesn't fall in weekend\n if ($startDate <= $time_stamp && $time_stamp <= $endDate && date(\"N\",$time_stamp) != 6 && date(\"N\",$time_stamp) != 7)\n $workingDays--;\n }\n\n date_default_timezone_set($old_timezone);\n return ['days' => $workingDays];\n\n}\n Y-m-d yyyy-mm-dd"
},
{
"answer_id": 72220181,
"author": "jurchiks",
"author_id": 540394,
"author_profile": "https://Stackoverflow.com/users/540394",
"pm_score": 0,
"selected": false,
"text": "use Cake\\Chronos\\Date;\n\n$weekdayCalculator = new WeekdayCalculator();\n$weekdayCalculator->addSpecialWorkday(new Date('2022-01-08')); // Override Saturday as a workday.\n// Sunday stays a normal holiday as usual.\n$weekdayCalculator->addSpecialHoliday(new Date('2022-01-10')); // Override the following Monday as a holiday.\n// As a result, we've shifted the workday one day back.\n\nvar_dump(\n $weekdayCalculator->isWorkday(new Date('2022-01-08')), // Returns TRUE - we manually set this date as a workday.\n $weekdayCalculator->isHoliday(new Date('2022-01-09')), // Returns TRUE - normal holiday.\n $weekdayCalculator->getNextWorkday(new Date('2022-01-07')), // Returns Date(2022-01-08).\n $weekdayCalculator->getNextWorkday(new Date('2022-01-08')), // Returns Date(2022-01-11) - 9, 10 = holidays, 11 = normal workday.\n $weekdayCalculator->getNextHoliday(new Date('2022-01-08')), // Returns Date(2022-01-09).\n $weekdayCalculator->countDays(new Date('2022-01-01'), new Date('2022-02-01')), // Returns int(31) - January has 31 days, 02-01 is excluded.\n $weekdayCalculator->countWorkdays(new Date('2022-01-01'), new Date('2022-02-01')), // Returns int(21).\n $weekdayCalculator->countHolidays(new Date('2022-01-01'), new Date('2022-02-01')), // Returns int(10).\n $weekdayCalculator->getDays(new Date('2022-01-01'), new Date('2022-02-01')), // Returns a Generator instance for all days between specified dates.\n $weekdayCalculator->getWorkdays(new Date('2022-01-01'), new Date('2022-02-01')), // Returns a Generator instance for all workdays.\n $weekdayCalculator->getHolidays(new Date('2022-01-01'), new Date('2022-02-01')), // Returns a Generator instance for all holidays.\n iterator_to_array($weekdayCalculator->getWorkdays(new Date('2022-01-01'), new Date('2022-02-01'))), // Returns an array of 21 Date instances.\n);\n cakephp/chronos"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103/"
] |
336,138 | <p>Are all the additions to C# for version 4 (dynamic, code contracts etc) expected to run on the current .NET CLR, or is there a planned .NET upgrade as well?</p>
| [
{
"answer_id": 336278,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "dynamic"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
336,144 | <p>I have an application where I would like to have mixed Java and Scala source (actually its migrating a java app to scala - but a bit at a time). </p>
<p>I can make this work in IDEs just fine, very nice. But I am not sure how to do this with maven - scalac can compile java and scala intertwined, but how to I set up maven for the module? </p>
<p>Also, does my scala source have to be a different folder to the java? </p>
| [
{
"answer_id": 336187,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 4,
"selected": false,
"text": "src/main/scala"
},
{
"answer_id": 336398,
"author": "lindelof",
"author_id": 1428,
"author_profile": "https://Stackoverflow.com/users/1428",
"pm_score": 3,
"selected": false,
"text": "src/\n|-- main\n| |-- bin\n| |-- sh\n| |-- sql\n| |-- scala\n| |-- java\n| `-- resources\n|-- site\n...\n"
},
{
"answer_id": 370377,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 6,
"selected": true,
"text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n<modelVersion>4.0.0</modelVersion>\n<groupId>demo</groupId>\n<artifactId>scala-java-app</artifactId>\n<version>0.0.1-SNAPSHOT</version>\n<packaging>jar</packaging>\n<name>scala-java-app</name>\n<repositories>\n <repository>\n <id>scala-tools.org</id>\n <name>Scala-tools Maven2 Repository</name>\n <url>http://scala-tools.org/repo-releases</url>\n </repository>\n</repositories>\n<pluginRepositories>\n <pluginRepository>\n <id>scala-tools.org</id>\n <name>Scala-tools Maven2 Repository</name>\n <url>http://scala-tools.org/repo-releases</url>\n </pluginRepository>\n</pluginRepositories>\n<build>\n <plugins>\n <plugin>\n <groupId>org.scala-tools</groupId>\n <artifactId>maven-scala-plugin</artifactId>\n <executions>\n\n <execution>\n <id>compile</id>\n <goals>\n <goal>compile</goal>\n </goals>\n <phase>compile</phase>\n </execution>\n <execution>\n <id>test-compile</id>\n <goals>\n <goal>testCompile</goal>\n </goals>\n <phase>test-compile</phase>\n </execution>\n <execution>\n <phase>process-resources</phase>\n <goals>\n <goal>compile</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <configuration>\n <source>1.5</source>\n <target>1.5</target>\n </configuration>\n </plugin>\n </plugins> \n</build>\n<dependencies>\n <dependency>\n <groupId>org.scala-lang</groupId>\n <artifactId>scala-library</artifactId>\n <version>2.7.2</version>\n </dependency>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n</dependencies>\n"
},
{
"answer_id": 22555794,
"author": "Julian Dehne",
"author_id": 2195026,
"author_profile": "https://Stackoverflow.com/users/2195026",
"pm_score": 0,
"selected": false,
"text": " <properties>\n <maven.compiler.source>1.7</maven.compiler.source>\n <maven.compiler.target>1.7</maven.compiler.target>\n <!-- <encoding>UTF-8</encoding> -->\n <scala.tools.version>2.10</scala.tools.version>\n <scala.version>2.10.3</scala.version>\n </properties>\n<build>\n <sourceDirectory>src/main/scala</sourceDirectory>\n <testSourceDirectory>src/test/scala</testSourceDirectory>\n <plugins>\n <plugin>\n <groupId>org.scala-tools</groupId>\n <artifactId>maven-scala-plugin</artifactId>\n <version>2.15.2</version>\n <executions> \n <execution>\n <id>scala-compile-first</id>\n <phase>process-resources</phase>\n <goals>\n <goal>compile</goal>\n </goals>\n </execution>\n <execution>\n <id>scala-test-compile</id>\n <phase>process-test-resources</phase>\n <goals>\n <goal>testCompile</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n\n <plugin> \n <groupId>net.alchim31.maven</groupId>\n <artifactId>scala-maven-plugin</artifactId>\n <version>3.1.3</version>\n <executions>\n <execution>\n <goals>\n <goal>compile</goal>\n <goal>testCompile</goal>\n </goals>\n <configuration>\n <args>\n <arg>-make:transitive</arg>\n <arg>-dependencyfile</arg>\n <arg>${project.build.directory}/.scala_dependencies</arg>\n </args>\n </configuration>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>2.13</version>\n <configuration>\n <useFile>false</useFile>\n <disableXmlReport>true</disableXmlReport> \n <includes>\n <include>**/*Test.*</include>\n <include>**/*Suite.*</include>\n </includes>\n </configuration>\n </plugin> \n </plugins>\n </build>\n"
},
{
"answer_id": 23496597,
"author": "Mebin",
"author_id": 3258644,
"author_profile": "https://Stackoverflow.com/users/3258644",
"pm_score": 1,
"selected": false,
"text": " <build>\n <plugins>\n <plugin>\n <groupId>org.scala-tools</groupId>\n <artifactId>maven-scala-plugin</artifactId>\n <executions>\n <execution>\n <goals>\n <goal>compile</goal>\n <goal>testCompile</goal>\n </goals>\n </execution>\n </executions>\n <configuration>\n <sourceDir>src/main/scala</sourceDir>\n <jvmArgs>\n <jvmArg>-Xms64m</jvmArg>\n <jvmArg>-Xmx1024m</jvmArg>\n </jvmArgs>\n </configuration>\n </plugin>\n </plugins>\n</build>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699/"
] |
336,148 | <p>I've been told that the java class TreeMap uses an implementation of a RB tree. If this is the case, how does one do an inorder, preorder and postorder tree-walk on a TreeMap?</p>
<p>Or is this not possible?</p>
| [
{
"answer_id": 336164,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": true,
"text": "printTree() /**\n * Print all items.\n */\npublic void printTree( ) {\n printTree( header.right );\n}\n\n/**\n * Internal method to print a subtree in sorted order.\n * @param t the node that roots the tree.\n */\nprivate void printTree( RedBlackNode t ) {\n if( t != nullNode ) {\n printTree( t.left );\n System.out.println( t.element );\n printTree( t.right );\n }\n}\n"
},
{
"answer_id": 338815,
"author": "Rich",
"author_id": 42897,
"author_profile": "https://Stackoverflow.com/users/42897",
"pm_score": 2,
"selected": false,
"text": "void inOrderWalk(TreeMap<K,V> treeMap) {\n //this will loop through the values in the map in sorted order (inorder traversal)\n for (Map.Entry<K,V> entry : treeMap.entrySet() {\n V value = entry.getValue();\n K key = entry.getKey()\n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36545/"
] |
336,205 | <p>I tried to precompile my ASP.NET MVC application and deploy it to an IIS6 box (with wildcard mapping), however I am getting an error with rendering partial views (user controls). Its working fine on my dev machine before precompiling.</p>
<p>The error is:</p>
<blockquote>
<p>Server Error in '/' Application.<br />
<br />
The partial view 'ListGrid' could not<br />
be found. The following locations were<br />
searched:<br />
~/Views/Initiative/ListGrid.aspx<br />
~/Views/Initiative/ListGrid.ascx<br />
~/Views/Shared/ListGrid.aspx<br />
~/Views/Shared/ListGrid.ascx<br /></p>
</blockquote>
<p>I checked Views\Shared for the file and it was not there, which I thought was normal because its precompiled. But just for giggles I put a blank file in that folder names ListGrid.ascx, but then I got this error:</p>
<blockquote>
<p>Server Error in '/' Application.<br />
<br />
The file '/Views/Shared/ListGrid.ascx'<br />
has not been pre-compiled, and cannot<br />
be requested.</p>
</blockquote>
<p>I googled and searched SO but could not find any similar problems, but had no luck.</p>
| [
{
"answer_id": 4494229,
"author": "mgerety",
"author_id": 122007,
"author_profile": "https://Stackoverflow.com/users/122007",
"pm_score": 4,
"selected": false,
"text": "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\aspnet_compiler -p \"$(ProjectDir).\" -v /$(ProjectName)\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37786/"
] |
336,210 | <p>Is there a regular expression which checks if a string contains only upper and lowercase letters, numbers, and underscores?</p>
| [
{
"answer_id": 336214,
"author": "Drew Hall",
"author_id": 23934,
"author_profile": "https://Stackoverflow.com/users/23934",
"pm_score": 4,
"selected": false,
"text": "^([A-Za-z]|[0-9]|_)+$\n ^\\w+$\n"
},
{
"answer_id": 336215,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 5,
"selected": false,
"text": "^[A-Za-z0-9_]+$\n ^[A-Za-z0-9_]*$\n ^\\w+$\n ^\\w*$\n"
},
{
"answer_id": 336216,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 3,
"selected": false,
"text": "^[a-zA-Z0-9_]+$\n #!/usr/bin/perl -w\n\nmy $arg1 = $ARGV[0];\n\n# Check that the string contains *only* one or more alphanumeric chars or underscores\nif ($arg1 !~ /^[a-zA-Z0-9_]+$/) {\n print \"Failed.\\n\";\n} else {\n print \"Success.\\n\";\n}\n"
},
{
"answer_id": 336219,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 1,
"selected": false,
"text": "^[A-Za-z0-9_]+$\n"
},
{
"answer_id": 336220,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 10,
"selected": false,
"text": "\"^[a-zA-Z0-9_]*$\"\n ^ : start of string\n[ : beginning of character group\na-z : any lowercase letter\nA-Z : any uppercase letter\n0-9 : any digit\n_ : underscore\n] : end of character group\n* : zero or more of the given characters\n$ : end of string\n + * [a-zA-Z0-9_] \\w ^\\w*$ ^\\w+$ \\w"
},
{
"answer_id": 336236,
"author": "mson",
"author_id": 36902,
"author_profile": "https://Stackoverflow.com/users/36902",
"pm_score": 2,
"selected": false,
"text": "[^a-zA-Z0-9 _]{1,255}\n"
},
{
"answer_id": 336269,
"author": "Anton",
"author_id": 20526,
"author_profile": "https://Stackoverflow.com/users/20526",
"pm_score": 6,
"selected": false,
"text": "[A-Za-z0-9_]\n \\w\n ^\n $\n \\w+ or \\w*\n ^\\w*$\n"
},
{
"answer_id": 342977,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 9,
"selected": false,
"text": "/^\\w+$/\n \\w [A-Za-z0-9_] + *"
},
{
"answer_id": 3108665,
"author": "mylesmckeown",
"author_id": 375077,
"author_profile": "https://Stackoverflow.com/users/375077",
"pm_score": 2,
"selected": false,
"text": "^([a-zA-Z_]{1,}\\d{1,})+|(\\d{1,}[a-zA-Z_]{1,})+$\n"
},
{
"answer_id": 4167782,
"author": "boooloooo",
"author_id": 506116,
"author_profile": "https://Stackoverflow.com/users/506116",
"pm_score": 4,
"selected": false,
"text": "^(?=.*\\d)(?=.*[A-Za-z])[A-Za-z0-9]{1,10}$\n"
},
{
"answer_id": 8812762,
"author": "Shantanu",
"author_id": 1142094,
"author_profile": "https://Stackoverflow.com/users/1142094",
"pm_score": 3,
"selected": false,
"text": "public static bool IsAlphaNumeric(this string stringToTest)\n{\n // English\n const string charSet = \"a-zA-Z\";\n const string numSet = @\"0-9\";\n\n // Greek\n //const string charSet = @\"\\u0388-\\u03EF\";\n //const string numSet = @\"0-9\";\n\n // Bengali\n //const string charSet = @\"\\u0985-\\u09E3\";\n //const string numSet = @\"\\u09E6-\\u09EF\";\n\n // Hindi\n //const string charSet = @\"\\u0905-\\u0963\";\n //const string numSet = @\"\\u0966-\\u096F\";\n\n return Regex.Match(stringToTest, @\"^(?=[\" + numSet + @\"]*?[\" + charSet + @\"]+)(?=[\" + charSet + @\"]*?[\" + numSet + @\"]+)[\" + charSet + numSet +@\"]+$\").Success;\n}\n\npublic static bool IsNumeric(this string stringToTest)\n{\n //English\n const string numSet = @\"0-9\";\n\n //Hindi\n //const string numSet = @\"\\u0966-\\u096F\";\n\n return Regex.Match(stringToTest, @\"^[\" + numSet + @\"]+$\").Success;\n}\n\npublic static bool IsAlpha(this string stringToTest)\n{\n //English\n const string charSet = \"a-zA-Z\";\n\n return Regex.Match(stringToTest, @\"^[\" + charSet + @\"]+$\").Success;\n}\n // English\nstring test = \"AASD121asf\";\n\n// Greek\n//string test = \"Ϡϛβ123\";\n\n// Bengali\n//string test = \"শর৩৮\";\n\n// Hindi\n//string test = @\"क़लम३७ख़\";\n\nbool isAlphaNum = test.IsAlphaNumeric();\n"
},
{
"answer_id": 9080433,
"author": "Danuel O'Neal",
"author_id": 1180441,
"author_profile": "https://Stackoverflow.com/users/1180441",
"pm_score": 5,
"selected": false,
"text": "0-9 A-Z a-z _ $regex = '/^[A-Za-z_][A-Za-z\\d_]*$/'\n ^[A-Za-z_][A-Za-z\\d_]*$\n"
},
{
"answer_id": 9995942,
"author": "Agustin",
"author_id": 686460,
"author_profile": "https://Stackoverflow.com/users/686460",
"pm_score": 3,
"selected": false,
"text": "^[\\p{L} \\p{Nd}_]+$\n"
},
{
"answer_id": 10965166,
"author": "Day Davis Waterbury",
"author_id": 955159,
"author_profile": "https://Stackoverflow.com/users/955159",
"pm_score": 5,
"selected": false,
"text": "\\w ^[[:alnum:]_]+$\n \\w grep -P [:alnum:] \\w ^\\w+$\n"
},
{
"answer_id": 30350504,
"author": "Saurabh",
"author_id": 2078672,
"author_profile": "https://Stackoverflow.com/users/2078672",
"pm_score": 1,
"selected": false,
"text": "[\\\\p{Alnum}_]\n"
},
{
"answer_id": 47289942,
"author": "Mukund Thakkar",
"author_id": 874524,
"author_profile": "https://Stackoverflow.com/users/874524",
"pm_score": 2,
"selected": false,
"text": "^\\w*$ 1\n123\n1av\npRo\nav1\n"
},
{
"answer_id": 54594157,
"author": "Marcio Martins",
"author_id": 1720622,
"author_profile": "https://Stackoverflow.com/users/1720622",
"pm_score": 2,
"selected": false,
"text": "^[A-ZÀ-Ýa-zà-ý0-9_]+$\n"
},
{
"answer_id": 59464503,
"author": "Chinmaya Pati",
"author_id": 5790355,
"author_profile": "https://Stackoverflow.com/users/5790355",
"pm_score": 3,
"selected": false,
"text": "/^[\\d]*[a-z_][a-z\\d_]*$/gi abcd True\nabcd12 True\nab12cd True\n12abcd True\n\n1234 False\n ^ ... $ [\\d]* [a-z_] [a-z\\d_]* /gi"
},
{
"answer_id": 62263317,
"author": "MiKr13",
"author_id": 9360885,
"author_profile": "https://Stackoverflow.com/users/9360885",
"pm_score": 4,
"selected": false,
"text": "/^\\w+$/\n const regex = /^\\w+$/;\nconst str = `nut_cracker_12`;\nlet m;\n\nif ((m = regex.exec(str)) !== null) {\n // The result can be accessed through the `m`-variable.\n m.forEach((match, groupIndex) => {\n console.log(`Found match, group ${groupIndex}: ${match}`);\n });\n}"
},
{
"answer_id": 64333720,
"author": "uma mahesh",
"author_id": 13039638,
"author_profile": "https://Stackoverflow.com/users/13039638",
"pm_score": -1,
"selected": false,
"text": "validatePnrAndTicketNumber(){\n let alphaNumericRegex=/^[a-zA-Z0-9]*$/;\n let numericRegex=/^[0-9]*$/;\n let numericdashRegex=/^(([1-9]{3})\\-?([0-9]{10}))$/;\n this.currBookingRefValue = this.requestForm.controls[\"bookingReference\"].value;\n if(this.currBookingRefValue.length == 14 && this.currBookingRefValue.match(numericdashRegex)){\n this.requestForm.controls[\"bookingReference\"].setErrors({'pattern': false});\n }else if(this.currBookingRefValue.length ==6 && this.currBookingRefValue.match(alphaNumericRegex)){\n this.requestForm.controls[\"bookingReference\"].setErrors({'pattern': false});\n }else if(this.currBookingRefValue.length ==13 && this.currBookingRefValue.match(numericRegex) ){\n this.requestForm.controls[\"bookingReference\"].setErrors({'pattern': false});\n }else{\n this.requestForm.controls[\"bookingReference\"].setErrors({'pattern': true});\n }\n}\n <input name=\"booking_reference\" type=\"text\" [class.input-not-empty]=\"bookingRef.value\"\n class=\"glyph-input form-control floating-label-input\" id=\"bookings_bookingReference\"\n value=\"\" maxlength=\"14\" aria-required=\"true\" role=\"textbox\" #bookingRef\n formControlName=\"bookingReference\" (focus)=\"resetMessageField()\" (blur)=\"validatePnrAndTicketNumber()\"/>\n"
},
{
"answer_id": 66505741,
"author": "Sharad",
"author_id": 6551863,
"author_profile": "https://Stackoverflow.com/users/6551863",
"pm_score": 2,
"selected": false,
"text": " public class RegExTest {\n public static void main(String[] args) {\n System.out.println(\"_C#\".matches(\"^[a-zA-Z0-9_]+$\"));\n }\n }\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,226 | <p>Stupid questions but cant get my head around it...
I have a string in this format 20081119</p>
<p>And I have a C# method that converts the string to a DateTime to be entered into a SQL Server DB </p>
<pre><code>public static DateTime MyDateConversion(string dateAsString)
{
return System.DateTime.ParseExact(dateAsString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
}
</code></pre>
<p>The problem is that the Date is coming out like this: Date = 19/11/2008 12:00:00 AM and I need it to be a DateTime of type yyyyMMdd as I am mapping it into a schema to call a stored proc.</p>
<p>Thanks in advance guys.</p>
<p>Cheers,
Con</p>
| [
{
"answer_id": 336249,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "DbParameter param = cmd.CreateParameter();\nparam.ParameterName = \"@foo\";\nparam.DbType = DbType.DateTime;\nparam.Value = yourDateTime; // the DateTime returned from .ParseExact\ncmd.Parameters.Add(param);\n SqlCommand cmd.Parameters.Add(\"@foo\", SqlDbType.DateTime).Value = yourDateTime;\n DateTime yourDateTime =\n DateTime.ParseExact(dateString, \"yyyyMMdd\", CultureInfo.InvariantCulture);\n string dateString = yourDateTime.ToString(\"yyyyMMdd\", CultureInfo.InvariantCulture);\n"
},
{
"answer_id": 336253,
"author": "Andrew Van Slaars",
"author_id": 8087,
"author_profile": "https://Stackoverflow.com/users/8087",
"pm_score": 0,
"selected": false,
"text": "var dateString = \"20081119\";\nvar enUS = new System.Globalization.CultureInfo(\"en-US\");\nvar resultingDate = DateTime.ParseExact(dateString,\"yyyyMMdd\",enUS);\nConsole.WriteLine(resultingDate.ToString());\n"
},
{
"answer_id": 337777,
"author": "Andrew Van Slaars",
"author_id": 8087,
"author_profile": "https://Stackoverflow.com/users/8087",
"pm_score": 1,
"selected": false,
"text": "var dateString = \"20081119\";\nvar fr = new System.Globalization.CultureInfo(\"fr-FR\");\nvar resultingDate =DateTime.ParseExact(dateString,\"yyyyMMdd\",System.Globalization.CultureInfo.CurrentCulture);\nConsole.WriteLine(resultingDate.ToString(fr));\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,235 | <p>I have installed VS 2008 SP1 on W2k3 OS. After I installed ASP.NET MVC beta and tried creating ASP.NET MVC type project I get the following error.</p>
<p>"the project type is not supported by this installation"</p>
<p>Let me know if you have fixed this issue.</p>
| [
{
"answer_id": 696120,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": false,
"text": "devenv /setup\n"
},
{
"answer_id": 1573448,
"author": "Vivek Ayer",
"author_id": 128263,
"author_profile": "https://Stackoverflow.com/users/128263",
"pm_score": 6,
"selected": false,
"text": "<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>"
},
{
"answer_id": 4646558,
"author": "shrilata Ellaboina",
"author_id": 569797,
"author_profile": "https://Stackoverflow.com/users/569797",
"pm_score": 1,
"selected": false,
"text": "AspNetMVC1.msi"
},
{
"answer_id": 6768568,
"author": "Travis",
"author_id": 845014,
"author_profile": "https://Stackoverflow.com/users/845014",
"pm_score": 1,
"selected": false,
"text": "devenv /setup\n devenv.exe /resetskippkgs\n"
},
{
"answer_id": 15655519,
"author": "Brian",
"author_id": 1794167,
"author_profile": "https://Stackoverflow.com/users/1794167",
"pm_score": 0,
"selected": false,
"text": "<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26788/"
] |
336,240 | <p>I am using Zend Framework(MVC part of it), and need to either redirect user to SSL enabled page or to force SSL from controller somehow and don't quite see how to do that? Maybe someone can share the knowledge? </p>
<p>Thanks!</p>
| [
{
"answer_id": 336261,
"author": "Matt Howell",
"author_id": 2321,
"author_profile": "https://Stackoverflow.com/users/2321",
"pm_score": 3,
"selected": false,
"text": "RewriteEngine On\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35520/"
] |
336,250 | <p>EDIT: I've tagged this C in a hope to get more response. It's more the theory I'm interested in than a specific language implementation. So if you're a C coder please treat the following PHP as pseudo-code and feel free to respond with an answer written in C.</p>
<p>I am trying to speed up a PHP CLI script by having it execute its tasks in parallel instead of serial. The tasks are completely independent of each other so it doesn't matter which order they start/finish in.</p>
<p>Here's the original script (note all these examples are stripped-back for clarity):</p>
<pre><code><?php
$items = range(0, 100);
function do_stuff_with($item) { echo "$item\n"; }
foreach ($items as $item) {
do_stuff_with($item);
}
</code></pre>
<p>I've managed to make it work on the <code>$items</code> in parallel with <a href="http://php.net/pcntl_fork" rel="nofollow noreferrer"><code>pcntl_fork()</code></a> as shown below:</p>
<pre><code><?php
ini_set('max_execution_time', 0);
ini_set('max_input_time', 0);
set_time_limit(0);
$items = range(0, 100);
function do_stuff_with($item) { echo "$item\n"; }
$pids = array();
foreach ($items as $item) {
$pid = pcntl_fork();
if ($pid == -1) {
die("couldn't fork()");
} elseif ($pid > 0) {
// parent
$pids[] = $pid;
} else {
// child
do_stuff_with($item);
exit(0);
}
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
</code></pre>
<p>Now I want to extend this so there's a maximum of, say, 10 children active at once. What's the best way of handling this? I've tried a few things but haven't had much luck.</p>
| [
{
"answer_id": 336330,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "socket_select() $my_process_index = 0;\n$pids = array();\n\n// Fork off $max_procs processes\nfor($i = 0; $i < $max_procs - 1; $i++)\n{\n $pid = pcntl_fork();\n if($pid == -1)\n {\n die(\"couldn't fork()\");\n }\n elseif($pid > 0)\n {\n // parent\n $my_process_index++;\n $pids[] = $pid\n }\n else\n {\n // child\n break;\n }\n}\n\n// $my_process_index is now an integer in the range [0, $max_procs), unique among all the processes\n// Each process will now process 1/$max_procs of the items\nfor($i = $my_process_index; $i < length($items); $i += $max_procs)\n{\n do_stuff_with($items[$i]);\n}\n\nif($my_process_index != 0)\n{\n exit(0);\n}\n"
},
{
"answer_id": 336471,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 3,
"selected": true,
"text": "ps --ppid ps fork() SIGCHLD ppid"
},
{
"answer_id": 71543900,
"author": "Gh Gh",
"author_id": 16471600,
"author_profile": "https://Stackoverflow.com/users/16471600",
"pm_score": 0,
"selected": false,
"text": "<?php\n\nini_set('max_execution_time', 0); \nini_set('max_input_time', 0); \nset_time_limit(0);\n\n$items = range(0, 100);\n\nfunction do_stuff_with($item) { echo \"$item\\n\"; }\n\n$pids = array();\nwhile (count($items)){\n $item = array_pop($items);\n $pid = pcntl_fork();\n if ($pid == -1) {\n die(\"couldn't fork()\");\n } elseif ($pid > 0) {\n // parent\n $pids[] = $pid;\n } else {\n // child\n do_stuff_with($item);\n exit(0);\n }\n\n while (count($pids) >= 10){ // limit\n while (($wait_pid = pcntl_waitpid(0, $status)) != -1) {\n $status = pcntl_wexitstatus($status);\n array_pop($pids);\n echo \"$wait_pid $status\".PHP_EOL;\n break;\n }\n }\n}\n\nwhile (count($pids)){\n while (($wait_pid = pcntl_waitpid(0, $status)) != -1) {\n $status = pcntl_wexitstatus($status);\n array_pop($pids);\n echo \"CHILD: child $status completed $wait_pid\".PHP_EOL;\n break;\n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,268 | <p>I thought these were synonomous, but I wrote the following in Microsoft SQL:</p>
<pre><code>Select Unique col from
(select col from table1 union select col from table2) alias
</code></pre>
<p>And it failed. Changing it to </p>
<pre><code>Select Distinct col from
(select col from table1 union select col from table2) alias
</code></pre>
<p>fixed it. Can someone explain?</p>
| [
{
"answer_id": 336273,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 7,
"selected": false,
"text": "Create Table Employee( \n Emp_PKey Int Identity(1, 1) Constraint PK_Employee_Emp_PKey Primary Key, \n Emp_SSN Numeric Not Null Unique, \n Emp_FName varchar(16), \n Emp_LName varchar(16) \n)\n Select Distinct Emp_LName\nFrom Employee\n"
},
{
"answer_id": 336282,
"author": "mson",
"author_id": 36902,
"author_profile": "https://Stackoverflow.com/users/36902",
"pm_score": 4,
"selected": false,
"text": "select col from table1 \nunion \nselect col from table2\n select col from table1 \nunion all\nselect col from table2\n"
},
{
"answer_id": 336455,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 7,
"selected": false,
"text": "SELECT UNIQUE SELECT DISTINCT SELECT DISTINCT SELECT UNIQUE SELECT UNIQUE"
},
{
"answer_id": 46234166,
"author": "Somnath Muluk",
"author_id": 1045444,
"author_profile": "https://Stackoverflow.com/users/1045444",
"pm_score": 3,
"selected": false,
"text": "SELECT DISTINCT SELECT UNIQUE SELECT UNIQUE UNIQUE"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42712/"
] |
336,288 | <p>Presently I'm starting to introduce the concept of Mock objects into my Unit Tests. In particular I'm using the Moq framework. However, one of the things I've noticed is that suddenly the classes I'm testing using this framework are showing code coverage of 0%.</p>
<p>Now I understand that since I'm just mocking the class, its not running the actual class itself....but how do I write these tests and have Code Coverage return accurate results? Do I have to write one set of tests that use Mocks and one set to instantiate the class directly.</p>
<p>Perhaps I am doing something wrong without realizing it?</p>
<p>Here is an example of me trying to Unit Test a class called "MyClass":</p>
<pre><code>using Moq;
using NUnitFramework;
namespace MyNameSpace
{
[TestFixture]
public class MyClassTests
{
[Test]
public void TestGetSomeString()
{
const string EXPECTED_STRING = "Some String!";
Mock<MyClass> myMock = new Mock<MyClass>();
myMock.Expect(m => m.GetSomeString()).Returns(EXPECTED_STRING);
string someString = myMock.Object.GetSomeString();
Assert.AreEqual(EXPECTED_STRING, someString);
myMock.VerifyAll();
}
}
public class MyClass
{
public virtual string GetSomeString()
{
return "Hello World!";
}
}
}
</code></pre>
<p>Does anyone know what I should be doing differently?</p>
| [
{
"answer_id": 336314,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 5,
"selected": true,
"text": "using Moq;\nusing NUnitFramework;\n\nnamespace MyNameSpace\n {\n [TestFixture]\n public class MyClassTests\n {\n\n [Test]\n public void TestGetSomeString()\n {\n const string EXPECTED_STRING = \"Some String!\";\n\n Mock<IDependance> myMock = new Mock<IDependance>();\n myMock.Expect(m => m.GiveMeAString()).Returns(\"Hello World\");\n\n MyClass myobject = new MyClass();\n\n string someString = myobject.GetSomeString(myMock.Object);\n\n Assert.AreEqual(EXPECTED_STRING, someString);\n myMock.VerifyAll();\n\n }\n\n }\n\n public class MyClass\n {\n\n public virtual string GetSomeString(IDependance objectThatITalkTo)\n {\n return objectThatITalkTo.GiveMeAString();\n }\n }\n\n public interface IDependance\n {\n string GiveMeAString();\n }\n }\n GetSomeString() IDependdance GiveMeAString() IDependdance public virtual string GetSomeString(IDependance objectThatITalkTo)\n {\n if (objectThatITalkTo.GiveMeAString() == \"Hello World\")\n return \"Hi\";\n return null;\n }\n myMock.Expect(m => m.GiveMeAString()).Returns(null);\n GetSomeString()"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39532/"
] |
336,289 | <p>In vc++ i am using MScomm for serial communication,
i received data in this format 02120812550006050.0,
i am not gettng how to read this ,in which format it is,
begning starting frame and at the end ending file, remaing i dont know.</p>
<p>EDIT 1:</p>
<p>it contains date time and data how i can seperate this one</p>
| [
{
"answer_id": 336323,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "static void extract (char *buff, char *date, char *time, float *val) {\n // format is \"\\x01\\x0fDDMMYYhhmmss\\x02vvvvvvv\\x03\\x04\"\n char temp[8];\n memcpy (date, buff + 2, 6); date[6] = '\\0';\n memcpy (time, buff + 8, 6); time[6] = '\\0';\n memcpy (temp, buff + 15, 7); temp[7] = '\\0';\n *val = atof (temp);\n}\n char buff[26]; // must be pre-filled before calling extract()\nchar dt[8];\nchar tm[8];\nfloat val;\nextract (buffer, dt, tm, &val);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,303 | <p>I'm writing a <a href="http://en.wikipedia.org/wiki/VoiceXML" rel="nofollow noreferrer">VoiceXML</a> application where we have a speech grammar and a <a href="http://en.wikipedia.org/wiki/DTMF" rel="nofollow noreferrer">DTMF</a> grammar. If the caller is calling from a particularly noisy environment, we need to disable the speech grammar. Is there a way to do this which doesn't involve copying the entire form into another form and deleting the speech grammar?</p>
| [
{
"answer_id": 435869,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 3,
"selected": false,
"text": "inputmodes <property name=\"inputmodes\" value=\"dtmf\"/>\n"
},
{
"answer_id": 5870264,
"author": "Neel",
"author_id": 180551,
"author_profile": "https://Stackoverflow.com/users/180551",
"pm_score": 0,
"selected": false,
"text": "<grammar type=\"application/srgs+xml\" src=\"/grammars/menu.grxml\" />\n<grammar type=\"application/srgs+xml\" src=\"/grammars/menu-dtmf.grxml\" />\n <grammar type=\"application/srgs+xml\" srcexpr=\"'/grammars/menu' + (dtmfMode?'-dtmf':'') + '.grxml'\" />\n<grammar type=\"application/srgs+xml\" src=\"/grammars/menu-dtmf.grxml\" />\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,309 | <p>I have a MySQL database that I want to <em>archive</em>. What is the best way to do this?</p>
<p>Note: I <em>don't</em> want to just do a <em>backup</em>. I want to do a one time export of the data for long term storage in a way that I can get at on a later date. Particularly, I want to not be tied to MySQL, a database or preferably any given software (I'd really like it to be trivial to wright a program that can read it back in, something like a few dozen lines of C or perl).</p>
<p>My current plan is to dump stuff to a table using the CSV engine and then burn that to DVD. The is nice because CSV can be loaded by so many different programs. The only gotcha in this is that the bulk of the data is in Blob columns as in binary so I'll need to decode how that is encoded.</p>
| [
{
"answer_id": 26879956,
"author": "zloctb",
"author_id": 1673376,
"author_profile": "https://Stackoverflow.com/users/1673376",
"pm_score": 0,
"selected": false,
"text": "mysql> ALTER TABLE arch2 ENGINE='ARCHIVE';\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
336,311 | <p>I am building a web application which uses an externally built class to handle much of the work and rules for the site. Most pages will require access to this class to get the information it needs to display. In the past I would put such a class in a session variable, so it's easily accessible when required and not need to be continually re-instantiated. </p>
<p>First Question, is this a bad idea to stuff this class into a session variable (it's not very big)?</p>
<p>Second question, if it's not a bad idea to store the sites app layer class in a session, then is there a way I can write a centralized method to use to grab or store the class into the session? I don't want to use a bunch of repeated code page after page getting the class, checking its there, creating if it's not, etc.</p>
| [
{
"answer_id": 414908,
"author": "Brettski",
"author_id": 5836,
"author_profile": "https://Stackoverflow.com/users/5836",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Configuration;\n\nnamespace BDZipper.Site\n{\n /// <summary>\n /// This class maintains all session variables for us instead of handeling them \n /// individually in the session. They are also strongly typed.\n /// </summary>\n public static class SessionManager\n {\n\n # region Private Constants\n // Define string constant for each property. We use the constant to call the session variable\n // easier not to make mistakes this way.\n // I think for simplicity, we will use the same key string in the web.config AppSettings as\n // we do for the session variable. This way we can use the same constant for both!\n private const string startDirectory = \"StartDirectory\";\n private const string currentDirectory = \"CurrentDirectory\";\n\n # endregion\n\n /// <summary>\n /// The starting directory for the application\n /// </summary>\n public static string StartDirectory\n {\n get\n {\n return GetSessionValue(startDirectory, true);\n }\n //set\n //{\n // HttpContext.Current.Session[startDirectory] = value;\n //}\n }\n\n public static string CurrentDirectory\n {\n get\n {\n return GetSessionValue(currentDirectory, false);\n }\n set\n {\n HttpContext.Current.Session[currentDirectory] = value;\n }\n }\n //TODO: Update to use any class or type\n /// <summary>\n /// Handles routine of getting values out of session and or AppSettings\n /// </summary>\n /// <param name=\"SessionVar\"></param>\n /// <param name=\"IsAppSetting\"></param>\n /// <returns></returns>\n private static string GetSessionValue(string SessionVar, bool IsAppSetting)\n {\n if (null != HttpContext.Current.Session[SessionVar])\n return (string)HttpContext.Current.Session[SessionVar];\n else if (IsAppSetting) // Session null with appSetting value\n return ConfigurationManager.AppSettings[SessionVar];\n else\n return \"\";\n }\n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5836/"
] |
336,327 | <p>I am trying to build a CAML query for SharePoint 2007 environment, to get items from a calendar list. Want to query items with a given 'From date' and 'To date', the calendar list contains 'EventDate' and 'EndDate' in Datetime format. I am only interested in the date part of the datetime field.</p>
<p>How can I trim the "EventDate" DateTime field of Calendar list to just Date and compare?</p>
<p>Is there any other way to get this done apart from CAML.</p>
| [
{
"answer_id": 336406,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<Where>\n <Gt>\n <FieldRef Name='EventDate' />\n <Value IncludeTimeValue='FALSE' Type='DateTime'>2008-12-03T12:00:00Z</Value>\n </Gt>\n</Where>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35366/"
] |
336,333 | <p>Is there a way to use add-as-link when dragging and dropping source files or entire source trees into a C# project?</p>
<p>Currently, dragging a tree of source files onto a C# project will cause Visual Studio to copy all files to mirror tree below my solution file.</p>
<p>This can be avoided with the the add-as-link option as depicted in the picture below. However, it gets tedious for large trees or when some files in a directory are already part of the project.</p>
<p>
<a href="http://jaapsuter.com/images/add_cs_file.jpg" rel="nofollow noreferrer">Screenshot of the add-as-link functionality in Visual Studio http://jaapsuter.com/images/add_cs_file.jpg</a>
</p>
<p>I've looked in Tools->Options, searched the web, and held various magic key combinations when dragging and dropping, to no avail.</p>
<p>I'm tempted to write a script that just globs my .cs files and runs a regular expression over my .csproj file. I'm aware of NAnt, Premake, and other solutions - but I'd like something lightweight.</p>
| [
{
"answer_id": 533773,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 2,
"selected": true,
"text": "<ItemGroup>\n <Compile Include=\"SomeDirectory\\**\\*.cs\"/>\n</ItemGroup>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27234/"
] |
336,348 | <p>I've got a web page that's using jquery to receive some product information as people are looking at things and then displays the last product images that were seen. This is in a jquery AJAX callback that looks pretty much like this:</p>
<pre><code>if(number_of_things_seen > 10) {
$('#shots li:last-child').remove();
}
$('<li><img src="' + p.ProductImageSmall + '"></li>').prependTo('#shots');
</code></pre>
<p>However, it seems to leak quite a bit of memory. Visually, it does the right thing, but the footprint grows indefinitely.</p>
<p>Safari's DOM inspector shows the DOM is how I would expect it to be, but it seems to maintain references to every image that it has displayed (as seen in <a href="http://skitch.com/dlsspy/7m5k/img-leaks" rel="nofollow noreferrer">this screenshot</a> in case anyone is interested).</p>
<p>I've added</p>
<pre><code>$('#shots li:last-child img').remove();
</code></pre>
<p>to the removal statement to no noticable effect.</p>
<p>Is there some magic necessary to let the browser release some of this stuff?</p>
| [
{
"answer_id": 336374,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 1,
"selected": false,
"text": "//not tested\n\nvar $list=$('#shots>li');\n$list.filter(':last-child').children('img')\n.attr('src', p.ProductImageSmall)\n.parent()\n.insertBefore( $list.eq(0) );\n"
},
{
"answer_id": 336513,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "removeChild() // I'm sure there is a nicer way to do it in jQuery\nif(number_of_things_seen > 10) {\n var shots = document.getElementById(\"shots\");\n var li = shots.getElementsByTagName(\"LI\");\n var move = shots.removeChild(li[li.length-1]);\n move.getElementsByTagName(\"IMG\")[0].src = p.ProductImageSmall;\n shots.insertBefore(move, li[0]);\n}\n"
},
{
"answer_id": 854624,
"author": "Rob Colburn",
"author_id": 105677,
"author_profile": "https://Stackoverflow.com/users/105677",
"pm_score": 2,
"selected": false,
"text": "window.setTimeout(\"location.reload()\",1000*60*60);//refresh in an hour\n"
},
{
"answer_id": 21600890,
"author": "Willem M.",
"author_id": 2635303,
"author_profile": "https://Stackoverflow.com/users/2635303",
"pm_score": 0,
"selected": false,
"text": "if(number_of_things_seen > 10) {\n $('#shots li:last-child').remove();\n}\n\n$('<li><div style=\"background-image: url(\\'' + p.ProductImageSmall +\n '\\'); background-repeat: no-repeat; background-position: center; '+\n ' width: 20px; height: 20px\"></div></li>').prependTo('#shots');\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39975/"
] |
336,387 | <p>i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.</p>
<p>this is the code:</p>
<pre><code>[TestMethod]
public void TestMethod1()
{
// Grab the binary data.
byte[] data = File.ReadAllBytes("Chick.jpg");
// Read in the data but do not close, before using the stream.
Stream originalBinaryDataStream = new MemoryStream(data);
Bitmap image = new Bitmap(originalBinaryDataStream);
image.Save(@"c:\test.jpg");
originalBinaryDataStream.Dispose();
// Now lets use a nice dispose, etc...
Bitmap2 image2;
using (Stream originalBinaryDataStream2 = new MemoryStream(data))
{
image2 = new Bitmap(originalBinaryDataStream2);
}
image2.Save(@"C:\temp\pewpew.jpg"); // This throws the GDI+ exception.
}
</code></pre>
<p>Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).</p>
<p>I'm really confused :(</p>
| [
{
"answer_id": 2555670,
"author": "Brian Low",
"author_id": 46039,
"author_profile": "https://Stackoverflow.com/users/46039",
"pm_score": 2,
"selected": false,
"text": " public static Image ToImage(this byte[] bytes)\n {\n using (var stream = new MemoryStream(bytes))\n using (var image = Image.FromStream(stream, false, true))\n {\n return new Bitmap(image);\n }\n }\n\n [Test]\n public void ShouldCreateImageThatCanBeSavedWithoutOpenStream()\n {\n var imageBytes = File.ReadAllBytes(\"bitmap.bmp\");\n\n var image = imageBytes.ToImage();\n\n image.Save(\"output.bmp\");\n }\n"
},
{
"answer_id": 20069667,
"author": "Yuri Perekupko",
"author_id": 932825,
"author_profile": "https://Stackoverflow.com/users/932825",
"pm_score": 2,
"selected": false,
"text": "using (var memoryStream = new MemoryStream())\n{\n // write to memory stream here\n\n memoryStream.Position = 0;\n using (var bitmap = new Bitmap(memoryStream))\n {\n var bitmap2 = new Bitmap(bitmap);\n return bitmap2;\n }\n}\n"
},
{
"answer_id": 43050571,
"author": "Ali Ezzat Odeh",
"author_id": 5462775,
"author_profile": "https://Stackoverflow.com/users/5462775",
"pm_score": 0,
"selected": false,
"text": "C:\\Program Files (x86)\\some_directory .exe"
},
{
"answer_id": 47941559,
"author": "mortb",
"author_id": 1257728,
"author_profile": "https://Stackoverflow.com/users/1257728",
"pm_score": 0,
"selected": false,
"text": "A generic error occurred in GDI+ MemoryStream private static string GetThumbnailImageAsBase64String(string path)\n {\n if (path == null || !File.Exists(path))\n {\n var log = ContainerResolver.Container.GetInstance<ILog>();\n log.Info($\"No file was found at path: {path}\");\n return null;\n }\n\n var width = LibraryItemFileSettings.Instance.ThumbnailImageWidth;\n\n using (var image = Image.FromFile(path))\n {\n using (var thumbnail = image.GetThumbnailImage(width, width * image.Height / image.Width, null, IntPtr.Zero))\n {\n using (var memoryStream = new MemoryStream())\n {\n thumbnail.Save(memoryStream, ImageFormat.Png); // <= crash here \n var bytes = new byte[memoryStream.Length];\n memoryStream.Position = 0;\n memoryStream.Read(bytes, 0, bytes.Length);\n return Convert.ToBase64String(bytes, 0, bytes.Length);\n }\n }\n }\n }\n"
},
{
"answer_id": 49316080,
"author": "mkb",
"author_id": 1538014,
"author_profile": "https://Stackoverflow.com/users/1538014",
"pm_score": 0,
"selected": false,
"text": "CacheOption BitmapCacheOption.OnLoad Image1 Image Image1.Source = new BitmapImage(new Uri(filepath));\n var image = new BitmapImage();\nimage.BeginInit();\nimage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;\nimage.CacheOption = BitmapCacheOption.OnLoad;\nimage.UriSource = new Uri(filepath);\nimage.EndInit();\nImage1.Source = image;\n"
},
{
"answer_id": 51598396,
"author": "BogdanRB",
"author_id": 1295946,
"author_profile": "https://Stackoverflow.com/users/1295946",
"pm_score": 0,
"selected": false,
"text": "static void Main(string[] args)\n{\n byte[] data = null;\n string fullPath = @\"c:\\testimage.jpg\";\n\n using (MemoryStream ms = new MemoryStream())\n using (Bitmap tmp = (Bitmap)Bitmap.FromFile(fullPath))\n using (Bitmap bm = new Bitmap(tmp))\n {\n bm.SetResolution(96, 96);\n using (EncoderParameters eps = new EncoderParameters(1))\n { \n eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);\n bm.Save(ms, GetEncoderInfo(\"image/jpeg\"), eps);\n }\n\n data = ms.ToArray();\n }\n\n File.WriteAllBytes(fullPath, data);\n}\n\nprivate static ImageCodecInfo GetEncoderInfo(string mimeType)\n{\n ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();\n\n for (int j = 0; j < encoders.Length; ++j)\n {\n if (String.Equals(encoders[j].MimeType, mimeType, StringComparison.InvariantCultureIgnoreCase))\n return encoders[j];\n }\n return null;\n}\n"
},
{
"answer_id": 66740270,
"author": "Kong SiengPirot",
"author_id": 15448632,
"author_profile": "https://Stackoverflow.com/users/15448632",
"pm_score": 0,
"selected": false,
"text": "public static byte[] SetImageToByte(Image img)\n {\n ImageConverter converter = new ImageConverter();\n return (byte[])converter.ConvertTo(img, typeof(byte[]));\n }\npublic static Bitmap SetByteToImage(byte[] blob)\n {\n MemoryStream mStream = new MemoryStream();\n byte[] pData = blob;\n mStream.Write(pData, 0, Convert.ToInt32(pData.Length));\n Bitmap bm = new Bitmap(mStream, false);\n mStream.Dispose();\n return bm;\n }\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
336,391 | <p>Javascripts are in <code>script.js</code> file which I have called in the xhtml file.</p>
<p>But it is throwing error at line where I have calling <code>onpageload</code> function saying " object expected.</p>
<p>However, if I have the scripts on same XHTML file, it is working fine.</p>
| [
{
"answer_id": 2555670,
"author": "Brian Low",
"author_id": 46039,
"author_profile": "https://Stackoverflow.com/users/46039",
"pm_score": 2,
"selected": false,
"text": " public static Image ToImage(this byte[] bytes)\n {\n using (var stream = new MemoryStream(bytes))\n using (var image = Image.FromStream(stream, false, true))\n {\n return new Bitmap(image);\n }\n }\n\n [Test]\n public void ShouldCreateImageThatCanBeSavedWithoutOpenStream()\n {\n var imageBytes = File.ReadAllBytes(\"bitmap.bmp\");\n\n var image = imageBytes.ToImage();\n\n image.Save(\"output.bmp\");\n }\n"
},
{
"answer_id": 20069667,
"author": "Yuri Perekupko",
"author_id": 932825,
"author_profile": "https://Stackoverflow.com/users/932825",
"pm_score": 2,
"selected": false,
"text": "using (var memoryStream = new MemoryStream())\n{\n // write to memory stream here\n\n memoryStream.Position = 0;\n using (var bitmap = new Bitmap(memoryStream))\n {\n var bitmap2 = new Bitmap(bitmap);\n return bitmap2;\n }\n}\n"
},
{
"answer_id": 43050571,
"author": "Ali Ezzat Odeh",
"author_id": 5462775,
"author_profile": "https://Stackoverflow.com/users/5462775",
"pm_score": 0,
"selected": false,
"text": "C:\\Program Files (x86)\\some_directory .exe"
},
{
"answer_id": 47941559,
"author": "mortb",
"author_id": 1257728,
"author_profile": "https://Stackoverflow.com/users/1257728",
"pm_score": 0,
"selected": false,
"text": "A generic error occurred in GDI+ MemoryStream private static string GetThumbnailImageAsBase64String(string path)\n {\n if (path == null || !File.Exists(path))\n {\n var log = ContainerResolver.Container.GetInstance<ILog>();\n log.Info($\"No file was found at path: {path}\");\n return null;\n }\n\n var width = LibraryItemFileSettings.Instance.ThumbnailImageWidth;\n\n using (var image = Image.FromFile(path))\n {\n using (var thumbnail = image.GetThumbnailImage(width, width * image.Height / image.Width, null, IntPtr.Zero))\n {\n using (var memoryStream = new MemoryStream())\n {\n thumbnail.Save(memoryStream, ImageFormat.Png); // <= crash here \n var bytes = new byte[memoryStream.Length];\n memoryStream.Position = 0;\n memoryStream.Read(bytes, 0, bytes.Length);\n return Convert.ToBase64String(bytes, 0, bytes.Length);\n }\n }\n }\n }\n"
},
{
"answer_id": 49316080,
"author": "mkb",
"author_id": 1538014,
"author_profile": "https://Stackoverflow.com/users/1538014",
"pm_score": 0,
"selected": false,
"text": "CacheOption BitmapCacheOption.OnLoad Image1 Image Image1.Source = new BitmapImage(new Uri(filepath));\n var image = new BitmapImage();\nimage.BeginInit();\nimage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;\nimage.CacheOption = BitmapCacheOption.OnLoad;\nimage.UriSource = new Uri(filepath);\nimage.EndInit();\nImage1.Source = image;\n"
},
{
"answer_id": 51598396,
"author": "BogdanRB",
"author_id": 1295946,
"author_profile": "https://Stackoverflow.com/users/1295946",
"pm_score": 0,
"selected": false,
"text": "static void Main(string[] args)\n{\n byte[] data = null;\n string fullPath = @\"c:\\testimage.jpg\";\n\n using (MemoryStream ms = new MemoryStream())\n using (Bitmap tmp = (Bitmap)Bitmap.FromFile(fullPath))\n using (Bitmap bm = new Bitmap(tmp))\n {\n bm.SetResolution(96, 96);\n using (EncoderParameters eps = new EncoderParameters(1))\n { \n eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);\n bm.Save(ms, GetEncoderInfo(\"image/jpeg\"), eps);\n }\n\n data = ms.ToArray();\n }\n\n File.WriteAllBytes(fullPath, data);\n}\n\nprivate static ImageCodecInfo GetEncoderInfo(string mimeType)\n{\n ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();\n\n for (int j = 0; j < encoders.Length; ++j)\n {\n if (String.Equals(encoders[j].MimeType, mimeType, StringComparison.InvariantCultureIgnoreCase))\n return encoders[j];\n }\n return null;\n}\n"
},
{
"answer_id": 66740270,
"author": "Kong SiengPirot",
"author_id": 15448632,
"author_profile": "https://Stackoverflow.com/users/15448632",
"pm_score": 0,
"selected": false,
"text": "public static byte[] SetImageToByte(Image img)\n {\n ImageConverter converter = new ImageConverter();\n return (byte[])converter.ConvertTo(img, typeof(byte[]));\n }\npublic static Bitmap SetByteToImage(byte[] blob)\n {\n MemoryStream mStream = new MemoryStream();\n byte[] pData = blob;\n mStream.Write(pData, 0, Convert.ToInt32(pData.Length));\n Bitmap bm = new Bitmap(mStream, false);\n mStream.Dispose();\n return bm;\n }\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,414 | <p>Is it possible somehow to close StreamReader after calling ReadToEnd method in construction like this:</p>
<pre><code>string s = new StreamReader("filename", Encoding.UTF8).ReadToEnd();
</code></pre>
<p>Any alternative elegant construction with the same semantics will be also accepted.</p>
| [
{
"answer_id": 336419,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 2,
"selected": false,
"text": "string s = null; \nusing ( StreamReader reader = new StreamReader( \"filename\", Encoding.UTF8 ) { s = reader.ReadToEnd(); }\n"
},
{
"answer_id": 336420,
"author": "JSC",
"author_id": 37311,
"author_profile": "https://Stackoverflow.com/users/37311",
"pm_score": 2,
"selected": false,
"text": "string s = string.Empty;\nusing(StreamReader sr = new StreamReader(\"filename\", Encoding.UTF8))\n{\n s = sr.ReadToEnd();\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
336,416 | <p>I have the following piece of code which replaces "template markers" such as %POST_TITLE% with the contents of a variable called $post_title.</p>
<pre><code>function replaceTags( $template, $newtext ) {
$template = preg_replace( '/%MYTAG%/', $newtext, $template );
return $template;
}
</code></pre>
<p>The issue is that when $post_full has a '$' in it, the returned result has this removed. For example:</p>
<pre><code>$template = "Replace this: %MYTAG";
$newtext = "I earn $1,000,000 a year";
print replaceTags( $template, $newtext );
// RESULT
Replace this: I earn ,000,000 a year";
</code></pre>
<p>I know this has something to do with not properly escaping the $1 in the $newtext. I have tried using preg_quote() but it doesn't have the desired effect.</p>
| [
{
"answer_id": 336421,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "$1 $newtext = preg_replace(\"!\" . '\\x24' . \"!\" , '\\\\\\$' , $newtext );\n"
},
{
"answer_id": 336436,
"author": "derobert",
"author_id": 27727,
"author_profile": "https://Stackoverflow.com/users/27727",
"pm_score": 3,
"selected": false,
"text": "str_replace"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2136/"
] |
336,452 | <p>I'd like to write a functional test of a RESTful web service I'm working on in a Ruby on Rails app. </p>
<p>The test is of a POST request where the body of the request is a plain XML doc and not a form. Any pointers on how to do this? The problem I'm encountering is how to specify the body XML in the call to the post method.</p>
| [
{
"answer_id": 337111,
"author": "Matt Burke",
"author_id": 29691,
"author_profile": "https://Stackoverflow.com/users/29691",
"pm_score": 1,
"selected": false,
"text": "@request.env['RAW_POST_BODY']"
},
{
"answer_id": 339542,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "@request.env['RAW_POST_DATA'] = MY_XML_STRING\npost :create \n"
},
{
"answer_id": 13365559,
"author": "Raul Pinto",
"author_id": 1680187,
"author_profile": "https://Stackoverflow.com/users/1680187",
"pm_score": 0,
"selected": false,
"text": "message = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tag>content</tag>'\n\n@xml_request_headers ||= {}\n@xml_request_headers['HTTP_ACCEPT'] = @xml_request_headers['CONTENT_TYPE'] = 'application/xml'\n\npost '/controller/action.xml', message, @xml_request_headers\n @xml_request_headers setup test_helper.rb"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,453 | <p>I've written a Custom User Control which returns some user specific data.
To load the Custom User Control I use the following line of code:</p>
<pre><code>UserControl myUC = (UserControl).Load("~/customUserControl.ascx");
</code></pre>
<p>But how can I access <code>string user</code> inside the User Control <code>myUC</code>? </p>
| [
{
"answer_id": 336480,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 0,
"selected": false,
"text": "MyUserControl myUCTyped = (MyUserControl)myUC;\nmyUCTyped.ThePublicProperty = \"some value\";\n"
},
{
"answer_id": 336481,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "MyUserControl myUC = (UserControl).Load(\"~/customUserControl.ascx\") as MyUserControl;\nstring result = myUC.user;\n"
},
{
"answer_id": 336539,
"author": "Stormenet",
"author_id": 2090,
"author_profile": "https://Stackoverflow.com/users/2090",
"pm_score": 2,
"selected": true,
"text": "Bob b = (Bob).Load(\"~/customUserControl.ascx\");\n class Bob : UserControl{\npublic string User { get; set;}\n}\n b.User = theuser;\n"
},
{
"answer_id": 336556,
"author": "Philipp Küng",
"author_id": 37972,
"author_profile": "https://Stackoverflow.com/users/37972",
"pm_score": 0,
"selected": false,
"text": "public partial class todo : System.Web.UI.UserControl\n{\n private string mysecondteststring;\n public string setValue\n {\n get\n {\n return mysecondteststring;\n }\n set\n {\n mysecondteststring = value;\n }\n }\n protected void Page_Load(object sender, EventArgs e)\n {\n // my code\n }\n}\n Reference"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37972/"
] |
336,466 | <p>Does any one know of a free tool or library to convert multi page tiffs to pdf in Asp.Net 1.1?</p>
| [
{
"answer_id": 736404,
"author": "lothar",
"author_id": 44434,
"author_profile": "https://Stackoverflow.com/users/44434",
"pm_score": 1,
"selected": false,
"text": "convert screenshot.tiff screenshot.pdf\n"
},
{
"answer_id": 18227722,
"author": "Sundaram",
"author_id": 2681804,
"author_profile": "https://Stackoverflow.com/users/2681804",
"pm_score": 0,
"selected": false,
"text": "SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\nf.OpenPdf(FilePath);\n\nif (f.PageCount > 0)\n{\n f.ToMultipageTiff(FilePath);\n}\n SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\nf.OpenPdf(FilePath);\n\nif (f.PageCount > 0)\n{\n for (int i = 0; i < f.PageCount; i++)\n {\n f.ImageOptions.Dpi = 200;\n System.Drawing.Bitmap bmp1 = (System.Drawing.Bitmap)f.ToDrawingImage(i + 1);\n bmp1.Save(Server.MapPath(\"~/FileUpload/\") + filename + \"_\" + (i + 1) + \".tiff\");\n }\n}\n SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\nf.OpenPdf(FilePath);\n\nif (f.PageCount > 0)\n{\n f.ToWord(FilePath);\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] |
336,475 | <p>I am writing some new code that will throw a custom exception - I want to include an error string and a status code. Which class should be exception derive from? <code>std::exception</code>? <code>std::runtime_error</code>? Any other 'gotchas' to worry about? I'm thinking of something like the following:</p>
<pre><code>class MyException : public std::exception(?)
{
public:
enum Status
{
ERROR_FOO,
ERROR_BAR,
...
};
MyException(const std::string& error, Status code) :
error_(error), code_(code)
{
...
}
virtual const char* what() const
{
return error_.c_str();
}
Status code() const
{
return code_;
}
private:
std::string error_;
Status code_;
};
</code></pre>
<p>Then in the code:</p>
<pre><code>throw MyException("Ooops!", MyException::ERROR_BAR);
</code></pre>
| [
{
"answer_id": 336507,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 2,
"selected": false,
"text": "invalid_argument, range_error, bad_cast"
},
{
"answer_id": 336527,
"author": "Evgeny Lazin",
"author_id": 42371,
"author_profile": "https://Stackoverflow.com/users/42371",
"pm_score": 2,
"selected": false,
"text": "class MyException : public std::exception\n{\npublic:\n enum Status\n {\n ERROR_FOO,\n ERROR_BAR,\n ...\n };\n\n MyException(const char* error, Status code) :\n std::exception(error),\n code_(code)\n {\n ...\n }\n ...\nprivate:\n Status code_;\n};\n"
},
{
"answer_id": 337981,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 0,
"selected": false,
"text": "// What is a no throw operation.\nvirtual const char* what() const throw ()\n{\n return error_.c_str();\n}\n class MyException: public std::runtime_error\n{ // STUFF .. Put all the error message stuff here\n};\n\nclass MyFOO_Exception: public MyException\n{ // STUFF\n};\n\nclass MyBAR_Exception: public MyException\n{ // STUFF\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
336,495 | <p>Working with Microsoft SQL Server I found extremely useful SQL Server Profiler and Estimated Execution Plan (available in Management Studio) to optimize queries during development and production system monitoring.</p>
<p>Are there similar tools (open source or commercial) or techniques available for MySQL?</p>
| [
{
"answer_id": 336520,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "EXPLAIN EXPLAIN SELECT * FROM foo INNER JOIN bar WHERE foo.index = 1 AND bar.foo_id = foo.id\n"
},
{
"answer_id": 25915819,
"author": "Yvan",
"author_id": 781153,
"author_profile": "https://Stackoverflow.com/users/781153",
"pm_score": 2,
"selected": false,
"text": "SHOW STATUS LIKE 'Last_query_cost';\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42512/"
] |
336,517 | <p>Ive decided that I really dont like microsoft and their ways. Please could you give me directions on how to handle winmail.dat in emails, is there a jython library or a java library that will allow me to handle this.</p>
<p>Ive just completed a email processing program, written in jython 2.2.1 on java 5. During the final load test, I realised that attachments that should have been in a standard MIME email format is now tied up in some blasted winmail.dat, which means many different outlook clients pollute the internet with this winmail.dat, so that means i need to support winmail.dat. Thus my program failed to process the data correctly.</p>
<p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p>
<p>What other surprises can be expected!? what else do I have to watch out for, so far standard MIME emails are catered for. Are there any other jack in the boxes? </p>
<p>Thanks so much for your time.</p>
| [
{
"answer_id": 11262382,
"author": "Bob Rivers",
"author_id": 51754,
"author_profile": "https://Stackoverflow.com/users/51754",
"pm_score": 3,
"selected": false,
"text": " <dependency>\n <groupId>org.apache.poi</groupId>\n <artifactId>poi-scratchpad</artifactId>\n <version>3.14</version>\n </dependency>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
336,553 | <p>Somewhere in the code, a waitHandle is used to perfom some actions. However the thing with waithandle is that the form freezes while waiting for some action to complete. So the following code would not work:</p>
<pre><code>frmProgressBar.show();
int successOrFail = PerformSynchronousActionUsingWaitHandle();
frmProgressBar.close();
frmMainScreen.show();
</code></pre>
<p>It won't work, since the frmProgressBar would be frozen instead.
I really need to keep line #1, line #3 and line #4, but how do I rewrite PerformSynchronousActionUsingWaitHandle() such that the operation is still synchronous but the progress bar is displayed. I may be able to get around this by showing the progress bar on a different thread, but the design of the system is such that this would be very messy.</p>
| [
{
"answer_id": 336885,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 1,
"selected": false,
"text": " public event EventHandler<WorkCompleteArgs> WorkComplete;\n private void StartClick(object sender, EventArgs e)\n {\n //hook a complete event\n this.WorkComplete += new EventHandler(OnWorkComplete);\n\n //do start code\n\n //run the PerformSynchronousActionUsingWaitHandle process in a thread\n Thread thread = new Thread(new ThreadStart(PerformSynchronousActionUsingWaitHandle));\n thread.Start();\n }\n private void OnWorkComplete(object sender, EventArgs e)\n {\n //cross thread\n if (this.InvokeRequired)\n {\n this.BeginInvoke(new EventHandler(OnWorkComplete), new object[] { sender, e });\n return;\n }\n\n //un hook\n this.WorkComplete -= new EventHandler(OnWorkComplete);\n\n //do complete code\n\n }\n private void PerformSynchronousActionUsingWaitHandle()\n {\n Thread.Sleep(1000);\n if (WorkComplete != null)\n {\n //use event args to return the functions result if needed.\n WorkComplete(this, new WorkCompleteArgs(true));\n }\n }\n\n public class WorkCompleteArgs\n {\n public WorkState {get;private set;}\n public WorkCompleteArgs(bool workState)\n {\n this.WorkState = workState;\n }\n }\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,572 | <p>How do we filter an xml document based on another xml document. I have to remove all the elements which are not there in the lookup xml. Both the input xml and lookup xml has the same root elements, we are using XSLT 1.0.</p>
<p>Ex Input</p>
<pre><code><Root>
<E1 a="1">V1</E1>
<E2>V2</E2>
<E3>V3</E3>
<E5>
<SE51>SEV1</SE51>
<SE52>SEV2</SE52>
</E5>
<E6>
<SE61>SEV3</SE61>
<SE62>SEV4</SE62>
</E6>
</Root>
</code></pre>
<p>Filter Xml</p>
<pre><code><Root>
<E1 a="1"></E1>
<E2></E2>
<E5>
<SE51></SE51>
<SE52></SE52>
</E5>
</Root>
</code></pre>
<p>Expected Output</p>
<pre><code><Root>
<E1 a="1">V1</E1>
<E2>V2</E2>
<E5>
<SE51>SEv1</SE51>
<SE52>SEV2</SE52>
</E5>
</Root>
</code></pre>
| [
{
"answer_id": 339609,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 3,
"selected": true,
"text": "<SE511>SEV11</SE511>"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26036/"
] |
336,575 | <p>I would like to know whether it is possible to force LWP::UserAgent to accept an expired SSL certificate for a single, well-known server. The issue is slightly complicated by the Squid proxy in between.</p>
<p>I went as far as to set up a debugging environment like:</p>
<pre><code>use warnings;
use strict;
use Carp;
use LWP::UserAgent;
use LWP::Debug qw(+);
use HTTP::Cookies;
my $proxy = 'http://proxy.example.net:8118';
my $cookie_jar = HTTP::Cookies->new( file => 'cookies.tmp' );
my $agent = LWP::UserAgent->new;
$agent->proxy( [ 'http' ], $proxy );
$agent->cookie_jar( $cookie_jar );
$ENV{HTTPS_PROXY} = $proxy;
$ENV{HTTPS_DEBUG} = 1;
$ENV{HTTPS_VERSION} = 3;
$ENV{HTTPS_CA_DIR} = '/etc/ssl/certs';
$ENV{HTTPS_CA_FILE} = '/etc/ssl/certs/ca-certificates.crt';
$agent->get( 'https://www.example.com/');
exit;
</code></pre>
<p>Fortunately the issue was eventually fixed on the remote server before I was able to come up with my own solution, but I would like to be able to optionally circumvent the problem should it arise again (the underlying service had been disrupted for several hours before I was called into action).</p>
<p>I would favor a solution at the LWP::UserAgent level over one based on the underlying Crypt::SSLeay or openSSL implementations, if such a solution exists, since I prefer not to relax security for other unrelated applications. Of course I am still looking for such a solution myself, in my copious free time.</p>
| [
{
"answer_id": 338550,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 5,
"selected": true,
"text": "$agent->ssl_opts(verify_hostname => 0);\n IO::Socket::SSL SSL_verify_mode 0x00 $agent->ssl_opts(SSL_verify_mode => 0x00);\n"
},
{
"answer_id": 15528718,
"author": "André Fernandes",
"author_id": 810448,
"author_profile": "https://Stackoverflow.com/users/810448",
"pm_score": 4,
"selected": false,
"text": "$agent->ssl_opts(verify_hostname => 0,\n SSL_verify_mode => 0x00);\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36218/"
] |
336,578 | <p>We have a Hibernate/Spring application that have the following Spring beans:</p>
<pre><code><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" />
</code></pre>
<p>When wiring the application together we get the following error when using private constructors in our hibernate entities:</p>
<pre><code>Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No visible constructors in class 'ourclass'
</code></pre>
<p>The entities are typical domain objects such as an Employee or the like. </p>
<p>When changing the constructor's visibility modifier to package (or public) the application runs fine and the entities gets stored/loaded in the database. How do we/can we use private constructors/static factory methods with Spring/Hibernate transaction management?</p>
<p>We use Hibernate annotations to map the entities/relationships. No bean definitions are declared in the applicationContext.xml for the domain class that is related to the problem. It is a pojo that should have a static factory method and a private constructor.</p>
<p>How can we make Hibernate (org.springframework.spring-orm.hibernate3 classes i guess) make use of the static factory method instead of the constructor? Or possibly make it call a private constructor if necessary?</p>
<p>Using the spring factory-method configuration would make sense but the entities are not mapped as beans in our applicationContext.xml. They are only annotated with the @Entity annotation for Hibernate persistence.</p>
<p>Hope this edit clearifies (rather than mystifies) the question. :)</p>
| [
{
"answer_id": 337408,
"author": "Chochos",
"author_id": 10165,
"author_profile": "https://Stackoverflow.com/users/10165",
"pm_score": 0,
"selected": false,
"text": "public package final"
},
{
"answer_id": 347953,
"author": "deterb",
"author_id": 15585,
"author_profile": "https://Stackoverflow.com/users/15585",
"pm_score": 4,
"selected": true,
"text": "public class MyInterceptor extends EmptyInterceptor {\n\n public Object instantiate(String entityName, EntityMode entityMode, Serializable id) {\n if(entityName.equals(Foo.class.getName())\n return Foo.create();\n return null;\n }\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382264/"
] |
336,585 | <p>I know the rule-of-thumb to read declarations right-to-left and I was fairly sure I knew what was going on until a colleague told me that:</p>
<pre><code>const MyStructure** ppMyStruct;
</code></pre>
<p>means "ppMyStruct is <strong>a pointer to a const pointer to a (mutable) MyStructure</strong>" (in C++).</p>
<p>I would have thought it meant "ppMyStruct is <strong>a pointer to a pointer to a const MyStructure</strong>".
I looked for an answer in the C++ spec, but apparently I'm not very good at that...</p>
<p>What does in mean in C++, and does it mean the same thing in C?</p>
| [
{
"answer_id": 336657,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 6,
"selected": false,
"text": " [flolo@titan ~]$ cdecl explain \"const struct s** ppMyStruct\"\n declare ppMyStruct as pointer to pointer to const struct s\n"
},
{
"answer_id": 336661,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 3,
"selected": false,
"text": "typedef struct foo_t {\n int i;\n} foo_t;\n\nint main()\n{\n foo_t f = {123};\n const foo_t *p = &f;\n const foo_t **pp = &p;\n printf(\"f.i = %d\\n\", (*pp)->i);\n (*pp)->i = 888; // error\n p->i = 999; // error\n}\n error C2166: l-value specifies const object\nerror C2166: l-value specifies const object\n error: assignment of read-only location '**pp'\nerror: assignment of read-only location '*p'\n error: assignment of data-member 'foo_t::i' in read-only structure\nerror: assignment of data-member 'foo_t::i' in read-only structure\n"
},
{
"answer_id": 336685,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 5,
"selected": false,
"text": "const MyStructure * *ppMyStruct; // ptr --> ptr --> const MyStructure\n MyStructure *const *ppMyStruct; // ptr --> const ptr --> MyStructure\n MyStructure * *const ppMyStruct; // const ptr --> ptr --> MyStructure\n"
},
{
"answer_id": 337153,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "MyStructure const** ppMyStruct;\n"
},
{
"answer_id": 2212094,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "void Foo( int * ptr,\n int const * ptrToConst,\n int * const constPtr,\n int const * const constPtrToConst )\n{\n *ptr = 0; // OK: modifies the pointee\n ptr = 0; // OK: modifies the pointer\n\n *ptrToConst = 0; // Error! Cannot modify the pointee\n ptrToConst = 0; // OK: modifies the pointer\n\n *constPtr = 0; // OK: modifies the pointee\n constPtr = 0; // Error! Cannot modify the pointer\n\n *constPtrToConst = 0; // Error! Cannot modify the pointee\n constPtrToConst = 0; // Error! Cannot modify the pointer\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15323/"
] |
336,605 | <p>Is there a fast algorithm for finding the Largest Common Substring in two <code>strings</code> or is it an NPComplete problem?</p>
<p>In PHP I can find a needle in a haystack:</p>
<pre><code><?php
if (strstr("there is a needle in a haystack", "needle")) {
echo "found<br>\n";
}
?>
</code></pre>
<p>I guess I could do this in a loop over one of the <code>strings</code> but that would be very expensive! Especially since my application of this is to search a database of email and look for spam (i.e. similar emails sent by the same person). </p>
<p>Does anyone have any PHP code they can throw out there?</p>
| [
{
"answer_id": 336617,
"author": "Tom",
"author_id": 42754,
"author_profile": "https://Stackoverflow.com/users/42754",
"pm_score": 3,
"selected": true,
"text": "<?php\n// Gather all messages by a user into two identical associative arrays\n$getMsgsRes = mysql_query(SELECT * FROM email_messages WHERE from = '$someUserID');\nwhile($msgInfo = mysql_fetch_assoc($getMsgsRes))\n{\n $msgsInfo1[] = $msgInfo;\n $msgsInfo2[] = $msgInfo;\n}\n\n// Loop over msgs and compare each one to every other\nforeach ($msgsInfo1 as $msg1)\n foreach ($msgsInfo2 as $msg2)\n similar_text($msg1['msgTxt'],$msg2['msgTxt'],$similarity_pst);\n if ($similarity_pst > 90)\n echo \"{$msg1['msgID']} is ${similarity_pst}% to {$msg2['msgID']}\\n\";\n?>\n"
},
{
"answer_id": 5109221,
"author": "Chris Bloom",
"author_id": 83743,
"author_profile": "https://Stackoverflow.com/users/83743",
"pm_score": 2,
"selected": false,
"text": "$array = array(\n 'PTT757LP4',\n 'PTT757A',\n 'PCT757B',\n 'PCT757LP4EV'\n);\necho longest_common_substring($array); // => T757\n function longest_common_substring($words) {\n $words = array_map('strtolower', array_map('trim', $words));\n $sort_by_strlen = create_function('$a, $b', 'if (strlen($a) == strlen($b)) { return strcmp($a, $b); } return (strlen($a) < strlen($b)) ? -1 : 1;');\n usort($words, $sort_by_strlen);\n // We have to assume that each string has something in common with the first\n // string (post sort), we just need to figure out what the longest common\n // string is. If any string DOES NOT have something in common with the first\n // string, return false.\n $longest_common_substring = array();\n $shortest_string = str_split(array_shift($words));\n\n while (sizeof($shortest_string)) {\n array_unshift($longest_common_substring, '');\n foreach ($shortest_string as $ci => $char) {\n foreach ($words as $wi => $word) {\n if (!strstr($word, $longest_common_substring[0] . $char)) {\n // No match\n break 2;\n } // if\n } // foreach\n // we found the current char in each word, so add it to the first longest_common_substring element,\n // then start checking again using the next char as well\n $longest_common_substring[0].= $char;\n } // foreach\n // We've finished looping through the entire shortest_string.\n // Remove the first char and start all over. Do this until there are no more\n // chars to search on.\n array_shift($shortest_string);\n }\n // If we made it here then we've run through everything\n usort($longest_common_substring, $sort_by_strlen);\n return array_pop($longest_common_substring);\n}\n"
},
{
"answer_id": 36451409,
"author": "zion ben yacov",
"author_id": 1011021,
"author_profile": "https://Stackoverflow.com/users/1011021",
"pm_score": 3,
"selected": false,
"text": "public static function getLongestMatchingSubstring($str1, $str2)\n{\n $len_1 = strlen($str1);\n $longest = '';\n for($i = 0; $i < $len_1; $i++){\n for($j = $len_1 - $i; $j > 0; $j--){\n $sub = substr($str1, $i, $j);\n if (strpos($str2, $sub) !== false && strlen($sub) > strlen($longest)){\n $longest = $sub;\n break;\n }\n }\n }\n return $longest;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42754/"
] |
336,628 | <p>One thing that annoys me when debugging programs in Visual Studio (2005 in my case) is that when I use "step over" (by pressing <kbd>F10</kbd>) to execute to the next line of code, I often end up reaching that particular line of code in a totally different thread than the one I was looking at. This means that all the context of what I was doing was lost.</p>
<p>How do I work around this?</p>
<p>If this is possible to do in later versions of Visual Studio, I'd like to hear about it as well.</p>
<p>Setting a breakpoint on the next line of code which has a conditional to only break for this thread is not the answer I'm looking for since it is way too much work to be useful for me :)</p>
| [
{
"answer_id": 378584,
"author": "Aaron",
"author_id": 28950,
"author_profile": "https://Stackoverflow.com/users/28950",
"pm_score": 6,
"selected": true,
"text": "$TID $TID == < > $TID == 0x000016a0 $TID Imports System\nImports EnvDTE\nImports EnvDTE80\nImports System.Diagnostics\n\nPublic Module DebugHelperFunctions\n\n Sub RunToCursorInMyThread()\n Dim textSelection As EnvDTE.TextSelection\n Dim myThread As EnvDTE.Thread\n Dim bp As EnvDTE.Breakpoint\n Dim bps As EnvDTE.Breakpoints\n\n ' For Breakpoints.Add()\n Dim FileName As String\n Dim LineNumber As Integer\n Dim ThreadID As String\n\n ' Get local references for ease of use \n myThread = DTE.Debugger.CurrentThread\n textSelection = DTE.ActiveDocument.Selection\n\n LineNumber = textSelection.ActivePoint.Line\n FileName = textSelection.DTE.ActiveDocument.FullName\n ThreadID = myThread.ID\n\n ' Add a \"One-Shot\" Breakpoint in current file on current line for current thread\n bps = DTE.Debugger.Breakpoints.Add(\"\", FileName, LineNumber, 1, \"$TID == \" & ThreadID)\n\n ' Run to the next stop\n DTE.Debugger.Go(True)\n\n ' Remove our \"One-Shot\" Breakpoint\n For Each bp In bps\n bp.Delete()\n Next\n End Sub\n\n Sub StepOverInMyThread()\n Dim textSelection As EnvDTE.TextSelection\n Dim myThread As EnvDTE.Thread\n Dim bp As EnvDTE.Breakpoint\n Dim bps As EnvDTE.Breakpoints\n\n ' For Breakpoints.Add()\n Dim FileName As String\n Dim LineNumber As Integer\n Dim ThreadID As String\n\n ' Get local references for ease of use \n myThread = DTE.Debugger.CurrentThread\n textSelection = DTE.ActiveDocument.Selection\n\n LineNumber = textSelection.ActivePoint.Line\n FileName = textSelection.DTE.ActiveDocument.FullName\n ThreadID = myThread.ID\n LineNumber = LineNumber + 1\n\n ' Add a \"One-Shot\" Breakpoint in current file on current line for current thread\n bps = DTE.Debugger.Breakpoints.Add(\"\", FileName, LineNumber, 1, \"$TID == \" & ThreadID)\n\n ' Run to the next stop\n DTE.Debugger.Go(True)\n\n ' Remove our \"One-Shot\" Breakpoint\n For Each bp In bps\n bp.Delete()\n Next\n End Sub\n\n\nEnd Module\n"
},
{
"answer_id": 26012873,
"author": "helb",
"author_id": 2383264,
"author_profile": "https://Stackoverflow.com/users/2383264",
"pm_score": 2,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n var t = new Thread(new ThreadStart(Work));\n t.Start();\n\n for (int i = 0; i < 20; i++)\n {\n Thread.Sleep(1000);\n Console.WriteLine(\"............\");\n }\n\n t.Join();\n }\n\n static void Work()\n {\n for (int i = 0; i < 20; i++)\n {\n Thread.Sleep(1000);\n Console.WriteLine(\"ZZzzzzzzzzzzzzzz\");\n }\n }\n}\n Main() Work()"
},
{
"answer_id": 46992387,
"author": "knightgambit",
"author_id": 5802135,
"author_profile": "https://Stackoverflow.com/users/5802135",
"pm_score": 1,
"selected": false,
"text": "if (instance.ID == myID)\n{\n // Assert BreakPoint\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11758/"
] |
336,633 | <p>In a <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> 2.0 C# application I use the following code to detect the operating system platform:</p>
<pre><code>string os_platform = System.Environment.OSVersion.Platform.ToString();
</code></pre>
<p>This returns "Win32NT". The problem is that it returns "Win32NT" even when running on Windows Vista 64-bit.</p>
<p>Is there any other method to know the correct platform (32 or 64 bit)?</p>
<p>Note that it should also detect 64 bit when run as a 32 bit application on Windows 64 bit.</p>
| [
{
"answer_id": 336645,
"author": "BobbyShaftoe",
"author_id": 38426,
"author_profile": "https://Stackoverflow.com/users/38426",
"pm_score": 4,
"selected": false,
"text": "if(IntPtr.Size == 8) {\n // 64 bit machine\n} else if(IntPtr.Size == 4) {\n // 32 bit machine\n} \n <Prefer32Bit>true</Prefer32Bit>"
},
{
"answer_id": 336729,
"author": "Stefan Schultze",
"author_id": 6358,
"author_profile": "https://Stackoverflow.com/users/6358",
"pm_score": 9,
"selected": true,
"text": "Environment.Is64BitOperatingSystem static bool is64BitProcess = (IntPtr.Size == 8);\nstatic bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();\n\n[DllImport(\"kernel32.dll\", SetLastError = true, CallingConvention = CallingConvention.Winapi)]\n[return: MarshalAs(UnmanagedType.Bool)]\nprivate static extern bool IsWow64Process(\n [In] IntPtr hProcess,\n [Out] out bool wow64Process\n);\n\npublic static bool InternalCheckIsWow64()\n{\n if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||\n Environment.OSVersion.Version.Major >= 6)\n {\n using (Process p = Process.GetCurrentProcess())\n {\n bool retVal;\n if (!IsWow64Process(p.Handle, out retVal))\n {\n return false;\n }\n return retVal;\n }\n }\n else\n {\n return false;\n }\n}\n"
},
{
"answer_id": 447073,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 2,
"selected": false,
"text": "[DllImport(\"kernel32.dll\", SetLastError = true, CallingConvention = CallingConvention.Winapi)] \n[return: MarshalAs(UnmanagedType.Bool)] \npublic static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo); \n\npublic static bool Is64Bit() \n{ \n bool retVal; \n\n IsWow64Process(Process.GetCurrentProcess().Handle, out retVal); \n\n return retVal; \n} \n"
},
{
"answer_id": 681542,
"author": "Bruno Lopes",
"author_id": 42926,
"author_profile": "https://Stackoverflow.com/users/42926",
"pm_score": 6,
"selected": false,
"text": " [DllImport(\"kernel32.dll\", SetLastError = true, CallingConvention = CallingConvention.Winapi)]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo);\n\n private bool Is64Bit()\n {\n if (IntPtr.Size == 8 || (IntPtr.Size == 4 && Is32BitProcessOn64BitProcessor()))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n\n private bool Is32BitProcessOn64BitProcessor()\n {\n bool retVal;\n\n IsWow64Process(Process.GetCurrentProcess().Handle, out retVal);\n\n return retVal;\n } \n"
},
{
"answer_id": 1040501,
"author": "Andrew Ensley",
"author_id": 20801,
"author_profile": "https://Stackoverflow.com/users/20801",
"pm_score": 4,
"selected": false,
"text": "PROCESSOR_ARCHITECTURE private int GetOSArchitecture()\n{\n string pa = \n Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\");\n return ((String.IsNullOrEmpty(pa) || \n String.Compare(pa, 0, \"x86\", 0, 3, true) == 0) ? 32 : 64);\n}\n"
},
{
"answer_id": 1060417,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "env PROCESSOR_ARCHITECTURE=x86\n PROCESSOR_ARCHITECTURE=AMD64\n"
},
{
"answer_id": 1840313,
"author": "dwhiteho",
"author_id": 223822,
"author_profile": "https://Stackoverflow.com/users/223822",
"pm_score": 6,
"selected": false,
"text": "[DllImport(\"kernel32\", SetLastError = true, CallingConvention = CallingConvention.Winapi)]\npublic extern static IntPtr LoadLibrary(string libraryName);\n\n[DllImport(\"kernel32\", SetLastError = true, CallingConvention = CallingConvention.Winapi)]\npublic extern static IntPtr GetProcAddress(IntPtr hwnd, string procedureName);\n\nprivate delegate bool IsWow64ProcessDelegate([In] IntPtr handle, [Out] out bool isWow64Process);\n\npublic static bool IsOS64Bit()\n{\n if (IntPtr.Size == 8 || (IntPtr.Size == 4 && Is32BitProcessOn64BitProcessor()))\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\nprivate static IsWow64ProcessDelegate GetIsWow64ProcessDelegate()\n{\n IntPtr handle = LoadLibrary(\"kernel32\");\n\n if ( handle != IntPtr.Zero)\n {\n IntPtr fnPtr = GetProcAddress(handle, \"IsWow64Process\");\n\n if (fnPtr != IntPtr.Zero)\n {\n return (IsWow64ProcessDelegate)Marshal.GetDelegateForFunctionPointer((IntPtr)fnPtr, typeof(IsWow64ProcessDelegate));\n }\n }\n\n return null;\n}\n\nprivate static bool Is32BitProcessOn64BitProcessor()\n{\n IsWow64ProcessDelegate fnDelegate = GetIsWow64ProcessDelegate();\n\n if (fnDelegate == null)\n {\n return false;\n }\n\n bool isWow64;\n bool retVal = fnDelegate.Invoke(Process.GetCurrentProcess().Handle, out isWow64);\n\n if (retVal == false)\n {\n return false;\n }\n\n return isWow64;\n}\n"
},
{
"answer_id": 2054835,
"author": "Santhosh",
"author_id": 184774,
"author_profile": "https://Stackoverflow.com/users/184774",
"pm_score": 3,
"selected": false,
"text": "if (PROCESSOR_ARCHITECTURE = x86 &&\n isDefined(PROCESSOR_ARCHITEW6432) &&\n PROCESSOR_ARCHITEW6432 = AMD64) {\n\n //64 bit OS\n}\nelse\n if (PROCESSOR_ARCHITECTURE = AMD64) {\n //64 bit OS\n }\n else\n if (PROCESSOR_ARCHITECTURE = x86) {\n //32 bit OS\n }\n"
},
{
"answer_id": 2691303,
"author": "Greg",
"author_id": 323292,
"author_profile": "https://Stackoverflow.com/users/323292",
"pm_score": 1,
"selected": false,
"text": "using System;\nnamespace CSharp411\n{\n class Program\n {\n static void Main( string[] args )\n {\n Console.WriteLine( \"Operation System Information\" );\n Console.WriteLine( \"----------------------------\" );\n Console.WriteLine( \"Name = {0}\", OSInfo.Name );\n Console.WriteLine( \"Edition = {0}\", OSInfo.Edition );\n Console.WriteLine( \"Service Pack = {0}\", OSInfo.ServicePack );\n Console.WriteLine( \"Version = {0}\", OSInfo.VersionString );\n Console.WriteLine( \"Bits = {0}\", OSInfo.Bits );\n Console.ReadLine();\n }\n }\n}\n"
},
{
"answer_id": 3489142,
"author": "synhershko",
"author_id": 135701,
"author_profile": "https://Stackoverflow.com/users/135701",
"pm_score": 5,
"selected": false,
"text": " /// <summary>\n /// The function determines whether the current operating system is a \n /// 64-bit operating system.\n /// </summary>\n /// <returns>\n /// The function returns true if the operating system is 64-bit; \n /// otherwise, it returns false.\n /// </returns>\n public static bool Is64BitOperatingSystem()\n {\n if (IntPtr.Size == 8) // 64-bit programs run only on Win64\n {\n return true;\n }\n else // 32-bit programs run on both 32-bit and 64-bit Windows\n {\n // Detect whether the current process is a 32-bit process \n // running on a 64-bit system.\n bool flag;\n return ((DoesWin32MethodExist(\"kernel32.dll\", \"IsWow64Process\") &&\n IsWow64Process(GetCurrentProcess(), out flag)) && flag);\n }\n }\n\n /// <summary>\n /// The function determins whether a method exists in the export \n /// table of a certain module.\n /// </summary>\n /// <param name=\"moduleName\">The name of the module</param>\n /// <param name=\"methodName\">The name of the method</param>\n /// <returns>\n /// The function returns true if the method specified by methodName \n /// exists in the export table of the module specified by moduleName.\n /// </returns>\n static bool DoesWin32MethodExist(string moduleName, string methodName)\n {\n IntPtr moduleHandle = GetModuleHandle(moduleName);\n if (moduleHandle == IntPtr.Zero)\n {\n return false;\n }\n return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);\n }\n\n [DllImport(\"kernel32.dll\")]\n static extern IntPtr GetCurrentProcess();\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n static extern IntPtr GetModuleHandle(string moduleName);\n\n [DllImport(\"kernel32\", CharSet = CharSet.Auto, SetLastError = true)]\n static extern IntPtr GetProcAddress(IntPtr hModule,\n [MarshalAs(UnmanagedType.LPStr)]string procName);\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);\n"
},
{
"answer_id": 3739596,
"author": "Josh",
"author_id": 450822,
"author_profile": "https://Stackoverflow.com/users/450822",
"pm_score": -1,
"selected": false,
"text": " public static bool Is64BitSystem()\n {\n if (Directory.Exists(Environment.GetEnvironmentVariable(\"Program Files (x86)\"))) return true;\n else return false;\n }\n"
},
{
"answer_id": 4878491,
"author": "dmihailescu",
"author_id": 376495,
"author_profile": "https://Stackoverflow.com/users/376495",
"pm_score": 2,
"selected": false,
"text": "bool bIs64BitOS = System.Environment.OSVersion.IsWin64BitOS();\n\nbool bIs64BitProc = System.Diagnostics.Process.GetCurrentProcess().Is64BitProc();\n\n//Hosts the extension methods \npublic static class OSHelperTools \n{ \n /// <summary> \n /// The function determines whether the current operating system is a \n /// 64-bit operating system. \n /// </summary> \n /// <returns> \n /// The function returns true if the operating system is 64-bit; \n /// otherwise, it returns false. \n /// </returns> \n public static bool IsWin64BitOS(this OperatingSystem os) \n { \n if (IntPtr.Size == 8) \n // 64-bit programs run only on Win64 \n return true; \n else// 32-bit programs run on both 32-bit and 64-bit Windows \n { // Detect whether the current process is a 32-bit process \n // running on a 64-bit system. \n return Process.GetCurrentProcess().Is64BitProc(); \n } \n } \n\n /// <summary> \n /// Checks if the process is 64 bit \n /// </summary> \n /// <param name=\"os\"></param> \n /// <returns> \n /// The function returns true if the process is 64-bit; \n /// otherwise, it returns false. \n /// </returns> \n public static bool Is64BitProc(this System.Diagnostics.Process p) \n { \n // 32-bit programs run on both 32-bit and 64-bit Windows \n // Detect whether the current process is a 32-bit process \n // running on a 64-bit system. \n bool result; \n return ((DoesWin32MethodExist(\"kernel32.dll\", \"IsWow64Process\") && IsWow64Process(p.Handle, out result)) && result); \n } \n\n /// <summary> \n /// The function determins whether a method exists in the export \n /// table of a certain module. \n /// </summary> \n /// <param name=\"moduleName\">The name of the module</param> \n /// <param name=\"methodName\">The name of the method</param> \n /// <returns> \n /// The function returns true if the method specified by methodName \n /// exists in the export table of the module specified by moduleName. \n /// </returns> \n static bool DoesWin32MethodExist(string moduleName, string methodName) \n { \n IntPtr moduleHandle = GetModuleHandle(moduleName); \n if (moduleHandle == IntPtr.Zero) \n return false; \n return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero); \n } \n [DllImport(\"kernel32.dll\")] \n static extern IntPtr GetCurrentProcess(); \n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)] \n static extern IntPtr GetModuleHandle(string moduleName); \n\n [DllImport(\"kernel32\", CharSet = CharSet.Auto, SetLastError = true)] \n static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)]string procName); \n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)] \n [return: MarshalAs(UnmanagedType.Bool)] \n static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process); \n}\n"
},
{
"answer_id": 7603582,
"author": "Julian Hall",
"author_id": 845420,
"author_profile": "https://Stackoverflow.com/users/845420",
"pm_score": 2,
"selected": false,
"text": " public static bool is64bit(String host)\n {\n using (var reg = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, host))\n using (var key = reg.OpenSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\\"))\n {\n return key.GetValue(\"ProgramFilesDir (x86)\") !=null;\n }\n }\n"
},
{
"answer_id": 8100948,
"author": "Ben G",
"author_id": 1042584,
"author_profile": "https://Stackoverflow.com/users/1042584",
"pm_score": -1,
"selected": false,
"text": "Dim drivelet As String = Application.StartupPath.ToString\nIf Directory.Exists(drivelet(0) & \":\\Program Files (x86)\") Then\n MsgBox(\"64bit\")\nElse\n MsgBox(\"32bit\")\nEnd if\n C:\\ C:\\"
},
{
"answer_id": 8621467,
"author": "blez",
"author_id": 309145,
"author_profile": "https://Stackoverflow.com/users/309145",
"pm_score": 2,
"selected": false,
"text": " public static bool Is32bitProcess(Process proc) {\n if (!IsThis64bitProcess()) return true; // We're in 32-bit mode, so all are 32-bit.\n\n foreach (ProcessModule module in proc.Modules) {\n try {\n string fname = Path.GetFileName(module.FileName).ToLowerInvariant();\n if (fname.Contains(\"wow64\")) {\n return true;\n }\n } catch {\n // What on earth is going on here?\n }\n }\n return false;\n }\n\n public static bool Is64bitProcess(Process proc) {\n return !Is32bitProcess(proc);\n }\n\n public static bool IsThis64bitProcess() {\n return (IntPtr.Size == 8);\n }\n"
},
{
"answer_id": 9538443,
"author": "user1054695",
"author_id": 1054695,
"author_profile": "https://Stackoverflow.com/users/1054695",
"pm_score": 2,
"selected": false,
"text": "string _osVersion = \"\";\nstring _osServicePack = \"\";\nstring _osArchitecture = \"\";\n\nManagementObjectSearcher searcher = new ManagementObjectSearcher(\"select * from Win32_OperatingSystem\");\nManagementObjectCollection collection = searcher.Get();\n\nforeach (ManagementObject mbo in collection)\n{\n _osVersion = mbo.GetPropertyValue(\"Caption\").ToString();\n _osServicePack = string.Format(\"{0}.{1}\", mbo.GetPropertyValue(\"ServicePackMajorVersion\").ToString(), mbo.GetPropertyValue(\"ServicePackMinorVersion\").ToString());\n\n try\n {\n _osArchitecture = mbo.GetPropertyValue(\"OSArchitecture\").ToString();\n }\n catch\n {\n // OSArchitecture only supported on Windows 7/Windows Server 2008\n }\n}\n\nConsole.WriteLine(\"osVersion : \" + _osVersion);\nConsole.WriteLine(\"osServicePack : \" + _osServicePack);\nConsole.WriteLine(\"osArchitecture: \" + _osArchitecture);\n\n/////////////////////////////////////////\n// Test on Windows 7 64-bit\n//\n// osVersion : Microsoft Windows 7 Professional\n// osservicePack : 1.0\n// osArchitecture: 64-bit\n\n/////////////////////////////////////////\n// Test on Windows Server 2008 64-bit\n// --The extra r's come from the registered trademark\n//\n// osVersion : Microsoftr Windows Serverr 2008 Standard\n// osServicePack : 1.0\n// osArchitecture: 64-bit\n\n/////////////////////////////////////////\n// Test on Windows Server 2003 32-bit\n// --OSArchitecture property not supported on W2K3\n//\n// osVersion : Microsoft(R) Windows(R) Server 2003, Standard Edition\n// osServicePack : 2.0\n// osArchitecture:\n"
},
{
"answer_id": 9905313,
"author": "SomeSysadmin",
"author_id": 1297845,
"author_profile": "https://Stackoverflow.com/users/1297845",
"pm_score": 3,
"selected": false,
"text": "System.Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITECTURE\")\n"
},
{
"answer_id": 10029210,
"author": "user885959",
"author_id": 885959,
"author_profile": "https://Stackoverflow.com/users/885959",
"pm_score": 0,
"selected": false,
"text": "string getOSArchitecture()\n{\n string architectureStr;\n if (Directory.Exists(Environment.GetFolderPath(\n Environment.SpecialFolder.ProgramFilesX86))) {\n architectureStr =\"64-bit\";\n }\n else {\n architectureStr = \"32-bit\";\n }\n return architectureStr;\n}\n"
},
{
"answer_id": 12169099,
"author": "Peter Vaughan-Williams",
"author_id": 1631719,
"author_profile": "https://Stackoverflow.com/users/1631719",
"pm_score": 7,
"selected": false,
"text": "Environment.Is64BitOperatingSystem\n"
},
{
"answer_id": 12759050,
"author": "OmarElsherif",
"author_id": 1540912,
"author_profile": "https://Stackoverflow.com/users/1540912",
"pm_score": 2,
"selected": false,
"text": "bool 64BitSystem = Environment.Is64BitOperatingSystem;\nbool 64BitProcess = Environment.Is64BitProcess;\n"
},
{
"answer_id": 15761315,
"author": "user2235582",
"author_id": 2235582,
"author_profile": "https://Stackoverflow.com/users/2235582",
"pm_score": 4,
"selected": false,
"text": "Environment.Is64BitOperatingSystem\n\nEnvironment.Is64BitProcess\n"
},
{
"answer_id": 20249505,
"author": "Majid95",
"author_id": 3042928,
"author_profile": "https://Stackoverflow.com/users/3042928",
"pm_score": -1,
"selected": false,
"text": "Function Is64Bit() As Boolean\n\n Return My.Computer.FileSystem.SpecialDirectories.ProgramFiles.Contains(\"Program Files (x86)\")\n\nEnd Function\n"
},
{
"answer_id": 24006270,
"author": "electricalbah",
"author_id": 1899556,
"author_profile": "https://Stackoverflow.com/users/1899556",
"pm_score": 4,
"selected": false,
"text": "//Workspace: Target Platform x86\nEnvironment.Is64BitOperatingSystem True\nEnvironment.Is64BitProcess False\n\n//Workspace: Target Platform x64\nEnvironment.Is64BitOperatingSystem True\nEnvironment.Is64BitProcess True\n\n//Workspace: Target Platform Any\nEnvironment.Is64BitOperatingSystem True\nEnvironment.Is64BitProcess True\n"
},
{
"answer_id": 28866330,
"author": "Alexandru",
"author_id": 982639,
"author_profile": "https://Stackoverflow.com/users/982639",
"pm_score": 3,
"selected": false,
"text": "public static class EnvironmentHelper\n{\n [DllImport(\"kernel32.dll\")]\n static extern IntPtr GetCurrentProcess();\n\n [DllImport(\"kernel32.dll\")]\n static extern IntPtr GetModuleHandle(string moduleName);\n\n [DllImport(\"kernel32\")]\n static extern IntPtr GetProcAddress(IntPtr hModule, string procName);\n\n [DllImport(\"kernel32.dll\")]\n static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);\n\n public static bool Is64BitOperatingSystem()\n {\n // Check if this process is natively an x64 process. If it is, it will only run on x64 environments, thus, the environment must be x64.\n if (IntPtr.Size == 8)\n return true;\n // Check if this process is an x86 process running on an x64 environment.\n IntPtr moduleHandle = GetModuleHandle(\"kernel32\");\n if (moduleHandle != IntPtr.Zero)\n {\n IntPtr processAddress = GetProcAddress(moduleHandle, \"IsWow64Process\");\n if (processAddress != IntPtr.Zero)\n {\n bool result;\n if (IsWow64Process(GetCurrentProcess(), out result) && result)\n return true;\n }\n }\n // The environment must be an x86 environment.\n return false;\n }\n}\n EnvironmentHelper.Is64BitOperatingSystem();\n"
},
{
"answer_id": 36083045,
"author": "WonderWorker",
"author_id": 1271898,
"author_profile": "https://Stackoverflow.com/users/1271898",
"pm_score": 1,
"selected": false,
"text": " [DllImport(\"kernel32.dll\", SetLastError = true, CallingConvention = CallingConvention.Winapi)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool wow64Process);\n\n public static int GetBit()\n {\n int MethodResult = \"\";\n try\n {\n int Architecture = 32;\n\n if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) || Environment.OSVersion.Version.Major >= 6)\n {\n using (Process p = Process.GetCurrentProcess())\n {\n bool Is64Bit;\n\n if (IsWow64Process(p.Handle, out Is64Bit))\n {\n if (Is64Bit)\n {\n Architecture = 64;\n\n }\n\n }\n\n }\n\n }\n\n MethodResult = Architecture;\n\n }\n catch //(Exception ex)\n {\n //ex.HandleException();\n }\n return MethodResult;\n }\n string Architecture = \"This is a \" + GetBit() + \"bit machine\";\n"
},
{
"answer_id": 40862732,
"author": "Alexandru Dicu",
"author_id": 1140388,
"author_profile": "https://Stackoverflow.com/users/1140388",
"pm_score": 3,
"selected": false,
"text": "private bool Is64BitSystem\n{\n get\n {\n return Directory.Exists(Environment.ExpandEnvironmentVariables(@\"%windir%\\SysWOW64\"));\n }\n}\n"
},
{
"answer_id": 47091439,
"author": "John Demetriou",
"author_id": 1766548,
"author_profile": "https://Stackoverflow.com/users/1766548",
"pm_score": 0,
"selected": false,
"text": "private bool Is64BitSystem\n{\n get\n {\n return Directory.Exists(Environment.ExpandEnvironmentVariables(@\"%PROGRAMFILES(X86)%\"));\n }\n}\n"
},
{
"answer_id": 66107002,
"author": "cube45",
"author_id": 2663813,
"author_profile": "https://Stackoverflow.com/users/2663813",
"pm_score": 0,
"selected": false,
"text": "System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture\n"
},
{
"answer_id": 74208220,
"author": "AndyCODE",
"author_id": 3409954,
"author_profile": "https://Stackoverflow.com/users/3409954",
"pm_score": 0,
"selected": false,
"text": "Dim r As String = \"\"\nUsing searcher As ManagementObjectSearcher = New System.Management.ManagementObjectSearcher(\"SELECT * FROM Win32_OperatingSystem\")\n Dim Information As ManagementObjectCollection = searcher.Get()\n If Information IsNot Nothing Then\n For Each obj As ManagementObject In Information\n r = obj(\"Caption\").ToString() & _\n \" - \" & _\n obj(\"OSArchitecture\").ToString() ' <--- !!! \"64-bit\" shown here\n Next\n End If\n MessageBox.Show(r)\nEnd Using\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34022/"
] |
336,640 | <p>If you check my earlier questions you may have noticed I just don't get the SelectList and Html.DropDown(). I find it intrigueing that I seem to be the only one in this. So maybe I should try to change my mindset or maybe there are things I don't know that will clear this all up. I really love the whole MVC framework, but SelectList just doesn't want to fit in my head. So here's my list:</p>
<p><strong>SelectList</strong></p>
<ul>
<li>Why can't I set the selected value after instantiation</li>
<li>Why can't I set selectedValue by index of items</li>
<li>Why is the selectedvalue sometimes a string, sometimes the class I put into it and sometimes a ListItem</li>
<li>Why are the items only accesible through GetItems()</li>
<li>Why don't the types of selectedItem and the listItems match?</li>
<li>Why are the items you put in the list converted to listItem and the selectedItem not?</li>
<li>Why can't I get the count of the items without usint the GetItems() method</li>
</ul>
<p><strong>Html.DropDownList()</strong></p>
<ul>
<li>Why doesn't modelbinding work with it</li>
<li>Why is there no behaviour for defaulting selection when there's only one option </li>
<li>Why doesn't making an item SelectedValue in the source selectLIst make it the marked item</li>
</ul>
<p>Before ppl suggest me to write my own:<br>
Since this will be shipped with the MVC product, I would rather have the offical support for a basic controll then to roll my own and have all the troubles that come with it.</p>
| [
{
"answer_id": 369917,
"author": "argibson",
"author_id": 40130,
"author_profile": "https://Stackoverflow.com/users/40130",
"pm_score": 2,
"selected": false,
"text": "IEnumerable<T> IEnumerable<T>"
},
{
"answer_id": 427195,
"author": "GONeale",
"author_id": 41211,
"author_profile": "https://Stackoverflow.com/users/41211",
"pm_score": 2,
"selected": false,
"text": "<%= Html.DropDownList(\"Module.Status\", new SelectList(ViewData.Model.Statuses, \"ID\", \"Name\", ((int)ViewData.Model.Module.Status)), new {tabindex = 1, title = \"Status\"}) public ActionResult Save(int? id, [Bind(Prefix = \"Module\", \n Include = \"Name,Description,Status\")] Module module)\n module.Status"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
336,654 | <p>I've found the following code from here "<a href="http://www.boyet.com/Articles/CodeFromInternet.html" rel="nofollow noreferrer"><a href="http://www.boyet.com/Articles/CodeFromInternet.html" rel="nofollow noreferrer">http://www.boyet.com/Articles/CodeFromInternet.html</a></a>".<br/>
It returns the speed of the CPU in GHz but works only on 32bit Windows. </p>
<pre><code>using System;
using System.Management;
namespace CpuSpeed
{
class Program
{
static double? GetCpuSpeedInGHz()
{
double? GHz = null;
using (ManagementClass mc = new ManagementClass("Win32_Processor"))
{
foreach (ManagementObject mo in mc.GetInstances())
{
GHz = 0.001 * (UInt32) mo.Properties["CurrentClockSpeed"].Value;
break;
}
}
return GHz;
}
static void Main(string[] args)
{
Console.WriteLine("The current CPU speed is {0}", (GetCpuSpeedInGHz() ?? -1.0).ToString());
Console.ReadLine();
}
}
}
</code></pre>
<p><br/>
I've searched for 64bit management classes, but without success.<br/>
Is there any other method to get the CPU speed under 64bit Windows?</p>
| [
{
"answer_id": 359576,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 3,
"selected": false,
"text": " RegistryKey registrykeyHKLM = Registry.LocalMachine;\n string keyPath = @\"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\";\n RegistryKey registrykeyCPU = registrykeyHKLM.OpenSubKey(keyPath, false);\n string MHz = registrykeyCPU.GetValue(\"~MHz\").ToString();\n string ProcessorNameString = (string)registrykeyCPU.GetValue(\"ProcessorNameString\");\n registrykeyCPU.Close();\n registrykeyHKLM.Close();\n Console.WriteLine(\"{0} MHz for {1}\", MHz, ProcessorNameString);\n"
},
{
"answer_id": 650762,
"author": "Marc",
"author_id": 34022,
"author_profile": "https://Stackoverflow.com/users/34022",
"pm_score": -1,
"selected": true,
"text": "Microsoft.Win32.RegistryKey registrykeyHKLM = Microsoft.Win32.Registry.LocalMachine;\nstring cpuPath = @\"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\";\nMicrosoft.Win32.RegistryKey registrykeyCPUs = registrykeyHKLM.OpenSubKey(cpuPath, false);\nStringBuilder sbCPUDetails = new StringBuilder();\nint iCPUCount;\nfor (iCPUCount = 0; iCPUCount < registrykeyCPUs.SubKeyCount; iCPUCount++)\n{\n Microsoft.Win32.RegistryKey registrykeyCPUDetail = registrykeyHKLM.OpenSubKey(cpuPath + \"\\\\\" + iCPUCount, false);\n string sMHz = registrykeyCPUDetail.GetValue(\"~MHz\").ToString();\n string sProcessorNameString = registrykeyCPUDetail.GetValue(\"ProcessorNameString\").ToString();\n sbCPUDetails.Append(Environment.NewLine + \"\\t\" + string.Format(\"CPU{0}: {1} MHz for {2}\", new object[] { iCPUCount, sMHz, sProcessorNameString }));\n registrykeyCPUDetail.Close();\n}\nregistrykeyCPUs.Close();\nregistrykeyHKLM.Close();\nsCPUSpeed = iCPUCount++ + \" core(s) found:\" + sbCPUDetails.ToString();\n"
},
{
"answer_id": 7095761,
"author": "Jon Norton",
"author_id": 4797,
"author_profile": "https://Stackoverflow.com/users/4797",
"pm_score": 0,
"selected": false,
"text": "Environment.ProcessorCount private float GetCpuClockSpeed()\n{\n return (int) Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\", \"~MHz\", 0);\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34022/"
] |
336,664 | <p>I'm working on a java web application that uses thousands of small files to build artifacts in response to requests. I think our system could see performance improvements if we could map these files into memory rather than run all over the disk to find them all the time. </p>
<p>I have heard of mmap in linux, and my basic understanding of that concept is that when a file is read from disk the file's contents get cached somewhere in memory for quicker subsequent access. What I have in mind is similar to that idea, except I'd like to read the whole mmap-able set of files into memory as my web app is initializing for minimal request-time responses.</p>
<p>One aspect of my thought-train here is that we'd probably get the files into jvm memory faster if they were all tarred up and somehow mounted in the JVM as a virtual file system. As it stands it can take several minutes for our current implementation to walk through the set of source files and just figure out what all is on the disk.. this is because we're essentially doing file stats for upwards of 300,000 files.</p>
<p>I have found the apache VFS project which can read information from a tar file, but I'm not sure from their documentation if you can specify something such as "also, read the entire tar into memory and hold it there..". </p>
<p>We're talking about a multithreaded environment here serving artifacts that usually piece together about 100 different files out of a complete set of 300,000+ source files to make one response. So whatever the virtual file system solution is, it needs to be thread safe and performant. We're only talking about reading files here, no writes. </p>
<p>Also, we're running a 64 bit OS with 32 gig of RAM, our 300,000 files take up about 1.5 to 2.5 gigs of space. We can surely read a 2.5 gigabyte file into memory much quicker than 300K small several-kilobyte-sized files.</p>
<p>Thanks for input!</p>
<ul>
<li>Jason</li>
</ul>
| [
{
"answer_id": 336697,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "mmap() open() mmap()"
},
{
"answer_id": 336704,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 0,
"selected": false,
"text": "mmap"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,665 | <p>I have a VB6 class with a method which raises an error:</p>
<pre><code>Public Sub DoSomething
...
err.Raise 12345, description:="Error message"
...
End Sub
</code></pre>
<p>This method is called from a form:</p>
<pre><code>Public Sub ErrTest()
On Error Goto err1
obj.DoSomething
Exit Sub
err1:
MsgBox err.Description
End Sub
</code></pre>
<p>This works fine at runtime, but at design time the error handling does not work. Instead the VB6 IDE displays its standard message box from where I can go into debug mode or end the program.</p>
<p>Why does this happen? Can I prevent it?</p>
| [
{
"answer_id": 336784,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 4,
"selected": true,
"text": "Err.Raise Err.Raise vbObjectError + 12345, Description:=\"Error message\"\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
336,670 | <p>I'm using xslt to transform xml to an aspx file. In the xslt, I have a script tag to include a jquery.js file. To get it to work with IE, the script tag must have an explicit closing tag. For some reason, this doesn't work with xslt below.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
xmlns:asp="remove">
<xsl:output method="html"/>
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TEST</title>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
</code></pre>
<p>But if I change the script tag as shown below, it works. </p>
<pre><code> <script type="text/javascript" src="jquery-1.2.6.js">
// <![CDATA[ // ]]>
</script>
</code></pre>
<p>I thought that the <code><xsl:output method="html" /></code> would do the trick, but it doesn't seem to work?</p>
<p>/Jonas</p>
| [
{
"answer_id": 505612,
"author": "Chris Chilvers",
"author_id": 35233,
"author_profile": "https://Stackoverflow.com/users/35233",
"pm_score": 3,
"selected": false,
"text": "XmlDocument doc = new XmlDocument();\ndoc.LoadXml(\"<book><author>Trudi Canavan</author><title>Voice of the Gods</title></book>\");\n\nXslCompiledTransform transform = new XslCompiledTransform();\ntransform.Load(\"XSLTFile1.xslt\");\n\nStringBuilder output = new StringBuilder();\n\n// Here we pass the output setting to the writer, otherwise the transform\n// may be set to Html, but the XmlWriter will be outputting Xml\nXmlWriter writer = XmlWriter.Create(output, transform.OutputSettings);\n\ntransform.Transform(doc, writer);\n\nConsole.WriteLine(output.ToString());\nConsole.ReadKey();\n"
},
{
"answer_id": 2573151,
"author": "Diadistis",
"author_id": 47401,
"author_profile": "https://Stackoverflow.com/users/47401",
"pm_score": 1,
"selected": false,
"text": "XmlTextWriter public class HtmlTextWriter : XmlTextWriter\n{\n private readonly string[] fullEndElements = \n new string[] { \"script\", \"title\" };\n\n private string lastStartElement = null;\n\n\n public HtmlTextWriter(TextWriter textWriter)\n : base(textWriter)\n {\n }\n\n public HtmlTextWriter(string filename, Encoding encoding)\n : base(filename, encoding)\n {\n }\n\n public HtmlTextWriter(Stream w, Encoding encoding)\n : base(stream, encoding)\n {\n }\n\n public override void WriteStartElement(string prefix, string localName, string ns)\n {\n lastStartElement = localName;\n base.WriteStartElement(prefix, localName, ns);\n }\n\n public override void WriteEndElement()\n {\n if (Array.IndexOf(fullEndElements, lastStartElement) > -1)\n {\n base.WriteFullEndElement();\n }\n else\n {\n base.WriteEndElement();\n }\n }\n}\n"
},
{
"answer_id": 3290763,
"author": "Bart van Delft",
"author_id": 396880,
"author_profile": "https://Stackoverflow.com/users/396880",
"pm_score": 0,
"selected": false,
"text": "private static Properties XHTML() {\n Properties p = new Properties();\n p.setProperty(OutputKeys.METHOD, \"xhtml\");\n p.setProperty(OutputKeys.DOCTYPE_PUBLIC,\n \"-//W3C//DTD XHTML 1.0 Strict//EN\");\n p.setProperty(OutputKeys.DOCTYPE_SYSTEM,\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\");\n p.setProperty(OutputKeys.ENCODING, \"UTF-8\");\n p.setProperty(\"{http://xml.apache.org/xalan}indent-amount\", \"4\");\n p.setProperty(OutputKeys.INDENT, \"yes\");\n p.setProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n p.setProperty(\"{http://example.com}selfclosing\",\"no\");\n return p;\n }\n selfclosing <div /> <script /> <div></div> <script></script>"
},
{
"answer_id": 5261115,
"author": "BizNuge",
"author_id": 653692,
"author_profile": "https://Stackoverflow.com/users/653692",
"pm_score": 1,
"selected": false,
"text": "<textarea></textarea> <textarea/>\n t.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, \"html\");"
},
{
"answer_id": 6423691,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 1,
"selected": false,
"text": "<Discount>\n <!--<xsl:if test=\"Discount>0\">-->\n <xsl:value-of select=\"Discount\"/>\n <!--</xsl:if>-->\n</Discount>\n <Discount>value of the discount</Discount>\n <Discount>\n <xsl:if test=\"Discount>0\">\n <xsl:value-of select=\"Discount\"/>\n </xsl:if>\n</Discount>\n <Discount/>\n"
},
{
"answer_id": 6764061,
"author": "Fritz W",
"author_id": 854208,
"author_profile": "https://Stackoverflow.com/users/854208",
"pm_score": 2,
"selected": false,
"text": "<xsl:value-of select=\"' '\"/>\n <script...> </script>\n <script ... />.\n"
},
{
"answer_id": 20440855,
"author": "David L.",
"author_id": 1182474,
"author_profile": "https://Stackoverflow.com/users/1182474",
"pm_score": 0,
"selected": false,
"text": "<xsl:text disable-output-escaping=\"yes\">\n <script src=\"jquery-2.0.3.js\"></script>\n</xsl:text>\n"
},
{
"answer_id": 30020824,
"author": "StevenP",
"author_id": 515433,
"author_profile": "https://Stackoverflow.com/users/515433",
"pm_score": 0,
"selected": false,
"text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\">//</script>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,682 | <p>Can I use LoadLibrary method for to import a data of type struct??
excuse me for my English.
thanks.</p>
| [
{
"answer_id": 336752,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 3,
"selected": false,
"text": "bool GetFlubber(Flubber* flubber) Flubber struct LoadLibrary GetProcAddress GetFlubber Flubber GetFlubber"
},
{
"answer_id": 351660,
"author": "reuben",
"author_id": 41646,
"author_profile": "https://Stackoverflow.com/users/41646",
"pm_score": 0,
"selected": false,
"text": "MyPointer = GetProcAddress(..., \"g_MyGlobal\");\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42746/"
] |
336,695 | <p>is there a free set of controls to be used for representing the OLAP cubes in aspx pages? something like the ones from Dundas, but free and (if possible) cross-browser.</p>
<p>Thanks,
Lucian</p>
| [
{
"answer_id": 336752,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 3,
"selected": false,
"text": "bool GetFlubber(Flubber* flubber) Flubber struct LoadLibrary GetProcAddress GetFlubber Flubber GetFlubber"
},
{
"answer_id": 351660,
"author": "reuben",
"author_id": 41646,
"author_profile": "https://Stackoverflow.com/users/41646",
"pm_score": 0,
"selected": false,
"text": "MyPointer = GetProcAddress(..., \"g_MyGlobal\");\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11464/"
] |
336,696 | <p>This java program I am working on seems to hang on startup, so I tried using jconsole to debug the problem.
As it turns out it is waiting on a call to a method which is declared as -</p>
<pre><code>synchronized void stopQuery()
</code></pre>
<p>But here is the crazy part, the lock for the 'synchronized' method is already held by the thread which is blocked for it.
I have attached a screenshot from JConsole after executing the getThreadInfo() MXBean method.<br/><br/>
Notice that the lockOwnerId and threadId are same! How is this even possible?</p>
<p><a href="https://i.stack.imgur.com/TYWk9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TYWk9.png" alt="alt text"></a>
</p>
<p>
<b>Edit:</b> <br/>
<b><a href="http://placidsystems.com/files/stacktrace.txt" rel="nofollow noreferrer"> Link </a></b> to one of the stack traces of this situation.
Note that after looking at the stacktrace it might appear that even the 'org.eclipse.jdt.internal.ui.text.JavaReconciler' thread is trying to lock on to the same DiskIndex object, but if you look at the object address you will see that it is in fact a different DiskIndex object.
</p>
<p><b>Edit 2:</b> <br/>
<b><a href="http://placidsystems.com/files/stacktrace2.txt" rel="nofollow noreferrer">Another Link </a></b> to a different stacktrace I obtained when I reproduced this problem. It should be helpful to compare the two to see what is common.</p>
<p>
</p>
| [
{
"answer_id": 336803,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 0,
"selected": false,
"text": "\"Worker-2\" prio=10 tid=0x00002aad1da66400 nid=0x5165 waiting for monitor entry [0x0000000041b43000..0x0000000041b43b90]\n java.lang.Thread.State: BLOCKED (on object monitor)\n at org.eclipse.jdt.internal.core.index.DiskIndex.stopQuery(DiskIndex.java)\n - waiting to lock <0x00002aacdfe83ea8> (a org.eclipse.jdt.internal.core.index.DiskIndex)\n at org.eclipse.jdt.internal.core.index.Index.stopQuery(Index.java:192)\n \"Text Viewer Hover Presenter\" daemon prio=10 tid=0x00002aad20166400 nid=0x51f4 in Object.wait() [0x000000004254c000..0x000000004254dd90]\n java.lang.Thread.State: WAITING (on object monitor)\n at java.lang.Object.wait(Native Method)\n - waiting on <0x00002aace2276720> (a java.lang.Object)\n at java.lang.Object.wait(Object.java:485)\n at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:450)\n - locked <0x00002aace2276720> (a java.lang.Object)\n at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:129)\n at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo(NLSStringHover.java:87)\n at org.eclipse.jdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover.getHoverInfo2(AbstractJavaEditorTextHover.java:86)\n at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:129)\n at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:82)\n at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:166)\n"
},
{
"answer_id": 338220,
"author": "Bob Cross",
"author_id": 5812,
"author_profile": "https://Stackoverflow.com/users/5812",
"pm_score": 2,
"selected": false,
"text": "\"Text Viewer Hover Presenter\" daemon prio=10 tid=0x00002aad20166400 nid=0x51f4 in Object.wait() [0x000000004254c000..0x000000004254dd90]\n java.lang.Thread.State: WAITING (on object monitor)\n at java.lang.Object.wait(Native Method)\n - waiting on <0x00002aace2276720> (a java.lang.Object)\n at java.lang.Object.wait(Object.java:485)\n at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:450)\n - locked <0x00002aace2276720> (a java.lang.Object)\n at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:129)\n at org.eclipse.jdt.internal.ui.text.java.hover.NLSStringHover.getHoverInfo(NLSStringHover.java:87)\n at org.eclipse.jdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover.getHoverInfo2(AbstractJavaEditorTextHover.java:86)\n at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo2(BestMatchHover.java:129)\n at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo2(JavaEditorTextHoverProxy.java:82)\n at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:166)\n\n\"Worker-3\" prio=10 tid=0x00002aad132c3800 nid=0x5166 in Object.wait() [0x0000000042249000..0x000000004224ab10]\n java.lang.Thread.State: WAITING (on object monitor)\n at java.lang.Object.wait(Native Method)\n - waiting on <0x00002aace2276720> (a java.lang.Object)\n at java.lang.Object.wait(Object.java:485)\n at org.eclipse.jdt.internal.ui.javaeditor.ASTProvider.getAST(ASTProvider.java:450)\n - locked <0x00002aace2276720> (a java.lang.Object)\n at org.eclipse.jdt.ui.SharedASTProvider.getAST(SharedASTProvider.java:129)\n at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:168)\n at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$3.run(SelectionListenerWithASTManager.java:153)\n - locked <0x00002aace2276ad0> (a java.lang.Object)\n at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)\n \"Worker-4\" prio=10 tid=0x00002aad132c4000 nid=0x5167 waiting for monitor entry [0x000000004234b000..0x000000004234bc90]\n java.lang.Thread.State: BLOCKED (on object monitor)\n at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$3.run(SelectionListenerWithASTManager.java:153)\n - waiting to lock <0x00002aace2276ad0> (a java.lang.Object)\n at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)\n\n\"Worker-1\" prio=10 tid=0x00002aad12835800 nid=0x5164 waiting for monitor entry [0x0000000041a42000..0x0000000041a42a10]\n java.lang.Thread.State: BLOCKED (on object monitor)\n at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$3.run(SelectionListenerWithASTManager.java:153)\n - waiting to lock <0x00002aace2276ad0> (a java.lang.Object)\n at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)\n\n\"Worker-0\" prio=10 tid=0x00002aad11a0ac00 nid=0x5146 waiting for monitor entry [0x0000000041941000..0x0000000041941d90]\n java.lang.Thread.State: BLOCKED (on object monitor)\n at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$3.run(SelectionListenerWithASTManager.java:153)\n - waiting to lock <0x00002aace2276ad0> (a java.lang.Object)\n at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14316/"
] |
336,712 | <p>What's the query syntax to determine the exact version number of the MySQL server software?</p>
| [
{
"answer_id": 336718,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 5,
"selected": true,
"text": "SHOW VARIABLES SHOW VARIABLES WHERE Variable_name = 'version';"
},
{
"answer_id": 336874,
"author": "Pawka",
"author_id": 33599,
"author_profile": "https://Stackoverflow.com/users/33599",
"pm_score": 2,
"selected": false,
"text": "mysql --version\n"
},
{
"answer_id": 13008331,
"author": "Nikola",
"author_id": 534755,
"author_profile": "https://Stackoverflow.com/users/534755",
"pm_score": 0,
"selected": false,
"text": "mysql [nikola@localhost]# mysql\nWelcome to the MySQL monitor. Commands end with ; or \\g.\nYour MySQL connection id is 386102\nServer version: 5.1.61 Source distribution\n\nCopyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.\n\nOracle is a registered trademark of Oracle Corporation and/or its\naffiliates. Other names may be trademarks of their respective\nowners.\n\nType 'help;' or '\\h' for help. Type '\\c' to clear the current input statement.\n Server version: 5.1.61 Source distribution"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2899/"
] |
336,714 | <p>I'm beginner in Java. I'm reading data from device through serial port. I'm getting data for every one minute, but first reading is coming half, after that data is coming correctly.</p>
<p>Output I'm getting is: </p>
<blockquote>
<p>6050.003120815340006050.003120815350006050.0</p>
</blockquote>
<p>Correct output should be like this: </p>
<blockquote>
<p>03120815340006050.003120815350006050.0</p>
</blockquote>
<p><br>
My code is:</p>
<pre><code>import java.io.*;
import java.util.*; //import gnu.io.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
byte[] readBuffer;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("portList... " + portList);
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("port identified is Serial.. "
+ portId.getPortType());
if (portId.getName().equals("COM2")) {
System.out.println("port identified is COM2.. "
+ portId.getName());
// if (portId.getName().equals("/dev/term/a")) {
SimpleRead reader = new SimpleRead();
} else {
System.out.println("unable to open port");
}
}
}
}
public SimpleRead() {
try {
System.out.println("In SimpleRead() contructor");
serialPort = (SerialPort) portId.open("SimpleReadApp1111",500);
System.out.println(" Serial Port.. " + serialPort);
} catch (PortInUseException e) {
System.out.println("Port in use Exception");
}
try {
inputStream = serialPort.getInputStream();
System.out.println(" Input Stream... " + inputStream);
} catch (IOException e) {
System.out.println("IO Exception");
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Tooo many Listener exception");
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// no handshaking or other flow control
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// timer on any read of the serial port
serialPort.enableReceiveTimeout(500);
System.out.println("................");
} catch (UnsupportedCommOperationException e) {
System.out.println("UnSupported comm operation");
}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
System.out.println("In run() function ");
Thread.sleep(500);
// System.out.println();
} catch (InterruptedException e) {
System.out.println("Interrupted Exception in run() method");
}
}
public void serialEvent(SerialPortEvent event) {
// System.out.println("In Serial Event function().. " + event +
// event.getEventType());
switch (event.getEventType()) {
/*
* case SerialPortEvent.BI: case SerialPortEvent.OE: case
* SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD:
* case SerialPortEvent.CTS: case SerialPortEvent.DSR: case
* SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break;
*/
case SerialPortEvent.DATA_AVAILABLE:
readBuffer = new byte[8];
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
// System.out.println("Number of bytes read " + numBytes);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {
System.out.println("IO Exception in SerialEvent()");
}
break;
}
// System.out.println();
/* String one = new String(readBuffer);
char two = one.charAt(0);
System.out.println("Character at three: " + two);*/
}
}
</code></pre>
| [
{
"answer_id": 336836,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 2,
"selected": false,
"text": "while (inputStream.available()>0) {\n int numBytes = inputStream.read(readBuffer);\n System.out.print(new String(readBuffer));\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,716 | <p>How can I assert my <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> request and test the JSON output from Ruby on Rails functional tests?</p>
| [
{
"answer_id": 395912,
"author": "nicholaides",
"author_id": 48424,
"author_profile": "https://Stackoverflow.com/users/48424",
"pm_score": 8,
"selected": true,
"text": "ActionDispatch::TestResponse#parsed_body user = @response.parsed_body\nassert_equal \"Mike\", user['name']\n JSON.parse user = JSON.parse(@response.body)\nassert_equal \"Mike\", user['name']\n"
},
{
"answer_id": 2481515,
"author": "Eric",
"author_id": 297819,
"author_profile": "https://Stackoverflow.com/users/297819",
"pm_score": 2,
"selected": false,
"text": "assert_equal '{\"total_votes\":1}', @response.body\n"
},
{
"answer_id": 3534520,
"author": "Josh",
"author_id": 423384,
"author_profile": "https://Stackoverflow.com/users/423384",
"pm_score": 7,
"selected": false,
"text": "def json_response\n ActiveSupport::JSON.decode @response.body\nend\n assert_equal \"Mike\", json_response['name']\n"
},
{
"answer_id": 17621503,
"author": "Damien",
"author_id": 1059843,
"author_profile": "https://Stackoverflow.com/users/1059843",
"pm_score": 1,
"selected": false,
"text": "assert_equal assigns(:user).to_json, @response.body\n"
},
{
"answer_id": 21117068,
"author": "rkallensee",
"author_id": 650203,
"author_profile": "https://Stackoverflow.com/users/650203",
"pm_score": -1,
"selected": false,
"text": "Gemfile group :test do\n gem 'assert_json'\nend\n class ExampleControllerTest < ActionController::TestCase\n include AssertJson\n\n def test_my_action\n get :my_action, :format => 'json'\n # => @response.body= '{\"key\":[{\"inner_key\":\"value1\"}]}'\n\n assert_json(@response.body) do\n has 'key' do\n has 'inner_key', 'value1'\n end\n has_not 'key_not_included'\n end\n end\n\nend\n AssertJson assert_json def test_my_action\n get :my_action, :format => 'json'\n # => @response.body= '[\"value1\", \"value2\"]'\n\n assert_json(@response.body) do\n has 'value1'\n has 'value2'\n has_not 'value3'\n end\n end\n"
},
{
"answer_id": 36857571,
"author": "Vedant Agarwala",
"author_id": 1396264,
"author_profile": "https://Stackoverflow.com/users/1396264",
"pm_score": 2,
"selected": false,
"text": "schema = {\n \"type\"=>\"object\",\n \"required\" => [\"a\"],\n \"properties\" => {\n \"a\" => {\n \"type\" => \"integer\",\n \"default\" => 42\n },\n \"b\" => {\n \"type\" => \"object\",\n \"properties\" => {\n \"x\" => {\n \"type\" => \"integer\"\n }\n }\n }\n }\n}\n JSON::Validator.validate(schema, { \"a\" => 5 })"
},
{
"answer_id": 53752482,
"author": "Mark G.",
"author_id": 443839,
"author_profile": "https://Stackoverflow.com/users/443839",
"pm_score": 2,
"selected": false,
"text": "parsed_body"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16371/"
] |
336,731 | <p>How do I create a view dynamically in SQL Server using C#?</p>
| [
{
"answer_id": 336740,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 2,
"selected": false,
"text": "query = \" Create View [Viewname] Select ....\";\n"
},
{
"answer_id": 336863,
"author": "Coolcoder",
"author_id": 42434,
"author_profile": "https://Stackoverflow.com/users/42434",
"pm_score": 4,
"selected": true,
"text": "SqlConnection conn = null;\nconn = new SqlConnection(\"yourConnectionString\");\nconn.Open();\nstring strSQLCommand = \"CREATE VIEW vw_YourView AS SELECT YOurColumn FROM YourTable\";\nSqlCommand command = new SqlCommand(strSQLCommand, conn); \nstring returnvalue = (string)command.ExecuteScalar(); \nconn.Close();\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18709/"
] |
336,755 | <p>In C# is it guaranteed that expressions are evaluated left to right? </p>
<p>For example:</p>
<pre><code>myClass = GetClass();
if (myClass == null || myClass.Property > 0)
continue;
</code></pre>
<p>Are there any languages that do not comply?</p>
| [
{
"answer_id": 336770,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "||"
},
{
"answer_id": 336772,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "MyClass == null myClass.Property > 0 MyClass == null"
},
{
"answer_id": 336832,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "or and"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,756 | <p>This code is not working on IE8 at all. FF3 is executing but the page is blank and seems loading not ending.</p>
<p>My code is:</p>
<pre><code>$("#leaderBoard").html("<script2 language=\"javascript2\"> document.write('<scr'+'ipt language=\"javascript21.1\">alert(1)</scri'+'pt>'); </script2>".replace(/script2/gi, "script"));
</code></pre>
<p>I want to let page load ad on ready.</p>
| [
{
"answer_id": 336807,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function() {\n // your code here\n});\n"
},
{
"answer_id": 336812,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "$(document).ready( function() {\n $(\"#leaderBoard\").load(\"/ad_generator.php\");\n});\n ad_generator.php"
},
{
"answer_id": 337326,
"author": "user37125",
"author_id": 37125,
"author_profile": "https://Stackoverflow.com/users/37125",
"pm_score": 3,
"selected": false,
"text": "$(\"#leaderBoard\").html('<sc'+'ript language=\"javascript1.1\">alert(1);</sc'+'ript>');\n"
},
{
"answer_id": 1721740,
"author": "Mihai Lazar",
"author_id": 4204,
"author_profile": "https://Stackoverflow.com/users/4204",
"pm_score": 0,
"selected": false,
"text": "document.write()\n $('.myDiv').html('<script src=\"path\\/to-add\\/provider\"><\\/script>');\n"
},
{
"answer_id": 3838341,
"author": "asnazrul",
"author_id": 463759,
"author_profile": "https://Stackoverflow.com/users/463759",
"pm_score": 1,
"selected": false,
"text": "//////////////////function in page's script section\n\nfunction aFunction (x) {\n\n ////script you want to execute\n\n alert(x);\n\n}\n\n//////////////////////in page's body\n\nvar d = $(\"<div />\");\nd.ready(function(){aFunction(\"x\");});\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,759 | <p>I am curious to know How the Loader Maps DLL in to Process Address Space. How loader does that magic. Example is highly appreciated.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 6375826,
"author": "0xC0000022L",
"author_id": 476371,
"author_profile": "https://Stackoverflow.com/users/476371",
"pm_score": 3,
"selected": false,
"text": "DLLMain()"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38038/"
] |
336,771 | <p>I'd like to run some C++ code while the Windows Mobile PocketPC is (or seems) being suspended. An example what I mean is the HTC Home plugin that shows (among others) a tab where the HTC Audio Manager can be used to play back mp3 files. When I press the on/off button, the display goes black, but the audio keeps playing. The only button to switch back on is the on/off button, as expected.</p>
<p>What I tried so far is to capture hardware button presses (works) and switch off the video display (works). What doesn't work with this approach is that when (accidentally) pressing any key on the device, the video display is switched on. I think this isn't the approach taken in the HTC Audio Manager.</p>
<p>I'm guessing on some low-level API magic for this to work, or that the code to play back audio runs at some interrupt level, or the device goes into a different suspend mode.</p>
| [
{
"answer_id": 917695,
"author": "vividos",
"author_id": 23740,
"author_profile": "https://Stackoverflow.com/users/23740",
"pm_score": 3,
"selected": true,
"text": "PowerPolicyNotify(PPN_UNATTENDEDMODE, TRUE) SetPowerRequirement(L\"gpd0:\", D0, POWER_NAME|POWER_FORCE, NULL, NULL) RequestPowerNotifications(hMsgQueue, PBT_POWERINFOCHANGE | PBT_TRANSITION) POWER_BROADCAST PBT_TRANSITION pPwrBrodcast->SystemPowerState SystemIdleTimerReset() PowerPolicyNotify() ReleasePowerRequirement() StopPowerNotifications()"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23740/"
] |
336,775 | <p>Continuing <a href="https://stackoverflow.com/questions/308481/writing-the-f-recursive-folder-visitor-in-c-seq-vs-ienumerable">my investigation</a> of expressing F# ideas in C#, I wanted a pipe forward operator. For anything wrapped in a IEnumerable, we already have it, as you can .NextFunc() to your heart's content. But for example if you have any fold-like reduction at the end, you can't feed the result of that into a function.</p>
<p>Here are two extension methods, I wondered if anyone else had tried this, and if it's a good idea or not (EDIT: now with <a href="http://#337846" rel="noreferrer">Earwicker's Maybe</a> included):</p>
<pre><code>public static void Pipe<T>(this T val, Action<T> action) where T : class
{ if (val!=null) action(val); }
public static R Pipe<T, R>(this T val, Func<T, R> func) where T : class where R : class
{ return val!=null?func(val):null; }
</code></pre>
<p>You can then write something like: </p>
<pre><code>Func<string, string[]> readlines = (f) => File.ReadAllLines(f);
Action<string, string> writefile = (f, s) => File.WriteAllText(f, s);
Action<string, string> RemoveLinesContaining = (file, text) =>
{
file.Pipe(readlines)
.Filter(s => !s.Contains(text))
.Fold((val, sb) => sb.AppendLine(val), new StringBuilder())
.Pipe((o) => o.ToString())
.Pipe((s) => writefile(file, s));
};
</code></pre>
<p>(I know, Filter == Where in C#, and Fold==Aggregate, but I wanted to roll my own, and I could have done WriteAllLines, but that's not the point)</p>
<p>EDIT: corrections as per Earwicker's comment (if I've understood correctly).</p>
| [
{
"answer_id": 336805,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "IEnumerable<T>"
},
{
"answer_id": 337846,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 6,
"selected": true,
"text": "public static class ReferenceExtensions\n{\n public static TOut IfNotNull<TIn, TOut>(this TIn v, Func<TIn, TOut> f)\n where TIn : class \n where TOut: class\n {\n if (v == null)\n return null;\n\n return f(v);\n }\n}\n var pixiesDrummer = Music.GetCompany(\"4ad.com\")\n .GetBand(\"Pixes\")\n .GetMember(\"David\");\n var pixiesDrummer = Music.GetCompany(\"4ad.com\")\n .IfNotNull(rc => rc.GetBand(\"Pixes\"))\n .IfNotNull(band => band.GetMember(\"David\"));\n public static TOut operator| <TIn, TOut>(TIn v, Func<TIn, TOut> f)\n var pixiesDrummer = Music.GetCompany(\"4ad.com\") \n | rc => rc.GetBand(\"Pixes\")\n | band => band.GetMember(\"David\");\n let (|>) x f = f x\n var n = Enumerable.Select(numbers, m => m * 2);\n var n = numbers.Select(m => m * 2);\n"
},
{
"answer_id": 5246009,
"author": "Jonas Elfström",
"author_id": 44620,
"author_profile": "https://Stackoverflow.com/users/44620",
"pm_score": 1,
"selected": false,
"text": "public static T Into<T>(this T obj, Func<T, T> f)\n{ return f(obj); }\n"
},
{
"answer_id": 32017111,
"author": "jbtule",
"author_id": 637783,
"author_profile": "https://Stackoverflow.com/users/637783",
"pm_score": 3,
"selected": false,
"text": "Pipe PipeR PipeR new [] { \"Joe\", \"Jane\", \"Janet\" }.Pipe(\", \", String.Join)\n \"One car red car blue Car\".PipeR(@\"(\\w+)\\s+(car)\",RegexOptions.IgnoreCase, Regex.IsMatch)\n Regex.IsMatch PipeR public static TR Pipe<T,TR>(this T target, Func<T, TR> func)\n{\n return func(target);\n}\n\npublic static TR Pipe<T,T1, TR>(this T target, T1 arg1, Func<T1, T, TR> func)\n{\n return func(arg1, target);\n}\n\npublic static TR Pipe<T, T1, T2, TR>(this T target, T1 arg1, T2 arg2, Func<T1, T2, T, TR> func)\n{\n return func(arg1, arg2, target);\n}\n\npublic static TR PipeR<T, T1, TR>(this T target, T1 arg1, Func<T, T1, TR> func)\n{\n return func(target, arg1);\n}\n\npublic static TR PipeR<T, T1, T2, TR>(this T target, T1 arg1, T2 arg2, Func<T, T1, T2, TR> func)\n{\n return func(target, arg1, arg2);\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
336,781 | <p>How can I read a Chinese text file using C#, my current code can't display the correct characters:</p>
<pre><code>try
{
using (StreamReader sr = new StreamReader(path,System.Text.Encoding.UTF8))
{
// This is an arbitrary size for this example.
string c = null;
while (sr.Peek() >= 0)
{
c = null;
c = sr.ReadLine();
Console.WriteLine(c);
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
</code></pre>
| [
{
"answer_id": 336786,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "Encoding.Unicode"
},
{
"answer_id": 336797,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "using (StreamReader sr = new StreamReader(path, appropriateEncoding))\n{\n string line;\n while ( (line = sr.ReadLine()) != null)\n {\n // ...\n }\n}\n"
},
{
"answer_id": 3542254,
"author": "didier",
"author_id": 427716,
"author_profile": "https://Stackoverflow.com/users/427716",
"pm_score": 3,
"selected": false,
"text": "// gb2312 (codepage 936) :\nSystem.Text.Encoding.GetEncoding(936)\n\n// Big5 (codepage 950) :\nSystem.Text.Encoding.GetEncoding(950)"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
336,813 | <p>I understand they both don't change the URL that the client sees. Is there anything in them that makes one of them preferable over the other?<br>
I'm planning to use it in the Application_BeginRequest in Global.asax, but also in regular aspx page.</p>
| [
{
"answer_id": 336829,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 4,
"selected": true,
"text": "Context.RewritePath() Server.Transfer() ThreadAbortException Response.End() Server.Transfer() Response.Redirect() RewritePath() Server.Transfer() Server.Execute() Server.Execute() <div>\n test 1 <br/>\n <% Server.Execute(\"include.aspx?hello=ok\"); %>\n test 2 <br/>\n</div>\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278/"
] |
336,814 | <p>Session transcript:</p>
<pre><code>> type lookma.c
int main() {
printf("%s", "no stdio.h");
}
> cl lookma.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
lookma.c
Microsoft (R) Incremental Linker Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
/out:lookma.exe
lookma.obj
> lookma
no stdio.h
</code></pre>
| [
{
"answer_id": 336825,
"author": "Chris Young",
"author_id": 9417,
"author_profile": "https://Stackoverflow.com/users/9417",
"pm_score": 5,
"selected": false,
"text": "int printf();\n"
},
{
"answer_id": 336844,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 3,
"selected": false,
"text": "printf() int"
},
{
"answer_id": 341974,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 6,
"selected": true,
"text": "printf() #include <stdio.h> printf() int extern int pqr();\nint main(void)\n{\n int i = pqr(1, 3);\n return i;\n}\n pqr() extern pqr(); pqr() int int -std=c99 -pedantic pqr()"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310/"
] |
336,817 | <p>I have a user control that I'm building. It's purpose is to display the status of a class to the user. Obviously, this does not matter, and will slow things down when the control runs in the IDE, as it does as soon as you add it to a form.</p>
<p>One way to work around this would be to have the control created and added to the controls collection of the form at run-time. But this seems less than perfect.</p>
<p>Is there a way to set a flag in the control so that it can skip certain sections of code based on how it is running?</p>
<p>p.s. I'm using C# and VS 2008</p>
| [
{
"answer_id": 336830,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 5,
"selected": true,
"text": "public static bool IsInRuntimeMode( IComponent component ) {\n bool ret = IsInDesignMode( component );\n return !ret;\n}\n\npublic static bool IsInDesignMode( IComponent component ) {\n bool ret = false;\n if ( null != component ) {\n ISite site = component.Site;\n if ( null != site ) {\n ret = site.DesignMode;\n }\n else if ( component is System.Windows.Forms.Control ) {\n IComponent parent = ( (System.Windows.Forms.Control)component ).Parent;\n ret = IsInDesignMode( parent );\n }\n }\n\n return ret;\n}\n"
},
{
"answer_id": 15572241,
"author": "Ben Gripka",
"author_id": 530658,
"author_profile": "https://Stackoverflow.com/users/530658",
"pm_score": 3,
"selected": false,
"text": "using System.ComponentModel;\n\nif (LicenseManager.UsageMode == LicenseUsageMode.Runtime)\n{\n}\n"
},
{
"answer_id": 52566040,
"author": "qaqz111",
"author_id": 5972372,
"author_profile": "https://Stackoverflow.com/users/5972372",
"pm_score": 0,
"selected": false,
"text": "//use a Property or Field for keeping the info to avoid runtime computation\npublic static bool NotInDesignMode { get; } = IsNotInDesignMode();\nprivate static bool IsNotInDesignMode()\n{\n /*\n File.WriteAllLines(@\"D:\\1.log\", new[]\n {\n LicenseManager.UsageMode.ToString(), //not always reliable, e.g. WPF app in Blend this will return RunTime\n Process.GetCurrentProcess().ProcessName, //filename without extension\n Process.GetCurrentProcess().MainModule.FileName, //full path\n Process.GetCurrentProcess().MainModule.ModuleName, //filename\n Assembly.GetEntryAssembly()?.Location, //null for WinForms app in VS IDE\n Assembly.GetEntryAssembly()?.ToString(), //null for WinForms app in VS IDE\n Assembly.GetExecutingAssembly().Location, //always return your project's output assembly info\n Assembly.GetExecutingAssembly().ToString(), //always return your project's output assembly info\n });\n //*/\n\n //LicenseManager.UsageMode will return RunTime if LicenseManager.context is not present.\n //So you can not return true by judging it's value is RunTime.\n if (LicenseUsageMode.Designtime == LicenseManager.UsageMode) return false;\n var procName = Process.GetCurrentProcess().ProcessName.ToLower();\n return \"devenv\" != procName //WinForms app in VS IDE\n && \"xdesproc\" != procName //WPF app in VS IDE/Blend\n && \"blend\" != procName //WinForms app in Blend\n //other IDE's process name if you detected by log from above\n ;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6389/"
] |
336,826 | <p>SQL Server Full Text Search uses language specific Word Breakers. </p>
<p>For the German language this is used to break/split words including compound words. However, it appears not all known compound words are included in the Word Breaker. I would like to know if a list is available of the words the Word Breaker does know about.</p>
| [
{
"answer_id": 336830,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 5,
"selected": true,
"text": "public static bool IsInRuntimeMode( IComponent component ) {\n bool ret = IsInDesignMode( component );\n return !ret;\n}\n\npublic static bool IsInDesignMode( IComponent component ) {\n bool ret = false;\n if ( null != component ) {\n ISite site = component.Site;\n if ( null != site ) {\n ret = site.DesignMode;\n }\n else if ( component is System.Windows.Forms.Control ) {\n IComponent parent = ( (System.Windows.Forms.Control)component ).Parent;\n ret = IsInDesignMode( parent );\n }\n }\n\n return ret;\n}\n"
},
{
"answer_id": 15572241,
"author": "Ben Gripka",
"author_id": 530658,
"author_profile": "https://Stackoverflow.com/users/530658",
"pm_score": 3,
"selected": false,
"text": "using System.ComponentModel;\n\nif (LicenseManager.UsageMode == LicenseUsageMode.Runtime)\n{\n}\n"
},
{
"answer_id": 52566040,
"author": "qaqz111",
"author_id": 5972372,
"author_profile": "https://Stackoverflow.com/users/5972372",
"pm_score": 0,
"selected": false,
"text": "//use a Property or Field for keeping the info to avoid runtime computation\npublic static bool NotInDesignMode { get; } = IsNotInDesignMode();\nprivate static bool IsNotInDesignMode()\n{\n /*\n File.WriteAllLines(@\"D:\\1.log\", new[]\n {\n LicenseManager.UsageMode.ToString(), //not always reliable, e.g. WPF app in Blend this will return RunTime\n Process.GetCurrentProcess().ProcessName, //filename without extension\n Process.GetCurrentProcess().MainModule.FileName, //full path\n Process.GetCurrentProcess().MainModule.ModuleName, //filename\n Assembly.GetEntryAssembly()?.Location, //null for WinForms app in VS IDE\n Assembly.GetEntryAssembly()?.ToString(), //null for WinForms app in VS IDE\n Assembly.GetExecutingAssembly().Location, //always return your project's output assembly info\n Assembly.GetExecutingAssembly().ToString(), //always return your project's output assembly info\n });\n //*/\n\n //LicenseManager.UsageMode will return RunTime if LicenseManager.context is not present.\n //So you can not return true by judging it's value is RunTime.\n if (LicenseUsageMode.Designtime == LicenseManager.UsageMode) return false;\n var procName = Process.GetCurrentProcess().ProcessName.ToLower();\n return \"devenv\" != procName //WinForms app in VS IDE\n && \"xdesproc\" != procName //WPF app in VS IDE/Blend\n && \"blend\" != procName //WinForms app in Blend\n //other IDE's process name if you detected by log from above\n ;\n}\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42434/"
] |
336,854 | <p>Specifically, once I get the WCAG Anaylsis warnings for a website into my warnings window I can't get rid of them, until I close down studio. When building another project in the same solution they stay there.</p>
<p>Anyone got any ideas?</p>
| [
{
"answer_id": 336972,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 0,
"selected": false,
"text": "website -> property pages -> accessibility -> uncheck \"show warnings\"\n window -> close all documents\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39643/"
] |
336,859 | <p>I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.</p>
<p>The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.</p>
<p>The two ways are:</p>
<pre><code>var functionOne = function() {
// Some code
};
</code></pre>
<pre><code>function functionTwo() {
// Some code
}
</code></pre>
<p>What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?</p>
| [
{
"answer_id": 336868,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 13,
"selected": true,
"text": "functionOne functionTwo // TypeError: functionOne is not a function\nfunctionOne();\n\nvar functionOne = function() {\n console.log(\"Hello!\");\n}; // Outputs: \"Hello!\"\nfunctionTwo();\n\nfunction functionTwo() {\n console.log(\"Hello!\");\n} 'use strict'; \n{ // note this block!\n function functionThree() {\n console.log(\"Hello!\");\n }\n}\nfunctionThree(); // ReferenceError"
},
{
"answer_id": 338053,
"author": "Eugene Lazutkin",
"author_id": 26394,
"author_profile": "https://Stackoverflow.com/users/26394",
"pm_score": 11,
"selected": false,
"text": "function abc(){} abc function xyz(){\n function abc(){};\n // abc is defined here...\n}\n// ...but not here\n var xyz = function abc(){};\n xyz abc var xyz = function abc(){\n // xyz is visible here\n // abc is visible here\n}\n// xyz is visible here\n// abc is undefined here\n function abc(){};\nvar xyz = abc;\n xyz abc console.log(xyz === abc); // prints \"true\"\n function abc(){};\nconsole.log(abc.name); // prints \"abc\"\n var abc = function(){};\nconsole.log(abc.name); // prints \"\"\n // Assume really.long.external.scoped is {}\nreally.long.external.scoped.name = function shortcut(n){\n // Let it call itself recursively:\n shortcut(n - 1);\n // ...\n // Let it pass itself as a callback:\n someFunction(shortcut);\n // ...\n}\n arguments.callee function abc(){}\n abc // We can call it here\nabc(); // Works\n\n// Yet, it is defined down there.\nfunction abc(){}\n\n// We can call it again\nabc(); // Works\n return // We can call it here\nabc(); // Works\nreturn;\nfunction abc(){}\n var xyz = function(){};\n xyz // We can't call it here\nxyz(); // UNDEFINED!!!\n\n// Now it is defined\nxyz = function(){}\n\n// We can call it here\nxyz(); // works\n var xyz = function abc(){};\nconsole.log(xyz.name); // Prints \"abc\"\n var abc = function(){};\n abc = function(){};\n abc eval() function abc(){};\n eval()"
},
{
"answer_id": 2124597,
"author": "Sasha Firsov",
"author_id": 257553,
"author_profile": "https://Stackoverflow.com/users/257553",
"pm_score": 5,
"selected": false,
"text": "{\n member:function() { /* How do I make \"this.member\" a named function? */\n }\n}\n"
},
{
"answer_id": 2672637,
"author": "thomasrutter",
"author_id": 53212,
"author_profile": "https://Stackoverflow.com/users/53212",
"pm_score": 7,
"selected": false,
"text": "var functionOne = function() {} function functionTwo() foo foo eval()"
},
{
"answer_id": 3435763,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 7,
"selected": false,
"text": "var FunctionDeclaration var undefined FunctionDeclaration alert(typeof foo); // 'function', it's already available\n alert(typeof bar); // 'undefined'\n function foo () {}\n var bar = function () {};\n alert(typeof bar); // 'function'\n bar FunctionExpression FunctionDeclaration function test () {}\n test = null;\n foo = function() { alert('hello!'); }; var var ReferenceError FunctionDeclaration"
},
{
"answer_id": 3435811,
"author": "Rob",
"author_id": 341616,
"author_profile": "https://Stackoverflow.com/users/341616",
"pm_score": 6,
"selected": false,
"text": "var MyNamespace = {}\nMyNamespace.foo= function() {\n\n}\n var MyNamespace = {\n foo: function() {\n },\n ...\n}\n"
},
{
"answer_id": 5185403,
"author": "Sean McMillan",
"author_id": 117587,
"author_profile": "https://Stackoverflow.com/users/117587",
"pm_score": 7,
"selected": false,
"text": "(function(){\n var exports = {};\n\n function privateUtil() {\n ...\n }\n\n exports.publicUtil = function() {\n ...\n };\n\n return exports;\n})();\n"
},
{
"answer_id": 11809755,
"author": "Joel Purra",
"author_id": 907779,
"author_profile": "https://Stackoverflow.com/users/907779",
"pm_score": 5,
"selected": false,
"text": "shortcut() yell() function assert(predicate, message) { if(!predicate) { throw new Error(message); } }\n\nvar ninja = {\n yell: function(n){\nreturn n > 0 ? ninja.yell(n-1) + \"a\" : \"hiy\";\n }\n};\nassert( ninja.yell(4) == \"hiyaaaa\", \"A single object isn't too bad, either.\" ); \n\nvar samurai = { yell: ninja.yell };\nvar ninja = null;\n\ntry {\n samurai.yell(4);\n} catch(e){\n assert( false, \"Uh, this isn't good! Where'd ninja.yell go?\" );\n} function assert(predicate, message) { if(!predicate) { throw new Error(message); } }\n\nvar ninja = {\n yell: function yell(n){\nreturn n > 0 ? yell(n-1) + \"a\" : \"hiy\";\n }\n};\nassert( ninja.yell(4) == \"hiyaaaa\", \"Works as we would expect it to!\" );\n \nvar samurai = { yell: ninja.yell };\nvar ninja = {};\nassert( samurai.yell(4) == \"hiyaaaa\", \"The method correctly calls itself.\" );\n\nconsole.log(samurai.yell(4));"
},
{
"answer_id": 12893927,
"author": "Ingo Kegel",
"author_id": 936832,
"author_profile": "https://Stackoverflow.com/users/936832",
"pm_score": 4,
"selected": false,
"text": "var functionOne = function() {\n // Some code\n};\n var one = new functionOne();\n one.constructor.name Function.name function functionTwo() {\n // Some code\n}\ntwo = new functionTwo();\n two.constructor.name"
},
{
"answer_id": 14175010,
"author": "NullPoiиteя",
"author_id": 1723893,
"author_profile": "https://Stackoverflow.com/users/1723893",
"pm_score": 4,
"selected": false,
"text": "var doSomething = function(x){ alert(x);} doSomething function foo() {\n return 3;\n}\n // Anonymous function expression\nvar a = function() {\n return 3;\n}\n\n// Named function expression\nvar a = function foo() {\n return 3;\n}\n\n// Self-invoking function expression\n(function foo() {\n alert(\"hello!\");\n})();\n"
},
{
"answer_id": 14734001,
"author": "eljenso",
"author_id": 30316,
"author_profile": "https://Stackoverflow.com/users/30316",
"pm_score": 5,
"selected": false,
"text": "undefined var foo = 1;\nfunction bar() {\n if (!foo) {\n var foo = 10 }\n return foo; }\nbar() // 10\n foo undefined !foo true foo 10 foo bar function f() {\n return a; \n function a() {return 1}; \n var a = 4;\n function a() {return 2}}\nf()() // 2\n\nfunction f() {\n return a;\n var a = 4;\n function a() {return 1};\n function a() {return 2}}\nf()() // 2\n function f() {\n var a = 4;\n function a() {return 1}; \n function a() {return 2}; \n return a; }\nf() // 4\n a 4 var a = 1;\nfunction b() {\n a = 10;\n return;\n function a() {}}\nb();\na // 1\n a 10 a"
},
{
"answer_id": 15704206,
"author": "Mbengue Assane",
"author_id": 288258,
"author_profile": "https://Stackoverflow.com/users/288258",
"pm_score": 6,
"selected": false,
"text": "if (condition){\n function myfunction(){\n // Some code\n }\n}\n myfunction if (condition){\n var myfunction = function (){\n // Some code\n }\n}\n myfunction condition"
},
{
"answer_id": 19595198,
"author": "Pawel Furmaniak",
"author_id": 221315,
"author_profile": "https://Stackoverflow.com/users/221315",
"pm_score": 4,
"selected": false,
"text": "var objectOne = new functionOne();\nconsole.log(objectOne.__proto__); // prints \"Object {}\" because constructor is an anonymous function\n\nvar objectTwo = new functionTwo();\nconsole.log(objectTwo.__proto__); // prints \"functionTwo {}\" because constructor is a named function\n"
},
{
"answer_id": 22173438,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 10,
"selected": false,
"text": "function function class function x() {\n console.log('x');\n}\n ; x x(); // Works even though it's above the declaration\nfunction x() {\n console.log('x');\n}\n try if switch while if (someCondition) {\n function foo() { // <===== HERE THERE\n } // <===== BE DRAGONS\n}\n \"use strict\";\nif (someCondition) {\n foo(); // Works just fine\n function foo() {\n }\n}\nconsole.log(typeof foo); // \"undefined\" (`foo` is not in scope here\n // because it's not in the same block)\n function var y = function () {\n console.log('y');\n};\n y SetFunctionName function var z = function w() {\n console.log('zw')\n};\n w var z = function w() {\n console.log(typeof w); // \"function\"\n};\nconsole.log(typeof w); // \"undefined\"\n var obj = {\n value: 0,\n get f() {\n return this.value;\n },\n set f(v) {\n this.value = v;\n }\n};\nconsole.log(obj.f); // 0\nconsole.log(typeof obj.f); // \"number\"\n () Object.defineProperty Object.defineProperties Object.create var a = [1, 2, 3];\nvar b = a.map(n => n * 2);\nconsole.log(b.join(\", \")); // 2, 4, 6\n n => n * 2 map() this this arguments super this this function => n => n * 2 var a = [1, 2, 3];\nvar b = a.map((n, i) => n * i);\nconsole.log(b.join(\", \")); // 0, 2, 6\n Array#map return {} return var a = [\n {first: \"Joe\", last: \"Bloggs\"},\n {first: \"Albert\", last: \"Bloggs\"},\n {first: \"Mary\", last: \"Albright\"}\n];\na = a.sort((a, b) => {\n var rv = a.last.localeCompare(b.last);\n if (rv === 0) {\n rv = a.first.localeCompare(b.first);\n }\n return rv;\n});\nconsole.log(JSON.stringify(a));\n { ... } { ... } var o = {\n foo() {\n }\n};\n var o = {\n foo: function foo() {\n }\n};\n super valueOf super.valueOf() Object.prototype.valueOf Object.prototype.valueOf.call(this) Object.assign super class class class Person {\n constructor(firstName, lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n }\n\n getFullName() {\n return this.firstName + \" \" + this.lastName;\n }\n}\n Person getFullName Person.prototype"
},
{
"answer_id": 24055237,
"author": "sla55er",
"author_id": 2454402,
"author_profile": "https://Stackoverflow.com/users/2454402",
"pm_score": 5,
"selected": false,
"text": "function abc(){}\n var abc = function() {};\n //this will work\nabc(param);\nfunction abc(){}\n\n//this would fail\nabc(param);\nvar abc = function() {}\n"
},
{
"answer_id": 25214775,
"author": "suhailvs",
"author_id": 2351696,
"author_profile": "https://Stackoverflow.com/users/2351696",
"pm_score": 7,
"selected": false,
"text": "functionTwo();\nfunction functionTwo() {\n}\n hoisted functionOne(); --------------- var functionOne;\n | is actually | functionOne();\nvar functionOne = function(){ | interpreted |-->\n}; | like | functionOne = function(){\n --------------- };\n functionTwo(); --------------- function functionTwo() {\n | is actually | };\nfunction functionTwo() { | interpreted |-->\n} | like | functionTwo();\n ---------------\n"
},
{
"answer_id": 26320800,
"author": "Jackson",
"author_id": 1468130,
"author_profile": "https://Stackoverflow.com/users/1468130",
"pm_score": 4,
"selected": false,
"text": "[].forEach(function iterator() {});\n 'use strict';\n\nvar a = function () {\n throw new Error();\n},\n b = function b() {\n throw new Error();\n },\n c = function d() {\n throw new Error();\n },\n e = {\n f: a,\n g: b,\n h: c,\n i: function () {\n throw new Error();\n },\n j: function j() {\n throw new Error();\n },\n k: function l() {\n throw new Error();\n }\n },\n m = (function () {\n return function () {\n throw new Error();\n };\n }()),\n n = (function () {\n return function n() {\n throw new Error();\n };\n }()),\n o = (function () {\n return function p() {\n throw new Error();\n };\n }());\n\nconsole.log([a, b, c].concat(Object.keys(e).reduce(function (values, key) {\n return values.concat(e[key]);\n}, [])).concat([m, n, o]).reduce(function (logs, func) {\n\n try {\n func();\n } catch (error) {\n return logs.concat('func.name: ' + func.name + '\\n' +\n 'Trace:\\n' +\n error.stack);\n // Need to manually log the error object in Nitro.\n }\n\n}, []).join('\\n\\n'));\n func.name: \nTrace:\nError\n at a (http://localhost:8000/test.js:4:11)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: b\nTrace:\nError\n at b (http://localhost:8000/test.js:7:15)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: d\nTrace:\nError\n at d (http://localhost:8000/test.js:10:15)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: \nTrace:\nError\n at a (http://localhost:8000/test.js:4:11)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: b\nTrace:\nError\n at b (http://localhost:8000/test.js:7:15)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: d\nTrace:\nError\n at d (http://localhost:8000/test.js:10:15)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: \nTrace:\nError\n at e.i (http://localhost:8000/test.js:17:19)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: j\nTrace:\nError\n at j (http://localhost:8000/test.js:20:19)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: l\nTrace:\nError\n at l (http://localhost:8000/test.js:23:19)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: \nTrace:\nError\n at http://localhost:8000/test.js:28:19\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: n\nTrace:\nError\n at n (http://localhost:8000/test.js:33:19)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27\n\nfunc.name: p\nTrace:\nError\n at p (http://localhost:8000/test.js:38:19)\n at http://localhost:8000/test.js:47:9\n at Array.reduce (native)\n at http://localhost:8000/test.js:44:27 test.js:42\n func.name: \nTrace:\na@http://localhost:8000/test.js:4:5\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: b\nTrace:\nb@http://localhost:8000/test.js:7:9\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: d\nTrace:\nd@http://localhost:8000/test.js:10:9\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: \nTrace:\na@http://localhost:8000/test.js:4:5\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: b\nTrace:\nb@http://localhost:8000/test.js:7:9\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: d\nTrace:\nd@http://localhost:8000/test.js:10:9\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: \nTrace:\ne.i@http://localhost:8000/test.js:17:13\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: j\nTrace:\nj@http://localhost:8000/test.js:20:13\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: l\nTrace:\nl@http://localhost:8000/test.js:23:13\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: \nTrace:\nm</<@http://localhost:8000/test.js:28:13\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: n\nTrace:\nn@http://localhost:8000/test.js:33:13\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n\n\nfunc.name: p\nTrace:\np@http://localhost:8000/test.js:38:13\n@http://localhost:8000/test.js:47:9\n@http://localhost:8000/test.js:54:1\n func.name: undefined\nTrace:\nError\n at a (http://localhost:8000/test.js:4:5)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at b (http://localhost:8000/test.js:7:9)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at d (http://localhost:8000/test.js:10:9)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at a (http://localhost:8000/test.js:4:5)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at b (http://localhost:8000/test.js:7:9)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at d (http://localhost:8000/test.js:10:9)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at e.i (http://localhost:8000/test.js:17:13)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at j (http://localhost:8000/test.js:20:13)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at l (http://localhost:8000/test.js:23:13)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at Anonymous function (http://localhost:8000/test.js:28:13)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at n (http://localhost:8000/test.js:33:13)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n\n\nfunc.name: undefined\nTrace:\nError\n at p (http://localhost:8000/test.js:38:13)\n at Anonymous function (http://localhost:8000/test.js:47:9)\n at Global code (http://localhost:8000/test.js:42:1)\n func.name: \nTrace:\na@http://localhost:8000/test.js:4:22\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: b\nTrace:\nb@http://localhost:8000/test.js:7:26\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: d\nTrace:\nd@http://localhost:8000/test.js:10:26\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: \nTrace:\na@http://localhost:8000/test.js:4:22\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: b\nTrace:\nb@http://localhost:8000/test.js:7:26\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: d\nTrace:\nd@http://localhost:8000/test.js:10:26\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: \nTrace:\ni@http://localhost:8000/test.js:17:30\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: j\nTrace:\nj@http://localhost:8000/test.js:20:30\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: l\nTrace:\nl@http://localhost:8000/test.js:23:30\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: \nTrace:\nhttp://localhost:8000/test.js:28:30\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: n\nTrace:\nn@http://localhost:8000/test.js:33:30\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n\nfunc.name: p\nTrace:\np@http://localhost:8000/test.js:38:30\nhttp://localhost:8000/test.js:47:13\nreduce@[native code]\nglobal code@http://localhost:8000/test.js:44:33\n"
},
{
"answer_id": 31533124,
"author": "Rohan",
"author_id": 2730064,
"author_profile": "https://Stackoverflow.com/users/2730064",
"pm_score": 5,
"selected": false,
"text": "var foo = function foo() {};\n function foo() {};\n var function function foo() {};\n var foo = function foo() {};\n var foo = undefined;\nfoo = function foo() {};\n"
},
{
"answer_id": 32477146,
"author": "varna",
"author_id": 1625434,
"author_profile": "https://Stackoverflow.com/users/1625434",
"pm_score": 4,
"selected": false,
"text": "function outerFunction() {\n function foo() {\n return 1;\n }\n return foo();\n function foo() {\n return 2;\n }\n}\nalert(outerFunction()); // Displays 2\n function foo() { // The first function declaration is moved to top\n return 1;\n}\nfunction foo() { // The second function declaration is moved to top\n return 2;\n}\nfunction outerFunction() {\n return foo();\n}\nalert(outerFunction()); //So executing from top to bottom,\n //the last foo() returns 2 which gets displayed\n function outerFunction() {\n var foo = function() {\n return 1;\n }\n return foo();\n var foo = function() {\n return 2;\n }\n}\nalert(outerFunction()); // Displays 1\n function outerFunction() {\n var foo = undefined;\n var foo = undefined;\n\n foo = function() {\n return 1;\n };\n return foo ();\n foo = function() { // This function expression is not reachable\n return 2;\n };\n}\nalert(outerFunction()); // Displays 1\n if (test) {\n function x() { doSomething(); }\n}\n var today = function today() {return new Date()}\n"
},
{
"answer_id": 34500152,
"author": "Nitin9791",
"author_id": 2873883,
"author_profile": "https://Stackoverflow.com/users/2873883",
"pm_score": 4,
"selected": false,
"text": "functionOne();\nvar functionOne = function() {\n // Some code\n};\n functionOne();\nfunction functionOne() {\n // Some code\n}\n"
},
{
"answer_id": 34995357,
"author": "Yash",
"author_id": 5081877,
"author_profile": "https://Stackoverflow.com/users/5081877",
"pm_score": 6,
"selected": false,
"text": "global_Page = 10; var global_Page; « undefined\n « Integer literal, Number Type. ------------------- global_Page = 10; « Number \nglobal_Page = 'Yash'; | Interpreted | global_Page = 'Yash'; « String\n « String literal, String Type. « AS « global_Page = true; « Boolean \nvar global_Page = true; | | global_Page = function (){ « function\n « Boolean Type ------------------- var local_functionblock; « undefined\nglobal_Page = function (){ local_functionblock = 777;« Number\n var local_functionblock = 777; }; \n // Assigning function as a data.\n}; \n function Identifier_opt ( FormalParameterList_opt ) { \n FunctionBody | sequence of statements\n\n « return; Default undefined\n « return 'some data';\n}\n Scope with respect to function-block global. \nScope with respect to page undefined | not available.\n function globalAccess() { function globalAccess() { \n} ------------------- }\nglobalAccess(); | | function globalAccess() { « Re-Defined / overridden.\nlocalAccess(); « Hoisted As « function localAccess() {\nfunction globalAccess() { | | }\n localAccess(); ------------------- localAccess(); « function accessed with in globalAccess() only.\n function localAccess() { }\n } globalAccess();\n} localAccess(); « ReferenceError as the function is not defined\n 10; « literal\n (10); « Expression (10).toString() -> '10'\nvar a; \n a = 10; « Expression var a.toString() -> '10'\n(function invoke() { « Expression Function\n console.log('Self Invoking'); (function () {\n}); }) () -> 'Self Invoking'\n\nvar f; \n f = function (){ « Expression var Function\n console.log('var Function'); f () -> 'var Function'\n };\n (function selfExecuting(){\n console.log('IIFE - Immediately-Invoked Function Expression');\n}());\n\nvar anonymous = function (){\n console.log('anonymous function Expression');\n};\n\nvar namedExpression = function for_InternalUSE(fact){\n if(fact === 1){\n return 1;\n }\n\n var localExpression = function(){\n console.log('Local to the parent Function Scope');\n };\n globalExpression = function(){ \n console.log('creates a new global variable, then assigned this function.');\n };\n\n //return; //undefined.\n return fact * for_InternalUSE( fact - 1); \n};\n\nnamedExpression();\nglobalExpression();\n var anonymous;\nvar namedExpression;\nvar globalExpression;\n\nanonymous = function (){\n console.log('anonymous function Expression');\n};\n\nnamedExpression = function for_InternalUSE(fact){\n var localExpression;\n\n if(fact === 1){\n return 1;\n }\n localExpression = function(){\n console.log('Local to the parent Function Scope');\n };\n globalExpression = function(){ \n console.log('creates a new global variable, then assigned this function.');\n };\n\n return fact * for_InternalUSE( fact - 1); // DEFAULT UNDEFINED.\n};\n\nnamedExpression(10);\nglobalExpression();\n jsperf Test Runner function Shape(id) { // Function Declaration\n this.id = id;\n};\n // Adding a prototyped method to a function.\n Shape.prototype.getID = function () {\n return this.id;\n };\n Shape.prototype.setID = function ( id ) {\n this.id = id;\n };\n\nvar expFn = Shape; // Function Expression\n\nvar funObj = new Shape( ); // Function Object\nfunObj.hasOwnProperty('prototype'); // false\nfunObj.setID( 10 );\nconsole.log( funObj.getID() ); // 10\n ArrowFunction : ArrowParameters => ConciseBody const fn = (item) => { return item & 1 ? 'Odd' : 'Even'; };\nconsole.log( fn(2) ); // Even\nconsole.log( fn(3) ); // Odd\n"
},
{
"answer_id": 37131496,
"author": "SuperNova",
"author_id": 3464971,
"author_profile": "https://Stackoverflow.com/users/3464971",
"pm_score": 3,
"selected": false,
"text": "new Function() var func = new Function(\"x\", \"y\", \"return x*y;\");\nfunction secondFunction(){\n var result;\n result = func(10,20);\n console.log ( result );\n}\n\nsecondFunction()\n"
},
{
"answer_id": 38940765,
"author": "Anoop Rai",
"author_id": 6698976,
"author_profile": "https://Stackoverflow.com/users/6698976",
"pm_score": 4,
"selected": false,
"text": "function fn(){\n console.log(\"Hello\");\n}\nfn();\n var fn=function(){\n console.log(\"Hello\");\n}\nfn();\n"
},
{
"answer_id": 43871841,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 4,
"selected": false,
"text": "var functionOne = function() {\n // Some code\n};\n function functionTwo() {\n // Some code\n}\n"
},
{
"answer_id": 46461041,
"author": "Panos Kalatzantonakis",
"author_id": 266068,
"author_profile": "https://Stackoverflow.com/users/266068",
"pm_score": 4,
"selected": false,
"text": "V8 SpiderMonkey Anonymous Named"
},
{
"answer_id": 48256045,
"author": "Jack G",
"author_id": 5601591,
"author_profile": "https://Stackoverflow.com/users/5601591",
"pm_score": 6,
"selected": false,
"text": "function add() try {\n console.log(\"Success: \", add(1, 1));\n} catch(e) {\n console.log(\"ERROR: \" + e);\n}\n\nfunction add(a, b){\n return a + b;\n} add try {\n console.log(\"Success: \", add(1, 1));\n} catch(e) {\n console.log(\"ERROR: \" + e);\n}\n\nvar add=function(a, b){\n return a + b;\n} add = undefined var add; var add=undefined var add = undefined;\n\ntry {\n console.log(\"Success: \", add(1, 1));\n} catch(e) {\n console.log(\"ERROR: \" + e);\n}\n\nadd = function(a, b){\n return a + b;\n} var add= function add() function add() try {\n console.log(\"Success: \", add(1, 1));\n} catch(e) {\n console.log(\"ERROR: \" + e);\n}\n\nvar add=function add(a, b){\n return a + b;\n} function thefuncname(){} function foobar(a, b){}\n\nconsole.log(foobar.name); var a = function foobar(){};\n\nconsole.log(a.name); function(){} var a = function(){};\nvar b = (function(){ return function(){} });\n\nconsole.log(a.name);\nconsole.log(b.name); \"\" console.log((function(){}).name === \"\"); var a = function(){};\nvar b = a;\nvar c = b;\n\nconsole.log(a.name);\nconsole.log(b.name);\nconsole.log(c.name); var (function(){\n \"use strict\";\n var foobar = function(){}; // initial value\n try {\n foobar = \"Hello World!\"; // new value\n console.log(\"[no error]\");\n } catch(error) {\n console.log(\"ERROR: \" + error.message);\n }\n console.log(foobar, window.foobar);\n})(); const arr = [] arr[10] = \"example\" arr = \"new value\" arr = [] (function(){\n \"use strict\";\n const foobar = function(){}; // initial value\n try {\n foobar = \"Hello World!\"; // new value\n console.log(\"[no error]\");\n } catch(error) {\n console.log(\"ERROR: \" + error.message);\n }\n console.log(foobar, window.foobar);\n})(); function funcName(){} var (function(){\n \"use strict\";\n function foobar(){}; // initial value\n try {\n foobar = \"Hello World!\"; // new value\n console.log(\"[no error]\");\n } catch(error) {\n console.log(\"ERROR: \" + error.message);\n }\n console.log(foobar, window.foobar);\n})(); function functionName() {} var functionName = function() {} var add=function(){} try {\n // typeof will simply return \"undefined\" if the variable does not exist\n if (typeof add !== \"undefined\") {\n add(1, 1); // just to prove it\n console.log(\"Not a block\");\n }else if(add===undefined){ // this throws an exception if add doesn't exist\n console.log('Behaves like var add=function(a,b){return a+b}');\n }\n} catch(e) {\n console.log(\"Is a block\");\n}\nvar add=function(a, b){return a + b} function add(){} try {\n // typeof will simply return \"undefined\" if the variable does not exist\n if (typeof add !== \"undefined\") {\n add(1, 1); // just to prove it\n console.log(\"Not a block\");\n }else if(add===undefined){ // this throws an exception if add doesn't exist\n console.log('Behaves like var add=function(a,b){return a+b}')\n }\n} catch(e) {\n console.log(\"Is a block\");\n}\nfunction add(a, b){\n return a + b;\n} try {\n // typeof will simply return \"undefined\" if the variable does not exist\n if (typeof add !== \"undefined\") {\n add(1, 1); // just to prove it\n console.log(\"Not a block\");\n }else if(add===undefined){ // this throws an exception if add doesn't exist\n console.log('Behaves like var add=function(a,b){return a+b}')\n }\n} catch(e) {\n console.log(\"Is a block\");\n}\n(function () {\n function add(a, b){\n return a + b;\n }\n})(); if else for while try catch finally switch do while with try {\n // typeof will simply return \"undefined\" if the variable does not exist\n if (typeof add !== \"undefined\") {\n add(1, 1); // just to prove it\n console.log(\"Not a block\");\n }else if(add===undefined){ // this throws an exception if add doesn't exist\n console.log('Behaves like var add=function(a,b){return a+b}')\n }\n} catch(e) {\n console.log(\"Is a block\");\n}\n{\n function add(a, b){\n return a + b;\n }\n} var add=function() try {\n // typeof will simply return \"undefined\" if the variable does not exist\n if (typeof add !== \"undefined\") {\n add(1, 1); // just to prove it\n console.log(\"Not a block\");\n }else if(add===undefined){ // this throws an exception if add doesn't exist\n console.log('Behaves like var add=function(a,b){return a+b}')\n }\n} catch(e) {\n console.log(\"Is a block\");\n}\n(() => {\n var add=function(a, b){\n return a + b;\n }\n})(); function add() try {\n // typeof will simply return \"undefined\" if the variable does not exist\n if (typeof add !== \"undefined\") {\n add(1, 1); // just to prove it\n console.log(\"Not a block\");\n }else if(add===undefined){ // this throws an exception if add doesn't exist\n console.log('Behaves like var add=function(a,b){return a+b}')\n }\n} catch(e) {\n console.log(\"Is a block\");\n}\n(() => {\n function add(a, b){\n return a + b;\n }\n})();"
},
{
"answer_id": 49172390,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "let first = function(x){\n return x[0];\n}\n function first(){\n ....\n}\n let safe = function(f){\n try {f()...}\n}\nlet last = safe(function(x){return x[0]}).\n let last = x => x[0]\n ...........\n function last(x){\n return x[0];\n }\n......\n\nlet last = safe(x => x[0]);\n"
},
{
"answer_id": 50340725,
"author": "Santosh Pillai",
"author_id": 4418897,
"author_profile": "https://Stackoverflow.com/users/4418897",
"pm_score": 2,
"selected": false,
"text": "a = 10\noutput : 10\n\n(1 + 3)\noutput = 4\n if (1 > 2) {\n // do something. \n}\n // test.js\n\nvar a = 10;\n\n// function expression\nvar fun_expression = function() {\n console.log(\"Running function Expression\");\n}\n\n// funciton expression\n\nfunction fun_declaration() {\n console.log(\"Running function Statement\");\n}\n // test.js\n\nconsole.log(a) //output: udefined (No error)\nconsole.log(fun_expression) // output: undefined (No error)\nconsole.log(fun_expression()) // output: Error. As we trying to invoke undefined. \nconsole.log(fun_declaration()) // output: running function statement (As fun_declaration is already hoisted in the memory). \n\nvar a = 10;\n\n// function expression\nvar fun_expression = function() {\n console.log('Running function expression')\n}\n\n// function declaration\n\nfunction fun_declaration() {\n console.log('running function declaration')\n}\n\nconsole.log(a) // output: 10\nconsole.log(fun_expression()) //output: Running function expression\nconsole.log(fun_declaration()) //output: running function declaration\n"
},
{
"answer_id": 51344002,
"author": "Kean Amaral",
"author_id": 9531203,
"author_profile": "https://Stackoverflow.com/users/9531203",
"pm_score": 3,
"selected": false,
"text": "var getRectArea = function(width, height) {\n return width * height;\n};\n\nconsole.log(\"Area of Rectangle: \" + getRectArea(3,4));\n// This should return the following result in the console: \n// Area of Rectangle: 12\n var w = 5;\nvar h = 6;\n\nfunction RectArea(width, height) { //declaring the function\n return area = width * height;\n} //note you do not need ; after }\n\nRectArea(w,h); //calling or executing the function\nconsole.log(\"Area of Rectangle: \" + area);\n// This should return the following result in the console: \n// Area of Rectangle: 30\n"
},
{
"answer_id": 52880785,
"author": "Nitesh Ranjan",
"author_id": 9095122,
"author_profile": "https://Stackoverflow.com/users/9095122",
"pm_score": 2,
"selected": false,
"text": "sum(1,2);\n\nconst sum = function(first, second) {\n return first + second;\n}\n sum(1,2);\n\nfunction sum(first, second) {\n return first + second;\n}\n"
},
{
"answer_id": 53819807,
"author": "Shakespear",
"author_id": 5889158,
"author_profile": "https://Stackoverflow.com/users/5889158",
"pm_score": 4,
"selected": false,
"text": "var functionOne = function() {\n // do something...\n};\n function functionTwo () {\n // do something...\n}\n setTimeout(function timeHandler() { // <-- look, a name here!\n console.log(\"I've waited 1 second\");\n}, 1000);\n (function IIFE(str) { // <-- look, always name IIFEs!\n console.log(str); // \"Hello!\"\n})('Hello!');\n"
},
{
"answer_id": 54002344,
"author": "H.Ostwal",
"author_id": 7750626,
"author_profile": "https://Stackoverflow.com/users/7750626",
"pm_score": 1,
"selected": false,
"text": " var functionOne = (function() {\n return {\n\n sayHello: function(){\n console.log('say hello')\n\n },\n redirectPage:function(_url){\n window.location.href = _url;\n }\n\n }\n})();\n"
},
{
"answer_id": 56683631,
"author": "Willem van der Veen",
"author_id": 8059459,
"author_profile": "https://Stackoverflow.com/users/8059459",
"pm_score": 2,
"selected": false,
"text": "undefined try {\n functionOne();\n} catch (e) {\n console.log('i cant run because im not hoisted');\n}\n\nfunctionTwo();\n\n// function expression, does not get hoisted\nlet functionOne = function randomName() {\n // Some code\n};\n\n// function declaration, gets hoisted\nfunction functionTwo() {\n console.log('I get hoisted');\n}\n\ntry {\n randomName(); // this isn't the proper name, it is functionOne\n} catch (e) {\n console.log('You cant call me with randomName my name is function one');\n}"
},
{
"answer_id": 60503227,
"author": "Robin Hossain",
"author_id": 3528282,
"author_profile": "https://Stackoverflow.com/users/3528282",
"pm_score": 1,
"selected": false,
"text": "var functionOne = function() {} function functionTwo() {} // Run-Time function declaration \nfunctionOne(); // Calling functionOne function here will give an Error\nvar functionOne = function () {\n // Some code\n};\n\n// Parse-Time function declaration \nfunctionTwo(); // Calling functionTwo function will not give an Error\nfunction functionTwo() {\n // Some code...\n}\n"
},
{
"answer_id": 63801906,
"author": "shreyasm-dev",
"author_id": 12984567,
"author_profile": "https://Stackoverflow.com/users/12984567",
"pm_score": 2,
"selected": false,
"text": ".bind() function x() {\n console.log(this)\n}.bind('string')\n\nx() var x = function() {\n console.log(this)\n}.bind('string')\n\nx()"
},
{
"answer_id": 68602977,
"author": "root",
"author_id": 5231110,
"author_profile": "https://Stackoverflow.com/users/5231110",
"pm_score": 2,
"selected": false,
"text": "function functionName() {} functionName() var functionName = function() {}"
},
{
"answer_id": 69662058,
"author": "S.G",
"author_id": 16348733,
"author_profile": "https://Stackoverflow.com/users/16348733",
"pm_score": 1,
"selected": false,
"text": "try {\n console.log(\"Success: \", add(1, 1));\n} catch(e) {\n console.log(\"ERROR: \" + e);\n}\n\nvar add=function(a, b){\n return a + b;\n}"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31569/"
] |
336,866 | <p>I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python <code>SimpleHTTPServer.SimpleHTTPRequestHandler</code>?</p>
<p>A simple example would be a textfield and a button. When the button is pressed the content of the field is send to the server which then sends back a corresponding answer. I am aware that there are many powerful solutions for this in Python, but I would like to keep this very simple.
I already found some nice examples for such a server (e.g. <a href="http://msdl.cs.mcgill.ca/people/julien/04Ajax" rel="noreferrer">here</a>), but so far I could not come up with a truly minimal one.</p>
<p>In case you wonder why I want to implement the GUI in such a way: My focus for this application is to display lots of data in a nice layout with only minimal interaction - so using HTML+CSS seems most convenient (and I have been already using it for non-interactive data display).</p>
| [
{
"answer_id": 336894,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": false,
"text": "from wsgiref.simple_server import make_server, demo_app\n\nhttpd = make_server('', 8000, demo_app)\nprint \"Serving HTTP on port 8000...\"\n\n# Respond to requests until process is killed\nhttpd.serve_forever()\n"
},
{
"answer_id": 338519,
"author": "nikow",
"author_id": 11992,
"author_profile": "https://Stackoverflow.com/users/11992",
"pm_score": 7,
"selected": true,
"text": "import threading\nimport webbrowser\nimport BaseHTTPServer\nimport SimpleHTTPServer\n\nFILE = 'frontend.html'\nPORT = 8080\n\n\nclass TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):\n \"\"\"The test example handler.\"\"\"\n\n def do_POST(self):\n \"\"\"Handle a post request by returning the square of the number.\"\"\"\n length = int(self.headers.getheader('content-length')) \n data_string = self.rfile.read(length)\n try:\n result = int(data_string) ** 2\n except:\n result = 'error'\n self.wfile.write(result)\n\n\ndef open_browser():\n \"\"\"Start a browser after waiting for half a second.\"\"\"\n def _open_browser():\n webbrowser.open('http://localhost:%s/%s' % (PORT, FILE))\n thread = threading.Timer(0.5, _open_browser)\n thread.start()\n\ndef start_server():\n \"\"\"Start the server.\"\"\"\n server_address = (\"\", PORT)\n server = BaseHTTPServer.HTTPServer(server_address, TestHandler)\n server.serve_forever()\n\nif __name__ == \"__main__\":\n open_browser()\n start_server()\n <html>\n<head>\n<title>AJAX test</title>\n</head>\n<body>\n<script type=\"text/javascript\">\n\nfunction xml_http_post(url, data, callback) {\n var req = false;\n try {\n // Firefox, Opera 8.0+, Safari\n req = new XMLHttpRequest();\n }\n catch (e) {\n // Internet Explorer\n try {\n req = new ActiveXObject(\"Msxml2.XMLHTTP\");\n }\n catch (e) {\n try {\n req = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n catch (e) {\n alert(\"Your browser does not support AJAX!\");\n return false;\n }\n }\n }\n req.open(\"POST\", url, true);\n req.onreadystatechange = function() {\n if (req.readyState == 4) {\n callback(req);\n }\n }\n req.send(data);\n}\n\nfunction test_button() {\n var data = document.test_form.test_text.value; \n xml_http_post(\"frontend.html\", data, test_handle)\n}\n\nfunction test_handle(req) {\n var elem = document.getElementById('test_result')\n elem.innerHTML = req.responseText\n}\n\n</script>\n\n<form name=test_form>\nsqr(\n<input type=\"text\" name=\"test_text\" value=\"0\" size=\"4\">\n) =\n<span id=\"test_result\">0</span>\n<input type=button onClick=\"test_button();\" value=\"start\" title=\"start\">\n</form>\n\n</body>\n</html>\n import threading\nimport webbrowser\nfrom wsgiref.simple_server import make_server\n\nFILE = 'frontend.html'\nPORT = 8080\n\ndef test_app(environ, start_response):\n if environ['REQUEST_METHOD'] == 'POST':\n try:\n request_body_size = int(environ['CONTENT_LENGTH'])\n request_body = environ['wsgi.input'].read(request_body_size)\n except (TypeError, ValueError):\n request_body = \"0\"\n try:\n response_body = str(int(request_body) ** 2)\n except:\n response_body = \"error\"\n status = '200 OK'\n headers = [('Content-type', 'text/plain')]\n start_response(status, headers)\n return [response_body]\n else:\n response_body = open(FILE).read()\n status = '200 OK'\n headers = [('Content-type', 'text/html'),\n ('Content-Length', str(len(response_body)))]\n start_response(status, headers)\n return [response_body]\n\ndef open_browser():\n \"\"\"Start a browser after waiting for half a second.\"\"\"\n def _open_browser():\n webbrowser.open('http://localhost:%s/%s' % (PORT, FILE))\n thread = threading.Timer(0.5, _open_browser)\n thread.start()\n\ndef start_server():\n \"\"\"Start the server.\"\"\"\n httpd = make_server(\"\", PORT, test_app)\n httpd.serve_forever()\n\nif __name__ == \"__main__\":\n open_browser()\n start_server()\n"
},
{
"answer_id": 26004385,
"author": "JonB",
"author_id": 1887912,
"author_profile": "https://Stackoverflow.com/users/1887912",
"pm_score": 0,
"selected": false,
"text": "webbrowser.open('file:///home/jon/workspace/webpages/frontend_example/%s' % FILE)\n// skipped the port part\nhttpd = make_server(\"\", 8080, test_app)\n// hardcoded it here.\n"
},
{
"answer_id": 46924680,
"author": "Aditya Shankar",
"author_id": 6743697,
"author_profile": "https://Stackoverflow.com/users/6743697",
"pm_score": 2,
"selected": false,
"text": "<body>\n<button id=\"runButton\">Run</button>\n<script type=\"text/javascript\">\nfunction xml_http_post(url, data) {\nvar req = new XMLHttpRequest();\nreq.open(\"POST\", url, true);\nreq.onreadystatechange = function() {\n if (req.readyState == 4) {\n console.log(req.responseText);\n }\n}\nreq.send(data);\n}\n\nfunction runbuttonfunc() {\n xml_http_post(\"frontend.html\", \"I sent you this message\")\n}\n\ndocument.getElementById(\"runButton\").onclick = runbuttonfunc;\n</script>\n</body>\n import http.server\n\nFILE = 'frontend.html'\nPORT = 8000\n\n\nclass TestHandler(http.server.SimpleHTTPRequestHandler):\n \"\"\"The test example handler.\"\"\"\n\n def do_POST(self):\n \"\"\"Handle a post request by returning the square of the number.\"\"\"\n print(self.headers)\n length = int(self.headers.get_all('content-length')[0])\n print(self.headers.get_all('content-length'))\n data_string = self.rfile.read(length)\n print(data_string)\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/plain\")\n self.end_headers()\n self.flush_headers()\n self.wfile.write(\"I got it!\".encode())\n\n\ndef start_server():\n \"\"\"Start the server.\"\"\"\n server_address = (\"\", PORT)\n server = http.server.HTTPServer(server_address, TestHandler)\n server.serve_forever()\n\nstart_server()\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11992/"
] |
336,884 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c">Can’t operator == be applied to generic types in C#?</a> </p>
</blockquote>
<p>I've got the following generic class and the compiler complains that "<code>Operator '!=' cannot be applied to operands of type 'TValue' and 'TValue'</code>" (see <a href="http://msdn.microsoft.com/en-us/library/a63h61ky.aspx" rel="nofollow noreferrer">CS0019</a>):</p>
<pre><code>public class Example<TValue>
{
private TValue _value;
public TValue Value
{
get { return _value; }
set
{
if (_value != value) // <<-- ERROR
{
_value= value;
OnPropertyChanged("Value");
}
}
}
}
</code></pre>
<p>If I constrain <code>TValue</code> to <code>class</code>, I could use <code>Object.Equals()</code>. Since I need this for boths structs and classes I'd be very happy if I could avoid that though. </p>
<p>So the question is, how can I compare two elements of the same but unconstrained generic type for equality?</p>
| [
{
"answer_id": 336913,
"author": "Sergiu Damian",
"author_id": 41345,
"author_profile": "https://Stackoverflow.com/users/41345",
"pm_score": 5,
"selected": true,
"text": "public class Example<TValue>\n{\n private TValue _value;\n public TValue Value\n {\n get { return _value; }\n set\n {\n\n if (!object.Equals(_value, value))\n {\n _value = value;\n OnPropertyChanged(\"Value\");\n }\n }\n }\n}\n"
},
{
"answer_id": 336968,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 0,
"selected": false,
"text": "!= != == != int != int !="
},
{
"answer_id": 336970,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 1,
"selected": false,
"text": "public class Example<TValue> where TValue: IComparable\n{\n private TValue _value;\n public TValue Value\n {\n get { return _value; }\n set\n {\n\n if (_value.CompareTo(value) != 0)\n {\n _value = value;\n OnPropertyChanged(\"Value\");\n }\n }\n }\n}\n"
},
{
"answer_id": 336987,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "IEquatable<TValue> x.Equals(y) IEqualityComparer<TValue> EqualityComparer<TValue>.Default"
},
{
"answer_id": 6691627,
"author": "lkurylo",
"author_id": 453396,
"author_profile": "https://Stackoverflow.com/users/453396",
"pm_score": 0,
"selected": false,
"text": "public static bool operator ==(EntityBase<T> entity1, EntityBase<T> entity2)\n {\n if ((object)entity1 == null && (object)entity2 == null)\n {\n return true;\n }\n\n if ((object)entity1 == null || (object)entity2 == null)\n {\n return false;\n }\n\n if (Comparer<T>.Default.Compare(entity1.Id, entity2.Id) != 0)\n {\n return false;\n }\n\n return true;\n }\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
336,897 | <p>In a webservice I see this code:</p>
<pre><code><WebMethod()> _
Public Function dosomething() As Boolean
Try
If successful Then
Return True
Else
Return False
End If
Catch ex As Exception
Throw ex
End Try
End Function
</code></pre>
<p>What's the point of catching the exception and just throwing it again? Do I miss something?</p>
<p>Edit:
Thanks for the answers! I thought it was something like that, but wasn't sure if I could/would refactor those away without any implications.</p>
| [
{
"answer_id": 336914,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 6,
"selected": false,
"text": "throw; throw ex;"
},
{
"answer_id": 336934,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": -1,
"selected": false,
"text": "try {\n // Something stupid\n}\ncatch(RuntimeException e) {\n throw e; //Handle it outside\n}\ncatch (Exception e) {\n // I'm dead\n}\n"
},
{
"answer_id": 30742941,
"author": "Jay",
"author_id": 103206,
"author_profile": "https://Stackoverflow.com/users/103206",
"pm_score": 1,
"selected": false,
"text": "return successful\n"
},
{
"answer_id": 37347068,
"author": "ROBERTREAD1",
"author_id": 3306172,
"author_profile": "https://Stackoverflow.com/users/3306172",
"pm_score": 0,
"selected": false,
"text": "Dim lockObj As New Object()\n\nIf Monitor.TryEnter(lockObj) Then\n Try\n ' The critical section.\n Catch\n throw\n Finally\n ' Ensure that the lock is released.\n Monitor.Exit(lockObj)\n End Try\nEnd If\n"
},
{
"answer_id": 57432110,
"author": "Nathan",
"author_id": 5875316,
"author_profile": "https://Stackoverflow.com/users/5875316",
"pm_score": 0,
"selected": false,
"text": " Sub CatchAndRethrowImplicitly()\n Try\n ThrowException()\n Catch e As ArithmeticException\n ' Satisfies the rule.\n Throw\n End Try\n End Sub\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19307/"
] |
336,903 | <p>Is there in Windows API or in MFC any analog to <code>atoh()</code> function?</p>
<p><code>atoh()</code> converts a string containing a hexadecimal number into an unsigned number like</p>
<pre><code>unsigned x = atoh("A");
</code></pre>
<p>and x = 10 after the operation.</p>
<p>In Windows I have a CString, containing "A". How can I convert it to int?</p>
| [
{
"answer_id": 336908,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "unsigned long ten = strtoul(\"a\", NULL, 16); char * strtoul()"
},
{
"answer_id": 336910,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 4,
"selected": true,
"text": "long x = strtoul(\"A\", (char **) NULL, 16);\n// x will be 10 decimal\n"
}
] | 2008/12/03 | [
"https://Stackoverflow.com/questions/336903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4378/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.