content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: What is the optimal way to organize shared .net assemblies in SVN? We are starting a new SOA project with a lot of shared .net assemblies. The code for these assemblies will be stored in SVN. In development phase, we would like to be able to code these assemblies as an entire solution with as little SVN 'friction' as possible. When the project enters more of a maintenance mode, the assemblies will be maintained on an individual level. Without making Branching, Tagging, and Automated Builds a maintenance nightmare, what's the best way to organize these libraries in SVN that also works well with the VS 2008 IDE? Do you setup Trunk/Branches/Tags at each library level and try to spaghetti it all together somehow at compile time, or is it better to keep it all as one big project with code replicated here and there for simplicity? Is there a solution using externs? A: What we did at our company was to set up a tools repository, and then a project repository. The tools repository is a Subversion repository, organized as follows: /svn/tools/ vendor1/ too11/ 1.0/ 1.1/ latest = a copy of vendor1/tool1/1.1 tool2/ 1.0/ 1.5/ latest = a copy of vendor1/tool2/1.5 vendor2/ foo/ 1.0.0/ 1.1.0/ 1.2.0/ latest = a copy of vendor2/foo/1.2.0 Every time we get a new version of a tool from a vendor, it is added under its vendor, name, and version number, and the 'latest' tag is updated. [Clarification: this is NOT a typical source respository -- it's intended to store specific versions of 'installed' images. Thus /svn/tools/nunit/nunit2/2.4 would be the top of a directory tree containing the results of installing NUnit 2.4 to a directory and importing it into the tools repository. Source and examples may be present, but the primary focus is on executables and libraries that are necessary to use the tool. If we needed to modify a vendor tool, we'd do that in a separate repository, and release the result to this repository.] One of the vendors is my company, and has a separate section for each tool, assembly, whatever that we release internally. The projects repository is a standard Subversion repository, with trunks, tags, and branches as you normally expect. Any given project will look like: /svn/ branches/ tags/ trunk/ foo/ source/ tools/ publish/ foo-build.xml (for NAnt) foo.build (for MSBuild) The tools directory has a Subversion svn:externals property set, that links in the appropriate version (either a specific version or 'latest') of each tool or assembly that is needed by that project. When the 'foo' project is built by CruiseControl.NET, the publish task will populate the 'publish' directory as the 'foo' assembly is intended to be deployed, and then executes the following subversion commands: svn import publish /svn/tools/vendor2/foo/1.2.3 svn delete /svn/tools/vendor2/foo/latest svn copy /svn/tools/vendor2/foo/1.2.3 /svn/tools/vendor2/foo/latest Developers work on their projects as normal, and let the build automation take care of the details. A normal subversion update will pull the latest versions of external tools as well as as project updates. If you've got a lot of tool interdependency, you can configure CruiseControl.NET (by hand) to trigger builds for subordinate projects when their dependencies change, but we haven't needed to go that far yet. Note: All of the Subversion repository paths have been shortened for clarity. We actually use Apache+SVN, and two separate servers, but you should adapt this as you see fit. A: What we did with shared assemblies during development phase (in a project which had loads of these), is that we put them on a network share (N Drive) type of a place, and every developer referenced them from there. Our build process would always update this share with the latest versions. This way the actual assemblies never had to be kept in source control. Only the code.
What is the optimal way to organize shared .net assemblies in SVN?
We are starting a new SOA project with a lot of shared .net assemblies. The code for these assemblies will be stored in SVN. In development phase, we would like to be able to code these assemblies as an entire solution with as little SVN 'friction' as possible. When the project enters more of a maintenance mode, the assemblies will be maintained on an individual level. Without making Branching, Tagging, and Automated Builds a maintenance nightmare, what's the best way to organize these libraries in SVN that also works well with the VS 2008 IDE? Do you setup Trunk/Branches/Tags at each library level and try to spaghetti it all together somehow at compile time, or is it better to keep it all as one big project with code replicated here and there for simplicity? Is there a solution using externs?
[ "What we did at our company was to set up a tools repository, and then a project repository. The tools repository is a Subversion repository, organized as follows:\n/svn/tools/\n vendor1/\n too11/\n 1.0/\n 1.1/\n latest = a copy of vendor1/tool1/1.1\n tool2/\n 1.0/\n 1.5/\n latest = a copy of vendor1/tool2/1.5\n vendor2/\n foo/\n 1.0.0/\n 1.1.0/\n 1.2.0/\n latest = a copy of vendor2/foo/1.2.0\n\nEvery time we get a new version of a tool from a vendor, it is added under its vendor, name, and version number, and the 'latest' tag is updated. \n[Clarification: this is NOT a typical source respository -- it's intended to store specific versions of 'installed' images. Thus /svn/tools/nunit/nunit2/2.4 would be the top of a directory tree containing the results of installing NUnit 2.4 to a directory and importing it into the tools repository. Source and examples may be present, but the primary focus is on executables and libraries that are necessary to use the tool. If we needed to modify a vendor tool, we'd do that in a separate repository, and release the result to this repository.]\nOne of the vendors is my company, and has a separate section for each tool, assembly, whatever that we release internally.\n\nThe projects repository is a standard Subversion repository, with trunks, tags, and branches as you normally expect. Any given project will look like:\n/svn/\n branches/\n tags/\n trunk/\n foo/\n source/\n tools/\n publish/\n foo-build.xml (for NAnt)\n foo.build (for MSBuild)\n\nThe tools directory has a Subversion svn:externals property set, that links in the appropriate version (either a specific version or 'latest') of each tool or assembly that is needed by that project. When the 'foo' project is built by CruiseControl.NET, the publish task will populate the 'publish' directory as the 'foo' assembly is intended to be deployed, and then executes the following subversion commands:\nsvn import publish /svn/tools/vendor2/foo/1.2.3\nsvn delete /svn/tools/vendor2/foo/latest\nsvn copy /svn/tools/vendor2/foo/1.2.3 /svn/tools/vendor2/foo/latest\n\nDevelopers work on their projects as normal, and let the build automation take care of the details. A normal subversion update will pull the latest versions of external tools as well as as project updates.\nIf you've got a lot of tool interdependency, you can configure CruiseControl.NET (by hand) to trigger builds for subordinate projects when their dependencies change, but we haven't needed to go that far yet.\n\nNote: All of the Subversion repository paths have been shortened for clarity. We actually use Apache+SVN, and two separate servers, but you should adapt this as you see fit.\n\n", "What we did with shared assemblies during development phase (in a project which had loads of these), is that we put them on a network share (N Drive) type of a place, and every developer referenced them from there.\nOur build process would always update this share with the latest versions. This way the actual assemblies never had to be kept in source control. Only the code.\n" ]
[ 6, 0 ]
[]
[]
[ ".net", "svn", "version_control" ]
stackoverflow_0000107292_.net_svn_version_control.txt
Q: Is there a means to produce a changelog in SVN When commiting to SVN I can add a top level commit message to detail what is being committed, but I would ideally like a means to comment on the individual files and what has changed within them. I have seen something similar in previous employment, but this was using CVS (and I can't recall whether this was achieved with a home brew script to produce the skeleton file) I have had a look at changelists but again I don't think (although i am willing to be proved wrong) that this gives the kind of granularity as outlined below. Ideally I am looking for something along the lines of: Foo.vb Added new function bar Bar.vb Removed function foo Added functionality in xyz to do abc +/- Modified function to log error A: You could just commit whenever you're done with one particular task. That should lead to better comments anyway. A comment reading "Implemented E-Mail verification" on the three files necessary tells me a lot more than "added function verify_email". I can see the latter myself in the diff. A: I would just do this in the individual commit message. TortoiseSVN has filename autocompletion so that greatly aids in this. Another thing you could do is svn st before you commit and copy/paste the filenames into your commit message. Oh, and be sure to strongly question the value of this. I know some OSS projects (linux?) require this sort of fidelity, but for many projects this is just noise. Diff can tell you much more than this, and more accurately. One other thing you may want to consider is using Git. Git allows you to commit locally, in smaller steps. You then push to the master server all of your commits individually or squashed into a single commit w/ all the commit messages in a single message. That was a way simplified explanation, but it probably is worth checking out. A: One of the essential differences between SVN and CVS is that changes are committed atomically. In CVS each file has its own version, but in SVN the version is for the whole project and includes all the files checked in together. Here are four ideas for a solution: Check in each of your programs separately, with its own log message. This may mean that if, say, you check in five files, you will "use up" five versions, of which four may result in a broken build. Do your development on a separate path (i.e. your own private branch), do as above, then at strategic moments merge your branch to the trunk. Check in everything together, and keep the individual records as comments in the program header. This may mean (a little) extra work, but you'd have to compose the individual login messages anyway. Do a single checkin for all the files, but with a nice full log message detailing each piece for each file. A: I've written a project for doing this kind of thing called MOAP One of its functions is to generate a ChangeLog entry from your local diff (currently supporting bazaar, cvs, svn, git and darcs). You do this by running 'moap changelog prepare' or 'moap cl prep' That entry can include functions changed as well if you enable the option. You then go and change that entry, describing your changes. You can remove files you don't want commited as part of your next commit. Then, you can run 'moap changelog commit' to commit the changes described in the ChangeLog entry. It will only commit the files listed there, and leave all your other changes local. Hope that helps! A: That kind of result could be obtain if there is some rules regarding the way comments are written inside each of the committed files. These comments can after that be extracted by a svn trigger.
Is there a means to produce a changelog in SVN
When commiting to SVN I can add a top level commit message to detail what is being committed, but I would ideally like a means to comment on the individual files and what has changed within them. I have seen something similar in previous employment, but this was using CVS (and I can't recall whether this was achieved with a home brew script to produce the skeleton file) I have had a look at changelists but again I don't think (although i am willing to be proved wrong) that this gives the kind of granularity as outlined below. Ideally I am looking for something along the lines of: Foo.vb Added new function bar Bar.vb Removed function foo Added functionality in xyz to do abc +/- Modified function to log error
[ "You could just commit whenever you're done with one particular task. That should lead to better comments anyway. A comment reading \"Implemented E-Mail verification\" on the three files necessary tells me a lot more than \"added function verify_email\". I can see the latter myself in the diff.\n", "I would just do this in the individual commit message. TortoiseSVN has filename autocompletion so that greatly aids in this.\nAnother thing you could do is svn st before you commit and copy/paste the filenames into your commit message.\nOh, and be sure to strongly question the value of this. I know some OSS projects (linux?) require this sort of fidelity, but for many projects this is just noise. Diff can tell you much more than this, and more accurately.\nOne other thing you may want to consider is using Git. Git allows you to commit locally, in smaller steps. You then push to the master server all of your commits individually or squashed into a single commit w/ all the commit messages in a single message. That was a way simplified explanation, but it probably is worth checking out.\n", "One of the essential differences between SVN and CVS is that changes are committed atomically. In CVS each file has its own version, but in SVN the version is for the whole project and includes all the files checked in together.\nHere are four ideas for a solution:\n\nCheck in each of your programs separately, with its own log message. This may mean that if, say, you check in five files, you will \"use up\" five versions, of which four may result in a broken build. \nDo your development on a separate path (i.e. your own private branch), do as above, then at strategic moments merge your branch to the trunk.\nCheck in everything together, and keep the individual records as comments in the program header. This may mean (a little) extra work, but you'd have to compose the individual login messages anyway. \nDo a single checkin for all the files, but with a nice full log message detailing each piece for each file.\n\n", "I've written a project for doing this kind of thing called MOAP\nOne of its functions is to generate a ChangeLog entry from your local diff (currently supporting bazaar, cvs, svn, git and darcs). You do this by running 'moap changelog prepare' or 'moap cl prep' That entry can include functions changed as well if you enable the option.\nYou then go and change that entry, describing your changes. You can remove files you don't want commited as part of your next commit.\nThen, you can run 'moap changelog commit' to commit the changes described in the ChangeLog entry. It will only commit the files listed there, and leave all your other changes local.\nHope that helps!\n", "That kind of result could be obtain if there is some rules regarding the way comments are written inside each of the committed files. These comments can after that be extracted by a svn trigger.\n" ]
[ 4, 2, 2, 2, 0 ]
[]
[]
[ "changelog", "cvs", "svn" ]
stackoverflow_0000102474_changelog_cvs_svn.txt
Q: Converting C++ code to HTML safe I decided to try http://www.screwturn.eu/ wiki as a code snippet storage utility. So far I am very impressed, but what irkes me is that when I copy paste my code that I want to save, '<'s and '[' (http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Character_references) invariably screw up the output as the wiki interprets them as either wiki or HTML tags. Does anyone know a way around this? Or failing that, know of a simple utility that would take C++ code and convert it to HTML safe code? A: You can use the @@...@@ tag to escape the code and automatically wrap it in PRE tags. A: Surround your code in <nowiki> .. </nowiki> tags. A: I don't know of utilities, but I'm sure you could write a very simple app that does a find/replace. To display angle brackets, you just need to replace them with &gt; and &lt; respectively. As for the square brackets, that is a wiki specific problem with the markdown methinks. A: Have you tried wrapping your code in html pre or code tags before pasting? Both allow any special characters (such as '<') to be used without being interpreted as html. pre also honors the formatting of the contents. example <pre> if (foo <= bar) { do_something(); } </pre> A: Dario Solera wrote "You can use the @@...@@ tag to escape the code and automatically wrap it in PRE tags." If you don't want it wrapped just use: <esc></esc> A: List of characters that need escaping: < (less-than sign) & (ampersand) [ (opening square bracket)
Converting C++ code to HTML safe
I decided to try http://www.screwturn.eu/ wiki as a code snippet storage utility. So far I am very impressed, but what irkes me is that when I copy paste my code that I want to save, '<'s and '[' (http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Character_references) invariably screw up the output as the wiki interprets them as either wiki or HTML tags. Does anyone know a way around this? Or failing that, know of a simple utility that would take C++ code and convert it to HTML safe code?
[ "You can use the @@...@@ tag to escape the code and automatically wrap it in PRE tags.\n", "Surround your code in <nowiki> .. </nowiki> tags.\n", "I don't know of utilities, but I'm sure you could write a very simple app that does a find/replace. To display angle brackets, you just need to replace them with &gt; and &lt; respectively. As for the square brackets, that is a wiki specific problem with the markdown methinks.\n", "Have you tried wrapping your code in html pre or code tags before pasting? Both allow any special characters (such as '<') to be used without being interpreted as html. pre also honors the formatting of the contents.\nexample\n<pre>\n if (foo <= bar) {\n do_something();\n }\n</pre>\n\n", "Dario Solera wrote \"You can use the @@...@@ tag to escape the code and automatically wrap it in PRE tags.\"\nIf you don't want it wrapped just use: <esc></esc>\n", "List of characters that need escaping:\n\n< (less-than sign)\n& (ampersand)\n[ (opening square bracket)\n\n" ]
[ 2, 1, 0, 0, 0, 0 ]
[ "To post C++ code on a web page, you should convert it to valid HTML first, which will usually require the use of HTML character entities, as others have noted. This is not limited to replacing < and > with &lt; and &gt;. Consider the following code:\nunsigned int maskedValue = value&mask;\n\nUh-oh, does the HTML DTD contain an entity called &mask;? Better replace & with &amp; as well.\nGoing in an alternate direction, you can get rid of [ and ] by replacing them with the trigraphs ??( and ??). In C++, trigraphs and digraphs are sequences of characters that can be used to represent specific characters that are not available in all character sets. They are unlikely to be recognized by most C++ programmers though.\n" ]
[ -1 ]
[ "c++", "wiki" ]
stackoverflow_0000101604_c++_wiki.txt
Q: Best way to translate mouse drag motion into 3d rotation of an object I have a 3d object that I wish to be able to rotate around in 3d. The easiest way is to directly translate X and Y mouse motion to rotation about the Y and X axes, but if there is some rotation along both axes, the way the model rotates becomes highly counterintuitive (i.e. if you flip the object 180 degrees about one axis, your motion along the other axis is reversed). I could simply do the above method, but instead of storing the amount to rotate about the two axes, I could store the full rotation matrix and just further rotate it along the same axes for each mouse drag, but I'm concerned that that would quickly have precision issues. A: It is probably most intuitive to rotate the object around the axis perpendicular to the current drag direction, either incrementally with each mouse motion, or relative to the drag start position. The two options give slightly different user interactions, which each have their pluses and minuses. There is a relatively straightforward way to convert an angle and a 3d vector representing the axis being rotated around into a rotation matrix. You are right in that updating a raw rotation matrix through incremental rotations will result in the matrix no longer being a pure rotation matrix. That is because a 3x3 rotation matrix has three times as much data than needed to represent a rotation. A more compact way to represent rotations is with Euler Angles, having a minimal 3 value vector. You could take the current rotation as an Euler angle vector, convert it to a matrix, apply the rotation (incremental or otherwise), and convert the matrix back to an Euler angle vector. That last step would naturally eliminate any non-rotational component to your matrix, so that you once again end up with a pure rotational matrix for the next state. Euler angles are conceptually nice, however it is a lot of work to do the back and forth conversions. A more practical choice is Quaternions (also), which are four element vectors. The four elements specify rotation and uniform scale, and it happens that if you go in and normalize the vector to unit length, you will get a scale factor of 1.0. It turns out that an angle-axis value can also be converted to a quaternion value very easily by q.x = sin(0.5*angle) * axis.x; q.y = sin(0.5*angle) * axis.y; q.z = sin(0.5*angle) * axis.z; q.w = cos(0.5*angle); You can then take the quaternion product (which uses only simple multiplication and addition) of the current rotation quaternion and incremental rotation quaternion to get a new quaternion which represents performing both rotations. At that point you can normalize the length to ensure a pure rotation, but otherwise continue iteratively combining rotations. Converting the quaternion to a rotation matrix is very straightforward (uses only multiplication and addition) when you want to display the model in its rotated state using traditional graphics API's. A: In my Computer Graphics course, we were given the following code which allowed us not to reinvent the wheel. trackball.h trackball.c A: Create an accumulator matrix and initialize it with the identity. Each frame, apply that to your modelview/world matrix state before drawing the object. Upon mouse motion, construct a rotation matrix about the X axis with some sensitivity_constant * delta_x. Construct another rotation matrix about the Y axis for the other component. Multiply one, then the other onto the accumulator. The accumulator will change as you move the mouse. When drawing, it will orient the object as you expect. Also, the person talking about quaternions is right; this will look good only for small incremental changes. If you drag it quickly on a diagonal, it won't rotate quite the way you expect. A: You can deal with loss of precision by renormalising your rotation matrix so each of the 3 rows are perpendicular again. Or you can regenerate the rotation matrix you are about to modify based on existing information about the object, and this takes away the need for renormalisation. Alternatively you can use quaternions, which is an alternative to Euler angles for dealing with rotations. I learned much of this in my early days from this faq, which deals with this problem (though for another application) in Euler's are Evil.
Best way to translate mouse drag motion into 3d rotation of an object
I have a 3d object that I wish to be able to rotate around in 3d. The easiest way is to directly translate X and Y mouse motion to rotation about the Y and X axes, but if there is some rotation along both axes, the way the model rotates becomes highly counterintuitive (i.e. if you flip the object 180 degrees about one axis, your motion along the other axis is reversed). I could simply do the above method, but instead of storing the amount to rotate about the two axes, I could store the full rotation matrix and just further rotate it along the same axes for each mouse drag, but I'm concerned that that would quickly have precision issues.
[ "It is probably most intuitive to rotate the object around the axis perpendicular to the current drag direction, either incrementally with each mouse motion, or relative to the drag start position. The two options give slightly different user interactions, which each have their pluses and minuses.\nThere is a relatively straightforward way to convert an angle and a 3d vector representing the axis being rotated around into a rotation matrix.\nYou are right in that updating a raw rotation matrix through incremental rotations will result in the matrix no longer being a pure rotation matrix. That is because a 3x3 rotation matrix has three times as much data than needed to represent a rotation.\nA more compact way to represent rotations is with Euler Angles, having a minimal 3 value vector. You could take the current rotation as an Euler angle vector, convert it to a matrix, apply the rotation (incremental or otherwise), and convert the matrix back to an Euler angle vector. That last step would naturally eliminate any non-rotational component to your matrix, so that you once again end up with a pure rotational matrix for the next state.\nEuler angles are conceptually nice, however it is a lot of work to do the back and forth conversions.\nA more practical choice is Quaternions (also), which are four element vectors. The four elements specify rotation and uniform scale, and it happens that if you go in and normalize the vector to unit length, you will get a scale factor of 1.0. It turns out that an angle-axis value can also be converted to a quaternion value very easily by\nq.x = sin(0.5*angle) * axis.x;\nq.y = sin(0.5*angle) * axis.y;\nq.z = sin(0.5*angle) * axis.z;\nq.w = cos(0.5*angle);\n\nYou can then take the quaternion product (which uses only simple multiplication and addition) of the current rotation quaternion and incremental rotation quaternion to get a new quaternion which represents performing both rotations. At that point you can normalize the length to ensure a pure rotation, but otherwise continue iteratively combining rotations.\nConverting the quaternion to a rotation matrix is very straightforward (uses only multiplication and addition) when you want to display the model in its rotated state using traditional graphics API's.\n", "In my Computer Graphics course, we were given the following code which allowed us not to reinvent the wheel.\ntrackball.h\ntrackball.c\n", "Create an accumulator matrix and initialize it with the identity.\nEach frame, apply that to your modelview/world matrix state before drawing the object.\nUpon mouse motion, construct a rotation matrix about the X axis with some sensitivity_constant * delta_x. Construct another rotation matrix about the Y axis for the other component. Multiply one, then the other onto the accumulator.\nThe accumulator will change as you move the mouse. When drawing, it will orient the object as you expect.\nAlso, the person talking about quaternions is right; this will look good only for small incremental changes. If you drag it quickly on a diagonal, it won't rotate quite the way you expect.\n", "You can deal with loss of precision by renormalising your rotation matrix so each of the 3 rows are perpendicular again. Or you can regenerate the rotation matrix you are about to modify based on existing information about the object, and this takes away the need for renormalisation. \nAlternatively you can use quaternions, which is an alternative to Euler angles for dealing with rotations.\nI learned much of this in my early days from this faq, which deals with this problem (though for another application) in Euler's are Evil.\n" ]
[ 8, 6, 4, 3 ]
[]
[]
[ "3d" ]
stackoverflow_0000107413_3d.txt
Q: Detect And Remove Rootkit What is the best (hopefully free or cheap) way to detect and then, if necessary, remove a rootkit found on your machine? A: SysInternals stopped updating RootKit Revealer a couple of years ago. The only sure way to detect a rootkit is to do an offline compare of installed files and filesystem metadata from a trusted list of known files and their parameters. Obviously, you need to trust the machine you are running the comparison from. In most situations, using a boot cdrom to run a virus scanner does the trick, for most people. Otherwise, you can start with a fresh install of whatever, boot it from cdrom, attach an external drive, run a perl script to find and gather parameters (size, md5, sha1), then store the parameters. To check, run a perl script to find and gather parameters, then compare them to the stored ones. Also, you'd need a perl script to update your stored parameters after a system update. --Edit-- Updating this to reflect available techniques. If you get a copy of any bootable rescue cd (such as trinity or rescuecd) with an up-to-date copy of the program "chntpasswd", you'll be able to browse and edit the windows registry offline. Coupled with a copy of the startup list from castlecops.com, you should be able to track down the most common run points for the most common rootkits. And always keep track of your driver files and what the good versions are too. With that level of control, your biggest problem will be the mess of spaghetti your registry is left in after you delete the rootkit and trojans. Usually. -- Edit -- and there are windows tools, too. But I described the tools I'm familiar with, and which are free and better documented. A: Rootkit revealer from SysInternals A: Remember that you can never trust a compromised machine. You may think you found all signs of a rootkit, but the attacker may have created backdoors in other places. Non-standard backdoors that tools you use won't detect. As a rule you should reinstall a compromised machine from scratch.
Detect And Remove Rootkit
What is the best (hopefully free or cheap) way to detect and then, if necessary, remove a rootkit found on your machine?
[ "SysInternals stopped updating RootKit Revealer a couple of years ago.\nThe only sure way to detect a rootkit is to do an offline compare of installed files and filesystem metadata from a trusted list of known files and their parameters. Obviously, you need to trust the machine you are running the comparison from.\nIn most situations, using a boot cdrom to run a virus scanner does the trick, for most people.\nOtherwise, you can start with a fresh install of whatever, boot it from cdrom, attach an external drive, run a perl script to find and gather parameters (size, md5, sha1), then store the parameters.\nTo check, run a perl script to find and gather parameters, then compare them to the stored ones.\nAlso, you'd need a perl script to update your stored parameters after a system update.\n--Edit--\nUpdating this to reflect available techniques. If you get a copy of any bootable rescue cd (such as trinity or rescuecd) with an up-to-date copy of the program \"chntpasswd\", you'll be able to browse and edit the windows registry offline.\nCoupled with a copy of the startup list from castlecops.com, you should be able to track down the most common run points for the most common rootkits. And always keep track of your driver files and what the good versions are too.\nWith that level of control, your biggest problem will be the mess of spaghetti your registry is left in after you delete the rootkit and trojans. Usually.\n-- Edit --\nand there are windows tools, too. But I described the tools I'm familiar with, and which are free and better documented.\n", "Rootkit revealer from SysInternals\n", "Remember that you can never trust a compromised machine. You may think you found all signs of a rootkit, but the attacker may have created backdoors in other places. Non-standard backdoors that tools you use won't detect. As a rule you should reinstall a compromised machine from scratch.\n" ]
[ 4, 2, 2 ]
[]
[]
[ "rootkit" ]
stackoverflow_0000107017_rootkit.txt
Q: Hooking into the TCP Stack in C It's not just a capture I'm looking to do here. I want to first capture the packet, then in real time, check the payload for specific data, remove it, inject a signature and reinject the packet into the stack to be sent on as before. I had a read of the ipfw divert sockets using IPFW and it looks very promising. What about examples in modifying packets and reinjecting them back into the stack using divert sockets? Also, as a matter of curiosity, would it be possible to read the data from the socket using Java or would this restrict me with packing mangling and reinjecting etc? A: See divert sockets: Divert Sockets mini HOWTO. They work by passing traffic matching a certain ipfw rule to a special raw socket that can then reinject altered traffic into the network layers. A: If you're just looking for packet capture, libpcap is very popular. It's used in basic tools such as tcpdump and ethereal. As far as "hooking into the stack", unless you plan on fundamentally changing the way the way the networking is implemented (i.e. add your own layer or alter the behavior of TCP), your idea of using IPF for packet modification or intervention seems like the best bet. In Linux they have a specific redirection target for userspace modules, IPF probably has something similar or you could modify IPF to do something similar. If you are just interested in seeing the packets, then libpcap is the way to go. You can find it at: http://www.tcpdump.org/ A: It's possible to do this in userspace with the QUEUE or NFQUEUE iptables target I think. The client application attaches to a queue and receives all matching packets, which it can modify before they're re-injected (it can also drop them if it wants). There is a client library libnetfilter_queue which it needs to link against. Sadly documentation is minimal, but there are some mailing list posts and examples knocking around. For performance reasons, you won't want to do this to every packet, but only specific matching ones, which you'll have to match using standard iptables rules. If that doesn't do enough, you'll need to write your own netfilter kernel module. A: I was going to echo other responses that have recommended iptables (depending on the complexity of both the patterns that you're trying to match and the packet modifications that you want to make) - until I took notice of the BSD tag on the question. As Stephen Pellicer has already mentioned, libpcap is a good option for capturing the packets. I believe, though, that libpcap can also be used to send packets. For reference I'm pretty sure that tcpreplay uses it to replay pcap formatted files.
Hooking into the TCP Stack in C
It's not just a capture I'm looking to do here. I want to first capture the packet, then in real time, check the payload for specific data, remove it, inject a signature and reinject the packet into the stack to be sent on as before. I had a read of the ipfw divert sockets using IPFW and it looks very promising. What about examples in modifying packets and reinjecting them back into the stack using divert sockets? Also, as a matter of curiosity, would it be possible to read the data from the socket using Java or would this restrict me with packing mangling and reinjecting etc?
[ "See divert sockets: Divert Sockets mini HOWTO.\nThey work by passing traffic matching a certain ipfw rule to a special raw socket that can then reinject altered traffic into the network layers.\n", "If you're just looking for packet capture, libpcap is very popular. It's used in basic tools such as tcpdump and ethereal. As far as \"hooking into the stack\", unless you plan on fundamentally changing the way the way the networking is implemented (i.e. add your own layer or alter the behavior of TCP), your idea of using IPF for packet modification or intervention seems like the best bet. In Linux they have a specific redirection target for userspace modules, IPF probably has something similar or you could modify IPF to do something similar.\nIf you are just interested in seeing the packets, then libpcap is the way to go. You can find it at: http://www.tcpdump.org/\n", "It's possible to do this in userspace with the QUEUE or NFQUEUE iptables target I think. The client application attaches to a queue and receives all matching packets, which it can modify before they're re-injected (it can also drop them if it wants).\nThere is a client library libnetfilter_queue which it needs to link against. Sadly documentation is minimal, but there are some mailing list posts and examples knocking around.\nFor performance reasons, you won't want to do this to every packet, but only specific matching ones, which you'll have to match using standard iptables rules. If that doesn't do enough, you'll need to write your own netfilter kernel module.\n", "I was going to echo other responses that have recommended iptables (depending on the complexity of both the patterns that you're trying to match and the packet modifications that you want to make) - until I took notice of the BSD tag on the question.\nAs Stephen Pellicer has already mentioned, libpcap is a good option for capturing the packets. I believe, though, that libpcap can also be used to send packets. For reference I'm pretty sure that tcpreplay uses it to replay pcap formatted files.\n" ]
[ 4, 1, 1, 0 ]
[]
[]
[ "bsd", "c", "freebsd", "stack", "tcp" ]
stackoverflow_0000063157_bsd_c_freebsd_stack_tcp.txt
Q: Java EE App Server Hello World I am fairly comfortable with standalone Java app development, but will soon be working on a project using a Java EE application server. Does anyone know of a straightforward how-to tutorial to getting a hello-world type application working in an application server? I'm (perhaps naievly) assuming that the overall approach is similar between different frameworks, so I'm more interested in finding out the approach rather than getting bogged down in differences between the different frameworks. If you are not aware of a good guide, then could you post bullet-point type steps to getting a hello-world running?, i.e. Download XX Write some code to do YY Change file ZZ Other steps... Note: Just because I have a windows machine at home, I would prefer to run if this could be run on windows, but in the interest of a better answer, linux/mac based implementations are welcome. A: I would choose JBoss AS or GlassFish for a start. However I'm not sure what you mean by Java EE "Hello World". If you just want to deploy some JSP you could use this tutorial (for JBoss): http://www.centerkey.com/jboss/ If you want to get further and do the EJB stack and/or deploy an ear-file, you could read the very good JBoss documentation: Installation Guide Getting started Configuration Guide In general you could also just do the basic installation and change or try the pre-installed example applications. I currently have JBoss installed (on windows). I develop with Eclipse and use the Java EE server integration to hot deploy or debug my code. After you get your first code running you realy should have a look at the ide integration since it makes development/deploy roundtrips so much faster. A: The JavaEE (they dropped the 2) space is pretty big. A good tutorial to start is the one from Sun. For a simple hello world application, the web container only would suffice. A well known servlet jsp container is tomcat. See here for installation instructions. Try installing it with eclipse and create a web project. This will generate some files for you that you can look at and edit. Also starting and stopping the application server is simpler. A: Another option is to get Oracle JDeveloper (free to download and use - it's a full featured IDE that includes some neat extras like the SQL workbench and BPEL designer). As a learning tool, it is quite good, not only for the tutorials available from Oracle, but it includes a range of "cue-card" lessons in the tool itself to teach many common techniques. cue card view http://tardate.heroku.com/images/jdev-cuecards.jpg A: If you haven't gone near NetBeans in a while its catching up with Eclipse very fast and worth a look, especially when starting Java EE. Version 6.x installs Tomcat and/or Glassfish for you and then provides wizards to create/deploy/redeploy applications. The initial tutorial on Web Applications is here and a more complex example here. A: As JeroenWyseur puts it, Java EE is a fairly big space. In addition to what he said, you should try to get more details of what exactly you'll be doing: servelts & co, EJB (entity, session, message beans?) and try to get familiar with that. It should be clear for you that your code runs in a managed environment, which imposes a lot of constraints. in order to make sure you understand what happens you should get familiar with the concept of deployment. Then, if you do EJBs, transaction management is important too. If you don't understand exactly what happens when a bean or a servlet is deployed, how transactions are managed, how beans are invoked, you're going to have a hard time. A book that helped me a lot back in the time is Mastering EJB, by Ed Roman. Also, getting familiar with RMI will help you understand EJBs.
Java EE App Server Hello World
I am fairly comfortable with standalone Java app development, but will soon be working on a project using a Java EE application server. Does anyone know of a straightforward how-to tutorial to getting a hello-world type application working in an application server? I'm (perhaps naievly) assuming that the overall approach is similar between different frameworks, so I'm more interested in finding out the approach rather than getting bogged down in differences between the different frameworks. If you are not aware of a good guide, then could you post bullet-point type steps to getting a hello-world running?, i.e. Download XX Write some code to do YY Change file ZZ Other steps... Note: Just because I have a windows machine at home, I would prefer to run if this could be run on windows, but in the interest of a better answer, linux/mac based implementations are welcome.
[ "I would choose JBoss AS or GlassFish for a start. However I'm not sure what you mean by Java EE \"Hello World\". If you just want to deploy some JSP you could use this tutorial (for JBoss):\nhttp://www.centerkey.com/jboss/\nIf you want to get further and do the EJB stack and/or deploy an ear-file, you could read the very good JBoss documentation:\nInstallation Guide\nGetting started\nConfiguration Guide\nIn general you could also just do the basic installation and change or try the pre-installed example applications. \nI currently have JBoss installed (on windows). I develop with Eclipse and use the Java EE server integration to hot deploy or debug my code. After you get your first code running you realy should have a look at the ide integration since it makes development/deploy roundtrips so much faster.\n", "The JavaEE (they dropped the 2) space is pretty big. A good tutorial to start is the one from Sun. For a simple hello world application, the web container only would suffice. A well known servlet jsp container is tomcat. See here for installation instructions. Try installing it with eclipse and create a web project. This will generate some files for you that you can look at and edit. Also starting and stopping the application server is simpler.\n", "Another option is to get Oracle JDeveloper (free to download and use - it's a full featured IDE that includes some neat extras like the SQL workbench and BPEL designer).\nAs a learning tool, it is quite good, not only for the tutorials available from Oracle, but it includes a range of \"cue-card\" lessons in the tool itself to teach many common techniques.\ncue card view http://tardate.heroku.com/images/jdev-cuecards.jpg\n", "If you haven't gone near NetBeans in a while its catching up with Eclipse very fast and worth a look, especially when starting Java EE.\nVersion 6.x installs Tomcat and/or Glassfish for you and then provides wizards to create/deploy/redeploy applications.\nThe initial tutorial on Web Applications is here and a more complex example here.\n", "As JeroenWyseur puts it, Java EE is a fairly big space. In addition to what he said, you should try to get more details of what exactly you'll be doing: servelts & co, EJB (entity, session, message beans?) and try to get familiar with that. \nIt should be clear for you that your code runs in a managed environment, which imposes a lot of constraints. in order to make sure you understand what happens you should get familiar with the concept of deployment. Then, if you do EJBs, transaction management is important too. If you don't understand exactly what happens when a bean or a servlet is deployed, how transactions are managed, how beans are invoked, you're going to have a hard time.\nA book that helped me a lot back in the time is Mastering EJB, by Ed Roman. \nAlso, getting familiar with RMI will help you understand EJBs.\n" ]
[ 6, 5, 2, 1, 0 ]
[]
[]
[ "jakarta_ee", "java" ]
stackoverflow_0000091061_jakarta_ee_java.txt
Q: Flash toggle snapping long, long ago in a galaxy far far away, You used to be able to toggle snapping in Flash with the ctrl key. Let's say you were dragging the end of a line very close to another object. You could very easily hold the ctrl key down to shut off the snapping and get it in there nice and close without the snap. At some point, Macromedia removed this functionality. I'm wondering if that single-key-toggle-snapping functionality has gone somewhere else within the app or do I have to click through the menus every time? A: I don't think there is, I've scoured the docs and could not find anything about it. The weird thing is also that you can't set a keyboard shortcut for toggling it. The option is there, but it's grayed out for some reason. The best I could manage was setting a shortcut for the object-snapping (since that's what i use the most) and just toggling that. Also, you don't need to go through the menus, the magnet button on the toolbar toggles snapping too.
Flash toggle snapping
long, long ago in a galaxy far far away, You used to be able to toggle snapping in Flash with the ctrl key. Let's say you were dragging the end of a line very close to another object. You could very easily hold the ctrl key down to shut off the snapping and get it in there nice and close without the snap. At some point, Macromedia removed this functionality. I'm wondering if that single-key-toggle-snapping functionality has gone somewhere else within the app or do I have to click through the menus every time?
[ "I don't think there is, I've scoured the docs and could not find anything about it. \nThe weird thing is also that you can't set a keyboard shortcut for toggling it. The option is there, but it's grayed out for some reason. The best I could manage was setting a shortcut for the object-snapping (since that's what i use the most) and just toggling that. \nAlso, you don't need to go through the menus, the magnet button on the toolbar toggles snapping too.\n" ]
[ 0 ]
[]
[]
[ "flash" ]
stackoverflow_0000106395_flash.txt
Q: How do I examine the configuration of a remote git repository? I've got a git-svn clone of an svn repo, and I want to encourage my colleagues to look at git as an option. The problem is that cloning the repo out of svn takes 3 days, but cloning from my git instance takes 10 minutes. I've got a script that will allow people to clone my git repo and re-point it at the original SVN, but it requires knowing how I set some of my config values. I'd prefer the script be able to pull those values over the wire. A: I'd say the better way to do this would be, instead of requiring that your coworkers do a git clone, just give them a a tarball of your existing git-svn checkout. This way, you don't have to repoint or query anything, as it's already done. A: If they have direct access to your repository (that is, not via ssh or some other network protocol) then I'd say you could run git config -f/path/to/your/repo/.git/config --get ... to query the parameters out of your config file. Otherwise, as far as I can tell, they will have to first scp (or rcp or ftp or ...) your config file to a scratch space (not overwriting theirs) and then do the same queries on the local config file: scp curries_box:/home/currie/repo/.git/config /tmp/currie_config git config -f/tmp/currie_config --get ... My only other thought is that you could maintain a copy of your .git/config file in your repository. Then, when they clone, they'll have a copy... though you'll have to manually update it... perhaps you can devise a hook to automate the update or at least detect when an update should be done.
How do I examine the configuration of a remote git repository?
I've got a git-svn clone of an svn repo, and I want to encourage my colleagues to look at git as an option. The problem is that cloning the repo out of svn takes 3 days, but cloning from my git instance takes 10 minutes. I've got a script that will allow people to clone my git repo and re-point it at the original SVN, but it requires knowing how I set some of my config values. I'd prefer the script be able to pull those values over the wire.
[ "I'd say the better way to do this would be, instead of requiring that your coworkers do a git clone, just give them a a tarball of your existing git-svn checkout. This way, you don't have to repoint or query anything, as it's already done.\n", "If they have direct access to your repository (that is, not via ssh or some other network protocol) then I'd say you could run \n\ngit config -f/path/to/your/repo/.git/config --get ...\n\nto query the parameters out of your config file. Otherwise, as far as I can tell, they will have to first scp (or rcp or ftp or ...) your config file to a scratch space (not overwriting theirs) and then do the same queries on the local config file:\n\nscp curries_box:/home/currie/repo/.git/config /tmp/currie_config\ngit config -f/tmp/currie_config --get ...\n\nMy only other thought is that you could maintain a copy of your .git/config file in your repository. Then, when they clone, they'll have a copy... though you'll have to manually update it... perhaps you can devise a hook to automate the update or at least detect when an update should be done.\n" ]
[ 4, 2 ]
[]
[]
[ "git", "git_svn" ]
stackoverflow_0000098400_git_git_svn.txt
Q: Git over Email? Assuming network access is sporadic with no central server, what would be the best way to use git to keep three or more branches in sync? Is there a way to extract just my deltas, email those, and merge them on the other end? A: While "git format-patch" and "git am" are great ways to manage patches from non-git sources, for git repositories you should investigate "git bundle". "git bundle" and the subcommands "create" and "unbundle" can be used to create and use a binary blob of incremental commits that can be used to transfer branch history across a 'weak' link via an alternative file transfer mechanism (e.g. email, snail-mail, etc.). git bundles will preserve commit ids, whereas format-patch/am will not resulting in the destination commits not being identical (different SHA1s). A: See the main pages for git-format-patch and git-am. This is one of the ways the system was originally designed to work with. A: There are a few tools in git to use to mail patches or import mailed patches: git-am (apply patches from a mailbox), git-format-patch (prepare email for mailing), git-send-email (send a collection of patches via mail), etc. man 1 git has a complete list.
Git over Email?
Assuming network access is sporadic with no central server, what would be the best way to use git to keep three or more branches in sync? Is there a way to extract just my deltas, email those, and merge them on the other end?
[ "While \"git format-patch\" and \"git am\" are great ways to manage patches from non-git sources, for git repositories you should investigate \"git bundle\".\n\"git bundle\" and the subcommands \"create\" and \"unbundle\" can be used to create and use a binary blob of incremental commits that can be used to transfer branch history across a 'weak' link via an alternative file transfer mechanism (e.g. email, snail-mail, etc.).\ngit bundles will preserve commit ids, whereas format-patch/am will not resulting in the destination commits not being identical (different SHA1s).\n", "See the main pages for git-format-patch and git-am. This is one of the ways the system was originally designed to work with.\n", "There are a few tools in git to use to mail patches or import mailed patches: git-am (apply patches from a mailbox), git-format-patch (prepare email for mailing), git-send-email (send a collection of patches via mail), etc. man 1 git has a complete list.\n" ]
[ 27, 5, 2 ]
[]
[]
[ "git", "version_control" ]
stackoverflow_0000085051_git_version_control.txt
Q: Are there any resources about the PHP XMLWriter functionality? The PHP documentation can be found here, but I think it's rather lacking. There are no examples of how to use these functions, and few (if any) of the pages have user comments. So where might I be able to find an explanation (and example code) on how to use these functions to write an XML document? A: I don't know any other resources, but I found the examples in the comments on this page quite helpful. A: I'd recommend looking at the DOM functions over the SimpleXML ones - it's much more robust. Not as simple, but definitely has more features.
Are there any resources about the PHP XMLWriter functionality?
The PHP documentation can be found here, but I think it's rather lacking. There are no examples of how to use these functions, and few (if any) of the pages have user comments. So where might I be able to find an explanation (and example code) on how to use these functions to write an XML document?
[ "I don't know any other resources, but I found the examples in the comments on this page quite helpful.\n", "I'd recommend looking at the DOM functions over the SimpleXML ones - it's much more robust. Not as simple, but definitely has more features.\n" ]
[ 1, 1 ]
[]
[]
[ "php", "xml", "xmlwriter" ]
stackoverflow_0000102652_php_xml_xmlwriter.txt
Q: Configuring sendmail behind a firewall I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall. So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying. A: @eli: modifying sendmail.cf directly is not usually recommended, since it is generated by the macro compiler. Edit /etc/mail/sendmail.mc to include the line: define(`SMART_HOST',`mailrelay.example.com')dnl After changing the sendmail.mc macro configuration file, it must be recompiled to produce the sendmail configuration file. # m4 /etc/mail/sendmail.mc > /etc/sendmail.cf And restart the sendmail service (Linux): # /etc/init.d/sendmail restart As well as setting the smarthost, you might want to also disable name resolution configuration and possibly shift your sendmail to non-standard port, or disable daemon mode. Disable Name Resolution Servers that are within fire-walled networks or using Network Address Translation (NAT) may not have DNS or NIS services available. This creates a problem for sendmail, since it will use DNS by default, and if it is not available you will see messages like this in mailq: host map: lookup (mydomain.com): deferred) Unless you are prepared to setup an appropriate DNS or NIS service that sendmail can use, in this situation you will typically configure name resolution to be done using the /etc/hosts file. This is done by enabling a 'service.switch' file and specifying resolution by file, as follows: 1: Enable service.switch for sendmail Edit /etc/mail/sendmail.mc to include the lines: define(`confSERVICE_SWITCH_FILE',`/etc/mail/service.switch')dnl 2: Configure service.switch for files Create or modify /etc/mail/service.switch to refer only to /etc/hosts for name resolution: # cat /etc/mail/service.switch hosts files 3: Recompile sendmail.mc and restart sendmail for this setting to take effect. Shift sendmail to non-standard port, or disable daemon mode By default, sendmail will listen on port 25. You may want to change this port or disable the sendmail daemon mode altogether for various reasons: - if there is a security policy prohibiting the use of well-known ports - if another SMTP product/process is to be running on the same host on the standard port - if you don't want to accept mail via smtp at all, just send it using sendmail 1: To shift sendmail to use non-standard port. Edit /etc/mail/sendmail.mc and modify the "Port" setting in the line: DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA') For example, to get sendmail to use port 125: DAEMON_OPTIONS(`Port=125,Addr=127.0.0.1, Name=MTA') This will require sendmail.mc to be recompiled and sendmail to be restarted. 2: Alternatively, to disable sendmail daemon mode altogether (Linux) Edit /etc/sysconfig/sendmail and modify the "DAEMON" setting to: DAEMON=no This change will require sendmail to be restarted. A: http://www.elandsys.com/resources/sendmail/smarthost.html Sendmail Smarthost A smarthost is a host through which outgoing mail is relayed. Some ISPs block outgoing SMTP traffic (port 25) and require their users to send out all mail through the ISP's mail server. Sendmail can be configured to use the ISP's mail server as the smart host. Read the linked article for instruction for how to set this up. A: @Espo: Thanks for the great advice on where to start. Your link would have been better if I had been configuring sendmail for its first use instead of taking an existing configuration and making this small change. However, once I knew to look for stuff on "SmartHost", I found an easier way. All I had to do was edit my /etc/mail/sendmail.cf file to change DS to DSmailrelay.example.com then restart sendmail and it worked.
Configuring sendmail behind a firewall
I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall. So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying.
[ "@eli: modifying sendmail.cf directly is not usually recommended, since it is generated by the macro compiler. \nEdit /etc/mail/sendmail.mc to include the line:\n define(`SMART_HOST',`mailrelay.example.com')dnl \n\nAfter changing the sendmail.mc macro configuration file, it must be recompiled\nto produce the sendmail configuration file.\n # m4 /etc/mail/sendmail.mc > /etc/sendmail.cf\n\nAnd restart the sendmail service (Linux):\n # /etc/init.d/sendmail restart\n\nAs well as setting the smarthost, you might want to also disable name resolution configuration and possibly shift your sendmail to non-standard port, or disable daemon mode.\nDisable Name Resolution\nServers that are within fire-walled networks or using Network Address\nTranslation (NAT) may not have DNS or NIS services available. This creates\na problem for sendmail, since it will use DNS by default, and if it is not\navailable you will see messages like this in mailq:\n host map: lookup (mydomain.com): deferred)\n\nUnless you are prepared to setup an appropriate DNS or NIS service that\nsendmail can use, in this situation you will typically configure name\nresolution to be done using the /etc/hosts file. This is done by enabling\na 'service.switch' file and specifying resolution by file, as follows:\n1: Enable service.switch for sendmail\nEdit /etc/mail/sendmail.mc to include the lines:\n define(`confSERVICE_SWITCH_FILE',`/etc/mail/service.switch')dnl\n\n2: Configure service.switch for files\nCreate or modify /etc/mail/service.switch to refer only to /etc/hosts for name\nresolution:\n # cat /etc/mail/service.switch\n hosts files\n\n3: Recompile sendmail.mc and restart sendmail for this setting to take effect.\nShift sendmail to non-standard port, or disable daemon mode\nBy default, sendmail will listen on port 25. You may want to change this port\nor disable the sendmail daemon mode altogether for various reasons:\n- if there is a security policy prohibiting the use of well-known ports\n- if another SMTP product/process is to be running on the same host on the standard port\n- if you don't want to accept mail via smtp at all, just send it using sendmail\n1: To shift sendmail to use non-standard port.\nEdit /etc/mail/sendmail.mc and modify the \"Port\" setting in the line:\n DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')\n\nFor example, to get sendmail to use port 125:\n DAEMON_OPTIONS(`Port=125,Addr=127.0.0.1, Name=MTA')\n\nThis will require sendmail.mc to be recompiled and sendmail to be restarted.\n2: Alternatively, to disable sendmail daemon mode altogether (Linux)\nEdit /etc/sysconfig/sendmail and modify the \"DAEMON\" setting to:\n DAEMON=no\n\nThis change will require sendmail to be restarted.\n", "http://www.elandsys.com/resources/sendmail/smarthost.html\n\nSendmail Smarthost\nA smarthost is a host through which\n outgoing mail is relayed. Some ISPs\n block outgoing SMTP traffic (port 25)\n and require their users to send out\n all mail through the ISP's mail\n server. Sendmail can be configured to\n use the ISP's mail server as the smart\n host.\n\nRead the linked article for instruction for how to set this up.\n", "@Espo: Thanks for the great advice on where to start. Your link would have been better if I had been configuring sendmail for its first use instead of taking an existing configuration and making this small change. However, once I knew to look for stuff on \"SmartHost\", I found an easier way.\nAll I had to do was edit my /etc/mail/sendmail.cf file to change\nDS\n\nto\nDSmailrelay.example.com\n\nthen restart sendmail and it worked.\n" ]
[ 14, 5, 3 ]
[]
[]
[ "configuration", "firewall", "sendmail", "smarthost" ]
stackoverflow_0000043970_configuration_firewall_sendmail_smarthost.txt
Q: What is the most flexible serialization for .NET objects, yet simple to implement? I would like to serialize and deserialize objects without having to worry about the entire class graph. Flexibility is key. I would like to be able to serialize any object passed to me without complete attributes needed throughout the entire object graph. That means that Binary Serialization is not an option as it only works with the other .NET Platforms. I would also like something readable by a person, and thus decipherable by a management program and other interpreters. I've found problems using the DataContract, JSON, and XML Serializers. Most of these errors seem to center around Serialization of Lists/Dictionaries (i.e. XML Serializable Generic Dictionary). "Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer." Please base your answers on actual experiences and not theory or reading of an article. A: Have you considered serializing to JSON instead of XML? Json.NET has a really powerful and flexible serializer that has no problems with Hashtables/generic dictionaries and doesn't require any particular attributes. I know because I wrote it :) It gives you heaps of control through various options on the serializer and it allows you to override how a type is serialized by creating a JsonConverter for it. In my opinion JSON is more human readable than XML and Json.NET gives the option to write nicely formatted JSON. Finally the project is open source so you can step into the code and make modifications if you need to. A: If I recall it works something like this with a property: [XmlArray("Foo")] [XmlArrayItem("Bar")] public List<BarClass> FooBars { get; set; } If you serialized this you'd get something like: <Foo> <Bar /> <Bar /> </Foo> Of course, I should probably defer to the experts. Here's more info from MS: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx Let me know if that works out for you. A: From your requirements it sounds like Xml Serialization is best. What sort of problems do you have with collections when serializing? If you're referring to not knowing what attributes to use on a List or something similar, you might try the XmlArray attribute on your property. You can definitely serialize a collection. A: The IntermediateSerializer in the XNA Framework is pretty damn cool. You can find a bunch of tutorials on using it at http://blogs.msdn.com/shawnhar A: SOAP Serialization worked well for me, even for objects not marked with [Serializable] A: You'll have problems with collection serialization if objects in the collection contain any reference to other objects in the same collection. If any type of dual-pointing exists, you end up creating a multi-map that cannot be serialized. On every problem I've ever had serializing a custom collection, it was always because of some added functionality that I needed that worked fine as part of a "typical" client-server application, and then failed miserably as part of a consumer-provider-server application. A: Put all the classes you want to serialize into a separate assembly, and then use the sgen tool to generate a serialization assembly to serialize to XML. Use XML attributes to control serialization. If you need to customize the serialization assembly (and you will need that to support classes that aren't IXmlSerializable and classes that contain abstract nodes), then instruct sgen to dump the source code into a separate file and then add it to your solution. Then you can modify it as necessary. http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx FWIW, I've managed to serialize the entire AdsML Framework (over 400 classes) using this technique. It did require a lot of manual customization, but there's no getting around that if you consider the size of the framework. (I used a separate tool to go from XSD to C#) A: Perhaps a more efficient route would be to serialize using the BinaryFormatter As copied from http://blog.paranoidferret.com/index.php/2007/04/27/csharp-tutorial-serialize-objects-to-a-file/ using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; public class Serializer { public Serializer() { } public void SerializeObject(string filename, ObjectToSerialize objectToSerialize) { Stream stream = File.Open(filename, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, objectToSerialize); stream.Close(); } public ObjectToSerialize DeSerializeObject(string filename) { ObjectToSerialize objectToSerialize; Stream stream = File.Open(filename, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter(); objectToSerialize = (ObjectToSerialize)bFormatter.Deserialize(stream); stream.Close(); return objectToSerialize; } } A: I agree that the DataContract-based serialization methods (to JSON, XML, etc) is a bit more complex than I'd like. If you're trying to get JSON check out http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx It's part of the MS AJAX extensions. Admittedly it is flagged as Obsolete in .NET 3.5 but ScottGu mentions in his blog comment here (http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx#4301973) that he's not sure why and it should be supported for a bit longer. A: The simplest thing to do is mark your objects with the Serializable attribute and then use a binary formatter to handle the serialization. The entire class graph shouldn't be a problem provided that any contained objects are also marked as Serializable. A: For interoperability we have always used Xml Serialisation and made sure our class was designed from the ground up to do it correctly. We create an XSD schema document and generate a set of classes from that using XSD.exe. This generates partial classes so we then create a set of corresponding partial classes to add the extra methods we want to help us populate the classes and use them in our application (as they are focused on serialising and deserialising and are a bit difficut to use sometimes). A: You should use the NetDataContractSerializer. It covers any kind of object graph and supports generics, lists, polymorphism (the KnownType attribute is not needed here), recursion and etc. The only drawback is that you have to mark all you classes with [Serializable] / [DataContract] attributes, but experience shows that you have to do some sort of manual fine-tuning anyway since not all members should be persisted. Also it serializes into an Xml, though its readability is questionable. We had the same requirements as yours and chose this solution.
What is the most flexible serialization for .NET objects, yet simple to implement?
I would like to serialize and deserialize objects without having to worry about the entire class graph. Flexibility is key. I would like to be able to serialize any object passed to me without complete attributes needed throughout the entire object graph. That means that Binary Serialization is not an option as it only works with the other .NET Platforms. I would also like something readable by a person, and thus decipherable by a management program and other interpreters. I've found problems using the DataContract, JSON, and XML Serializers. Most of these errors seem to center around Serialization of Lists/Dictionaries (i.e. XML Serializable Generic Dictionary). "Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer." Please base your answers on actual experiences and not theory or reading of an article.
[ "Have you considered serializing to JSON instead of XML?\nJson.NET has a really powerful and flexible serializer that has no problems with Hashtables/generic dictionaries and doesn't require any particular attributes. I know because I wrote it :)\nIt gives you heaps of control through various options on the serializer and it allows you to override how a type is serialized by creating a JsonConverter for it.\nIn my opinion JSON is more human readable than XML and Json.NET gives the option to write nicely formatted JSON.\nFinally the project is open source so you can step into the code and make modifications if you need to.\n", "If I recall it works something like this with a property:\n[XmlArray(\"Foo\")]\n[XmlArrayItem(\"Bar\")]\npublic List<BarClass> FooBars\n{ get; set; }\n\nIf you serialized this you'd get something like:\n<Foo>\n <Bar />\n <Bar />\n</Foo>\n\nOf course, I should probably defer to the experts. Here's more info from MS: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx\nLet me know if that works out for you.\n", "From your requirements it sounds like Xml Serialization is best.\nWhat sort of problems do you have with collections when serializing? If you're referring to not knowing what attributes to use on a List or something similar, you might try the \nXmlArray attribute on your property. You can definitely serialize a collection.\n", "The IntermediateSerializer in the XNA Framework is pretty damn cool. You can find a bunch of tutorials on using it at http://blogs.msdn.com/shawnhar\n", "SOAP Serialization worked well for me, even for objects not marked with [Serializable]\n", "You'll have problems with collection serialization if objects in the collection contain any reference to other objects in the same collection. If any type of dual-pointing exists, you end up creating a multi-map that cannot be serialized. On every problem I've ever had serializing a custom collection, it was always because of some added functionality that I needed that worked fine as part of a \"typical\" client-server application, and then failed miserably as part of a consumer-provider-server application.\n", "Put all the classes you want to serialize into a separate assembly, and then use the sgen tool to generate a serialization assembly to serialize to XML. Use XML attributes to control serialization. \nIf you need to customize the serialization assembly (and you will need that to support classes that aren't IXmlSerializable and classes that contain abstract nodes), then instruct sgen to dump the source code into a separate file and then add it to your solution. Then you can modify it as necessary.\nhttp://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx\nFWIW, I've managed to serialize the entire AdsML Framework (over 400 classes) using this technique. It did require a lot of manual customization, but there's no getting around that if you consider the size of the framework. (I used a separate tool to go from XSD to C#)\n", "Perhaps a more efficient route would be to serialize using the BinaryFormatter\nAs copied from http://blog.paranoidferret.com/index.php/2007/04/27/csharp-tutorial-serialize-objects-to-a-file/\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\npublic class Serializer\n{\n public Serializer()\n {\n }\n\n public void SerializeObject(string filename,\n ObjectToSerialize objectToSerialize)\n {\n Stream stream = File.Open(filename, FileMode.Create);\n BinaryFormatter bFormatter = new BinaryFormatter();\n bFormatter.Serialize(stream, objectToSerialize);\n stream.Close();\n }\n\n public ObjectToSerialize DeSerializeObject(string filename)\n {\n ObjectToSerialize objectToSerialize;\n Stream stream = File.Open(filename, FileMode.Open);\n BinaryFormatter bFormatter = new BinaryFormatter();\n objectToSerialize =\n (ObjectToSerialize)bFormatter.Deserialize(stream);\n stream.Close();\n return objectToSerialize;\n }\n}\n\n", "I agree that the DataContract-based serialization methods (to JSON, XML, etc) is a bit more complex than I'd like.\nIf you're trying to get JSON check out http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\nIt's part of the MS AJAX extensions. Admittedly it is flagged as Obsolete in .NET 3.5 but ScottGu mentions in his blog comment here (http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx#4301973) that he's not sure why and it should be supported for a bit longer.\n", "The simplest thing to do is mark your objects with the Serializable attribute and then use a binary formatter to handle the serialization. The entire class graph shouldn't be a problem provided that any contained objects are also marked as Serializable.\n", "For interoperability we have always used Xml Serialisation and made sure our class was designed from the ground up to do it correctly.\nWe create an XSD schema document and generate a set of classes from that using XSD.exe. This generates partial classes so we then create a set of corresponding partial classes to add the extra methods we want to help us populate the classes and use them in our application (as they are focused on serialising and deserialising and are a bit difficut to use sometimes).\n", "You should use the NetDataContractSerializer. It covers any kind of object graph and supports generics, lists, polymorphism (the KnownType attribute is not needed here), recursion and etc.\nThe only drawback is that you have to mark all you classes with [Serializable] / [DataContract] attributes, but experience shows that you have to do some sort of manual fine-tuning anyway since not all members should be persisted.\nAlso it serializes into an Xml, though its readability is questionable.\nWe had the same requirements as yours and chose this solution.\n" ]
[ 55, 3, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ ".net", "c#", "json", "json.net", "serialization" ]
stackoverflow_0000106599_.net_c#_json_json.net_serialization.txt
Q: ASP.NET Validators inside an UpdatePanel I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit? A: I suspect you are running the original release (RTM) of .NET 2.0. Until early 2007 validator controls were not compatible with UpdatePanels. This was resolved with the SP1 of the .NET Framework. The source of the problem is that UpdatePanel can detect markup changes in your page, but it has no way to track scripts correctly. Validators rely heavily on scripts. During a partial postback, the scripts are either blown away, not updated, or not run when they are meant to. In early betas, MS had the UpdatePanel try to guess what scripts needed to be re-rendered or run. It didn't work very well, and they had to take it out. To get around the immediate problem, Microsoft released a patched version of the validator classes in a new DLL called Validators.DLL, and gave instructions on how to tell ASP.NET to use those classes instead of the real ones. If you Google for that DLL name, you should find more information. See also This blog post. This was a stop-gag measure and you should not use it avoid it if possible. The real solution to the problem came shortly after, in .NET 2.0 SP1. Microsoft introduced a new mechanism to register scripts in SP1, and changed the real validator classes to use that mechanism instead of the older one. Let me give you some details on the changes: Traditionally, you were supposed to register scripts via Page methods such as Page.RegisterStartupScript() and Page.RegisterClientScriptBlock(). The problem is that these methods were not designed for extensibility and UpdatePanel had no way to monitor those calls. In SP1 there is a new property object on the page called Page.ClientScripts. This object has methods to register scripts that are equivalent (and in some ways better) to the original ones. Also, UpdatePanel can monitor these calls, so that it rerenders or calls the methods when appropriate. The older RegisterStartupScript(), etc. methods have been deprecated. They still work, but not inside an UpdatePanel. There is no reason (other than politics, I suppose) to not update your installations to .NET 2.0 SP1. Service Packs carry important fixes. Good luck. A: @Jonathan Holland: What is wrong with using Validators.dll? Since they replace the original classes, you are quietly bypassing any bug and security fixes, enhancements, etc. that Microsoft might release in the future (or might have already released). Unless you look carefully at the web.config, you might never notice that you are skipping patches. Of course, you have to evaluate each situation. If you are absolutely stuck using .NET 2.0 RTM, then Validators.dll is better than nothing. A: @jmein Actually the problem is that the Validator client script's don't work when placed inside of an updatePanel (UpdatePanels refresh using .innerHTML, which adds the script nodes as text nodes, not script nodes, so the browser does not run them). The fix was a patch released by microsoft that fixes this issue. I found it with the help of Google. http://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx
ASP.NET Validators inside an UpdatePanel
I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit?
[ "I suspect you are running the original release (RTM) of .NET 2.0.\nUntil early 2007 validator controls were not compatible with UpdatePanels. This was resolved with the SP1 of the .NET Framework.\nThe source of the problem is that UpdatePanel can detect markup changes in your page, but it has no way to track scripts correctly. Validators rely heavily on scripts. During a partial postback, the scripts are either blown away, not updated, or not run when they are meant to.\nIn early betas, MS had the UpdatePanel try to guess what scripts needed to be re-rendered or run. It didn't work very well, and they had to take it out.\nTo get around the immediate problem, Microsoft released a patched version of the validator classes in a new DLL called Validators.DLL, and gave instructions on how to tell ASP.NET to use those classes instead of the real ones. If you Google for that DLL name, you should find more information. See also This blog post.\nThis was a stop-gag measure and you should not use it avoid it if possible.\nThe real solution to the problem came shortly after, in .NET 2.0 SP1. Microsoft introduced a new mechanism to register scripts in SP1, and changed the real validator classes to use that mechanism instead of the older one.\nLet me give you some details on the changes:\nTraditionally, you were supposed to register scripts via Page methods such as Page.RegisterStartupScript() and Page.RegisterClientScriptBlock(). The problem is that these methods were not designed for extensibility and UpdatePanel had no way to monitor those calls.\nIn SP1 there is a new property object on the page called Page.ClientScripts. This object has methods to register scripts that are equivalent (and in some ways better) to the original ones. Also, UpdatePanel can monitor these calls, so that it rerenders or calls the methods when appropriate. The older RegisterStartupScript(), etc. methods have been deprecated. They still work, but not inside an UpdatePanel.\nThere is no reason (other than politics, I suppose) to not update your installations to .NET 2.0 SP1. Service Packs carry important fixes.\nGood luck.\n", "\n@Jonathan Holland: What is wrong with using Validators.dll?\n\nSince they replace the original classes, you are quietly bypassing any bug and security fixes, enhancements, etc. that Microsoft might release in the future (or might have already released). Unless you look carefully at the web.config, you might never notice that you are skipping patches.\nOf course, you have to evaluate each situation. If you are absolutely stuck using .NET 2.0 RTM, then Validators.dll is better than nothing.\n", "@jmein\nActually the problem is that the Validator client script's don't work when placed inside of an updatePanel (UpdatePanels refresh using .innerHTML, which adds the script nodes as text nodes, not script nodes, so the browser does not run them).\nThe fix was a patch released by microsoft that fixes this issue. I found it with the help of Google.\nhttp://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx\n" ]
[ 21, 3, 2 ]
[ "If for what ever reason you are unable to use the udpated version of the ASP.NET validator controls is actually very easy to validate a validation group yourself, all you need to do is call \nPage_ClientValidate(\"validationGroupName\");\n\nThen you can use the PageRequestManager execute the validation as you need.\nDefinately using the updated validation controls is the way to go, but I'm quite partial to JavaScript ;)\n" ]
[ -1 ]
[ "asp.net", "asp.net_ajax", "updatepanel" ]
stackoverflow_0000032814_asp.net_asp.net_ajax_updatepanel.txt
Q: GCC - "expected unqualified-id before ')' token" Please bear with me, I'm just learning C++. I'm trying to write my header file (for class) and I'm running into an odd error. cards.h:21: error: expected unqualified-id before ')' token cards.h:22: error: expected `)' before "str" cards.h:23: error: expected `)' before "r" What does "expected unqualified-id before ')' token" mean? And what am I doing wrong? Edit: Sorry, I didn't post the entire code. /* Card header file [Author] */ // NOTE: Lanugage Docs here http://www.cplusplus.com/doc/tutorial/ #define Card #define Hand #define AppError #include <string> using namespace std; // TODO: Docs here class Card { // line 17 public: enum Suit {Club, Diamond, Spade, Heart}; enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}; Card(); // line 22 Card(string str); Card(Rank r, Suit s); Edit: I'm just trying to compile the header file by itself using "g++ file.h". Edit: Closed question. My code is working now. Thanks everyone! Edit: Reopened question after reading Etiquette: Closing your posts A: Your issue is your #define. You did #define Card, so now everywhere Card is seen as a token, it will be replaced. Usually a #define Token with no additional token, as in #define Token Replace will use the value 1. Remove the #define Card, it's making line 22 read: 1(); or ();, which is causing the complaint. A: (edited for updated question) Remove the #define statements, they're mangling the file. Were you trying to implement an include guard? That would be something like this: #ifndef CARD_H #define CARD_H class Card ... ... #endif old answer: It means that string is not defined in the current line. Try std::string. A: Just my two cents, but I guess you used the pre-compiled header #define Card #define Hand #define AppError as if you wanted to tell the compiler "Hey, the classes Card, Hand and AppError are defined elsewhere" (i.e. forward-declarations). Even if we ignore the fact macros are a pain for the exact reasons your code did not compile (as John Millikin put it, mangling your file), perhaps what you wanted to write was something like: class Card ; class Hand ; class AppError ; Which are forward-declarations of those classes. A: Remove the #define Card.
GCC - "expected unqualified-id before ')' token"
Please bear with me, I'm just learning C++. I'm trying to write my header file (for class) and I'm running into an odd error. cards.h:21: error: expected unqualified-id before ')' token cards.h:22: error: expected `)' before "str" cards.h:23: error: expected `)' before "r" What does "expected unqualified-id before ')' token" mean? And what am I doing wrong? Edit: Sorry, I didn't post the entire code. /* Card header file [Author] */ // NOTE: Lanugage Docs here http://www.cplusplus.com/doc/tutorial/ #define Card #define Hand #define AppError #include <string> using namespace std; // TODO: Docs here class Card { // line 17 public: enum Suit {Club, Diamond, Spade, Heart}; enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}; Card(); // line 22 Card(string str); Card(Rank r, Suit s); Edit: I'm just trying to compile the header file by itself using "g++ file.h". Edit: Closed question. My code is working now. Thanks everyone! Edit: Reopened question after reading Etiquette: Closing your posts
[ "Your issue is your #define. You did #define Card, so now everywhere Card is seen as a token, it will be replaced.\nUsually a #define Token with no additional token, as in #define Token Replace will use the value 1.\nRemove the #define Card, it's making line 22 read: 1(); or ();, which is causing the complaint.\n", "(edited for updated question)\nRemove the #define statements, they're mangling the file. Were you trying to implement an include guard? That would be something like this:\n#ifndef CARD_H\n#define CARD_H\n\nclass Card ...\n...\n\n#endif\n\n\nold answer:\nIt means that string is not defined in the current line. Try std::string.\n", "Just my two cents, but I guess you used the pre-compiled header\n#define Card\n#define Hand\n#define AppError\n\nas if you wanted to tell the compiler \"Hey, the classes Card, Hand and AppError are defined elsewhere\" (i.e. forward-declarations).\nEven if we ignore the fact macros are a pain for the exact reasons your code did not compile (as John Millikin put it, mangling your file), perhaps what you wanted to write was something like:\nclass Card ;\nclass Hand ;\nclass AppError ;\n\nWhich are forward-declarations of those classes.\n", "Remove the #define Card.\n" ]
[ 13, 4, 2, 0 ]
[]
[]
[ "c++" ]
stackoverflow_0000106117_c++.txt
Q: Why is my Java program leaking memory when I call run() on a Thread object? (Jeopardy-style question, I wish the answer had been online when I had this issue) Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed. But I found that my program would leak memory over time. What am I doing wrong? A: This is a known bug in Java 1.4: http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087 It's fixed in Java 1.5 but Sun doesn't intend to fix it in 1.4. The issue is that, at construction time, a Thread is added to a list of references in an internal thread table. It won't get removed from that list until its start() method has completed. As long as that reference is there, it won't get garbage collected. So, never create a thread unless you're definitely going to call its start() method. A Thread object's run() method should not be called directly. A better way to code it is to implement the Runnable interface rather than subclass Thread. When you don't need a thread, call myRunnable.run(); When you do need a thread: Thread myThread = new Thread(myRunnable); myThread.start(); A: I doubt that constructing an instance of a Thread or a subclass thereof leaks memory. Firstly, there's nothing of the sorts mentioned in the Javadocs or the Java Language Specification. Secondly, I ran a simple test and it also shows that no memory is leaked (at least not on Sun's JDK 1.5.0_05 on 32-bit x86 Linux 2.6): public final class Test { public static final void main(String[] params) throws Exception { final Runtime rt = Runtime.getRuntime(); long i = 0; while(true) { new MyThread().run(); i++; if ((i % 100) == 0) { System.out.println((i / 100) + ": " + (rt.freeMemory() / 1024 / 1024) + " " + (rt.totalMemory() / 1024 / 1024)); } } } static class MyThread extends Thread { private final byte[] tmp = new byte[10 * 1024 * 1024]; public void run() { System.out.print("."); } } } EDIT: Just to summarize the idea of the test above. Every instance of the MyThread subclass of a Thread references its own 10 MB array. If instances of MyThread weren't garbage-collected, the JVM would run out of memory pretty quickly. However, running the test code shows that the JVM is using a small constant amount of memory regardless of the number of MyThreads constructed so far. I claim this is because instances of MyThread are garbage-collected. A: Let's see if we could get nearer to the core of the problem: If you start your program (lets say) 1000 x using start(), then 1000 x using run() in a thread, do both loose memory? If so, then your algorithm should be checked (i.e. for outer objects such as Vectors used in your Runnable). If there is no such memory leak as described above then you should investigate about starting parameters and memory usage of threads regarding the JVM.
Why is my Java program leaking memory when I call run() on a Thread object?
(Jeopardy-style question, I wish the answer had been online when I had this issue) Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed. But I found that my program would leak memory over time. What am I doing wrong?
[ "This is a known bug in Java 1.4:\nhttp://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087\nIt's fixed in Java 1.5 but Sun doesn't intend to fix it in 1.4.\nThe issue is that, at construction time, a Thread is added to a list of references in an internal thread table. It won't get removed from that list until its start() method has completed. As long as that reference is there, it won't get garbage collected.\nSo, never create a thread unless you're definitely going to call its start() method. A Thread object's run() method should not be called directly.\nA better way to code it is to implement the Runnable interface rather than subclass Thread. When you don't need a thread, call\nmyRunnable.run();\n\nWhen you do need a thread:\nThread myThread = new Thread(myRunnable);\nmyThread.start();\n\n", "I doubt that constructing an instance of a Thread or a subclass thereof leaks memory. Firstly, there's nothing of the sorts mentioned in the Javadocs or the Java Language Specification. Secondly, I ran a simple test and it also shows that no memory is leaked (at least not on Sun's JDK 1.5.0_05 on 32-bit x86 Linux 2.6):\npublic final class Test {\n public static final void main(String[] params) throws Exception {\n final Runtime rt = Runtime.getRuntime();\n long i = 0;\n while(true) {\n new MyThread().run();\n i++;\n if ((i % 100) == 0) {\n System.out.println((i / 100) + \": \" + (rt.freeMemory() / 1024 / 1024) + \" \" + (rt.totalMemory() / 1024 / 1024));\n }\n }\n }\n\n static class MyThread extends Thread {\n private final byte[] tmp = new byte[10 * 1024 * 1024];\n\n public void run() {\n System.out.print(\".\");\n }\n }\n}\n\nEDIT: Just to summarize the idea of the test above. Every instance of the MyThread subclass of a Thread references its own 10 MB array. If instances of MyThread weren't garbage-collected, the JVM would run out of memory pretty quickly. However, running the test code shows that the JVM is using a small constant amount of memory regardless of the number of MyThreads constructed so far. I claim this is because instances of MyThread are garbage-collected.\n", "Let's see if we could get nearer to the core of the problem:\nIf you start your program (lets say) 1000 x using start(), then 1000 x using run() in a thread, do both loose memory? If so, then your algorithm should be checked (i.e. for outer objects such as Vectors used in your Runnable).\nIf there is no such memory leak as described above then you should investigate about starting parameters and memory usage of threads regarding the JVM.\n" ]
[ 48, 3, 2 ]
[]
[]
[ "java", "memory_leaks", "multithreading" ]
stackoverflow_0000107823_java_memory_leaks_multithreading.txt
Q: How Does Listening to a Multicast Hurt Me? I'm receiving a recovery feed from an exchange for recovering data missed from their primary feed. The exchange strongly recommends listening to the recovery feed only when data is needed, and leaving the multicast once I have recovered the data I need. My question is, if I am using asio, and not reading from the NIC when I don't need it, what is the harm? The messages have sequence numbers, so I can't accidentally process an old message "left" on the card. Is this really harming my application? A: It's likely not harming your application so much as harming your machine - since the nic is still configured into the multicast group, it's still listening to those messages and passing them up, before your software ignores them and they get discarded. That's a lot of extra work that your network stack and kernel are doing, and therefore a lot of extra load on the machine in general, not just your app. A: Listening to your recovery feed could also have a potential impact on a network level. As pjz mentioned, your NIC and IP stack will have more frames/packets to process. In addition, more of your available bandwidth is being used up by data that is not being used by your application; this could lead to dropped frames if there is congestion on your link. Whether congestion is likely to occur depends on whether your server is 100Mb or 1Gb attached, how much other traffic your host is sending/receiving, etc. Another potential concern is the impact on other hosts. If the switch your host is attached to does not have IGMP snooping enabled, then all hosts on the same VLAN will receive the additional multicast traffic, which could lead them to experience the same problems as mentioned above. If you have a networking team administering your network for you, it may be worth seeking out some recommendations from them? If you feel it is necessary to subscribe to a redundant feed, it would seem prudent to work out what level of redundancy already exists in your network and how likely it is that messages on the primary feed will be lost. A: An addition to muz's comment... It's unlikely that this will make any difference to your system, but it's worth being aware that there is an overhead associated with maintaining a multicast membership (assuming that you're using IGMP - which is probably reasonable given the restriction about "leaving the multicast") IGMP requires the sending and processing of multicast group memberships at regular intervals. And (as alluded to in muz's comment) if you have any switches or routers between you and the multicast source that are capable of igmp snooping then they are able to disable the multicast for a given network.
How Does Listening to a Multicast Hurt Me?
I'm receiving a recovery feed from an exchange for recovering data missed from their primary feed. The exchange strongly recommends listening to the recovery feed only when data is needed, and leaving the multicast once I have recovered the data I need. My question is, if I am using asio, and not reading from the NIC when I don't need it, what is the harm? The messages have sequence numbers, so I can't accidentally process an old message "left" on the card. Is this really harming my application?
[ "It's likely not harming your application so much as harming your machine - since the nic is still configured into the multicast group, it's still listening to those messages and passing them up, before your software ignores them and they get discarded. That's a lot of extra work that your network stack and kernel are doing, and therefore a lot of extra load on the machine in general, not just your app.\n", "Listening to your recovery feed could also have a potential impact on a network level. As pjz mentioned, your NIC and IP stack will have more frames/packets to process. In addition, more of your available bandwidth is being used up by data that is not being used by your application; this could lead to dropped frames if there is congestion on your link. Whether congestion is likely to occur depends on whether your server is 100Mb or 1Gb attached, how much other traffic your host is sending/receiving, etc.\nAnother potential concern is the impact on other hosts. If the switch your host is attached to does not have IGMP snooping enabled, then all hosts on the same VLAN will receive the additional multicast traffic, which could lead them to experience the same problems as mentioned above.\nIf you have a networking team administering your network for you, it may be worth seeking out some recommendations from them? If you feel it is necessary to subscribe to a redundant feed, it would seem prudent to work out what level of redundancy already exists in your network and how likely it is that messages on the primary feed will be lost.\n", "An addition to muz's comment...\nIt's unlikely that this will make any difference to your system, but it's worth being aware that there is an overhead associated with maintaining a multicast membership (assuming that you're using IGMP - which is probably reasonable given the restriction about \"leaving the multicast\")\nIGMP requires the sending and processing of multicast group memberships at regular intervals. And (as alluded to in muz's comment) if you have any switches or routers between you and the multicast source that are capable of igmp snooping then they are able to disable the multicast for a given network.\n" ]
[ 5, 4, 1 ]
[]
[]
[ "boost_asio", "language_agnostic", "network_programming", "networking", "udp" ]
stackoverflow_0000073194_boost_asio_language_agnostic_network_programming_networking_udp.txt
Q: QDrag destroyed while dragging I have a Windows/Linux Qt 4.3 application that uses drag and drop in a QTreeView. I have two very similar applications which use the same set of Qt libraries. Drag and drop works in both on Linux but in only in one on Windows. In the application that does not work the QDrag object gets deleted as soon as the mouse is moved. It is deleted by a DeferredDelete event from the event queue which is still processed in Qt during a drag. I do not know how to see what is causing the QDrag object to get deleted prematurely. I can not figure out a good way to debug this problem. I have compared the source and cannot find anything obvious. I have tried using the code from one of the applications in the other application. Any suggestions? Update: The reason the QDrag operation failed is because COM was not initialized successfully so the call to DoDragDrop in QDrag::exec returned immediately. QApplication tried to initialize COM by calling OleInitialize in qt_init but it failed with the error "Cannot change thread mode after it is set". The interesting thing is that this happens even when OleInitialize is the first thing done in main so the thread mode is getting set initially by some external dependency. One of the differences between the applications that work on Windows is that the one that fails also contains .NET code so maybe that is the problem. Solved: This problem is a COM/CLR interop issue. The CLR sets the apartment state to MTA when it initializes and then when Qt attempts to initialize COM it fails. This problem and an old solution are discussed by Adam Nathan in Gotcha with STAThreadAttribute and Managed C++. In Visual Studio 2005 you can set the /CLRTHREADATTRIBUTE:STA compiler option in Configuration Properties > Linker > Advanced to set the threading attribute to STA without needing to create a new entry point. A: I have no idea what can cause this, but I would try to find out by subclassing QDrag, overwrite deleteLater() (well, reimplement it, but as it's a slot, it will get called anyway), use this instead of a QDrag and put a breakpoint in deleteLater().
QDrag destroyed while dragging
I have a Windows/Linux Qt 4.3 application that uses drag and drop in a QTreeView. I have two very similar applications which use the same set of Qt libraries. Drag and drop works in both on Linux but in only in one on Windows. In the application that does not work the QDrag object gets deleted as soon as the mouse is moved. It is deleted by a DeferredDelete event from the event queue which is still processed in Qt during a drag. I do not know how to see what is causing the QDrag object to get deleted prematurely. I can not figure out a good way to debug this problem. I have compared the source and cannot find anything obvious. I have tried using the code from one of the applications in the other application. Any suggestions? Update: The reason the QDrag operation failed is because COM was not initialized successfully so the call to DoDragDrop in QDrag::exec returned immediately. QApplication tried to initialize COM by calling OleInitialize in qt_init but it failed with the error "Cannot change thread mode after it is set". The interesting thing is that this happens even when OleInitialize is the first thing done in main so the thread mode is getting set initially by some external dependency. One of the differences between the applications that work on Windows is that the one that fails also contains .NET code so maybe that is the problem. Solved: This problem is a COM/CLR interop issue. The CLR sets the apartment state to MTA when it initializes and then when Qt attempts to initialize COM it fails. This problem and an old solution are discussed by Adam Nathan in Gotcha with STAThreadAttribute and Managed C++. In Visual Studio 2005 you can set the /CLRTHREADATTRIBUTE:STA compiler option in Configuration Properties > Linker > Advanced to set the threading attribute to STA without needing to create a new entry point.
[ "I have no idea what can cause this, but I would try to find out by subclassing QDrag, overwrite deleteLater() (well, reimplement it, but as it's a slot, it will get called anyway), use this instead of a QDrag and put a breakpoint in deleteLater(). \n" ]
[ 2 ]
[]
[]
[ "c++", "com", "drag_and_drop", "qt" ]
stackoverflow_0000106056_c++_com_drag_and_drop_qt.txt
Q: Inserting a string of form "GUID1, GUID2, GUID3 ..." into an IN statement in TSQL I've got a stored procedure in my database, that looks like this ALTER PROCEDURE [dbo].[GetCountingAnalysisResults] @RespondentFilters varchar AS BEGIN @RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f''' DECLARE @SQL nvarchar(600) SET @SQL = 'SELECT * FROM Answer WHERE Answer.RespondentId IN ('+@RespondentFilters+''')) GROUP BY ChosenOptionId' exec sp_executesql @SQL END It compiles and executes, but somehow it doesn't give me good results, just like the IN statement wasn't working. Please, if anybody know the solution to this problem, help me. A: You should definitely look at splitting the list of GUIDs into a table and joining against that table. You should be able to find plenty of examples online for a table-valued function that splits an input string into a table. Otherwise, your stored procedure is vulnerable to SQL injection. Consider the following value for @RespondentFilters: @RespondentFilters = '''''); SELECT * FROM User; /*' Your query would be more secure parsing (i.e. validating) the parameter values and joining: SELECT * FROM Answer WHERE Answer.RespondentId IN (SELECT [Item] FROM dbo.ParseList(@RespondentFilters)) GROUP BY ChosenOptionId or SELECT * FROM Answer INNER JOIN dbo.ParseList(@RespondentFilters) Filter ON Filter.Item = Answer.RespondentId GROUP BY ChosenOptionId It's slightly more efficient as well, since you aren't dealing with dynamic SQL (sp_executesql will cache query plans, but I'm not sure if it will accurately identify your query as a parameterized query since it has a variable list of items in the IN clause). A: You need single quotes around each GUID in the list @RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'', ''114c61f2-8935-4755-b4e9-4a598a51cc7f''' A: It looks like you don't have closing quotes around your @RespondentFilters '8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f' Since GUIDs do a string compare, that's not going to work. Your best bet is to use some code to split the list out into multiple values. Something like this: -- This would be the input parameter of the stored procedure, if you want to do it that way, or a UDF declare @string varchar(500) set @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z' declare @pos int declare @piece varchar(500) -- Need to tack a delimiter onto the end of the input string if one doesn't exist if right(rtrim(@string),1) ',' set @string = @string + ',' set @pos = patindex('%,%' , @string) while @pos 0 begin set @piece = left(@string, @pos - 1) -- You have a piece of data, so insert it, print it, do whatever you want to with it. print cast(@piece as varchar(500)) set @string = stuff(@string, 1, @pos, '') set @pos = patindex('%,%' , @string) end Code stolen from Raymond Lewallen A: I think you need quotes inside the string too. Try: @RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'',''114c61f2-8935-4755-b4e9-4a598a51cc7f''' You could also consider parsing the @RespondentFilters into a temporary table. A: Tank you all for your ansewers. They all helped a lot. I've dealt with the problem by writing a split function, and it works fine. It's a litte bit overhead from what I could have done, but you know, the deadline is hiding around the corner :)
Inserting a string of form "GUID1, GUID2, GUID3 ..." into an IN statement in TSQL
I've got a stored procedure in my database, that looks like this ALTER PROCEDURE [dbo].[GetCountingAnalysisResults] @RespondentFilters varchar AS BEGIN @RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f''' DECLARE @SQL nvarchar(600) SET @SQL = 'SELECT * FROM Answer WHERE Answer.RespondentId IN ('+@RespondentFilters+''')) GROUP BY ChosenOptionId' exec sp_executesql @SQL END It compiles and executes, but somehow it doesn't give me good results, just like the IN statement wasn't working. Please, if anybody know the solution to this problem, help me.
[ "You should definitely look at splitting the list of GUIDs into a table and joining against that table. You should be able to find plenty of examples online for a table-valued function that splits an input string into a table.\nOtherwise, your stored procedure is vulnerable to SQL injection. Consider the following value for @RespondentFilters:\n@RespondentFilters = '''''); SELECT * FROM User; /*'\n\nYour query would be more secure parsing (i.e. validating) the parameter values and joining:\nSELECT *\nFROM Answer\nWHERE Answer.RespondentId IN (SELECT [Item] FROM dbo.ParseList(@RespondentFilters))\nGROUP BY ChosenOptionId\n\nor\nSELECT *\nFROM Answer\nINNER JOIN dbo.ParseList(@RespondentFilters) Filter ON Filter.Item = Answer.RespondentId\nGROUP BY ChosenOptionId\n\nIt's slightly more efficient as well, since you aren't dealing with dynamic SQL (sp_executesql will cache query plans, but I'm not sure if it will accurately identify your query as a parameterized query since it has a variable list of items in the IN clause).\n", "You need single quotes around each GUID in the list\n@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'', ''114c61f2-8935-4755-b4e9-4a598a51cc7f'''\n\n", "It looks like you don't have closing quotes around your @RespondentFilters '8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f'\nSince GUIDs do a string compare, that's not going to work. \nYour best bet is to use some code to split the list out into multiple values.\nSomething like this:\n\n-- This would be the input parameter of the stored procedure, if you want to do it that way, or a UDF\ndeclare @string varchar(500)\nset @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'\n\n\ndeclare @pos int\ndeclare @piece varchar(500)\n\n-- Need to tack a delimiter onto the end of the input string if one doesn't exist\nif right(rtrim(@string),1) ','\n set @string = @string + ','\n\nset @pos = patindex('%,%' , @string)\nwhile @pos 0\nbegin\n set @piece = left(@string, @pos - 1)\n\n -- You have a piece of data, so insert it, print it, do whatever you want to with it.\n print cast(@piece as varchar(500))\n\n set @string = stuff(@string, 1, @pos, '')\n set @pos = patindex('%,%' , @string)\nend\n\nCode stolen from Raymond Lewallen\n", "I think you need quotes inside the string too. Try:\n@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a'',''114c61f2-8935-4755-b4e9-4a598a51cc7f'''\n\nYou could also consider parsing the @RespondentFilters into a temporary table.\n", "Tank you all for your ansewers. They all helped a lot. I've dealt with the problem by writing a split function, and it works fine. It's a litte bit overhead from what I could have done, but you know, the deadline is hiding around the corner :)\n" ]
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "guid", "sql_server", "stored_procedures", "tsql" ]
stackoverflow_0000093653_guid_sql_server_stored_procedures_tsql.txt
Q: Closing/cleaning up "mixed" file descriptors / sockets When I create a socket using accept() and make a FILE out of it using fdopen(), what do I have to do to clean everything up? Do I need to do fclose() on the FILE, shutdown() and close() on the socket, or only the shutdown() and or close() or fclose()? If I don't do fclose(), do I have to free() the FILE pointer manually? A: From man fdopen: The file descriptor is not dup’ed, and will be closed when the stream created by fdopen() is closed So I would just use fclose(), which also closes the underlying file descriptor. I don't know whether shutdown() is needed, either. A: From http://opengroup.org/onlinepubs/007908775/xsh/fclose.html The fclose() function will perform a close() on the file descriptor that is associated with the stream pointed to by stream. If you've wrapped your socket in a stream it probably no longer makes sense to shutdown(), at least not without flushing the stream first. But I won't swear to that, because I don't know that there are no uses where you'd want to shutdown() rather than just close().
Closing/cleaning up "mixed" file descriptors / sockets
When I create a socket using accept() and make a FILE out of it using fdopen(), what do I have to do to clean everything up? Do I need to do fclose() on the FILE, shutdown() and close() on the socket, or only the shutdown() and or close() or fclose()? If I don't do fclose(), do I have to free() the FILE pointer manually?
[ "From man fdopen:\n\nThe file descriptor is not dup’ed, and will be closed when the stream created by fdopen() is closed\n\nSo I would just use fclose(), which also closes the underlying file descriptor. I don't know whether shutdown() is needed, either.\n", "From http://opengroup.org/onlinepubs/007908775/xsh/fclose.html\n\nThe fclose() function will perform a\n close() on the file descriptor that is\n associated with the stream pointed to\n by stream.\n\nIf you've wrapped your socket in a stream it probably no longer makes sense to shutdown(), at least not without flushing the stream first. But I won't swear to that, because I don't know that there are no uses where you'd want to shutdown() rather than just close().\n" ]
[ 5, 3 ]
[ "You have 2 things here you need to clean up: the stream represented by FILE and the file descriptor represented by the socket. You need to close the stream first, then the file descriptor. So, in general you will need to fclose() any FILE objects, then close() any file descriptors.\nPersonally I have never used shutdown() when I want to cleanup after myself, so I can't say.\nedit\nOthers have correctly pointed out that fdclose() will also close the underlying file descriptor, and since calling close() on a close file descriptor will lead to an error, in this case you only need fdclose().\n" ]
[ -1 ]
[ "c", "file_descriptor", "io", "sockets" ]
stackoverflow_0000108043_c_file_descriptor_io_sockets.txt
Q: How do you diagnose a leak in C memory caused by a Java program? I'm working on a large application (300K LOC) that is causing a memory leak in the Sun 1.6 JVM (1.6_05). Profiling the Java shows no leak. Are there any diagnostics available from the JVM that might detect the cause of the leak? I haven't been able to create a simple, isolated Java test case. Is the only way to figure this out by using a C heap analyzer on the JVM? The application creates a pool of sockets and does a significant amount of network I/O. A: Some profiler like profiler4j can show the managed and the unmanaged memory (live curve). Then you can see if you has a leak and when the leak occur. But you does not find more informations. After this there are 2 possible solutions: You can with the live curve isolate the problem and create a simpler test until you have find the cause of the problem. You search your code for the typical problems like: Instances of the class Thread that are never start. Images or Graphics that never are dispose ODBC Bridge Objects that are never close A: I love valgrind ( http://valgrind.org/ ), if you are executing it on a system it supports. It really rocks!
How do you diagnose a leak in C memory caused by a Java program?
I'm working on a large application (300K LOC) that is causing a memory leak in the Sun 1.6 JVM (1.6_05). Profiling the Java shows no leak. Are there any diagnostics available from the JVM that might detect the cause of the leak? I haven't been able to create a simple, isolated Java test case. Is the only way to figure this out by using a C heap analyzer on the JVM? The application creates a pool of sockets and does a significant amount of network I/O.
[ "Some profiler like profiler4j can show the managed and the unmanaged memory (live curve). Then you can see if you has a leak and when the leak occur. But you does not find more informations.\nAfter this there are 2 possible solutions:\n\nYou can with the live curve isolate the problem and create a simpler test until you have find the cause of the problem.\nYou search your code for the typical problems like:\n\n\nInstances of the class Thread that are never start.\nImages or Graphics that never are dispose\nODBC Bridge Objects that are never close\n\n\n", "I love valgrind ( http://valgrind.org/ ), if you are executing it on a system it supports. It really rocks!\n" ]
[ 2, 0 ]
[]
[]
[ "java", "memory_leaks" ]
stackoverflow_0000108057_java_memory_leaks.txt
Q: MySQL 5.0 instance manager like functionality for earlier versions? MySQL introduced a server side utility that lets you manage multiple instances on a remote machine. I am looking for similar functionality for earlier versions of mysql. [1]http://dev.mysql.com/doc/refman/5.0/en/instance-manager.html A: I am not familiar with the instance manager, but I have used phpMyAdmin on several systems (including a remotely hosted server) with great success. It supports MySQL 5.0 and 4.1.
MySQL 5.0 instance manager like functionality for earlier versions?
MySQL introduced a server side utility that lets you manage multiple instances on a remote machine. I am looking for similar functionality for earlier versions of mysql. [1]http://dev.mysql.com/doc/refman/5.0/en/instance-manager.html
[ "I am not familiar with the instance manager, but I have used phpMyAdmin on several systems (including a remotely hosted server) with great success. It supports MySQL 5.0 and 4.1.\n" ]
[ 1 ]
[]
[]
[ "multiple_instances", "mysql_management" ]
stackoverflow_0000102318_multiple_instances_mysql_management.txt
Q: How does VxWorks deal with priority inheritance? We have 3 tasks running at different priorities: A (120), B (110), C (100). A takes a mutex semaphore with the Inversion Safe flag. Task B does a semTake, which causes Task A's priority to be elevated to 110. Later, task C does a semTake. Task A's priority is now 100. At this point, A releases the semaphore and C grabs it. We notice that A's priority did not go back down to its original priority of 120. Shouldn't A's priority be restored right away? A: Ideally, when the inherited priority level is lowered, it will be done in a step-wise fashion. As each dependency that caused the priority level to be bumped up is removed, the inherited priority level should drop down to the priority level of the highest remaining dependency. For Example: task A (100 bumped up to 80) has two mutexes (X & Y) that tasks B (pri 90) and task C (pri 80) are respectively pending for. When task A gives up mutex Y to task C, we might expect that its priority will drop to 90. When it finally gives up mutex X to task B, we would expect its priority level to drop back to 100. Priority inheritance does not work that way in VxWorks. How it works depends on the version of VxWorks you are using. pre-VxWorks 6.0 The priority level remains "bumped up" until the task that has the lock on the mutex semaphore gives up its last inversion safe mutex semaphore. Using the example from above, when task A gives up mutex Y to task C, its priority remains at 80. After it gives up mutex X to task B, then its priority will drop back to 100 (skipping 90). Let's throw curve ball #1 into the mix. What if task A had a lock on mutex Z while all this was going on, but no one was pending on Z? In that case, the priority level will remain at 80 until Z is given up--then it will drop back to 100. Why do it this way? It's simple, and for most cases, it is good enough. However, it does mean that when "curve ball #1" comes into play, the priority will remain higher for a longer period of time than is necessary. VxWorks 6.0+ The priority level now remains elevated until the task that has the lock on the mutex semaphore gives up its last inversion safe mutex that contributed to raising the priority level. This improvement avoids the problem of "curve ball #1". It does have its own limitations. For example, if task B and/or task C time(s) out while waiting for task A to give up the semaphores, task A's priority level does not get recalculated until it gives up the semaphore.
How does VxWorks deal with priority inheritance?
We have 3 tasks running at different priorities: A (120), B (110), C (100). A takes a mutex semaphore with the Inversion Safe flag. Task B does a semTake, which causes Task A's priority to be elevated to 110. Later, task C does a semTake. Task A's priority is now 100. At this point, A releases the semaphore and C grabs it. We notice that A's priority did not go back down to its original priority of 120. Shouldn't A's priority be restored right away?
[ "Ideally, when the inherited priority level is\nlowered, it will be done in a step-wise fashion. As each\ndependency that caused the priority level to be bumped up is removed,\nthe inherited priority level should drop down to the priority level of\nthe highest remaining dependency.\nFor Example:\ntask A (100 bumped up to 80) has two mutexes (X & Y)\nthat tasks B (pri 90) and task C (pri 80) are respectively pending\nfor. When task A gives up mutex Y to task C, we might expect that its\npriority will drop to 90. When it finally gives up mutex X to task B,\nwe would expect its priority level to drop back to 100.\nPriority inheritance does not work that way in VxWorks.\nHow it works depends on the version of VxWorks you are using.\npre-VxWorks 6.0\nThe priority level remains \"bumped up\" until the task that has the\nlock on the mutex semaphore gives up its last inversion safe mutex\nsemaphore. \nUsing the example from above, when task A gives up mutex Y\nto task C, its priority remains at 80. After it gives up mutex X to\ntask B, then its priority will drop back to 100 (skipping 90). \nLet's throw curve ball #1 into the mix. What if task A had a lock on mutex\nZ while all this was going on, but no one was pending on Z? In that\ncase, the priority level will remain at 80 until Z is given up--then\nit will drop back to 100.\nWhy do it this way?\nIt's simple, and for most cases, it is good\nenough. However, it does mean that when \"curve ball #1\" comes into\nplay, the priority will remain higher for a longer period of time than\nis necessary.\nVxWorks 6.0+\nThe priority level now\nremains elevated until the task that has the lock on the mutex\nsemaphore gives up its last inversion safe mutex that contributed to\nraising the priority level. \nThis improvement avoids the problem of\n\"curve ball #1\". It does have its own limitations. For example, if\ntask B and/or task C time(s) out while waiting for task A to give up\nthe semaphores, task A's priority level does not get recalculated\nuntil it gives up the semaphore.\n" ]
[ 6 ]
[]
[]
[ "semaphore", "vxworks" ]
stackoverflow_0000108098_semaphore_vxworks.txt
Q: Ruby Soap4R Web Service, .NET Consumer How do I generate WSDL from a Web Service in Ruby using Soap4R (SOAP::RPC::StandaloneServer) that would be consumed from .NET? A: There's not a way to do this through SOAP4R, unfortunately. SOAP4R is more for interacting with SOAP endpoints, or generating your own through a WSDL specification. The only Ruby code I know that does this comes from ActionWebService, which was part of Rails, pre-Rails 2. If you install the gem actionwebservice (you'll have to force it, most likely), you can look at the method to_wsdl in the file lib/action_web_service/dispatcher/action_controller_dispatcher.rb. This builds WSDL using the Builder library. The definitions for the WSDL are defined using methods in ActionWebService::API. It should not be too hard to extract that code into something you can use for your project.
Ruby Soap4R Web Service, .NET Consumer
How do I generate WSDL from a Web Service in Ruby using Soap4R (SOAP::RPC::StandaloneServer) that would be consumed from .NET?
[ "There's not a way to do this through SOAP4R, unfortunately. SOAP4R is more for interacting with SOAP endpoints, or generating your own through a WSDL specification.\nThe only Ruby code I know that does this comes from ActionWebService, which was part of Rails, pre-Rails 2. If you install the gem actionwebservice (you'll have to force it, most likely), you can look at the method to_wsdl in the file lib/action_web_service/dispatcher/action_controller_dispatcher.rb. This builds WSDL using the Builder library. The definitions for the WSDL are defined using methods in ActionWebService::API. It should not be too hard to extract that code into something you can use for your project.\n" ]
[ 2 ]
[]
[]
[ "ruby", "soap4r", "web_services" ]
stackoverflow_0000105177_ruby_soap4r_web_services.txt
Q: How to display only one validation error message with a with MyFaces Trinidad? For a registration form I have something simple like: <tr:panelLabelAndMessage label="Zip/City" showRequired="true"> <tr:inputText id="zip" value="#{data['registration'].zipCode}" contentStyle="width:36px" simple="true" required="true" /> <tr:inputText id="city" value="#{data['registration'].city}" contentStyle="width:133px" simple="true" required="true" /> </tr:panelLabelAndMessage> <tr:message for="zip" /> <tr:message for="city" /> When including the last two lines, I get two messages on validation error. When ommiting last to lines, a javascript alert shows up, which is not what I want. Is there a solution to show only one validation failed message somehow? Thanks a lot! A: Problem is, the fields must layout horizontally. It's a no-go to put ZIP field and city not next to each other in one line. At least for me. A co-worker has pointed me to set a faclets variable inside the first tr:message and to put a rendered attribute at the second one that reacts on this variable. Havn't got the time to try nor found the right command for setting a varable yet. Will post results as soon as possible. A: I know this won't be ideal, but if you remove the panelLabelAndMessage tag and just use the label attribute on the inputText tag that should remove the extra error message.
How to display only one validation error message with a with MyFaces Trinidad?
For a registration form I have something simple like: <tr:panelLabelAndMessage label="Zip/City" showRequired="true"> <tr:inputText id="zip" value="#{data['registration'].zipCode}" contentStyle="width:36px" simple="true" required="true" /> <tr:inputText id="city" value="#{data['registration'].city}" contentStyle="width:133px" simple="true" required="true" /> </tr:panelLabelAndMessage> <tr:message for="zip" /> <tr:message for="city" /> When including the last two lines, I get two messages on validation error. When ommiting last to lines, a javascript alert shows up, which is not what I want. Is there a solution to show only one validation failed message somehow? Thanks a lot!
[ "Problem is, the fields must layout horizontally. It's a no-go to put ZIP field and city not next to each other in one line. At least for me.\nA co-worker has pointed me to set a faclets variable inside the first tr:message and to put a rendered attribute at the second one that reacts on this variable. Havn't got the time to try nor found the right command for setting a varable yet. Will post results as soon as possible.\n", "I know this won't be ideal, but if you remove the panelLabelAndMessage tag and just use the label attribute on the inputText tag that should remove the extra error message. \n" ]
[ 1, 0 ]
[]
[]
[ "myfaces", "trinidad", "webforms" ]
stackoverflow_0000092027_myfaces_trinidad_webforms.txt
Q: What is the best way to replace the file browse button in html? I know that it's possible to replace the browse button, which is generated in html, when you use input tag with type="file. I'm not sure what is the best way, so if someone has experience with this please contribute. A: The best way is to make the file input control almost invisible (by giving it a very low opacity - do not do "visibility: hidden" or "display: none") and absolutely position something under it - with a lower z-index. This way, the actual control will not be visible, and whatever you put under it will show through. But since the control is positioned above that button, it will still capture the click events (this is why you want to use opacity, not visibility or display - browsers make the element unclickable if you use those to hide it). This article goes in-depth on the technique. A: Browsers don't really like you to mess around with file inputs, but it's possible to do this. I've seen a couple of techniques, but the simplest is to absolutely position the file input over whatever you want to use as a button, and set its opacity to zero or near-zero. This means that when the user clicks on the image (or whatever you have under there) they're actually clicking on the invisible browse button. For example: <input type="file" id="fileInput"> <img src="..."> #fileInput{ position: absolute; opacity: 0; -moz-opacity: 0; filter: alpha(opacity=0); } A: If you don't mind using javascript you can set the opasity of the file-input to 0, place your styled control on top via z-index and send clickevents from your button to the file-input. See here for the technique: http://www.quirksmode.org/dom/inputfile.html A: This isn't technically possible for security purposes, so the user cannot be misled. However, there are a couple of workarounds - take a look at http://www.quirksmode.org/dom/inputfile.html for one example. For the record, this question has already been asked here (where I gave the same answer). A: You can use a Flash uploader like SWFupload to do this, as well.
What is the best way to replace the file browse button in html?
I know that it's possible to replace the browse button, which is generated in html, when you use input tag with type="file. I'm not sure what is the best way, so if someone has experience with this please contribute.
[ "The best way is to make the file input control almost invisible (by giving it a very low opacity - do not do \"visibility: hidden\" or \"display: none\") and absolutely position something under it - with a lower z-index.\nThis way, the actual control will not be visible, and whatever you put under it will show through. But since the control is positioned above that button, it will still capture the click events (this is why you want to use opacity, not visibility or display - browsers make the element unclickable if you use those to hide it).\nThis article goes in-depth on the technique.\n", "Browsers don't really like you to mess around with file inputs, but it's possible to do this. I've seen a couple of techniques, but the simplest is to absolutely position the file input over whatever you want to use as a button, and set its opacity to zero or near-zero. This means that when the user clicks on the image (or whatever you have under there) they're actually clicking on the invisible browse button.\nFor example:\n<input type=\"file\" id=\"fileInput\">\n<img src=\"...\">\n\n#fileInput{\n position: absolute;\n opacity: 0;\n -moz-opacity: 0;\n filter: alpha(opacity=0);\n}\n\n", "If you don't mind using javascript you can set the opasity of the file-input to 0, place your styled control on top via z-index and send clickevents from your button to the file-input. See here for the technique: http://www.quirksmode.org/dom/inputfile.html\n", "This isn't technically possible for security purposes, so the user cannot be misled.\nHowever, there are a couple of workarounds - take a look at http://www.quirksmode.org/dom/inputfile.html for one example.\nFor the record, this question has already been asked here (where I gave the same answer).\n", "You can use a Flash uploader like SWFupload to do this, as well.\n" ]
[ 22, 5, 2, 0, 0 ]
[]
[]
[ "css", "file", "html", "input" ]
stackoverflow_0000108149_css_file_html_input.txt
Q: cURL in PHP returns different data in _FILE and _RETURNTRANSFER I have noticed that cURL in PHP returns different data when told to output to a file via CURLOPT_FILE as it does when told to send the output to a string via CURLOPT_RETURNTRANSFER. _RETURNTRANSFER seems to strip newlines and extra white space as if parsing it for display as standard HTML code. _FILE on the other hand preserves the file exactly as it was intended. I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have _RETURNTRANSFER return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible. Here is the code I am using. The data in question is a CSV file with \r\n line endings. function update_roster() { $url = "http://example.com/"; $userID = "xx"; $apikey = "xxx"; $passfields = "userID=$userID&apikey=$apikey"; $file = fopen("roster.csv","w+"); $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FILE, $file); $variable_in_question = curl_exec ($ch); curl_close ($ch); fclose($file); return $variable_in_question; } Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that. This works just fine:$cresult = split("\r\n", $cresult); This does not: $cresult = split('\r\n', $cresult); A: Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that. This works just fine:$cresult = split("\r\n", $cresult); This does not: $cresult = split('\r\n', $cresult); A: In most scripting langage (it's also true in Bash for instance), simple quotes are used to represent things as they are written, whereas double quotes are "analysed" (i don't think it's the appropriate word but i can't find better). $str = 'foo'; echo '$str'; // print “$str” to the screen echo "$str"; // print “foo” to the screen It is true for variables and escaped characters. A: I didn't try to reproduce the "bug" (I think we can consider this as a bug if it is the actual behavior), but maybe you could get over it. The PHP Doc says that the default comportement is to write the result to a file, and that the default file is STDOUT (the browser's window). What you want is to get the same result than in a file but in a variable. You could do that using ob_start(); and ob_get_clean();. $ch = curl_init(...); // ... ob_start(); curl_exec($ch); $yourResult = ob_get_clean(); curl_close($ch); I know that's not really the clean way (if there is one), but at least it sould work fine. (Please excuse me if my english is not perfect ;-)...)
cURL in PHP returns different data in _FILE and _RETURNTRANSFER
I have noticed that cURL in PHP returns different data when told to output to a file via CURLOPT_FILE as it does when told to send the output to a string via CURLOPT_RETURNTRANSFER. _RETURNTRANSFER seems to strip newlines and extra white space as if parsing it for display as standard HTML code. _FILE on the other hand preserves the file exactly as it was intended. I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have _RETURNTRANSFER return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible. Here is the code I am using. The data in question is a CSV file with \r\n line endings. function update_roster() { $url = "http://example.com/"; $userID = "xx"; $apikey = "xxx"; $passfields = "userID=$userID&apikey=$apikey"; $file = fopen("roster.csv","w+"); $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FILE, $file); $variable_in_question = curl_exec ($ch); curl_close ($ch); fclose($file); return $variable_in_question; } Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that. This works just fine:$cresult = split("\r\n", $cresult); This does not: $cresult = split('\r\n', $cresult);
[ "Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \\r\\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.\nThis works just fine:$cresult = split(\"\\r\\n\", $cresult);\nThis does not: $cresult = split('\\r\\n', $cresult);\n", "In most scripting langage (it's also true in Bash for instance), simple quotes are used to represent things as they are written, whereas double quotes are \"analysed\" (i don't think it's the appropriate word but i can't find better).\n$str = 'foo';\necho '$str'; // print “$str” to the screen\necho \"$str\"; // print “foo” to the screen\n\nIt is true for variables and escaped characters.\n", "I didn't try to reproduce the \"bug\" (I think we can consider this as a bug if it is the actual behavior), but maybe you could get over it.\nThe PHP Doc says that the default comportement is to write the result to a file, and that the default file is STDOUT (the browser's window). What you want is to get the same result than in a file but in a variable.\nYou could do that using ob_start(); and ob_get_clean();.\n$ch = curl_init(...);\n// ...\nob_start();\ncurl_exec($ch);\n$yourResult = ob_get_clean();\ncurl_close($ch);\n\nI know that's not really the clean way (if there is one), but at least it sould work fine.\n(Please excuse me if my english is not perfect ;-)...)\n" ]
[ 1, 1, 0 ]
[]
[]
[ "curl", "php" ]
stackoverflow_0000104223_curl_php.txt
Q: How to display latest revision in a file? I'm wondering how do you deal with displaying release revision number when pushing live new versions of your app? You can use $Rev$ in a file to get latest revision, but only after you update the file. What if I want to update a string in one file every time I change any file in the repository/directory? Is there a way? A: The best way to do this is have a build script for releases that will determine the revision number using svnversion or svn info and insert it into a file. It's always helpful to have a script which: checks out a clean copy of the source into an empty directory uses svnversion or something similar to compute a build number compiles source into a product creates an archive (zip or tarball or whatever) of the product cleans up: deletes everything but the archive Then you have a one-step process to create a release with an easily identifiable version. It also helps you avoid giving someone a build from your own working copy, which may have changes that were never checked into source control. A: There is a simple tool in TortoiseSVN named SubWCRev.exe. It takes revision from path and create file from your own template. You can use it as prebuild command. A: Did you try to use hooks? They work on server-side only but may do the trick. Otherwise I would just call a script do update the revision if the keywords aren't suitable for you. A: Automatically update the file as part of building/deploying the release. A: On the one project where I had a reason do this, I cheated: it calls svnversion on itself when it starts up. A: As alexander said, one way is to update the revision as part of the build process. One method of doing this is to take your release builds from an automated build process triggered from your version control checkin, by using a tool such as buildbot. A scenario might be to trigger the automated build using the post-hook script on your subversion repository. This causes your buildbot to update to the most recently checked in revision. Your build script (eg. Makefile) would use 'svnversion' (or 'svn info' and grep) to read the repository revision and write it into a header file before the build takes place. After the successful build, automatically check this file back into the repository with a suitable comment about the release version.
How to display latest revision in a file?
I'm wondering how do you deal with displaying release revision number when pushing live new versions of your app? You can use $Rev$ in a file to get latest revision, but only after you update the file. What if I want to update a string in one file every time I change any file in the repository/directory? Is there a way?
[ "The best way to do this is have a build script for releases that will determine the revision number using svnversion or svn info and insert it into a file. It's always helpful to have a script which:\n\nchecks out a clean copy of the source into an empty directory\nuses svnversion or something similar to compute a build number\ncompiles source into a product\ncreates an archive (zip or tarball or whatever) of the product\ncleans up: deletes everything but the archive\n\nThen you have a one-step process to create a release with an easily identifiable version. It also helps you avoid giving someone a build from your own working copy, which may have changes that were never checked into source control.\n", "There is a simple tool in TortoiseSVN named SubWCRev.exe. It takes revision from path and create file from your own template. You can use it as prebuild command.\n", "Did you try to use hooks? They work on server-side only but may do the trick. Otherwise I would just call a script do update the revision if the keywords aren't suitable for you.\n", "Automatically update the file as part of building/deploying the release.\n", "On the one project where I had a reason do this, I cheated: it calls svnversion on itself when it starts up.\n", "As alexander said, one way is to update the revision as part of the build process.\nOne method of doing this is to take your release builds from an automated build process triggered from your version control checkin, by using a tool such as buildbot.\nA scenario might be to trigger the automated build using the post-hook script on your subversion repository.\nThis causes your buildbot to update to the most recently checked in revision.\nYour build script (eg. Makefile) would use 'svnversion' (or 'svn info' and grep) to read the repository revision and write it into a header file before the build takes place.\nAfter the successful build, automatically check this file back into the repository with a suitable comment about the release version.\n" ]
[ 8, 3, 2, 2, 1, 1 ]
[]
[]
[ "svn", "versioning" ]
stackoverflow_0000107840_svn_versioning.txt
Q: Hibernate 3: unable to query PostgreSQL database I am setting up a project using Hibernate 3.3.1 GA and PostgreSQL 8.3. I've just created a database, the first table, added one row there and now configuring Hibernate. However, even the simplest query: Criteria criteria = session.createCriteria(Place.class); List result = criteria.list(); could not be executed (empty list is returned though there is one record in the database). I looked at the PostgreSQL logs to see: 2008-09-17 22:52:59 CEST LOG: connection received: host=192.168.175.1 port=2670 2008-09-17 22:52:59 CEST LOG: connection authorized: user=... database=... 2008-09-17 22:53:00 CEST LOG: execute <unnamed>: SHOW TRANSACTION ISOLATION LEVEL 2008-09-17 22:53:02 CEST LOG: could not receive data from client: Connection reset by peer 2008-09-17 22:53:02 CEST LOG: unexpected EOF on client connection 2008-09-17 22:53:02 CEST LOG: disconnection: session time: 0:00:03.011 user=... database=... host=192.168.175.1 port=2670 I wrote a simple program using plain JDBC to fetch the same data and it worked. PostgreSQL logs in this case look like this (for comparison): 2008-09-17 22:52:24 CEST LOG: connection received: host=192.168.175.1 port=2668 2008-09-17 22:52:24 CEST LOG: connection authorized: user=... database=... 2008-09-17 22:52:25 CEST LOG: execute <unnamed>: SELECT * from PLACE 2008-09-17 22:52:25 CEST LOG: disconnection: session time: 0:00:00.456 user=... database=... host=192.168.175.1 port=2668 Hibernate debug log does not indicate any errors. If I take the query listed in the logs: 15:17:01,859 DEBUG org.hibernate.loader.entity.EntityLoader: Static select for entity com.example.data.Place: select place0_.ID as ID0_0_, place0_.NAME as NAME0_0_, place0_.LATITUDE as LATITUDE0_0_, place0_.LONGITUDE as LONGITUDE0_0_ from PLACE place0_ where place0_.ID=? and execute it agains the database in the psql, it works (this means that Hibernate has generated a proper SQL). Below is the Hibernate configuration: <hibernate-configuration> <session-factory> <property name="hibernate.connection.url">jdbc:postgresql://192.168.175.128:5433/...</property> <property name="hibernate.connection.driver_class">org.postgresql.Driver</property> <property name="hibernate.connection.username">...</property> <property name="hibernate.connection.password">...</property> <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.use_outer_join">true</property> <mapping resource="com/example/data/Place.hbm.xml"/> </session-factory> </hibernate-configuration> ...and the mapping file: <hibernate-mapping package="com.example.data"> <class name="com.example.data.Place" table="PLACE"> <id column="ID" name="id" type="java.lang.Integer"> <generator class="native"/> </id> <property column="NAME" name="name" not-null="true" type="java.lang.String"> <meta attribute="use-in-tostring">true</meta> </property> <property column="LATITUDE" name="latitude" not-null="true" type="java.lang.Float"> <meta attribute="use-in-tostring">true</meta> </property> <property column="LONGITUDE" name="longitude" not-null="true" type="java.lang.Float"> <meta attribute="use-in-tostring">true</meta> </property> </class> </hibernate-mapping> Googling for unexpected EOF log entry was not friutful. Any ideas, community? A: After applying debugger to the Hibernate code, it is fixed! It is not visible in the question's text, but the problem is that Place passed to the createCriteria() method is from another package, not com/example/data, specified in the configuration XML files. Hibernate invokes Class.isAssignableFrom(), and if false is returned, it exits silently, thus breaking the connection. I will open a ticket for Hibernate developers on this matter.
Hibernate 3: unable to query PostgreSQL database
I am setting up a project using Hibernate 3.3.1 GA and PostgreSQL 8.3. I've just created a database, the first table, added one row there and now configuring Hibernate. However, even the simplest query: Criteria criteria = session.createCriteria(Place.class); List result = criteria.list(); could not be executed (empty list is returned though there is one record in the database). I looked at the PostgreSQL logs to see: 2008-09-17 22:52:59 CEST LOG: connection received: host=192.168.175.1 port=2670 2008-09-17 22:52:59 CEST LOG: connection authorized: user=... database=... 2008-09-17 22:53:00 CEST LOG: execute <unnamed>: SHOW TRANSACTION ISOLATION LEVEL 2008-09-17 22:53:02 CEST LOG: could not receive data from client: Connection reset by peer 2008-09-17 22:53:02 CEST LOG: unexpected EOF on client connection 2008-09-17 22:53:02 CEST LOG: disconnection: session time: 0:00:03.011 user=... database=... host=192.168.175.1 port=2670 I wrote a simple program using plain JDBC to fetch the same data and it worked. PostgreSQL logs in this case look like this (for comparison): 2008-09-17 22:52:24 CEST LOG: connection received: host=192.168.175.1 port=2668 2008-09-17 22:52:24 CEST LOG: connection authorized: user=... database=... 2008-09-17 22:52:25 CEST LOG: execute <unnamed>: SELECT * from PLACE 2008-09-17 22:52:25 CEST LOG: disconnection: session time: 0:00:00.456 user=... database=... host=192.168.175.1 port=2668 Hibernate debug log does not indicate any errors. If I take the query listed in the logs: 15:17:01,859 DEBUG org.hibernate.loader.entity.EntityLoader: Static select for entity com.example.data.Place: select place0_.ID as ID0_0_, place0_.NAME as NAME0_0_, place0_.LATITUDE as LATITUDE0_0_, place0_.LONGITUDE as LONGITUDE0_0_ from PLACE place0_ where place0_.ID=? and execute it agains the database in the psql, it works (this means that Hibernate has generated a proper SQL). Below is the Hibernate configuration: <hibernate-configuration> <session-factory> <property name="hibernate.connection.url">jdbc:postgresql://192.168.175.128:5433/...</property> <property name="hibernate.connection.driver_class">org.postgresql.Driver</property> <property name="hibernate.connection.username">...</property> <property name="hibernate.connection.password">...</property> <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.use_outer_join">true</property> <mapping resource="com/example/data/Place.hbm.xml"/> </session-factory> </hibernate-configuration> ...and the mapping file: <hibernate-mapping package="com.example.data"> <class name="com.example.data.Place" table="PLACE"> <id column="ID" name="id" type="java.lang.Integer"> <generator class="native"/> </id> <property column="NAME" name="name" not-null="true" type="java.lang.String"> <meta attribute="use-in-tostring">true</meta> </property> <property column="LATITUDE" name="latitude" not-null="true" type="java.lang.Float"> <meta attribute="use-in-tostring">true</meta> </property> <property column="LONGITUDE" name="longitude" not-null="true" type="java.lang.Float"> <meta attribute="use-in-tostring">true</meta> </property> </class> </hibernate-mapping> Googling for unexpected EOF log entry was not friutful. Any ideas, community?
[ "After applying debugger to the Hibernate code, it is fixed!\nIt is not visible in the question's text, but the problem is that Place passed to the createCriteria() method is from another package, not com/example/data, specified in the configuration XML files. \nHibernate invokes Class.isAssignableFrom(), and if false is returned, it exits silently, thus breaking the connection. I will open a ticket for Hibernate developers on this matter.\n" ]
[ 3 ]
[]
[]
[ "database", "hibernate", "java", "jdbc", "postgresql" ]
stackoverflow_0000108171_database_hibernate_java_jdbc_postgresql.txt
Q: Can you access a Delphi DBIV database without it creating lock files? I'm trying to read data from a Delphi DBIV database, every time I access the database it creates a Paradox.lck and a Pdoxusrs.lck file. I'm using only a TQuery Object to do this (nothing else). can I access a Delphi DBIV database without it creating these lock files? A: Why don't you want the lock files? Without really looking into it, I assume those lock files have a real purpose It's been a while since I've used the BDE, but can't you use some keyword in your SELECT query to indicate that you do not want any locking? For example in MS SQL you can use the following syntax: SELECT * WITH(NOLOCK) FROM SomeTable A: If your application is creating PARADOX.LCK and PDOXUSRS.LCK files, it is also creating or accessing a PDOXUSRS.NET file somewhere. The BDE uses a single common PDOXUSRS.NET file, and a PARADOX.LCK and PDOXUSRS.LCK file in each shared directory, to coordinate shared access among the distributed instances of the engine. You must find out if your application shares the tables with any other application. If the data is shared, you must allow the BDE to create and use these lock files. If you are certain that you are the SOLE user of the data, you can eliminate the creation of the lock files. But -- unless the lock files are the only thing preventing you from doing something useful, it is rarely worth blocking their creation. Registry entries tell the BDE where to find its configuration file. A configuration file editor ships with the BDE; look for BDEADMIN.EXE or BDECFG32.EXE. The configuration editor uses the same registry entry to determine which file to edit. To avoid creating lock files when you are the sole user of the data: Open the config editor. Go to Configuration | Drivers | native | PARADOX, or Drivers | PARADOX, and note the NET DIR entry. Set the NET DIR value to blank. Go to Configuration | System | INIT, or System, and set LOCAL SHARE to False. Save your edits. Follow the path you noted in step 2 and delete the PDOXUSRS.NET found there. Delete any leftover PARADOX.LCK or PDOXUSRS.LCK files in your data directory. Warning: fooling around with the lock files when you don't understand their purpose is a good way to brick your app. -Al. A: Thanks for your responses. I'll look into both of your suggestions. To A I Breveleri: yeah I know what your saying, I'm reluctant to switch them off, but the other App that uses the database is far more important than mine. Ideally I'd like the following to happen: My app starts getting data, if the other app wants to use the database then my app stops. At the moment the exact opposite is happening. Stew.
Can you access a Delphi DBIV database without it creating lock files?
I'm trying to read data from a Delphi DBIV database, every time I access the database it creates a Paradox.lck and a Pdoxusrs.lck file. I'm using only a TQuery Object to do this (nothing else). can I access a Delphi DBIV database without it creating these lock files?
[ "Why don't you want the lock files? Without really looking into it, I assume those lock files have a real purpose\nIt's been a while since I've used the BDE, but can't you use some keyword in your SELECT query to indicate that you do not want any locking?\nFor example in MS SQL you can use the following syntax:\nSELECT * WITH(NOLOCK)\nFROM SomeTable\n\n", "If your application is creating PARADOX.LCK and PDOXUSRS.LCK files, it is also creating or accessing a PDOXUSRS.NET file somewhere.\nThe BDE uses a single common PDOXUSRS.NET file, and a PARADOX.LCK and PDOXUSRS.LCK file in each shared directory, to coordinate shared access among the distributed instances of the engine.\nYou must find out if your application shares the tables with any other application. If the data is shared, you must allow the BDE to create and use these lock files.\nIf you are certain that you are the SOLE user of the data, you can eliminate the creation of the lock files. But -- unless the lock files are the only thing preventing you from doing something useful, it is rarely worth blocking their creation.\nRegistry entries tell the BDE where to find its configuration file. A configuration file editor ships with the BDE; look for BDEADMIN.EXE or BDECFG32.EXE. The configuration editor uses the same registry entry to determine which file to edit.\nTo avoid creating lock files when you are the sole user of the data:\n\nOpen the config editor.\nGo to Configuration | Drivers | native | PARADOX, or Drivers | PARADOX, and note the NET DIR entry.\nSet the NET DIR value to blank.\nGo to Configuration | System | INIT, or System, and set LOCAL SHARE to False.\nSave your edits.\nFollow the path you noted in step 2 and delete the PDOXUSRS.NET found there.\nDelete any leftover PARADOX.LCK or PDOXUSRS.LCK files in your data directory.\n\nWarning: fooling around with the lock files when you don't understand their purpose is a good way to brick your app.\n-Al.\n", "Thanks for your responses. I'll look into both of your suggestions. \nTo A I Breveleri:\nyeah I know what your saying, I'm reluctant to switch them off, but the other App that uses the database is far more important than mine. Ideally I'd like the following to happen:\nMy app starts getting data, if the other app wants to use the database then my app stops.\nAt the moment the exact opposite is happening. \nStew.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "database", "delphi" ]
stackoverflow_0000100917_database_delphi.txt
Q: Subclassed form not behaving properly in Designer view (VS 2008) I have subclassed Form to include some extra functionality, which boils down to a List<Image> which displays in a set of predefined spots on the form. I have the following: public class ButtonForm : Form { public class TitleButton { public TitleButton() { /* does stuff here */ } // there's other stuff too, just thought I should point out there's // a default constructor. } private List<TitleButton> _buttons = new List<TitleButton>(); public List<TitleButton> TitleButtons { get { return _buttons; } set { _buttons = value; } } // Other stuff here } Then my actual form that I want to use is a subclass of ButtonForm instead of Form. This all works great, Designer even picks up the new property and shows it up on the property list. I thought this would be great! It showed the collection, I could add the buttons into there and away I would go. So I opened the collection editor, added in all the objects, and lo and behold, there sitting in the designer was a picture perfect view of what I wanted. This is where it starts to get ugly. For some reason or another, Designer refuses to actually generate code to create the objects and attach them to the collection, so while it looks great in Design mode, as soon as I compile and run it, it all disappears again and I'm back to square one. I'm at a total loss as to why this would happen; if the Designer can generate it well enough to get a picture perfect view of my form with the extra behaviour, why can't/won't it generate the code into the actual code file? A: First of all you need to inherit your TitleButton class from Component so that the designer knows it is a component that can be created via designer generated code. Then you need to instruct the designer code generator to work on the contents of the collection and not the collection instance itself. So try the following... public class TitleButton : Component { // ... } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List<TitleButton> TitleButtons { // ... }
Subclassed form not behaving properly in Designer view (VS 2008)
I have subclassed Form to include some extra functionality, which boils down to a List<Image> which displays in a set of predefined spots on the form. I have the following: public class ButtonForm : Form { public class TitleButton { public TitleButton() { /* does stuff here */ } // there's other stuff too, just thought I should point out there's // a default constructor. } private List<TitleButton> _buttons = new List<TitleButton>(); public List<TitleButton> TitleButtons { get { return _buttons; } set { _buttons = value; } } // Other stuff here } Then my actual form that I want to use is a subclass of ButtonForm instead of Form. This all works great, Designer even picks up the new property and shows it up on the property list. I thought this would be great! It showed the collection, I could add the buttons into there and away I would go. So I opened the collection editor, added in all the objects, and lo and behold, there sitting in the designer was a picture perfect view of what I wanted. This is where it starts to get ugly. For some reason or another, Designer refuses to actually generate code to create the objects and attach them to the collection, so while it looks great in Design mode, as soon as I compile and run it, it all disappears again and I'm back to square one. I'm at a total loss as to why this would happen; if the Designer can generate it well enough to get a picture perfect view of my form with the extra behaviour, why can't/won't it generate the code into the actual code file?
[ "First of all you need to inherit your TitleButton class from Component so that the designer knows it is a component that can be created via designer generated code. Then you need to instruct the designer code generator to work on the contents of the collection and not the collection instance itself. So try the following...\npublic class TitleButton : Component\n{\n // ... \n}\n\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic List<TitleButton> TitleButtons\n{\n // ...\n}\n\n" ]
[ 3 ]
[]
[]
[ "c#", "visual_studio_2008", "winforms" ]
stackoverflow_0000108270_c#_visual_studio_2008_winforms.txt
Q: Does the tee command always wait for EOF? I'd like to log the output of a command to stdout as well as to a log file. I've got Cygwin installed and I'm trying to use the tee command to accomplish this. devenv mysolution.sln /build myproject "Release|Win32" | tee build.log Trouble is that tee seems to insist on waiting for the end of file before outputting anything to either stdout or the log file. This takes away the point of it all, which is to have a log file for future reference, but also some stdout logging so I can easily see the build progress. tee's options appear to be limited to --append, --ignore-interrupts, --help, and --version. So is there another method to get to what I'm trying to do? A: You can output to the file and tail -f the file. devenv mysolution.sln /build myproject "Release|Win32" > build.log & tail -f build.log A: Write your own! (The point here is that the autoflush ($|) setting is turned on, so every line seen is flushed straight away. This may perhaps be what the real tee command lacked.) #!/usr/bin/perl -w use strict; use IO::File; $| = 1; my @fhs = map IO::File->new(">$_"), @ARGV; while (my $line = <STDIN>) { print $line; $_->print($line) for @fhs; } $_->close for @fhs; You can call the script anything you want. I call it perlmilktee! :-P A: tee seems to insist on waiting for the end of file before outputting anything to either stdout or the log file. This should definitely not be happening - it would render tee nearly useless. Here's a simple test that I wrote that puts this to the test, and it's definitely not waiting for eof. $ cat test #!/bin/sh echo "hello" sleep 5 echo "goodbye" $ ./test | tee test.log hello <pause> goodbye
Does the tee command always wait for EOF?
I'd like to log the output of a command to stdout as well as to a log file. I've got Cygwin installed and I'm trying to use the tee command to accomplish this. devenv mysolution.sln /build myproject "Release|Win32" | tee build.log Trouble is that tee seems to insist on waiting for the end of file before outputting anything to either stdout or the log file. This takes away the point of it all, which is to have a log file for future reference, but also some stdout logging so I can easily see the build progress. tee's options appear to be limited to --append, --ignore-interrupts, --help, and --version. So is there another method to get to what I'm trying to do?
[ "You can output to the file and tail -f the file.\ndevenv mysolution.sln /build myproject \"Release|Win32\" > build.log &\ntail -f build.log\n", "Write your own! (The point here is that the autoflush ($|) setting is turned on, so every line seen is flushed straight away. This may perhaps be what the real tee command lacked.)\n#!/usr/bin/perl -w\nuse strict;\nuse IO::File;\n$| = 1;\nmy @fhs = map IO::File->new(\">$_\"), @ARGV;\nwhile (my $line = <STDIN>) {\n print $line;\n $_->print($line) for @fhs;\n}\n$_->close for @fhs;\n\nYou can call the script anything you want. I call it perlmilktee! :-P\n", "\ntee seems to insist on waiting for the\n end of file before outputting anything\n to either stdout or the log file.\n\nThis should definitely not be happening - it would render tee nearly useless. Here's a simple test that I wrote that puts this to the test, and it's definitely not waiting for eof. \n$ cat test\n#!/bin/sh\necho \"hello\"\nsleep 5\necho \"goodbye\"\n\n$ ./test | tee test.log\nhello\n<pause>\ngoodbye\n\n" ]
[ 4, 2, 2 ]
[]
[]
[ "command_line", "cygwin" ]
stackoverflow_0000106563_command_line_cygwin.txt
Q: Which SharePoint 2007 features are not available to Office 2003 users? I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list? I have been searching for awhile but I cannot seem to find a comprehensive list. Thanks :) A: There is an entire MS white paper on Office integration with SharePoint: http://download.microsoft.com/download/5/d/c/5dcfc15a-c31e-4a14-93cf-b44bce3e447e/Microsoft%20Office%20and%20SharePoint%20Integration%20White%20Paper.doc A: This post might be helpful: http://www.sharepointusecases.com/index.php/2008/08/office-2003-and-sharepoint-2007-comparision
Which SharePoint 2007 features are not available to Office 2003 users?
I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list? I have been searching for awhile but I cannot seem to find a comprehensive list. Thanks :)
[ "There is an entire MS white paper on Office integration with SharePoint:\nhttp://download.microsoft.com/download/5/d/c/5dcfc15a-c31e-4a14-93cf-b44bce3e447e/Microsoft%20Office%20and%20SharePoint%20Integration%20White%20Paper.doc\n", "This post might be helpful: http://www.sharepointusecases.com/index.php/2008/08/office-2003-and-sharepoint-2007-comparision\n" ]
[ 1, 1 ]
[]
[]
[ "ms_office", "sharepoint" ]
stackoverflow_0000106000_ms_office_sharepoint.txt
Q: How do you resolve crashing Windbg Logger on Vista? I would like to use the Logger tool that ships with the Microsoft Debugging Tools for Windows. However, on Vista it crashes even with built-in Vista applications: > logger calc or > logger notepad The issue occurs if I run the tool from a command prompt with or without administrator rights. I'm using version 3.01 (3/20/2008). The last thing the Logger output window shows is "Verbose log Enabled". If I attach a debugger I see that an "Access violation writing location 0x000000" error has occurred with the following call stack: logexts.dll!_LogGetCategory@20() + 0xb bytes logger.exe!PopulateLogextsSettings() + 0x31 bytes logger.exe!SettingsDlgProc() + 0x48 bytes user32.dll!_InternalCallWinProc@20() + 0x23 bytes user32.dll!_UserCallDlgProcCheckWow@32() - 0x19bc bytes user32.dll!_DefDlgProcWorker@20() + 0x7f bytes user32.dll!_DefDlgProcA@16() + 0x22 bytes user32.dll!_InternalCallWinProc@20() + 0x23 bytes user32.dll!_UserCallWinProcCheckWow@32() + 0xb3 bytes user32.dll!_SendMessageWorker@20() + 0xd5 bytes user32.dll!_InternalCreateDialog@28() + 0x700 bytes user32.dll!_InternalDialogBox@24() + 0xa3 bytes user32.dll!_DialogBoxIndirectParamAorW@24() + 0x36 bytes user32.dll!_DialogBoxParamA@20() + 0x4c bytes logger.exe!ChooseSettings() + 0x24 bytes logger.exe!InitLogexts() + 0x84 bytes logger.exe!DebuggerLoop() + 0x210 bytes logger.exe!_WinMain@16() + 0x215 bytes logger.exe!__initterm_e() + 0x1a1 bytes kernel32.dll!@BaseThreadInitThunk@12() + 0x12 bytes ntdll.dll!___RtlUserThreadStart@8() + 0x27 bytes ntdll.dll!__RtlUserThreadStart@8() + 0x1b bytes Anybody encountered this issue and know how to fix it? A: I'm using 6.9.3.113 (April 29, 2008) of the debugging tools, and I don't get any problems on Vista. If I try running logger notepad it works OK (even as a non-admin). The first thing I would check is that if you're running the x64 version of Vista, you'll need to use the 64bit version of the debugging tools as well.
How do you resolve crashing Windbg Logger on Vista?
I would like to use the Logger tool that ships with the Microsoft Debugging Tools for Windows. However, on Vista it crashes even with built-in Vista applications: > logger calc or > logger notepad The issue occurs if I run the tool from a command prompt with or without administrator rights. I'm using version 3.01 (3/20/2008). The last thing the Logger output window shows is "Verbose log Enabled". If I attach a debugger I see that an "Access violation writing location 0x000000" error has occurred with the following call stack: logexts.dll!_LogGetCategory@20() + 0xb bytes logger.exe!PopulateLogextsSettings() + 0x31 bytes logger.exe!SettingsDlgProc() + 0x48 bytes user32.dll!_InternalCallWinProc@20() + 0x23 bytes user32.dll!_UserCallDlgProcCheckWow@32() - 0x19bc bytes user32.dll!_DefDlgProcWorker@20() + 0x7f bytes user32.dll!_DefDlgProcA@16() + 0x22 bytes user32.dll!_InternalCallWinProc@20() + 0x23 bytes user32.dll!_UserCallWinProcCheckWow@32() + 0xb3 bytes user32.dll!_SendMessageWorker@20() + 0xd5 bytes user32.dll!_InternalCreateDialog@28() + 0x700 bytes user32.dll!_InternalDialogBox@24() + 0xa3 bytes user32.dll!_DialogBoxIndirectParamAorW@24() + 0x36 bytes user32.dll!_DialogBoxParamA@20() + 0x4c bytes logger.exe!ChooseSettings() + 0x24 bytes logger.exe!InitLogexts() + 0x84 bytes logger.exe!DebuggerLoop() + 0x210 bytes logger.exe!_WinMain@16() + 0x215 bytes logger.exe!__initterm_e() + 0x1a1 bytes kernel32.dll!@BaseThreadInitThunk@12() + 0x12 bytes ntdll.dll!___RtlUserThreadStart@8() + 0x27 bytes ntdll.dll!__RtlUserThreadStart@8() + 0x1b bytes Anybody encountered this issue and know how to fix it?
[ "I'm using 6.9.3.113 (April 29, 2008) of the debugging tools, and I don't get any problems on Vista. If I try running \nlogger notepad\n\nit works OK (even as a non-admin). The first thing I would check is that if you're running the x64 version of Vista, you'll need to use the 64bit version of the debugging tools as well.\n" ]
[ 1 ]
[]
[]
[ "debugging", "windbg", "windows_vista" ]
stackoverflow_0000105022_debugging_windbg_windows_vista.txt
Q: Parse multiple XML files with ASP.NET (C#) and return those with particular element Greetings. I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element. Example XML file 1: <file> <title>Title 1</title> <someContent>Content</someContent> <filter>filter</filter> </file> Example XML file 2: <file> <title>Title 2</title> <someContent>Content</someContent> <filter>filter, different filter</filter> </file> Example case 1: Give me all XML that has a filter of 'filter'. Example case 2: Give me all XML that has a title of 'Title 1'. Looking, it seems this should be possible with LINQ, but I've only seen examples on how to do this when there is one XML file, not when there are multiples, such as in this case. I would prefer that this be done on the server-side, so that I can cache on that end. Functionality from any version of the .NET Framework can be used. Thanks! ~James A: If you are using .Net 3.5, this is extremely easy with LINQ: //get the files XElement xe1 = XElement.Load(string_file_path_1); XElement xe2 = XElement.Load(string_file_path_2); //Give me all XML that has a filter of 'filter'. var filter_elements1 = from p in xe1.Descendants("filter") select p; var filter_elements2 = from p in xe2.Descendants("filter") select p; var filter_elements = filter_elements1.Union(filter_elements2); //Give me all XML that has a title of 'Title 1'. var title1 = from p in xe1.Descendants("title") where p.Value.Equals("Title 1") select p; var title2 = from p in xe2.Descendants("title") where p.Value.Equals("Title 1") select p; var titles = title1.Union(title2); This can all be written shorthand and get you your results in just 4 lines total: XElement xe1 = XElement.Load(string_file_path_1); XElement xe2 = XElement.Load(string_file_path_2); var _filter_elements = (from p1 in xe1.Descendants("filter") select p1).Union(from p2 in xe2.Descendants("filter") select p2); var _titles = (from p1 in xe1.Descendants("title") where p1.Value.Equals("Title 1") select p1).Union(from p2 in xe2.Descendants("title") where p2.Value.Equals("Title 1") select p2); These will all be IEnumerable lists, so they are super easy to work with: foreach (var v in filter_elements) Response.Write("value of filter element" + v.Value + "<br />"); LINQ rules! A: You might want to create your own iterator class that iterate over those files. Say, make a XMLContentEnumerator : IEnumerable. that would iterate over files in a specific directory and parse its content, and then you would be able to make a normal LINQ filtering query such as: var xc = new XMLContentEnumerator(@"C:\dir"); var filesWithHello = xc.Where(x => x.title.Contains("hello")); I don't have the environment to provide a full example, but this should give some ideas. A: Here's one way using Framework 2.0. You can make this cleaner by using regular expressions rather than a simple string test. You can also try compiling your XPath expressions if you need to squeeze more for performance. static void Main(string[] args) { string[] myFiles = { @"C:\temp\XMLFile1.xml", @"C:\temp\XMLFile2.xml", @"C:\temp\XMLFile3.xml" }; foreach (string file in myFiles) { System.Xml.XPath.XPathDocument myDoc = new System.Xml.XPath.XPathDocument(file); System.Xml.XPath.XPathNavigator myNav = myDoc.CreateNavigator(); if(myNav.SelectSingleNode("/file/filter[1]") != null && myNav.SelectSingleNode("/file/filter[1]").InnerXml.Contains("filter")) Console.WriteLine(file + " Contains 'filter'"); if (myNav.SelectSingleNode("/file/title[1]") != null && myNav.SelectSingleNode("/file/title[1]").InnerXml.Contains("Title 1")) Console.WriteLine(file + " Contains 'Title 1'"); } Console.ReadLine(); } A: Use XPath? http://www.w3schools.com/XPath/default.asp
Parse multiple XML files with ASP.NET (C#) and return those with particular element
Greetings. I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element. Example XML file 1: <file> <title>Title 1</title> <someContent>Content</someContent> <filter>filter</filter> </file> Example XML file 2: <file> <title>Title 2</title> <someContent>Content</someContent> <filter>filter, different filter</filter> </file> Example case 1: Give me all XML that has a filter of 'filter'. Example case 2: Give me all XML that has a title of 'Title 1'. Looking, it seems this should be possible with LINQ, but I've only seen examples on how to do this when there is one XML file, not when there are multiples, such as in this case. I would prefer that this be done on the server-side, so that I can cache on that end. Functionality from any version of the .NET Framework can be used. Thanks! ~James
[ "If you are using .Net 3.5, this is extremely easy with LINQ:\n//get the files\nXElement xe1 = XElement.Load(string_file_path_1);\nXElement xe2 = XElement.Load(string_file_path_2);\n\n//Give me all XML that has a filter of 'filter'.\nvar filter_elements1 = from p in xe1.Descendants(\"filter\") select p;\nvar filter_elements2 = from p in xe2.Descendants(\"filter\") select p;\nvar filter_elements = filter_elements1.Union(filter_elements2);\n\n//Give me all XML that has a title of 'Title 1'.\nvar title1 = from p in xe1.Descendants(\"title\") where p.Value.Equals(\"Title 1\") select p;\nvar title2 = from p in xe2.Descendants(\"title\") where p.Value.Equals(\"Title 1\") select p;\nvar titles = title1.Union(title2);\n\nThis can all be written shorthand and get you your results in just 4 lines total:\nXElement xe1 = XElement.Load(string_file_path_1);\nXElement xe2 = XElement.Load(string_file_path_2);\nvar _filter_elements = (from p1 in xe1.Descendants(\"filter\") select p1).Union(from p2 in xe2.Descendants(\"filter\") select p2);\nvar _titles = (from p1 in xe1.Descendants(\"title\") where p1.Value.Equals(\"Title 1\") select p1).Union(from p2 in xe2.Descendants(\"title\") where p2.Value.Equals(\"Title 1\") select p2);\n\nThese will all be IEnumerable lists, so they are super easy to work with:\nforeach (var v in filter_elements)\n Response.Write(\"value of filter element\" + v.Value + \"<br />\");\n\nLINQ rules!\n", "You might want to create your own iterator class that iterate over those files.\nSay, make a XMLContentEnumerator : IEnumerable. that would iterate over files in a specific directory and parse its content, and then you would be able to make a normal LINQ filtering query such as:\nvar xc = new XMLContentEnumerator(@\"C:\\dir\");\n\nvar filesWithHello = xc.Where(x => x.title.Contains(\"hello\"));\n\nI don't have the environment to provide a full example, but this should give some ideas.\n", "Here's one way using Framework 2.0. You can make this cleaner by using regular expressions rather than a simple string test. You can also try compiling your XPath expressions if you need to squeeze more for performance.\nstatic void Main(string[] args)\n{\n string[] myFiles = { @\"C:\\temp\\XMLFile1.xml\", \n @\"C:\\temp\\XMLFile2.xml\", \n @\"C:\\temp\\XMLFile3.xml\" };\n foreach (string file in myFiles)\n {\n System.Xml.XPath.XPathDocument myDoc = \n new System.Xml.XPath.XPathDocument(file);\n System.Xml.XPath.XPathNavigator myNav = \n myDoc.CreateNavigator();\n\n if(myNav.SelectSingleNode(\"/file/filter[1]\") != null &&\n myNav.SelectSingleNode(\"/file/filter[1]\").InnerXml.Contains(\"filter\"))\n Console.WriteLine(file + \" Contains 'filter'\");\n\n if (myNav.SelectSingleNode(\"/file/title[1]\") != null &&\n myNav.SelectSingleNode(\"/file/title[1]\").InnerXml.Contains(\"Title 1\"))\n Console.WriteLine(file + \" Contains 'Title 1'\");\n }\n\n Console.ReadLine();\n}\n\n", "Use XPath?\nhttp://www.w3schools.com/XPath/default.asp\n" ]
[ 7, 2, 2, 1 ]
[]
[]
[ "asp.net", "c#", "xml" ]
stackoverflow_0000108010_asp.net_c#_xml.txt
Q: Is it okay to have a lot of database views? I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views. Are those views wasting CPU cycles and RAM during all the time that I am not reading from them? Should I instead use stored procedures, temporary tables, or short-lived normal tables since I rarely read from my views? I'm not a DBA so I don't know what's going on behind the scenes inside the database server. Is it possible to have too many database views? What's considered best practice? A: For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views. However, from a people-perspective, trying to manage and figure out what "hundreds" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views? The main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called "active_persons" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use. A: A view is a query that you run often with preset parameters. If you know you will be looking at the same data all the time you can create a view for ease of use and for data binding. That being said, when you select from a view the view defining query is run along with the query you are running. For example, if vwCustomersWhoHavePaid is: Select * from customers where paid = 1 and the query you are running returns the customers who have paid after August first is formatted like this: Select * from vwCustomersWhoHavePaid where datepaid > '08/01/08' The query you are actually running is: Select * from (Select * from customers where paid = 1) where datepaid > '08/01/08' This is something you should keep in mind when creating views, they are a way of storing data that you look at often. It's just a way of organizing data so it's easier to access. A: The views are only going to take up cpu/memory resources when they are called. Anyhow, best practice would be to consolidate what can be consolidated, remove what can be removed, and if it's literally only used by your reports, choose a consistent naming standard for the views so they can easily be grouped together when looking for a particular view. Also, unless you really need transactional isolation, consider using the NOLOCK table hint in your queries. -- Kevin Fairchild A: You ask: What's going on behind the scenes? A view is a bunch of SQL text. When a query uses a view, SQL Server places that SQL text into the query. This happens BEFORE optimization. The result is the optimizer can consider the combined code instead of two separate pieces of code for the best execution plan. You should look at the execution plans of your queries! There is so much to learn there. SQL Server also has a concept of a clustered view. A clustered view is a system maintained result set (each insert/update/delete on the underlying tables can cause insert/update/deletes on the clustered view's data). It is a common mistake to think that views operate in the way that clustered views operate.
Is it okay to have a lot of database views?
I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views. Are those views wasting CPU cycles and RAM during all the time that I am not reading from them? Should I instead use stored procedures, temporary tables, or short-lived normal tables since I rarely read from my views? I'm not a DBA so I don't know what's going on behind the scenes inside the database server. Is it possible to have too many database views? What's considered best practice?
[ "For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views.\nHowever, from a people-perspective, trying to manage and figure out what \"hundreds\" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views?\nThe main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called \"active_persons\" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use.\n", "A view is a query that you run often with preset parameters. If you know you will be looking at the same data all the time you can create a view for ease of use and for data binding. \nThat being said, when you select from a view the view defining query is run along with the query you are running. \nFor example, if vwCustomersWhoHavePaid is:\nSelect * from customers where paid = 1\n\nand the query you are running returns the customers who have paid after August first is formatted like this:\nSelect * from vwCustomersWhoHavePaid where datepaid > '08/01/08'\n\nThe query you are actually running is:\nSelect * from (Select * from customers where paid = 1) where datepaid > '08/01/08'\n\nThis is something you should keep in mind when creating views, they are a way of storing data that you look at often. It's just a way of organizing data so it's easier to access.\n", "The views are only going to take up cpu/memory resources when they are called.\nAnyhow, best practice would be to consolidate what can be consolidated, remove what can be removed, and if it's literally only used by your reports, choose a consistent naming standard for the views so they can easily be grouped together when looking for a particular view.\nAlso, unless you really need transactional isolation, consider using the NOLOCK table hint in your queries.\n-- Kevin Fairchild\n", "You ask: What's going on behind the scenes?\nA view is a bunch of SQL text. When a query uses a view, SQL Server places that SQL text into the query. This happens BEFORE optimization. The result is the optimizer can consider the combined code instead of two separate pieces of code for the best execution plan.\nYou should look at the execution plans of your queries! There is so much to learn there.\nSQL Server also has a concept of a clustered view. A clustered view is a system maintained result set (each insert/update/delete on the underlying tables can cause insert/update/deletes on the clustered view's data). It is a common mistake to think that views operate in the way that clustered views operate.\n" ]
[ 8, 2, 1, 1 ]
[]
[]
[ "crystal_reports", "database", "database_design", "sql", "sql_server" ]
stackoverflow_0000040169_crystal_reports_database_database_design_sql_sql_server.txt
Q: Will this C++ code cause a memory leak (casting array new) I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus: STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize]; Later on however the memory is freed using a delete call: delete pStruct; Will this mix of array new[] and non-array delete cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use malloc and free instead? A: Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example. More importantly if STRUCT where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor. Of course, if you know where pStruct came from why not just cast it on delete to match the allocation: delete [] (BYTE*) pStruct; A: I personally think you'd be better off using std::vector to manage your memory, so you don't need the delete. std::vector<BYTE> backing(sizeof(STRUCT) + nPaddingSize); STRUCT* pStruct = (STRUCT*)(&backing[0]); Once backing leaves scope, your pStruct is no longer valid. Or, you can use: boost::scoped_array<BYTE> backing(new BYTE[sizeof(STRUCT) + nPaddingSize]); STRUCT* pStruct = (STRUCT*)backing.get(); Or boost::shared_array if you need to move ownership around. A: The behaviour of the code is undefined. You may be lucky (or not) and it may work with your compiler, but really that's not correct code. There's two problems with it: The delete should be an array delete []. The delete should be called on a pointer to the same type as the type allocated. So to be entirely correct, you want to be doing something like this: delete [] (BYTE*)(pStruct); A: Yes it will cause a memory leak. See this except from C++ Gotchas: http://www.informit.com/articles/article.aspx?p=30642 for why. Raymond Chen has an explanation of how vector new and delete differ from the scalar versions under the covers for the Microsoft compiler... Here: http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx IMHO you should fix the delete to: delete [] pStruct; rather than switching to malloc/free, if only because it's a simpler change to make without making mistakes ;) And, of course, the simpler to make change that I show above is wrong due to the casting in the original allocation, it should be delete [] reinterpret_cast<BYTE *>(pStruct); so, I guess it's probably as easy to switch to malloc/free after all ;) A: The C++ standard clearly states: delete-expression: ::opt delete cast-expression ::opt delete [ ] cast-expression The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void. In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object [...] If not, the behavior is undefined. The value of the operand in delete pStruct is a pointer to an array of char, independent of its static type (STRUCT*). Therefore, any discussion of memory leaks is quite pointless, because the code is ill-formed, and a C++ compiler is not required to produce a sensible executable in this case. It could leak memory, it could not, or it could do anything up to crashing your system. Indeed, a C++ implementation with which I tested your code aborts the program execution at the point of the delete expression. A: As highlighted in other posts: 1) Calls to new/delete allocate memory and may call constructors/destructors (C++ '03 5.3.4/5.3.5) 2) Mixing array/non-array versions of new and delete is undefined behaviour. (C++ '03 5.3.5/4) Looking at the source it appears that someone did a search and replace for malloc and free and the above is the result. C++ does have a direct replacement for these functions, and that is to call the allocation functions for new and delete directly: STRUCT* pStruct = (STRUCT*)::operator new (sizeof(STRUCT) + nPaddingSize); // ... pStruct->~STRUCT (); // Call STRUCT destructor ::operator delete (pStruct); If the constructor for STRUCT should be called, then you could consider allocating the memory and then use placement new: BYTE * pByteData = new BYTE[sizeof(STRUCT) + nPaddingSize]; STRUCT * pStruct = new (pByteData) STRUCT (); // ... pStruct->~STRUCT (); delete[] pByteData; A: If you really must do this sort of thing, you should probably call operator new directly: STRUCT* pStruct = operator new(sizeof(STRUCT) + nPaddingSize); I believe calling it this way avoids calling constructors/destructors. A: @eric - Thanks for the comments. You keep saying something though, that drives me nuts: Those run-time libraries handle the memory management calls to the OS in a OS independent consistent syntax and those run-time libraries are responsible for making malloc and new work consistently between OSes such as Linux, Windows, Solaris, AIX, etc.... This is not true. The compiler writer provides the implementation of the std libraries, for instance, and they are absolutely free to implement those in an OS dependent way. They're free, for instance, to make one giant call to malloc, and then manage memory within the block however they wish. Compatibility is provided because the API of std, etc. is the same - not because the run-time libraries all turn around and call the exact same OS calls. A: The various possible uses of the keywords new and delete seem to create a fair amount of confusion. There are always two stages to constructing dynamic objects in C++: the allocation of the raw memory and the construction of the new object in the allocated memory area. On the other side of the object lifetime there is the destruction of the object and the deallocation of the memory location where the object resided. Frequently these two steps are performed by a single C++ statement. MyObject* ObjPtr = new MyObject; //... delete MyObject; Instead of the above you can use the C++ raw memory allocation functions operator new and operator delete and explicit construction (via placement new) and destruction to perform the equivalent steps. void* MemoryPtr = ::operator new( sizeof(MyObject) ); MyObject* ObjPtr = new (MemoryPtr) MyObject; // ... ObjPtr->~MyObject(); ::operator delete( MemoryPtr ); Notice how there is no casting involved, and only one type of object is constructed in the allocated memory area. Using something like new char[N] as a way to allocate raw memory is technically incorrect as, logically, char objects are created in the newly allocated memory. I don't know of any situation where it doesn't 'just work' but it blurs the distinction between raw memory allocation and object creation so I advise against it. In this particular case, there is no gain to be had by separating out the two steps of delete but you do need to manually control the initial allocation. The above code works in the 'everything working' scenario but it will leak the raw memory in the case where the constructor of MyObject throws an exception. While this could be caught and solved with an exception handler at the point of allocation it is probably neater to provide a custom operator new so that the complete construction can be handled by a placement new expression. class MyObject { void* operator new( std::size_t rqsize, std::size_t padding ) { return ::operator new( rqsize + padding ); } // Usual (non-placement) delete // We need to define this as our placement operator delete // function happens to have one of the allowed signatures for // a non-placement operator delete void operator delete( void* p ) { ::operator delete( p ); } // Placement operator delete void operator delete( void* p, std::size_t ) { ::operator delete( p ); } }; There are a couple of subtle points here. We define a class placement new so that we can allocate enough memory for the class instance plus some user specifiable padding. Because we do this we need to provide a matching placement delete so that if the memory allocation succeeds but the construction fails, the allocated memory is automatically deallocated. Unfortunately, the signature for our placement delete matches one of the two allowed signatures for non-placement delete so we need to provide the other form of non-placement delete so that our real placement delete is treated as a placement delete. (We could have got around this by adding an extra dummy parameter to both our placement new and placement delete, but this would have required extra work at all the calling sites.) // Called in one step like so: MyObject* ObjectPtr = new (padding) MyObject; Using a single new expression we are now guaranteed that memory won't leak if any part of the new expression throws. At the other end of the object lifetime, because we defined operator delete (even if we hadn't, the memory for the object originally came from global operator new in any case), the following is the correct way to destroy the dynamically created object. delete ObjectPtr; Summary! Look no casts! operator new and operator delete deal with raw memory, placement new can construct objects in raw memory. An explicit cast from a void* to an object pointer is usually a sign of something logically wrong, even if it does 'just work'. We've completely ignored new[] and delete[]. These variable size objects will not work in arrays in any case. Placement new allows a new expression not to leak, the new expression still evaluates to a pointer to an object that needs destroying and memory that needs deallocating. Use of some type of smart pointer may help prevent other types of leak. On the plus side we've let a plain delete be the correct way to do this so most standard smart pointers will work. A: I am currently unable to vote, but slicedlime's answer is preferable to Rob Walker's answer, since the problem has nothing to do with allocators or whether or not the STRUCT has a destructor. Also note that the example code does not necessarily result in a memory leak - it's undefined behavior. Pretty much anything could happen (from nothing bad to a crash far, far away). The example code results in undefined behavior, plain and simple. slicedlime's answer is direct and to the point (with the caveat that the word 'vector' should be changed to 'array' since vectors are an STL thing). This kind of stuff is covered pretty well in the C++ FAQ (Sections 16.12, 16.13, and 16.14): http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12 A: It's an array delete ([]) you're referring to, not a vector delete. A vector is std::vector, and it takes care of deletion of its elements. A: Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors. Also your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string) Better would be to do it correctly, as this will also correctly call any constructors and deconstructors STRUCT* pStruct = new STRUCT; ... delete pStruct; A: You'd could cast back to a BYTE * and the delete: delete[] (BYTE*)pStruct; A: It's always best to keep acquisition/release of any resource as balanced as possible. Although leaking or not is hard to say in this case. It depends on the compiler's implementation of the vector (de)allocation. BYTE * pBytes = new BYTE [sizeof(STRUCT) + nPaddingSize]; STRUCT* pStruct = reinterpret_cast< STRUCT* > ( pBytes ) ; // do stuff with pStruct delete [] pBytes ; A: You're sort of mixing C and C++ ways of doing things. Why allocate more than the size of a STRUCT? Why not just "new STRUCT"? If you must do this then it might be clearer to use malloc and free in this case, since then you or other programmers might be a little less likely to make assumptions about the types and sizes of the allocated objects. A: Len: the problem with that is that pStruct is a STRUCT*, but the memory allocated is actually a BYTE[] of some unknown size. So delete[] pStruct will not de-allocate all of the allocated memory. A: Use operator new and delete: struct STRUCT { void *operator new (size_t) { return new char [sizeof(STRUCT) + nPaddingSize]; } void operator delete (void *memory) { delete [] reinterpret_cast <char *> (memory); } }; void main() { STRUCT *s = new STRUCT; delete s; } A: I think the is no memory leak. STRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize]; This gets translated into a memory allocation call within the operating system upon which a pointer to that memory is returned. At the time memory is allocated, the size of sizeof(STRUCT) and the size of nPaddingSize would be known in order to fulfill any memory allocation requests against the underlying operating system. So the memory that is allocated is "recorded" in the operating system's global memory allocation tables. Memory tables are indexed by their pointers. So in the corresponding call to delete, all memory that was originally allocated is free. (memory fragmentation a popular subject in this realm as well). You see, the C/C++ compiler is not managing memory, the underlying operating system is. I agree there are cleaner methods but the OP did say this was legacy code. In short, I don't see a memory leak as the accepted answer believes there to be one. A: @Matt Cruikshank You should pay attention and read what I wrote again because I never suggested not calling delete[] and just let the OS clean up. And you're wrong about the C++ run-time libraries managing the heap. If that were the case then C++ would not be portable as is today and a crashing application would never get cleaned up by the OS. (acknowledging there are OS specific run-times that make C/C++ appear non-portable). I challenge you to find stdlib.h in the Linux sources from kernel.org. The new keyword in C++ actually is talking to the same memory management routines as malloc. The C++ run-time libraries make OS system calls and it's the OS that manages the heaps. You are partly correct in that the run-time libraries indicate when to release the memory however, they don't actually walk any heap tables directly. In other words, the runtime you link against does not add code to your application to walk heaps to allocate or deallocate. This is the case in Windows, Linux, Solaris, AIX, etc... It's also the reason you won't fine malloc in any Linux's kernel source nor will you find stdlib.h in Linux source. Understand these modern operating system have virtual memory managers that complicates things a bit further. Ever wonder why you can make a call to malloc for 2G of RAM on a 1G box and still get back a valid memory pointer? Memory management on x86 processors is managed within Kernel space using three tables. PAM (Page Allocation Table), PD (Page Directories) and PT (Page Tables). This is at the hardware level I'm speaking of. One of the things the OS memory manager does, not your C++ application, is to find out how much physical memory is installed on the box during boot with help of BIOS calls. The OS also handles exceptions such as when you try to access memory your application does not have rights too. (GPF General Protection Fault). It may be that we are saying the same thing Matt, but I think you may be confusing the under hood functionality a bit. I use to maintain a C/C++ compiler for a living... A: @ericmayo - cripes. Well, experimenting with VS2005, I can't get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is "undefined" here, is about the best defense I can muster. You've got to admit though, it's a really lousy practice to do what the original poster said. If that were the case then C++ would not be portable as is today and a crashing application would never get cleaned up by the OS. This logic doesn't really hold, though. My assertion is that a compiler's runtime can manage the memory within the memory blocks that the OS returns to it. This is how most virtual machines work, so your argument against portability in this case don't make much sense. A: @Matt Cruikshank "Well, experimenting with VS2005, I can't get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is "undefined" here, is about the best defense I can muster." I disagree that it's a compiler behavior or even a compiler issue. The 'new' keyword gets compiled and linked, as you pointed out, to run-time libraries. Those run-time libraries handle the memory management calls to the OS in a OS independent consistent syntax and those run-time libraries are responsible for making malloc and new work consistently between OSes such as Linux, Windows, Solaris, AIX, etc.... This is the reason I mentioned the portability argument; an attempt to prove to you that the run-time does not actually manage memory either. The OS manages memory. The run-time libs interface to the OS.. On Windows, this is the virtual memory manager DLLs. This is why stdlib.h is implemented within the GLIB-C libraries and not the Linux kernel source; if GLIB-C is used on other OSes, it's implementation of malloc changes to make the correct OS calls. In VS, Borland, etc.. you will never find any libraries that ship with their compilers that actually manage memory either. You will, however, find OS specific definitions for malloc. Since we have the source to Linux, you can go look at how malloc is implemented there. You will see that malloc is actually implemented in the GCC compiler which, in turn, basically makes two Linux system calls into the kernel to allocate memory. Never, malloc itself, actually managing memory! And don't take it from me. Read the source code to Linux OS or you can see what K&R say about it... Here is a PDF link to the K&R on C. http://www.oberon2005.ru/paper/kr_c.pdf See near end of Page 149: "Calls to malloc and free may occur in any order; malloc calls upon the operating system to obtain more memory as necessary. These routines illustrate some of the considerations involved in writing machine-dependent code in a relatively machineindependent way, and also show a real-life application of structures, unions and typedef." "You've got to admit though, it's a really lousy practice to do what the original poster said." Oh, I don't disagree there. My point was that the original poster's code was not conducive of a memory leak. That's all I was saying. I didn't chime in on the best practice side of things. Since the code is calling delete, the memory is getting free up. I agree, in your defense, if the original poster's code never exited or never made it to the delete call, that the code could have a memory leak but since he states that later on he sees the delete getting called. "Later on however the memory is freed using a delete call:" Moreover, my reason for responding as I did was due to the OP's comment "variable length structures (TAPI), where the structure size will depend on variable length strings" That comment sounded like he was questioning the dynamic nature of the allocations against the cast being made and was consequentially wondering if that would cause a memory leak. I was reading between the lines if you will ;). A: In addition to the excellent answers above, I would also like to add: If your code runs on linux or if you can compile it on linux then I would suggest running it through Valgrind. It is an excellent tool, among the myriad of useful warnings it produces it also will tell you when you allocate memory as an array and then free it as a non-array ( and vice-versa ).
Will this C++ code cause a memory leak (casting array new)
I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus: STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize]; Later on however the memory is freed using a delete call: delete pStruct; Will this mix of array new[] and non-array delete cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use malloc and free instead?
[ "Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.\nMore importantly if STRUCT where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.\nOf course, if you know where pStruct came from why not just cast it on delete to match the allocation:\ndelete [] (BYTE*) pStruct;\n\n", "I personally think you'd be better off using std::vector to manage your memory, so you don't need the delete.\nstd::vector<BYTE> backing(sizeof(STRUCT) + nPaddingSize);\nSTRUCT* pStruct = (STRUCT*)(&backing[0]);\n\nOnce backing leaves scope, your pStruct is no longer valid.\nOr, you can use:\nboost::scoped_array<BYTE> backing(new BYTE[sizeof(STRUCT) + nPaddingSize]);\nSTRUCT* pStruct = (STRUCT*)backing.get();\n\nOr boost::shared_array if you need to move ownership around.\n", "The behaviour of the code is undefined. You may be lucky (or not) and it may work with your compiler, but really that's not correct code. There's two problems with it:\n\nThe delete should be an array delete [].\nThe delete should be called on a pointer to the same type as the type allocated.\n\nSo to be entirely correct, you want to be doing something like this:\ndelete [] (BYTE*)(pStruct);\n\n", "Yes it will cause a memory leak.\nSee this except from C++ Gotchas: http://www.informit.com/articles/article.aspx?p=30642 for why.\nRaymond Chen has an explanation of how vector new and delete differ from the scalar versions under the covers for the Microsoft compiler... Here: \nhttp://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx \nIMHO you should fix the delete to:\ndelete [] pStruct;\n\nrather than switching to malloc/free, if only because it's a simpler change to make without making mistakes ;)\nAnd, of course, the simpler to make change that I show above is wrong due to the casting in the original allocation, it should be \ndelete [] reinterpret_cast<BYTE *>(pStruct);\n\nso, I guess it's probably as easy to switch to malloc/free after all ;)\n", "The C++ standard clearly states:\ndelete-expression:\n ::opt delete cast-expression\n ::opt delete [ ] cast-expression\n\n\nThe first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void.\nIn the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object [...] If not, the behavior is undefined.\n\nThe value of the operand in delete pStruct is a pointer to an array of char, independent of its static type (STRUCT*). Therefore, any discussion of memory leaks is quite pointless, because the code is ill-formed, and a C++ compiler is not required to produce a sensible executable in this case.\nIt could leak memory, it could not, or it could do anything up to crashing your system. Indeed, a C++ implementation with which I tested your code aborts the program execution at the point of the delete expression.\n", "As highlighted in other posts:\n1) Calls to new/delete allocate memory and may call constructors/destructors (C++ '03 5.3.4/5.3.5)\n2) Mixing array/non-array versions of new and delete is undefined behaviour. (C++ '03 5.3.5/4)\nLooking at the source it appears that someone did a search and replace for malloc and free and the above is the result. C++ does have a direct replacement for these functions, and that is to call the allocation functions for new and delete directly:\nSTRUCT* pStruct = (STRUCT*)::operator new (sizeof(STRUCT) + nPaddingSize);\n// ...\npStruct->~STRUCT (); // Call STRUCT destructor\n::operator delete (pStruct);\n\nIf the constructor for STRUCT should be called, then you could consider allocating the memory and then use placement new:\nBYTE * pByteData = new BYTE[sizeof(STRUCT) + nPaddingSize];\nSTRUCT * pStruct = new (pByteData) STRUCT ();\n// ...\npStruct->~STRUCT ();\ndelete[] pByteData;\n\n", "If you really must do this sort of thing, you should probably call operator new directly:\nSTRUCT* pStruct = operator new(sizeof(STRUCT) + nPaddingSize);\n\nI believe calling it this way avoids calling constructors/destructors.\n", "@eric - Thanks for the comments. You keep saying something though, that drives me nuts:\n\nThose run-time libraries handle the\n memory management calls to the OS in a\n OS independent consistent syntax and\n those run-time libraries are\n responsible for making malloc and new\n work consistently between OSes such as\n Linux, Windows, Solaris, AIX, etc....\n\nThis is not true. The compiler writer provides the implementation of the std libraries, for instance, and they are absolutely free to implement those in an OS dependent way. They're free, for instance, to make one giant call to malloc, and then manage memory within the block however they wish.\nCompatibility is provided because the API of std, etc. is the same - not because the run-time libraries all turn around and call the exact same OS calls.\n", "The various possible uses of the keywords new and delete seem to create a fair amount of confusion. There are always two stages to constructing dynamic objects in C++: the allocation of the raw memory and the construction of the new object in the allocated memory area. On the other side of the object lifetime there is the destruction of the object and the deallocation of the memory location where the object resided.\nFrequently these two steps are performed by a single C++ statement.\nMyObject* ObjPtr = new MyObject;\n\n//...\n\ndelete MyObject;\n\nInstead of the above you can use the C++ raw memory allocation functions operator new and operator delete and explicit construction (via placement new) and destruction to perform the equivalent steps.\nvoid* MemoryPtr = ::operator new( sizeof(MyObject) );\nMyObject* ObjPtr = new (MemoryPtr) MyObject;\n\n// ...\n\nObjPtr->~MyObject();\n::operator delete( MemoryPtr );\n\nNotice how there is no casting involved, and only one type of object is constructed in the allocated memory area. Using something like new char[N] as a way to allocate raw memory is technically incorrect as, logically, char objects are created in the newly allocated memory. I don't know of any situation where it doesn't 'just work' but it blurs the distinction between raw memory allocation and object creation so I advise against it.\nIn this particular case, there is no gain to be had by separating out the two steps of delete but you do need to manually control the initial allocation. The above code works in the 'everything working' scenario but it will leak the raw memory in the case where the constructor of MyObject throws an exception. While this could be caught and solved with an exception handler at the point of allocation it is probably neater to provide a custom operator new so that the complete construction can be handled by a placement new expression.\nclass MyObject\n{\n void* operator new( std::size_t rqsize, std::size_t padding )\n {\n return ::operator new( rqsize + padding );\n }\n\n // Usual (non-placement) delete\n // We need to define this as our placement operator delete\n // function happens to have one of the allowed signatures for\n // a non-placement operator delete\n void operator delete( void* p )\n {\n ::operator delete( p );\n }\n\n // Placement operator delete\n void operator delete( void* p, std::size_t )\n {\n ::operator delete( p );\n }\n};\n\nThere are a couple of subtle points here. We define a class placement new so that we can allocate enough memory for the class instance plus some user specifiable padding. Because we do this we need to provide a matching placement delete so that if the memory allocation succeeds but the construction fails, the allocated memory is automatically deallocated. Unfortunately, the signature for our placement delete matches one of the two allowed signatures for non-placement delete so we need to provide the other form of non-placement delete so that our real placement delete is treated as a placement delete. (We could have got around this by adding an extra dummy parameter to both our placement new and placement delete, but this would have required extra work at all the calling sites.)\n// Called in one step like so:\nMyObject* ObjectPtr = new (padding) MyObject;\n\nUsing a single new expression we are now guaranteed that memory won't leak if any part of the new expression throws.\nAt the other end of the object lifetime, because we defined operator delete (even if we hadn't, the memory for the object originally came from global operator new in any case), the following is the correct way to destroy the dynamically created object.\ndelete ObjectPtr;\n\nSummary!\n\nLook no casts! operator new and operator delete deal with raw memory, placement new can construct objects in raw memory. An explicit cast from a void* to an object pointer is usually a sign of something logically wrong, even if it does 'just work'.\nWe've completely ignored new[] and delete[]. These variable size objects will not work in arrays in any case.\nPlacement new allows a new expression not to leak, the new expression still evaluates to a pointer to an object that needs destroying and memory that needs deallocating. Use of some type of smart pointer may help prevent other types of leak. On the plus side we've let a plain delete be the correct way to do this so most standard smart pointers will work.\n\n", "I am currently unable to vote, but slicedlime's answer is preferable to Rob Walker's answer, since the problem has nothing to do with allocators or whether or not the STRUCT has a destructor.\nAlso note that the example code does not necessarily result in a memory leak - it's undefined behavior. Pretty much anything could happen (from nothing bad to a crash far, far away).\nThe example code results in undefined behavior, plain and simple. slicedlime's answer is direct and to the point (with the caveat that the word 'vector' should be changed to 'array' since vectors are an STL thing).\nThis kind of stuff is covered pretty well in the C++ FAQ (Sections 16.12, 16.13, and 16.14):\nhttp://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12\n", "It's an array delete ([]) you're referring to, not a vector delete.\nA vector is std::vector, and it takes care of deletion of its elements.\n", "Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors.\nAlso your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string)\nBetter would be to do it correctly, as this will also correctly call any constructors and deconstructors\nSTRUCT* pStruct = new STRUCT;\n...\ndelete pStruct;\n\n", "You'd could cast back to a BYTE * and the delete:\ndelete[] (BYTE*)pStruct;\n\n", "It's always best to keep acquisition/release of any resource as balanced as possible.\nAlthough leaking or not is hard to say in this case. It depends on the compiler's implementation of the vector (de)allocation.\nBYTE * pBytes = new BYTE [sizeof(STRUCT) + nPaddingSize];\n\nSTRUCT* pStruct = reinterpret_cast< STRUCT* > ( pBytes ) ;\n\n // do stuff with pStruct\n\ndelete [] pBytes ;\n\n", "You're sort of mixing C and C++ ways of doing things. Why allocate more than the size of a STRUCT? Why not just \"new STRUCT\"? If you must do this then it might be clearer to use malloc and free in this case, since then you or other programmers might be a little less likely to make assumptions about the types and sizes of the allocated objects.\n", "Len: the problem with that is that pStruct is a STRUCT*, but the memory allocated is actually a BYTE[] of some unknown size. So delete[] pStruct will not de-allocate all of the allocated memory.\n", "Use operator new and delete:\nstruct STRUCT\n{\n void *operator new (size_t)\n {\n return new char [sizeof(STRUCT) + nPaddingSize];\n }\n\n void operator delete (void *memory)\n {\n delete [] reinterpret_cast <char *> (memory);\n }\n};\n\nvoid main()\n{\n STRUCT *s = new STRUCT;\n delete s;\n}\n\n", "I think the is no memory leak.\nSTRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize];\n\nThis gets translated into a memory allocation call within the operating system upon which a pointer to that memory is returned. At the time memory is allocated, the size of sizeof(STRUCT) and the size of nPaddingSize would be known in order to fulfill any memory allocation requests against the underlying operating system.\nSo the memory that is allocated is \"recorded\" in the operating system's global memory allocation tables. Memory tables are indexed by their pointers. So in the corresponding call to delete, all memory that was originally allocated is free. (memory fragmentation a popular subject in this realm as well).\nYou see, the C/C++ compiler is not managing memory, the underlying operating system is.\nI agree there are cleaner methods but the OP did say this was legacy code.\nIn short, I don't see a memory leak as the accepted answer believes there to be one.\n", "@Matt Cruikshank \nYou should pay attention and read what I wrote again because I never suggested not calling delete[] and just let the OS clean up. And you're wrong about the C++ run-time libraries managing the heap. If that were the case then C++ would not be portable as is today and a crashing application would never get cleaned up by the OS. (acknowledging there are OS specific run-times that make C/C++ appear non-portable). I challenge you to find stdlib.h in the Linux sources from kernel.org. The new keyword in C++ actually is talking to the same memory management routines as malloc.\nThe C++ run-time libraries make OS system calls and it's the OS that manages the heaps. You are partly correct in that the run-time libraries indicate when to release the memory however, they don't actually walk any heap tables directly. In other words, the runtime you link against does not add code to your application to walk heaps to allocate or deallocate. This is the case in Windows, Linux, Solaris, AIX, etc... It's also the reason you won't fine malloc in any Linux's kernel source nor will you find stdlib.h in Linux source. Understand these modern operating system have virtual memory managers that complicates things a bit further.\nEver wonder why you can make a call to malloc for 2G of RAM on a 1G box and still get back a valid memory pointer?\nMemory management on x86 processors is managed within Kernel space using three tables. PAM (Page Allocation Table), PD (Page Directories) and PT (Page Tables). This is at the hardware level I'm speaking of. One of the things the OS memory manager does, not your C++ application, is to find out how much physical memory is installed on the box during boot with help of BIOS calls. The OS also handles exceptions such as when you try to access memory your application does not have rights too. (GPF General Protection Fault).\nIt may be that we are saying the same thing Matt, but I think you may be confusing the under hood functionality a bit. I use to maintain a C/C++ compiler for a living...\n", "@ericmayo - cripes. Well, experimenting with VS2005, I can't get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is \"undefined\" here, is about the best defense I can muster.\nYou've got to admit though, it's a really lousy practice to do what the original poster said.\n\nIf that were the case then C++ would\n not be portable as is today and a\n crashing application would never get\n cleaned up by the OS.\n\nThis logic doesn't really hold, though. My assertion is that a compiler's runtime can manage the memory within the memory blocks that the OS returns to it. This is how most virtual machines work, so your argument against portability in this case don't make much sense.\n", "@Matt Cruikshank\n\"Well, experimenting with VS2005, I can't get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is \"undefined\" here, is about the best defense I can muster.\"\nI disagree that it's a compiler behavior or even a compiler issue. The 'new' keyword gets compiled and linked, as you pointed out, to run-time libraries. Those run-time libraries handle the memory management calls to the OS in a OS independent consistent syntax and those run-time libraries are responsible for making malloc and new work consistently between OSes such as Linux, Windows, Solaris, AIX, etc.... This is the reason I mentioned the portability argument; an attempt to prove to you that the run-time does not actually manage memory either. \nThe OS manages memory. \nThe run-time libs interface to the OS.. On Windows, this is the virtual memory manager DLLs. This is why stdlib.h is implemented within the GLIB-C libraries and not the Linux kernel source; if GLIB-C is used on other OSes, it's implementation of malloc changes to make the correct OS calls. In VS, Borland, etc.. you will never find any libraries that ship with their compilers that actually manage memory either. You will, however, find OS specific definitions for malloc.\nSince we have the source to Linux, you can go look at how malloc is implemented there. You will see that malloc is actually implemented in the GCC compiler which, in turn, basically makes two Linux system calls into the kernel to allocate memory. Never, malloc itself, actually managing memory!\nAnd don't take it from me. Read the source code to Linux OS or you can see what K&R say about it... Here is a PDF link to the K&R on C.\nhttp://www.oberon2005.ru/paper/kr_c.pdf\nSee near end of Page 149:\n\"Calls to malloc and free may occur in any order; malloc calls\nupon the operating system to obtain more memory as necessary. These routines illustrate some of the considerations involved in writing machine-dependent code in a relatively machineindependent way, and also show a real-life application of structures, unions and typedef.\"\n\"You've got to admit though, it's a really lousy practice to do what the original poster said.\"\nOh, I don't disagree there. My point was that the original poster's code was not conducive of a memory leak. That's all I was saying. I didn't chime in on the best practice side of things. Since the code is calling delete, the memory is getting free up.\nI agree, in your defense, if the original poster's code never exited or never made it to the delete call, that the code could have a memory leak but since he states that later on he sees the delete getting called. \"Later on however the memory is freed using a delete call:\"\nMoreover, my reason for responding as I did was due to the OP's comment \"variable length structures (TAPI), where the structure size will depend on variable length strings\"\nThat comment sounded like he was questioning the dynamic nature of the allocations against the cast being made and was consequentially wondering if that would cause a memory leak. I was reading between the lines if you will ;).\n", "In addition to the excellent answers above, I would also like to add:\nIf your code runs on linux or if you can compile it on linux then I would suggest running it through Valgrind. It is an excellent tool, among the myriad of useful warnings it produces it also will tell you when you allocate memory as an array and then free it as a non-array ( and vice-versa ).\n" ]
[ 12, 7, 6, 6, 4, 3, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "Rob Walker reply is good.\nJust small addition, if you don't have any constructor or/and distructors, so you basically need allocate and free a chunk of raw memory, consider using free/malloc pair.\n", "ericmayo.myopenid.com is so wrong, that someone with enough reputation should downvote him.\nThe C or C++ runtime libraries are managing the heap which is given to it in blocks by the Operating System, somewhat like you indicate, Eric. But it is the responsibility of the developer to indicate to the compiler which runtime calls should be made to free memory, and possibly destruct the objects that are there. Vector delete (aka delete[]) is necessary in this case, in order for the C++ runtime to leave the heap in a valid state. The fact that when the PROCESS terminates, the OS is smart enough to deallocate the underlying memory blocks is not something that developers should rely on. This would be like never calling delete at all.\n" ]
[ -1, -1 ]
[ "c++", "memory_leaks", "memory_management" ]
stackoverflow_0000073134_c++_memory_leaks_memory_management.txt
Q: Checking for external dependances in vb.net Something i've never really done before, but what is the best way to make sure that any external assemblies/dll's that my application uses are available, and possibly the correct version. I wrote an app that relies on the System.Data.SQLite.dll, i went to test it on a machine where that dll was missing, and my app just threw up a runtime exception because the dll was missing. How can i trap this error? A: What you want to do is use reflection to check and see if the assembly can be loaded into memory. Wrap that up in a try..catch block and handle any of the specific exceptions that come from it. Try Assembly.Load("System.Data.SQLite, Version=1.0.22.0, Culture=neutral, PublicKeyToken=DB937BC2D44FF139"); Catch ex As FileNotFoundException //do something here End Try A: (I've set the community-owned flag on this one, because this is mostly all from my gut instinct, and I've probably missed a crucial step in there somewhere) Short answer: It's generally a good idea to deploy your dependencies along-side your application, using an installer. Without them, as you've noticed, there is very little chance of your application working. Long answer: Ok, say you have extra functionality you want to provide if something else is installed on the target machine. Here's some general guidelines to do it: For any type that has a field, property, event, parameter, or return-value that references a type defined in the possibly uninstalled assembly: must be wrapped with an interface, and replace all other field, parameter, return-value, or local variable declarations to use the interface. Any time you go to construct one of the previously wrapped classes, you must use the System.Activator.CreateInstance method, and wrap it in a try/catch filtering on 7 different exception types: FileNotFoundException FileLoadException BadImageFormatException TypeLoadException MissingMethodException MissingMemberException MissingFieldException If one of those is caught, you must either provide an alternative implementation of the previously created interface, or write your code so that it checks for null any time it references that object. A: You should trap the error outside of your main loop. Or if you want to ship/locate your own assemblies you can try overriding the assembly probing: Link. A: You could use a setup project to build an installer for your app. This would analyze all of the static dependencies and produce an installer that ensures that the target machine gets everything it needs.
Checking for external dependances in vb.net
Something i've never really done before, but what is the best way to make sure that any external assemblies/dll's that my application uses are available, and possibly the correct version. I wrote an app that relies on the System.Data.SQLite.dll, i went to test it on a machine where that dll was missing, and my app just threw up a runtime exception because the dll was missing. How can i trap this error?
[ "What you want to do is use reflection to check and see if the assembly can be loaded into memory. Wrap that up in a try..catch block and handle any of the specific exceptions that come from it.\nTry\n Assembly.Load(\"System.Data.SQLite, Version=1.0.22.0, Culture=neutral, PublicKeyToken=DB937BC2D44FF139\");\nCatch ex As FileNotFoundException\n //do something here\nEnd Try\n\n", "(I've set the community-owned flag on this one, because this is mostly all from my gut instinct, and I've probably missed a crucial step in there somewhere)\nShort answer: It's generally a good idea to deploy your dependencies along-side your application, using an installer. Without them, as you've noticed, there is very little chance of your application working.\nLong answer: Ok, say you have extra functionality you want to provide if something else is installed on the target machine. Here's some general guidelines to do it:\n\nFor any type that has a field, property, event, parameter, or return-value that references a type defined in the possibly uninstalled assembly: must be wrapped with an interface, and replace all other field, parameter, return-value, or local variable declarations to use the interface.\nAny time you go to construct one of the previously wrapped classes, you must use the System.Activator.CreateInstance method, and wrap it in a try/catch filtering on 7 different exception types:\n\nFileNotFoundException\nFileLoadException\nBadImageFormatException\nTypeLoadException\nMissingMethodException\nMissingMemberException\nMissingFieldException\n\nIf one of those is caught, you must either provide an alternative implementation of the previously created interface, or write your code so that it checks for null any time it references that object.\n\n", "You should trap the error outside of your main loop.\nOr if you want to ship/locate your own assemblies you can try overriding the assembly probing: Link.\n", "You could use a setup project to build an installer for your app. This would analyze all of the static dependencies and produce an installer that ensures that the target machine gets everything it needs.\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ ".net" ]
stackoverflow_0000108346_.net.txt
Q: Can the ffmpeg av libs return an accurate PTS? I'm working with an mpeg stream that uses a IBBP... GOP sequence. The (DTS,PTS) values returned for the first 4 AVPackets are as follows: I=(0,3) B=(1,1) B=(2,2) P=(3,6) The PTS on the I frame looks like it is legit, but then the PTS on the B frames cannot be right, since the B frames shouldn't be displayed before the I frame as their PTS values indicate. I've also tried decoding the packets and using the pts value in the resulting AVFrame, put that PTS is always set to zero. Is there any way to get an accurate PTS out of ffmpeg? If not, what's the best way to sync audio then? A: I think I finally figured out what's going on based on a comment made in http://www.dranger.com/ffmpeg/tutorial05.html: ffmpeg reorders the packets so that the DTS of the packet being processed by avcodec_decode_video() will always be the same as the PTS of the frame it returns Translation: If I feed a packet into avcodec_decode_video() that has a PTS of 12, avcodec_decode_video() will not return the decoded frame contained in that packet until I feed it a later packet that has a DTS of 12. If the packet's PTS is the same as its DTS, then the packet given is the same as the frame returned. If the packet's PTS is 2 frames later than its DTS, then avcodec_decode_video() will delay the frame and not return it until I provide 2 more packets. Based on this behavior, I'm guessing that av_read_frame() is maybe reordering the packets from IPBB to IBBP so that avcodec_decode_video() only has to buffer the P frames for 3 frames instead of 5. For example, the difference between the input and the output of the P frame with this ordering is 3 (6 - 3): | I B B P B B P | DTS: 0 1 2 3 4 5 6 | decode() result: I B B P vs. a difference of 5 with the standard ordering (6 - 1): | I P B B P B B | DTS: 0 1 2 3 4 5 6 | decode() result: I B B P <shrug/> but that is pure conjecture. A: Ok, scratch my previous confused reply. For a IBBPBBI movie, you'd expect the PTSes to look like this (in decoding order) 0, 3, 1, 2, 6, 4, 5, ... corresponding to the frames I, P, B, B, I, B, B, ... So you appear to be missing an I at the start of your sequence but otherwise the timestamps look correct. A: I'm fairly certain you are getting accurate values. It might help if you thing of an MPEG stream as, well, a stream. In that case, prior to the IBBPBB that you see there would normally be another GOP. Maybe something like this (using same notation as original question): P(-3,-2) B(-2,-1) B(-1,0) Basically the B frames after the I frames are based on the I frame and the last P frame from the previous GOP. While it makes logical sense for a video to start off with this: Start GOP: IPBBPBBPBB... Later on it must be Start GOP: IBBPBBPBBPBB Start GOP: IBBPBBPBBPBB Start GOP: IBB... Remember that decoding any B frame requires a complete frame before it and after it. So each pair of B frames should be displayed before the I or P frame just prior to it in the file. FFMPEG may just have forgone the "special case" of first GOP. Since the first two B frames don't have a prior frame to manipulate, you should be able to safely discard them. Just rebase your timestamps off of the first I frame and adjust the audio stream the same amount. Whether this will actually result in a loss of frames will depend on FFMPEG's implementation, but worse case scenario is that you lose 83 milliseconds (2 frames at 24 frames/sec).
Can the ffmpeg av libs return an accurate PTS?
I'm working with an mpeg stream that uses a IBBP... GOP sequence. The (DTS,PTS) values returned for the first 4 AVPackets are as follows: I=(0,3) B=(1,1) B=(2,2) P=(3,6) The PTS on the I frame looks like it is legit, but then the PTS on the B frames cannot be right, since the B frames shouldn't be displayed before the I frame as their PTS values indicate. I've also tried decoding the packets and using the pts value in the resulting AVFrame, put that PTS is always set to zero. Is there any way to get an accurate PTS out of ffmpeg? If not, what's the best way to sync audio then?
[ "I think I finally figured out what's going on based on a comment made in http://www.dranger.com/ffmpeg/tutorial05.html:\n\nffmpeg reorders the packets so that the DTS of the packet being processed by avcodec_decode_video() will always be the same as the PTS of the frame it returns\n\nTranslation: If I feed a packet into avcodec_decode_video() that has a PTS of 12, avcodec_decode_video() will not return the decoded frame contained in that packet until I feed it a later packet that has a DTS of 12. If the packet's PTS is the same as its DTS, then the packet given is the same as the frame returned. If the packet's PTS is 2 frames later than its DTS, then avcodec_decode_video() will delay the frame and not return it until I provide 2 more packets. \nBased on this behavior, I'm guessing that av_read_frame() is maybe reordering the packets from IPBB to IBBP so that avcodec_decode_video() only has to buffer the P frames for 3 frames instead of 5. For example, the difference between the input and the output of the P frame with this ordering is 3 (6 - 3):\n| I B B P B B P\n| DTS: 0 1 2 3 4 5 6\n| decode() result: I B B P\n\nvs. a difference of 5 with the standard ordering (6 - 1):\n| I P B B P B B\n| DTS: 0 1 2 3 4 5 6\n| decode() result: I B B P\n\n<shrug/> but that is pure conjecture.\n", "Ok, scratch my previous confused reply.\nFor a IBBPBBI movie, you'd expect the PTSes to look like this (in decoding order)\n0, 3, 1, 2, 6, 4, 5, ...\n\ncorresponding to the frames\nI, P, B, B, I, B, B, ...\n\nSo you appear to be missing an I at the start of your sequence but otherwise the timestamps look correct.\n", "I'm fairly certain you are getting accurate values. It might help if you thing of an MPEG stream as, well, a stream. In that case, prior to the IBBPBB that you see there would normally be another GOP. Maybe something like this (using same notation as original question):\nP(-3,-2) B(-2,-1) B(-1,0)\n\nBasically the B frames after the I frames are based on the I frame and the last P frame from the previous GOP.\nWhile it makes logical sense for a video to start off with this:\nStart GOP: IPBBPBBPBB...\n\nLater on it must be\nStart GOP: IBBPBBPBBPBB\nStart GOP: IBBPBBPBBPBB\nStart GOP: IBB... \n\nRemember that decoding any B frame requires a complete frame before it and after it. So each pair of B frames should be displayed before the I or P frame just prior to it in the file.\nFFMPEG may just have forgone the \"special case\" of first GOP.\nSince the first two B frames don't have a prior frame to manipulate, you should be able to safely discard them. Just rebase your timestamps off of the first I frame and adjust the audio stream the same amount.\nWhether this will actually result in a loss of frames will depend on FFMPEG's implementation, but worse case scenario is that you lose 83 milliseconds (2 frames at 24 frames/sec).\n" ]
[ 11, 2, 0 ]
[]
[]
[ "dts", "ffmpeg", "mpeg", "pts" ]
stackoverflow_0000096107_dts_ffmpeg_mpeg_pts.txt
Q: How do you search for an XML comment covering N lines of a file? I am attempting to find xml files with large swaths of commented out xml. I would like to programmatically search for xml comments that stretch beyond a given number of lines. Is there an easy way of doing this? A: Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expression, you can create a pattern to match the comment prefix and match a minimum number of characters before it matches the first comment suffix. http://www.regular-expressions.info/ Here is the pattern that worked in some preliminary tests: <!-- (.[^-->]|[\r\n][^-->]){5}(.[^-->]|[\r\n][^-->])*? --> It will match the starting comment prefix and everything including newline character (on a windows OS) and it's lazy so it will stop at the first comment suffix. Sorry for the edits, you are correct here is an updated pattern. It's obviously not optimized, but in some tests it seems to resolve the error you pointed out. A: I'm not sure about number of lines, but if you can use the length of the string, here's something that would work using XPath. static void Main(string[] args) { string[] myFiles = { @"C:\temp\XMLFile1.xml", @"C:\temp\XMLFile2.xml", @"C:\temp\XMLFile3.xml" }; int maxSize = 5; foreach (string file in myFiles) { System.Xml.XPath.XPathDocument myDoc = new System.Xml.XPath.XPathDocument(file); System.Xml.XPath.XPathNavigator myNav = myDoc.CreateNavigator(); System.Xml.XPath.XPathNodeIterator nodes = myNav.Select("//comment()"); while (nodes.MoveNext()) { if (nodes.Current.ToString().Length > maxSize) Console.WriteLine(file + ": Long comment length = " + nodes.Current.ToString().Length); } } Console.ReadLine(); } A: I'm using this application to test the regex: http://www.regular-expressions.info/dotnetexample.html I have tested it against some fairly good data and it seems to be pulling out only the commented section.
How do you search for an XML comment covering N lines of a file?
I am attempting to find xml files with large swaths of commented out xml. I would like to programmatically search for xml comments that stretch beyond a given number of lines. Is there an easy way of doing this?
[ "Considering that XML doesn't use a line based format, you should probably check the number of characters. With a regular expression, you can create a pattern to match the comment prefix and match a minimum number of characters before it matches the first comment suffix.\nhttp://www.regular-expressions.info/\nHere is the pattern that worked in some preliminary tests:\n<!-- (.[^-->]|[\\r\\n][^-->]){5}(.[^-->]|[\\r\\n][^-->])*? -->\n\nIt will match the starting comment prefix and everything including newline character (on a windows OS) and it's lazy so it will stop at the first comment suffix.\nSorry for the edits, you are correct here is an updated pattern. It's obviously not optimized, but in some tests it seems to resolve the error you pointed out.\n", "I'm not sure about number of lines, but if you can use the length of the string, here's something that would work using XPath.\nstatic void Main(string[] args)\n{\n string[] myFiles = { @\"C:\\temp\\XMLFile1.xml\", \n @\"C:\\temp\\XMLFile2.xml\", \n @\"C:\\temp\\XMLFile3.xml\" };\n int maxSize = 5;\n foreach (string file in myFiles)\n {\n System.Xml.XPath.XPathDocument myDoc = \n new System.Xml.XPath.XPathDocument(file);\n System.Xml.XPath.XPathNavigator myNav = \n myDoc.CreateNavigator();\n\n System.Xml.XPath.XPathNodeIterator nodes = myNav.Select(\"//comment()\");\n while (nodes.MoveNext())\n {\n if (nodes.Current.ToString().Length > maxSize)\n Console.WriteLine(file + \": Long comment length = \" + \n nodes.Current.ToString().Length);\n }\n\n\n }\n\n Console.ReadLine();\n}\n\n", "I'm using this application to test the regex:\nhttp://www.regular-expressions.info/dotnetexample.html\nI have tested it against some fairly good data and it seems to be pulling out only the commented section.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "xml" ]
stackoverflow_0000086271_xml.txt
Q: PLY: Token shifting problem in C parser I'm writing a C parser using PLY, and recently ran into a problem. This code: typedef int my_type; my_type x; Is correct C code, because my_type is defined as a type previously to being used as such. I handle it by filling a type symbol table in the parser that gets used by the lexer to differentiate between types and simple identifiers. However, while the type declaration rule ends with SEMI (the ';' token), PLY shifts the token my_type from the second line before deciding it's done with the first one. Because of this, I have no chance to pass the update in the type symbol table to the lexer and it sees my_type as an identifier and not a type. Any ideas for a fix ? The full code is at: http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py Not sure how I can create a smaller example out of this. Edit: Problem solved. See my solution below. A: Not sure why you're doing that level of analysis in your lexer. Lexical analysis should probably be used to separate the input stream into lexical tokens (number, line-change, keyword and so on). It's the parsing phase that should be doing that level of analysis, including table lookups for typedefs and such. That's the way I've always separated the duties between lexx and yacc, my tools of choice. A: With some help from Dave Beazley (PLY's creator), my problem was solved. The idea is to use special sub-rules and do the actions in them. In my case, I split the declaration rule to: def p_decl_body(self, p): """ decl_body : declaration_specifiers init_declarator_list_opt """ # <<Handle the declaration here>> def p_declaration(self, p): """ declaration : decl_body SEMI """ p[0] = p[1] decl_body is always reduced before the token after SEMI is shifted in, so my action gets executed at the correct time. A: I think you need to move the check for whether an ID is a TYPEID from c_lexer.py to c_parser.py. As you said, since the parser is looking ahead 1 token, you can't make that decision in the lexer. Instead, alter your parser to check ID's to see if they are TYPEID's in declarations, and, if they aren't, generate an error. As Pax Diablo said in his excellent answer, the lexer/tokenizer's job isn't to make those kinds of decisions about tokens. That's the parser's job.
PLY: Token shifting problem in C parser
I'm writing a C parser using PLY, and recently ran into a problem. This code: typedef int my_type; my_type x; Is correct C code, because my_type is defined as a type previously to being used as such. I handle it by filling a type symbol table in the parser that gets used by the lexer to differentiate between types and simple identifiers. However, while the type declaration rule ends with SEMI (the ';' token), PLY shifts the token my_type from the second line before deciding it's done with the first one. Because of this, I have no chance to pass the update in the type symbol table to the lexer and it sees my_type as an identifier and not a type. Any ideas for a fix ? The full code is at: http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py Not sure how I can create a smaller example out of this. Edit: Problem solved. See my solution below.
[ "Not sure why you're doing that level of analysis in your lexer.\nLexical analysis should probably be used to separate the input stream into lexical tokens (number, line-change, keyword and so on). It's the parsing phase that should be doing that level of analysis, including table lookups for typedefs and such.\nThat's the way I've always separated the duties between lexx and yacc, my tools of choice.\n", "With some help from Dave Beazley (PLY's creator), my problem was solved.\nThe idea is to use special sub-rules and do the actions in them. In my case, I split the declaration rule to:\ndef p_decl_body(self, p):\n \"\"\" decl_body : declaration_specifiers init_declarator_list_opt\n \"\"\"\n # <<Handle the declaration here>> \n\ndef p_declaration(self, p):\n \"\"\" declaration : decl_body SEMI \n \"\"\"\n p[0] = p[1]\n\ndecl_body is always reduced before the token after SEMI is shifted in, so my action gets executed at the correct time.\n", "I think you need to move the check for whether an ID is a TYPEID from c_lexer.py to c_parser.py.\nAs you said, since the parser is looking ahead 1 token, you can't make that decision in the lexer.\nInstead, alter your parser to check ID's to see if they are TYPEID's in declarations, and, if they aren't, generate an error.\nAs Pax Diablo said in his excellent answer, the lexer/tokenizer's job isn't to make those kinds of decisions about tokens. That's the parser's job.\n" ]
[ 3, 2, 1 ]
[]
[]
[ "parsing", "ply", "python", "yacc" ]
stackoverflow_0000108009_parsing_ply_python_yacc.txt
Q: How can I read and manipulate PDF 1.5 files in Perl? There doesn't appear to be any Perl libraries that can open, manipulate, and re-save PDF documents that use the newer PDF version (1.5 and above I believe) that use a cross-reference stream rather than table. Does anyone know of any unix/linux-based utilities to convert a PDF to an older version? Or perhaps there's a Perl module in CPAN I missed that can handle this? A: Done! An hour ago, I uploaded CAM::PDF v1.50 to CPAN. It now supports PDF v1.5 compressed object streams and cross-reference streams. I've tested it with a few PDF files that I found online, but I'd sure appreciate feedback (good or bad). A: I would try running it through ghostscript with appropriate parameters. Something like gs -dBATCH -dNOPAUSE -sDEVICE=pdfwriter -dCompatibilityLevel=1.2
How can I read and manipulate PDF 1.5 files in Perl?
There doesn't appear to be any Perl libraries that can open, manipulate, and re-save PDF documents that use the newer PDF version (1.5 and above I believe) that use a cross-reference stream rather than table. Does anyone know of any unix/linux-based utilities to convert a PDF to an older version? Or perhaps there's a Perl module in CPAN I missed that can handle this?
[ "Done! An hour ago, I uploaded CAM::PDF v1.50 to CPAN. It now supports PDF v1.5 compressed object streams and cross-reference streams. I've tested it with a few PDF files that I found online, but I'd sure appreciate feedback (good or bad).\n", "I would try running it through ghostscript with appropriate parameters.\nSomething like gs -dBATCH -dNOPAUSE -sDEVICE=pdfwriter -dCompatibilityLevel=1.2\n" ]
[ 14, 1 ]
[]
[]
[ "pdf", "perl" ]
stackoverflow_0000092426_pdf_perl.txt
Q: How do I pop up an image in a separate div on mouse-over using CSS only? I have a small gallery of thumbnails. When I place my mouse pointer over a thumbnail image I'd like to have a full size image pop up in a div in the top right of the screen. I've seen this done using just CSS and I'd like to go down that route rather than use javascript if possible. A: Pure CSS Popups2, from the same site that brings us Complexspiral. Note that this example is using actual navigational links as the rolled-over element. If you don't want that, it may cause some stickiness regarding versions of IE. The basic technique is to stick each image inside a link tag with an actual href (Otherwise some IE versions will neglect :hover) <a href="#">Text <img class="popup" src="pic.gif" /></a> and position it cleverly using absolute position. Hide the image initially a img.popup { display: none } and then on the link rollover, set it up to appear. a:hover img.popup { display: block } That's the basic technique, but there are always going to be major positioning limitations since the image tag dwells inside the link tag. See the link for details; he uses something a little more tricky than display: none to hide the image. A: CSS Playground uses pure CSS for this type of thing, one of the demos is surely to help you and as it's all CSS just view source to learn - you probably want to use the :hover pseudo class but there are limitations to it depending on your browser targeting. A: Eric Meyer's Pure CSS Popups 2 demo sounds similar enough to what you want. A: Here are a few examples: CSS Image gallery Cross Browser Multi-Page Photograph Gallery A CSS-only Image Gallery: Explained A CSS-only Image Gallery: Example This last one acts upon click. Just to be complete in behaviours.
How do I pop up an image in a separate div on mouse-over using CSS only?
I have a small gallery of thumbnails. When I place my mouse pointer over a thumbnail image I'd like to have a full size image pop up in a div in the top right of the screen. I've seen this done using just CSS and I'd like to go down that route rather than use javascript if possible.
[ "Pure CSS Popups2, from the same site that brings us Complexspiral. Note that this example is using actual navigational links as the rolled-over element. If you don't want that, it may cause some stickiness regarding versions of IE.\nThe basic technique is to stick each image inside a link tag with an actual href (Otherwise some IE versions will neglect :hover)\n<a href=\"#\">Text <img class=\"popup\" src=\"pic.gif\" /></a>\n\nand position it cleverly using absolute position. Hide the image initially\na img.popup { display: none }\n\nand then on the link rollover, set it up to appear. \na:hover img.popup { display: block }\n\nThat's the basic technique, but there are always going to be major positioning limitations since the image tag dwells inside the link tag. See the link for details; he uses something a little more tricky than display: none to hide the image.\n", "CSS Playground uses pure CSS for this type of thing, one of the demos is surely to help you and as it's all CSS just view source to learn - you probably want to use the :hover pseudo class but there are limitations to it depending on your browser targeting.\n", "Eric Meyer's Pure CSS Popups 2 demo sounds similar enough to what you want.\n", "Here are a few examples:\n\nCSS Image gallery\nCross Browser Multi-Page Photograph Gallery\nA CSS-only Image Gallery: Explained\nA CSS-only Image Gallery: Example\n\nThis last one acts upon click. Just to be complete in behaviours.\n" ]
[ 5, 1, 0, 0 ]
[]
[]
[ "css", "popup", "xhtml" ]
stackoverflow_0000108461_css_popup_xhtml.txt
Q: How do I get started reverse engineering z80 machine code? I have a .z80 memory dump. How do I reverse engineer it? What do I need to know? How can I minimize manual labour? A: Most powerful disassembler - IDA supports z80. Also list of disassemblers published at "Software Development Tools for Z80 Family" page A: It depends on what operating system your in, there are a lot of good tools here: http://www.z80.info/z80sdt.htm The first program I ever wrote was in Z80 Assembly language.
How do I get started reverse engineering z80 machine code?
I have a .z80 memory dump. How do I reverse engineer it? What do I need to know? How can I minimize manual labour?
[ "Most powerful disassembler - IDA supports z80.\nAlso list of disassemblers published at \"Software Development Tools for Z80 Family\" page\n", "It depends on what operating system your in, there are a lot of good tools here:\nhttp://www.z80.info/z80sdt.htm\nThe first program I ever wrote was in Z80 Assembly language. \n" ]
[ 14, 3 ]
[]
[]
[ "assembly", "decompiling", "disassembly", "reverse_engineering", "z80" ]
stackoverflow_0000108485_assembly_decompiling_disassembly_reverse_engineering_z80.txt
Q: DataGridViewCell Bordercolor Does anyone know how to change the Bordercolor for a Datagridviewcell in c#? Here's a picture of what I mean: Datagridviewstyle http://www.zivillian.de/datagridview.png Picture Backgroundcolor, Textcolor and Images are no Problem, but I don't know how to realise the Borders. EDIT: I want to realise this with winforms. Another problem is the cross in the second Row, but that's for later... A: You'd have to draw the cells yourself to achieve this, using OwnerDraw. A: You can hook up on two events on your datagridview. 'ItemCreated' and 'ItemDatabound' Each will pass you an eventarg that can access your itemtemplate. Within that you can .FindControl("ControlId") or step through the .Controls collections to find the cell. Once you got that cell you can do whatever you want - both bordercolor and the cross. ItemCreated will fire for each drawing (postback) while ItemDatabound only when you databind :)
DataGridViewCell Bordercolor
Does anyone know how to change the Bordercolor for a Datagridviewcell in c#? Here's a picture of what I mean: Datagridviewstyle http://www.zivillian.de/datagridview.png Picture Backgroundcolor, Textcolor and Images are no Problem, but I don't know how to realise the Borders. EDIT: I want to realise this with winforms. Another problem is the cross in the second Row, but that's for later...
[ "You'd have to draw the cells yourself to achieve this, using OwnerDraw.\n", "You can hook up on two events on your datagridview. 'ItemCreated' and 'ItemDatabound' Each will pass you an eventarg that can access your itemtemplate. Within that you can .FindControl(\"ControlId\") or step through the .Controls collections to find the cell. Once you got that cell you can do whatever you want - both bordercolor and the cross.\nItemCreated will fire for each drawing (postback) while ItemDatabound only when you databind :)\n" ]
[ 2, 1 ]
[]
[]
[ ".net", "c#", "coding_style", "datagridview" ]
stackoverflow_0000108505_.net_c#_coding_style_datagridview.txt
Q: Can I check if a SOAP web service supports a certain WebMethod? Our web services are distributed across different servers for various reasons (such as decreasing latency to the client), and they're not always all up-to-date. Rather than throwing an exception when a method doesn't exist because the particular web service is too old, it would be nicer if we could have the client check if the service responds to a given method before calling it, and otherwise disable the feature (or work around it). Is there a way to do that? A: Get the WSDL (append ?wsdl to the URL) - you can parse that any way you like. A: Unit test the web service to ensure its signatures don't break. When you write code that breaks the method signature, you'll know and can adjust the other applications accordingly. Or just don't break the web services and publish them in a way that enable syou to version them. As in http://services.domain.com/MyService/V1.1/Service.asmx (for .NET) so that way your applications that use v1.1 won't break when you publish v1.2 and make breaking changes. I would also check out using an internal UDDI server if it's really that big of a hasle to manage your web services. Using the Green Pages of UDDI will tell you what you want to know about the service. A: When you are making a SOAP request you are just sending an HTTP request to a server. If the server understands it, it will respond with an HTTP 200 and some XML back, if it doesn't it will send you some error HTTP code (404, 500, ...) There is no general way to ask for the existance of a "method" exposed by a web service. Try to use the WSDL exposed if it is automatic, or just try to use the "method" and check for an error in the response (you don't have to send an exception to the user...) Also, I don't know if I understood you well, but you are thinking of quering the server twice, once to check if the method exists, and second to make the actual call it if it does? I would just check for the error if it doesn't, and proceed normally if it does.
Can I check if a SOAP web service supports a certain WebMethod?
Our web services are distributed across different servers for various reasons (such as decreasing latency to the client), and they're not always all up-to-date. Rather than throwing an exception when a method doesn't exist because the particular web service is too old, it would be nicer if we could have the client check if the service responds to a given method before calling it, and otherwise disable the feature (or work around it). Is there a way to do that?
[ "Get the WSDL (append ?wsdl to the URL) - you can parse that any way you like.\n", "Unit test the web service to ensure its signatures don't break. When you write code that breaks the method signature, you'll know and can adjust the other applications accordingly.\nOr just don't break the web services and publish them in a way that enable syou to version them. As in http://services.domain.com/MyService/V1.1/Service.asmx (for .NET) so that way your applications that use v1.1 won't break when you publish v1.2 and make breaking changes.\nI would also check out using an internal UDDI server if it's really that big of a hasle to manage your web services. Using the Green Pages of UDDI will tell you what you want to know about the service.\n", "When you are making a SOAP request you are just sending an HTTP request to a server. If the server understands it, it will respond with an HTTP 200 and some XML back, if it doesn't it will send you some error HTTP code (404, 500, ...)\nThere is no general way to ask for the existance of a \"method\" exposed by a web service. Try to use the WSDL exposed if it is automatic, or just try to use the \"method\" and check for an error in the response (you don't have to send an exception to the user...)\nAlso, I don't know if I understood you well, but you are thinking of quering the server twice, once to check if the method exists, and second to make the actual call it if it does? I would just check for the error if it doesn't, and proceed normally if it does.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "asp.net", "soap", "web_services" ]
stackoverflow_0000108499_asp.net_soap_web_services.txt
Q: in Rails : Retrieve user input from a form that isn't associated with a Model, use the result within the controller Here's a simplified version of what I'm trying to do : Before any other actions are performed, present the user with a form to retrieve a string. Input the string, and then redirect to the default controller action (e.g. index). The string only needs to exist, no other validations are necessary. The string must be available (as an instance variable?) to all the actions in this controller. I'm very new with Rails, but this doesn't seem like it ought to be exceedingly hard, so I'm feeling kind of dumb. What I've tried : I have a before_filter redirecting to a private method that looks like def check_string if @string return true else get_string end end the get_string method looks like def get_string if params[:string] respond_to do |format| format.html {redirect_to(accounts_url)} # authenticate.html.erb end end respond_to do |format| format.html {render :action =>"get_string"} # get_string.html.erb end end This fails because i have two render or redirect calls in the same action. I can take out that first respond_to, of course, but what happens is that the controller gets trapped in the get_string method. I can more or less see why that's happening, but I don't know how to fix it and break out. I need to be able to show one form (View), get and then do something with the input string, and then proceed as normal. The get_string.html.erb file looks like <h1>Enter a string</h1> <% form_tag('/accounts/get_string') do %> <%= password_field_tag(:string, params[:string])%> <%= submit_tag('Ok')%> <% end %> I'll be thankful for any help! EDIT Thanks for the replies... @Laurie Young : You are right, I was misunderstanding. For some reason I had it in my head that the instance of any given controller invoked by a user would persist throughout their session, and that some of the Rails magic was in tracking objects associated with each user session. I can see why that doesn't make a whole lot of sense in retrospect, and why my attempt to use an instance variable (which I'd thought would persist) won't work. Thanks to you as well :) A: Part of the problem is that you aren't setting @string. You don't really need the before_filter for this at all, and should just be able to use: def get_string @string = params[:string] || session[:string] respond_to do |format| if @string format.html {redirect_to(accounts_url)} # authenticate.html.erb else format.html {render :action =>"get_string"} # get_string.html.erb end end end If you want the @string variable to be available for all actions, you will need to store it in the session. A: It looks like me like your missing a rails concept. Every single page the user sees is a different request. I might have missunderstood what you are trying to do. But it seems to me you want the user to see two pages, In the first page they set a string variable In the second page they see a page that is somehow dependent on the variable set The best way to do this would be to have to a before filter that checks for the existance of the varibale, and if its not set, redirects to them to the form, and otherwise continues class MyController < ApplicationController::Base before_filter :require_string def require_string return true if @string #return early if called multiple times in one request if params['string'] or session['string'] #depending on if you set it as a URL or session var @string = (params['string'] or session['string']) return true end #We now know that string is not set redirect_to string_setting_url and return false #the return false prevents any futher processing in this request end end This is the basic idea behind how plugins like RestfulAuthentication work. In that case "string" is a login token (the user ID i think), is is stored in the session. If you take a look at the login_required' action inauthenticated_system.rb` from ResultfulAuth: it does basically this, though it has a few more error corrections, other stuff added in
in Rails : Retrieve user input from a form that isn't associated with a Model, use the result within the controller
Here's a simplified version of what I'm trying to do : Before any other actions are performed, present the user with a form to retrieve a string. Input the string, and then redirect to the default controller action (e.g. index). The string only needs to exist, no other validations are necessary. The string must be available (as an instance variable?) to all the actions in this controller. I'm very new with Rails, but this doesn't seem like it ought to be exceedingly hard, so I'm feeling kind of dumb. What I've tried : I have a before_filter redirecting to a private method that looks like def check_string if @string return true else get_string end end the get_string method looks like def get_string if params[:string] respond_to do |format| format.html {redirect_to(accounts_url)} # authenticate.html.erb end end respond_to do |format| format.html {render :action =>"get_string"} # get_string.html.erb end end This fails because i have two render or redirect calls in the same action. I can take out that first respond_to, of course, but what happens is that the controller gets trapped in the get_string method. I can more or less see why that's happening, but I don't know how to fix it and break out. I need to be able to show one form (View), get and then do something with the input string, and then proceed as normal. The get_string.html.erb file looks like <h1>Enter a string</h1> <% form_tag('/accounts/get_string') do %> <%= password_field_tag(:string, params[:string])%> <%= submit_tag('Ok')%> <% end %> I'll be thankful for any help! EDIT Thanks for the replies... @Laurie Young : You are right, I was misunderstanding. For some reason I had it in my head that the instance of any given controller invoked by a user would persist throughout their session, and that some of the Rails magic was in tracking objects associated with each user session. I can see why that doesn't make a whole lot of sense in retrospect, and why my attempt to use an instance variable (which I'd thought would persist) won't work. Thanks to you as well :)
[ "Part of the problem is that you aren't setting @string. You don't really need the before_filter for this at all, and should just be able to use:\ndef get_string\n @string = params[:string] || session[:string] \n respond_to do |format|\n if @string \n format.html {redirect_to(accounts_url)} # authenticate.html.erb\n else \n format.html {render :action =>\"get_string\"} # get_string.html.erb\n end\n end\nend\n\nIf you want the @string variable to be available for all actions, you will need to store it in the session.\n", "It looks like me like your missing a rails concept. Every single page the user sees is a different request. \nI might have missunderstood what you are trying to do. But it seems to me you want the user to see two pages, \n\nIn the first page they set a string variable \nIn the second page they see a page that is somehow dependent on the variable set \n\nThe best way to do this would be to have to a before filter that checks for the existance of the varibale, and if its not set, redirects to them to the form, and otherwise continues\nclass MyController < ApplicationController::Base\n before_filter :require_string\n\n def require_string\n return true if @string #return early if called multiple times in one request\n if params['string'] or session['string'] #depending on if you set it as a URL or session var\n @string = (params['string'] or session['string'])\n return true\n end\n\n #We now know that string is not set\n redirect_to string_setting_url and return false #the return false prevents any futher processing in this request\n end\nend\n\nThis is the basic idea behind how plugins like RestfulAuthentication work. In that case \"string\" is a login token (the user ID i think), is is stored in the session. \nIf you take a look at the login_required' action inauthenticated_system.rb` from ResultfulAuth: it does basically this, though it has a few more error corrections, other stuff added in\n" ]
[ 2, 0 ]
[]
[]
[ "before_filter", "ruby_on_rails" ]
stackoverflow_0000106711_before_filter_ruby_on_rails.txt
Q: Can IIS7 be installed on XP? I'm pretty sure I know the answer to this, but short of a virtual Vista installation, is there a way to install IIS 7 on XP? A: No. Which means I'm moving to vista this week as I have to use IIS7. EDIT: Ha - voted up! I assume it's a sympathy vote. :-) A: I think it would be better to move to Win 2008 server (setup as workstation see: http://www.win2008workstation.com/wordpress/) A: Its a completly different model on vista than xp... http.sys and all that type of stuff. I don't believe you can install IIS 6 on XP.
Can IIS7 be installed on XP?
I'm pretty sure I know the answer to this, but short of a virtual Vista installation, is there a way to install IIS 7 on XP?
[ "No. Which means I'm moving to vista this week as I have to use IIS7.\nEDIT: Ha - voted up! I assume it's a sympathy vote. :-)\n", "I think it would be better to move to Win 2008 server (setup as workstation see: http://www.win2008workstation.com/wordpress/)\n", "Its a completly different model on vista than xp... http.sys and all that type of stuff. I don't believe you can install IIS 6 on XP.\n" ]
[ 6, 2, 0 ]
[]
[]
[ "iis_7", "windows_xp" ]
stackoverflow_0000108432_iis_7_windows_xp.txt
Q: What are the options for delivering Flash video? I'd like a concise introduction to the different options. A: From Wikipedia Embedded in an SWF file using the Flash authoring tool (supported in Flash Player 6 and later). The entire file must be transferred before playback can begin. Changing the video requires rebuilding the SWF file.[citation needed] Progressive download via HTTP (supported in Flash Player 7 and later). This method uses ActionScript to include an externally hosted Flash Video file client-side for playback. Progressive download has several advantages, including buffering, use of generic HTTP servers, and the ability to reuse a single SWF player for multiple Flash Video sources. Flash Player 8 includes support for random access within video files using the partial download functionality of HTTP, sometimes this is referred to as streaming. However, unlike streaming using RTMP, HTTP "streaming" does not support real-time broadcasting. Streaming via HTTP requires a custom player and the injection of specific Flash Video metadata containing the exact starting position in bytes and timecode of each keyframe. Using this specific information, a custom Flash Video player can request any part of the Flash Video file starting at a specified keyframe. For example, Google Video and Youtube support progressive downloading and can seek to any part of the video before buffering is complete. The server-side part of this "HTTP pseudo-streaming" method is fairly simple to implement, for example in PHP, as an Apache HTTPD module, or a lighttpd module. Rich Media Project provides players and Flash components compatible with "HTTP pseudo-streaming" method. Streamed via RTMP to the Flash Player using the Flash Media Server (formerly called Flash Communication Server), VCS, ElectroServer, Wowza Pro or the open source Red5 server. As of April 2008, there are four stream recorders available for this protocol, re-encoding screencast software excluded. There is a useful introduction from Adobe here: Flash video learning guide A: You can stream FLV videos using a simple player like JW FLV Media Player. It supports several streaming methods, playlists etc. It's actively developed, and I have found it to be the best solution for streaming flash video. A: Further to yoavf's answer, you can also use haxevideo as an open source rtmp video streaming server.
What are the options for delivering Flash video?
I'd like a concise introduction to the different options.
[ "From Wikipedia\n\n\nEmbedded in an SWF file using the Flash authoring tool (supported in Flash Player 6 and later). The entire file must be transferred before playback can begin. Changing the video requires rebuilding the SWF file.[citation needed]\nProgressive download via HTTP (supported in Flash Player 7 and later). This method uses ActionScript to include an externally hosted Flash Video file client-side for playback. Progressive download has several advantages, including buffering, use of generic HTTP servers, and the ability to reuse a single SWF player for multiple Flash Video sources. Flash Player 8 includes support for random access within video files using the partial download functionality of HTTP, sometimes this is referred to as streaming. However, unlike streaming using RTMP, HTTP \"streaming\" does not support real-time broadcasting. Streaming via HTTP requires a custom player and the injection of specific Flash Video metadata containing the exact starting position in bytes and timecode of each keyframe. Using this specific information, a custom Flash Video player can request any part of the Flash Video file starting at a specified keyframe. For example, Google Video and Youtube support progressive downloading and can seek to any part of the video before buffering is complete. The server-side part of this \"HTTP pseudo-streaming\" method is fairly simple to implement, for example in PHP, as an Apache HTTPD module, or a lighttpd module. Rich Media Project provides players and Flash components compatible with \"HTTP pseudo-streaming\" method.\nStreamed via RTMP to the Flash Player using the Flash Media Server (formerly called Flash Communication Server), VCS, ElectroServer, Wowza Pro or the open source Red5 server. As of April 2008, there are four stream recorders available for this protocol, re-encoding screencast software excluded.\n\n\nThere is a useful introduction from Adobe here: Flash video learning guide\n", "You can stream FLV videos using a simple player like JW FLV Media Player. It supports several streaming methods, playlists etc. It's actively developed, and I have found it to be the best solution for streaming flash video.\n", "Further to yoavf's answer, you can also use haxevideo as an open source rtmp video streaming server.\n" ]
[ 4, 2, 0 ]
[]
[]
[ "flash", "video" ]
stackoverflow_0000007726_flash_video.txt
Q: deleting a buffer through a different type of pointer? Say I have the following C++: char *p = new char[cb]; SOME_STRUCT *pSS = (SOME_STRUCT *) p; delete pSS; Is this safe according to the C++ standard? Do I need to cast back to a char* and then use delete[]? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe? A: It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite: [16.13] Can I drop the [] when deleting array of some built-in type (char, int, etc.)? http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13 A: No, it's undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that thudbang linked to says, operator delete[] might be overloaded to do something different to operator delete. You can sometimes get away with it, but it's also good practice to get into the habit of matching delete[] with new[] for the cases where you can't. A: I highly doubt it. There are a lot of questionable ways of freeing memory, for example you can use delete on your char array (rather than delete[]) and it will likely work fine. I blogged in detail about this (apologies for the self-link, but it's easier than rewriting it all). The compiler is not so much the issue as the platform. Most libraries will use the allocation methods of the underlying operating system, which means the same code could behave differently on Mac vs. Windows vs. Linux. I have seen examples of this and every single one was questionable code. The safest approach is to always allocate and free memory using the same data type. If you are allocating chars and returning them to other code, you may be better off providing specific allocate/deallocate methods: SOME_STRUCT* Allocate() { size_t cb; // Initialised to something return (SOME_STRUCT*)(new char[cb]); }   void Free(SOME_STRUCT* obj) { delete[] (char*)obj; } (Overloading the new and delete operators may also be an option, but I have never liked doing this.) A: C++ Standard [5.3.5.2] declares: If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section. In either alternative, the value of the operand of delete may be a null pointer value. If it is not a null pointer value, in the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a subobject (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined. In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression.77) If not, the behavior is undefined. [ Note: this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression. —end note ] [ Note: a pointer to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness (5.2.11) of the pointer expression before it is used as the operand of the delete-expression. —end note ] A: This is a very similar question to the one that I answered here: link text In short, no, it's not safe according to the C++ standard. If, for some reason, you need a SOME_STRUCT object allocated in an area of memory that has a size difference from size_of(SOME_STRUCT) (and it had better be bigger!), then you are better off using a raw allocation function like global operator new to perform the allocation and then creating the object instance in raw memory with a placement new. Placement new will be extremely cheap if the object type has no constructor. void* p = ::operator new( cb ); SOME_STRUCT* pSS = new (p) SOME_STRUCT; // ... delete pSS; This will work most of the time. It should always work if SOME_STRUCT is a POD-struct. It will also work in other cases if SOME_STRUCT's constructor does not throw and if SOME_STRUCT does not have a custom operator delete. This technique also removes the need for any casts. ::operator new and ::operator delete are C++'s closest equivalent to malloc and free and as these (in the absence of class overrides) are called as appropriate by new and delete expressions they can (with care!) be used in combination. A: While this should work, I don't think you can guarantee it to be safe because the SOME_STRUCT is not a char* (unless it's merely a typedef). Additionally, since you're using different types of references, if you continue to use the *p access, and the memory has been deleted, you will get a runtime error. A: This will work OK if the memory being pointed to and the pointer you are pointing with are both POD. In this case, no destructor would be called anyhow, and the memory allocator does not know or care about the type stored within the memory. The only case this is OK with non-POD types, is if the pointee is a subtype of the pointer, (e.g. You are pointing at a Car with a Vehicle*) and the pointer's destructor has been declared virtual. A: This isn't safe, and non of the responses so far have emphasized enough the madness of doing this. Simply don't do it, if you consider yourself a real programmer, or ever want to work as a professional programmer in a team. You can only say that your struct contains non destructor at the moment, however you are laying a nasty possibly compiler and system specific trap for the future. Also, your code is unlikely to work as expected. The very best you can hope for is it doesn't crash. However I suspect you will slowly get a memory leak, as array allocations via new very often allocate extra memory in the bytes prior to the returned pointer. You won't be freeing the memory you think you are. A good memory allocation routine should pick up this mismatch, as would tools like Lint etc. Simply don't do that, and purge from your mind whatever thinking process led you to even consider such nonsense. A: I've changed the code to use malloc/free. While I know how MSVC implements new/delete for plain-old-data (and SOME_STRUCT in this case was a Win32 structure, so simple C), I just wanted to know if it was a portable technique. It's not, so I'll use something that is. A: If you use malloc/free instead of new/delete, malloc and free won't care about the type. So if you're using a C-like POD (plain old data, like a build-in type, or a struct), you can malloc some type, and free another. note that this is poor style even if it works.
deleting a buffer through a different type of pointer?
Say I have the following C++: char *p = new char[cb]; SOME_STRUCT *pSS = (SOME_STRUCT *) p; delete pSS; Is this safe according to the C++ standard? Do I need to cast back to a char* and then use delete[]? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?
[ "It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite:\n[16.13] Can I drop the [] when deleting array of some built-in type (char, int, etc.)?\nhttp://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13\n", "No, it's undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that thudbang linked to says, operator delete[] might be overloaded to do something different to operator delete. You can sometimes get away with it, but it's also good practice to get into the habit of matching delete[] with new[] for the cases where you can't.\n", "I highly doubt it.\nThere are a lot of questionable ways of freeing memory, for example you can use delete on your char array (rather than delete[]) and it will likely work fine. I blogged in detail about this (apologies for the self-link, but it's easier than rewriting it all).\nThe compiler is not so much the issue as the platform. Most libraries will use the allocation methods of the underlying operating system, which means the same code could behave differently on Mac vs. Windows vs. Linux. I have seen examples of this and every single one was questionable code.\nThe safest approach is to always allocate and free memory using the same data type. If you are allocating chars and returning them to other code, you may be better off providing specific allocate/deallocate methods:\nSOME_STRUCT* Allocate()\n{\n size_t cb; // Initialised to something\n return (SOME_STRUCT*)(new char[cb]);\n}\n\n \nvoid Free(SOME_STRUCT* obj)\n{\n delete[] (char*)obj;\n}\n\n(Overloading the new and delete operators may also be an option, but I have never liked doing this.)\n", "C++ Standard [5.3.5.2] declares:\n\nIf the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion\n function, and the converted operand is used in place of the original operand for the remainder of this section. In either\n alternative, the value of the operand of delete may be a null pointer value. If it is not a null pointer value, in the first\n alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a\n subobject (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined. In the second\n alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous\n array new-expression.77) If not, the behavior is undefined. [ Note: this means that the syntax of the delete-expression\n must match the type of the object allocated by new, not the syntax of the new-expression. —end note ] [ Note: a pointer\n to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness (5.2.11) of the\n pointer expression before it is used as the operand of the delete-expression. —end note ]\n\n", "This is a very similar question to the one that I answered here: link text\nIn short, no, it's not safe according to the C++ standard. If, for some reason, you need a SOME_STRUCT object allocated in an area of memory that has a size difference from size_of(SOME_STRUCT) (and it had better be bigger!), then you are better off using a raw allocation function like global operator new to perform the allocation and then creating the object instance in raw memory with a placement new. Placement new will be extremely cheap if the object type has no constructor.\nvoid* p = ::operator new( cb );\nSOME_STRUCT* pSS = new (p) SOME_STRUCT;\n\n// ...\n\ndelete pSS;\n\nThis will work most of the time. It should always work if SOME_STRUCT is a POD-struct. It will also work in other cases if SOME_STRUCT's constructor does not throw and if SOME_STRUCT does not have a custom operator delete. This technique also removes the need for any casts.\n::operator new and ::operator delete are C++'s closest equivalent to malloc and free and as these (in the absence of class overrides) are called as appropriate by new and delete expressions they can (with care!) be used in combination.\n", "While this should work, I don't think you can guarantee it to be safe because the SOME_STRUCT is not a char* (unless it's merely a typedef).\nAdditionally, since you're using different types of references, if you continue to use the *p access, and the memory has been deleted, you will get a runtime error.\n", "This will work OK if the memory being pointed to and the pointer you are pointing with are both POD. In this case, no destructor would be called anyhow, and the memory allocator does not know or care about the type stored within the memory.\nThe only case this is OK with non-POD types, is if the pointee is a subtype of the pointer, (e.g. You are pointing at a Car with a Vehicle*) and the pointer's destructor has been declared virtual.\n", "This isn't safe, and non of the responses so far have emphasized enough the madness of doing this. Simply don't do it, if you consider yourself a real programmer, or ever want to work as a professional programmer in a team. You can only say that your struct contains non destructor at the moment, however you are laying a nasty possibly compiler and system specific trap for the future. Also, your code is unlikely to work as expected. The very best you can hope for is it doesn't crash. However I suspect you will slowly get a memory leak, as array allocations via new very often allocate extra memory in the bytes prior to the returned pointer. You won't be freeing the memory you think you are. A good memory allocation routine should pick up this mismatch, as would tools like Lint etc. \nSimply don't do that, and purge from your mind whatever thinking process led you to even consider such nonsense.\n", "I've changed the code to use malloc/free. While I know how MSVC implements new/delete for plain-old-data (and SOME_STRUCT in this case was a Win32 structure, so simple C), I just wanted to know if it was a portable technique.\nIt's not, so I'll use something that is.\n", "If you use malloc/free instead of new/delete, malloc and free won't care about the type.\nSo if you're using a C-like POD (plain old data, like a build-in type, or a struct), you can malloc some type, and free another. note that this is poor style even if it works.\n" ]
[ 9, 6, 4, 2, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "c++", "memory_management", "pointers" ]
stackoverflow_0000070880_c++_memory_management_pointers.txt
Q: How to write an emacs mode for a new language? I would like to write an Emacs major mode for a 4GL. Can someone show me a tutorial? As far as I googled I was able to find only this broken: link http://two-wugs.net/emacs/mode-tutorial.html A: If you're lazy, one easy way is to extend generic-mode to know about your new language: http://emacswiki.org/emacs/GenericMode I do this a lot for config files for applications that I work with a lot to get decent syntax highlighting. Here's one I did for the asterisk PBX a long time ago as an example.
How to write an emacs mode for a new language?
I would like to write an Emacs major mode for a 4GL. Can someone show me a tutorial? As far as I googled I was able to find only this broken: link http://two-wugs.net/emacs/mode-tutorial.html
[ "If you're lazy, one easy way is to extend generic-mode to know about your new language:\nhttp://emacswiki.org/emacs/GenericMode\nI do this a lot for config files for applications that I work with a lot to get decent syntax highlighting. Here's one I did for the asterisk PBX a long time ago as an example.\n" ]
[ 22 ]
[]
[]
[ "emacs", "mode" ]
stackoverflow_0000091201_emacs_mode.txt
Q: How would I allow a user to stream video to a web application for storage? I'd like to add some functionality to a site that would allow users to record video using their webcam and easily store it online. I don't even know if this is possible right now, but I think flash has access to local webcams running through the browser. Do you have any suggestions or resources to get me started on this? I'm primarily a java developer so If I could do it in an applet that would be great, but It may be easier to accomplish this using flash or some other technology. This would mean streaming the video back to the webserver and storing it there. Uploading a file is easy enough, but I'd rather the user not have to deal with that if it's possible. Just to be clear. I'm not talking about uploading a video. I'm talking about allowing the user to click "record" in a web application and having the video streamed to the server and stored when the user clicks "stop". A: This is possible with Adobe's Flash Media Server. Red5 is an open source alternative. The protocol they use for this is RTMP. A: On the server side, you have three alternatives: Adobe's Flash Media Server Red5, an open source version Wowza Media Server Pro, a commercial alternative You can either run any of these on your own server or else go for a web provider (I found this list to be helpful) On the client side, you'll need a flash file for the user interface. Red5 and Wowza some with the source code for their example recorders so it's easy to customize these for your own use. A: In addition to the above choices, you can also use haxevideo (open source)
How would I allow a user to stream video to a web application for storage?
I'd like to add some functionality to a site that would allow users to record video using their webcam and easily store it online. I don't even know if this is possible right now, but I think flash has access to local webcams running through the browser. Do you have any suggestions or resources to get me started on this? I'm primarily a java developer so If I could do it in an applet that would be great, but It may be easier to accomplish this using flash or some other technology. This would mean streaming the video back to the webserver and storing it there. Uploading a file is easy enough, but I'd rather the user not have to deal with that if it's possible. Just to be clear. I'm not talking about uploading a video. I'm talking about allowing the user to click "record" in a web application and having the video streamed to the server and stored when the user clicks "stop".
[ "This is possible with Adobe's Flash Media Server. Red5 is an open source alternative. The protocol they use for this is RTMP.\n", "On the server side, you have three alternatives:\n\nAdobe's Flash Media Server\nRed5, an open source version\nWowza Media Server Pro, a commercial alternative\n\nYou can either run any of these on your own server or else go for a web provider (I found this list to be helpful)\nOn the client side, you'll need a flash file for the user interface. Red5 and Wowza some with the source code for their example recorders so it's easy to customize these for your own use.\n", "In addition to the above choices, you can also use haxevideo (open source)\n" ]
[ 2, 1, 1 ]
[]
[]
[ "applet", "flash", "java", "web_applications" ]
stackoverflow_0000054221_applet_flash_java_web_applications.txt
Q: How do I create a zoom effect in OpenGLES on the iPhone? I have an OpenGL ES game that I am hacking together. One part of it involves looking at a large "map-like" area and then double-tapping on one part to "zoom into" it. How would you use OpenGL ES to provide this effect (given that it may need to zoom in on different parts of the map). I've heard of glScale and glOrtho, but I'm unclear on how they actually work since the whole openGL world is very new to me. A: The 2-D zooming you describe might be better achieved using Core Animation. NSView (and its NDA'd iPhone counterpart) provide implicit animation when you change their frame. All you'd need to do in this case would be to set the frame's origin.x and origin.y and size.width and size.height to such values to make the view larger than the screen. If you did this and wrapped it in the appropriate calls to start and commit an animation, you'd get a zooming animation for free. Core Animation uses OpenGL behind the scenes for its animations. If, however, you feel that you have to do this in OpenGL, may I suggest a little writeup I did at http://www.sunsetlakesoftware.com/2008/08/05/lessons-molecules-opengl-es? I'm the author of Molecules, a free 3-D molecular visualizer for the iPhone, and I knew nothing about OpenGL ES before I started that project. 3 weeks later, it was in the App Store as it launched. OpenGL calls are pretty simple, it's the math surrounding them that can give you headaches. Zooming in on objects is actually pretty simple, and can be done either by moving the camera or by actually physically scaling objects. For Molecules, I went the route of scaling the object using the glScalef(x,y,z) function, where x, y, and z are the scale factors you wish to apply to your model object. I do my scaling incrementally. That is, I don't reset the transformation matrix at the start of each rendered frame (using glLoadIdentity()), but just scale it a little bit based on user input. If the user moves their fingers apart by 5%, I increase the scale by 5%. Again, I'd suggest Core Animation for the 2-D zooming you describe, but it isn't too hard to achieve the same results in OpenGL ES. A: Respectfully, the answer is to take a few days to learn the basics of OpenGL, and there are much better places for that on the net than here.
How do I create a zoom effect in OpenGLES on the iPhone?
I have an OpenGL ES game that I am hacking together. One part of it involves looking at a large "map-like" area and then double-tapping on one part to "zoom into" it. How would you use OpenGL ES to provide this effect (given that it may need to zoom in on different parts of the map). I've heard of glScale and glOrtho, but I'm unclear on how they actually work since the whole openGL world is very new to me.
[ "The 2-D zooming you describe might be better achieved using Core Animation. NSView (and its NDA'd iPhone counterpart) provide implicit animation when you change their frame. All you'd need to do in this case would be to set the frame's origin.x and origin.y and size.width and size.height to such values to make the view larger than the screen. If you did this and wrapped it in the appropriate calls to start and commit an animation, you'd get a zooming animation for free. Core Animation uses OpenGL behind the scenes for its animations.\nIf, however, you feel that you have to do this in OpenGL, may I suggest a little writeup I did at http://www.sunsetlakesoftware.com/2008/08/05/lessons-molecules-opengl-es? I'm the author of Molecules, a free 3-D molecular visualizer for the iPhone, and I knew nothing about OpenGL ES before I started that project. 3 weeks later, it was in the App Store as it launched.\nOpenGL calls are pretty simple, it's the math surrounding them that can give you headaches. Zooming in on objects is actually pretty simple, and can be done either by moving the camera or by actually physically scaling objects. For Molecules, I went the route of scaling the object using the glScalef(x,y,z) function, where x, y, and z are the scale factors you wish to apply to your model object. I do my scaling incrementally. That is, I don't reset the transformation matrix at the start of each rendered frame (using glLoadIdentity()), but just scale it a little bit based on user input. If the user moves their fingers apart by 5%, I increase the scale by 5%.\nAgain, I'd suggest Core Animation for the 2-D zooming you describe, but it isn't too hard to achieve the same results in OpenGL ES.\n", "Respectfully, the answer is to take a few days to learn the basics of OpenGL, and there are much better places for that on the net than here.\n" ]
[ 2, 0 ]
[]
[]
[ "iphone", "objective_c", "opengl_es" ]
stackoverflow_0000103537_iphone_objective_c_opengl_es.txt
Q: data access in DDD? After reading Evan's and Nilsson's books I am still not sure how to manage Data access in a domain driven project. Should the CRUD methods be part of the repositories, i.e. OrderRepository.GetOrdersByCustomer(customer) or should they be part of the entities: Customer.GetOrders(). The latter approach seems more OO, but it will distribute Data Access for a single entity type among multiple objects, i.e. Customer.GetOrders(), Invoice.GetOrders(), ShipmentBatch.GetOrders() ,etc. What about Inserting and updating? A: CRUD-ish methods should be part of the Repository...ish. But I think you should ask why you have a bunch of CRUD methods. What do they really do? What are they really for? If you actually call out the data access patterns your application uses I think it makes the repository a lot more useful and keeps you from having to do shotgun surgery when certain types of changes happen to your domain. CustomerRepo.GetThoseWhoHaventPaidTheirBill() // or GetCustomer(new HaventPaidBillSpecification()) // is better than foreach (var customer in GetCustomer()) { /* logic leaking all over the floor */ } "Save" type methods should also be part of the repository. If you have aggregate roots, this keeps you from having a Repository explosion, or having logic spread out all over: You don't have 4 x # of entities data access patterns, just the ones you actually use on the aggregate roots. That's my $.02. A: DDD usually prefers the repository pattern over the active record pattern you hint at with Customer.Save. One downside in the Active Record model is that it pretty much presumes a single persistence model, barring some particularly intrusive code (in most languages). The repository interface is defined in the domain layer, but doesn't know whether your data is stored in a database or not. With the repository pattern, I can create an InMemoryRepository so that I can test domain logic in isolation, and use dependency injection in the application to have the service layer instantiate a SqlRepository, for example. To many people, having a special repository just for testing sounds goofy, but if you use the repository model, you may find that you don't really need a database for your particular application; sometimes a simple FileRepository will do the trick. Wedding to yourself to a database before you know you need it is potentially limiting. Even if a database is necessary, it's a lot faster to run tests against an InMemoryRepository. If you don't have much in the way of domain logic, you probably don't need DDD. ActiveRecord is quite suitable for a lot of problems, especially if you have mostly data and just a little bit of logic. A: Let's step back for a second. Evans recommends that repositories return aggregate roots and not just entities. So assuming that your Customer is an aggregate root that includes Orders, then when you fetched the customer from its repository, the orders came along with it. You would access the orders by navigating the relationship from Customer to Orders. customer.Orders; So to answer your question, CRUD operations are present on aggregate root repositories. CustomerRepository.Add(customer); CustomerRepository.Get(customerID); CustomerRepository.Save(customer); CustomerRepository.Delete(customer); A: I've done it both ways you are talking about, My preferred approach now is the persistent ignorant (or PONO -- Plain Ole' .Net Object) method where your domain classes are only worried about being domain classes. They do not know anything about how they are persisted or even if they are persisted. Of course you have to be pragmatic about this at times and allow for things such as an Id (but even then I just use a layer super type which has the Id so I can have a single point where things like default value live) The main reason for this is that I strive to follow the principle of Single Responsibility. By following this principle I've found my code much more testable and maintainable. It's also much easier to make changes when they are needed since I only have one thing to think about. One thing to be watchful of is the method bloat that repositories can suffer from. GetOrderbyCustomer.. GetAllOrders.. GetOrders30DaysOld.. etc etc. One good solution to this problem is to look at the Query Object pattern. And then your repositories can just take in a query object to execute. I'd also strongly recommend looking into something like NHibernate. It includes a lot of the concepts that make Repositories so useful (Identity Map, Cache, Query objects..) A: Even in a DDD, I would keep Data Access classes and routines separate from Entities. Reasons are, Testability improves Separation of concerns and Modular design More maintainable in the long run, as you add entities, routines I am no expert, just my opinion. A: The annoying thing with Nilsson's Applying DDD&P is that he always starts with "I wouldn't do that in a real-world-application but..." and then his example follows. Back to the topic: I think OrderRepository.GetOrdersByCustomer(customer) is the way to go, but there is also a discussion on the ALT.Net Mailing list (http://tech.groups.yahoo.com/group/altdotnet/) about DDD.
data access in DDD?
After reading Evan's and Nilsson's books I am still not sure how to manage Data access in a domain driven project. Should the CRUD methods be part of the repositories, i.e. OrderRepository.GetOrdersByCustomer(customer) or should they be part of the entities: Customer.GetOrders(). The latter approach seems more OO, but it will distribute Data Access for a single entity type among multiple objects, i.e. Customer.GetOrders(), Invoice.GetOrders(), ShipmentBatch.GetOrders() ,etc. What about Inserting and updating?
[ "CRUD-ish methods should be part of the Repository...ish. But I think you should ask why you have a bunch of CRUD methods. What do they really do? What are they really for? If you actually call out the data access patterns your application uses I think it makes the repository a lot more useful and keeps you from having to do shotgun surgery when certain types of changes happen to your domain.\nCustomerRepo.GetThoseWhoHaventPaidTheirBill()\n\n// or\n\nGetCustomer(new HaventPaidBillSpecification())\n\n// is better than\n\nforeach (var customer in GetCustomer()) {\n /* logic leaking all over the floor */\n}\n\n\"Save\" type methods should also be part of the repository.\nIf you have aggregate roots, this keeps you from having a Repository explosion, or having logic spread out all over: You don't have 4 x # of entities data access patterns, just the ones you actually use on the aggregate roots.\nThat's my $.02.\n", "DDD usually prefers the repository pattern over the active record pattern you hint at with Customer.Save.\nOne downside in the Active Record model is that it pretty much presumes a single persistence model, barring some particularly intrusive code (in most languages).\nThe repository interface is defined in the domain layer, but doesn't know whether your data is stored in a database or not. With the repository pattern, I can create an InMemoryRepository so that I can test domain logic in isolation, and use dependency injection in the application to have the service layer instantiate a SqlRepository, for example.\nTo many people, having a special repository just for testing sounds goofy, but if you use the repository model, you may find that you don't really need a database for your particular application; sometimes a simple FileRepository will do the trick. Wedding to yourself to a database before you know you need it is potentially limiting. Even if a database is necessary, it's a lot faster to run tests against an InMemoryRepository.\nIf you don't have much in the way of domain logic, you probably don't need DDD. ActiveRecord is quite suitable for a lot of problems, especially if you have mostly data and just a little bit of logic.\n", "Let's step back for a second. Evans recommends that repositories return aggregate roots and not just entities. So assuming that your Customer is an aggregate root that includes Orders, then when you fetched the customer from its repository, the orders came along with it. You would access the orders by navigating the relationship from Customer to Orders.\ncustomer.Orders;\n\nSo to answer your question, CRUD operations are present on aggregate root repositories.\nCustomerRepository.Add(customer);\nCustomerRepository.Get(customerID);\nCustomerRepository.Save(customer);\nCustomerRepository.Delete(customer);\n\n", "I've done it both ways you are talking about, My preferred approach now is the persistent ignorant (or PONO -- Plain Ole' .Net Object) method where your domain classes are only worried about being domain classes. They do not know anything about how they are persisted or even if they are persisted. Of course you have to be pragmatic about this at times and allow for things such as an Id (but even then I just use a layer super type which has the Id so I can have a single point where things like default value live)\nThe main reason for this is that I strive to follow the principle of Single Responsibility. By following this principle I've found my code much more testable and maintainable. It's also much easier to make changes when they are needed since I only have one thing to think about.\nOne thing to be watchful of is the method bloat that repositories can suffer from. GetOrderbyCustomer.. GetAllOrders.. GetOrders30DaysOld.. etc etc. One good solution to this problem is to look at the Query Object pattern. And then your repositories can just take in a query object to execute.\nI'd also strongly recommend looking into something like NHibernate. It includes a lot of the concepts that make Repositories so useful (Identity Map, Cache, Query objects..)\n", "Even in a DDD, I would keep Data Access classes and routines separate from Entities.\nReasons are,\n\nTestability improves\nSeparation of concerns and Modular design\nMore maintainable in the long run, as you add entities, routines\n\nI am no expert, just my opinion.\n", "The annoying thing with Nilsson's Applying DDD&P is that he always starts with \"I wouldn't do that in a real-world-application but...\" and then his example follows. Back to the topic: I think OrderRepository.GetOrdersByCustomer(customer) is the way to go, but there is also a discussion on the ALT.Net Mailing list (http://tech.groups.yahoo.com/group/altdotnet/) about DDD. \n" ]
[ 15, 5, 4, 3, 2, 1 ]
[]
[]
[ "data_access", "domain_driven_design" ]
stackoverflow_0000077171_data_access_domain_driven_design.txt
Q: Rails state of the art for spam prevention What is the current state of the art in rails for preventing spam accounts? Captcha? Any good plugins, tutorials or suggestions? A: Use a library: You're (almost) always better off appropriating code from people who are better at the subdomain than you are. The Wordpress guys behind Akismet have forgotten more about blog spam than I know, and I was an email anti-spam researcher for a while. You might be interested in a Rails integration plugin for Akismet. Defense in Diversity: Spam is a quirky problem, in that the more popular a countermeasure gets the worse it becomes. As such, particularly for low-profile sites, you can get disgustingly good results by coding simple one-off tripwires. I won't give you any code to copy/paste because it defeats the purpose of the excercize: having a countermeasure which is globally unique. One simple example is having a hidden form element which starts as some randomized string, and which is set to a known good value by Javascript code. You then bounce anything which doesn't have the good value supplied. This blocks clients which don't implement Javascript, which includes the overwhelming majority of spam scripts. There are issues, of course, as some legitimate clients also block Javascript -- but realistically, if you're using Rails, I'm guessing you're sort of assuming cookies are on and Javascript works. A: I also recommend ReCAPTCHA, both because it's a highly-reliable service you don't have to manage, and because it serves two common goods - the OCR tasks described by the ReCAPTCHA team, and the progress towards teaching people how captchas work, reducing abandonment rates. A: There is a re-captcha plugin if you want to use captch to verifye that only human can register, or add content: http://ambethia.com/recaptcha/files/README_rdoc.html A: Edit: It appears BranBuster is dead (this was years ago). But I really like: https://github.com/matthutchinson/acts_as_textcaptcha I'm a big fan of the rails plugin called "BrainBuster". It's a logic-based CAPTCHA which I find preferable over the "type these words" things, because it is annoying to decipher the words sometimes... It's simple to look at "What is 10 minus 3?" and come up with the answer. YMMV: https://github.com/rsanheim/brain_buster A: Spam is fair. It doesn't care what you're running behind the scenes. So by extension, the things that work well on Rails are the same things that work for PHP, ASPNET, etc. Take a look at Akismet and the various "karma" anti-bot tools there are about. For some there are existing ruby ports but you might have to rewrite a few to task. A: For account creation, you may want to use Captchas. I personally am not terribly fond of them and I don't think they are that effective. But if you use them, I strongly suggest you use a service instead of trying to whip up your own. Re-captcha comes to mind. Not sure if there are wrappers for Ruby or Rails, though. To prevent spam content, however, I strongly suggest Defensio (disclaimer: I've worked there in the past). It uses state of the art spam filtering techniques like what's used for email, such as bayesian filtering. There are plugins for many blogging platforms, including Mephisto (made with Rails). The API is simple and you can look in a few places to get working examples of how to use it with Ruby.
Rails state of the art for spam prevention
What is the current state of the art in rails for preventing spam accounts? Captcha? Any good plugins, tutorials or suggestions?
[ "Use a library: You're (almost) always better off appropriating code from people who are better at the subdomain than you are. The Wordpress guys behind Akismet have forgotten more about blog spam than I know, and I was an email anti-spam researcher for a while. You might be interested in a Rails integration plugin for Akismet.\nDefense in Diversity: Spam is a quirky problem, in that the more popular a countermeasure gets the worse it becomes. As such, particularly for low-profile sites, you can get disgustingly good results by coding simple one-off tripwires. I won't give you any code to copy/paste because it defeats the purpose of the excercize: having a countermeasure which is globally unique. \nOne simple example is having a hidden form element which starts as some randomized string, and which is set to a known good value by Javascript code. You then bounce anything which doesn't have the good value supplied. This blocks clients which don't implement Javascript, which includes the overwhelming majority of spam scripts. There are issues, of course, as some legitimate clients also block Javascript -- but realistically, if you're using Rails, I'm guessing you're sort of assuming cookies are on and Javascript works.\n", "I also recommend ReCAPTCHA, both because it's a highly-reliable service you don't have to manage, and because it serves two common goods - the OCR tasks described by the ReCAPTCHA team, and the progress towards teaching people how captchas work, reducing abandonment rates. \n", "There is a re-captcha plugin if you want to use captch to verifye that only human can register, or add content: http://ambethia.com/recaptcha/files/README_rdoc.html\n", "Edit:\nIt appears BranBuster is dead (this was years ago). But I really like:\nhttps://github.com/matthutchinson/acts_as_textcaptcha\nI'm a big fan of the rails plugin called \"BrainBuster\". It's a logic-based CAPTCHA which I find preferable over the \"type these words\" things, because it is annoying to decipher the words sometimes... It's simple to look at \"What is 10 minus 3?\" and come up with the answer. YMMV:\nhttps://github.com/rsanheim/brain_buster\n", "Spam is fair. It doesn't care what you're running behind the scenes.\nSo by extension, the things that work well on Rails are the same things that work for PHP, ASPNET, etc. Take a look at Akismet and the various \"karma\" anti-bot tools there are about.\nFor some there are existing ruby ports but you might have to rewrite a few to task.\n", "For account creation, you may want to use Captchas. I personally am not terribly fond of them and I don't think they are that effective. But if you use them, I strongly suggest you use a service instead of trying to whip up your own. Re-captcha comes to mind. Not sure if there are wrappers for Ruby or Rails, though.\nTo prevent spam content, however, I strongly suggest Defensio (disclaimer: I've worked there in the past). It uses state of the art spam filtering techniques like what's used for email, such as bayesian filtering. There are plugins for many blogging platforms, including Mephisto (made with Rails). The API is simple and you can look in a few places to get working examples of how to use it with Ruby.\n" ]
[ 6, 3, 1, 1, 0, 0 ]
[]
[]
[ "captcha", "ruby_on_rails" ]
stackoverflow_0000102027_captcha_ruby_on_rails.txt
Q: What are the main differences between CLTL2 and ANSI CL? Any online links / resources? A: Bill Clementson has http://bc.tech.coop/cltl2-ansi.htm which is a repost of http://groups.google.com/group/comp.lang.lisp/msg/0e9aced3bf023d86 I also found http://web.archive.org/web/20060111013153/http://www.ntlug.org/~cbbrowne/commonlisp.html#AEN10329 while answering the question. I've not compared the two. As the posters note, those are only main differences. The intent is to let you tweak your copy of cltl2 into not confusing you in any major way, but the resulting document should not be treated as standard. Personally I didn't bother-- I use cltl2 as a bed side reading (Steele is an excellent writer!), to gain insight into various aspects of the language, and the process by which those aspects were standardized; lets me think in CL better. When I program, I reference HyperSpec exclusively.
What are the main differences between CLTL2 and ANSI CL?
Any online links / resources?
[ "Bill Clementson has http://bc.tech.coop/cltl2-ansi.htm which is a repost of http://groups.google.com/group/comp.lang.lisp/msg/0e9aced3bf023d86\nI also found http://web.archive.org/web/20060111013153/http://www.ntlug.org/~cbbrowne/commonlisp.html#AEN10329 while answering the question. I've not compared the two.\nAs the posters note, those are only main differences. The intent is to let you tweak your copy of cltl2 into not confusing you in any major way, but the resulting document should not be treated as standard.\nPersonally I didn't bother-- I use cltl2 as a bed side reading (Steele is an excellent writer!), to gain insight into various aspects of the language, and the process by which those aspects were standardized; lets me think in CL better. When I program, I reference HyperSpec exclusively.\n" ]
[ 5 ]
[]
[]
[ "common_lisp", "lisp" ]
stackoverflow_0000108537_common_lisp_lisp.txt
Q: What factor determines the cost of a software project? If you have $100 in your hand right now. And have to bet on one of these options. That would you bet it on? The question is: What is the most important factor, that determents the cost of a project. Typing speed of the programmers. The total amount of characters typed while programming. The 'wc *.c' command. The end size of the c files. The abstractions used while solving the problem. Update: Ok, just for the record. This is the most stupid question I ever asked. The question should be. Rank the list above. Most important factor first. Which are the most important factor. I ask, because I think the character count matters. Less character to change when requirements change. The faster it's done. Or? UPDATE: This question was discussed in Stackoverflow podcast #23. Thanks Jeff! :) A: From McConnell: http://www.codinghorror.com/blog/archives/000637.html [For a software project], size is easily the most significant determinant of effort, cost, and schedule. The kind of software you're developing comes in second, and personnel factors are a close third. The programming language and environment you use are not first-tier influences on project outcome, but they are a first-tier influence on the estimate. Project size Kind of software being developed Personnel factors I don't think you accounted for #3 in the above list. There's usually an order of magnitude or more difference in skill between programmers, not to mention all the Peopleware issues that can affect the schedule profoundly (bad apples, bad management, etc). A: None of those things are major factors in the cost of a project. What it all comes down to is how well your schedule is put together - can you deliver what you said you would deliver by a certain date. If your schedule estimates are off, well guess what, you're project is going to cost a lot more than you thought it would. In the end, it's schedule estimates all the way. Edit: I realize this is a vote, and that I didn't actually vote on any of the choices in the question, so feel free to consider this a comment on the question instead of a vote. A: I thing the largest amount on large projects are testing and fixing the bugs and fixing misinterpretation of the requirements. First you need write tests. Than you fix the code that the tests run. Than you make the manual tests. Then you must write more tests. On a large project the testing and fixing can consume 40-50% of time. If you have high quality requirements then it can be more. A: Characters, file size, and typing speed can be considered of zero cost, compared to proper problem definition, design and testing. They are easily an order of magnitude more important. A: The most important single factor determining the cost of a project is the scale and ambition of the vision. The second most important is how well you (your team, your management, etc.) control the inevitable temptation to expand that vision as you progress. The factors you list are themselves just metrics of the scale of the project, not what determines that scale. A: Of the four options you gave, I'd go with #2 - the size of the project. A quick project for cleaning out spam is going to be generally quicker than developing a new word processor, after all. After that I'd go with "The abstractions used while solving the problem." next - if you come up with the wrong method of solving the problem, either wrong because of the logic being bad or because of a restriction with the system - then you'll definitely spend more money on re-design and re-coding what has already been done.
What factor determines the cost of a software project?
If you have $100 in your hand right now. And have to bet on one of these options. That would you bet it on? The question is: What is the most important factor, that determents the cost of a project. Typing speed of the programmers. The total amount of characters typed while programming. The 'wc *.c' command. The end size of the c files. The abstractions used while solving the problem. Update: Ok, just for the record. This is the most stupid question I ever asked. The question should be. Rank the list above. Most important factor first. Which are the most important factor. I ask, because I think the character count matters. Less character to change when requirements change. The faster it's done. Or? UPDATE: This question was discussed in Stackoverflow podcast #23. Thanks Jeff! :)
[ "From McConnell:\nhttp://www.codinghorror.com/blog/archives/000637.html\n\n[For a software project], size is easily the most significant determinant of effort, cost, and schedule. The kind of software you're developing comes in second, and personnel factors are a close third. The programming language and environment you use are not first-tier influences on project outcome, but they are a first-tier influence on the estimate. \n\n\nProject size\nKind of software being developed\nPersonnel factors\n\nI don't think you accounted for #3 in the above list. There's usually an order of magnitude or more difference in skill between programmers, not to mention all the Peopleware issues that can affect the schedule profoundly (bad apples, bad management, etc).\n", "None of those things are major factors in the cost of a project. What it all comes down to is how well your schedule is put together - can you deliver what you said you would deliver by a certain date. If your schedule estimates are off, well guess what, you're project is going to cost a lot more than you thought it would. In the end, it's schedule estimates all the way.\nEdit: I realize this is a vote, and that I didn't actually vote on any of the choices in the question, so feel free to consider this a comment on the question instead of a vote.\n", "I thing the largest amount on large projects are testing and fixing the bugs and fixing misinterpretation of the requirements. First you need write tests. Than you fix the code that the tests run. Than you make the manual tests. Then you must write more tests. On a large project the testing and fixing can consume 40-50% of time. If you have high quality requirements then it can be more.\n", "Characters, file size, and typing speed can be considered of zero cost, compared to proper problem definition, design and testing. They are easily an order of magnitude more important.\n", "The most important single factor determining the cost of a project is the scale and ambition of the vision. The second most important is how well you (your team, your management, etc.) control the inevitable temptation to expand that vision as you progress. The factors you list are themselves just metrics of the scale of the project, not what determines that scale.\n", "Of the four options you gave, I'd go with #2 - the size of the project. A quick project for cleaning out spam is going to be generally quicker than developing a new word processor, after all.\nAfter that I'd go with \"The abstractions used while solving the problem.\" next - if you come up with the wrong method of solving the problem, either wrong because of the logic being bad or because of a restriction with the system - then you'll definitely spend more money on re-design and re-coding what has already been done.\n" ]
[ 7, 1, 0, 0, 0, 0 ]
[]
[]
[ "estimation", "project_management" ]
stackoverflow_0000108604_estimation_project_management.txt
Q: How to record webcam to flv with smooth playback I would like my website to record flvs using webcams. These flvs need to play smoothly so I can play with them afterwards, for example transcoding them to avis. I've tried many different servers to handle the flv recording. The resulting flvs play OK in Wimpy FLV Player, for example, except that the progress indicator doesn't move smoothly or in a regular fashion. This is a sign that there is something wrong and if I try to transcode them using "ffmpeg -i input.flv output.avi" (with or without the framerate option "-r 15") I don't get the right avi. Here's what I tried and the kind of problem I get: Using red5 (v 0.6.3 and 0.7.0, both on OS X 10.5.4 and Ubuntu 8.04) and the publisher.html example it includes. Here's the resulting flv. The indicator jumps towards the end very rapidly. Still using red5, but publishing "live" and starting the recording after a couple of seconds. I used these example files. Here's the resulting flv. The indicator still jumps to the end very rapidly, no sound at all with this method... Using Wowza Media Server Pro (v 1.5.3, on my mac). The progress indicator doesn't jump to the end, but it moves more quickly at the very beginning. This is enough that conversion to other formats using ffmpeg will have the visual not synchronized properly with the audio. Just to be sure I tried the video recorder that comes with it, as well as using red5's publisher.html (with identical results). Using Flash Media Server 3 through an account hosted at www.influxis.com. I get yet another progression pattern. The progress indicator jumps a bit a the beginning and then becomes regular. Here's an example. I know it is possible to record a "flawless" flv because facebook's video application does it (using red5?) Indeed, it's easy to look at the HTML source of facebook video and get the http URL to download the flvs they produce. When played back in Wimpy, the progress indicator is smooth, and transcoding with "ffmpeg -i facebook.flv -r 15 facebook.avi" produces a good avi. Here's an example. So, can I manage to get a good flv with a constant framerate? PS: Server must be either installable on Linux or else be available at a reasonably priced hosting provider. Edit: As pointed out, maybe the problem is not framerate per say but something else. I am not knowledgeable in video and I don't know how to inspect the examples I gave to check things out; maybe someone can shed some light on this. A: Looking at your red5 example flv in richflv (very handy flv editing tool) we can see that you have regular keyframes but the duration metadata isn't set. The facebook example flv has hardly any keyframes (which would mean you wouldn't be able 'seek' within it very well) however the metadata duration is correct. I'd look into flvtool2 and flvtool++ (which is a more memory efficient alternative for long files) to insert the correct metadata post capture. A: Your problem might not be with the framerate but with keyframes and markers.
How to record webcam to flv with smooth playback
I would like my website to record flvs using webcams. These flvs need to play smoothly so I can play with them afterwards, for example transcoding them to avis. I've tried many different servers to handle the flv recording. The resulting flvs play OK in Wimpy FLV Player, for example, except that the progress indicator doesn't move smoothly or in a regular fashion. This is a sign that there is something wrong and if I try to transcode them using "ffmpeg -i input.flv output.avi" (with or without the framerate option "-r 15") I don't get the right avi. Here's what I tried and the kind of problem I get: Using red5 (v 0.6.3 and 0.7.0, both on OS X 10.5.4 and Ubuntu 8.04) and the publisher.html example it includes. Here's the resulting flv. The indicator jumps towards the end very rapidly. Still using red5, but publishing "live" and starting the recording after a couple of seconds. I used these example files. Here's the resulting flv. The indicator still jumps to the end very rapidly, no sound at all with this method... Using Wowza Media Server Pro (v 1.5.3, on my mac). The progress indicator doesn't jump to the end, but it moves more quickly at the very beginning. This is enough that conversion to other formats using ffmpeg will have the visual not synchronized properly with the audio. Just to be sure I tried the video recorder that comes with it, as well as using red5's publisher.html (with identical results). Using Flash Media Server 3 through an account hosted at www.influxis.com. I get yet another progression pattern. The progress indicator jumps a bit a the beginning and then becomes regular. Here's an example. I know it is possible to record a "flawless" flv because facebook's video application does it (using red5?) Indeed, it's easy to look at the HTML source of facebook video and get the http URL to download the flvs they produce. When played back in Wimpy, the progress indicator is smooth, and transcoding with "ffmpeg -i facebook.flv -r 15 facebook.avi" produces a good avi. Here's an example. So, can I manage to get a good flv with a constant framerate? PS: Server must be either installable on Linux or else be available at a reasonably priced hosting provider. Edit: As pointed out, maybe the problem is not framerate per say but something else. I am not knowledgeable in video and I don't know how to inspect the examples I gave to check things out; maybe someone can shed some light on this.
[ "Looking at your red5 example flv in richflv (very handy flv editing tool) we can see that you have regular keyframes but the duration metadata isn't set.\nThe facebook example flv has hardly any keyframes (which would mean you wouldn't be able 'seek' within it very well) however the metadata duration is correct.\nI'd look into flvtool2 and flvtool++ (which is a more memory efficient alternative for long files) to insert the correct metadata post capture.\n", "Your problem might not be with the framerate but with keyframes and markers.\n" ]
[ 2, 0 ]
[]
[]
[ "flash", "red5", "webcam" ]
stackoverflow_0000067536_flash_red5_webcam.txt
Q: Does WCF play well with Java? Which of the WCF Service Protocols work well with Java? Do the TCP Service Bindings work with java remoting (either Corba, EJB, JMS, etc.)? What about the WebServices exposed as Service EndPoints. Have these been tested against the common Java WebServices stack for interoperability? A: You will need to use one of the HTTP bindings. The TCP binding requires WCF to be on both sides. A: I have had some bad experiences when dealing with a Java based web service using the WS-Security specs. In that case there was very little, and mostly conflicting, documentation and no tech support at all from the vendor. It took us quite a bit of time to get it working but using a WS-Security sample as the basis we got everything working in the end. The main problem was working against a poorly document black box system with security enabled makes it hard to figure out where you are going wrong, with or without WCF. A: WCF has been tested with Sun's Java WEbservices stack and Apache's Axis for interoperability. So, I'd say it's pretty good. Can you elaborate on "OR DOES TCP WORK AS WELL" ? thank you,
Does WCF play well with Java?
Which of the WCF Service Protocols work well with Java? Do the TCP Service Bindings work with java remoting (either Corba, EJB, JMS, etc.)? What about the WebServices exposed as Service EndPoints. Have these been tested against the common Java WebServices stack for interoperability?
[ "You will need to use one of the HTTP bindings. The TCP binding requires WCF to be on both sides.\n", "I have had some bad experiences when dealing with a Java based web service using the WS-Security specs. In that case there was very little, and mostly conflicting, documentation and no tech support at all from the vendor. It took us quite a bit of time to get it working but using a WS-Security sample as the basis we got everything working in the end.\nThe main problem was working against a poorly document black box system with security enabled makes it hard to figure out where you are going wrong, with or without WCF. \n", "WCF has been tested with Sun's Java WEbservices stack and Apache's Axis for interoperability.\nSo, I'd say it's pretty good.\nCan you elaborate on \"OR DOES TCP WORK AS WELL\" ?\nthank you,\n" ]
[ 8, 2, 1 ]
[]
[]
[ "c#", "java", "wcf" ]
stackoverflow_0000107076_c#_java_wcf.txt
Q: Solution deployment, CM, InstallShield People, We have 4 or 5 utilities that work in conjunction with our application. These utilities are either .bat files, or VB apps, PowerBuilder, etc. I am trying to manage these utils in source control, and am trying to figure out a better way to assign versions to them. Right now, the developers use the version control's meta-data -- specifically label -- to store the version number of the tool. My goal is to have individual InstallShield packages for each utility, and an easy means to manage and assign version numbers to these packages. Would you recommend a separate .ini file with the info, or store the info in InstallShield .ism file itself, or just use the meta-data info from version control tool? UPDATE: I like the idea Orion. I have one concern though. The script that increments the version number... it can not be intelligent enough to increment Major number etc. right. e.g. if one of the utils has version 1.2.3 and we are at a point where the new version is 2.0.0. The script may not be able to handle this. I think this has to do a lot with our branching techniques -- we don't have any. The folks thought since the utils are so small, the source may not need branches. A: PowerBuilder in particular has a nice trick you can do to incorporate the build number from an ini file into the compiled application. Details here: http://www.pbdr.com/pbtips/ex/autorev.htm We have ini file inside source control that stores the build number and its value is used in our build scripts to determine what label to apply to the source tree after a successful build. Works very nicely for our needs. When we branch, we do have to manually kick the file to increment the proper number though. A: I managed our build system at my last job, which seemed to have some parallels to what you're asking. There were ~30 C++ projects which needed compiling, and various .NET/Java things, and the odd perl script. This was all built on our build machine using NAnt - If I were doing it today I'd use rake, but the idea is the same. We basically had an auto-incrementing build number which was stored in a version.txt file in the root of the repository. Each time we did a build (automatically done each night, or also on-demand if neccessary) the script would increment this number and check the file back into source control. All the other apps referenced this file for their version number, or for things which didn't support working like this, the script would set environment variables or perform other workarounds I'm pretty sure that our installshield programs referenced an environment variable for their version number, but we deprecated them in favour of wix as installshield really did suck in the case of visual studio, grep/replace the number within the .csproj files, and check them back in Hope this gives you some ideas A: Using the meta data from your version control system should keep things simpler. It's how your developers already use the system. There is no additional file to maintain. My personal experience has taught me to version the satellite applications with the same as version as the main app. K.I.S.S
Solution deployment, CM, InstallShield
People, We have 4 or 5 utilities that work in conjunction with our application. These utilities are either .bat files, or VB apps, PowerBuilder, etc. I am trying to manage these utils in source control, and am trying to figure out a better way to assign versions to them. Right now, the developers use the version control's meta-data -- specifically label -- to store the version number of the tool. My goal is to have individual InstallShield packages for each utility, and an easy means to manage and assign version numbers to these packages. Would you recommend a separate .ini file with the info, or store the info in InstallShield .ism file itself, or just use the meta-data info from version control tool? UPDATE: I like the idea Orion. I have one concern though. The script that increments the version number... it can not be intelligent enough to increment Major number etc. right. e.g. if one of the utils has version 1.2.3 and we are at a point where the new version is 2.0.0. The script may not be able to handle this. I think this has to do a lot with our branching techniques -- we don't have any. The folks thought since the utils are so small, the source may not need branches.
[ "PowerBuilder in particular has a nice trick you can do to incorporate the build number from an ini file into the compiled application.\nDetails here: http://www.pbdr.com/pbtips/ex/autorev.htm\nWe have ini file inside source control that stores the build number and its value is used in our build scripts to determine what label to apply to the source tree after a successful build. Works very nicely for our needs. When we branch, we do have to manually kick the file to increment the proper number though.\n", "I managed our build system at my last job, which seemed to have some parallels to what you're asking.\nThere were ~30 C++ projects which needed compiling, and various .NET/Java things, and the odd perl script.\nThis was all built on our build machine using NAnt - If I were doing it today I'd use rake, but the idea is the same.\nWe basically had an auto-incrementing build number which was stored in a version.txt file in the root of the repository.\nEach time we did a build (automatically done each night, or also on-demand if neccessary) the script would increment this number and check the file back into source control.\nAll the other apps referenced this file for their version number, or for things which didn't support working like this, the script would set environment variables or perform other workarounds\n\nI'm pretty sure that our installshield programs referenced an environment variable for their version number, but we deprecated them in favour of wix as installshield really did suck\nin the case of visual studio, grep/replace the number within the .csproj files, and check them back in\n\nHope this gives you some ideas\n", "Using the meta data from your version control system should keep things simpler. It's how your developers already use the system. There is no additional file to maintain. My personal experience has taught me to version the satellite applications with the same as version as the main app. K.I.S.S\n" ]
[ 1, 0, 0 ]
[]
[]
[ "content_management_system", "installshield", "packaging", "versioning" ]
stackoverflow_0000017955_content_management_system_installshield_packaging_versioning.txt
Q: Customising the generic Rails error message Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to. We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client. Can anyone recommend an approach that would allow us to do this. Thanks DOm A: For catching exceptions in Rails 2, rescue_from controller method is a great way to specify actions which handle various cases. class ApplicationController < ActionController::Base rescue_from MyAppError, :with => :show_errors def show_errors render :action => "..." end end This way you can make dynamic error pages to replace the static "public/500.html" page. A: It's not clear if you're trying to do inline error messaging or new page error messaging, but if you want to improve the text around inline error messaging, this post provides good information.
Customising the generic Rails error message
Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to. We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client. Can anyone recommend an approach that would allow us to do this. Thanks DOm
[ "For catching exceptions in Rails 2, rescue_from controller method is a great way to specify actions which handle various cases.\nclass ApplicationController < ActionController::Base\n rescue_from MyAppError, :with => :show_errors\n\n def show_errors\n render :action => \"...\"\n end\nend\n\nThis way you can make dynamic error pages to replace the static \"public/500.html\" page.\n", "It's not clear if you're trying to do inline error messaging or new page error messaging, but if you want to improve the text around inline error messaging, this post provides good information.\n" ]
[ 5, 0 ]
[]
[]
[ "ruby_on_rails" ]
stackoverflow_0000101012_ruby_on_rails.txt
Q: What is the recommended version of GNU autotools? We maintain a RPM based software distribution at work so that we have a common set of software across all the platforms that we support. As a result we have to build a lot of third party software, and frequently find situations where we need to run autoconf/automake/libtoolize/etc to get it to build on Solaris or another platform. I've had very mixed results with this. It seems that these tools are fairly brittle and frequently the files only work with the version of autoconf/automake/etc that they were originally written for. Ideally I'd like to only have to support one version of the GNU autotools, but I get the impression that I'm really going to end up having to have a copy of every version lying around. Is this unusual, or do other people have the same problems? Is there a subset of the versions of autotools that will cover all cases? A: It is true that autotools can be brittle and version specific. But remember that you only need to use these tools on your development machines. Deploying the project to the target machine doesn't require that any of the tools are installed on the target. Even test machines don't need any of the tools. They are really only need to run when the dependencies change, such as adding additional files or libraries to the project. We have been using these tools for inhouse projects for many years, and haven't come across a better solution. If you are in a Unix world, don't underestimate the benefit of having a system where configure; make; make install just works. A: Your experiences are not unusual. Autotools is brittle like that, specially for complex projects. There seems to be no alternative for having a lot of versions of it around, sadly.
What is the recommended version of GNU autotools?
We maintain a RPM based software distribution at work so that we have a common set of software across all the platforms that we support. As a result we have to build a lot of third party software, and frequently find situations where we need to run autoconf/automake/libtoolize/etc to get it to build on Solaris or another platform. I've had very mixed results with this. It seems that these tools are fairly brittle and frequently the files only work with the version of autoconf/automake/etc that they were originally written for. Ideally I'd like to only have to support one version of the GNU autotools, but I get the impression that I'm really going to end up having to have a copy of every version lying around. Is this unusual, or do other people have the same problems? Is there a subset of the versions of autotools that will cover all cases?
[ "It is true that autotools can be brittle and version specific. But remember that you only need to use these tools on your development machines. Deploying the project to the target machine doesn't require that any of the tools are installed on the target. Even test machines don't need any of the tools. They are really only need to run when the dependencies change, such as adding additional files or libraries to the project.\nWe have been using these tools for inhouse projects for many years, and haven't come across a better solution. If you are in a Unix world, don't underestimate the benefit of having a system where configure; make; make install just works. \n", "Your experiences are not unusual. Autotools is brittle like that, specially for complex projects. There seems to be no alternative for having a lot of versions of it around, sadly.\n" ]
[ 5, 1 ]
[]
[]
[ "autotools", "c", "c++", "gnu", "unix" ]
stackoverflow_0000106405_autotools_c_c++_gnu_unix.txt
Q: MOSS 2007: BDC permisson problem - no BDC application is listed in the web part's configuration menu I'm actually working at MOSS 2007 project where I have to import data from an external data source (WebService) via an application in the Business Data Catalog. The application definition was created with BDC Meta Man and was imported successfully into the Business Data Catalog without any errors. I've first tested the external data source through the option "Edit profile page template" where a BDC-Webpart is already located on a site. In the preferences menu of the web part I could selected the new BDC application with the "Typ"-Picker and everything works fine. Unfortunately it doesn't work with BDC web parts on other MOSS applications which uses the same SSP. Every time I placed a BDC web part on a site and try to configure it. The "Typ"-Picker in the web part's menu remains empty and no application from BDC is listed. I then checked the permission settings in the BDC menu of the SSP where I experimentally granted all rights to every user account so I could see if it was permission problem. Unfortunately it didn't change anything and the BDC application is still not visible in the "Typ"-Picker. So perhaps someone had a similar problem and know what the problem is! Bye, Flo A: Make sure you set the permissions on the application as well as the entity.
MOSS 2007: BDC permisson problem - no BDC application is listed in the web part's configuration menu
I'm actually working at MOSS 2007 project where I have to import data from an external data source (WebService) via an application in the Business Data Catalog. The application definition was created with BDC Meta Man and was imported successfully into the Business Data Catalog without any errors. I've first tested the external data source through the option "Edit profile page template" where a BDC-Webpart is already located on a site. In the preferences menu of the web part I could selected the new BDC application with the "Typ"-Picker and everything works fine. Unfortunately it doesn't work with BDC web parts on other MOSS applications which uses the same SSP. Every time I placed a BDC web part on a site and try to configure it. The "Typ"-Picker in the web part's menu remains empty and no application from BDC is listed. I then checked the permission settings in the BDC menu of the SSP where I experimentally granted all rights to every user account so I could see if it was permission problem. Unfortunately it didn't change anything and the BDC application is still not visible in the "Typ"-Picker. So perhaps someone had a similar problem and know what the problem is! Bye, Flo
[ "Make sure you set the permissions on the application as well as the entity.\n" ]
[ 3 ]
[]
[]
[ "bdc", "moss", "sharepoint" ]
stackoverflow_0000108051_bdc_moss_sharepoint.txt
Q: How do I stop Blend 2.5 June Preview replacing Canvas.ZIndex with Panel.ZIndex on SL1.0 XAML? I have a Silverlight 1.0 application that I edit with Blend 2.5. Whenever I touch a UIElement in the designer that has a Canvas attribute such as Canvas.ZIndex="1", when it updates the XAML, it changes the Canvas prefix to Panel, leaving Panel.ZIndex="1", causing the page to fail to load. How do I make it stop the insanity!?! I have uninstalled 2.5 and reinstalled an older Blend 2 preview and that was better, but then compatibility with VS2k8 was not as good, and I'm also working on some SL2.0 projects from time to time, as well as WPF apps, both of which I prefer Blend 2.5 for. A: Looks like it's a reported bug in 2.5, http://social.expression.microsoft.com/forums/en-US/blend/thread/db02b75c-922e-4de1-8943-bd525d9862c0/ Their suggested workaround is to use 2.0 for SL1. Still, I expect there will be a new version of Blend released fairly shortly, since SL2 is likely to be released around PDC this year (end of October).
How do I stop Blend 2.5 June Preview replacing Canvas.ZIndex with Panel.ZIndex on SL1.0 XAML?
I have a Silverlight 1.0 application that I edit with Blend 2.5. Whenever I touch a UIElement in the designer that has a Canvas attribute such as Canvas.ZIndex="1", when it updates the XAML, it changes the Canvas prefix to Panel, leaving Panel.ZIndex="1", causing the page to fail to load. How do I make it stop the insanity!?! I have uninstalled 2.5 and reinstalled an older Blend 2 preview and that was better, but then compatibility with VS2k8 was not as good, and I'm also working on some SL2.0 projects from time to time, as well as WPF apps, both of which I prefer Blend 2.5 for.
[ "Looks like it's a reported bug in 2.5,\nhttp://social.expression.microsoft.com/forums/en-US/blend/thread/db02b75c-922e-4de1-8943-bd525d9862c0/\nTheir suggested workaround is to use 2.0 for SL1. Still, I expect there will be a new version of Blend released fairly shortly, since SL2 is likely to be released around PDC this year (end of October).\n" ]
[ 1 ]
[]
[]
[ "blend", "silverlight", "wpf", "xaml" ]
stackoverflow_0000105480_blend_silverlight_wpf_xaml.txt
Q: VS2005 VB.NET XML Comments ''' - stopped working I'm using VS2005 in a solution with a mix of VB and C# in different projects. I use this solution on several different computers and XML comments with both /// (c#) and ''' (VB) have been fine for months. all of a sudden, on my main development machine, they've stopped working in VB. They still work in C#. They work in other projects, too (in VB). It's just all VB projects within this one solution. Does anyone have any ideas? I can't pinpoint when it stopped working as I haven't modified much of the VB code for weeks/months. A: aha! in the 'compile' tab under properties, the 'generate documentation' checkbox was not ticked. looking at SVN it looks like someone checked in the VB projects with this unticked, for some reason. thanks for the help! it's my first time using this site. looks like the guys involved have done a good job. i love the fact you don't have to register. A: The one reason this might be the case is that the XML file is no longer being created/updated. Make sure the XML Documentation file is set in the project property pages. Has your XML file been put under source control and if so is it checked out on a build. If not then it won't update.
VS2005 VB.NET XML Comments ''' - stopped working
I'm using VS2005 in a solution with a mix of VB and C# in different projects. I use this solution on several different computers and XML comments with both /// (c#) and ''' (VB) have been fine for months. all of a sudden, on my main development machine, they've stopped working in VB. They still work in C#. They work in other projects, too (in VB). It's just all VB projects within this one solution. Does anyone have any ideas? I can't pinpoint when it stopped working as I haven't modified much of the VB code for weeks/months.
[ "aha!\nin the 'compile' tab under properties, the 'generate documentation' checkbox was not ticked.\nlooking at SVN it looks like someone checked in the VB projects with this unticked, for some reason.\nthanks for the help! it's my first time using this site. looks like the guys involved have done a good job. i love the fact you don't have to register.\n", "The one reason this might be the case is that the XML file is no longer being created/updated. Make sure the XML Documentation file is set in the project property pages. Has your XML file been put under source control and if so is it checked out on a build. If not then it won't update.\n" ]
[ 28, 3 ]
[]
[]
[ "comments", "vb.net", "visual_studio_2005" ]
stackoverflow_0000108717_comments_vb.net_visual_studio_2005.txt
Q: Is it possible to build following SQL query The original query looks like this (MySQL): SELECT * FROM books WHERE title LIKE "%text%" OR description LIKE "%text%" ORDER BY date Would it be possible to rewrite it (without unions or procedures), so that result will look like this: list of books where title matches query ordered by date, followed by: list of books where description matches query ordered by date So basically just give a higher priority to matching titles over descriptions. A: In sql server I would do the following: select * from books where title like '%text%' or description like '%text%' order by case when title like '%text%' then 1 else 2 end, date I'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise, just include the derived column in the SELECT as well. A: select * from books where title like "%text%" or description like "%text%" order by date, case when title like "%text%" then 0 else 1 end A: rjk's suggestion is the right way to go. Bear in mind, though, that this query (with or without a union) can't use indexes, so it's not going to scale well. You might want to check out MySQL's fulltext indexing, which will scale better, allow more sophisticated queries, and even help with result ranking. A: You could use a case to sort by: order by case when title like '%text%' then 0 else 1 end A: How about something like this... select * from books where title like "%text%" or description like "%text%" order by case when title like "%text%" then 1 else 0 end desc, date A: DECLARE @Books TABLE ( [ID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY, [Title] NVARCHAR(MAX) NOT NULL, [Description] NVARCHAR(MAX) NOT NULL, [Date] DATETIME NOT NULL ) INSERT INTO @Books SELECT 'War and Peace','A Russian Epic','2008-01-01' UNION SELECT 'Dogs of War','Mercenary Stories','2006-01-01' UNION SELECT 'World At Arms','A Story of World War Two','2007-01-01' UNION SELECT 'The B Team','Street Wars','2005-01-01' SELECT * FROM ( SELECT *, CASE WHEN [Title] LIKE '%war%' THEN 1 WHEN [Description] LIKE '%war%' THEN 2 END AS Ord FROM @Books WHERE [Title] LIKE '%war%' OR [Description] LIKE '%war%' ) AS Derived ORDER BY Ord ASC, [Date] ASC I believe this gives you what you want, but due to the extra workload in the derived CASE statment, it may not have good performance.
Is it possible to build following SQL query
The original query looks like this (MySQL): SELECT * FROM books WHERE title LIKE "%text%" OR description LIKE "%text%" ORDER BY date Would it be possible to rewrite it (without unions or procedures), so that result will look like this: list of books where title matches query ordered by date, followed by: list of books where description matches query ordered by date So basically just give a higher priority to matching titles over descriptions.
[ "In sql server I would do the following:\nselect * from books \nwhere title like '%text%' or description like '%text%'\norder by case when title like '%text%' then 1 else 2 end, date\n\nI'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise, just include the derived column in the SELECT as well.\n", "select * from books \nwhere title like \"%text%\" or description like \"%text%\" \norder by date, case when title like \"%text%\" then 0 else 1 end\n\n", "rjk's suggestion is the right way to go. Bear in mind, though, that this query (with or without a union) can't use indexes, so it's not going to scale well. You might want to check out MySQL's fulltext indexing, which will scale better, allow more sophisticated queries, and even help with result ranking.\n", "You could use a case to sort by:\norder by case when title like '%text%' then 0 else 1 end\n\n", "How about something like this...\nselect * \nfrom books \nwhere title like \"%text%\" \nor description like \"%text%\" \norder by case when title like \"%text%\" then 1 else 0 end desc, date\n\n", "DECLARE @Books TABLE\n(\n [ID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,\n [Title] NVARCHAR(MAX) NOT NULL,\n [Description] NVARCHAR(MAX) NOT NULL,\n [Date] DATETIME NOT NULL\n)\n\nINSERT INTO @Books\nSELECT 'War and Peace','A Russian Epic','2008-01-01' UNION\nSELECT 'Dogs of War','Mercenary Stories','2006-01-01' UNION\nSELECT 'World At Arms','A Story of World War Two','2007-01-01' UNION\nSELECT 'The B Team','Street Wars','2005-01-01' \n\nSELECT * FROM\n(\n SELECT *, CASE WHEN [Title] LIKE '%war%' THEN 1 WHEN [Description] LIKE '%war%' THEN 2 END AS Ord\n FROM @Books\n WHERE [Title] LIKE '%war%' OR [Description] LIKE '%war%'\n) AS Derived\nORDER BY Ord ASC, [Date] ASC\n\nI believe this gives you what you want, but due to the extra workload in the derived CASE statment, it may not have good performance.\n" ]
[ 18, 3, 2, 0, 0, 0 ]
[ "The union command will help you. Something along these lines:\nSELECT *, 1 as order from books where title like '%text%'\nunion\nSELECT *, 2 as order from books where description like '%text%'\nORDER BY order, date\n\n" ]
[ -2 ]
[ "database", "mysql", "sql" ]
stackoverflow_0000105564_database_mysql_sql.txt
Q: Topological sort, recursive, using generators Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } I'd like to have a top-down, recursive solution to let's say, find the chain starting at 'a': a, c, d, e, g, f, b So, right now (a non-generator solution): def get_all(D,k): L = [] def get2(D,k): L.append(k) for ii in D.get(k,[]): get2(D, ii) get2(D,k) return L Obviously, this is pretty weak :) I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this. A: Both answers give the same result, but if my reading of the question is correct give the wrong answer to a simple alteration to the given graph - if you add a dependency on 'c' from 'b' (which doesn't introduce a cycle as the graph is directed) the output is: a c d e g f b d e g f which isn't totally helpful. Try this small variation, which keeps track of which nodes of the graph have already been visited: def get_all(D, k, seen=None): if not seen: seen = set( ) if k not in seen: seen.add(k) yield k for ii in D.get(k, []): for jj in get_all(D, ii, seen): yield jj A: Try this: #!/usr/bin/env python def get_all(D, k): yield k for ii in D.get(k, []): for jj in get_all(D, ii): yield jj A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } for ii in get_all(A,'a'): print ii Gives me steve@rei:~/code/tmp $ python recur.py a c d e g f b
Topological sort, recursive, using generators
Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... A = { 'a' : dict(b=1, c=1), 'c' : dict(d=1), 'd' : dict(e=1,f=1,g=1), 'h' : dict(j=1) } I'd like to have a top-down, recursive solution to let's say, find the chain starting at 'a': a, c, d, e, g, f, b So, right now (a non-generator solution): def get_all(D,k): L = [] def get2(D,k): L.append(k) for ii in D.get(k,[]): get2(D, ii) get2(D,k) return L Obviously, this is pretty weak :) I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this.
[ "Both answers give the same result, but if my reading of the question is correct give the wrong answer to a simple alteration to the given graph - if you add a dependency on 'c' from 'b' (which doesn't introduce a cycle as the graph is directed) the output is: \na\nc\nd\ne\ng\nf\nb\nd\ne\ng\nf\n\nwhich isn't totally helpful. Try this small variation, which keeps track of which nodes of the graph have already been visited:\ndef get_all(D, k, seen=None):\n if not seen:\n seen = set( )\n if k not in seen:\n seen.add(k)\n yield k\n for ii in D.get(k, []):\n for jj in get_all(D, ii, seen):\n yield jj\n\n", "Try this:\n#!/usr/bin/env python\n\ndef get_all(D, k):\n yield k\n for ii in D.get(k, []):\n for jj in get_all(D, ii):\n yield jj\n\nA = { 'a' : dict(b=1, c=1),\n 'c' : dict(d=1),\n 'd' : dict(e=1,f=1,g=1),\n 'h' : dict(j=1)\n }\n\nfor ii in get_all(A,'a'):\n print ii\n\nGives me \n\nsteve@rei:~/code/tmp\n$ python recur.py\na\nc\nd\ne\ng\nf\nb\n\n" ]
[ 6, 4 ]
[]
[]
[ "generator", "python", "recursion", "topology" ]
stackoverflow_0000108586_generator_python_recursion_topology.txt
Q: Fluent NHibernate Many-to-Many I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships. public class Person { public Person() { GroupsOwned = new List<Groups>(); } public virtual IList<Groups> GroupsOwned { get; set; } } public class Groups { public Groups() { Admins= new List<Person>(); } public virtual IList<Person> Admins{ get; set; } } With the mapping looking like this Person: ... HasManyToMany<Groups>(x => x.GroupsOwned) .WithTableName("GroupAdministrators") .WithParentKeyColumn("PersonID") .WithChildKeyColumn("GroupID") .Cascade.SaveUpdate(); Groups: ... HasManyToMany<Person>(x => x.Admins) .WithTableName("GroupAdministrators") .WithParentKeyColumn("GroupID") .WithChildKeyColumn("PersonID") .Cascade.SaveUpdate(); When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it. Thanks for any advice you may have. A: The fact that it is adding two records to the table looks like you are missing an inverse attribute. Since both the person and the group are being changed, NHibernate is persisting the relation twice (once for each object). The inverse attribute is specifically for avoiding this. I'm not sure about how to add it in mapping in code, but the link shows how to do it in XML. A: @Santiago I think you're right. The answer might just be that you need to remove one of your ManyToMany declarations, looking more at Fluent it looks like it might be smart enough to just do it for you. A: Are you making sure to add the Person to the Groups.Admin? You have to make both links. A: You have three tables right? People, Groups, and GroupAdministrators when you add to both sides you get People (with an id of p1) Groups (with an id of g1) and in GroupAdministrators you have two columns and a table that has (p1,g1) (p1,g1) and your unit test code looks like the following. Context hibContext //Built here Transaction hibTrans //build and start the transaction. Person p1 = new Person() Groups g1 = new Groups() p1.getGroupsOwned().add(g1) g1.getAdmins().add(p1) hibTrans.commit(); hibContext.close(); And then in your test you make a new context, and test to see what's in the context, and you get back the right thing, but your tables are all mucked up?
Fluent NHibernate Many-to-Many
I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships. public class Person { public Person() { GroupsOwned = new List<Groups>(); } public virtual IList<Groups> GroupsOwned { get; set; } } public class Groups { public Groups() { Admins= new List<Person>(); } public virtual IList<Person> Admins{ get; set; } } With the mapping looking like this Person: ... HasManyToMany<Groups>(x => x.GroupsOwned) .WithTableName("GroupAdministrators") .WithParentKeyColumn("PersonID") .WithChildKeyColumn("GroupID") .Cascade.SaveUpdate(); Groups: ... HasManyToMany<Person>(x => x.Admins) .WithTableName("GroupAdministrators") .WithParentKeyColumn("GroupID") .WithChildKeyColumn("PersonID") .Cascade.SaveUpdate(); When I run my integration test, basically I'm creating a new person and group. Adding the Group to the Person.GroupsOwned. If I get the Person Object back from the repository, the GroupsOwned is equal to the initial group, however, when I get the group back if I check count on Group.Admins, the count is 0. The Join table has the GroupID and the PersonID saved in it. Thanks for any advice you may have.
[ "The fact that it is adding two records to the table looks like you are missing an inverse attribute. Since both the person and the group are being changed, NHibernate is persisting the relation twice (once for each object). The inverse attribute is specifically for avoiding this.\nI'm not sure about how to add it in mapping in code, but the link shows how to do it in XML.\n", "@Santiago I think you're right.\nThe answer might just be that you need to remove one of your ManyToMany declarations, looking more at Fluent it looks like it might be smart enough to just do it for you.\n", "Are you making sure to add the Person to the Groups.Admin? You have to make both links.\n", "You have three tables right?\nPeople, Groups, and GroupAdministrators\nwhen you add to both sides you get\nPeople (with an id of p1)\nGroups (with an id of g1)\nand in GroupAdministrators you have two columns and a table that has\n(p1,g1)\n(p1,g1)\nand your unit test code looks like the following.\nContext hibContext //Built here\nTransaction hibTrans //build and start the transaction.\n\nPerson p1 = new Person()\nGroups g1 = new Groups()\n\np1.getGroupsOwned().add(g1)\ng1.getAdmins().add(p1)\n\nhibTrans.commit();\nhibContext.close();\n\nAnd then in your test you make a new context, and test to see what's in the context, and you get back the right thing, but your tables are all mucked up?\n" ]
[ 39, 7, 0, 0 ]
[]
[]
[ "c#", "fluent", "fluent_nhibernate", "nhibernate" ]
stackoverflow_0000108396_c#_fluent_fluent_nhibernate_nhibernate.txt
Q: re-rendering of combox store in Gwt-Ext i've created a Form Panel, and i'm rendering couple of Combo Boxes in the panel with a store which is populated via an response handler. the problem if i want to render the panel again it renders the combo boxes without the store, though i'm re-constructing the panel. i tried to debug to figure out the cause and surprisingly though for combo box the Store is null on calling - comboBox.setStore(store) it checks for the property (isRendered) and finds it to be true and hence doesn't add the store but just keep the existing store which is still null. i've seen this problem in another scenaio where i had created a collapsible field set containing the Combobox, On minimize and maximize of the fieldset the store vanishes for the same reasons. can someone please help me here, i'm completely struck here i tried various option but nothing works. A: Thanks for your comments, actually i tried the plugin approach but couldn't understand it completely as to how will i get the handle to the store which is not an exposed element of the component. Anyways i tried something else, while debugging i found that though i'm creating the component again on click of show button, the ID passed is same ( which is desired ) but somehow for the given id there is already the previous reference available in the Ext.Components. Hence an easy solution is following : Component comp = Ext.getCmp(id); if ( comp != null ) comp.destroy( ); this actually worked as the reference which was causing the ( isRendered( ) property of the ComboBox to return true is no more available and hence i can see the store again properly. i hope this helps others who are facing similar issue. Thanks anyways for replying. A: Have you tried doLayout() method of FormPanel? A: ComboBox.view.setStore() should help. If view is a private variable, just try to mention it between Combobox config params when creating. If it doesn't help - you can use plugin like that: view_plugin = { init: function(o) { o.setNewStore = function(newStore) { this.view.setStore(newStore); }; } }; and add a line of plugins: view_plugin, to Combobox config. Then you can call combobox.setNewStore(newStore) later in the code. A: You need to write: field = new ComboBox({plugins: view_plugin}); In your case and define my code of view_pligin somewhere before. Or you can even incorporate it inline: field = new ComboBox({plugins: { code of plugin }); Inside plugin all private properties and methods are accessible/changeable. You also can change store using field.setNewStore(store) at any time later on.
re-rendering of combox store in Gwt-Ext
i've created a Form Panel, and i'm rendering couple of Combo Boxes in the panel with a store which is populated via an response handler. the problem if i want to render the panel again it renders the combo boxes without the store, though i'm re-constructing the panel. i tried to debug to figure out the cause and surprisingly though for combo box the Store is null on calling - comboBox.setStore(store) it checks for the property (isRendered) and finds it to be true and hence doesn't add the store but just keep the existing store which is still null. i've seen this problem in another scenaio where i had created a collapsible field set containing the Combobox, On minimize and maximize of the fieldset the store vanishes for the same reasons. can someone please help me here, i'm completely struck here i tried various option but nothing works.
[ "Thanks for your comments, actually i tried the plugin approach but couldn't understand it completely as to how will i get the handle to the store which is not an exposed element of the component.\nAnyways i tried something else, while debugging i found that though i'm creating the component again on click of show button, the ID passed is same ( which is desired ) but somehow for the given id there is already the previous reference available in the Ext.Components.\nHence an easy solution is following : \nComponent comp = Ext.getCmp(id);\nif ( comp != null )\n comp.destroy( );\nthis actually worked as the reference which was causing the ( isRendered( ) property of the ComboBox to return true is no more available and hence i can see the store again properly.\ni hope this helps others who are facing similar issue.\nThanks anyways for replying.\n", "Have you tried doLayout() method of FormPanel?\n", "ComboBox.view.setStore() should help.\nIf view is a private variable, just try to mention it between Combobox config params when creating. If it doesn't help - you can use plugin like that:\nview_plugin = {\n\n init: function(o) {\n\n o.setNewStore = function(newStore) {\n this.view.setStore(newStore);\n };\n }\n};\n\nand add a line of \nplugins: view_plugin,\n\nto Combobox config.\nThen you can call combobox.setNewStore(newStore) later in the code.\n", "You need to write:\nfield = new ComboBox({plugins: view_plugin});\nIn your case and define my code of view_pligin somewhere before. Or you can even incorporate it inline:\nfield = new ComboBox({plugins: { code of plugin });\nInside plugin all private properties and methods are accessible/changeable.\nYou also can change store using field.setNewStore(store) at any time later on.\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "combobox", "forms", "gwt_ext" ]
stackoverflow_0000090713_combobox_forms_gwt_ext.txt
Q: Running code in the context of a java WAR from the command line How would I go about writing some code to allow access to a Java class in my webapp from the command line. E.g. I have a java class with command line interface, that can runs code in the context of the webapp, with access to the DB etc. I want to log on the machine hosting my WARred app in tomcat and be able to interact with it Where should i start looking ? Thanks A: Do you just want to run class files that just so happen to be bundled in the WAR, or do you want ot interact with the actual, running WAR instance? If the former, then the WAR is just a normal Jar file and you can execute classes in that just like any other other Jar file. If you want to interact with the running WAR, then you might want to look at JMX. All current JDKs (at least 1.5+) come with JMX "for free". It's easy to create little interface classes to be used as commands to interact with your WAR. THen you would need to create a command line program that connects to the WAR via JMX, or you can use a tool like JConsole (which comes with the JDK, but it's a GUI) to interact with your instance. There are other JMX clients out there as well. If none of that is attractive, there's always web services. A: A suggestion: Your command line interface class should accept an InputStream as it's input and provide an OutputStream (it can't hardcode output to System.out and input to System.in) that it's output will be written to. Then you'll have to write a server class that listens for connections on a certain port. When a connection is made the server would take the InputStream from the connection and give it to the command line class which would provide the OutputStream that data written to will be passed to the client that made the connection.
Running code in the context of a java WAR from the command line
How would I go about writing some code to allow access to a Java class in my webapp from the command line. E.g. I have a java class with command line interface, that can runs code in the context of the webapp, with access to the DB etc. I want to log on the machine hosting my WARred app in tomcat and be able to interact with it Where should i start looking ? Thanks
[ "Do you just want to run class files that just so happen to be bundled in the WAR, or do you want ot interact with the actual, running WAR instance? If the former, then the WAR is just a normal Jar file and you can execute classes in that just like any other other Jar file.\nIf you want to interact with the running WAR, then you might want to look at JMX.\nAll current JDKs (at least 1.5+) come with JMX \"for free\". It's easy to create little interface classes to be used as commands to interact with your WAR.\nTHen you would need to create a command line program that connects to the WAR via JMX, or you can use a tool like JConsole (which comes with the JDK, but it's a GUI) to interact with your instance. There are other JMX clients out there as well.\nIf none of that is attractive, there's always web services.\n", "A suggestion:\nYour command line interface class should accept an InputStream as it's input and provide an OutputStream (it can't hardcode output to System.out and input to System.in) that it's output will be written to. Then you'll have to write a server class that listens for connections on a certain port. When a connection is made the server would take the InputStream from the connection and give it to the command line class which would provide the OutputStream that data written to will be passed to the client that made the connection. \n" ]
[ 4, 0 ]
[]
[]
[ "java", "security", "servlets", "tomcat", "war" ]
stackoverflow_0000108838_java_security_servlets_tomcat_war.txt
Q: Can Flash save content without server-side help? As far as I know, Flash has to pass info off to another external process in order to save files - POSTing to PHP or talking to an executable, right? But every once in a while I hear rumors that Flash is able to open a file, make changes, then save/write those changes, all on its own - is it possible? A: This will be available in Flash Player 10: Reading and Writing Local Files in Flash Player 10 http://www.mikechambers.com/blog/2008/08/20/reading-and-writing-local-files-in-flash-player-10/ Otherwise you need to use Adobe AIR, or bounce it off the server. mike chambers [email protected] A: The next version of the player, Flash 10 can do this. It also has support for some other nifty stuff like simple 3D and typed arrays. The flash player running inside AIR can also do this. A: There are lots of security issues around the behavior you just described so Adobe put many sandbox restrictions around file modification behavior. Even with Flash Player 10, expect a requirement that the file manipulation require that the code be executing in response to a mouse event. A: There is something called Local Shared Object, also known as "Flash Cookie" that allows you to store a limited amount of data locally at a user's computer. A little googling turned up a few links: Documentation on the SharedObject class A tutorial And I'm sure a little creative googling can turn up even more
Can Flash save content without server-side help?
As far as I know, Flash has to pass info off to another external process in order to save files - POSTing to PHP or talking to an executable, right? But every once in a while I hear rumors that Flash is able to open a file, make changes, then save/write those changes, all on its own - is it possible?
[ "This will be available in Flash Player 10:\nReading and Writing Local Files in Flash Player 10\nhttp://www.mikechambers.com/blog/2008/08/20/reading-and-writing-local-files-in-flash-player-10/\nOtherwise you need to use Adobe AIR, or bounce it off the server.\nmike chambers\[email protected]\n", "The next version of the player, Flash 10 can do this. It also has support for some other nifty stuff like simple 3D and typed arrays.\nThe flash player running inside AIR can also do this.\n", "There are lots of security issues around the behavior you just described so Adobe put many sandbox restrictions around file modification behavior. Even with Flash Player 10, expect a requirement that the file manipulation require that the code be executing in response to a mouse event.\n", "There is something called Local Shared Object, also known as \"Flash Cookie\" that allows you to store a limited amount of data locally at a user's computer.\nA little googling turned up a few links:\n\nDocumentation on the SharedObject class\nA tutorial\n\nAnd I'm sure a little creative googling can turn up even more\n" ]
[ 5, 3, 1, 0 ]
[]
[]
[ "actionscript_3", "flash" ]
stackoverflow_0000107800_actionscript_3_flash.txt
Q: How can I turn on PHP errors display on just a subfolder I don't want PHP errors to display /html, but I want them to display in /html/beta/usercomponent. Everything is set up so that errors do not display at all. How can I get errors to just show up in that one folder (and its subfolders)? A: In .htaccess: php_value error_reporting 2147483647 This number, according to documentation should enable 'all' errors irrespective of version, if you want a more granular setting, manually OR the values together, or run php -r 'echo E_ALL | E_STRICT ;' to let php compute the value for you. You need AllowOverride All in apaches master configuration to enable .htaccess files. More Reading on this can be found here: Php/Error Reporting Flag Php/Error Reporting values Php/Different Ways of Tuning Settings Notice If you are using Php-CGI instead of mod_php, this may not work as advertised, and all you will get is an internal server error, and you will be left without much option other than enabling it either site-wide on a per-script basis with error_reporting( E_ALL | E_STRICT ); or similar constructs before the error occurs. My advice is to disable displaying errors to the user, and utilize heavily php's error_log feature. display_errors = 0 error_logging = E_ALL | E_STRICT error_log = /var/log/php If you have problems with this being too noisy, this is not a sign you need to just take error reporting off selectively, this is a sign somebody should fix the code. @Roger Yes, you can use it in a <Directory> construct in apaches configuration too, however, the .htaccess in this case is equivalent, and makes it more portable especially if you have multiple working checkout copies of the same codebase and you want to distribute this change to all of them. If you have multiple virtual hosts, you'll want the construct in the respective virtual hosts definition, otherwise, yes <Directory /path/to/wherever/on/filesystem> <IfModule mod_php5.c> php_value error_reporting 214748364 </IfModule> </Directory> The Additional "ifmodule" commands are just a safety net so the above problem with apache dying if you don't have mod_php won't occur. A: The easiest way would be to control the error reporting from a .htaccess file. But this is assuming you are using Apache and the scripts in /html/beta/usercomponent are called from that directory and not included from elsewhere. .htacess php_value error_reporting [int] You will have to compose the integer value yourself from the list as described in the error_reporting documentation, since the constants like E_ERROR aren't defined when Apache interprets the .htaccess. It's a simple bitwise flag, so a value of 12, for example, would be E_WARNING + E_PARSE + E_NOTICE. A: you could do this by using an Environment variable. this way you can have more choices than just turning Error reporting on/off for a special directory. in your code where ever you wanted to change any behaviour for a specific set of directoris, or running modes, check if a environment variable is set or not. like this: if ($_ENV['MY_PHP_APP_MODE'] == 'devel') { // show errors and debugging info } elseif ($_ENV['MY_PHP_APP_MODE'] == 'production') { // show some cool message to the user so he won't freak out // log the errors and send email to the admin } and when you are running your application in your development environment, you can set an env variable in your .htaccess file like this: setenv MY_PHP_APP_MODE devel or when you are in production evn: setenv MY_PHP_APP_MODE production the same technique applies to your situation. in directories where you want to do something special (turn on error reporting) set some env variable and in your code, check for that. A: I don't believe there's a simple answer to this, but I'd certainly want to be proven wrong. edit: turns out this can be controlled from .htaccess files. Thanks people! :) You can use error_reporting() http://docs.php.net/manual/en/function.error-reporting.php to switch the setting on a script by script basis, though. If you happen to have a single script which is included every time at /html/beta/usercomponent, this will do the trick.
How can I turn on PHP errors display on just a subfolder
I don't want PHP errors to display /html, but I want them to display in /html/beta/usercomponent. Everything is set up so that errors do not display at all. How can I get errors to just show up in that one folder (and its subfolders)?
[ "In .htaccess:\nphp_value error_reporting 2147483647\n\nThis number, according to documentation should enable 'all' errors irrespective of version, if you want a more granular setting, manually OR the values together, or run \nphp -r 'echo E_ALL | E_STRICT ;'\n\nto let php compute the value for you.\nYou need \nAllowOverride All\n\nin apaches master configuration to enable .htaccess files. \nMore Reading on this can be found here: \n\nPhp/Error Reporting Flag\nPhp/Error Reporting values\nPhp/Different Ways of Tuning Settings\n\n\nNotice If you are using Php-CGI instead of mod_php, this may not work as advertised, and all you will get is an internal server error, and you will be left without much option other than enabling it either site-wide on a per-script basis with \nerror_reporting( E_ALL | E_STRICT ); \n\nor similar constructs before the error occurs. \nMy advice is to disable displaying errors to the user, and utilize heavily php's error_log feature. \ndisplay_errors = 0\nerror_logging = E_ALL | E_STRICT \nerror_log = /var/log/php \n\nIf you have problems with this being too noisy, this is not a sign you need to just take error reporting off selectively, this is a sign somebody should fix the code.\n\n@Roger\nYes, you can use it in a <Directory> construct in apaches configuration too, however, the .htaccess in this case is equivalent, and makes it more portable especially if you have multiple working checkout copies of the same codebase and you want to distribute this change to all of them.\nIf you have multiple virtual hosts, you'll want the construct in the respective virtual hosts definition, otherwise, yes\n <Directory /path/to/wherever/on/filesystem> \n <IfModule mod_php5.c>\n php_value error_reporting 214748364\n </IfModule>\n </Directory>\n\nThe Additional \"ifmodule\" commands are just a safety net so the above problem with apache dying if you don't have mod_php won't occur. \n", "The easiest way would be to control the error reporting from a .htaccess file. But this is assuming you are using Apache and the scripts in /html/beta/usercomponent are called from that directory and not included from elsewhere.\n.htacess\nphp_value error_reporting [int]\n\nYou will have to compose the integer value yourself from the list as described in the error_reporting documentation, since the constants like E_ERROR aren't defined when Apache interprets the .htaccess.\nIt's a simple bitwise flag, so a value of 12, for example, would be E_WARNING + E_PARSE + E_NOTICE.\n", "you could do this by using an Environment variable. this way you can have more choices than just turning Error reporting on/off for a special directory. in your code where ever you wanted to change any behaviour for a specific set of directoris, or running modes, check if a environment variable is set or not. like this:\nif ($_ENV['MY_PHP_APP_MODE'] == 'devel') {\n // show errors and debugging info\n} elseif ($_ENV['MY_PHP_APP_MODE'] == 'production') {\n // show some cool message to the user so he won't freak out\n // log the errors and send email to the admin\n}\n\nand when you are running your application in your development environment, you can set an env variable in your .htaccess file like this:\n setenv MY_PHP_APP_MODE devel\n\nor when you are in production evn:\n setenv MY_PHP_APP_MODE production\n\nthe same technique applies to your situation. in directories where you want to do something special (turn on error reporting) set some env variable and in your code, check for that.\n", "I don't believe there's a simple answer to this, but I'd certainly want to be proven wrong.\nedit: turns out this can be controlled from .htaccess files. Thanks people! :)\nYou can use error_reporting() http://docs.php.net/manual/en/function.error-reporting.php to switch the setting on a script by script basis, though. If you happen to have a single script which is included every time at /html/beta/usercomponent, this will do the trick.\n" ]
[ 28, 4, 4, 0 ]
[]
[]
[ "php" ]
stackoverflow_0000107828_php.txt
Q: Fastest way to delete all the data in a large table I had to delete all the rows from a log table that contained about 5 million rows. My initial try was to issue the following command in query analyzer: delete from client_log which took a very long time. A: Check out truncate table which is a lot faster. A: I discovered the TRUNCATE TABLE in the msdn transact-SQL reference. For all interested here are the remarks: TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log. TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. TRUNCATE TABLE may not be used on tables participating in an indexed view. A: There is a common myth that TRUNCATE somehow skips transaction log. This is misunderstanding, and is clearly mentioned in MSDN. This myth is invoked in several comments here. Let's eradicate it together ;) A: For reference TRUNCATE TABLE also works on MySQL A: I use the following method to zero out tables, with the added bonus that it leaves me with an archive copy of the table. CREATE TABLE `new_table` LIKE `table`; RENAME TABLE `table` TO `old_table`, `new_table` TO `table`; A: forget truncate and delete. maintain your table definitions (in case you want to recreate it) and just use drop table. A: truncate table client_log is your best bet, truncate kills all content in the table and indices and resets any seeds you've got too. A: On SQL Server you can use the Truncate Table command which is faster than a regular delete and also uses less resources. It will reset any identity fields back to the seed value as well. The drawbacks of truncate are that it can't be used on tables that are referenced by foreign keys and it won't fire any triggers. Also you won't be able to rollback the data if anything goes wrong. A: truncate table is not SQL-platform independent. If you suspect that you might ever change database providers, you might be wary of using it. A: Note that TRUNCATE will also reset any auto incrementing keys, if you are using those. If you do not wish to lose your auto incrementing keys, you can speed up the delete by deleting in sets (e.g., DELETE FROM table WHERE id > 1 AND id < 10000). It will speed it up significantly and in some cases prevent data from being locked up. A: Yes, well, deleting 5 million rows is probably going to take a long time. The only potentially faster way I can think of would be to drop the table, and re-create it. That only works, of course, if you want to delete ALL data in the table. A: The suggestion of "Drop and recreate the table" is probably not a good one because that goofs up your foreign keys. You ARE using foreign keys, right? A: I am revising my earlier statement: You should understand that by using TRUNCATE the data will be cleared but nothing will be logged to the transaction log. Writing to the log is why DELETE will take forever on 5 million rows. I use TRUNCATE often during development, but you should be wary about using it on a production database because you will not be able to roll back your changes. You should immediately make a full database backup after doing a TRUNCATE to establish a new basis for restoration. The above statement was intended to prompt you to be sure that you understand there is difference between the two. Unfortunately, it is poorly written and makes unsupported statements as I have not actually done any testing myself between the two. It is based on statements that I have heard from others. From MSDN: The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log. I just wanted to say that there is a fundamental difference between the two and because there is a difference, there will be applications where one or the other may be inappropriate. A: If you cannot use TRUNCATE TABLE because of foreign keys and/or triggers, you can consider to: drop all indexes; do the usual DELETE; re-create all indexes. This may speed up DELETE somewhat.
Fastest way to delete all the data in a large table
I had to delete all the rows from a log table that contained about 5 million rows. My initial try was to issue the following command in query analyzer: delete from client_log which took a very long time.
[ "Check out truncate table which is a lot faster.\n", "I discovered the TRUNCATE TABLE in the msdn transact-SQL reference. For all interested here are the remarks:\nTRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE.\nThe DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log.\nTRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.\nYou cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.\nTRUNCATE TABLE may not be used on tables participating in an indexed view.\n", "There is a common myth that TRUNCATE somehow skips transaction log.\nThis is misunderstanding, and is clearly mentioned in MSDN. \nThis myth is invoked in several comments here. Let's eradicate it together ;)\n", "For reference TRUNCATE TABLE also works on MySQL\n", "I use the following method to zero out tables, with the added bonus that it leaves me with an archive copy of the table.\nCREATE TABLE `new_table` LIKE `table`;\nRENAME TABLE `table` TO `old_table`, `new_table` TO `table`;\n\n", "forget truncate and delete. maintain your table definitions (in case you want to recreate it) and just use drop table.\n", "truncate table client_log\nis your best bet, truncate kills all content in the table and indices and resets any seeds you've got too.\n", "On SQL Server you can use the Truncate Table command which is faster than a regular delete and also uses less resources. It will reset any identity fields back to the seed value as well.\nThe drawbacks of truncate are that it can't be used on tables that are referenced by foreign keys and it won't fire any triggers. Also you won't be able to rollback the data if anything goes wrong.\n", "truncate table is not SQL-platform independent. If you suspect that you might ever change database providers, you might be wary of using it.\n", "Note that TRUNCATE will also reset any auto incrementing keys, if you are using those.\nIf you do not wish to lose your auto incrementing keys, you can speed up the delete by deleting in sets (e.g., DELETE FROM table WHERE id > 1 AND id < 10000). It will speed it up significantly and in some cases prevent data from being locked up.\n", "Yes, well, deleting 5 million rows is probably going to take a long time. The only potentially faster way I can think of would be to drop the table, and re-create it. That only works, of course, if you want to delete ALL data in the table.\n", "The suggestion of \"Drop and recreate the table\" is probably not a good one because that goofs up your foreign keys.\nYou ARE using foreign keys, right?\n", "I am revising my earlier statement:\n\nYou should understand that by using\n TRUNCATE the data will be cleared but\n nothing will be logged to the\n transaction log. Writing to the log\n is why DELETE will take forever on 5\n million rows. I use TRUNCATE often\n during development, but you should be\n wary about using it on a production\n database because you will not be able\n to roll back your changes. You should\n immediately make a full database\n backup after doing a TRUNCATE to\n establish a new basis for restoration.\n\nThe above statement was intended to prompt you to be sure that you understand there is difference between the two. Unfortunately, it is poorly written and makes unsupported statements as I have not actually done any testing myself between the two. It is based on statements that I have heard from others.\nFrom MSDN:\n\nThe DELETE statement removes rows one\n at a time and records an entry in the\n transaction log for each deleted row.\n TRUNCATE TABLE removes the data by\n deallocating the data pages used to\n store the table's data, and only the\n page deallocations are recorded in the\n transaction log.\n\nI just wanted to say that there is a fundamental difference between the two and because there is a difference, there will be applications where one or the other may be inappropriate.\n", "If you cannot use TRUNCATE TABLE because of foreign keys and/or triggers, you can consider to:\n\ndrop all indexes;\ndo the usual DELETE;\nre-create all indexes.\n\nThis may speed up DELETE somewhat.\n" ]
[ 87, 37, 17, 6, 5, 3, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ "DELETE * FROM table_name;\n\nPremature optimization may be dangerous. Optimizing may mean doing something weird, but if it works you may want to take advantage of it.\nSELECT DbVendor_SuperFastDeleteAllFunction(tablename, BOZO_BIT) FROM dummy;\n\nFor speed I think it depends on...\n\nThe underlying database: Oracle, Microsoft, MySQL, PostgreSQL, others, custom...\nThe table, it's content, and related tables:\n\nThere may be deletion rules. Is there an existing procedure to delete all content in the table? Can this be optimized for the specific underlying database engine? How much do we care about breaking things / related data? Performing a DELETE may be the 'safest' way assuming that other related tables do not depend on this table. Are there other tables and queries that are related / depend on the data within this table? If we don't care much about this table being around, using DROP might be a fast method, again depending on the underlying database.\nDROP TABLE table_name;\n\nHow many rows are being deleted? Is there other information that is quickly gleaned that will optimize the deletion? For example, can we tell if the table is already empty? Can we tell if there are hundreds, thousands, millions, billions of rows?\n" ]
[ -1 ]
[ "sql_server", "tsql" ]
stackoverflow_0000064117_sql_server_tsql.txt
Q: Convert timestamp to alphanum I have an application where a user has to remember and insert an unix timestamp like 1221931027. In order to make it easier to remember the key I like to reduce the number of characters to insert through allowing the characters [a-z]. So I'm searching for an algorithm to convert the timestamp to a shorter alphanum version and do the same backwards. Any hints? A: You could just convert the timestamp into base-36. A: #include <time.h> #include <stdio.h> // tobase36() returns a pointer to static storage which is overwritten by // the next call to this function. // // This implementation presumes ASCII or Latin1. char * tobase36(time_t n) { static char text[32]; char *ptr = &text[sizeof(text)]; *--ptr = 0; // NUL terminator // handle special case of n==0 if (n==0) { *--ptr = '0'; return ptr; } // some systems don't support negative time values, but some do int isNegative = 0; if (n < 0) { isNegative = 1; n = -n; } // this loop is the heart of the conversion while (n != 0) { int digit = n % 36; n /= 36; *--ptr = digit + (digit < 10 ? '0' : 'A'-10); } // insert '-' if needed if (isNegative) { *--ptr = '-'; } return ptr; } int main(int argc, const char **argv) { int i; for (i=1; i<argc; ++i) { long timestamp = atol(argv[i]); printf("%12d => %8s\n", timestamp, tobase36(timestamp)); } } /* $ gcc -o base36 base36.c $ ./base36 0 1 -1 10 11 20 30 35 36 71 72 2147483647 -2147483647 0 => 0 1 => 1 -1 => -1 10 => A 11 => B 20 => K 30 => U 35 => Z 36 => 10 71 => 1Z 72 => 20 2147483647 => ZIK0ZJ -2147483647 => -ZIK0ZJ */ A: convert the timestamp to HEX. That will generate a shorter alphanumeric number for you out of the timestamp. A: Another option sometimes used for things like this is to use lists of syllables. ie. you have a list of syllables like ['a','ab', 'ba','bi','bo','ca','...] and transform the number into base(len(list_of_syllables)). This is longer in terms of letters, but it can often be easier to memorise something like "flobagoka' than something like 'af3q5jl'. (The downside is that it can be easy to generate words that sound like profanity) [Edit] Here's an example of such an algorithm. Using this, 1221931027 would be "buruvadrage"
Convert timestamp to alphanum
I have an application where a user has to remember and insert an unix timestamp like 1221931027. In order to make it easier to remember the key I like to reduce the number of characters to insert through allowing the characters [a-z]. So I'm searching for an algorithm to convert the timestamp to a shorter alphanum version and do the same backwards. Any hints?
[ "You could just convert the timestamp into base-36.\n", "#include <time.h>\n#include <stdio.h>\n\n// tobase36() returns a pointer to static storage which is overwritten by \n// the next call to this function. \n//\n// This implementation presumes ASCII or Latin1.\n\nchar * tobase36(time_t n)\n{\n static char text[32];\n char *ptr = &text[sizeof(text)];\n *--ptr = 0; // NUL terminator\n\n // handle special case of n==0\n if (n==0) {\n *--ptr = '0';\n return ptr;\n }\n\n // some systems don't support negative time values, but some do\n int isNegative = 0;\n if (n < 0)\n {\n isNegative = 1;\n n = -n;\n }\n\n // this loop is the heart of the conversion\n while (n != 0)\n {\n int digit = n % 36;\n n /= 36;\n *--ptr = digit + (digit < 10 ? '0' : 'A'-10);\n }\n\n // insert '-' if needed\n if (isNegative)\n {\n *--ptr = '-';\n }\n\n return ptr;\n}\n\nint main(int argc, const char **argv)\n{\n int i;\n for (i=1; i<argc; ++i)\n {\n long timestamp = atol(argv[i]);\n printf(\"%12d => %8s\\n\", timestamp, tobase36(timestamp));\n }\n}\n\n/*\n$ gcc -o base36 base36.c\n$ ./base36 0 1 -1 10 11 20 30 35 36 71 72 2147483647 -2147483647\n 0 => 0\n 1 => 1\n -1 => -1\n 10 => A\n 11 => B\n 20 => K\n 30 => U\n 35 => Z\n 36 => 10\n 71 => 1Z\n 72 => 20\n 2147483647 => ZIK0ZJ\n -2147483647 => -ZIK0ZJ\n*/\n\n", "convert the timestamp to HEX. That will generate a shorter alphanumeric number for you out of the timestamp. \n", "Another option sometimes used for things like this is to use lists of syllables. ie. you have a list of syllables like ['a','ab', 'ba','bi','bo','ca','...] and transform the number into base(len(list_of_syllables)). This is longer in terms of letters, but it can often be easier to memorise something like \"flobagoka' than something like 'af3q5jl'. (The downside is that it can be easy to generate words that sound like profanity)\n[Edit] Here's an example of such an algorithm. Using this, 1221931027 would be \"buruvadrage\"\n" ]
[ 5, 2, 0, 0 ]
[]
[]
[ "algorithm", "time" ]
stackoverflow_0000108807_algorithm_time.txt
Q: Objectively, what are the pros and cons of Cairngorm over PureMVC? There are so many reasons why using an MVC framework in Flex rocks, but picking the right one seems tricky. I am interested in what you all think from your experiences of implementing either of these (or another). Sam A: The question has already been asked, however since you ask specifically for the benefits of Cairngorm and PureMVC specifically, these are my thoughts: Both PureMVC and Cairngorm make it hard to write testable code. This is mostly down to their use of global variables that tie your application code together tightly, making it hard to isolate any part for testing. This is more true of Cairngorm than PureMVC, but both are pretty bad. PureMVC is more invasive than Cairngorm (meaning that your code is heavily dependent on the framework, e.g. you have to subclass/implement the framework classes/interfaces), but that doesn't mean that Cairngorm isn't. Cairngorm is full of anti-patterns like heavy use of global variables, PureMVC hides the worst parts of itself. PureMVC is anti-Flex, Cairngorm just doesn't use many of the good parts of Flex. By this I mean that PureMVC reinvents many things that Flex already have, because it wants to be platform agnostic, and because of its architecture, specifically the mediators, it makes it harder to use bindings to their full power. Cairngorm just skips over things like event bubbling, and instead opts for solutions involving global variable. In short, Cairngorm is the VisualBasic of Flex, it works but will teach you a lot of bad habits. PureMVC isn't so bad, it just isn't a very good fit for writing Flex applications. What I think you should look at is Mate, which uses Flex to it's full potential, and it isn't built around global variables. Instead it helps you write loosely coupled, testable, reusable and maintainable code without the heavy and needless dependencies on the framework that you see in other application frameworks. If you for some reason don't like Mate, try Swiz, which is a great improvement over Cairngorm, but still has some weird preference for using global variables for central event dispatching (which is completely bizarre considering that one of the points of the framework is to avoid the evil global variables of Cairngorm).
Objectively, what are the pros and cons of Cairngorm over PureMVC?
There are so many reasons why using an MVC framework in Flex rocks, but picking the right one seems tricky. I am interested in what you all think from your experiences of implementing either of these (or another). Sam
[ "The question has already been asked, however since you ask specifically for the benefits of Cairngorm and PureMVC specifically, these are my thoughts:\n\nBoth PureMVC and Cairngorm make it hard to write testable code. This is mostly down to their use of global variables that tie your application code together tightly, making it hard to isolate any part for testing. This is more true of Cairngorm than PureMVC, but both are pretty bad.\nPureMVC is more invasive than Cairngorm (meaning that your code is heavily dependent on the framework, e.g. you have to subclass/implement the framework classes/interfaces), but that doesn't mean that Cairngorm isn't.\nCairngorm is full of anti-patterns like heavy use of global variables, PureMVC hides the worst parts of itself.\nPureMVC is anti-Flex, Cairngorm just doesn't use many of the good parts of Flex. By this I mean that PureMVC reinvents many things that Flex already have, because it wants to be platform agnostic, and because of its architecture, specifically the mediators, it makes it harder to use bindings to their full power. Cairngorm just skips over things like event bubbling, and instead opts for solutions involving global variable.\n\nIn short, Cairngorm is the VisualBasic of Flex, it works but will teach you a lot of bad habits. PureMVC isn't so bad, it just isn't a very good fit for writing Flex applications.\nWhat I think you should look at is Mate, which uses Flex to it's full potential, and it isn't built around global variables. Instead it helps you write loosely coupled, testable, reusable and maintainable code without the heavy and needless dependencies on the framework that you see in other application frameworks.\nIf you for some reason don't like Mate, try Swiz, which is a great improvement over Cairngorm, but still has some weird preference for using global variables for central event dispatching (which is completely bizarre considering that one of the points of the framework is to avoid the evil global variables of Cairngorm).\n" ]
[ 13 ]
[]
[]
[ "apache_flex", "cairngorm", "puremvc" ]
stackoverflow_0000108889_apache_flex_cairngorm_puremvc.txt
Q: How verbose should validation output be? I have an application that reads a database and outputs alerts to any dependencies that are not being met. My thinking on this issue is "Give the minimum information that points the user to the issue." I have been told by a co-worker that I should be as verbose as possible, printing out the values of the database fields for each field I mention verses giving the minimum message that "field one needs to be less then field two". I know that there must be some convention or standard for this issue as it reminds me of compiler errors and warnings. Does anyone know how a compiler messages are are chosen? What suggestion does the community have for this issue? A: I think the key is to be concise. Put as much detail as is required for the reason for the warning to be communicated and nothing more. A: When writing, know your audience. If you're logging warning/error messages for your own consumption, then it's fairly easy: what do you need to know when something goes wrong? If you're logging warning/error messages for someone else, then things get tricky. What do they know? What does their mental model of the system look like? What sorts of problems can they solve, and what information do they need to solve them? Pushing every last scrap of data into a message is punting - at best, the reader will have to wade through irrelevant information in order to find what they need; at worst, they'll become confused and end up making decisions based on the wrong data. The compiler analogy is apt: think how annoying it would be if the entire symbol table was dumped along with every warning... A: For normal, day-to-day operation, I give a data validation message that gives enough information that the user can fix the problem, so that the data validates. For example, if I have two fields (fieldA and fieldB) and one of them have to be greater than the other, then I would state that on the validation output, specifying which field is the offending field. For example, if A has to be greater than B, and they supply an answer less than B, then the message would be "fieldA needs to be higher than fieldB" That said, I also program a debug mode into my applications (especially the web-applications) which has a verbose mode, telling exactly what's happening with everything. If that's turned on you would see two messages, the user-friendly error, and then "FieldA=XX and FieldB=YY: XX is not greater than YY". That's simplified, but it's the general idea. A: I would suggest that you should implement both modes. During normal operation you need a useful but short message. But sometimes things could go wrong and in this case a 'dump' mode which gives the user all possible information is a life saver. A: I think there are 3 levels of the details of an error message for the 3 typical user groups: The end user. This is a surfer on a web site or an user of a desktop application. He should receive an error message if the problem can not be compensate. It should include the minimum of information. The end user should not receive any information over the system like current configuration and file paths. The end user should contact the administrator. A continuous error id can be helpful that the administrator can find more informations. The administrator need more helpful information to solve the problem self. It can include information like table xy not fount or login to database failed. The developer: If the administrator can not solve the problem then it will contact the software vendor. In this case the administrator should be able to send a log file that the developer can solve it also if he can not reproduce the problem. A: The specifics of the content of a log can be discussed, but it is my experience that the level of verbosity will quickly determined during stress test. If the system can not function properly, it is because you just: get either too verbose with your logs, or did log too often (actually, I believe Jeff himself had a similar problem) Atwood: We were logging in such a way that the log.... during the log call was triggering another log call. Which is normally okay, but with the load that we have, eventually they would happen so close together that there's also a lock. So, there's two locks going on there. Spolsky: [...] you have a tendency to wanna log everything. But then you just get logs that are, you know, a hundred megabyte per user and you get thirty of them a minute and it can't possibly be analyzed or stored in any reasonable way. So the next thing you have to do is to start culling your logs or just have different levels of debugging, where it's like in high debug mode everything is logged and in low debug mode nothing is logged. And... it's kind of hard to figure out what you really want in a log. Atwood: I mean that, ironically, to troubleshoot this hang, which turned out to be because of logging, we were adding more logging. Spolsky: [laughs] Atwood: The joke just writes itself! The joke just writes itself, right... So my point is, when you will run your system in a production-like environment, you should quickly be able to determine if the level of verbosity you choose is sustainable.
How verbose should validation output be?
I have an application that reads a database and outputs alerts to any dependencies that are not being met. My thinking on this issue is "Give the minimum information that points the user to the issue." I have been told by a co-worker that I should be as verbose as possible, printing out the values of the database fields for each field I mention verses giving the minimum message that "field one needs to be less then field two". I know that there must be some convention or standard for this issue as it reminds me of compiler errors and warnings. Does anyone know how a compiler messages are are chosen? What suggestion does the community have for this issue?
[ "I think the key is to be concise. Put as much detail as is required for the reason for the warning to be communicated and nothing more.\n", "When writing, know your audience. \nIf you're logging warning/error messages for your own consumption, then it's fairly easy: what do you need to know when something goes wrong?\nIf you're logging warning/error messages for someone else, then things get tricky. What do they know? What does their mental model of the system look like? What sorts of problems can they solve, and what information do they need to solve them?\nPushing every last scrap of data into a message is punting - at best, the reader will have to wade through irrelevant information in order to find what they need; at worst, they'll become confused and end up making decisions based on the wrong data. \nThe compiler analogy is apt: think how annoying it would be if the entire symbol table was dumped along with every warning...\n", "For normal, day-to-day operation, I give a data validation message that gives enough information that the user can fix the problem, so that the data validates. For example, if I have two fields (fieldA and fieldB) and one of them have to be greater than the other, then I would state that on the validation output, specifying which field is the offending field.\nFor example, if A has to be greater than B, and they supply an answer less than B, then the message would be \"fieldA needs to be higher than fieldB\"\nThat said, I also program a debug mode into my applications (especially the web-applications) which has a verbose mode, telling exactly what's happening with everything. If that's turned on you would see two messages, the user-friendly error, and then \"FieldA=XX and FieldB=YY: XX is not greater than YY\".\nThat's simplified, but it's the general idea.\n", "I would suggest that you should implement both modes. During normal operation you need a useful but short message. But sometimes things could go wrong and in this case a 'dump' mode which gives the user all possible information is a life saver.\n", "I think there are 3 levels of the details of an error message for the 3 typical user groups:\n\nThe end user. This is a surfer on a web site or an user of a desktop application. He should receive an error message if the problem can not be compensate. It should include the minimum of information. The end user should not receive any information over the system like current configuration and file paths. The end user should contact the administrator. A continuous error id can be helpful that the administrator can find more informations.\nThe administrator need more helpful information to solve the problem self. It can include information like table xy not fount or login to database failed.\nThe developer: If the administrator can not solve the problem then it will contact the software vendor. In this case the administrator should be able to send a log file that the developer can solve it also if he can not reproduce the problem.\n\n", "The specifics of the content of a log can be discussed, but it is my experience that the level of verbosity will quickly determined during stress test.\nIf the system can not function properly, it is because you just:\n\nget either too verbose with your logs, or\ndid log too often (actually, I believe Jeff himself had a similar problem)\n\n\nAtwood: We were logging in such a way that the log.... during the log call was triggering another log call. Which is normally okay, but with the load that we have, eventually they would happen so close together that there's also a lock. So, there's two locks going on there.\nSpolsky: [...] you have a tendency to wanna log everything. But then you just get logs that are, you know, a hundred megabyte per user and you get thirty of them a minute and it can't possibly be analyzed or stored in any reasonable way. So the next thing you have to do is to start culling your logs or just have different levels of debugging, where it's like in high debug mode everything is logged and in low debug mode nothing is logged. And... it's kind of hard to figure out what you really want in a log.\nAtwood: I mean that, ironically, to troubleshoot this hang, which turned out to be because of logging, we were adding more logging.\nSpolsky: [laughs]\nAtwood: The joke just writes itself! The joke just writes itself, right...\n\nSo my point is, when you will run your system in a production-like environment, you should quickly be able to determine if the level of verbosity you choose is sustainable.\n" ]
[ 2, 2, 1, 0, 0, 0 ]
[ "Dealing with errors Vs. warnings first: An error should be for something which violates the standard. A warning should be for something which is allowed, but quite likely isn't what the author intended.\nFor example, the W3C Markup Validator will warn about the use of the syntax <br /> in an HTML document. In XHTML this means \"A line break\", but in an HTML document, while being allowed, actually means \"A line break followed by a greater than sign\" (even if most browsers don't respect this). \nAs for verbosity, what is best does depend on who is using the system. Some users would be better with brief messages that they can skim through, while other users (perhaps those less advanced) would find the additional information useful. Without knowing more about who they are, I'd tend towards using a flag (-v is traditional) to let the user select which version they prefer.\n" ]
[ -1 ]
[ "database", "formatting", "user_interface", "validation" ]
stackoverflow_0000108947_database_formatting_user_interface_validation.txt
Q: Table and List view with single Model in Qt I have a 2D model where each row represents a frame in a video, and each column represents an object. The object can have different states on each frame, and this is stored in the model. Then I have a QTableView that shows this data. The model has header data, so each row has a header like "frame k" and each column has a header like "object n". This table is editable. But I want the user to edit it another way. The other way is a graphics view that shows a single frame. Below the graphics view is a list (oriented horizontally) that represents each frame. This way the user can click on a frame in the list and the graphics view now displays that frame. The problem is that the list displays the first column of each row in the model. What I want it to do is show the header of each row instead (so the list says "frame 1, frame 2, etc"). Is there a way to do this? A: Two possible solutions: Try to use a proxy model (a subclass of QAbstractProxyModel) which accesses row headers as columns in a single row. Not trivial because the proxy model displays as data what the original model considers to be header. Display a second 2D view of your model, but hide everything except for the column headers. Since your frames are rows, you'll need a proxy model to transpose between rows and columns. DISCLAIMER: I did not actually implement any of the solutions.
Table and List view with single Model in Qt
I have a 2D model where each row represents a frame in a video, and each column represents an object. The object can have different states on each frame, and this is stored in the model. Then I have a QTableView that shows this data. The model has header data, so each row has a header like "frame k" and each column has a header like "object n". This table is editable. But I want the user to edit it another way. The other way is a graphics view that shows a single frame. Below the graphics view is a list (oriented horizontally) that represents each frame. This way the user can click on a frame in the list and the graphics view now displays that frame. The problem is that the list displays the first column of each row in the model. What I want it to do is show the header of each row instead (so the list says "frame 1, frame 2, etc"). Is there a way to do this?
[ "Two possible solutions:\n\nTry to use a proxy model (a subclass of QAbstractProxyModel) which accesses row headers as columns in a single row. Not trivial because the proxy model displays as data what the original model considers to be header.\nDisplay a second 2D view of your model, but hide everything except for the column headers. Since your frames are rows, you'll need a proxy model to transpose between rows and columns.\n\nDISCLAIMER: I did not actually implement any of the solutions.\n" ]
[ 1 ]
[]
[]
[ "model", "qt", "view" ]
stackoverflow_0000102789_model_qt_view.txt
Q: Decoding printf statements in C (Printf Primer) I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to QString variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little 'printf primer' for Stackoverflow. In the code, I came across this little gem, printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g); How will the variables a, b, c, d, e, f, g be formatted? A: Danny is mostly right. a. unsigned decimal, minimum 4 characters, space padded b. floating point, minimum 16 digits before the decimal (0 padded), 1 digit after the decimal c. hex, minimum 4 characters, 0 padded, letters are printed in upper case d. same as above, but minimum 2 characters e. e is assumed to be an int, converted to an unsigned char and printed f. same as e g. This is likely a typo, the 4 has no effect. If it were "%.4s", then a maximum of 4 characters from the string would be printed. It is interesting to note that in this case, the string does not need to be null terminated. Edit: jj33 points out 2 errors in b and g above here. A: @Jason Day, I think the 4 in the last %4s is significant if there are fewer than 4 characters. If there are more than 4 you are right, %4s and %s would be the same, but with fewer than 4 chars in g %s would be left justified and %4s would be right-justified in a 4 char field. b is actually minimum 16 chars for the whole field, including the decimal and the single digit after the decimal I think (16 total chars vs 18 total chars) A: Here's my printf primer: http://www.pixelbeat.org/programming/gcc/format_specs.html I always compile with -Wall with gcc which will warn about any mismatches between the supplied printf formats and variables. A: @jj33, you're absolutely right, on both counts. #include <stdio.h> int main(int argc, char *argv[]) { char *s = "Hello, World"; char *s2 = "he"; printf("4s: '%4s'\n", s); printf(".4s: '%.4s'\n", s); printf("4s2: '%4s'\n", s2); printf(".4s2: '%.4s'\n", s2); return 0; } $ gcc -o foo foo.c $ ./foo 4s: 'Hello, World' .4s: 'Hell' 4s2: ' he' .4s2: 'he' Good catch! A: a. decimal, four significant digits b. Not sure c. hex, minimum 4 characters d. Also hex, minimum 2 characters e. 1 character f. String of characters, minimum 4 A: What you really need is a tool which takes the format strings in printf() statements and converts them into equivalent QString based function calls. Does anyone want to spend his Free Software Donation Time on developing such a tool? Placeholder for URL to a Free Software hosting service holding the source code of such a tool
Decoding printf statements in C (Printf Primer)
I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to QString variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little 'printf primer' for Stackoverflow. In the code, I came across this little gem, printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g); How will the variables a, b, c, d, e, f, g be formatted?
[ "Danny is mostly right.\na. unsigned decimal, minimum 4 characters, space padded\nb. floating point, minimum 16 digits before the decimal (0 padded), 1 digit after the decimal\nc. hex, minimum 4 characters, 0 padded, letters are printed in upper case\nd. same as above, but minimum 2 characters\ne. e is assumed to be an int, converted to an unsigned char and printed\nf. same as e\ng. This is likely a typo, the 4 has no effect. If it were \"%.4s\", then a maximum of 4 characters from the string would be printed. It is interesting to note that in this case, the string does not need to be null terminated.\nEdit: jj33 points out 2 errors in b and g above here.\n", "@Jason Day, I think the 4 in the last %4s is significant if there are fewer than 4 characters. If there are more than 4 you are right, %4s and %s would be the same, but with fewer than 4 chars in g %s would be left justified and %4s would be right-justified in a 4 char field.\nb is actually minimum 16 chars for the whole field, including the decimal and the single digit after the decimal I think (16 total chars vs 18 total chars)\n", "Here's my printf primer:\nhttp://www.pixelbeat.org/programming/gcc/format_specs.html\nI always compile with -Wall with gcc which\nwill warn about any mismatches between the supplied\nprintf formats and variables.\n", "@jj33, you're absolutely right, on both counts.\n#include <stdio.h>\n\nint main(int argc, char *argv[]) {\n char *s = \"Hello, World\";\n char *s2 = \"he\";\n\n printf(\"4s: '%4s'\\n\", s);\n printf(\".4s: '%.4s'\\n\", s);\n printf(\"4s2: '%4s'\\n\", s2);\n printf(\".4s2: '%.4s'\\n\", s2);\n\n return 0;\n}\n\n$ gcc -o foo foo.c\n$ ./foo\n4s: 'Hello, World'\n.4s: 'Hell'\n4s2: ' he'\n.4s2: 'he'\n\nGood catch!\n", "a. decimal, four significant digits \nb. Not sure\nc. hex, minimum 4 characters \nd. Also hex, minimum 2 characters \ne. 1 character \nf. String of characters, minimum 4\n", "What you really need is a tool which takes the format strings in printf() statements and converts them into equivalent QString based function calls.\nDoes anyone want to spend his Free Software Donation Time on developing such a tool?\nPlaceholder for URL to a Free Software hosting service holding the source code of such a tool\n" ]
[ 5, 5, 4, 3, 0, 0 ]
[]
[]
[ "c", "printf", "qstring", "qt" ]
stackoverflow_0000007981_c_printf_qstring_qt.txt
Q: Is there a .NET OS abstraction layer to make OS calls work cross-platform? I really want to write .NET apps that run on any platform (PC, Linux and Mac). I am not really concerned about UI capabilities because these are mostly background services. I have heard of MONO and that it allows you to write .NET apps that run on Mac and Linux, but I want to be able to write a single app that when compiled for Windows will run as a Service, and when compiled for Linux will run as whatever the UNIX equivalent is. I also would like to be able to store things in the registry and have that work. Is there any way to write truly OS agnostic code like this? ...and DON'T say I should make it run on the web! :) A: Yes, Mono has the windows service stuff ported to Linux, but you are going to have to think of a better way to store configuration settings than Registry... Using XML files for instance would be cross platform. You should also check out mono's wiki on how to develop portable applications here. A: Short answer: no. You could create an application which will run on both Windows and Linux. But there are platform-specific features and right now Mono could not automatically 'translate' those for you. A Windows Service is a good example of that.
Is there a .NET OS abstraction layer to make OS calls work cross-platform?
I really want to write .NET apps that run on any platform (PC, Linux and Mac). I am not really concerned about UI capabilities because these are mostly background services. I have heard of MONO and that it allows you to write .NET apps that run on Mac and Linux, but I want to be able to write a single app that when compiled for Windows will run as a Service, and when compiled for Linux will run as whatever the UNIX equivalent is. I also would like to be able to store things in the registry and have that work. Is there any way to write truly OS agnostic code like this? ...and DON'T say I should make it run on the web! :)
[ "Yes, Mono has the windows service stuff ported to Linux, but you are going to have to think of a better way to store configuration settings than Registry... Using XML files for instance would be cross platform.\nYou should also check out mono's wiki on how to develop portable applications here.\n", "Short answer: no.\nYou could create an application which will run on both Windows and Linux.\nBut there are platform-specific features and right now Mono could not automatically 'translate' those for you. A Windows Service is a good example of that.\n" ]
[ 8, 1 ]
[]
[]
[ ".net", "abstraction", "cross_platform", "mono", "operating_system" ]
stackoverflow_0000109070_.net_abstraction_cross_platform_mono_operating_system.txt
Q: Sharepoint calculated field's formula for created by i have a sharepoint list with 2 users for examole (user A and user B) i need a calculated field in the list items such that if user "A" created the item the field vaule will be "X" and if user "B" created the item fields value would be "Y" but i couldnt use [created by] in the furmiula of the calculated field !! why is that ?!! and is there another way to do what i need to do ?! A: If using Sharepoint Designer is an option you can create a workflow for that list. Set it to start when a new item is created -or- edited, use a condition of "If Created_By equals ..." and an action of "Set yourfield to yourvalue", then add an Else If branch and repeat. This will always override anything a user enters in "yourfield". Takes about 2 minutes to do all of this. A: I believe you can create a text field that has the default value set to [Me] which should then be usable in a calculated field. A: For more complicated formulae (i.e. anything with conditional logic), try creating an event handler for the content type (or doc library). This will allow you full control to set the fields to what you desire. The field can be hidden from the user inside the edit screens. Make sure use the STSDev from codeplex to setup the solution for deployment.
Sharepoint calculated field's formula for created by
i have a sharepoint list with 2 users for examole (user A and user B) i need a calculated field in the list items such that if user "A" created the item the field vaule will be "X" and if user "B" created the item fields value would be "Y" but i couldnt use [created by] in the furmiula of the calculated field !! why is that ?!! and is there another way to do what i need to do ?!
[ "If using Sharepoint Designer is an option you can create a workflow for that list. Set it to start when a new item is created -or- edited, use a condition of \"If Created_By equals ...\" and an action of \"Set yourfield to yourvalue\", then add an Else If branch and repeat. This will always override anything a user enters in \"yourfield\". Takes about 2 minutes to do all of this.\n", "I believe you can create a text field that has the default value set to [Me] which should then be usable in a calculated field.\n", "For more complicated formulae (i.e. anything with conditional logic), try creating an event handler for the content type (or doc library). This will allow you full control to set the fields to what you desire.\nThe field can be hidden from the user inside the edit screens.\nMake sure use the STSDev from codeplex to setup the solution for deployment.\n" ]
[ 6, 0, 0 ]
[]
[]
[ "formula", "list", "sharepoint" ]
stackoverflow_0000108521_formula_list_sharepoint.txt
Q: ASP.NET MVC: Making routes/URLs IIS6 and IIS7-friendly I have an ASP.NET MVC-application which I want deployable on both IIS6 and IIS7 and as we all know, IIS6 needs the ".mvc"-naming in the URL. Will this code work to make sure it works on all IIS-versions? Without having to make special adjustments in code, global.asax or config-files for the different IIS-versions. bool usingIntegratedPipeline = HttpRuntime.UsingIntegratedPipeline; routes.MapRoute( "Default", usingIntegratedPipeline ? "{controller}/{action}/{id}" : "{controller}.mvc/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); Update: Forgot to mention. No ISAPI. Hosted website, no control over the IIS-server. A: That should fix the .mvc problem since the integrated pipeline is IIS7 strictly. But remember to change settings on the IIS7 website to use "2.0 Integrated Pipeline" otherwhise it will return false aswell. Also ofcouse setup the mapping of .mvc to the asp.net isapi dll, but Im guessing that you already know this. Some small suggestions on other things you might need to remember when deploying MVC applications on IIS6 that I found useful: http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx A: You can use an ISAPI filter to rewrite URLs which will allow you to have the nice URLs while still on IIS 6. Look, for example, here
ASP.NET MVC: Making routes/URLs IIS6 and IIS7-friendly
I have an ASP.NET MVC-application which I want deployable on both IIS6 and IIS7 and as we all know, IIS6 needs the ".mvc"-naming in the URL. Will this code work to make sure it works on all IIS-versions? Without having to make special adjustments in code, global.asax or config-files for the different IIS-versions. bool usingIntegratedPipeline = HttpRuntime.UsingIntegratedPipeline; routes.MapRoute( "Default", usingIntegratedPipeline ? "{controller}/{action}/{id}" : "{controller}.mvc/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); Update: Forgot to mention. No ISAPI. Hosted website, no control over the IIS-server.
[ "That should fix the .mvc problem since the integrated pipeline is IIS7 strictly.\nBut remember to change settings on the IIS7 website to use \"2.0 Integrated Pipeline\" otherwhise it will return false aswell.\nAlso ofcouse setup the mapping of .mvc to the asp.net isapi dll, but Im guessing that you already know this.\nSome small suggestions on other things you might need to remember when deploying MVC applications on IIS6 that I found useful:\nhttp://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx\n", "You can use an ISAPI filter to rewrite URLs which will allow you to have the nice URLs while still on IIS 6. \nLook, for example, here\n" ]
[ 3, 0 ]
[]
[]
[ ".net", "asp.net_mvc", "iis", "url", "url_routing" ]
stackoverflow_0000109044_.net_asp.net_mvc_iis_url_url_routing.txt
Q: Create Web Client Solution dialog closes on click or tab out of default field without messages I installed Web Client Software Factory February 2008 release on Visual Studio Team System 2008 Development Edition (without SP1). When I first installed that, I tried out the software factory as I've never used one before and it worked fine. That was two months ago. Recently I needed to learn how to use the software factory and when I tried to create a WCSF solution, I get a problem. The WCSF shows up as a Visual Studio installed template under the Guidance Package project type. There are four templates (which I believe is as it should be) which are: Web Client Solution (C#, Web Site) Web Client Solution (C#, WAP) Web Client Solution (Visual Basic, Web Site) Web Client Solution (Visual Basic, WAP) Once I select any of them and proceed to create the solution, Visual Studio displays the 'Create Web Client Solution' dialog. Here's the weird part. As long as I click on any clickable control e.g. TextBox, Button or I press the 'Tab' key on the keyboard to change the cursor's location, the dialog just closes, no solution is created and the status bar will display "Creating project 'C:\MyWebApp' ... project creation failed." If I click on any other part of the dialog, nothing happens. I've tried uninstalling everything (including Visual Studio) and reinstall and it still won't work. I tried using Microsoft's 'Windows Install Clean Up' tool to ensure any potential corrupt MSI entries are removed before reinstalling. Nothing works. Hopefully someone else has faced this before and found an answer. Cheers. ~ hg A: I believe this might be a VS related authorization problem not a particular WCFS problem. Try this fix: http://developerspoint.wordpress.com/2008/06/25/how-to-deal-with-project-creation-failed-problem-of-visual-studio-2008/
Create Web Client Solution dialog closes on click or tab out of default field without messages
I installed Web Client Software Factory February 2008 release on Visual Studio Team System 2008 Development Edition (without SP1). When I first installed that, I tried out the software factory as I've never used one before and it worked fine. That was two months ago. Recently I needed to learn how to use the software factory and when I tried to create a WCSF solution, I get a problem. The WCSF shows up as a Visual Studio installed template under the Guidance Package project type. There are four templates (which I believe is as it should be) which are: Web Client Solution (C#, Web Site) Web Client Solution (C#, WAP) Web Client Solution (Visual Basic, Web Site) Web Client Solution (Visual Basic, WAP) Once I select any of them and proceed to create the solution, Visual Studio displays the 'Create Web Client Solution' dialog. Here's the weird part. As long as I click on any clickable control e.g. TextBox, Button or I press the 'Tab' key on the keyboard to change the cursor's location, the dialog just closes, no solution is created and the status bar will display "Creating project 'C:\MyWebApp' ... project creation failed." If I click on any other part of the dialog, nothing happens. I've tried uninstalling everything (including Visual Studio) and reinstall and it still won't work. I tried using Microsoft's 'Windows Install Clean Up' tool to ensure any potential corrupt MSI entries are removed before reinstalling. Nothing works. Hopefully someone else has faced this before and found an answer. Cheers. ~ hg
[ "I believe this might be a VS related authorization problem not a particular WCFS problem.\nTry this fix:\nhttp://developerspoint.wordpress.com/2008/06/25/how-to-deal-with-project-creation-failed-problem-of-visual-studio-2008/\n" ]
[ 1 ]
[]
[]
[ ".net", "visual_studio_2008" ]
stackoverflow_0000090586_.net_visual_studio_2008.txt
Q: Dynamically created operators I created a program using dev-cpp and wxwidgets which solves a puzzle. The user must fill the operations blocks and the results blocks, and the program will solve it. I'm solving it using brute force, I generate all non-repeated 9 length number combinations using a recursive algorithm. It does it pretty fast. Up to here all is great! But the problem is when my program operates depending the character on the blocks. Its extremely slow (it never gets the answer), because of the chars comparation against +, -, *, etc. I'm doing a CASE. Is there some way or some programming language which allows dynamic creation of operators? So I can define the operator ROW1COL2 to be a +, and the same way to all other operations. I leave a screenshot of the app, so its easier to understand how the puzzle works. http://www.imageshare.web.id/images/9gg5cev8vyokp8rhlot9.png PD: The algorithm works, I tried it with a trivial puzzle, and solved it in a second. A: Not sure that this is really what you're looking for but.. Any Object Oriented language such as C++ or C# will allow you to create an "Operator" base class and then to derive from this base class a "PlusOperator" or "MinusOperator" etc'. this is the standard way to avoid such case statements. However I am not sure this will solve your performance problem. Using plain brute force for such a problem will result you in an exponential solution. this will seem to work fast for small input - say completing all the numbers. But if you want to complete the operations its a much larger problem with alot more possibilities. So its likely that even without the CASE your program is not going to be able to solve it. The right way to try to solve this kind of problems is using some advanced search methods which use some Heuristic function. See the A* (A-star) algorithm for example. Good luck! A: You can represent the numbers and operators as objects, so the parsing is done only once in the beginning of the solving.
Dynamically created operators
I created a program using dev-cpp and wxwidgets which solves a puzzle. The user must fill the operations blocks and the results blocks, and the program will solve it. I'm solving it using brute force, I generate all non-repeated 9 length number combinations using a recursive algorithm. It does it pretty fast. Up to here all is great! But the problem is when my program operates depending the character on the blocks. Its extremely slow (it never gets the answer), because of the chars comparation against +, -, *, etc. I'm doing a CASE. Is there some way or some programming language which allows dynamic creation of operators? So I can define the operator ROW1COL2 to be a +, and the same way to all other operations. I leave a screenshot of the app, so its easier to understand how the puzzle works. http://www.imageshare.web.id/images/9gg5cev8vyokp8rhlot9.png PD: The algorithm works, I tried it with a trivial puzzle, and solved it in a second.
[ "Not sure that this is really what you're looking for but..\nAny Object Oriented language such as C++ or C# will allow you to create an \"Operator\" base class and then to derive from this base class a \"PlusOperator\" or \"MinusOperator\" etc'. this is the standard way to avoid such case statements. \nHowever I am not sure this will solve your performance problem.\nUsing plain brute force for such a problem will result you in an exponential solution. this will seem to work fast for small input - say completing all the numbers. But if you want to complete the operations its a much larger problem with alot more possibilities.\nSo its likely that even without the CASE your program is not going to be able to solve it.\nThe right way to try to solve this kind of problems is using some advanced search methods which use some Heuristic function. See the A* (A-star) algorithm for example.\nGood luck!\n", "You can represent the numbers and operators as objects, so the parsing is done only once in the beginning of the solving.\n" ]
[ 1, 0 ]
[]
[]
[ "c++", "dynamic", "operators", "wxwidgets" ]
stackoverflow_0000109129_c++_dynamic_operators_wxwidgets.txt
Q: Best javascript framework for drawing/showing images? What's the best javascript framework for drawing (lines, curves whatnot) on images? A: jQuery has several plugins available for doing graphics. Raphael is a plugin that uses SVG (for Firefox and other browsers that support SVG), and VML for the IE products. In addition, jQuery provides a great architecture for javascript projects with plenty of support and plug-ins. Raphael is available here: http://raphaeljs.com/index.html jQuery is available here: http://jquery.com/ A: Processing var p = Processing(CanvasElement); p.size(100, 100); p.background(0); p.fill(255); p.ellipse(50, 50, 50, 50); A: Take a look at this library that is a jquery plugin: http://www.openstudio.fr/Library-for-simple-drawing-with.html A: Refer to this question. A: You can create "images" using javascript's flot library. It's on google code: flot And requires jQuery Here's an example, how a graph might look like
Best javascript framework for drawing/showing images?
What's the best javascript framework for drawing (lines, curves whatnot) on images?
[ "jQuery has several plugins available for doing graphics. Raphael is a plugin that uses SVG (for Firefox and other browsers that support SVG), and VML for the IE products. In addition, jQuery provides a great architecture for javascript projects with plenty of support and plug-ins.\nRaphael is available here: http://raphaeljs.com/index.html\njQuery is available here: http://jquery.com/\n", "Processing\nvar p = Processing(CanvasElement);\np.size(100, 100);\np.background(0);\np.fill(255);\np.ellipse(50, 50, 50, 50);\n\n", "Take a look at this library that is a jquery plugin:\nhttp://www.openstudio.fr/Library-for-simple-drawing-with.html\n", "Refer to this question.\n", "You can create \"images\" using javascript's flot library.\nIt's on google code: flot\nAnd requires jQuery\nHere's an example, how a graph might look like\n" ]
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "javascript", "toolkit" ]
stackoverflow_0000109149_javascript_toolkit.txt
Q: PHP GD, imagecreatefromstring( ); how to get the image dimensions? Normally I use imagecreatefromjpeg() and then getimagesize(), but with Firefox 3 I need to go round this different. So now im using imagecreatefromstring(), but how do I retreive the image dimensions now? A: imagesx() and imagesy() functions seem to work with images made with imagecreatefromstring(), too. A: ah yes! i just found the answer on the internet a second ago :) for those who still interested : $image = imagecreatefromstring($img_str); $w = imagesx($image); $h = imagesy($image);
PHP GD, imagecreatefromstring( ); how to get the image dimensions?
Normally I use imagecreatefromjpeg() and then getimagesize(), but with Firefox 3 I need to go round this different. So now im using imagecreatefromstring(), but how do I retreive the image dimensions now?
[ "imagesx() and imagesy() functions seem to work with images made with imagecreatefromstring(), too.\n", "ah yes! i just found the answer on the internet a second ago :)\nfor those who still interested :\n$image = imagecreatefromstring($img_str);\n$w = imagesx($image);\n$h = imagesy($image);\n\n" ]
[ 19, 7 ]
[]
[]
[ "gd", "image", "php", "upload" ]
stackoverflow_0000109210_gd_image_php_upload.txt
Q: WinForms context menu - not open in certain parts / detect underlying control I have a .NET 2.0 Windows Forms application. On this app there is a Form control with a Menu bar and a status bar. Also there's a ListView on this form. If I add a context menu to this form, the context menu will open when the user right clicks any part of the form, including the menu bar and the status bar. How can I prevent the context menu from opening when the click happened on the menu bar / status bar? I want it to open only when clicking the "gray area" of the form. If the click happened above a control on this form (for example, on the ListView), how can I identify this? I'd like to know if the user right clicked above the gray area or above the ListView, so I can enable/disable some menu items based on this. A: After you've placed your Statusbar at the bottom and MenuStrip at the top, Set ContextMenuStrip on your form to None Place a standard Panel in the middle (between MenuStrip and StatusStrip) with the Dock property set to Fill. Set the ContextMenuStrip property on your Panel (instead of on the form). And place the ListView and all other controls that should go into the form in the Panel Eg ~~~~~~~~~~~~~ menustrip ~~~~~~~~~~~~~ Panel. Dock=Fill. ContextMenuStrip=yourContextMenu. ~~~~~~~~~~~~~ StatusStrip ~~~~~~~~~~~~~ A: I found the answer: Point clientPos = this.PointToClient(Form.MousePosition); Control control = this.GetChildAtPoint(clientPos); This should give the underlying control that was clicked on the Form, or null if the click was on the gray area. So we just need to test for the type of the control on the Opening event of the context menu. If it's MenuStrip, ToolStrip or StatusStrip, do e.Cancel = true;.
WinForms context menu - not open in certain parts / detect underlying control
I have a .NET 2.0 Windows Forms application. On this app there is a Form control with a Menu bar and a status bar. Also there's a ListView on this form. If I add a context menu to this form, the context menu will open when the user right clicks any part of the form, including the menu bar and the status bar. How can I prevent the context menu from opening when the click happened on the menu bar / status bar? I want it to open only when clicking the "gray area" of the form. If the click happened above a control on this form (for example, on the ListView), how can I identify this? I'd like to know if the user right clicked above the gray area or above the ListView, so I can enable/disable some menu items based on this.
[ "After you've placed your Statusbar at the bottom and MenuStrip at the top, \n\nSet ContextMenuStrip on your form to None \nPlace a standard Panel in the middle (between MenuStrip and StatusStrip) with the Dock property set to Fill. \nSet the ContextMenuStrip property on your Panel (instead of on the form).\n\nAnd place the ListView and all other controls that should go into the form in the Panel\nEg\n~~~~~~~~~~~~~\nmenustrip\n~~~~~~~~~~~~~\nPanel. Dock=Fill. ContextMenuStrip=yourContextMenu.\n~~~~~~~~~~~~~\nStatusStrip\n~~~~~~~~~~~~~\n", "I found the answer:\nPoint clientPos = this.PointToClient(Form.MousePosition);\nControl control = this.GetChildAtPoint(clientPos);\n\nThis should give the underlying control that was clicked on the Form, or null if the click was on the gray area. So we just need to test for the type of the control on the Opening event of the context menu. If it's MenuStrip, ToolStrip or StatusStrip, do e.Cancel = true;.\n" ]
[ 3, 1 ]
[]
[]
[ ".net", "c#", "contextmenu", "winforms" ]
stackoverflow_0000109262_.net_c#_contextmenu_winforms.txt
Q: Why Does Ruby Only Permit Certain Operator Overloading In Ruby, like in many other OO programming languages, operators are overloadable. However, only certain character operators can be overloaded. This list may be incomplete but, here are some of the operators that cannot be overloaded: !, not, &&, and, ||, or A: "The && and || operators are not overloadable, mainly because they provide "short circuit" evaluation that cannot be reproduced with pure method calls." -- Jim Weirich A: Methods are overloadable, those are part of the language syntax. A: Yep. Operators are not overloadable. Only methods. Some operators are not really. They're sugar for methods. So 5 + 5 is really 5.+(5), and foo[bar] = baz is really foo.[]=(bar, baz). A: In Ruby 1.9, the ! operator is actually also a method and can be overriden. This only leaves && and || and their low-precedence counterparts and and or. There's also some other "combined operators" that cannot be overriden, e.g. a != b is actually !(a == b) and a += b is actually a = a+b. A: And let's not forget about << for example: string = "test" string << "ing" is the same as calling: string.<<("ing")
Why Does Ruby Only Permit Certain Operator Overloading
In Ruby, like in many other OO programming languages, operators are overloadable. However, only certain character operators can be overloaded. This list may be incomplete but, here are some of the operators that cannot be overloaded: !, not, &&, and, ||, or
[ "\"The && and || operators are not overloadable, mainly because they provide \"short circuit\" evaluation that cannot be reproduced with pure method calls.\"\n-- Jim Weirich\n", "Methods are overloadable, those are part of the language syntax.\n", "Yep. Operators are not overloadable. Only methods.\nSome operators are not really. They're sugar for methods. So 5 + 5 is really 5.+(5), and foo[bar] = baz is really foo.[]=(bar, baz).\n", "In Ruby 1.9, the ! operator is actually also a method and can be overriden. This only leaves && and || and their low-precedence counterparts and and or.\nThere's also some other \"combined operators\" that cannot be overriden, e.g. a != b is actually !(a == b) and a += b is actually a = a+b.\n", "And let's not forget about << for example:\nstring = \"test\"\nstring << \"ing\"\n\nis the same as calling:\nstring.<<(\"ing\")\n\n" ]
[ 25, 12, 12, 6, 1 ]
[]
[]
[ "methods", "operator_overloading", "operators", "ruby" ]
stackoverflow_0000092862_methods_operator_overloading_operators_ruby.txt
Q: DatagridView virtual model with comboboxColumn is it possible to have different items in different rows within a comboboxcolumn in a datagridview. This would be using virtual mode. Code samples would be great. A: I think what you're looking for is here. The technique involves handling the EditingControlShowing event of the DataGridView control and updating the datasource for the DataGridViewComboBoxEditingControl (presumably based on the values in the other columns in that row). Edit: here's some code that shows the main points //Some types we'll need enum Jobs { Programmer, Salesman } enum DrinkCode { Coffee, Coke, MountainDew, GinAndTonic } internal class Drink { public DrinkCode Code { get; set; } public string Name { get; set; } public bool Caffeinated { get; set; } public bool Alcoholic { get; set; } } internal class Person { public string Name { get; set; } public Jobs Job { get; set; } public DrinkCode Drink { get; set; } } // the form class public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = FindPersons(); this.dataGridView1.DataSource = bindingSource; DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn() { column.DataPropertyName = "Drink"; column.HeaderText = "beverage"; column.DisplayMember = "Name"; column.ValueMember = "Code"; column.DataSource = BuildDrinksList(); } dataGridView1.Columns.Add(column); //handling this event is the nub of the solution dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing); } void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { //When the focus goes into the combo box cell, we can update the contents of the dropdown // DataGridViewComboBoxEditingControl comboBox = e.Control as DataGridViewComboBoxEditingControl; //if you have more than one drop down this is not going to be good enough, but hey, it's an example! if (comboBox != null) { BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource; Person person = bindingSource.Current as Person; BindingList<Drink> bindingList = t his.BuildDrinksList(person); comboBox.DataSource = bindingList; } } //the rest of this is just data to make the example work private BindingList<Drink> BuildDrinksList() { var drinks = new BindingList<Drink>(); drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.Coffee, Name = "Coffee" }); drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.Coke, Name = "Coke" }); drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.MountainDew, Name = "Mountain Dew" }); drinks.Add(new Drink() { Alcoholic = true, Caffeinated = false, Code = DrinkCode.GinAndTonic, Name = "Gin and Tonic" }); return drinks; } private BindingList<Drink> BuildDrinksList(Person p) { var drinks = new BindingList<Drink>(); if (p.Job == Jobs.Programmer) { drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.Coffee, Name = "Coffee" }); drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.Coke, Name = "Coke" }); drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.MountainDew, Name = "Mountain Dew" }); } if (p.Job == Jobs.Salesman) { drinks.Add(new Drink() { Alcoholic = true, Caffeinated = false, Code = DrinkCode.GinAndTonic, Name = "Gin and Tonic" }); } return drinks; } private BindingList<Person> FindPersons() { BindingList<Person> bindingList = new BindingList<Person>(); bindingList.Add(new Person() { Job = Jobs.Programmer, Drink = DrinkCode.Coffee, Name = "steve" }); bindingList.Add(new Person() { Job = Jobs.Salesman, Drink = DrinkCode.GinAndTonic, Name = "john" }); return bindingList; } }
DatagridView virtual model with comboboxColumn
is it possible to have different items in different rows within a comboboxcolumn in a datagridview. This would be using virtual mode. Code samples would be great.
[ "I think what you're looking for is here.\nThe technique involves handling the EditingControlShowing event of the DataGridView control and updating the datasource for the DataGridViewComboBoxEditingControl (presumably based on the values in the other columns in that row).\nEdit: here's some code that shows the main points\n//Some types we'll need\nenum Jobs\n{\n Programmer,\n Salesman\n}\n\nenum DrinkCode\n{\n Coffee,\n Coke,\n MountainDew,\n GinAndTonic\n}\n\ninternal class Drink\n{\n public DrinkCode Code { get; set; }\n public string Name { get; set; }\n public bool Caffeinated { get; set; }\n public bool Alcoholic { get; set; }\n}\n\ninternal class Person\n{\n public string Name { get; set; }\n\n public Jobs Job { get; set; }\n\n public DrinkCode Drink { get; set; }\n}\n\n// the form class\npublic partial class Form1 : Form\n{\n\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n BindingSource bindingSource = new BindingSource();\n bindingSource.DataSource = FindPersons();\n this.dataGridView1.DataSource = bindingSource;\n\n DataGridViewComboBoxColumn column =\n new DataGridViewComboBoxColumn()\n {\n column.DataPropertyName = \"Drink\";\n column.HeaderText = \"beverage\";\n column.DisplayMember = \"Name\";\n column.ValueMember = \"Code\";\n column.DataSource = BuildDrinksList();\n }\n\n dataGridView1.Columns.Add(column);\n //handling this event is the nub of the solution\n dataGridView1.EditingControlShowing += \n new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);\n }\n\n\n void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n {\n //When the focus goes into the combo box cell, we can update the contents of the dropdown\n // \n DataGridViewComboBoxEditingControl comboBox = e.Control as DataGridViewComboBoxEditingControl;\n //if you have more than one drop down this is not going to be good enough, but hey, it's an example!\n if (comboBox != null)\n {\n BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource;\n Person person = bindingSource.Current as Person;\n BindingList<Drink> bindingList = t his.BuildDrinksList(person);\n comboBox.DataSource = bindingList;\n\n }\n }\n\n //the rest of this is just data to make the example work\n private BindingList<Drink> BuildDrinksList()\n {\n var drinks = new BindingList<Drink>();\n\n drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.Coffee, Name = \"Coffee\" });\n drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.Coke, Name = \"Coke\" });\n drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.MountainDew, Name = \"Mountain Dew\" });\n drinks.Add(new Drink() { Alcoholic = true, Caffeinated = false, Code = DrinkCode.GinAndTonic, Name = \"Gin and Tonic\" });\n\n return drinks;\n }\n\n private BindingList<Drink> BuildDrinksList(Person p)\n {\n var drinks = new BindingList<Drink>();\n\n if (p.Job == Jobs.Programmer)\n {\n drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.Coffee, Name = \"Coffee\" });\n drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.Coke, Name = \"Coke\" });\n drinks.Add(new Drink() { Alcoholic = false, Caffeinated = true, Code = DrinkCode.MountainDew, Name = \"Mountain Dew\" });\n }\n if (p.Job == Jobs.Salesman)\n {\n drinks.Add(new Drink() { Alcoholic = true, Caffeinated = false, Code = DrinkCode.GinAndTonic, Name = \"Gin and Tonic\" });\n }\n return drinks;\n }\n\n private BindingList<Person> FindPersons()\n {\n BindingList<Person> bindingList = new BindingList<Person>();\n bindingList.Add(new Person() { Job = Jobs.Programmer, Drink = DrinkCode.Coffee, Name = \"steve\" });\n bindingList.Add(new Person() { Job = Jobs.Salesman, Drink = DrinkCode.GinAndTonic, Name = \"john\" });\n return bindingList;\n }\n}\n\n" ]
[ 5 ]
[]
[]
[ ".net", "c#", "datagridview", "winforms" ]
stackoverflow_0000108777_.net_c#_datagridview_winforms.txt
Q: How can I use perldoc to lookup the %ENV variable? I find from reading perldoc perlvar, about a thousand lines in is help for %ENV. Is there a way to find that from the command line directly? On my Windows machine, I've tried the following perldoc ENV perldoc %ENV perldoc %%ENV perldoc -r ENV (returns info about Use Env) perldoc -r %ENV perldoc -r %%%ENV perldoc -r %%%%ENV (says No documentation found for "%ENV") None actually return information about the %ENV variable. How do I use perldoc to find out about %ENV, if I don't want to have to eye-grep through thousands of line? I've tried the suggested "perldoc perlvar" and then typing /%ENV, but nothing happens. perl -v: This is perl, v5.8.0 built for MSWin32-x86-multi-thread Though I've asked about %ENV, this also applies to any general term, so knowing that %ENV is in perlvar for this one example won't help me next time when I don't know which section. Is there a way to get perldoc to dump everything (ugh) and I can grep the output? A: Check out the latest development version of Pod::Perldoc. I submitted a patch which lets you do this: $ perldoc -v '%ENV' %ENV $ENV{expr} The hash %ENV contains your current environment. Setting a value in "ENV" changes the environment for any child processes you subsequently fork() off. A: perldoc doesn't have an option to search for a particular entry in perlvar (like -f does for perlfunc). General searching is dependent on your pager (specified in the PAGER environment variable). Personally, I like "less." You can get less for windows from the GnuWin32 project. A: The searching for %ENV is a feature of the pager named 'less', not of perldoc. So if perldoc uses a different pager, this might not work. Activestate Perl comes with HTML documentation, you can open perlvar in your browser, hit Ctrl+f and type %ENV, then hit enter. A: I use Apache::Perldoc (old, but still does its job) on my local machine to browse the local documentation. If I have net access though, I just look at perldoc.perl.org and search. However, in this case, search isn't useful for the variables and it's better to use the Special variables link at the left of the page. As you get more experience with Perl, you'll know where to look for the documentation. For know, you might have to refer to perltoc, but after awhile you'll know to look for functions in perlfunc, variables in perlvar, and so on. You might also use my Perl documentation documentation. A: Install unixutils for Windows Call: perldoc perlvar | grep -A10 %env A: firefox http://perldoc.perl.org/perlvar.html#%ENV By the way, many many many bugs have been fixed since 5.8.0.
How can I use perldoc to lookup the %ENV variable?
I find from reading perldoc perlvar, about a thousand lines in is help for %ENV. Is there a way to find that from the command line directly? On my Windows machine, I've tried the following perldoc ENV perldoc %ENV perldoc %%ENV perldoc -r ENV (returns info about Use Env) perldoc -r %ENV perldoc -r %%%ENV perldoc -r %%%%ENV (says No documentation found for "%ENV") None actually return information about the %ENV variable. How do I use perldoc to find out about %ENV, if I don't want to have to eye-grep through thousands of line? I've tried the suggested "perldoc perlvar" and then typing /%ENV, but nothing happens. perl -v: This is perl, v5.8.0 built for MSWin32-x86-multi-thread Though I've asked about %ENV, this also applies to any general term, so knowing that %ENV is in perlvar for this one example won't help me next time when I don't know which section. Is there a way to get perldoc to dump everything (ugh) and I can grep the output?
[ "Check out the latest development version of Pod::Perldoc. I submitted a patch which lets you do this:\n$ perldoc -v '%ENV'\n\n%ENV\n$ENV{expr}\nThe hash %ENV contains your current environment. Setting a value in\n\"ENV\" changes the environment for any child processes you subsequently\nfork() off.\n\n", "perldoc doesn't have an option to search for a particular entry in perlvar (like -f does for perlfunc). General searching is dependent on your pager (specified in the PAGER environment variable). Personally, I like \"less.\" You can get less for windows from the GnuWin32 project.\n", "The searching for %ENV is a feature of the pager named 'less', not of perldoc. So if perldoc uses a different pager, this might not work.\nActivestate Perl comes with HTML documentation, you can open perlvar in your browser, hit Ctrl+f and type %ENV, then hit enter.\n", "I use Apache::Perldoc (old, but still does its job) on my local machine to browse the local documentation. If I have net access though, I just look at perldoc.perl.org and search. However, in this case, search isn't useful for the variables and it's better to use the Special variables link at the left of the page.\nAs you get more experience with Perl, you'll know where to look for the documentation. For know, you might have to refer to perltoc, but after awhile you'll know to look for functions in perlfunc, variables in perlvar, and so on. \nYou might also use my Perl documentation documentation.\n", "\nInstall unixutils for Windows \nCall: \nperldoc perlvar | grep -A10 %env\n\n", "firefox http://perldoc.perl.org/perlvar.html#%ENV\n\nBy the way, many many many bugs have been fixed since 5.8.0.\n" ]
[ 20, 3, 2, 1, 0, 0 ]
[ "If you'd like to see the contents of your %ENV, you can use Data::Dumper to print it out in a rather readable format:\nperl -MData::Dumper -e 'print Dumper \\%ENV'\n" ]
[ -1 ]
[ "perl", "perldoc" ]
stackoverflow_0000084506_perl_perldoc.txt
Q: What does -> mean in F#? I've been trying to get into F# on and off for a while but I keep getting put off. Why? Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator ->. However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies. I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back. Can someone please, explain it or point to a truly accessible resource that explains it? A: '->' is not an operator. It appears in the F# syntax in a number of places, and its meaning depends on how it is used as part of a larger construct. Inside a type, '->' describes function types as people have described above. For example let f : int -> int = ... says that 'f' is a function that takes an int and returns an int. Inside a lambda ("thing that starts with 'fun' keyword"), '->' is syntax that separates the arguments from the body. For example fun x y -> x + y + 1 is an expression that defines a two argument function with the given implementation. Inside a "match" construct, '->' is syntax that separates patterns from the code that should run if the pattern is matched. For example, in match someList with | [] -> 0 | h::t -> 1 the stuff to the left of each '->' are patterns, and the stuff on the right is what happens if the pattern on the left was matched. The difficulty in understanding may be rooted in the faulty assumption that '->' is "an operator" with a single meaning. An analogy might be "." in C#, if you have never seen any code before, and try to analyze the "." operator based on looking at "obj.Method" and "3.14" and "System.Collections", you may get very confused, because the symbol has different meanings in different contexts. Once you know enough of the language to recognize these contexts, however, things become clear. A: It basically means "maps to". Read it that way or as "is transformed into" or something like that. So, from the F# in 20 minutes tutorial, > List.map (fun x -> x % 2 = 0) [1 .. 10];; val it : bool list = [false; true; false; true; false; true; false; true; false; true] The code (fun i -> i % 2 = 0) defines an anonymous function, called a lambda expression, that has a parameter x and the function returns the result of "x % 2 = 0", which is whether or not x is even. A: First question - are you familiar with lambda expressions in C#? If so the -> in F# is the same as the => in C# (I think you read it 'goes to'). The -> operator can also be found in the context of pattern matching match x with | 1 -> dosomething | _ -> dosomethingelse I'm not sure if this is also a lambda expression, or something else, but I guess the 'goes to' still holds. Maybe what you are really referring to is the F# parser's 'cryptic' responses: > let add a b = a + b val add: int -> int -> int This means (as most of the examples explain) that add is a 'val' that takes two ints and returns an int. To me this was totally opaque to start with. I mean, how do I know that add isn't a val that takes one int and returns two ints? Well, the thing is that in a sense, it does. If I give add just one int, I get back an (int -> int): > let inc = add 1 val inc: int -> int This (currying) is one of the things that makes F# so sexy, for me. For helpful info on F#, I have found that blogs are FAR more useful that any of the official 'documentation': Here are some names to check out Dustin Campbell (that's diditwith.net, cited in another answer) Don Symes ('the' man) Tomasp.net (aka Tomas Petricek) Andrew Kennedy (for units of measure) Fsharp.it (famous for the Project Euler solutions) http://lorgonblog.spaces.live.com/Blog (aka Brian) Jomo Fisher A: (a -> b) means "function from a to b". In type annotation, it denotes a function type. For example, f : (int -> String) means that f refers to a function that takes an integer and returns a string. It is also used as a contstructor of such values, as in val f : (int -> int) = fun n -> n * 2 which creates a value which is a function from some number n to that same number multiplied by two. A: From Microsoft: Function types are the types given to first-class function values and are written int -> int. They are similar to .NET delegate types, except they aren't given names. All F# function identifiers can be used as first-class function values, and anonymous function values can be created using the (fun ... -> ...) expression form. A: There are plenty of great answers here already, I just want to add to the conversation another way of thinking about it. ' -> ' means function. 'a -> 'b is a function that takes an 'a and returns a 'b ('a * 'b) -> ('c * 'd) is a function that takes a tuple of type ('a, 'b) and returns a tuple of ('c, 'd). Such as int/string returns float/char. Where it gets interesting is in the cascade case of 'a -> 'b -> 'c. This is a function that takes an 'a and returns a function ('b -> 'c), or a function that takes a 'b -> 'c. So if you write: let f x y z = () The type will be f : 'a -> 'b -> 'c -> unit, so if you only applied the first parameter, the result would be a curried function 'b -> 'c -> 'unit. A: In the context of defining a function, it is similar to => from the lambda expression in C# 3.0. F#: let f = fun x -> x*x C#: Func<int, int> f = x => x * x; The -> in F# is also used in pattern matching, where it means: if the expression matches the part between | and ->, then what comes after -> should be given back as the result: let isOne x = match x with | 1 -> true | _ -> false A: Many great answers to this questions, thanks people. I'd like to put here an editable answer that brings things together. For those familiar with C# understanding -> being the same as => lamba expression is a good first step. This usage is :- fun x y -> x + y + 1 Can be understood as the equivalent to:- (x, y) => x + y + 1; However its clear that -> has a more fundemental meaning which stems from concept that a function that takes two parameters such as the above can be reduced (is that the correct term?) to a series of functions only taking one parameter. Hence when the above is described in like this:- Int -> Int -> Int It really helped to know that -> is right associative hence the above can be considered:- Int -> (Int -> Int) Aha! We have a function that takes Int and returns (Int -> Int) (a curried function?). The explaination that -> can also appear as part of type definiton also helped. (Int -> Int) is the type of any of function which takes an Int and returns an Int. Also helpful is the -> appears in other syntax such as matching but there it doesn't have the same meaning? Is that correct? I'm not sure it is. I suspect it has the same meaning but I don't have the vocabulary to express that yet. Note the purpose of this answer is not to spawn further answers but to be collaboratively edited by you people to create a more definitive answer. Utlimately it would be good that all the uncertainies and fluf (such as this paragraph) be removed and better examples added. Lets try keep this answer as accessible to the uninitiated as possible. A: The nice thing about languages such as Haskell (it's very similar in F#, but I don't know the exact syntax -- this should help you understand ->, though) is that you can apply only parts of the argument, to create curried functions: adder n x y = n + x + y In other words: "give me three things, and I'll add them together". When you throw numbers at it, the compiler will infer the types of n x and y. Say you write adder 1 2 3 The type of 1, 2 and 3 is Int. Therefore: adder :: Int -> Int -> Int -> Int That is, give me three integers, and I will become an integer, eventually, or the same thing as saying: five :: Int five = 5 But, here's the nice part! Try this: add5 = adder 5 As you remember, adder takes an int, an int, an int, and gives you back an int. However, that is not the entire truth, as you'll see shortly. In fact, add5 will have this type: add5 :: Int -> Int -> Int It will be as if you have "peeled off" of the integers (the left-most), and glued it directly to the function. Looking closer at the function signature, we notice that the -> are right-associative, i.e.: addder :: Int -> (Int -> (Int -> Int)) This should make it quite clear: when you give adder the first integer, it'll evaluate to whatever's to the right of the first arrow, or: add5andtwomore :: Int -> (Int -> Int) add5andtwomore = adder 5 Now you can use add5andtwomore instead of "adder 5". This way, you can apply another integer to get (say) "add5and7andonemore": add5and7andonemore :: Int -> Int add5and7andonemore = adder 5 7 As you see, add5and7andonemore wants exactly another argument, and when you give it one, it will suddenly become an integer! > add5and7andonemore 9 => ((add5andtwomore) 7) 9 => ((adder 5) 7) 9) <=> adder 5 7 9 Substituting the parameters to adder (n x y) for (5 7 9), we get: > adder 5 7 9 = 5 + 7 + 9 => 5 + 7 + 9 => 21 In fact, plus is also just a function that takes an int and gives you back another int, so the above is really more like: > 5 + 7 + 9 => (+ 5 (+ 7 9)) => (+ 5 16) => 21 There you go!
What does -> mean in F#?
I've been trying to get into F# on and off for a while but I keep getting put off. Why? Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator ->. However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies. I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back. Can someone please, explain it or point to a truly accessible resource that explains it?
[ "'->' is not an operator. It appears in the F# syntax in a number of places, and its meaning depends on how it is used as part of a larger construct.\nInside a type, '->' describes function types as people have described above. For example\nlet f : int -> int = ...\n\nsays that 'f' is a function that takes an int and returns an int.\nInside a lambda (\"thing that starts with 'fun' keyword\"), '->' is syntax that separates the arguments from the body. For example\nfun x y -> x + y + 1\n\nis an expression that defines a two argument function with the given implementation.\nInside a \"match\" construct, '->' is syntax that separates patterns from the code that should run if the pattern is matched. For example, in\nmatch someList with\n| [] -> 0\n| h::t -> 1\n\nthe stuff to the left of each '->' are patterns, and the stuff on the right is what happens if the pattern on the left was matched.\nThe difficulty in understanding may be rooted in the faulty assumption that '->' is \"an operator\" with a single meaning. An analogy might be \".\" in C#, if you have never seen any code before, and try to analyze the \".\" operator based on looking at \"obj.Method\" and \"3.14\" and \"System.Collections\", you may get very confused, because the symbol has different meanings in different contexts. Once you know enough of the language to recognize these contexts, however, things become clear.\n", "It basically means \"maps to\". Read it that way or as \"is transformed into\" or something like that.\nSo, from the F# in 20 minutes tutorial,\n> List.map (fun x -> x % 2 = 0) [1 .. 10];;\nval it : bool list\n= [false; true; false; true; false; true; false; true; false; true]\n\n\nThe code (fun i -> i % 2 = 0) defines\n an anonymous function, called a lambda\n expression, that has a parameter x and\n the function returns the result of \"x\n % 2 = 0\", which is whether or not x is\n even.\n\n", "First question - are you familiar with lambda expressions in C#? If so the -> in F# is the same as the => in C# (I think you read it 'goes to').\nThe -> operator can also be found in the context of pattern matching\nmatch x with\n| 1 -> dosomething\n| _ -> dosomethingelse\n\nI'm not sure if this is also a lambda expression, or something else, but I guess the 'goes to' still holds.\nMaybe what you are really referring to is the F# parser's 'cryptic' responses:\n> let add a b = a + b\nval add: int -> int -> int\n\nThis means (as most of the examples explain) that add is a 'val' that takes two ints and returns an int. To me this was totally opaque to start with. I mean, how do I know that add isn't a val that takes one int and returns two ints?\nWell, the thing is that in a sense, it does. If I give add just one int, I get back an (int -> int):\n> let inc = add 1\nval inc: int -> int\n\nThis (currying) is one of the things that makes F# so sexy, for me. \nFor helpful info on F#, I have found that blogs are FAR more useful that any of the official 'documentation': Here are some names to check out\n\nDustin Campbell (that's diditwith.net, cited in another answer)\nDon Symes ('the' man)\nTomasp.net (aka Tomas Petricek)\nAndrew Kennedy (for units of measure)\nFsharp.it (famous for the Project Euler solutions)\nhttp://lorgonblog.spaces.live.com/Blog (aka Brian)\nJomo Fisher\n\n", "(a -> b) means \"function from a to b\". In type annotation, it denotes a function type. For example, f : (int -> String) means that f refers to a function that takes an integer and returns a string. It is also used as a contstructor of such values, as in\nval f : (int -> int) = fun n -> n * 2\n\nwhich creates a value which is a function from some number n to that same number multiplied by two.\n", "From Microsoft:\n\nFunction types are the types given to\n first-class function values and are\n written int -> int. They are similar\n to .NET delegate types, except they\n aren't given names. All F# function\n identifiers can be used as first-class\n function values, and anonymous\n function values can be created using\n the (fun ... -> ...) expression form.\n\n", "There are plenty of great answers here already, I just want to add to the conversation another way of thinking about it.\n' -> ' means function. \n'a -> 'b is a function that takes an 'a and returns a 'b\n('a * 'b) -> ('c * 'd) is a function that takes a tuple of type ('a, 'b) and returns a tuple of ('c, 'd). Such as int/string returns float/char.\nWhere it gets interesting is in the cascade case of 'a -> 'b -> 'c. This is a function that takes an 'a and returns a function ('b -> 'c), or a function that takes a 'b -> 'c.\nSo if you write:\n let f x y z = ()\nThe type will be f : 'a -> 'b -> 'c -> unit, so if you only applied the first parameter, the result would be a curried function 'b -> 'c -> 'unit. \n", "In the context of defining a function, it is similar to => from the lambda expression in C# 3.0.\nF#: let f = fun x -> x*x\nC#: Func<int, int> f = x => x * x;\n\nThe -> in F# is also used in pattern matching, where it means: if the expression matches the part between | and ->, then what comes after -> should be given back as the result:\nlet isOne x = match x with\n | 1 -> true\n | _ -> false\n\n", "Many great answers to this questions, thanks people. I'd like to put here an editable answer that brings things together.\nFor those familiar with C# understanding -> being the same as => lamba expression is a good first step. This usage is :-\nfun x y -> x + y + 1\n\nCan be understood as the equivalent to:-\n(x, y) => x + y + 1;\n\nHowever its clear that -> has a more fundemental meaning which stems from concept that a function that takes two parameters such as the above can be reduced (is that the correct term?) to a series of functions only taking one parameter.\nHence when the above is described in like this:-\nInt -> Int -> Int\n\nIt really helped to know that -> is right associative hence the above can be considered:-\nInt -> (Int -> Int)\n\nAha! We have a function that takes Int and returns (Int -> Int) (a curried function?).\nThe explaination that -> can also appear as part of type definiton also helped. (Int -> Int) is the type of any of function which takes an Int and returns an Int.\nAlso helpful is the -> appears in other syntax such as matching but there it doesn't have the same meaning? Is that correct? I'm not sure it is. I suspect it has the same meaning but I don't have the vocabulary to express that yet.\nNote the purpose of this answer is not to spawn further answers but to be collaboratively edited by you people to create a more definitive answer. Utlimately it would be good that all the uncertainies and fluf (such as this paragraph) be removed and better examples added. Lets try keep this answer as accessible to the uninitiated as possible.\n", "The nice thing about languages such as Haskell (it's very similar in F#, but I don't know the exact syntax -- this should help you understand ->, though) is that you can apply only parts of the argument, to create curried functions:\nadder n x y = n + x + y\n\nIn other words: \"give me three things, and I'll add them together\". When you throw numbers at it, the compiler will infer the types of n x and y. Say you write\nadder 1 2 3\n\nThe type of 1, 2 and 3 is Int. Therefore:\nadder :: Int -> Int -> Int -> Int\n\nThat is, give me three integers, and I will become an integer, eventually, or the same thing as saying:\nfive :: Int\nfive = 5\n\nBut, here's the nice part! Try this:\nadd5 = adder 5\n\nAs you remember, adder takes an int, an int, an int, and gives you back an int. However, that is not the entire truth, as you'll see shortly. In fact, add5 will have this type:\nadd5 :: Int -> Int -> Int\n\nIt will be as if you have \"peeled off\" of the integers (the left-most), and glued it directly to the function. Looking closer at the function signature, we notice that the -> are right-associative, i.e.:\naddder :: Int -> (Int -> (Int -> Int))\n\nThis should make it quite clear: when you give adder the first integer, it'll evaluate to whatever's to the right of the first arrow, or:\nadd5andtwomore :: Int -> (Int -> Int)\nadd5andtwomore = adder 5\n\nNow you can use add5andtwomore instead of \"adder 5\". This way, you can apply another integer to get (say) \"add5and7andonemore\":\nadd5and7andonemore :: Int -> Int\nadd5and7andonemore = adder 5 7\n\nAs you see, add5and7andonemore wants exactly another argument, and when you give it one, it will suddenly become an integer!\n > add5and7andonemore 9\n => ((add5andtwomore) 7) 9\n => ((adder 5) 7) 9)\n<=> adder 5 7 9\n\nSubstituting the parameters to adder (n x y) for (5 7 9), we get:\n > adder 5 7 9 = 5 + 7 + 9\n => 5 + 7 + 9\n => 21\n\nIn fact, plus is also just a function that takes an int and gives you back another int, so the above is really more like:\n > 5 + 7 + 9\n => (+ 5 (+ 7 9))\n => (+ 5 16)\n => 21\n\nThere you go!\n" ]
[ 51, 13, 9, 4, 1, 1, 1, 1, 0 ]
[]
[]
[ "f#", "functional_programming" ]
stackoverflow_0000104618_f#_functional_programming.txt
Q: How do you manage a large product backlog? We have a large backlog of things we should do in our software, in a lot of different categories, for example: New problem areas for our products to solve New functionality supporting existing problem areas New functionality requested by our existing users Usability and "look" enhancements Architectural upgrades to the back-end Bug fixes Managing all of these in a sensible fashion is a job that falls to Product Management, but it is tricky for a lot of reasons. Firstly, we have a number of different systems that hold the different things (market requirements document in files, bugs in a bug database, customer requirements in our help desk system, enginering's wish-list on our intranet, etc). And secondly, many of the items are of wildly different size, scope, complexity and of course value, which means that choosing isn't as simple as just ordering a list by priority. Because we now are fairly large, have a complex product and lots of customers, the basic solutions (a spreadsheet, a google doc, a basecamp to-do list) just isn't sufficient to deal with this. We need a way to group things together in various ways, prioritise them on an ongoing basis, make it clear what we're doing and what is coming - without it requiring all of someone's time to just manage some tool. How do you manage this in a way that allows the business to always do what is most valuable to existing customers, helps get new ones, and keeps the software innards sane? Note that this is different from the development-side, which I think we have down pretty well. We develop everything in an iterative, agile fashion, and once something has been chosen for design and implementation, we can do that. It's the part where we need to figure out what to do next that's hardest! Have you found a method or a tool that works? If so, please share! (And if you would like to know the answer too, rate up the question so it stays visible :) Addendum: Of course it's nice to fix all the bugs first, but in a real system that actually is installed on customers' machines, that is not always practical. For example, we may have a bug that only occurs very rarely and that it would take a huge amount of time and architectural upheaval to fix - we might leave that for a while. Or we might have a bug where someone thinks something is hard to use, and we think fixing it should wait for a bigger revamp of that area. So, there are lots of reasons why we don't just fix them all straight away, but keep them open so we don't forget. Besides, it is the prioritization of the non-bugs that is the hardest; just imagine we don't have any :) A: Managing a large backlog in an aggressive manner is almost always wasteful. By the time you get to the middle of a prioritized pile things have more often than not changed. I'd recommend adopting something like what Corey Ladas calls a priority filter: http://leansoftwareengineering.com/2008/08/19/priority-filter/ Essentially, you have a few buckets of increasing size and decreasing priority. You allow stakeholders to fill them, but force them to ignore the rest of the stories until there are openings in the buckets. Very simple but very effective. Edit: Allan asked what to do if tasks are of different sizes. Basically, a big part of making this work is right-sizing your tasks. We only apply this prioritization to user stories. User stories are typically significantly smaller than "create a community site". I would consider the community site bit an epic or even a project. It would need to be broken down into significantly smaller bits in order to be prioritized. That said, it can still be challenging to make stories similarly sized. Sometimes you just can't, so you communicate that during your planning decisions. With regards to moving wibbles two pixels, many of these things that are easy can be done for "free". You just have to be careful to balance these and only do them if they're really close to free and they're actually somewhat important. We treat bugs similarly. Bugs get one of three categories, Now, Soon or Eventually. We fix Now and Soon bugs as quickly as we can with the only difference being when we publish the fixes. Eventually bugs don't get fix unless devs get bored and have nothing to do or they somehow become higher priority. A: The key is aggressive categorization and prioritization. Fix the problems which are keeping customers away quickly and add more features to keep the customers coming. Push back issues which only affect a small number of people unless they are very easy to fix. A: A simple technique is to use a prioritization matrix. Examples: http://erc.msh.org/quality/pstools/psprior2.cfm http://it.toolbox.com/blogs/enterprise-solutions/sample-project-prioritization-matrix-23381 Also useful is the prioritization quadrants (two dimensions: Importance, Urgency) that Covey proposes: http://www.dkeener.com/keenstuff/priority.html. Focus on the Important and Urgent, then the Important and Not urgent. The non-Important stuff...well.. if someone wants to do that in their off hours :-). A variant of the Covey quadrants that I've used is with the dimensions of Importance and Ease. Ease is a good way to prioritize the tasks within a Covey quadrant. A: I think you have to get them all into one place so that the can be prioritised. Having to collate several different sources makes this virtually impossible. Once you have that then someone/a group have to rank each bug, requested feature and desired development. Things you could prioritise by are: Value added to the product Importance to customers, both existing and potential Scale of the task A: You should fix all the bugs first and only then think about adding new functions to it. A: All of this stuff could be tracked by a good bug tracking system that has the following features: Ability to mark work items as bugs or enhancement requests Category field for the region of responsibility that the work item falls under (UI, back-end, etc) Version # field for when the fix or feature is scheduled to be done Status field (in progress, completed, verified, etc) Priority field A: Since you already are doing things in agile fashion, you could borrow some ideas from XP: put all your stories in big pile of index cards (or some such tool) now developers should estimate how big or small those stories are (here developers have final word) and let client (or their proxy -- like product manager) order those stories by their business value (here client has final word) and if developers think that there is something technical which is more important (like fixing those pesky bugs), they have to communicate that to client (business person) and make client to rise that priority (client still has final word) select as many stories for next iteration as your teams velocity allows This way: there is a single queue of task, ordered by business needs clients get best return for their investment business value drives development, not technology or geeks developers get to say how hard things are to implement if there is no ROI, task stays near bottom of that pile For more information, see Planning Extreme Programming by Kent Bech and Martin Fowler. They say it much better than I can ever do. A: I'm not sure if the tool is as critical as the process. I've seen teams be very successful using something as simple as index cards and white boards to manage fairly large projects. One thing that I would recommend in prioritization is make sure you have a comprehensive list of these items together. This way you can weigh the priority of fixing an issue vs. a new feature, etc.. A: Beyond any tool and process, there should be... some people ;) In our shop, he is called a Release Manager and he determines the next functional perimeter to ship into production. Then there is a Freeze Manager who actually knows about code and files and bugs (he is usually one of the programmers), and will enforce the choices of the release manager, and monitor the necessary merges in order to have something to test and then release. Between them two, a prioritization can be established, both at high level (functional requests) and low-level (bugs and technical issues)
How do you manage a large product backlog?
We have a large backlog of things we should do in our software, in a lot of different categories, for example: New problem areas for our products to solve New functionality supporting existing problem areas New functionality requested by our existing users Usability and "look" enhancements Architectural upgrades to the back-end Bug fixes Managing all of these in a sensible fashion is a job that falls to Product Management, but it is tricky for a lot of reasons. Firstly, we have a number of different systems that hold the different things (market requirements document in files, bugs in a bug database, customer requirements in our help desk system, enginering's wish-list on our intranet, etc). And secondly, many of the items are of wildly different size, scope, complexity and of course value, which means that choosing isn't as simple as just ordering a list by priority. Because we now are fairly large, have a complex product and lots of customers, the basic solutions (a spreadsheet, a google doc, a basecamp to-do list) just isn't sufficient to deal with this. We need a way to group things together in various ways, prioritise them on an ongoing basis, make it clear what we're doing and what is coming - without it requiring all of someone's time to just manage some tool. How do you manage this in a way that allows the business to always do what is most valuable to existing customers, helps get new ones, and keeps the software innards sane? Note that this is different from the development-side, which I think we have down pretty well. We develop everything in an iterative, agile fashion, and once something has been chosen for design and implementation, we can do that. It's the part where we need to figure out what to do next that's hardest! Have you found a method or a tool that works? If so, please share! (And if you would like to know the answer too, rate up the question so it stays visible :) Addendum: Of course it's nice to fix all the bugs first, but in a real system that actually is installed on customers' machines, that is not always practical. For example, we may have a bug that only occurs very rarely and that it would take a huge amount of time and architectural upheaval to fix - we might leave that for a while. Or we might have a bug where someone thinks something is hard to use, and we think fixing it should wait for a bigger revamp of that area. So, there are lots of reasons why we don't just fix them all straight away, but keep them open so we don't forget. Besides, it is the prioritization of the non-bugs that is the hardest; just imagine we don't have any :)
[ "Managing a large backlog in an aggressive manner is almost always wasteful. By the time you get to the middle of a prioritized pile things have more often than not changed. I'd recommend adopting something like what Corey Ladas calls a priority filter:\nhttp://leansoftwareengineering.com/2008/08/19/priority-filter/\nEssentially, you have a few buckets of increasing size and decreasing priority. You allow stakeholders to fill them, but force them to ignore the rest of the stories until there are openings in the buckets. Very simple but very effective.\nEdit: Allan asked what to do if tasks are of different sizes. Basically, a big part of making this work is right-sizing your tasks. We only apply this prioritization to user stories. User stories are typically significantly smaller than \"create a community site\". I would consider the community site bit an epic or even a project. It would need to be broken down into significantly smaller bits in order to be prioritized.\nThat said, it can still be challenging to make stories similarly sized. Sometimes you just can't, so you communicate that during your planning decisions. \nWith regards to moving wibbles two pixels, many of these things that are easy can be done for \"free\". You just have to be careful to balance these and only do them if they're really close to free and they're actually somewhat important. \nWe treat bugs similarly. Bugs get one of three categories, Now, Soon or Eventually. We fix Now and Soon bugs as quickly as we can with the only difference being when we publish the fixes. Eventually bugs don't get fix unless devs get bored and have nothing to do or they somehow become higher priority.\n", "The key is aggressive categorization and prioritization.\nFix the problems which are keeping customers away quickly and add more features to keep the customers coming. Push back issues which only affect a small number of people unless they are very easy to fix.\n", "A simple technique is to use a prioritization matrix. \nExamples: \n\nhttp://erc.msh.org/quality/pstools/psprior2.cfm\nhttp://it.toolbox.com/blogs/enterprise-solutions/sample-project-prioritization-matrix-23381\n\nAlso useful is the prioritization quadrants (two dimensions: Importance, Urgency) that Covey proposes: http://www.dkeener.com/keenstuff/priority.html. Focus on the Important and Urgent, then the Important and Not urgent. The non-Important stuff...well.. if someone wants to do that in their off hours :-). A variant of the Covey quadrants that I've used is with the dimensions of Importance and Ease. Ease is a good way to prioritize the tasks within a Covey quadrant.\n", "I think you have to get them all into one place so that the can be prioritised. Having to collate several different sources makes this virtually impossible. Once you have that then someone/a group have to rank each bug, requested feature and desired development.\nThings you could prioritise by are:\n\nValue added to the product\nImportance to customers, both existing and potential\nScale of the task\n\n", "You should fix all the bugs first and only then think about adding new functions to it.\n", "All of this stuff could be tracked by a good bug tracking system that has the following features:\n\nAbility to mark work items as bugs or enhancement requests\nCategory field for the region of responsibility that the work item falls under (UI, back-end, etc)\nVersion # field for when the fix or feature is scheduled to be done\nStatus field (in progress, completed, verified, etc)\nPriority field\n\n", "Since you already are doing things in agile fashion, you could borrow some ideas from XP:\n\nput all your stories in big pile of index cards (or some such tool)\nnow developers should estimate how big or small those stories are (here developers have final word)\nand let client (or their proxy -- like product manager) order those stories by their business value (here client has final word)\nand if developers think that there is something technical which is more important (like fixing those pesky bugs), they have to communicate that to client (business person) and make client to rise that priority (client still has final word)\nselect as many stories for next iteration as your teams velocity allows\n\nThis way:\n\nthere is a single queue of task, ordered by business needs\nclients get best return for their investment\nbusiness value drives development, not technology or geeks\ndevelopers get to say how hard things are to implement\nif there is no ROI, task stays near bottom of that pile\n\nFor more information, see Planning Extreme Programming by Kent Bech and Martin Fowler. They say it much better than I can ever do.\n", "I'm not sure if the tool is as critical as the process. I've seen teams be very successful using something as simple as index cards and white boards to manage fairly large projects. One thing that I would recommend in prioritization is make sure you have a comprehensive list of these items together. This way you can weigh the priority of fixing an issue vs. a new feature, etc..\n", "Beyond any tool and process, there should be... some people ;)\nIn our shop, he is called a Release Manager and he determines the next functional perimeter to ship into production.\nThen there is a Freeze Manager who actually knows about code and files and bugs (he is usually one of the programmers), and will enforce the choices of the release manager, and monitor the necessary merges in order to have something to test and then release.\nBetween them two, a prioritization can be established, both at high level (functional requests) and low-level (bugs and technical issues)\n" ]
[ 12, 5, 3, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "backlog", "product_management", "project_management", "requirements" ]
stackoverflow_0000109141_backlog_product_management_project_management_requirements.txt
Q: How do I set up a local CPAN mirror? What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of? A: CPAN::Mini is the way to go. Once you've mirrored CPAN locally, you'll want to set your mirror URL in CPAN.pm or CPANPLUS to the local directory using a "file:" URL like this: file:///path/to/my/cpan/mirror If you'd like your mirror to have copies of development versions of CPAN distribution, you can use CPAN::Mini::Devel. Update: The "What do I need to mirror CPAN?" FAQ given in another answer is for mirroring all of CPAN, usually to provide another public mirror. That includes old, outdated versions of distributions. CPAN::Mini just mirrors the latest versions. This is much smaller and for most users is generally what people would use for local or disconnected (laptop) access to CPAN. A: Besides the other answers, check out Leon's CPAN::Mini::Webserver, which gives you a CPAN Search interface to your local CPAN copy. If you want to do more fancy things, see my "MyCPAN" talk. You can inject your own private modules into your private CPAN with CPAN::Mini::Inject, for instance. A: CPAN::Mini is fine. By default it keeps only the latest version of a distribution, not every version as CPAN does. You can also install CPAN::Mini::Webserver, which provides you with a web interface to your local cpan mirror - very handy if you are offline and still want to work with perl. A: Try CPAN::Mini. A: The most likely scenario for running a CPAN mirror is so that your network of 50 machines can all be updated from it locally, instead of hitting the network 50 times. I'd argue that using CPAN in the traditional manner is a poor way to keep a network of servers up to date. I run a network of RedHat machines. I package all CPAN modules intended for use in production into RPMs (mostly using the cpanflute2 tool from RPM::Specfile) and deploy them that way, thereby ensuring proper dependency tracking which you don't really get from CPAN itself in any sane way.
How do I set up a local CPAN mirror?
What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of?
[ "CPAN::Mini is the way to go. Once you've mirrored CPAN locally, you'll want to set your mirror URL in CPAN.pm or CPANPLUS to the local directory using a \"file:\" URL like this:\nfile:///path/to/my/cpan/mirror\n\nIf you'd like your mirror to have copies of development versions of CPAN distribution, you can use CPAN::Mini::Devel.\nUpdate: \nThe \"What do I need to mirror CPAN?\" FAQ given in another answer is for mirroring all of CPAN, usually to provide another public mirror. That includes old, outdated versions of distributions. CPAN::Mini just mirrors the latest versions. This is much smaller and for most users is generally what people would use for local or disconnected (laptop) access to CPAN.\n", "Besides the other answers, check out Leon's CPAN::Mini::Webserver, which gives you a CPAN Search interface to your local CPAN copy.\nIf you want to do more fancy things, see my \"MyCPAN\" talk. You can inject your own private modules into your private CPAN with CPAN::Mini::Inject, for instance.\n", "CPAN::Mini is fine. By default it keeps only the latest version of a distribution, not every version as CPAN does.\nYou can also install CPAN::Mini::Webserver, which provides you with a web interface to your local cpan mirror - very handy if you are offline and still want to work with perl.\n", "Try CPAN::Mini.\n", "The most likely scenario for running a CPAN mirror is so that your network of 50 machines can all be updated from it locally, instead of hitting the network 50 times.\nI'd argue that using CPAN in the traditional manner is a poor way to keep a network of servers up to date.\nI run a network of RedHat machines. I package all CPAN modules intended for use in production into RPMs (mostly using the cpanflute2 tool from RPM::Specfile) and deploy them that way, thereby ensuring proper dependency tracking which you don't really get from CPAN itself in any sane way.\n" ]
[ 25, 8, 5, 3, 2 ]
[]
[]
[ "administration", "cpan", "perl" ]
stackoverflow_0000077695_administration_cpan_perl.txt
Q: Can you record audio with a Java Midlet on a Nokia phone (N80/N95) without the JVM leaking memory? I would like to repeatedly capture snippets of audio on a Nokia mobile phone with a Java Midlet. My current experience is that using the code in Sun's documentation (see: http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html) and wrapping this in a "while(true)" loop works, but the application slowly consumes all the memory on the phone and the program eventually throws an exception and fails to initiate further recordings. The consumed memory isn't Java heap memory---my example program (below) shows that Java memory stays roughly static at around 185,000 bytes---but there is some kind of memory leak in the underlying supporting library provided by Nokia; I believe the memory leak occurs because if you try and start another (non-Java) application (e.g. web browser) after running the Java application for a while, the phone kills that application with a warning about lack of memory. I've tried several different approaches from that taken by Sun's canonical example in the documentation (initialize everything each time round the loop, initialize as much as possible only once, call as many of the deallocate-style functions which shouldn't be strictly necessary etc.). None appear to be successful. Below is a simple example program which I believe should work, but crashes after running for 15 minutes or so on both the N80 (despite a firmware update) and N95. Other forums report this problem too, but the solutions presented there do not appear to work (for example, see: http://discussion.forum.nokia.com/forum/showthread.php?t=129876). import javax.microedition.media.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.io.*; public class Standalone extends MIDlet { protected void startApp() { final Form form = new Form("Test audio recording"); final StringItem status = new StringItem("Status",""); form.append(status); final Command exit = new Command("Exit", Command.EXIT, 1); form.addCommand(exit); form.setCommandListener(new CommandListener() { public void commandAction(Command cmd, Displayable disp) { if (cmd == exit) { destroyApp(false); notifyDestroyed(); } } }); Thread t = new Thread(){ public void run() { int counter = 0; while(true) { //Code cut 'n' paste from Sun JSR135 javadocs for RecordControl: try { Player p = Manager.createPlayer("capture://audio"); p.realize(); RecordControl rc = (RecordControl)p.getControl("RecordControl"); ByteArrayOutputStream output = new ByteArrayOutputStream(); rc.setRecordStream(output); rc.startRecord(); p.start(); Thread.currentThread().sleep(5000); rc.commit(); p.close(); } catch (Exception e) { status.setText("completed "+counter+ " T="+Runtime.getRuntime().totalMemory()+ " F="+Runtime.getRuntime().freeMemory()+ ": Error: "+e); break; } counter++; status.setText("completed "+counter+ " T="+Runtime.getRuntime().totalMemory()+ " F="+Runtime.getRuntime().freeMemory()); System.gc(); //One forum post suggests this, but doesn't help this.yield(); } } }; t.start(); final Display display = Display.getDisplay(this); display.setCurrent(form); } protected void pauseApp() {} protected void destroyApp(boolean bool) {} } A: There is a known memory leak with the N-series Nokia devices. It is not specific to Java and is in the underbelly of the OS somewhere. Recently working on a game that targeted the Nokia N90, I had similar problems. I would run into memory problems that would accumulate over several different restarts of the application. The solution was just to reduce the overall quality and the amount of resources in the game... I would recommend attempting to update your firmware as newer versions supposedly address this problem. However, Nokia does not make it very easy to upgrade the firmware, in most cases you have to send the device off to Nokia. And, if this app is not just for your own personal use, you have to expect anyone using the N-series devices to not have the latest firmware. Finally, I would recommend spending some time looking around Forum Nokia as I know there are posts related to memory leaks and the N-series devices. Here is a post that seems to address the problem you are having. http://discussion.forum.nokia.com/forum/showthread.php?t=123486 A: I think you should file a bugreport instead of trying to work around that.
Can you record audio with a Java Midlet on a Nokia phone (N80/N95) without the JVM leaking memory?
I would like to repeatedly capture snippets of audio on a Nokia mobile phone with a Java Midlet. My current experience is that using the code in Sun's documentation (see: http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html) and wrapping this in a "while(true)" loop works, but the application slowly consumes all the memory on the phone and the program eventually throws an exception and fails to initiate further recordings. The consumed memory isn't Java heap memory---my example program (below) shows that Java memory stays roughly static at around 185,000 bytes---but there is some kind of memory leak in the underlying supporting library provided by Nokia; I believe the memory leak occurs because if you try and start another (non-Java) application (e.g. web browser) after running the Java application for a while, the phone kills that application with a warning about lack of memory. I've tried several different approaches from that taken by Sun's canonical example in the documentation (initialize everything each time round the loop, initialize as much as possible only once, call as many of the deallocate-style functions which shouldn't be strictly necessary etc.). None appear to be successful. Below is a simple example program which I believe should work, but crashes after running for 15 minutes or so on both the N80 (despite a firmware update) and N95. Other forums report this problem too, but the solutions presented there do not appear to work (for example, see: http://discussion.forum.nokia.com/forum/showthread.php?t=129876). import javax.microedition.media.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.io.*; public class Standalone extends MIDlet { protected void startApp() { final Form form = new Form("Test audio recording"); final StringItem status = new StringItem("Status",""); form.append(status); final Command exit = new Command("Exit", Command.EXIT, 1); form.addCommand(exit); form.setCommandListener(new CommandListener() { public void commandAction(Command cmd, Displayable disp) { if (cmd == exit) { destroyApp(false); notifyDestroyed(); } } }); Thread t = new Thread(){ public void run() { int counter = 0; while(true) { //Code cut 'n' paste from Sun JSR135 javadocs for RecordControl: try { Player p = Manager.createPlayer("capture://audio"); p.realize(); RecordControl rc = (RecordControl)p.getControl("RecordControl"); ByteArrayOutputStream output = new ByteArrayOutputStream(); rc.setRecordStream(output); rc.startRecord(); p.start(); Thread.currentThread().sleep(5000); rc.commit(); p.close(); } catch (Exception e) { status.setText("completed "+counter+ " T="+Runtime.getRuntime().totalMemory()+ " F="+Runtime.getRuntime().freeMemory()+ ": Error: "+e); break; } counter++; status.setText("completed "+counter+ " T="+Runtime.getRuntime().totalMemory()+ " F="+Runtime.getRuntime().freeMemory()); System.gc(); //One forum post suggests this, but doesn't help this.yield(); } } }; t.start(); final Display display = Display.getDisplay(this); display.setCurrent(form); } protected void pauseApp() {} protected void destroyApp(boolean bool) {} }
[ "There is a known memory leak with the N-series Nokia devices. It is not specific to Java and is in the underbelly of the OS somewhere.\nRecently working on a game that targeted the Nokia N90, I had similar problems. I would run into memory problems that would accumulate over several different restarts of the application. The solution was just to reduce the overall quality and the amount of resources in the game...\nI would recommend attempting to update your firmware as newer versions supposedly address this problem. However, Nokia does not make it very easy to upgrade the firmware, in most cases you have to send the device off to Nokia. And, if this app is not just for your own personal use, you have to expect anyone using the N-series devices to not have the latest firmware.\nFinally, I would recommend spending some time looking around Forum Nokia as I know there are posts related to memory leaks and the N-series devices. Here is a post that seems to address the problem you are having.\nhttp://discussion.forum.nokia.com/forum/showthread.php?t=123486\n", "I think you should file a bugreport instead of trying to work around that.\n" ]
[ 1, 0 ]
[]
[]
[ "audio", "java", "memory_leaks", "midlet", "nokia" ]
stackoverflow_0000100832_audio_java_memory_leaks_midlet_nokia.txt
Q: Why isn't there a viable mod_ruby for Apache yet? As popular as Ruby and Rails are, it seems like this problem would already be solved. JRuby and mod_rails are all fine and dandy, but why isn't there an Apache mod for just straight Ruby? A: There is Phusion Passenger, a robust Apache module that can run Rack applications with minimum configuration. It's becoming appealing to shared hosts, and turning any program into a Rack application is ridiculously easy: A Rack application is an Ruby object (not a class) that responds to call. It takes exactly one argument, the environment and returns an Array of exactly three values: The status, the headers, and the body. A: The basic problem is this: for a long time, MRI was the only feasible Ruby Implementation. MRI has a number of problems that make it hard to embed it into another application (which is basically what mod_ruby does: it embeds MRI in Apache), especially a multi-threaded one (which Apache is). It is not particularly thread-safe and it has quite a bit of global state. This global state means for example that if one Rails application modifies some class, then all other Rails applications that run on the same Apache server, will also see this modified class. Another problem is that the MRI source code is not easily hackable. MRI is now more than 15 years old, and it's starting to show. As a result of these problems, mod_ruby has never really properly worked, and at some point the maintainers simply gave up. The C based PHP interpreter, on the other hand, was designed from day one to be run as mod_php inside Apache. Indeed, for the first couple of versions, there wasn't even a commandline version of the interpreter, mod_php was the only way to run PHP. Phusion Passenger (aka mod_rack aka mod_rails) solves this problem by basically giving up and sidestepping the problem: they simply run a seperate copy of MRI in a seperate process for every application. It works great, and not only for Ruby. It supports WSGI (standard interface for Python Web Frameworks), Rack (standard interface for Ruby Web Frameworks) and direct support for Ruby on Rails. My hopes are on mod_rubinius, which unfortunately doesn't exist yet. Rubinius was designed from the beginning to be thread-safe, embeddable, free of global state, not use the C stack and so on. It was designed to be able to run multiple Rubinius VMs inside one Rubinius process. This makes mod_rubinius infinitely easier to implement and maintain than mod_ruby. Unfortunately, of course, Rubinius is not released yet, and the real work on mod_rubinius cannot even begin until Rubinius is released. The good news is that mod_rubinius already has more manpower behind it than mod_ruby ever had, because it has paid developers working on it by a Rails hosting company that desperately wants to use it themselves. A: It's perhaps worth double-clarifying mislav's point that mod_rails isn't actually limited to Rails code at all. The new name, mod_rack, is way better. Trivially small apps can be rackable -- their example being: class HelloWorld def call(env) [200, {"Content-Type" => "text/plain"}, ["Hello world!"]] end end A: There is one: mod_ruby, but it hasn't been maintained in about 2 years. A: There is mod_rails and it can run Rack applications, what more can you need?
Why isn't there a viable mod_ruby for Apache yet?
As popular as Ruby and Rails are, it seems like this problem would already be solved. JRuby and mod_rails are all fine and dandy, but why isn't there an Apache mod for just straight Ruby?
[ "There is Phusion Passenger, a robust Apache module that can run Rack applications with minimum configuration. It's becoming appealing to shared hosts, and turning any program into a Rack application is ridiculously easy:\n\nA Rack application is an Ruby object\n (not a class) that responds to call.\n It takes exactly one argument, the\n environment and returns an Array of\n exactly three values: The status, the\n headers, and the body.\n\n", "The basic problem is this: for a long time, MRI was the only feasible Ruby Implementation. MRI has a number of problems that make it hard to embed it into another application (which is basically what mod_ruby does: it embeds MRI in Apache), especially a multi-threaded one (which Apache is). It is not particularly thread-safe and it has quite a bit of global state.\nThis global state means for example that if one Rails application modifies some class, then all other Rails applications that run on the same Apache server, will also see this modified class.\nAnother problem is that the MRI source code is not easily hackable. MRI is now more than 15 years old, and it's starting to show.\nAs a result of these problems, mod_ruby has never really properly worked, and at some point the maintainers simply gave up.\nThe C based PHP interpreter, on the other hand, was designed from day one to be run as mod_php inside Apache. Indeed, for the first couple of versions, there wasn't even a commandline version of the interpreter, mod_php was the only way to run PHP.\nPhusion Passenger (aka mod_rack aka mod_rails) solves this problem by basically giving up and sidestepping the problem: they simply run a seperate copy of MRI in a seperate process for every application. It works great, and not only for Ruby. It supports WSGI (standard interface for Python Web Frameworks), Rack (standard interface for Ruby Web Frameworks) and direct support for Ruby on Rails.\nMy hopes are on mod_rubinius, which unfortunately doesn't exist yet. Rubinius was designed from the beginning to be thread-safe, embeddable, free of global state, not use the C stack and so on. It was designed to be able to run multiple Rubinius VMs inside one Rubinius process. This makes mod_rubinius infinitely easier to implement and maintain than mod_ruby. Unfortunately, of course, Rubinius is not released yet, and the real work on mod_rubinius cannot even begin until Rubinius is released. The good news is that mod_rubinius already has more manpower behind it than mod_ruby ever had, because it has paid developers working on it by a Rails hosting company that desperately wants to use it themselves.\n", "It's perhaps worth double-clarifying mislav's point that mod_rails isn't actually limited to Rails code at all. The new name, mod_rack, is way better. Trivially small apps can be rackable -- their example being:\nclass HelloWorld\n def call(env)\n [200, {\"Content-Type\" => \"text/plain\"}, [\"Hello world!\"]]\n end\nend\n\n", "There is one: mod_ruby, but it hasn't been maintained in about 2 years.\n", "There is mod_rails and it can run Rack applications, what more can you need?\n" ]
[ 23, 18, 5, 4, 0 ]
[]
[]
[ "apache", "ruby", "ruby_on_rails" ]
stackoverflow_0000075001_apache_ruby_ruby_on_rails.txt
Q: How would you implement FORM based authentication without a backing database? I have a PHP script that runs as a CGI program and the HTTP Authenticate header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored. I am very open to having a master username and password. I just need to protect the application from an intruder who doesn't know these credentials. So how would you implement this? Cookies? I could present the form and if it validates, I can send back a cookie that is a hash of the IP address come secret code. Then I can prevent pages from rendering unless the thing decrypts correctly. But I have no idea how to implement that in PHP. A: A few ways you could do this. htaccess -- have your webserver handle securing the pages in question (not exactly cgi form based though). Use cookies and some sort of hashing algorithm (md5 is good enough) to store the passwords in a flat file where each line in the file is username:passwordhash. Make sure to salt your hashes for extra security vs rainbow tables. (This method is a bit naive... be very careful with security if you go this route) use something like a sqlite database just to handle authentication. Sqlite is compact and simple enough that it may still meet your needs even if you don't want a big db backend. Theoretically, you could also store session data in a flat file, even if you can't have a database. A: If you're currently using Authenticate, then you may already have an htpasswd file. If you would like to continue using that file, but switch to using FORM based authentication rather than via the Authenticate header, you can use a PHP script to use the same htpasswd file and use sessions to maintain the authentication status. A quick Google search for php htpasswd reveals this page with a PHP function to check credentials against an htpasswd. You could integrate it (assuming you have sessions set to autostart) with some code like this: // At the top of your 'private' page(s): if($_SESSION['authenticated'] !== TRUE) { header('Location: /login.php'); die(); } // the target of the POST form from login.php if(http_authenticate($_POST['username'], $_POST['password'])) $_SESSION['authenticated'] = TRUE; A: Do you really need a form? No matter what you do, you're limited by the username and password being known. If they know that, they get your magic cookie that lets them. You want to prevent them seeing the pages if they don't know the secret, and basic authorization does that, is easy to set up, and doesn't require a lot of work on your part. Do you really need to see the Authorization header if the web server takes care of the access control for you? Also, if you're providing the application to a known list of people (rather than the public), you can provide web-server-based access on other factors, such as incoming IP address, client certificates, and many other things that are a matter of configuration rather than programming. If you explained your security constraints, we might be able to offer a better solution. Good luck, :)
How would you implement FORM based authentication without a backing database?
I have a PHP script that runs as a CGI program and the HTTP Authenticate header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored. I am very open to having a master username and password. I just need to protect the application from an intruder who doesn't know these credentials. So how would you implement this? Cookies? I could present the form and if it validates, I can send back a cookie that is a hash of the IP address come secret code. Then I can prevent pages from rendering unless the thing decrypts correctly. But I have no idea how to implement that in PHP.
[ "A few ways you could do this.\n\nhtaccess -- have your webserver handle securing the pages in question (not exactly cgi form based though).\nUse cookies and some sort of hashing algorithm (md5 is good enough) to store the passwords in a flat file where each line in the file is username:passwordhash. Make sure to salt your hashes for extra security vs rainbow tables. (This method is a bit naive... be very careful with security if you go this route)\nuse something like a sqlite database just to handle authentication. Sqlite is compact and simple enough that it may still meet your needs even if you don't want a big db backend.\n\nTheoretically, you could also store session data in a flat file, even if you can't have a database.\n", "If you're currently using Authenticate, then you may already have an htpasswd file. If you would like to continue using that file, but switch to using FORM based authentication rather than via the Authenticate header, you can use a PHP script to use the same htpasswd file and use sessions to maintain the authentication status. \nA quick Google search for php htpasswd reveals this page with a PHP function to check credentials against an htpasswd. You could integrate it (assuming you have sessions set to autostart) with some code like this:\n// At the top of your 'private' page(s):\nif($_SESSION['authenticated'] !== TRUE) {\n header('Location: /login.php');\n die();\n}\n\n// the target of the POST form from login.php\nif(http_authenticate($_POST['username'], $_POST['password']))\n $_SESSION['authenticated'] = TRUE;\n\n", "Do you really need a form? No matter what you do, you're limited by the username and password being known. If they know that, they get your magic cookie that lets them. You want to prevent them seeing the pages if they don't know the secret, and basic authorization does that, is easy to set up, and doesn't require a lot of work on your part. \nDo you really need to see the Authorization header if the web server takes care of the access control for you?\nAlso, if you're providing the application to a known list of people (rather than the public), you can provide web-server-based access on other factors, such as incoming IP address, client certificates, and many other things that are a matter of configuration rather than programming. If you explained your security constraints, we might be able to offer a better solution.\nGood luck, :)\n" ]
[ 5, 1, 1 ]
[ "... About salt, add the username in your hash salt will prevent someone who knows your salt and have access to your password file to write a rainbow table and crack number of your users's password.\n" ]
[ -1 ]
[ "authentication", "cgi", "cookies", "http", "php" ]
stackoverflow_0000017376_authentication_cgi_cookies_http_php.txt
Q: How do I test that a Rails Helper defines a method? I am creating a Rails plugin and it is dynamically adding a method to a Helper. I just want to ensure that the method is added. How can I see if the Helper responds to the method name? A: Try this: def test_that_foo_helper_defines_bar o = Object.new assert !o.respond_to? :bar o.extend FooHelper assert o.respond_to? :bar end
How do I test that a Rails Helper defines a method?
I am creating a Rails plugin and it is dynamically adding a method to a Helper. I just want to ensure that the method is added. How can I see if the Helper responds to the method name?
[ "Try this:\ndef test_that_foo_helper_defines_bar\n o = Object.new\n assert !o.respond_to? :bar\n o.extend FooHelper\n assert o.respond_to? :bar\nend\n\n" ]
[ 6 ]
[]
[]
[ "helper", "ruby", "ruby_on_rails", "unit_testing" ]
stackoverflow_0000109528_helper_ruby_ruby_on_rails_unit_testing.txt
Q: Rails and Gmail SMTP, how to use a custom from address I've got my Rails (2.1) app setup to send email via Gmail, however whenever I send an email no matter what I set the from address to in my ActionMailer the emails always come as if sent from my Gmail email address. Is this a security restriction they've put in place at Gmail to stop spammers using their SMTP? Note: I've tried both of the following methods within my ActionMailer (just in case): @from = [email protected] from '[email protected]' A: I believe it's just something Gmail does when mail is sent through its SMTP, as it was mentioned that they do this on a tutorial about using their SMTP to send mail. A: This is most likely to stop people trying to send email from addresses that Google can't verify that the sender owns. This is fairly common amongst mail providers, and is probably a safeguard to stop people using Google's services for sending spam. A: I think I tried and failed in the past myself, but I did just come across this on the gmail site: http://mail.google.com/support/bin/answer.py?ctx=gmail&hl=en&answer=22370 Looks like you can specify a custom "From" address within gmail, and perhaps at that point, see if setting @from will work (now that gmail knows about your custom from address).
Rails and Gmail SMTP, how to use a custom from address
I've got my Rails (2.1) app setup to send email via Gmail, however whenever I send an email no matter what I set the from address to in my ActionMailer the emails always come as if sent from my Gmail email address. Is this a security restriction they've put in place at Gmail to stop spammers using their SMTP? Note: I've tried both of the following methods within my ActionMailer (just in case): @from = [email protected] from '[email protected]'
[ "I believe it's just something Gmail does when mail is sent through its SMTP, as it was mentioned that they do this on a tutorial about using their SMTP to send mail.\n", "This is most likely to stop people trying to send email from addresses that Google can't verify that the sender owns. This is fairly common amongst mail providers, and is probably a safeguard to stop people using Google's services for sending spam.\n", "I think I tried and failed in the past myself, but I did just come across this on the gmail site: http://mail.google.com/support/bin/answer.py?ctx=gmail&hl=en&answer=22370\nLooks like you can specify a custom \"From\" address within gmail, and perhaps at that point, see if setting @from will work (now that gmail knows about your custom from address).\n" ]
[ 6, 3, 3 ]
[]
[]
[ "actionmailer", "gmail", "ruby_on_rails", "smtp" ]
stackoverflow_0000109520_actionmailer_gmail_ruby_on_rails_smtp.txt
Q: PHP replace double backslashes "\\" to a single backslash "\" Okay so im working on this php image upload system but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie: C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg. A: Note that you may be running into PHP's Magic Quotes "feature" where incoming backslashes are turned to \\. See http://us2.php.net/magic_quotes A: Use the stripslashes function. That should make them all single slashes. A: Have you considered the stripslashes() function? http://www.php.net/stripslashes
PHP replace double backslashes "\\" to a single backslash "\"
Okay so im working on this php image upload system but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie: C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg.
[ "Note that you may be running into PHP's Magic Quotes \"feature\" where incoming backslashes are turned to \\\\.\nSee \nhttp://us2.php.net/magic_quotes\n", "Use the stripslashes function.\nThat should make them all single slashes.\n", "Have you considered the stripslashes() function?\nhttp://www.php.net/stripslashes\n" ]
[ 3, 2, 1 ]
[]
[]
[ "backslash", "php", "replace", "string" ]
stackoverflow_0000109444_backslash_php_replace_string.txt
Q: .NET Reporting Tutorial Does anyone know a Tutorial for the Reporting in C# .NET. I mean the Reports in "Microsoft.Reporting" Namespace (not Crystal Reports). A: I know you probably aren't looking for links that you can find on google yourself, but these cover reporting services in great detail and should cover most of your questions. Reporting Services Tutorials Intro to reporting services Reporting Services in Action Webcasts on Reporting Services Useful reporting services links But I'm pretty sure reporting services is tied pretty close to MS SQL, so if you aren't using it you might have to look for a different solution.
.NET Reporting Tutorial
Does anyone know a Tutorial for the Reporting in C# .NET. I mean the Reports in "Microsoft.Reporting" Namespace (not Crystal Reports).
[ "I know you probably aren't looking for links that you can find on google yourself, but these cover reporting services in great detail and should cover most of your questions.\n\nReporting Services Tutorials\nIntro to reporting services\nReporting Services in Action\nWebcasts on Reporting Services\nUseful reporting services links\n\nBut I'm pretty sure reporting services is tied pretty close to MS SQL, so if you aren't using it you might have to look for a different solution.\n" ]
[ 7 ]
[]
[]
[ ".net", "c#", "reporting" ]
stackoverflow_0000109154_.net_c#_reporting.txt
Q: Custom Text Wrapping in WPF Is there a way of wrapping text in a non-rectangular container in WPF? Here is how it is done in photoshop A: Unfortunately there isn't a straightforward way without making a complete implementation of a TextFormatter. MSDN article on the basics of an Advanced TextFormatter: The text layout and UI controls in WPF provide formatting properties that allow you to easily include formatted text in your application. These controls expose a number of properties to handle the presentation of text, which includes its typeface, size, and color. Under ordinary circumstances, these controls can handle the majority of text presentation in your application. However, some advanced scenarios require the control of text storage as well as text presentation. WPF provides an extensible text formatting engine for this purpose. A: Have you looked at the UIElement.Clip property? For non-rectangular text wrapping, you could try setting a TextBlock.Clip property to a non-rectangular Geometry object. I haven't tried this; either it will not draw text outside the clip region or it will wrap text to fit within the clip. Charles Petzold mentions this technique.
Custom Text Wrapping in WPF
Is there a way of wrapping text in a non-rectangular container in WPF? Here is how it is done in photoshop
[ "Unfortunately there isn't a straightforward way without making a complete implementation of a TextFormatter. MSDN article on the basics of an Advanced TextFormatter: \n\nThe text layout and UI controls in WPF provide formatting properties that allow you to easily include formatted text in your application. These controls expose a number of properties to handle the presentation of text, which includes its typeface, size, and color. Under ordinary circumstances, these controls can handle the majority of text presentation in your application. However, some advanced scenarios require the control of text storage as well as text presentation. WPF provides an extensible text formatting engine for this purpose.\n\n", "Have you looked at the UIElement.Clip property?\nFor non-rectangular text wrapping, you could try setting a TextBlock.Clip property to a non-rectangular Geometry object. I haven't tried this; either it will not draw text outside the clip region or it will wrap text to fit within the clip.\nCharles Petzold mentions this technique.\n" ]
[ 5, 1 ]
[]
[]
[ "text", "wpf" ]
stackoverflow_0000108689_text_wpf.txt