Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm looking for a fast way to determine the area of intersection between a rectangle and a circle (I need to do millions of these calculations). A specific property is that in all cases the circle and rectangle always have 2 points of intersection.
Given 2 points of intersection: **0 vertices** is inside the circle: The area of a [circular segment](http://mathworld.wolfram.com/CircularSegment.html) ``` XXXXX ------------------- X X X X Circular segment X X XX XX +-X-------X--+ XXXXXXXX | X X | | XXXXX | ``` **1 vertex** is inside the circle: The sum of the areas of a circular segment and a triangle. ``` XXXXX XXXXXXXXX X X Triangle ->X _-X X X X _- X X +--X--+ X _- X <- Circular segment X | X | X- XXX XXXXX | XXXX | | ``` **2 vertices** are inside the circle: The sum of the area of two triangles and a circular segment ``` XXXXX +------------X X X | _--'/'X X +--X--- Triangle->| _-- / X X | X |_-- /XX <- Circular segment X +-X---- +-------XX XXXXX Triangle^ ``` **3 vertices** are inside the circle: The area of the rectangle minus the area of a triangle plus the area of a circular segment ``` XXXXX X +--X+ XXX X | X -------XXX-----+ <- Triangle outside X | |X Rect ''. XXX | X +---+X ''. XX| X X ''. X <- Circular segment inside X X ^|X X X | X XXXXX ``` To calculate these areas: * Most of the points you'll need to use can be found by finding the [intersection of a line and a circle](http://mathworld.wolfram.com/Circle-LineIntersection.html) * The areas you need to compute can be found by [computing the area of a circular segment](http://mathworld.wolfram.com/CircularSegment.html) and [computing the area of a triangle](http://mathworld.wolfram.com/TriangleArea.html). * You can determine if a vertex is inside the circle by calculating if its distance from the center is less than the radius.
I realize this was answered a while ago but I'm solving the same problem and I couldn't find an out-of-the box workable solution I could use. Note that my boxes are [axis aligned](https://en.wikipedia.org/wiki/Axis-aligned_object), this is not quite specified by the OP. The solution below is completely general, and will work for any number of intersections (not only two). Note that if your boxes are not axis-aligned (but still boxes with right angles, rather than general [quads](https://en.wikipedia.org/wiki/Quadrilateral)), you can take advantage of the circles being round, rotate the coordinates of everything so that the box ends up axis-aligned and *then* use this code. I want to use integration - that seems like a good idea. Let's start with writing an obvious formula for plotting a circle: ``` x = center.x + cos(theta) * radius y = center.y + sin(theta) * radius ^ | |**### ** | #* # * * x |# * # * # y |# * # * +-----------------------> theta * # * # * # * # * #* # ***### ``` This is nice, but I'm unable to integrate the area of that circle over `x` or `y`; those are different quantities. I can only integrate over the angle `theta`, yielding areas of pizza slices. Not what I want. Let's try to change the arguments: ``` (x - center.x) / radius = cos(theta) // the 1st equation theta = acos((x - center.x) / radius) // value of theta from the 1st equation y = center.y + sin(acos((x - center.x) / radius)) * radius // substitute to the 2nd equation ``` That's more like it. Now given the range of `x`, I can integrate over `y`, to get an area of the upper half of a circle. This only holds for `x` in `[center.x - radius, center.x + radius]` (other values will cause imaginary outputs) but we know that the area outside that range is zero, so that is handled easily. Let's assume unit circle for simplicity, we can always plug the center and radius back later on: ``` y = sin(acos(x)) // x in [-1, 1] y = sqrt(1 - x * x) // the same thing, arguably faster to compute http://www.wolframalpha.com/input/?i=sin%28acos%28x%29%29+ ^ y | ***|*** <- 1 **** | **** ** | ** * | * * | * ----|----------+----------|-----> x -1 1 ``` This function indeed has an integral of `pi/2`, since it is an upper half of a unit circle (the area of half a circle is `pi * r^2 / 2` and we already said *unit*, which means `r = 1`). Now we can calculate area of intersection of a half-circle and an infinitely tall box, standing on the x axis (the center of the circle also lies on the the x axis) by integrating over `y`: ``` f(x): integral(sqrt(1 - x * x) * dx) = (sqrt(1 - x * x) * x + asin(x)) / 2 + C // http://www.wolframalpha.com/input/?i=sqrt%281+-+x*x%29 area(x0, x1) = f(max(-1, min(1, x1))) - f(max(-1, min(1, x0))) // the integral is not defined outside [-1, 1] but we want it to be zero out there ~ ~ | ^ | | | | | ***|*** <- 1 ****###|##|**** **|######|##| ** * |######|##| * * |######|##| * ----|---|------+--|-------|-----> x -1 x0 x1 1 ``` This may not be very useful, as infinitely tall boxes are not what we want. We need to add one more parameter in order to be able to free the bottom edge of the infinitely tall box: ``` g(x, h): integral((sqrt(1 - x * x) - h) * dx) = (sqrt(1 - x * x) * x + asin(x) - 2 * h * x) / 2 + C // http://www.wolframalpha.com/input/?i=sqrt%281+-+x*x%29+-+h area(x0, x1, h) = g(min(section(h), max(-section(h), x1))) - g(min(section(h), max(-section(h), x0))) ~ ~ | ^ | | | | | ***|*** <- 1 ****###|##|**** **|######|##| ** * +------+--+ * <- h * | * ----|---|------+--|-------|-----> x -1 x0 x1 1 ``` Where `h` is the (positive) distance of the bottom edge of our infinite box from the x axis. The `section` function calculates the (positive) position of intersection of the unit circle with the horizontal line given by `y = h` and we could define it by solving: ``` sqrt(1 - x * x) = h // http://www.wolframalpha.com/input/?i=sqrt%281+-+x+*+x%29+%3D+h section(h): (h < 1)? sqrt(1 - h * h) : 0 // if h is 1 or above, then the section is an empty interval and we want the area integral to be zero ^ y | ***|*** <- 1 **** | **** ** | ** -----*---------+---------*------- y = h * | * ----||---------+---------||-----> x -1| |1 -section(h) section(h) ``` Now we can get the things going. So how to calculate the area of intersection of a finite box intersecting a unit circle above the x axis: ``` area(x0, x1, y0, y1) = area(x0, x1, y0) - area(x0, x1, y1) // where x0 <= x1 and y0 <= y1 ~ ~ ~ ~ | ^ | | ^ | | | | | | | | ***|*** | ***|*** ****###|##|**** ****---+--+**** <- y1 **|######|##| ** ** | ** * +------+--+ * <- y0 * | * * | * * | * ----|---|------+--|-------|-----> x ----|---|------+--|-------|-----> x x0 x1 x0 x1 ^ | ***|*** ****---+--+**** <- y1 **|######|##| ** * +------+--+ * <- y0 * | * ----|---|------+--|-------|-----> x x0 x1 ``` That's nice. So how about a box which is not above the x axis? I'd say not all the boxes are. Three simple cases arise: * the box is above the x axis (use the above equation) * the box is below the x axis (flip the sign of y coordinates and use the above equation) * the box is intersecting the x axis (split the box to upper and lower half, calculate the area of both using the above and sum them) Easy enough? Let's write some code: ``` float section(float h, float r = 1) // returns the positive root of intersection of line y = h with circle centered at the origin and radius r { assert(r >= 0); // assume r is positive, leads to some simplifications in the formula below (can factor out r from the square root) return (h < r)? sqrt(r * r - h * h) : 0; // http://www.wolframalpha.com/input/?i=r+*+sin%28acos%28x+%2F+r%29%29+%3D+h } float g(float x, float h, float r = 1) // indefinite integral of circle segment { return .5f * (sqrt(1 - x * x / (r * r)) * x * r + r * r * asin(x / r) - 2 * h * x); // http://www.wolframalpha.com/input/?i=r+*+sin%28acos%28x+%2F+r%29%29+-+h } float area(float x0, float x1, float h, float r) // area of intersection of an infinitely tall box with left edge at x0, right edge at x1, bottom edge at h and top edge at infinity, with circle centered at the origin with radius r { if(x0 > x1) std::swap(x0, x1); // this must be sorted otherwise we get negative area float s = section(h, r); return g(max(-s, min(s, x1)), h, r) - g(max(-s, min(s, x0)), h, r); // integrate the area } float area(float x0, float x1, float y0, float y1, float r) // area of the intersection of a finite box with a circle centered at the origin with radius r { if(y0 > y1) std::swap(y0, y1); // this will simplify the reasoning if(y0 < 0) { if(y1 < 0) return area(x0, x1, -y0, -y1, r); // the box is completely under, just flip it above and try again else return area(x0, x1, 0, -y0, r) + area(x0, x1, 0, y1, r); // the box is both above and below, divide it to two boxes and go again } else { assert(y1 >= 0); // y0 >= 0, which means that y1 >= 0 also (y1 >= y0) because of the swap at the beginning return area(x0, x1, y0, r) - area(x0, x1, y1, r); // area of the lower box minus area of the higher box } } float area(float x0, float x1, float y0, float y1, float cx, float cy, float r) // area of the intersection of a general box with a general circle { x0 -= cx; x1 -= cx; y0 -= cy; y1 -= cy; // get rid of the circle center return area(x0, x1, y0, y1, r); } ``` And some basic unit tests: ``` printf("%f\n", area(-10, 10, -10, 10, 0, 0, 1)); // unit circle completely inside a huge box, area of intersection is pi printf("%f\n", area(-10, 0, -10, 10, 0, 0, 1)); // half of unit circle inside a large box, area of intersection is pi/2 printf("%f\n", area(0, 10, -10, 10, 0, 0, 1)); // half of unit circle inside a large box, area of intersection is pi/2 printf("%f\n", area(-10, 10, -10, 0, 0, 0, 1)); // half of unit circle inside a large box, area of intersection is pi/2 printf("%f\n", area(-10, 10, 0, 10, 0, 0, 1)); // half of unit circle inside a large box, area of intersection is pi/2 printf("%f\n", area(0, 1, 0, 1, 0, 0, 1)); // unit box covering one quadrant of the circle, area of intersection is pi/4 printf("%f\n", area(0, -1, 0, 1, 0, 0, 1)); // unit box covering one quadrant of the circle, area of intersection is pi/4 printf("%f\n", area(0, -1, 0, -1, 0, 0, 1)); // unit box covering one quadrant of the circle, area of intersection is pi/4 printf("%f\n", area(0, 1, 0, -1, 0, 0, 1)); // unit box covering one quadrant of the circle, area of intersection is pi/4 printf("%f\n", area(-.5f, .5f, -.5f, .5f, 0, 0, 10)); // unit box completely inside a huge circle, area of intersection is 1 printf("%f\n", area(-20, -10, -10, 10, 0, 0, 1)); // huge box completely outside a circle (left), area of intersection is 0 printf("%f\n", area(10, 20, -10, 10, 0, 0, 1)); // huge box completely outside a circle (right), area of intersection is 0 printf("%f\n", area(-10, 10, -20, -10, 0, 0, 1)); // huge box completely outside a circle (below), area of intersection is 0 printf("%f\n", area(-10, 10, 10, 20, 0, 0, 1)); // huge box completely outside a circle (above), area of intersection is 0 ``` The output of this is: ``` 3.141593 1.570796 1.570796 1.570796 1.570796 0.785398 0.785398 0.785398 0.785398 1.000000 -0.000000 0.000000 0.000000 0.000000 ``` Which seems correct to me. You may want to inline the functions if you don't trust your compiler to do it for you. This uses 6 sqrt, 4 asin, 8 div, 16 mul and 17 adds for boxes that do not intersect the x axis and a double of that (and 1 more add) for boxes that do. Note that the divisions are by radius and could be reduced to two divisions and a bunch of multiplications. If the box in question intersected the x axis but did not intersect the y axis, you could rotate everything by `pi/2` and do the calculation in the original cost. I'm using it as a reference to debug subpixel-precise antialiased circle rasterizer. It is slow as hell :), I need to calculate the area of intersection of each pixel in the bounding box of the circle with the circle to get alpha. You can sort of see that it works and no numerical artifacts seem to appear. The figure below is a plot of a bunch of circles with the radius increasing from 0.3 px to about 6 px, laid out in a spiral. [![circles](https://i.stack.imgur.com/v7L92.png)](https://i.stack.imgur.com/v7L92.png)
Area of intersection between circle and rectangle
[ "", "java", "math", "intersection", "area", "" ]
I need for my program to determine if it was compiled for 32 bit windows or 64 bit/any CPU. I need to choose a different COM server flag depending on the compilation options. Any ideas?
**Checking at run time if you are running a 64-bit application:** To see whether your process is 64-bit or 32-bit you can simply check the **IntPtr.Size** or any other pointer type. If you get 4 then you are running on 32-bit. If you get 8 then you are running on 64-bit. **What type of computer is your process running as:** You can check the PROCESSOR\_ARCHITECTURE environment variable to see if you are running on an x64, ia64 or x86 machine. **Is your process running under emulation:** The Win32 API IsWow64Process will tell you if you are running a 32-bit application under x64. Wow64 means windows32 on windows64. Contrary to what other people have posted: IsWow64Process will not tell you if you are running a 32-bit or a 64bit application. On 32-bit machines it will tell you FALSE for 32-bit applications when run, and on a 64-bit machine it will tell you TRUE for a 32-bit application. It only tells you if your application is running under emulation.
Are you aware of [`Environment.Is64BitProcess`](http://msdn.microsoft.com/en-us/library/system.environment.is64bitprocess.aspx "Environment.Is64BitProcess")? It determines whether the current running process is a 64-bit process.
How to determine if the executing program was compiled for 64 bit?
[ "", "c#", "64-bit", "" ]
Last week I wrote a few lines of code in C# to fire up a large text file (300,000 lines) into a Dictionary. It took ten minutes to write and it executed in less than a second. Now I'm converting that piece of code into C++ (because I need it in an old C++ COM object). I've spent two days on it this far. :-( Although the productivity difference is shocking on its own, it's the performance that I would need some advice on. It takes seven seconds to load, and even worse: it takes just exactly that much time to free all the CStringWs afterwards. This is not acceptable, and I must find a way to increase the performance. Are there any chance that I can allocate this many strings without seeing this horrible performace degradation? My guess right now is that I'll have to stuff all the text into a large array and then let my hash table point to the beginning of each string within this array and drop the CStringW stuff. But before that, any advice from you C++ experts out there? **EDIT**: My answer to myself is given below. I realized that that is the fastest route for me, and also step in what *I* consider *the right direction* - towards more managed code.
You are stepping into the shoes of Raymond Chen. He did the exact same thing, writing a Chinese dictionary in unmanaged C++. Rico Mariani did too, writing it in C#. Mr. Mariani made one version. Mr. Chen wrote 6 versions, trying to match the perf of Mariani's version. He pretty much rewrote significant chunks of the C/C++ runtime library to get there. Managed code got a lot more respect after that. The GC allocator is impossible to beat. Check [this blog](https://learn.microsoft.com/en-us/archive/blogs/ricom/performance-quiz-6-chineseenglish-dictionary-reader) post for the links. This [blog post](http://www.voidnish.com/Articles/ShowArticle.aspx?code=StlClrBclComparison) might interest you too, instructive to see how the STL value semantics are part of the problem.
This sounds very much like the Raymond Chen vs Rico Mariani's C++ vs C# Chinese/English dictionary performance bake off. It took Raymond several iterations to beat C#. Perhaps there are ideas there that would help. <http://blogs.msdn.com/ricom/archive/2005/05/10/performance-quiz-6-chinese-english-dictionary-reader.aspx>
C++ string memory management
[ "", "c++", "mfc", "memory-management", "" ]
I have put together a script which will upload a CSV file and then extract the data into an already made table. I want to make it so the first line(the column headers) will not be inserted into the table, but the rest of the data will be. ``` $fp = fopen($_SESSION['filename'],"r"); while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) { $import="INSERT into csv_table(name,address,age) values('$data[0]','$data[1]','$data[2]')"; mysql_query($import) or die(mysql_error()); } fclose($fp); ``` this is the part of the code i use to extract the data from the csv file. Thank You very much for any help with this matter!
Just put the following before the `while` loop to read the first line: ``` fgetcsv($fp, 1000, ","); ``` Thereafter the `while` loop starts with the second line instead.
Underthink it. Create a boolean flag on the outside, and toggle it once you enter the loop instead of importing, using an if statement.
How do i remove the top line in a CSV file (the coloumn headers)?
[ "", "php", "csv", "" ]
I'm hoping someone here will be able to aid me with my struggles with integration with ActiveMQ from C#. Here's what I did so far: ``` using Apache.NMS; using Apache.NMS.ActiveMQ; namespace JMSTest { class Program { static void Main(string[] args) { IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/"); IConnection connection = factory.CreateConnection(); ISession session = connection.CreateSession(); } } } ``` Pretty basic stuff: just create a connection factory, then use it to create the connection and at the end create a session. Now when I execute this code this is the exception that's being thrown: ``` System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) at System.String.Substring(Int32 startIndex, Int32 length) at Apache.NMS.ActiveMQ.OpenWire.StringPackageSplitter.StringPackageSplitterEnumerator.System.Collections.IEnumerator.get_Current() at Apache.NMS.ActiveMQ.OpenWire.OpenWireBinaryWriter.Write(String text) at Apache.NMS.ActiveMQ.OpenWire.BaseDataStreamMarshaller.LooseMarshalString(String value, BinaryWriter dataOut) at Apache.NMS.ActiveMQ.OpenWire.V2.ConnectionIdMarshaller.LooseMarshal(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut) at Apache.NMS.ActiveMQ.OpenWire.OpenWireFormat.LooseMarshalNestedObject(DataStructure o, BinaryWriter dataOut) at Apache.NMS.ActiveMQ.OpenWire.BaseDataStreamMarshaller.LooseMarshalCachedObject(OpenWireFormat wireFormat, DataStructure o, BinaryWriter dataOut) at Apache.NMS.ActiveMQ.OpenWire.V2.ConnectionInfoMarshaller.LooseMarshal(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut) at Apache.NMS.ActiveMQ.OpenWire.OpenWireFormat.Marshal(Object o, BinaryWriter ds) at Apache.NMS.ActiveMQ.Transport.Tcp.TcpTransport.Oneway(Command command) : Transport connection error: Index and length must refer to a location within the string. Parameter name: length ``` Does anyone has any idea what's going on? I'm using Apache ActiveMQ version 5.2.0 (fresh download from their web site).
I tried the exact same thing you have here and it seemed to work. Someone on the intraweb responded to your request on Nabble that there was a bug (where?) that was fixed. Maybe download the latest version of Apache.NMS/Apache.NMS.ActiveMQ and try again. Apache.NMS comes with [Spring.NET](http://www.springframework.net/download.html) - that's probably the best and easiest way to get Apache.NMS.
Well, the problem is solved. It took a while but with the help of the post that Andy White sent I was able to get it up and running just the way I wanted. The problem was of course that those libraries currently available at <http://svn.apache.org/viewvc/activemq/activemq-dotnet/> are simply broken and don't work at all. Thank you Andy!
Apache ActiveMQ access without Spring.NET
[ "", "c#", "apache", "activemq-classic", "" ]
I want to come up with a binary format for passing data between application instances in a form of POFs (Plain Old Files ;)). Prerequisites: 1. should be cross-platform 2. information to be persisted includes a single POJO & arbitrary byte[]s (files actually, the POJO stores it's names in a String[]) 3. only sequential access is required 4. should be a way to check data consistency 5. should be small and fast 6. should prevent an average user with archiver + notepad from modifying the data Currently I'm using DeflaterOutputStream + OutputStreamWriter together with InflaterInputStream + InputStreamReader to save/restore objects serialized with XStream, one object per file. Readers/Writers use UTF8. Now, need to extend this to support the previously described. My idea of format: ``` {serialized to XML object} {delimiter} {String file name}{delimiter}{byte[] file data} {delimiter} {another String file name}{delimiter}{another byte[] file data} ... {delimiter} {delimiter} {MD5 hash for the entire file} ``` 1. Does this look sane? 2. What would you use for a delimiter and how would you determine it? 3. The right way to calculate MD5 in this case? 4. What would you suggest to read on the subject? TIA.
It looks INsane. * why invent a new file format? * why try to prevent only stupid users from changing file? * why use a binary format ( hard to compress ) ? * why use a format that cannot be parsed while being received? (receiver has to receive entire file before being able to act on the file. ) * XML is already a serialization format that is compressable. So you are serializing a serialized format.
1) Does this look sane? It looks fairly sane. However, if you are going to invent your own format rather than just using [Java serialization](http://java.sun.com/developer/technicalArticles/Programming/serialization/) then you should have a good reason. Do you have any good reasons (they do exist in some cases)? One of the standard reasons for using XStream is to make the result human readable, which a binary format immediately loses. Do you have a good reason for a binary format rather than a human readable one? See [this question](https://stackoverflow.com/questions/568671) for why human readable is good (and bad). Wouldn't it be easier just to put everything in a signed jar. There are already [standard Java libraries](http://java.sun.com/docs/books/tutorial/deployment/jar/apiindex.html) and [tools](http://java.sun.com/docs/books/tutorial/deployment/jar/) to do this, and you get compression and verification provided. 2) What would you use for a delimiter and how determine it? Rather than a delimiter I'd explicitly store the length of each block before the block. It's just as easy, and prevents you having to escape the delimiter if it comes up on its own. 3) The right way to calculate MD5 in this case? There is [example code here](http://www.java2s.com/Tutorial/Java/0490__Security/MD5MessageDigestyourmessage.htm) which looks sensible. 4) What would you suggest to read on the subject? On the subject of serialization? I'd read about the Java serialization, [JSON](http://www.json.org/), and XStream serialization so I understood the pros and cons of each, especially the benefits of human readable files. I'd also look at a classic file format, for example from Microsoft, to understand possible design decisions from back in the days that every byte mattered, and how these have been extended. For example: [The WAV file format](http://ccrma.stanford.edu/courses/422/projects/WaveFormat/).
Developing a (file) exchange format for java
[ "", "java", "serialization", "binary", "format", "" ]
I am working on a ASP.Net project creating a Outlook like calendar scheduler app. I need to implement javascript on the webpages, but VS 2005 that I am using now is not very helpful, like intellisense or debugging,etc.. in case of javascript. I am planning to use jQuery in the app too. Questions : 1. Is there some feature of VS 2005 that helps in javascript, that i dont know, or should I move to VS 2008 (is it better than VS 2005 in this regard?) ? 2. And also tell me a good IDE to practice javascript, in a HTML-Javascript environment. I am not going to use Rails or PHP or python. Thanks.
It would be helpful for you to provide details on what sort of "help" you're looking for. VS2008 has better JavaScript support than VS2005 in general, including JavaScript debugging. [Here's a link from Scott Guthrie about VS2008 JavaScript support](http://weblogs.asp.net/scottgu/archive/2007/07/19/vs-2008-javascript-debugging.aspx). With jQuery, you can add intellisense to Visual Studio to help you out. [Here's another link to a post from Scott Guthrie](http://weblogs.asp.net/scottgu/archive/2008/11/21/jquery-intellisense-in-vs-2008.aspx) about enabling the intellisense.
I agree that VS 2008 is much better for the environment you are considering, as you can easily add intellisense support for jQuery. VS 2008 can also debug inside it's own webserver or IIS which means that it's very easy to test your environment. For our projects we use VS 2008 and code using the MVC framework which has incorporated jQuery. I run each web project inside the debug environment before we deploy to IIS for final testing. I use firebug to debug JS in Firefox, Chrome and safari have their own debuggers and VS 2008 handles IE for me. Another nice feature of VS 2008 is the ability to publish projects to a specific location copying only the required files. I wouldn't want to publish to a live environment but to create the required files within the final testing environment first is a much needed time saver.
IDE Suggestion required.Envionment : ASP.NET-VB-JAVASCRIPT
[ "", "asp.net", "javascript", "visual-studio", "ide", "" ]
I have in the database words that include special character (in Spanish mostly, like tildes). In the database everything is saved and shown correctly with PHPmyAdmin, but when I get the data (using PHP) and display it in a browser, I get a weird character, like a "?" with a square... I need a general fix so I don't need to escape each character every time, and also I would be able to insert special Spanish characters from a PHP form into the database... The HTML is correct: ``` <meta http-equiv="content-type" content="text/html; charset=utf-8" /> ``` All tables and databas are set to utf8\_spanish The character I get: � Any suggestions??? Thanks!!!
Changed the HTML charset to ISO-8859-1 fixed the problem! Silly
I'd just like to provide some more details on the solution proposed by [vartec](https://stackoverflow.com/questions/633762/special-characters-in-php-mysql/633788#633788) which is (depending on your MySQL installation) the most correct solution to your problem. First of all the character set / encoding issue in MySQL is a somewhat complex subject which is extensively covered in the MySQL manual [Chapter 9.1 "Character Set Support"](http://dev.mysql.com/doc/refman/5.1/en/charset.html). In your case especially [9.1.4. "Connection Character Sets and Collations"](http://dev.mysql.com/doc/refman/5.1/en/charset-connection.html) will be most relevant. To make it short: MySQL must know which character set / encoding your client application (talking from the database persoective that's your PHP script) is expecting as it'll transcode all the string data from the internal character set / encoding defined at server-, database-, table- or column-level into the connection character set / encoding. You're using UTF-8 on the client side so must tell MySQL that you use UTF-8. This is done by the MySQL command `SET NAMES 'utf8'` which must be sent as the first query on opening a connection. Depending on your installation and on the MySQL client library you use in the PHP script this can be done automatically on each connect. If you use PDO it's just a matter of setting a configuration parameter ``` $db = new PDO($dsn, $user, $password); $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'"); ``` Using mysqli changing the client character set / encoding is even more simple: ``` $mysqli = new mysqli("localhost", "user", "password", "db"); $mysqli->set_charset("utf8"); ``` I hope that will help to make the whole thing more understandable.
Special characters in PHP / MySQL
[ "", "php", "mysql", "special-characters", "" ]
I am wondering how people use STL (No fancy boost)... just an ol' fashion STL. Tricks/tips/mostly used cases acquired over many, many years... and perhaps gotchas...
I use the STL in almost all of my projects, for things from loops (with iterators) to splitting up the input into a program. Tokenise an input string by spaces and input the result into an std::vector for parsing later: ``` std::stringstream iss(input); std::vector<std::string> * _input = new std::vector<std::string>(); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(*_input)); ``` Other favourites off course are std::reverse and various other algorithms defined in `<algorithm>`.
My favourite is the following to change anything streamable to a string: ``` template <class TYPE> std::string Str( const TYPE & t ) { std::ostringstream os; os << t; return os.str(); } ``` Then: ``` string beast = Str( 666 ); ```
Most used STL algorithm, predicates, iterators
[ "", "c++", "stl", "" ]
I want to fill these containers pretty quickly with some data for testing. What are the best and quick ways to do that? It shouldn't be too convoluted, and thus and inhumanly short, but also NOT to verbose **Edit** Guys I thought you can do something with memset knowning that vector has an underlining array? Also, what about map?
If you already have the initial data laying around, say in a C style array, don't forget that these STL containers have "2-iterator constructors". ``` const char raw_data[100] = { ... }; std::vector<char> v(raw_data, raw_data + 100); ``` **Edit**: I was asked to show an example for a map. It isn't often you have an array of pairs laying around, but in the past I have created a Python script that generated the array of pairs from a raw data file. I then #include this code-generated structure and initalized a map with it like this: ``` #include <map> #include <string> #include <utility> using namespace std; typedef map<string, int> MyMap; // this array may have been generated from a script, for example: const MyMap::value_type raw_data[2] = { MyMap::value_type("hello", 42), MyMap::value_type("world", 88), }; MyMap my_map(raw_data, raw_data + 2); ``` Alternatively if you have an array of keys, and and array of data values, you can loop over them, calling map.insert(make\_pair(key, value)); You also ask about memset and vector. I don't think there is any real merit to using memset to initialize a vector, because vectors can be given an initial value for all their elements via the constructor: ``` vector<int> v2(100, 42); // 100 ints all with the value of 42 vector<string> v(42, "initial value"); // 42 copies of "initial value" ```
* boost assignment library way (<http://www.boost.org/doc/libs/1_38_0/libs/assign/doc/index.html>) using namespace boost::assign; std::vector< int > v; v += 1,2,3,4,5,6,7,8,9; std::map< std::string, int > m; insert( m )( "Bar", 1 )( "Foo", 2 ); vector< int > v; v += 1, 2, repeat\_fun(4, &rand), 4; * std::generate or std::generate\_n * std::backinserter - sometimes will help you
Quick way to fill vector, map, and set, using stl functions
[ "", "c++", "stl", "" ]
We are using the jdbc-odbc bridge to connect to an MS SQL database. When perform inserts or updates, strings are put into the database padded to the length of the database field. Is there any way to turn off this behavior (strings should go into the table without padding)? For reference, we are able to insert field values that don't contain the padding using the SQL management tools and query analyzer, so I'm pretty sure this is occuring at the jdbc or odbc layer of things. EDIT: The fields in the database are listed as nvarchar(X), where X = 50, 255, whatever EDIT 2: The call to do the insert is using a prepared statement, just like: ``` PreparedStatement stmt = new con.prepareStatement("INSERT INTO...."); stmt.setString(1, "somevalue"); ```
How are you setting the String? Are you doing?: ``` PreparedStatement stmt = new con.prepareStatement("INSERT INTO...."); stmt.setString(1, "somevalue"); ``` If so, try this: ``` stmt.setObject(1, "somevalue", Types.VARCHAR); ``` Again, this is just guessing without seeing how you are inserting.
If you can make your insert to work with regular SQL tools ( like ... I don't know Toad for MS SQL Sever or something ) then changing the driver should do. Use Microsoft SQL Server JDBC type IV driver. Give this link a try <http://www.microsoft.com/downloads/details.aspx?familyid=F914793A-6FB4-475F-9537-B8FCB776BEFD&displaylang=en> Unfortunately these kinds of download comes with a lot of garbage. There's an install tool and another hundreds of file. Just look for something like: intalldir\lib\someSingle.jar Copy to somewhere else and uninstall/delete the rest. I did this a couple of months ago, unfortunately I don't remeber exactly where it was. **EDIT** Ok, I got it. Click on the download and at the end of the page click on "I agree and want to download the UNIX version" This is a regular compressed file ( use win rar or other ) and there look for that sigle jar. That should work.
Prevent jdbc from padding strings on sql insert and update
[ "", "java", "jdbc", "odbc", "" ]
Ok, so on a web page, I've got a JavaScript object which I'm using as an associative array. This exists statically in a script block when the page loads: ``` var salesWeeks = { "200911" : ["11 / 2009", "Fiscal 2009"], "200910" : ["10 / 2009", "Fiscal 2009"], "200909" : ["09 / 2009", "Fiscal 2009"], "200908" : ["08 / 2009", "Fiscal 2009"], "200907" : ["07 / 2009", "Fiscal 2009"], "200906" : ["06 / 2009", "Fiscal 2009"], "200905" : ["05 / 2009", "Fiscal 2009"], "200904" : ["04 / 2009", "Fiscal 2009"], "200903" : ["03 / 2009", "Fiscal 2009"], "200902" : ["02 / 2009", "Fiscal 2009"], "200901" : ["01 / 2009", "Fiscal 2009"], "200852" : ["52 / 2008", "Fiscal 2009"], "200851" : ["51 / 2008", "Fiscal 2009"] }; ``` The order of the key/value pairs is intentional, as I'm turning the object into an HTML select box such as this: ``` <select id="ddl_sw" name="ddl_sw"> <option value="">== SELECT WEEK ==</option> <option value="200911">11 / 2009 (Fiscal 2009)</option> <option value="200910">10 / 2009 (Fiscal 2009)</option> <option value="200909">09 / 2009 (Fiscal 2009)</option> <option value="200908">08 / 2009 (Fiscal 2009)</option> <option value="200907">07 / 2009 (Fiscal 2009)</option> <option value="200906">06 / 2009 (Fiscal 2009)</option> <option value="200905">05 / 2009 (Fiscal 2009)</option> <option value="200904">04 / 2009 (Fiscal 2009)</option> <option value="200903">03 / 2009 (Fiscal 2009)</option> <option value="200902">02 / 2009 (Fiscal 2009)</option> <option value="200901">01 / 2009 (Fiscal 2009)</option> <option value="200852">52 / 2008 (Fiscal 2009)</option> <option value="200851">51 / 2008 (Fiscal 2009)</option> </select> ``` ...with code that looks like this (snipped from a function): ``` var arr = []; arr.push( "<select id=\"ddl_sw\" name=\"ddl_sw\">" + "<option value=\"\">== SELECT WEEK ==</option>" ); for(var key in salesWeeks) { arr.push( "<option value=\"" + key + "\">" + salesWeeks[key][0] + " (" + salesWeeks[key][1] + ")" + "<\/option>" ); } arr.push("<\/select>"); return arr.join(""); ``` This all works fine in IE, FireFox and Opera. However in Chrome, the order comes out all weird: ``` <select id="ddl_sw" name="ddl_sw"> <option value="">== SELECT WEEK ==</option> <option value="200852">52 / 2008 (Fiscal 2009)</option> <option value="200908">08 / 2009 (Fiscal 2009)</option> <option value="200906">06 / 2009 (Fiscal 2009)</option> <option value="200902">02 / 2009 (Fiscal 2009)</option> <option value="200907">07 / 2009 (Fiscal 2009)</option> <option value="200904">04 / 2009 (Fiscal 2009)</option> <option value="200909">09 / 2009 (Fiscal 2009)</option> <option value="200903">03 / 2009 (Fiscal 2009)</option> <option value="200905">05 / 2009 (Fiscal 2009)</option> <option value="200901">01 / 2009 (Fiscal 2009)</option> <option value="200910">10 / 2009 (Fiscal 2009)</option> <option value="200911">11 / 2009 (Fiscal 2009)</option> <option value="200851">51 / 2008 (Fiscal 2009)</option> </select> ``` NOTE: This order, though weird, does not change on subsequent refreshes. It's always in this order. So, what is Chrome doing? Some optimization in how it processes the loop? In the first place, am I wrong to rely on the order that the key/value pairs are declared in *any* associative array? I never questioned it before, I just assumed the order would hold because this technique has always worked for me in the other browsers. But I suppose I've never seen it stated anywhere that the order is guaranteed. Maybe it's not? Any insight would be awesome. Thanks.
Think of an associative array as a paper sack into which all the key-value pairs are placed. As you reach your hand into the sack to look at the pairs (such as with the for...in loop), the order that you encounter them is for all practical purposes random. If you want to see them in a specific order, you'll need to extract the keys into an array and sort it. Then walk across the array, using the keys you encounter to index into the associative array.
The order in which elements are stored in an associative array is not guaranteed. You'll have to sort your output explicitly.
Google Chrome: JavaScript associative arrays, evaluated out of sequence
[ "", "javascript", "google-chrome", "associative-array", "" ]
When you need to have very small objects, say that contains 2 float property, and you will have millions of them that aren't gonna be "destroyed" right away, are structs a better choice or classes? Like in xna as a library, there are point3s, etc as structs but if you need to hold onto those values for a long time, would it pose a performance threat?
Contrary to most questions about structs, this actually seems to be a good use of a struct. If the data it contains are value types, and you are going to use a lot of these, a structure would work well. Some tips: :: The struct should not be larger than 16 bytes, or you lose the performance advantages. :: Make the struct immutable. That makes the usage clearer. Example: ``` public struct Point3D { public float X { get; private set; } public float Y { get; private set; } public float Z { get; private set; } public Point3D(float x, float y, float z) { X = x; Y = y; Z = z; } public Point3D Invert() { return new Point3D(-X, -Y, -Z); } } ```
The answer depends on where the objects/values will eventually be stored. If they are to be stored in an untyped collection like ArrayList, then you end up boxing them. Boxing creates an object wrapper for a struct and the footprint is the same as with a class object. On the other hand if you use a typed array like T[] or List, then using structs will only store the actual data for each element with footprint for entire collection only and not its elements. So structs are more efficient for use in T[] arrays.
Struct vs Class for long lived objects
[ "", "c#", ".net", "class", "struct", "" ]
Appart from projects funded/pushed by MS itself, are there any real-world examples of projects that opted for Silverlight? What were your experiences? Learning curve? Advantages? Resources? Pitfalls? Sacrifices? --EDIT-- I'm most interested in the developing (team)'s story.
I've just reviewed the [Silverlight showcase for the UK](http://silverlight.net/showcase/?appid=983&country=GB), an IT market I know pretty well, there are 31 apps featured and the break down looks like this 8 x Games = 26%, 6 x Experiments and fun = 19% - eg christmas cards and Xaml XEyes, 6 x Demos = 19% - eg a Deepzoom picture, 11 x Reasonable web sites = 36% Realistically 31 apps for the whole of the UK, of which only around a third are real, is a tiny amount of development. This could indicate a couple of things, 1) Serious Silverlight development isn't happening in the UK, but maybe is elsewhere 2) Companies doing serious silverlight dev don't want to use Microsoft's showcase 3) There isn't much serious Silverlight development happening yet My gut feel is that Silverlight is taking a while to become mainstream, it's a brilliant technology, but users don't buy technology or features, they buy benefits .... We need a couple of killer Silverlight apps, then it will take off like Ajax did, once google (and others) showed the way
I was at a conference last week, and a number of non-MS people were telling their experiences of using Silverlight for line-of-business apps. Generally, it seemed positive. The advantage seemed that you could start with the Silverlight version, and then if you (later) needed more client control, *mostly* just copy the xaml and app code into WPF. **mostly** is important, as there are currently some glitches. But it is much harder to start with WPF and port to Silverlight ;-p Sacrifices? Not as much power over the client. Limited framework, etc. Pitfalls? Not-quite-compatible xaml. Different IO, etc. I can't cite specific projects, as I simply didn't write them down ;-p Besides, they might be company-private. Knowing that they exist doesn't violate NDA ;-p
Any real Silverlight projects?
[ "", "c#", ".net", "silverlight", "" ]
Assume that you have an idCollection `IList<long>` and you have a method to get 4 unique ids.Every time you call it, it gives you random 4 unique ids ? ``` var idCollec = new[] {1,2,3,4,5,6,7,8,9,10,11,12}.ToList(); For example {2,6,11,12} {3,4,7,8} {5,8,10,12} ... .. ``` What is the smartest way to do it ? Thanks
Seems like easiest way would be to have something like: ``` if(idCollection.Count <4) { throw new ArgumentException("Source array not long enough"); } List<long> FourUniqueIds = new List<long>(4); while(FourUniqueIds.Count <4) { long temp = idCollection[random.Next(idCollection.Count)]; if(!FourUniqueIds.Contains(temp)) { FourUniqueIds.add(temp); } } ```
It can be done with a nice LINQ query. The key to doing it without the risk of getting duplicates, is to create a never ending IEnumerable of random integers. Then you can take n distinct values from it, and use them as indexes into the list. Sample program: ``` using System; using System.Collections.Generic; using System.Linq; namespace TestRandom { class Program { static void Main(string[] args) { // Just to prepopulate a list. var ids = (from n in Enumerable.Range(0, 100) select (long)rand.Next(0, 1000)).ToList(); // Example usage of the GetRandomSet method. foreach(long id in GetRandomSet(ids, 4)) Console.WriteLine(id); } // Get count random entries from the list. public static IEnumerable<long> GetRandomSet(IList<long> ids, int count) { // Can't get more than there is in the list. if ( count > ids.Count) count = ids.Count; return RandomIntegers(0, ids.Count) .Distinct() .Take(count) .Select(index => ids[index]); } private static IEnumerable<int> RandomIntegers(int min, int max) { while (true) yield return rand.Next(min, max); } private static readonly Random rand = new Random(); } ``` } If you use this approach, make sure you do not try to take more distinct values than there are available in the range passed to RandomIntegers.
What is the easiest way to get 4(or any count) random unique ids from an id collection with c#?
[ "", "c#", "asp.net", "generics", "c#-3.0", "" ]
The following query returns a single row, as desired. The 'contracts' table has 6 fields, each with a different username in it, for which I want to retrieve first/last names from a separate 'users' table. This works fine, but is there something more concise? I'm think the solution must be something using GROUP BY contracts.id to keep it one row, but I can't seem to find anything better than this slew of sub-selects. Help! ``` SELECT contracts.field1, contracts.field2, (SELECT first_name FROM users WHERE username = service_provider_1), (SELECT last_name FROM users WHERE username = service_provider_1), (SELECT first_name FROM users WHERE username = service_provider_2), (SELECT last_name FROM users WHERE username = service_provider_2), (SELECT first_name FROM users WHERE username = service_org_business_contact), (SELECT last_name FROM users WHERE username = service_org_business_contact), (SELECT first_name FROM users WHERE username = client_service_contact_1), (SELECT last_name FROM users WHERE username = client_service_contact_1), (SELECT first_name FROM users WHERE username = client_service_contact_2), (SELECT last_name FROM users WHERE username = client_service_contact_2), (SELECT first_name FROM users WHERE username = client_business_contact), (SELECT last_name FROM users WHERE username = client_business_contact) FROM contracts WHERE id = ? ``` It wouldn't be so bad if I could get *both* first/last name from a single sub-select... so even with a cruddy sub-select solution I have twice the verbosity I should think I need... EDIT: I get it now. The answer to being able to join to the same table multiple times is to use an alias for the table. Thank folks! New code is: ``` SELECT contracts.field1, contracts.field2, sp1.first_name, sp1.last_name, sp2.first_name, sp2.last_name, sobc.first_name, sobc.last_name, csc1.first_name, csc1.last_name, csc2.first_name, csc2.last_name, cbc.first_name, cbc.last_name FROM contracts JOIN users AS sp1 ON service_provider_1 = sp1.username JOIN users AS sp2 ON service_provider_2 = sp2.username JOIN users AS sobc ON service_org_business_contact = sobc.username JOIN users AS csc1 ON client_service_contact_1 = csc1.username JOIN users AS csc2 ON client_service_contact_2 = csc2.username JOIN users AS cbc ON client_business_contact = cbc.username WHERE contracts.id = ? ``` Sadly, using joins is almost as verbose as using the subselects, but I assume it might be faster?
``` SELECT contracts.field1, contracts.field2, sp1.first_name, sp1.last_name sp2.first_name, sp2.last_name, /* etc, etc */ FROM contracts INNER JOIN users sp1 ON contracts.id = sp1.id AND sp1.username = service_provider_1 INNER JOIN users sp2 ON contracts.id = sp2.id AND sp2.username = service_provider_2 INNER JOIN users sobc ON contracts.id = sobc.id AND sobc.username = service_org_business_contact INNER JOIN /* etc, etc */ WHERE contracts.id = @myid ``` did you also want to combine `first_name` and `last_name` for each username? You can do this like ``` RTRIM(sp1.first_name) + ' ' + RTRIM(sp1.last_name) as sp1_name ``` in your SELECT clause. The RTRIM are necessary if the data type is (N)CHAR, not necessary if the type is (N)VARCHAR **EDIT:** As stated in the comments on [this answer](https://stackoverflow.com/questions/558316/how-do-i-condense-this-sql-of-multiple-sub-selects-into-something-more-sane/558333#558333), the JOIN on id is probably not necessary, in which case it becomes ``` SELECT contracts.field1, contracts.field2, sp1.first_name, sp1.last_name sp2.first_name, sp2.last_name, /* etc, etc */ FROM contracts INNER JOIN users sp1 ON sp1.username = service_provider_1 INNER JOIN users sp2 ON sp2.username = service_provider_2 INNER JOIN users sobc ON sobc.username = service_org_business_contact INNER JOIN /* etc, etc */ WHERE contracts.id = @myid ``` My layout probably makes it appear longer! You may need to use LEFT OUTER JOINS if it is possible to have a contract record that doesn't have a `first_name` and `last_name` for one of it's fields within the users table.
Why not join to the users table 6 times?
How do I condense this SQL of multiple sub-selects into something more sane?
[ "", "sql", "mysql", "" ]
I need to automatically generate a PDF file from an exisiting (X)HTML-document. The input files (reports) use a rather simple, table-based layout, so support for really fancy JavaScript/CSS stuff is probably not needed. As I am used to working in Java, a solution that can easily be used in a java-project is preferable. It only needs to work on windows systems, though. One way to do it that is feasable, but does not produce good quality output (at least out of the box) is using [CSS2XSLFO](http://re.be/css2xslfo/index.xhtml), and Apache FOP to create the PDF files. The problem I encountered was that while CSS-attributes are converted nicely, the table-layout is pretty messed up, with text flowing out of the table cell. I also took a quick look at Jrex, a Java-API for using the Gecko rendering engine. Is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a PDF-Printer tool automatically? I have no experience in OLE programming in windows, so I have no clue what's possible and what is not. Do you have an idea?
The [Flying Saucer](https://github.com/flyingsaucerproject/flyingsaucer) XHTML renderer project has support for outputting XHTML to PDF. Have a look at an example [here](https://web.archive.org/web/20150905173204/http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html).
Did you try [WKHTMLTOPDF](http://wkhtmltopdf.org/)? It's a simple shell utility, an open source implementation of WebKit. Both are free. We've set a small tutorial [here](http://beebole.com/blog/erlang/convert-html-to-pdf-with-full-css-support-an-opensource-alternative-based-on-webkit/) **EDIT( 2017 ):** If it was to build something today, I wouldn't go that route anymore. But would use <http://pdfkit.org/> instead. Probably stripping it of all its nodejs dependencies, to run in the browser.
Converting HTML files to PDF
[ "", "java", "html", "pdf", "pdf-generation", "" ]
Can anyone provide an example of how to loop through a System.DirectoryServices.PropertyCollection and output the property name and value? I am using C#. @JaredPar - The PropertyCollection does not have a Name/Value property. It does have a PropertyNames and Values, type System.Collection.ICollection. I do not know the basline object type that makes up the PropertyCollection object. @JaredPar again - I originally mislabeled the question with the wrong type. That was my bad. **Update:** Based on Zhaph - Ben Duguid input, I was able to develop the following code. ``` using System.Collections; using System.DirectoryServices; public void DisplayValue(DirectoryEntry de) { if(de.Children != null) { foreach(DirectoryEntry child in de.Children) { PropertyCollection pc = child.Properties; IDictionaryEnumerator ide = pc.GetEnumerator(); ide.Reset(); while(ide.MoveNext()) { PropertyValueCollection pvc = ide.Entry.Value as PropertyValueCollection; Console.WriteLine(string.Format("Name: {0}", ide.Entry.Key.ToString())); Console.WriteLine(string.Format("Value: {0}", pvc.Value)); } } } } ```
The PropertyCollection has a PropertyName collection - which is a collection of strings (see [PropertyCollection.Contains](http://msdn.microsoft.com/en-us/library/system.directoryservices.propertycollection.contains.aspx) and [PropertyCollection.Item](http://msdn.microsoft.com/en-us/library/system.directoryservices.propertycollection.item.aspx) both of which take a string). You can usually call [GetEnumerator](http://msdn.microsoft.com/en-us/library/system.directoryservices.propertycollection.getenumerator.aspx) to allow you to enumerate over the collection, using the usual enumeration methods - in this case you'd get an IDictionary containing the string key, and then an object for each item/values.
See the value of PropertyValueCollection at runtime in the watch window to identify types of element, it contains & you can expand on it to further see what property each of the element has. Adding to @JaredPar's code ``` PropertyCollection collection = GetTheCollection(); foreach ( PropertyValueCollection value in collection ) { // Do something with the value Console.WriteLine(value.PropertyName); Console.WriteLine(value.Value); Console.WriteLine(value.Count); } ``` EDIT: PropertyCollection is made up of [PropertyValueCollection](http://msdn.microsoft.com/en-us/library/system.directoryservices.propertycollection.item.aspx)
How do I loop through a PropertyCollection
[ "", "c#", "asp.net", "iis", "directoryservices", "" ]
I'm trying to read an Excel file (Office 2003). There is an Excel file that needs to be uploaded and its contents parsed. Via Google, I can only find answers to these related (and insufficient topics): generating Excel files, reading Excel XML files, reading Excel CSV files, or incomplete abandoned projects. I own Office 2003 so if I need any files from there, they are available. It's installed on my box but isn't and can't be installed on my shared host. **Edit:** so far all answers point to [PHP-ExcelReader](https://sourceforge.net/projects/phpexcelreader/) and/or [this additional article](https://devzone.zend.com/27/reading-and-writing-spreadsheets-with-php/) about how to use it.
I use [PHP-ExcelReader](http://sourceforge.net/projects/phpexcelreader/) to read xls files, and works great.
You have 2 choices as far as I know: 1. [Spreadsheet\_Excel\_Reader](http://sourceforge.net/projects/phpexcelreader/), which knows the Office 2003 binary format 2. [PHPExcel](https://github.com/PHPOffice/PHPExcel), which knows both Office 2003 as well as Excel 2007 (XML). (Follow the link, and you'll see they upgraded this library to [PHPSpreadSheet](https://github.com/PHPOffice/PhpSpreadsheet)) PHPExcel uses Spreadsheet\_Excel\_Reader for the Office 2003 format. Update: I once had to read some Excel files but I used the Office 2003 XML format in order to read them and told the people that were using the application to save and upload only that type of Excel file.
Reading an Excel file in PHP
[ "", "php", "import-from-excel", "" ]
Is there any way to know in C# the type of application that is running. Windows Service ASP.NET Windows Form Console I would like to react to the application type but cannot find a way to determine it.
You should have the client code tell your code what the context is and then work from that. At best, you will be able to guess based on external factors. If you must guess, this is what I would look for: * For ASP.NET, I would look for HttpContext.Current * For Windows Forms, I see if the static OpenForms collection on the Application class has any items in it. * For Windows Presentation Foundation, see if the static Current property on the Application class is not null. * For a service, there really is no way to determine this, since services do not have to register process handles, thread handles, or the like. * For console windows, if none of the above is true, then I would assume this is a console.
Try checking [`Application.MessageLoop`](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.messageloop.aspx). It *should* be true for Windows Forms applications (that have a WinForms message loop), and false for windows services. I don't know what it would return for ASP.NET. As for console applications, they would have no message loop so they would return false. You can check for that using most properties in the [`Console`](http://msdn.microsoft.com/en-us/library/system.console_members.aspx) class, but I warn you that it's a HACK. If you *must*, I'd go with: ``` bool isConsole = Console.In != StreamReader.Null; ``` Note, that a console app could still call `Console.SetIn(StreamReader.Null)` or a windows app could call `Console.SetIn(something else`), so this is easily tricked.
Work out the type of c# application a class contained in a DLL is being used by
[ "", "c#", ".net", "dll", "assemblies", "types", "" ]
I recently upgraded an ASP.NET app to .NET 3.5 and switched to the newer version of the ASP.NET AJAX library. In FireFox and IE7, everything works great, in IE6, anything that would perform a callback (Partial Refresh, or calling a PageMethod/WebMethod) throws an error: ``` Object Doesn't support this property or method Line: 5175 Char: 9 ``` Is there a known compatibility issue with .NET 3.5 and IE6? EDIT: I attached a debugger to IE6 and was able to find the exact line it is breaking on: ``` this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), true /*async*/); ``` It appears that IE6 is denying the permission to do "open". This is not a cross-site request, so I am puzzled. This site is currently running on a fake hostname mapped to a local server, and not on an actual domain, but I don't think that should make a difference. EDIT: I added a bounty, this bug is still driving me nuts...HALP! EDIT: Solution found! This [forum post](http://forums.asp.net/p/1326906/2944515.aspx) made me curious enough to search for MXSML, and sure enough, there it was, a typo in the framework library. MsXML was typed as MXsml. Of course, when dealing with assembly scripts, you can't do much to fix them, but I installed SP1 hoping that they were corrected there. They were...So, if you have this issue, install .NET 3.5 SP1 and it will go away. Woo!
How are you testing in IE6? I have come across several javascript errors when you using anything but a clean install of only IE6 in conjunction with the asp.net ajax libraries. (ie. the asp.net ajax libraries don't support multiple installs of IE, or even [IETester](http://www.my-debugbar.com/wiki/IETester/HomePage)) It is something in the IE security model that makes things go haywire when multiple version's of IE are used. You'll find that cookies won't work right either in anything but the "installed" version of IE on the system you are running. You may also look here for some [more information](http://tredosoft.com/Multiple_IE) on multiple IE installs. If found the comments to be particularly helpful! **UPDATE** I was able to dig, this up in the [asp.net fourms](http://forums.asp.net/p/1326906/2944515.aspx). That's the only other thing I could find. May not be too be too helpful, but it at least sounds about like what you are hitting.
According to [MSDN](http://msdn.microsoft.com/en-us/library/bb470452.aspx) IE6 is supported. Make sure that the Internet Zone in the Security Zones settings are set to Medium.
ASP.NET AJAX 3.5 and IE6?
[ "", "javascript", ".net-3.5", "asp.net-ajax", "internet-explorer-6", "" ]
When a user signs up in our Struts application, we want to send them an email that includes a link to a different page. The link needs to include a unique identifier in its query string so the destination page can identify the user and react accordingly. To improve the security of this system, I'd like to first encrypt the query string containing the identifier and second set the link to expire--after it's been used and/or after a few days. What Java technologies/methods would you suggest I use to do this?
I'm going to make some assumptions about your concerns: 1. A user should not be able to guess another user's URL. 2. Once used, a URL should not be reusable (avoiding session replay attacks.) 3. Whether used or not, a URL shouldn't live forever, thus avoiding brute-force probing. Here's how I'd do it. * Keep the user's ID and the expiration timestamp in a table. * Concatenate these into a string, then make an SHA-1 hash out of it. * Generate a URL using the SHA-1 hash value. Map all such URLs to a servlet that will do the validation. * When someone sends you a request for a page with the hash, use it to look up the user and expiration. * After the user has done whatever the landing page is supposed to do, mark the row in the database as "used". * Run a job every day to purge rows that are either used or past their expiration date.
For the first part have a look at [[Generating Private, Unique, Secure URLs](https://stackoverflow.com/questions/599535/generating-private-unique-secure-urls)](https://stackoverflow.com/questions/599535/generating-private-unique-secure-urls). For the expiration, you simply need to store the unique key creation timestamp in the database and only allow your action to execute when for example now-keyCreatedAt<3 days. Another way is to have a cron or [Quartz](http://www.quartz-scheduler.org/) job periodically delete those rows which evaluate true for "now-keyCreatedAt<3 days".
What's the best way to secure a query string with Java?
[ "", "java", "security", "url", "encryption", "" ]
Is there a way to find a value in DataTable in C# without doing row-by-row operation? The value can be a part of (a substring of row[columnName].value , separated by comma) a cell in the datatable and the value may be present in any one of columns in the row.
A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter. Looking at your requirement your filterexpression will have to be somewhat general to make this work. ``` myDataTable.Select("columnName1 like '%" + value + "%'"); ```
Maybe you can filter rows by possible columns like this : ``` DataRow[] filteredRows = datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value)); ```
Find a value in DataTable
[ "", "c#", "datatable", "" ]
I am developing mobile apps for some time in .NET and I was always wondering if the grass is greener on the other side (Java). Thus, I would like to ask your opinion about which one you prefer for your mobile apps and why is that so.
The main advantage of using Java is the broader installed base. If you use Java, you are going to reach orders of magnitude more phones than if you use .NET. As far as I know, .NET works exclusively with Windows Mobile phones. On the other hand, Mobile .NET is easier than Java (IMHO), and that's partly because of Visual Studio IDE which makes life so much simpler than any other development environment on the Java World. For example, doing Form Based applications in .NET mobile is really straightforward and simple. So, the answer will basically depend on what you are trying to accomplish: * Trying to reach to the biggest number of mobile devices: go with Java * Trying to develop an application for Windows Mobile devices: go with .NET * Trying to develop an application that will run only on a controlled environment (A single business) where you get to decide the devices it will run on: decide which device you are going to use and then pick development environment. Keep in mind that if you are talking about Java for Android or Blackberry development, you will face the same issue of not reaching to a huge installed base that you will with .NET. If you want the huge installed base, go with plain Java Mobile Edition.
I can only speak for windows mobile development stay with .net. Sun don't even release a JVM for windows mobile devices I have developed for windows devices using java and using <http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html> as my JVM which was very good the author even responded to a feature request I made.
.Net vs Java for mobile development. What's your take?
[ "", "java", ".net", "mobile", "" ]
Is it possible to read a .PST file using C#? I would like to do this as a standalone application, not as an Outlook addin (if that is possible). If have seen [other](https://stackoverflow.com/questions/318727/pst-to-csv-file-conversion) [SO](https://stackoverflow.com/questions/486883/problem-in-releasing-memory-from-an-outlook-pst-file) [questions](https://stackoverflow.com/questions/235231/how-to-avoid-outlook-security-alert-when-reading-outlook-message-from-c-program) [similar](https://stackoverflow.com/questions/466716/reading-an-outlook-2003-ost-file) to this mention [MailNavigator](http://www.mailnavigator.com/reading_ms_outlook_pst_files.html) but I am looking to do this programmatically in C#. I have looked at the [Microsoft.Office.Interop.Outlook](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.aspx) namespace but that appears to be just for Outlook addins. [LibPST](http://alioth.debian.org/projects/libpst/) appears to be able to read PST files, but this is in C (sorry Joel, I didn't [learn C before graduating](http://www.joelonsoftware.com/articles/CollegeAdvice.html)). Any help would be greatly appreciated, thanks! **EDIT:** Thank you all for the responses! I accepted Matthew Ruston's response as the answer because it ultimately led me to the code I was looking for. Here is a simple example of what I got to work (You will need to add a reference to Microsoft.Office.Interop.Outlook): ``` using System; using System.Collections.Generic; using Microsoft.Office.Interop.Outlook; namespace PSTReader { class Program { static void Main () { try { IEnumerable<MailItem> mailItems = readPst(@"C:\temp\PST\Test.pst", "Test PST"); foreach (MailItem mailItem in mailItems) { Console.WriteLine(mailItem.SenderName + " - " + mailItem.Subject); } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } private static IEnumerable<MailItem> readPst(string pstFilePath, string pstName) { List<MailItem> mailItems = new List<MailItem>(); Application app = new Application(); NameSpace outlookNs = app.GetNamespace("MAPI"); // Add PST file (Outlook Data File) to Default Profile outlookNs.AddStore(pstFilePath); MAPIFolder rootFolder = outlookNs.Stores[pstName].GetRootFolder(); // Traverse through all folders in the PST file // TODO: This is not recursive, refactor Folders subFolders = rootFolder.Folders; foreach (Folder folder in subFolders) { Items items = folder.Items; foreach (object item in items) { if (item is MailItem) { MailItem mailItem = item as MailItem; mailItems.Add(mailItem); } } } // Remove PST file from Default Profile outlookNs.RemoveStore(rootFolder); return mailItems; } } } ``` ***Note:*** This code assumes that Outlook is installed and already configured for the current user. It uses the Default Profile (you can edit the default profile by going to Mail in the Control Panel). One major improvement on this code would be to create a temporary profile to use instead of the Default, then destroy it once completed.
The Outlook Interop library is not just for addins. For example it could be used to write a console app that just reads all your Outlook Contacts. I am pretty sure that the standard Microsoft Outlook Interop library will let you read the mail - albeit it will probably throw a security prompt in Outlook that the user will have to click through. **EDITS**: Actually implementing mail reading using Outlook Interop depends on what your definition of 'standalone' means. The Outlook Interop lib requires Outlook to be installed on the client machine in order to function. ``` // Dumps all email in Outlook to console window. // Prompts user with warning that an application is attempting to read Outlook data. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Outlook = Microsoft.Office.Interop.Outlook; namespace OutlookEmail { class Program { static void Main(string[] args) { Outlook.Application app = new Outlook.Application(); Outlook.NameSpace outlookNs = app.GetNamespace("MAPI"); Outlook.MAPIFolder emailFolder = outlookNs.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); foreach (Outlook.MailItem item in emailFolder.Items) { Console.WriteLine(item.SenderEmailAddress + " " + item.Subject + "\n" + item.Body); } Console.ReadKey(); } } } ```
I went through and did the refactoring for subfolders ``` private static IEnumerable<MailItem> readPst(string pstFilePath, string pstName) { List<MailItem> mailItems = new List<MailItem>(); Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); NameSpace outlookNs = app.GetNamespace("MAPI"); // Add PST file (Outlook Data File) to Default Profile outlookNs.AddStore(pstFilePath); string storeInfo = null; foreach (Store store in outlookNs.Stores) { storeInfo = store.DisplayName; storeInfo = store.FilePath; storeInfo = store.StoreID; } MAPIFolder rootFolder = outlookNs.Stores[pstName].GetRootFolder(); // Traverse through all folders in the PST file Folders subFolders = rootFolder.Folders; foreach (Folder folder in subFolders) { ExtractItems(mailItems, folder); } // Remove PST file from Default Profile outlookNs.RemoveStore(rootFolder); return mailItems; } private static void ExtractItems(List<MailItem> mailItems, Folder folder) { Items items = folder.Items; int itemcount = items.Count; foreach (object item in items) { if (item is MailItem) { MailItem mailItem = item as MailItem; mailItems.Add(mailItem); } } foreach (Folder subfolder in folder.Folders) { ExtractItems(mailItems, subfolder); } } ```
Can I read an Outlook (2003/2007) PST file in C#?
[ "", "c#", "outlook", "outlook-2007", "outlook-2003", "pst", "" ]
I have a JFreeChart line plot that is updated dynamically with one data point for every iteration of my algorithm. Because the number of data points can quickly become very large, I have used the [setFixedAutoRange(double)](http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/axis/ValueAxis.html#setFixedAutoRange(double)) method on the domain axis. This restricts the graph to displaying the n most recent iterations (200 in my case). This works well, except during the first 200 iterations. The problem is that, until there have been 200 iterations, the axis includes negative values (for example, after 50 iterations, the range is from -150 to 50). Negative iterations make no sense. I would like the axis to start at zero rather than a negative value. How can I achieve this? I don't mind whether the axis goes from 0 to 200 initially (with the right hand part of the chart left blank until the plot fills it up) or whether it starts at 0 to 1 and grows (so that the plot is always stretched across the full width of the chart). Either would acceptable, though I have a slight preference for the former. Things I have tried: * Calling [setLowerBound](http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/axis/ValueAxis.html#setLowerBound(double)) doesn't play nicely with setFixedAutoRange. * Calling [setRangeType(RangeType.POSITIVE)](http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/axis/NumberAxis.html#setRangeType(org.jfree.data.RangeType)) doesn't seem to make any difference. Any ideas?
It looks like you're looking for a solution that involves configuring JFreeChart to do it for you, rather than manually setting the range. I can't help with that....but here are some other ugly solutions :P .... You could do something like this (sorry for the pseudo-code): ``` while(producingData) { this.produceData(); if(!allDataButton.isSelected()) { domainAxis.setRange((count < 200) ? 0 : count-200), count); } else { domainAxis.setRange(0, count); } } ``` If I were a perl-coder, I'd write it like this, just to make it a smidget harder to read :P ``` while(producingData) { this.produceData(); domainAxis.setRange( (((count < 200) || allDataButton.isSelected()) ? 0 : count-200), count); } ```
I encountered the same problem, which I solved with: ``` axis.setAutoRangeMinimumSize(100); // Ensures graph always shows at least 0-100. axis.setRangeType(RangeType.POSITIVE); ``` I'm using JFreeChart v1.0.14. Perhaps they've fixed a bug with `setAutoRangeType` since the question was originally posted? One downside of this approach is that zero values are not visible.
How to avoid negative values with JFreeChart fixed auto range
[ "", "java", "swing", "charts", "graph", "jfreechart", "" ]
Can someone provide the XML configuration I should use with Microsoft Unity application block in the Enterprise Library 4.1 to achieve the same result as the following? ``` using System; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.InterceptionExtension; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { IUnityContainer container = new UnityContainer(); container.AddNewExtension<Interception>(); container.RegisterType<ILogger, Logger>(); container.Configure<Interception>().SetInterceptorFor<ILogger>(new InterfaceInterceptor()); var logger = container.Resolve<ILogger>(); logger.Write("World."); Console.ReadKey(); } } public interface ILogger { [Test] void Write(string message); } public class Logger : ILogger { public void Write(string message) { Console.Write(message); } } public class TestAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { return new TestHandler(); } } public class TestHandler : ICallHandler { public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Console.Write("Hello, "); return getNext()(input, getNext); } } } ``` So instead of this: ``` IUnityContainer container = new UnityContainer(); container.AddNewExtension<Interception>(); container.RegisterType<ILogger, Logger>(); container.Configure<Interception>().SetInterceptorFor<ILogger>(new InterfaceInterceptor()); ``` I would have this: ``` IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Containers.Default.Configure(container); ``` with an XML config file.
Found the answer on my own: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <typeAliases> <typeAlias alias="ILogger" type="ConsoleApplication1.ILogger, ConsoleApplication1" /> <typeAlias alias="Logger" type="ConsoleApplication1.Logger, ConsoleApplication1" /> <typeAlias alias="TestAttribute" type="ConsoleApplication1.TestAttribute, ConsoleApplication1" /> <typeAlias alias="TestHandler" type="ConsoleApplication1.TestHandler, ConsoleApplication1" /> <typeAlias alias="interface" type="Microsoft.Practices.Unity.InterceptionExtension.InterfaceInterceptor, Microsoft.Practices.Unity.Interception, Version=1.2.0.0" /> </typeAliases> <containers> <container name="ConfigureInterceptorForType"> <extensions> <add type="Microsoft.Practices.Unity.InterceptionExtension.Interception, Microsoft.Practices.Unity.Interception" /> </extensions> <extensionConfig> <add name="interception" type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationElement, Microsoft.Practices.Unity.Interception.Configuration"> <interceptors> <interceptor type="interface"> <key type="ILogger"/> </interceptor> </interceptors> </add> </extensionConfig> <types> <type type="ILogger" mapTo="Logger" /> </types> </container> </containers> </unity> </configuration> ``` And again, the C# code: ``` using System; using System.Configuration; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using Microsoft.Practices.Unity.InterceptionExtension; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //IUnityContainer container = new UnityContainer(); //container.AddNewExtension<Interception>(); //container.RegisterType<ILogger, Logger>(); //container.Configure<Interception>().SetInterceptorFor<ILogger>(new InterfaceInterceptor()); IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Containers["ConfigureInterceptorForType"].Configure(container); var logger = container.Resolve<ILogger>(); logger.Write("World."); Console.ReadKey(); } } public interface ILogger { [Test] void Write(string message); } public class Logger : ILogger { public void Write(string message) { Console.Write(message); } } public class TestAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { return new TestHandler(); } } public class TestHandler : ICallHandler { public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Console.Write("Hello, "); return getNext()(input, getNext); } } } ```
Can this be done without the Test attribute? Purely from XML. Just specify the interface to intercept and it will intercept all or matching methods?
Microsoft Unity - code to xml
[ "", "c#", "inversion-of-control", "aop", "ioc-container", "" ]
I'm not talking about the vista glass feature, I already know how to accomplish that. The feature that I'm talking about is add controls to the titlebar, like office 2007 does with the logo and toolbar.
You need to do some Win32 interop to achieve that effect. Depending on whether you are using Winforms or WPF, the way you hook to the message processing differs (I don't remember Winforms, so I'll give all examples for WPF). But in both cases, you need to: 1. Intercept the creation of the window and modify the window styles and extended styles. In WPF you need to inherit from [`HwndSource`](http://msdn.microsoft.com/en-us/library/system.windows.interop.hwndsource.aspx) and modify the [`HwndSourceParameters`](http://msdn.microsoft.com/en-us/library/system.windows.interop.hwndsourceparameters.aspx) in order to achieve this. You need WS\_OVERLAPPEDWINDOW, WS\_CLIPSIBLINGS and WS\_VISIBLE for regular style and WS\_EX\_WINDOWEDGE and WS\_EX\_APPWINDOW extended styles. 2. Add a message handler throught he HwndSource parameters HwndSourceHook. 3. In the message proc added through the hook in step two, you need to process several messages: * [`WM_NCACTIVATE`](http://msdn.microsoft.com/en-us/library/ms632633(VS.85).aspx) - to change the painting of the title when the app is activated or not * [`WM_NCCALCSIZE`](http://msdn.microsoft.com/en-us/library/ms632634(VS.85).aspx) - to return to the OS that you don't have non-client areas * [`WM_NCPAINT`](http://msdn.microsoft.com/en-us/library/dd145212(VS.85).aspx) - in general you need to invaldate the window rect only here, the WPF will take care of the actual painting) * [`WM_NCHITTEST`](http://msdn.microsoft.com/en-us/library/ms645618(VS.85).aspx) - to process the moving of the window, minimizing and maximizing. 4. Once you do the above, your client area where WPF is going to paint your visual tree is going to span the whole area of the window. You will need to add the "non-cliet" visuals so that your application looks like a regular application to the user. 5. You might need several more messages: * [`WM_THEMECHANGED`](http://msdn.microsoft.com/en-us/ms632650.aspx) if you want to change your "non-client" area painting to be consistent with the OS theme * [`WM_DWMCOMPOSITIONCHANGED`](http://msdn.microsoft.com/en-us/library/aa969230(VS.85).aspx) if you want to extend glass and get the standard OS NC-glass painting when glass is enabled and switch to your custom logic when glass is not. 6. You might want to look at the Win32 Theme APIs if you want go get the standard Win32 assets for borders, caption, close, mininmize and maximize buttons to use in your 'non-client" area. 7. If you want to extend Glass into your window, you can look at: * [`DwmExtendFrameIntoClientArea`](http://msdn.microsoft.com/en-us/library/aa969512(VS.85).aspx) - to get the standard glass NC-area * [`DwmDefWindowProc`](http://msdn.microsoft.com/en-us/library/aa969507(VS.85).aspx) - to get the desktop manager to paint Glass and the standard NC controls * [`DwmIsCompositionEnabled`](http://msdn.microsoft.com/en-us/library/aa969518.aspx) - to determine if Glass is enabled; you can use the above two APIs only when Glass is enabled. If Glass is not enabled, you need to do your own drawing of the NC area. You can find the proper C# definitions of all messages, styles and corresponding Win32 APIs you need on [P/Invoke](http://pinvoke.net). You could also achieve similar effect by using standard WPF window with a `WindowStyle=none`. However, there will be some differences between the behavior of the desktop towards your app and other apps; most obvious of them is that you won't be able to stack or tile your window by right-clicking on the taskbar. You can also look into some third-party components that enable some of this functionality. I have not used any (as you can see, I am not scared of Win32 interop :-)), so I can't recommend you any particular.
As Franci mentions, what you want is DwmExtendFrameIntoClientArea. Here's an example from Codeproject that shows how to do it. <http://www.codeproject.com/KB/dialog/AeroNonClientAreaButtons.aspx>
Chrome Style C# Applications?
[ "", "c#", "windows-vista", "google-chrome", "" ]
I saw some cool code highlighting that looked like code in Eclipse, however I can't find it. :( Do you know any cool java code highlight css?
I think you want [code-prettify](http://code.google.com/p/google-code-prettify/) Supports a bunch of different languages (including Java). Here are the [docs/examples](http://google-code-prettify.googlecode.com/svn/trunk/README.html).
You might want to look at [SyntaxHighlighter](http://alexgorbatchev.com/wiki/SyntaxHighlighter)
How can I highlight java code via CSS?
[ "", "java", "css", "highlight", "" ]
In javascript, when would you want to use this: ``` (function(){ //Bunch of code... })(); ``` over this: ``` //Bunch of code... ```
It's all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of JavaScript code. For example, as mentioned in a comment by [Alexander](https://stackoverflow.com/users/10608/alexander-bird): ``` (function() { var foo = 3; console.log(foo); })(); console.log(foo); ``` This will first log `3` and then throw an error on the next `console.log` because `foo` is not defined.
Simplistic. So very normal looking, its almost comforting: ``` var userName = "Sean"; console.log(name()); function name() { return userName; } ``` However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations? Wait... what? I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'. So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it. One problem: it has a function in it called 'name' same as my function. This is what's called a collision. We've got two functions declared in the same *scope* with the same name. We want to avoid this. So we need to scope our code somehow. The only way to scope code in javascript is to wrap it in a function: ``` function main() { // We are now in our own sound-proofed room and the // character-converter library's name() function can exist at the // same time as ours. var userName = "Sean"; console.log(name()); function name() { return userName; } } ``` That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces. We have a function in a function... which is weird to look at, but totally legal. Only one problem. Our code doesn't work. Our `userName` variable is never echoed into the console! We can solve this issue by adding a call to our function after our existing code block... ``` function main() { // We are now in our own sound-proofed room and the // character-converter libarary's name() function can exist at the // same time as ours. var userName = "Sean"; console.log(name()); function name() { return userName; } } main(); ``` Or before! ``` main(); function main() { // We are now in our own sound-proofed room and the // character-converter libarary's name() function can exist at the // same time as ours. var userName = "Sean"; console.log(name()); function name() { return userName; } } ``` A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim. We need MORE scoping. And some way to automatically execute our main() function. Now we come to auto-execution functions (or self-executing, self-running, whatever). ``` ((){})(); ``` The syntax is awkward as sin. However, it works. When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function *call*. So lets look at our code again, with some self-executing syntax: ``` (function main() { var userName = "Sean"; console.log(name()); function name() { return userName; } } )(); ``` So, in most tutorials you read, you will now be bombarded with the term 'anonymous self-executing' or something similar. After many years of professional development, I *strongly* urge you to name *every function you write* for debugging purposes. When something goes wrong (and it will), you will be checking the backtrace in your browser. It is *always* easier to narrow your code issues when the entries in the stack trace have names!
What is the purpose of a self executing function in javascript?
[ "", "javascript", "closures", "iife", "self-executing-function", "" ]
I work at a small website building company and on one of our clients website we have a flash animation in the banner. The animation is rather chunky being 4 megabytes. The client has recently requested a rebuild of the site which would again include an animated header. We were thinking about this time not building the header in Flash (or actually having it build in flash, since none of us can actually do flash), but building it ourselves in Javascript (with jQuery().animate() and plugins). Is this a bad idea? Is flash better for an animated header? I understand you have more options, but you also require users to download flash player while Javascript is widely available. Also it is a quite simple animation, it mainly consists of text popping in and out and some images moving around/fading in and out. This should be quite easy using jQuery right (I consider myself quite experienced with jQuery), why would we choose the flash approach over the javascript/jQuery aproach? Also if we choose the Javascript approach, what is the best way to make sure the animation doesn't affect anything else in the page? Will doing the complete animation inside an absolutely position div do the trick? **Edit** When I said banner, I actually meant Header.
In this order: 1. Don't use anything animated on a web page. It looks like an ad and distracts from the content. It's just irritating. 2. Flash is build for animations. Use it if the knowledge is there. 3. Try JavaScript and watch the CPU. We made a simple slideshow with jQuery and the PC starts the fan after the first run through it. Think about limiting the animation, so that it doesn't roast a user's computer if he leaves the room for a bathroom break.
You might also try animated GIF. Some might consider it ancient, but it is very portable, small, and gets the job done.
Should an animated header be in flash or javascript?
[ "", "javascript", "jquery", "flash", "animation", "" ]
Now that my OpenGL application is getting larger and more complex, I am noticing that it's also getting a little slow on very low-end systems such as Netbooks. In Java, I am able to get around this by drawing to a BufferedImage then drawing that to the screen and updating the cached render every one in a while. How would I go about doing this in OpenGL with C++? I found a few guides but they seem to only work on newer hardware/specific Nvidia cards. Since the cached rendering operations will only be updated every once in a while, i can sacrifice speed for compatability. ``` glBegin(GL_QUADS); setColor(DARK_BLUE); glVertex2f(0, 0); //TL glVertex2f(appWidth, 0); //TR setColor(LIGHT_BLUE); glVertex2f(appWidth, appHeight); //BR glVertex2f(0, appHeight); //BR glEnd(); ``` This is something that I am especially concerned about. A gradient that takes up the entire screen is being re-drawn many times per second. How can I cache it to a texture then just draw that texture to increase performance? Also, a trick I use in Java is to render it to a 1 X height texture then scale that to width x height to increase the performance and lower memory usage. Is there such a trick with openGL?
Hey there, thought I'd give you some insight in to this. There's essentially two ways to do it. Frame Buffer Objects (FBOs) for more modern hardware, and the back buffer for a fall back. The article from one of the previous posters is a good article to follow on it, and there's plent of tutorials on google for FBOs. In my 2d Engine (Phoenix), we decided we would go with just the back buffer method. Our class was fairly simple and you can view the header and source here: <http://code.google.com/p/phoenixgl/source/browse/branches/0.3/libPhoenixGL/PhRenderTexture.h> <http://code.google.com/p/phoenixgl/source/browse/branches/0.3/libPhoenixGL/PhRenderTexture.cpp> Hope that helps!
If you don't want to use [Framebuffer Objects](http://www.opengl.org/registry/specs/ARB/framebuffer_object.txt) for compatibility reasons (but they are pretty widely available), you don't want to use the legacy (and non portable) [Pbuffers](http://www.opengl.org/registry/specs/ARB/wgl_pbuffer.txt) either. That leaves you with the simple possibility of reading the contents of the framebuffer with [glReadPixels](http://www.opengl.org/sdk/docs/man/xhtml/glReadPixels.xml) and creating a new texture with that data using [glTexImage2D](http://www.opengl.org/sdk/docs/man/xhtml/glTexImage2D.xml). Let me add that I don't really think that in your case you are going to gain much. Drawing a texture onscreen requires at least texel access per pixel, that's not really a huge saving if the alternative is just interpolating a color as you are doing now!
How do draw to a texture in OpenGL
[ "", "c++", "opengl", "graphics", "" ]
I am trying to upload files to my server using php to save them into a binary form into my mysql database but I cant get it to work, here is the script I’m using, I believe it has something to do with "$\_FILES" because when I take this out "&& $\_FILES['userfile']['size'] > 0" the script starts to run but then the variables underneath that use "$\_FILES" aren’t defined. ``` if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } db_connect(); db_select(); $query = "INSERT INTO upload (name, size, type, content ) ". "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; mysql_query($query) or die('Error, query failed'); db_disconnect(); echo "<br>File $fileName uploaded<br>"; } ```
This is a 2 fold process, first the upload itself and then the manipulation on the server. The first validation would be to make sure the file was even uploaded. For that you can use after the line ``` $fileName = $_FILES['userfile']['name']; ``` Use: ``` if(is_uploaded_file($fileName)) { // Here goes all the file manipulation/storage/etc } else { echo 'Error: File could not be uploaded.'; } ``` Try to use that and maybe re-post if the file was actually uploaded. Just because $\_FILES has content it does not necessarily mean that the file was uploaded to the server.
You should better use the [file upload status](http://docs.php.net/manual/en/features.file-upload.errors.php) to check whether the upload was successful. And don’t use the `addslashes` function for MySQL queries. Use the [`mysql_real_escape_string`](http://docs.php.net/manual/en/function.mysql-real-escape-string.php) instead.
PHP file upload
[ "", "php", "mysql", "file", "upload", "" ]
This select statement gives me the arithmetic error message: ``` SELECT CAST(FLOOR((CAST(LeftDate AS DECIMAL(12,5)))) AS DATETIME), LeftDate FROM Table WHERE LeftDate > '2008-12-31' ``` While this one works: ``` SELECT CAST(FLOOR((CAST(LeftDate AS DECIMAL(12,5)))) AS DATETIME), LeftDate FROM Table WHERE LeftDate < '2008-12-31' ``` Could there be something wrong with the data (I've checked for null values, and there are none)?
Found the problem to be when a date was set to 9999-12-31, probably to big for the decimal to handle. Changed from decimal to float, and every thing is working like a charm.
In general, converting a date to a numeric or string, to perform date operations on it, is highly inefficient. (The conversions are relatively intensive, as are string manipulations.) It is much better to stick to just date functions. The example you give is (I believe) to strip away the time part of the DateTime, the following does that without the overhead of conversions... ``` DATEADD(DAY, DATEDIFF(DAY, 0, <mydate>), 0) ``` This should also avoid arithmentic overflows...
Arithmetic overflow error converting expression to data type datetime
[ "", "sql", "sql-server", "sql-server-2005", "" ]
Why aren't they const? I believe that's flawed API design. Or am I missing something? ``` UINT GetWidth(); UINT GetHeight(); ... ``` vs. ``` UINT GetWidth() const; UINT GetHeight() const; ... ```
Hard to say. I'd agree, but perhaps there is something in the implementation that prevents them from being `const`, and that they didn't want to add overhead to hide. Nowdays we have the `mutable` keyword, but I think that is younger than this API. Or maybe the designers of the API belong to the (sometimes shockingly large, imo) bunch of C++ developers who are hostile towards the `const` keyword, feeling that only makes things harder to use. I'm no Windows historian, so I can't tell you. :)
Flawed API design? C-style C++ headers? From the teams who brought us [CString](http://msdn.microsoft.com/en-us/library/aa300688(VS.60).aspx)? Nah, can't be... Seriously, though, don't expect [GoTW](http://www.gotw.ca/gotw/)-level C++ usage in any Win32 API, or more than a basic wrapper around the C-style handles. Herb Sutter has been busy with .NET:ing C++ rather than improving Microsoft library design. The [WTL](http://www.microsoft.com/downloads/details.aspx?familyid=E5BA5BA4-6E6B-462A-B24C-61115E846F0C&displaylang=en) is as close as I've seen Microsoft come to [modern C++](http://en.wikipedia.org/wiki/Modern_C%2B%2B_Design), and that has led a rather obscure existence.
Shouldn't Gdiplus::Image::GetWidth() and a bunch of other getters be "const"?
[ "", "c++", "windows", "winapi", "gdi+", "" ]
If I have thousands of hierarchical records to take from database and generate xml, what will be the best way to do it with a good performance and less CPU utilization?
You can output XML directly from SQL Server 2005 using ``` FOR XML ``` > The results of a query > are returned as an XML document. Must be used with > one of the three RAW, AUTO > and EXPLICIT options ``` RAW ``` > Each row in the result set is an XML element with a generic > identifier as the element tag ``` AUTO ``` > Results returned in a simple > nested XML tree. An element will > be generated for each table field in the > SELECT clause ``` EXPLICIT ``` > Specifies the shape of the resulting > XML tree explicitly. > A query must be written in a > particular way so that additional > information about the nesting is > specified ``` XMLDATA ``` > Returns the schema, but does not add the root element to the result ``` ELEMENTS ``` > Specifies that the columns are > returned as child elements to the table > element. If not specified, they are mapped as > attributes Generate an inline XSD schema at the same time using ``` XMLSCHEMA ``` You can handle null values in records using ``` XSINIL ``` You can also return data in Binary form. You might want to have a look on [MSDN for XML support in SQL Server 2005](http://msdn.microsoft.com/en-us/library/ms345117.aspx), for technologies such as XQuery, XML data type, etc.
That depends - if your application and database servers are on separate machines, then you need to specify which CPU you want to reduce the load on. If your database is already loaded up, you might be better off doing the XML transform on your application server, otherwise go and ahead and use SQL Server FOR XML capabilities.
What is the best way to generate XML from the data in the database?
[ "", "c#", "xml", "sql-server-2005", "performance", "" ]
I have a sketch pad made in Flash AS3 like this one here: <http://henryjones.us/articles/using-the-as3-jpeg-encoder> I want to send the jpg to the server and some data from a html form field with php. Is there a way to force the Flash movie to deliver the image file when one presses the submit button?
it's a little tricky: You can do it one of two ways: Arthem posted this in another thread: > This was of great help to me: > <http://www.quietless.com/kitchen/upload-bitmapdata-snapshot-to-server-in-as3/> > > You need to modify the > URLRequestWrapper to insert field > names and file names where needed. > Here's what I've done: > > bytes = 'Content-Disposition: > form-data; name="' + $fieldName + '"; > filename="'; > > It does the most formatting of headers > so the server could understand it as a > file upload. > > By the way, if you have a BitmapData > you might need to encode it to JPEG or > PNG first. And I usually use this solution: I haven't used the imageshack API, but you may want to try using adobe's JPGEncoder class - here's a quick example that passes a username and the JPG's byte array, it's really quite simple. ``` private function savePicToServer(bmpData:BitmapData):void { var jpgEncoder:JPGEncoder = new JPGEncoder(85); var jpgStream:ByteArray = jpgEncoder.encode(bmpData); var loader:URLLoader = new URLLoader(); configureListeners(loader); var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); var request:URLRequest = new URLRequest(ModelLocator.BASE_URL + ModelLocator.UPLOAD_URL + "?user=" + ModelLocator.getInstance().username); request.requestHeaders.push(header); request.method = URLRequestMethod.POST; request.data = jpgStream; loader.load(request); } ``` Note that the variables are passed as part of the query string. You can't use URLVariables, as several people have suggested, as the URLVariables would be stored in the request's data property, which we are already using to pass the byteArray.
I wanted to send an encrypted authorization code form Flash to PHP along with a JPG image. It was not suitable to post this in the get variables and so I got around it this way. Most of the code is the actual gathering of a stage snapshot, but only a specific region of it. The part that is relevant to here is the use of writeMultiByte to tack on the encrypted password to the end of the jpb image info. I then send the length of this password using the get variables url string so that PHP know show much to chop off the end. ``` var stage_snapshot:BitmapData = new BitmapData(600, 120); var myRectangle:Rectangle = new Rectangle(0, 0, 600, 120); var myMatrix:Matrix = new Matrix(); var translateMatrix:Matrix = new Matrix(); translateMatrix.translate(-101, -33); myMatrix.concat(translateMatrix); stage_snapshot.draw(stage,myMatrix,null,null,myRectangle); trace ("creating JPGEncoder"); // Setup the JPGEncoder, run the algorithm on the BitmapData, and retrieve the ByteArray var encoded_jpg:JPGEncoder = new JPGEncoder(100); var jpg_binary:ByteArray = new ByteArray(); jpg_binary = encoded_jpg.encode(stage_snapshot); var pw = cryptoSalt.encrypt("mysecretpassword"); **var pwLength = pw.length; jpg_binary.writeMultiByte(pw,"us-ascii");** trace ("stage snapshot taken"); var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream"); var request:URLRequest = new URLRequest("savejpg.php?length1=" + pwLength); request.requestHeaders.push(header); request.method = URLRequestMethod.POST; request.data = jpg_binary; var loader:URLLoader = new URLLoader(); trace ("sending pic to php"); loader.load(request); loader.addEventListener(Event.COMPLETE,finishSave); ``` The receiving PHP: ``` $pwlength = $_GET['length1']; $jpg = $GLOBALS["HTTP_RAW_POST_DATA"]; $pw = substr($jpg, - $pwlength); $jpg = substr($jpg,0,strlen($jpg) - $pwlength); $filename = 'uploads/test.jpg'; file_put_contents($filename, $jpg); file_put_contents("uploads/pw.txt",$pw); ```
How can I send a ByteArray (from Flash) and some form data to php?
[ "", "php", "flash", "actionscript-3", "input", "jpeg", "" ]
I am currently building an application that consists of several components, each of which is essentially a WPF user control with a little C# code around it for the plugin system to work (using MEF). The problem I am having is that each component should include an icon and for niceness purposes I defined that as a `System.Windows.Media.Brush` so I can just use the `DrawingBrush` exported from Design there. Now I need to access that piece of XAML from non-WPF C# where I currently have the horrible workaround of instantiating the user control and asking it for the resource: ``` private Brush CachedIcon = null; public override Brush Icon { get { if (CachedIcon == null) { CachedIcon = (Brush)(new BlahControl().TryFindResource("Icon")); } return CachedIcon; } } ``` I couldn't find a way to read that resource (which is a .xaml file, and referenced in a `ResourceDictionary` in the custom control) from a "normal" C# class. Anything belonging to WPF has that nice `TryFindResource` method but how to do that otherwise? I don't want to have the XAML file with the icon lying around un-embedded.
In your XAML code make sure the icon resource has the build option set to "Resource", and then reference the resource to make it a xaml static resource ``` <UserControl.Resources> <BitmapImage x:Key="icon1" UriSource="Resources/Icon1.ico" /> </UserControl.Resources> ``` Then in your .Net 2.0 code you will find the resource in the "{xamlName}.g.resource" stream Example code that loads all icons from a xaml dll into a dictionary: ``` using System.IO; using System.Reflection; using System.Collections; using System.Resources; ... var icons = new Dictionary<String, Bitmap>(); var externalBaml = Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "MyXaml.dll")); Stream resourceStream = externalBaml.GetManifestResourceStream(externalBaml.GetName().Name + ".g.resources"); using (ResourceReader resourceReader = new ResourceReader(resourceStream)) { foreach (DictionaryEntry resourceEntry in resourceReader) { if (resourceEntry.Key.ToString().ToUpper().EndsWith(".ICO")) { icons.Add(resourceEntry.Key.ToString(), Image.FromStream(resourceEntry.Value as Stream) as Bitmap); } } } ```
My suggestions are: * Provide metadata on your control about where the icon can be found. You can do this with your own custom attribute (see example 1 below). This metadata will allow you to load the icon without creating an instance of the control. * Since you're using MEF, you can use metadata in your export to achieve the same as above. Details [here](http://mef.codeplex.com/Wiki/View.aspx?title=Exports%20and%20Metadata&referringTitle=Guide). See example 2 below. * Treat your icon as an `ImageSource` rather than a `Brush`. You can use WPF's `Image` control to show your `ImageSource`, or you can paint it with an `ImageBrush`. * Use the technique provided by TFD to read the resource with the name specified in the metadata. Unfortunately, WPF does not appear to provide anything like a `BamlReader`, which would make it much cleaner to load the WPF resource from a non-WPF context. Example 1: ``` [Icon("MyIconResourceName")] public class BlahControl : Control { ... } ``` Example 2: ``` [Export(typeof(IApplicationComponent))] [ExportMetadata("IconResource", "MyIconResourceName")] public class BlahControl : Control { ... } ```
Acessing WPF XAML Resources from non-WPF code
[ "", "c#", "wpf", "embedded-resource", "" ]
I have a site like SO, Wordpress, etc, where you make a post and u can have (optional) tags against it. What is a common database schema to handle this? I'm assuming it's a many<->many structure, with three tables. Anyone have any ideas?
A three table many to many structure should be fine. Eg. `Posts, PostsToTags(post_id,tag_id), Tags` The key is indexing. Make sure you PostsToTags table is indexed both ways (`post_id,tag_id` and `tag_id,post_id`) also if read performance is ultra critical you could introduce an indexed view (which could give you post\_name, tag\_name) You will of course need indexes on Posts and Tags as well.
"I'm assuming it's a many<->many structure, with three tables. Anyone have any ideas?" More to the point, there aren't any serious alternatives, are there? Two relational tables in a many-to-many relationship require at least an association table to carry all the combination of foreign keys. Does SO do this? Who knows. Their data model includes reference counts, and -- for all any knows -- date time stamps and original creator and a lot of other junk about the tag. Minimally, there have to be three tables. What they do on SO is hard to know.
A database schema for Tags (eg. each Post has some optional tags)
[ "", "sql", "architecture", "schema", "many-to-many", "" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128) when used in a pipe sequence. What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack: ``` # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" ``` Is there a better way to make piping work?
Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself. A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send. ``` # -*- coding: utf-8 -*- print u"åäö".encode('utf-8') ``` Another didactic example is a Python program to convert between ISO-8859-1 and UTF-8, making everything uppercase in between. ``` import sys for line in sys.stdin: # Decode what you receive: line = line.decode('iso8859-1') # Work with Unicode internally: line = line.upper() # Encode what you send: line = line.encode('utf-8') sys.stdout.write(line) ``` Setting the system default encoding is a bad idea, because some modules and libraries you use can rely on the fact it is ASCII. Don't do it.
First, regarding this solution: ``` # -*- coding: utf-8 -*- print u"åäö".encode('utf-8') ``` It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone. A better solution is to change **`sys.stdout`** at the start of your program, to encode with a selected encoding. Here is one solution I found on [Python: How is sys.stdout.encoding chosen?](http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/), in particular a comment by "toka": ``` import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) ```
Setting the correct encoding when piping stdout in Python
[ "", "python", "encoding", "terminal", "stdout", "python-2.x", "" ]
My database isn't actually customers and orders, it's customers and prescriptions for their eye tests (just in case anyone was wondering why I'd want my customers to make orders less frequently!) I have a database for a chain of opticians, the prescriptions table has the branch ID number, the patient ID number, and the date they had their eyes tested. Over time, patients will have more than one eye test listed in the database. How can I get a list of patients who have had a prescription entered on the system more than once in six months. In other words, where the date of one prescription is, for example, within three months of the date of the previous prescription for the same patient. Sample data: ``` Branch Patient DateOfTest 1 1 2007-08-12 1 1 2008-08-30 1 1 2008-08-31 1 2 2006-04-15 1 2 2007-04-12 ``` I don't need to know the actual dates in the result set, and it doesn't have to be exactly three months, just a list of patients who have a prescription too close to the previous prescription. In the sample data given, I want the query to return: ``` Branch Patient 1 1 ``` This sort of query isn't going to be run very regularly, so I'm not overly bothered about efficiency. On our live database I have a quarter of a million records in the prescriptions table.
Something like this ``` select p1.branch, p1.patient from prescription p1, prescription p2 where p1.patient=p2.patient and p1.dateoftest > p2.dateoftest and datediff('day', p2.dateoftest, p1.dateoftest) < 90; ``` should do... you might want to add ``` and p1.dateoftest > getdate() ``` to limit to future test prescriptions.
This one will efficiently use an index on `(Branch, Patient, DateOfTest)` which you of course should have: ``` SELECT Patient, DateOfTest, pDate FROM ( SELECT ( SELECT TOP 1 DateOfTest AS last FROM Patients pp WHERE pp.Branch = p.Branch AND pp.Patient = p.Patient AND pp.DateOfTest BETWEEN DATEADD(month, -3, p.DateOfTest) AND p.DateOfTest ORDER BY DateOfTest DESC ) pDate FROM Patients p ) po WHERE pDate IS NOT NULL ```
sql query to find customers who order too frequently?
[ "", "sql", "sql-server", "t-sql", "" ]
How do you call a Javascript function from an ASPX control event? Specifically, I want to call the function from the SelectedIndexChanged event of a DropDownList.
I get a little nervous whenever I see this kind of question, because nine times out of ten it means the asker doesn't really understand what's going on. When your SelectedIndexChanged event fires on the server, it fires as part of a *full postback*. That means that for that code to run, the entire rest of your page's load code also had to run. More than that, the code runs as the result of a new http request from the browser. As far as the browser is concerned, an entirely new page is coming back in the result. The old page, and the old DOM, are discarded. So at the time your SelectedIndexChanged event code is running, the javascript function you want to call doesn't even exist in the browser. So what to do instead? You have a few options: * Change the page so the control doesn't post back to the server at all. Detect the change entirely in javascript at the client. This is my preferred option because it avoids odd onload scripts in the browser page and it saves work for your server. The down side is that it makes your page dependent on javascript, but that's not really a big deal because if javascript is disabled this was doomed from the beginning. * Set your desired javascript to run onload in the SelectedIndexChanged event using the ClientScript.SetStartupScript(). * Apply the expected results of your javascript to the server-model of the page. This has the advantage of working even when javascript is turned off (accessibility), but at the cost of doing much more work on the server, spending more time reasoning about the logical state of your page, and possibly needing to duplicate client-side and server-side logic. Also, this event depends on javascript anyway: if javascript is disabled it won't fire. * Some combination of the first and third options are also possible, such that it uses javascript locally if available, but posts back to the server if not. Personally I'd like to see better, more intuitive, support for that built into ASP.Net. But again: I'm talking about the general case. This specific event requires javascript to work at all.
As Muerte said you have to just put the javascript, or a call to it on the page from the code behind. Personally I use this: ``` ClientScript.RegisterClientScriptBlock("customscript", "<script>simple script here</script>") ``` Of you can call the function if you already have a more complex one on the page instead of the stuff I have.
How do you call a Javascript function from an ASPX control event?
[ "", "asp.net", "javascript", "" ]
I am trying to do what I think is a "de-intersect" (I'm not sure what the proper name is, but that's what Tim Sweeney of EpicGames called it in the old UnrealEd) ``` // foo and bar have some identical elements (given a case-insensitive match) List‹string› foo = GetFoo(); List‹string› bar = GetBar(); // remove non matches foo = foo.Where(x => bar.Contains(x, StringComparer.InvariantCultureIgnoreCase)).ToList(); bar = bar.Where(x => foo.Contains(x, StringComparer.InvariantCultureIgnoreCase)).ToList(); ``` Then later on, I do another thing where I subtract the result from the original, to see which elements I removed. That's super-fast using .Except(), so no troubles there. There must be a faster way to do this, because this one is pretty bad-performing with ~30,000 elements (of string) in either List. Preferably, a method to do this step and the one later on in one fell swoop would be nice. I tried using .Exists() instead of .Contains(), but it's slightly slower. I feel a bit thick, but I think it should be possible with some combination of .Except() and .Intersect() and/or .Union().
With intersect it would be done like this: ``` var matches = ((from f in foo select f) .Intersect( from b in bar select b, StringComparer.InvariantCultureIgnoreCase)) ```
This operation can be called a symmetric difference. You need a different data structure, like a hash table. Add the intersection of both sets to it, then difference the intersection from each set. **UPDATE:** I got a bit of time to try this in code. I used `HashSet<T>` with a set of 50,000 strings, from 2 to 10 characters long with the following results: > **Original**: 79499 ms > > **Hashset**: 33 ms BTW, there is a method on HashSet called `SymmetricExceptWith` which I thought would do the work for me, but it actually adds the different elements from both sets to the set the method is called on. Maybe this is what you want, rather than leaving the initial two sets unmodified, and the code would be more elegant. Here is the code: ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; class Program { static void Main(string[] args) { // foo and bar have some identical elements (given a case-insensitive match) var foo = getRandomStrings(); var bar = getRandomStrings(); var timer = new Stopwatch(); timer.Start(); // remove non matches var f = foo.Where(x => !bar.Contains(x)).ToList(); var b = bar.Where(x => !foo.Contains(x)).ToList(); timer.Stop(); Debug.WriteLine(String.Format("Original: {0} ms", timer.ElapsedMilliseconds)); timer.Reset(); timer.Start(); var intersect = new HashSet<String>(foo); intersect.IntersectWith(bar); var fSet = new HashSet<String>(foo); var bSet = new HashSet<String>(bar); fSet.ExceptWith(intersect); bSet.ExceptWith(intersect); timer.Stop(); var fCheck = new HashSet<String>(f); var bCheck = new HashSet<String>(b); Debug.WriteLine(String.Format("Hashset: {0} ms", timer.ElapsedMilliseconds)); Console.WriteLine("Sets equal? {0} {1}", fSet.SetEquals(fCheck), bSet.SetEquals(bCheck)); //bSet.SetEquals(set)); Console.ReadKey(); } static Random _rnd = new Random(); private const int Count = 50000; private static List<string> getRandomStrings() { var strings = new List<String>(Count); var chars = new Char[10]; for (var i = 0; i < Count; i++) { var len = _rnd.Next(2, 10); for (var j = 0; j < len; j++) { var c = (Char)_rnd.Next('a', 'z'); chars[j] = c; } strings.Add(new String(chars, 0, len)); } return strings; } } ```
Faster way to do a List<T>.Contains()
[ "", "c#", "list", "extension-methods", "contains", "" ]
Take the tsql query below: ``` DECLARE @table TABLE(data VARCHAR(20)) INSERT INTO @table VALUES ('not duplicate row') INSERT INTO @table VALUES ('duplicate row') INSERT INTO @table VALUES ('duplicate row') INSERT INTO @table VALUES ('second duplicate row') INSERT INTO @table VALUES ('second duplicate row') SELECT data INTO #duplicates FROM @table GROUP BY data HAVING COUNT(*) > 1 -- delete all rows that are duplicated DELETE FROM @table FROM @table o INNER JOIN #duplicates d ON d.data = o.data -- insert one row for every duplicate set INSERT INTO @table(data) SELECT data FROM #duplicates ``` I understand what it is doing, but the last part of logic (after --insert one row for every duplicate set), doesn't make sense. Where we have the set of code for --delete all rows that are duplicated, that gets rid of the duplicates so what's the part of the last section? This query was found [here](http://www.simple-talk.com/sql/t-sql-programming/removing-duplicates-from-a-table-in-sql-server/) Thanks
> Where we have the set of code for --delete all rows that are duplicated, that gets rid of the duplicates so what's the part of the last section? First, it deletes all rows that ever had duplicates. That is, all rows, and original also. In the case above, only one row (`'not duplicate row'`) will remain in the table after `DELETE`. All four other rows will be deleted. Then is populates the table with the deleted rows again, but now the duplicates are removed. This is not the best way to delete duplicates. The best way is: ``` WITH q AS ( SELECT data, ROW_NUMBER() OVER (PARTITION BY data ORDER BY data) AS rn FROM @table ) DELETE FROM q WHERE rn > 1 ```
The delete call deletes *all* matching records. Because all duplicated rows have been deleted the last piece reinserts a single row.
Deleting duplicate records using a temporary table
[ "", "sql", "t-sql", "" ]
Suppose I have a set of functions and classes which are templated to use single (`float`) or `double` precision. Of course I could write just two pieces of bootstrap code, or mess with macros. But can I just switch template argument at runtime?
No, you can't switch template arguments at runtime, since templates are instantiated by the compiler at compile-time. What you *can* do is have both templates derive from a common base class, always use the base class in your code, and then decide which derived class to use at runtime: ``` class Base { ... }; template <typename T> class Foo : public Base { ... }; Base *newBase() { if(some condition) return new Foo<float>(); else return new Foo<double>(); } ``` Macros have the same problem as templates, in that they are expanded at compile-time.
Templates are a compile-time mechanism. BTW, macros are as well (strictly speaking - a preprocessing mechanism - that comes even before compilation).
Select template argument at runtime in C++
[ "", "c++", "templates", "runtime", "arguments", "" ]
When parsing an xml document for its nodes or attributes, if the document is large, I would have a bunch of ifs and else statements. Obviously, 100+ ifs does not make up maintainable code in the long run. Rather than doing this, is there another better way? I read on Hanselman's blog about a friend of his who had the same situation and wrote loads of ifs/else if and generally poor code. Hanselman provided some snippets of a more maintainable way but the entire code isn't available so it's a little hard to understand exactly what (the whole picture) is going on. [Life after if, else](http://www.hanselman.com/blog/BackToBasicsLifeAfterIfForAndSwitchLikeADataStructuresReminder.aspx) I am using .NET 3.5 SO I have the full power of extension methods and LINQ available to me. However, I use .NET 2.0 a work so would also appreciate any solutions in v2.0. :) My code looks very similar to the problem on Hanselman's site: if (xmlNode.Attributes["a"].Value == "abc" { } else if (xmlNode.Attributes["b"].Value == "xyz" { wt = MyEnum.Haze; } I could just have a dictionary storing the values I am looking for as keys and perhaps a delegate in the value (or whatever I want to happen on finding a required value), so I could say if (containskey) get delegate and execute it, in pseudocode. This sort of thing goes on and on. Obviously very naive way of coding. I have the same problem with parsing a text document for values, etc. Thanks
What you're doing here is executing a list of tests. For each test, if a predicate is true, execute an action. When a test passes, stop processing the list. Right? A couple of people have suggested using a dictionary, but the problem with using a dictionary is that you don't control the order of the items in it. If you want to perform the tests in a specific order (which, as stated, you do), that's not going to work. So a list seems like the way to go. Here's a functional way to do this, assuming that the predicates are examining an `XmlElement`. Your tests are instances of a class: ``` class Test { string Predicate { get; set; } Action Verb { get; set; } Test(string predicate, Action verb) { Predicate = predicate; Verb = verb; } bool Execute(XmlElement e) { if (e.SelectSingleNode(Predicate) != null) { Verb(); return true; } return false; } } ``` To populate the list of tests: ``` List<Test> tests = new List<Test>(); tests.Add(new Test("@foo = 'bar'", Method1)); tests.Add(new Test("@foo = 'baz'", Method2)); tests.Add(new Test("@foo = 'bat'", Method3)); ``` To execute the tests: ``` foreach (Test t in tests) { if (t.Execute()) break; } ``` You've eliminated a lot of if/else clutter, but you've replaced it with this: ``` void Method1() { ... do something here } void Method2() { ... do something else here } ``` If your method naming is good, though, this results in pretty clean code. To use .NET 2.0, I think you need to add this to the code: ``` public delegate void Action(); ``` because I think that type was defined in 3.0. I could be wrong.
If you need to map `<condition on xml node`> to `<change of state`> there's no way to avoid defining that mapping *somewhere*. It all depends on how many assumptions you can make about the conditions and what you do under those conditions. I think the dictionary idea is a good one. To offer as much flexibility as possible, I'd start like this: ``` Dictionary<Predicate<XmlNode>, Action> mappings; ``` Then start simplifying where you can. For example, are you often just setting wt to a value of MyEnum like in the example? If so, you want something like this: ``` Func<MyEnum, Action> setWt = val => () => wt = val; ``` And for the presumably common case that you simply check if an attribute has a specific value, you'd want some convenience there too: ``` Func<string, string, Predicate<XmlNode>> checkAttr = (attr, val) => node => node.Attributes[attr] == val; ``` Now your dictionary can contain items like: ``` ... {checkAttr("a", "abc"), setWt(MyEnum.Haze)}, ... ``` Which is nice and terse, but also isn't restricted to the simple `<attribute, value`> to `<enum`> mapping. OK, so now you have a big dictionary of these condition-action pairs, and you just say: ``` foreach(DictionaryEntry<Predicate<XmlNode>, Action> mapping in mappings) { if (mapping.Key(xmlNode)) { mapping.Value(); break; } } ``` If you avoid the lambda syntax and the dictionary initializers, you should be able to do that in 2.0.
Coming out of the habit of writing ifs/elseifs for every possible condition
[ "", "c#", "" ]
Simple question for a newb and my Google-Fu is failing me. Using PHP, how can you count the number of files in a given directory, including any sub-directories (and any sub-directories they might have, etc.)? e.g. if directory structure looks like this: ``` /Dir_A/ /Dir_A/File1.blah /Dir_A/Dir_B/ /Dir_A/Dir_B/File2.blah /Dir_A/Dir_B/File3.blah /Dir_A/Dir_B/Dir_C/ /Dir_A/Dir_B/Dir_C/File4.blah /Dir_A/Dir_D/ /Dir_A/Dir_D/File5.blah ``` The script should return with '5' for "./Dir\_A". I've cobbled together the following but it's not quite returning the correct answer, and I'm not sure why: ``` function getFilecount( $path = '.', $filecount = 0, $total = 0 ){ $ignore = array( 'cgi-bin', '.', '..', '.DS_Store' ); $dh = @opendir( $path ); while( false !== ( $file = readdir( $dh ) ) ){ if( !in_array( $file, $ignore ) ){ if( is_dir( "$path/$file" ) ){ $filecount = count(glob( "$path/$file/" . "*")); $total += $filecount; echo $filecount; /* debugging */ echo " $total"; /* debugging */ echo " $path/$file "; /* debugging */ getFilecount( "$path/$file", $filecount, $total); } } } return $total; } ``` I'd greatly appreciate any help.
This should do the trick: ``` function getFileCount($path) { $size = 0; $ignore = array('.','..','cgi-bin','.DS_Store'); $files = scandir($path); foreach($files as $t) { if(in_array($t, $ignore)) continue; if (is_dir(rtrim($path, '/') . '/' . $t)) { $size += getFileCount(rtrim($path, '/') . '/' . $t); } else { $size++; } } return $size; } ```
Use the SPL, then see if you still get an error. [RecursiveDirectoryIterator](http://www.php.net/~helly/php/ext/spl/classRecursiveDirectoryIterator.html) Usage example: ``` <?php $path = realpath('/etc'); $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); foreach($objects as $name => $object){ echo "$name\n"; } ?> ``` This prints a list of all files and directories under $path (including $path ifself). If you want to omit directories, remove the RecursiveIteratorIterator::SELF\_FIRST part. Then just use isDir()
Recursively counting files with PHP
[ "", "php", "recursion", "count", "" ]
So I have this library code, see... ``` class Thing { public: class Obj { public: static const int len = 16; explicit Obj(char *str) { strncpy(str_, str, len); } virtual void operator()() = 0; private: char str_[len]; }; explicit Thing(vector<Obj*> &objs) : objs_(objs) {} ~Thing() { for(vector<Obj*>::iterator i = objs_.begin(); i != objs_.end(); ++i) { delete *i; } } private: vector<Obj*> objs_; } ``` And in my client code... ``` class FooObj : public Thing::Obj { virtual void operator()() { //do stuff } } class BarObj : public Thing::Obj { virtual void operator()() { //do different stuff } } vector<Objs*> objs; int nStructs = system_call(*structs); for(int i = 0; i < nStructs; i++) { objs.push_back(newFooObj(structs[i].str)); } objs.push_back(newBarObj("bar1"); objs.push_back(newBarObj("bar2"); Thing thing(objs); // thing does stuff, including call Obj::()() on the elements of the objs_ vector ``` The thing I'm stuck on is exception safety. As it stands, if any of the Obj constructors throw, or the Thing constructor throws, the Objs already in the vector will leak. The vector needs to contain pointers to Objs because they're being used polymorphically. And, I need to handle any exceptions here, because this is being invoked from an older codebase that is exception-unaware. As I see it, my options are: 1. Wrap the client code in a giant try block, and clean up the vector in the catch block. 2. Put try blocks around all of the allocations, the catch blocks of which call a common cleanup function. 3. Some clever RAII-based idea that I haven't thought of yet. 4. Punt. Realistically, if the constructors throw, the application is about to go down in flames anyway, but I'd like to handle this more gracefully.
Since your Thing destructor already knows how to clean up the vector, you're most of the way towards a [RAII](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) solution. Instead of creating the vector of Objs, and then passing it to Thing's constructor, you could initialize Thing with an empty vector and add a member function to add new Objs, by pointer, to the vector. This way, if an Obj's constructor throws, the compiler will automatically invoke Thing's destructor, properly destroying any Objs that were already allocated. Thing's constructor becomes a no-op: ``` explicit Thing() {} ``` Add a `push_back` member: ``` void push_back(Obj *new_obj) { objs_.push_back(new_obj); } ``` Then the allocation code in your client becomes: ``` Thing thing(objs); int nStructs = system_call(*structs); for(int i = 0; i < nStructs; i++) { thing.push_back(newFooObj(structs[i].str)); } thing.push_back(newBarObj("bar1"); thing.push_back(newBarObj("bar2"); ``` As another poster suggested, a smart pointer type inside your vector would also work well. Just don't use STL's `auto_ptr`; it doesn't follow normal copy semantics and is therefore unsuitable for use in STL containers. The `shared_ptr` provided by Boost and the forthcoming C++0x would be fine.
Take a look at [`boost::ptr_vector`](http://www.boost.org/doc/libs/1_38_0/libs/ptr_container/doc/ptr_container.html)
Help me make this code exception-safe
[ "", "c++", "exception", "smart-pointers", "container-managed", "" ]
I'm trying to set the maxlength on input fields dynamically using JavaScript. Apparently that is a problem in IE, and I found part of the solution. ``` $("input#title").get(0).setAttribute("max_length", 25); $("input#title").get(0).setAttribute( "onkeypress", "return limitMe(event, this)"); function limitMe(evt, txt) { if (evt.which && evt.which == 8) return true; else return (txt.value.length < txt.getAttribute("max_length"); } ``` It works in Firefox, but not in IE for some reason. However, it works on input fields set like this: ``` <input type="text" max_length="25" onkeypress="return limitMe(event, this);"/> ``` But since the input fields are created dynamically, I can't do this... Any ideas?
If you're using jQuery then why not make full use of its abstractions? E.g. Instead of: ``` $("input#title").get(0).setAttribute("max_length", 25); $("input#title").get(0).setAttribute( "onkeypress", "return limitMe(event, this)"); function limitMe(evt, txt) { if (evt.which && evt.which == 8) return true; else return (txt.value.length < txt.getAttribute("max_length"); } ``` Do this: ``` $('input#title').attr('maxLength','25').keypress(limitMe); function limitMe(e) { if (e.keyCode == 8) { return true; } return this.value.length < $(this).attr("maxLength"); } ``` --- Edit: The reason it's not working in IE is probably because of how you attached the 'onKeyPress' handler, via setAttribute. - This isn't the proper way to register event handlers.
The attribute you're looking for is `maxlength`, not `max_length`. See [here](http://www.w3.org/TR/html401/interact/forms.html#h-17.4).
setting maxlength using javascript
[ "", "javascript", "html", "forms", "" ]
I have the following sorted data: ``` AAA AAA TCG TTT TTT TTT ``` I want to count the occurrences of each String: ``` AAA 2 TCG 1 TTT 3 ``` I know I can do that using `uniq -c`, but here I need to do extra processing on the overall C++ code that I have. I am stuck with this construct (modified according to 'pgras' suggestion): ``` #include <iostream> #include <vector> #include <fstream> #include <sstream> using namespace std; int main ( int arg_count, char *arg_vec[] ) { if (arg_count !=2 ) { cerr << "expected one argument" << endl; return EXIT_FAILURE; } string line; ifstream myfile (arg_vec[1]); if (myfile.is_open()) { int count; string lastTag = ""; while (getline(myfile,line) ) { stringstream ss(line); string Tag; ss >> Tag; // read first column //cout << Tag << endl; if (Tag != lastTag) { lastTag = Tag; count = 0; } else { count++; } cout << lastTag << " " << count << endl; } cout << lastTag << " " << count << endl; myfile.close(); } else {cout << "Unable to open file";} return 0; } ``` It prints this wrong result: ``` AAA 0 AAA 1 TCT 0 TTT 0 TTT 1 TTT 2 TTT 2 ```
You have to reset counter when tag is different from lastTag, and increment if it's the same... When the tag is different you can handle the previous tag with it's associated count value (before you reset count)...
If you just want to print it out, your algorithm is ok. If you want to pass it to another function, you can use for example STL map. ``` map<string, int> dict; while(getline(myfile,line)) { string Tag; stringstream ss(line); ss >> Tag; if (dict.count(Tag) == 0) dict[Tag] = 1; else dict[Tag]++; } ```
Algorithm for Counting Sorted Strings (Homebrew "uniq -c")
[ "", "c++", "algorithm", "unix", "string", "counting", "" ]
is there any function of datetime return dayofweekindex? such as: int Todaywhat\_is\_Index= = DateTime.Now.IndexOfDayofThisWeek; if Today is friday, it must be return 5 ifToday is Saturday, it must be return 6 ifToday is Sunday, it must be return 0
Yes, check [DateTime.DayOfWeek](http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx). Please note this depends on the regional settings (here in Europe Monday is the first day of the week).
This little one-liner works independent of locale, with always Friday == 5 ``` int x = (int)System.Globalization.CultureInfo .InvariantCulture.Calendar.GetDayOfWeek(DateTime.Now); ```
Return index value datetime.now.dayofweek but how?
[ "", "c#", ".net", "datetime", "" ]
Can anyone think of a nicer way to do the following: ``` public string ShortDescription { get { return this.Description.Length <= 25 ? this.Description : this.Description.Substring(0, 25) + "..."; } } ``` I would have liked to just do string.Substring(0, 25) but it throws an exception if the string is less than the length supplied.
I needed this so often, I wrote an extension method for it: ``` public static class StringExtensions { public static string SafeSubstring(this string input, int startIndex, int length, string suffix) { // Todo: Check that startIndex + length does not cause an arithmetic overflow - not that this is likely, but still... if (input.Length >= (startIndex + length)) { if (suffix == null) suffix = string.Empty; return input.Substring(startIndex, length) + suffix; } else { if (input.Length > startIndex) { return input.Substring(startIndex); } else { return string.Empty; } } } } ``` if you only need it once, that is overkill, but if you need it more often then it can come in handy. *Edit:* Added support for a string suffix. Pass in "..." and you get your ellipses on shorter strings, or pass in string.Empty for no special suffixes.
``` return this.Description.Substring(0, Math.Min(this.Description.Length, 25)); ``` Doesn't have the `...` part. Your way is probably the best, actually.
Tiny way to get the first 25 characters
[ "", "c#", "string", "" ]
I am trying to quickly process large images (about 2000x2000). I am using a TrackBar to change the overall brightness of an image. The problem is that the TrackBar (as you all know) can be moved very quickly. This is ok as I do not need to process the image for *every* tick of the TrackBar, but it does need to be reasonably responsive. Think of the brightness TrackBars found in image editors. I have tried doing all of the processing in another thread, which works, but it is still too slow (even using LockBits on the Bitmap). I can't use a ColorMatrix because it allows component overflows and I need values to clip at 255. So, I am thinking that I can achieve good performance by using the ThreadPool and splitting the image up into sections. The problem with this approach is that I just don't have much experience with multi-trheaded applications and I don't know how to avoid the race conditions that crop up (calling LockBits on an already locked image, etc.). Could anyone give me an example of how to do this? Here is the code that I have so far. I know that it is far from good, but I am just working it out and trying a bunch of different things at this point. The basic concept is to use a base image as a source, perform some operation on each pixel, then draw the processed pixel into a display Bitmap. Any help would be awesome. ``` public Form1( ) { InitializeComponent( ); testPBox1.Image = Properties.Resources.test; trackBar1.Value = 100; trackBar1.ValueChanged += trackBar1_ValueChanged; } void trackBar1_ValueChanged( object sender, EventArgs e ) { testPBox1.IntensityScale = (float) trackBar1.Value / 100; } class TestPBox : Control { private const int MIN_SAT_WARNING = 240; private Bitmap m_srcBitmap; private Bitmap m_dispBitmap; private float m_scale; public TestPBox( ) { this.DoubleBuffered = true; IntensityScale = 1.0f; } public Bitmap Image { get { return m_dispBitmap; } set { if ( value != null ) { m_srcBitmap = value; m_dispBitmap = (Bitmap) value.Clone( ); Invalidate( ); } } } [DefaultValue( 1.0f )] public float IntensityScale { get { return m_scale; } set { if ( value == 0.0 || m_scale == value ) { return; } if ( !this.DesignMode ) { m_scale = value; ProcessImage( ); } } } private void ProcessImage( ) { if ( Image != null ) { int sections = 10; int sectionHeight = (int) m_srcBitmap.Height / sections; for ( int i = 0; i < sections; ++i ) { Rectangle next = new Rectangle( 0, i * sectionHeight, m_srcBitmap.Width, sectionHeight ); ThreadPool.QueueUserWorkItem( new WaitCallback( delegate { ChangeIntensity( next ); } ) ); } } } private unsafe void ChangeIntensity( Rectangle rect ) { BitmapData srcData = m_srcBitmap.LockBits( rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb ); BitmapData dspData = m_dispBitmap.LockBits( rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb ); byte* pSrc = (byte*) srcData.Scan0; byte* pDsp = (byte*) dspData.Scan0; for ( int y = 0; y < rect.Height; ++y ) { for ( int x = 0; x < rect.Width; ++x ) { // we are dealing with a monochrome image, so r = g = b. // We only need to get one component value to use for all r, g, and b. byte b = (byte) CompMinMax( 0, 255, (int) ( pSrc[0] * m_scale ) ); Color c = ( b > MIN_SAT_WARNING ) ? Color.FromArgb( b, Color.Red ) : Color.FromArgb( 255, b, b, b ); // windows stores images internally in // reverse byte order, i.e., Bgra, not Argb. pDsp[3] = (byte) c.A; pDsp[2] = (byte) c.R; pDsp[1] = (byte) c.G; pDsp[0] = (byte) c.B; pSrc += 4; pDsp += 4; } } m_srcBitmap.UnlockBits( srcData ); m_dispBitmap.UnlockBits( dspData ); this.Invalidate( ); } private int CompMinMax( int min, int max, int value ) { if ( value > max ) return max; if ( value < min ) return min; return value; } protected override void OnPaint( PaintEventArgs e ) { if ( Image != null ) { Graphics g = e.Graphics; Rectangle drawingRect = PaintUtils.CenterInRect( ClientRectangle, PaintUtils.ScaleRect( ClientRectangle, Image.Size ).Size ); g.DrawImage( Image, drawingRect, 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel ); } base.OnPaint( e ); } } ```
Have you considered generating a scaled-down version of the image and doing the image manipulation on that while the user is dragging the trackbar? That would give you responsiveness while still giving the user useful feedback until they settle on a final value.
If you want to use your current approach, there are a couple minor tweaks you could make that would get rid of the race conditions. The thing you'd need to change would be to adjust it so that you call LockBits/UnlockBits in ProcessImage, not in the individual thread pool requests. However, you'd need to also track a WaitHandle that was passed into your threadpool delegate so you could block until all of your threadpool threads were completed. Just don't unlock the bits, invalidate, and return until after all of your delegates have finished. However, depending on your release timeframe, you might want to consider using the task parallel library instead of the ThreadPool. C# 4 will include this, but if you can't wait that long, the Mono version works reasonably well today. It actually makes this type of work quite a bit easier than doing it via the ThreadPool.
How to use multiple threads to process an image in sections?
[ "", "c#", "performance", "multithreading", "image-processing", "" ]
I have a method that gets called at the start of my program, and it works fine when I run the jar, but when I run the jnlp file it crashes. ``` public void newImg(String i) { try { File file = new File(i); img = ImageIO.read(file); } } ``` img is a bufferedImage, by the way.
Odds are the path you're giving to the file, or permissions, don't match. Put the File ctor into a try block, catch the exception, and find out what it is. It should look something like this: ``` try { File file = new File(i); img = ImageIO.read(file); } catch (Exception ex) { // You probably want to open the java console, or use a logger // as a JNLP may send stderr someplace weird. Systemm.err.println("Exception was: ", ex.toString()); } ``` The code you have doesn't do anything with the exception. You might want to look at the [exceptions thread](http://java.sun.com/docs/books/tutorial/essential/exceptions/) in the Java Tutorial. ### update See my comments. I just tried something and confirmed what I was thinking -- code with a `try {}` and no `catch` or `finally` won't even compile. if this is really the code you think you're working with, you've probably been loading an old class file; this one hasn't compiled. ``` $ cat Foo.java public class Foo { public void tryit() { try { File f = new File(null); } } } $ javac Foo.java Foo.java:3: 'try' without 'catch' or 'finally' try { ^ 1 error $ ```
Maybe your not loading your image properly. Don't use the relative location of the file. This will be different for each OS. Your image in the JAR you should be loaded correctly like this: ``` URL url = this.getClass().getResource("image.jpg"); Image img = Toolkit.getDefaultToolkit().getImage(url); ``` This will load a file called image.jpg that is located in the same location as the class. You can also use things like File.pathSeparator if its in another location. Use one of these two methods to load it as a resource: <http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)> <http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)>
Java Image messes up when I run the .jnlp file
[ "", "java", "image", "jar", "jnlp", "" ]
So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like ``` proc = subprocess.Popen('sudo apach2ctl restart', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ``` works fine, but as soon as I stick it into a script I start getting: `sudo: apach2ctl: command not found`. I would guess this is due to the way sudo handles environments on ubuntu. (I've also tried `sudo -E apche2ctl restart` and `sudo env path=$PATH apache2ctl restart` with no avail) So my question is basically, if I want to run `apache2ctl restart` as super user that prompts the user for the super user password when required, how should I go about doing this? I have no intention of storing passwords in the script. Edit: I've tried passing in the commands as both a string and tokenized into a list. In the python interpreter, with a string I'll get the password prompt properly (still doesnt work in a python script as in my original problem), a list just gives the help screen for sudo. Edit 2: So what I gather is that while Popen will work with some commands just as strings when shell=True, it takes ``` proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart']) ``` without 'shell=True' to get sudo to work. Thanks!
Try giving the full path to apache2ctl.
Try: `subprocess.call(['sudo', 'apach2ctl', 'restart'])` The subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself. If you don't define them, then it grabs sys.stdout, etc...
running a command as a super user from a python script
[ "", "python", "subprocess", "sudo", "" ]
I have a PHP engine login page which i want to sign in using another PHP file without me physically inputting the details on that page, so i should be able to run a PHP file and sign into another login page on my server
simply have your other PHP file post the required login credentials to your login page's action url
I'm confused, I don't know if I really understood your question! But if it's the case, just send the details of your login form through a post method. And in this other page you'll just check if the login & password are good and start a session for this user!
Sign in into a page using PHP
[ "", "php", "authentication", "" ]
I have a list of Objects (the model) that are constantly appended to (similar to a log file) and I'd like to display as rich text in a JEditorPane (the view). How can I glue them together? <http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#document> doesn't seem to give enough information to use.
You can use `DefaultStyledDocument` together with `AttributeSet`: ``` SimpleAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setBold(attr , true); StyleConstants.setForeground(attr, Color.RED); document.insertString(document.getLenght(),"yourstring", attr)) ```
One simple solution would be to convert each object in the model to HTML and append the strings to create an HTML document that can be set on the JEditorPane.
Java Swing custom text JEditorPane
[ "", "java", "swing", "text", "jeditorpane", "" ]
So I just created a textbox with JavaScript like this: **EDIT: Added the len variable** ``` var len = tbl.rows.length; var rtb = tbl.insertRow(len); var cName = rtb.insertCell(0); var cDis = rtb.insertCell(1); var cDur = rtb.insertCell(2); cName.innerHTML = '<input type="text" name="tbName1' + len + '" value="' + selected_text + '" >'; cDis.innerHTML = '<input type="text" name="tbDis1' + len + '" id="tbDis1' + len + '" >'; cDur.innerHTML = '<input type="text" name="tbDur1' + len + '" >'; var txtBox = document.getElementById('tbDist1' + len); txtBox.focus(); ``` **EDIT:Changed the second to last line.** Still get this error: txtBox is null txtBox.focus(); The last line isn't working. After I create the textbox, I can't set focus to it. Is there any way of doing so?
Hum... you're creating the textbox by saying `id="tbDis1' + len + '"` but you're accessing it by doing `'tbDist1' + (len - 1)`... why? I am not sure about the context, but that would try to focus the previously added textbox, if any. Also, you're creating it with `tbDis` and trying to get to it by using `tbDist`. Missing a `t` in there. Setting the id as `id="tbDist1' + len + '"` and accessing it with `'tbDist1' + (len)` should do the trick.
If you check the value of `txtBox` you will see it is undefined. You try to get the element with id `tbDist1 + (len-1)`, but you create an element with id `tbDis1 + len`.
Setfocus to textbox from JavaScript after just creating the textbox with JavaScript?
[ "", "javascript", "focus", "" ]
I'm trying to collect information from a textfile which contains names of organisations (without spaces) and floating integers. I want to store this information in an array structure. The problem I'm having so far is collecting the information. Here is a sample of the textfile: > CBA 12.3 4.5 7.5 2.9 4.1 > > TLS 3.9 1 8.6 12.8 4.9 I can have up to 128 different numbers for each organisation, and up to 200 organisations in the textfile. This is what my structure looks like so far: ``` struct callCentre { char name[256]; float data[20]; }; ``` My main: ``` int main() { callCentre aCentre[10]; getdata(aCentre); calcdata(aCentre); printdata(aCentre); return 0; } ``` And the getdata function: ``` void getdata(callCentre aCentre[]) { ifstream ins; char dataset[20]; cout << "Enter the name of the data file: "; cin >> dataset; ins.open(dataset); if(ins.good()) { while(ins.good()) { ins >> aCentre[c].name; for(int i = 0; i < MAX; i++) { ins >> aCentre[c].data[i]; if(ins == '\n') break; } c++; } } else { cout << "Data files couldnt be found." << endl; } ins.close(); } ``` What I'm trying to achieve in my getdata function is this: store the organisation name first into the structure, then read each float into the data array until the program detects a newline byte. However, so far my check for the newline byte isn't working. Assume that variables *c* and *MAX* are already defined. How should I go about this properly?
``` char byte = ins.peek(); ``` Or ``` if(ins.peek() == '\n') break; ``` (Edit): You'll want to also check for an eof after your peek(), because some files may not have a ending newline. I'd like to point out that you might want to consider using a `vector<callCentre>` instead of a static array. If your input file length exceeds the capacity of the array, you'll walk all over the stack.
The >> operator treats whitespace as a delimiter, and that includes newlines, so it just eats those and you never see them.
Detect newline byte from filestream
[ "", "c++", "newline", "text-files", "fstream", "" ]
Is there a good java API for manipulating RAR archive files someone could recommend? Googling did not turn up anything overwhelmingly convincing.
You could try [JUnRar](https://github.com/edmund-wagner/junrar), "a RAR handling API implemented in pure Java" (quoting the site).
There is also this fork from SF(@Fabian's answer and this one are forked from an old SF project): <https://github.com/jukka/java-unrar>
RAR archives with java
[ "", "java", "archive", "rar", "" ]
The code I'm working with has its own smart pointer implementation which does simple reference counting. Yes, we shouldn't have our own implementation. Yes, we should be using one from boost or some such. Bear with me. I found I wanted to write code like this: ``` ... CountedPointer<Base> base; ... CountedPointer<Derived> derived; ... base = derived; ``` However, the copy constructor for CountedPointer has a prototype like this: ``` CountedPointer(const CountedPointer<T> &other); ``` So the above code won't compile since it can't find a suitable constructor (or assignment operator - it's the same story there). I tried re-writing the copy constructor with a prototype like this: ``` template<U> CountedPointer(const CountedPointer<U> &other); ``` However, I hit the problem that the copy constructor must access a private member of the object it's copying (i.e. the raw pointer) and if it's in a different specialisation of CountedPointer, they're not visible. Alexandrescu avoids this problem in his library [Loki](http://loki-lib.sourceforge.net/) by having accessor functions for the encapsulated pointer, but I'd prefer not to give direct access to the raw pointer if possible. Is there any way I can write this to allow the derived to base copy, but not allow general access to the raw pointer? **Update:** I've implemented the accepted answer below, and it works well. I spent a while figuring out why my program seg-faulted horribly when I only provided the templated version of the copy constructor, replacing the original un-templated version. Eventually, I realised that the compiler doesn't regard the templated version as being a copy constructor, and provides a default one. The default one just dumbly copies the contents without updating the counter, so I end up with dangling pointers and double frees. The same sort of thing applies to the assignment operator.
Can't you make them friends? Like: ``` template<typename T> class CountedPointer { // ... template<U> CountedPointer(const CountedPointer<U> &other); template<typename U> friend class CountedPointer; }; ```
"Alexandrescu avoids this problem in his library Loki by having accessor functions for the encapsulated pointer, but I'd prefer not to give direct access to the raw pointer if possible" I think the cost of adding a raw pointer getter is going to be much less than the complexity cost of trying to get around not having raw access. There just isn't a language mechanism to convert instances between two unrelated template classes. To the compiler they are two completly different things with no relationship at run time. That's why you one template class instance can't access the others privates. You could consider creating such a relationship with a base class for all CountedPointers. You might have to put a void\* in this base class. Then you'd have to do all the checking yourself (is T derrived from U then force the cast... Can I implicitly convert a T to a U?, if so force a conversion.. etc) but that may get pretty complex. Here's a rough start for this approach: ``` class CountedPointerBase { void* rawPtr; }; template <class T> class CountedPointer : public ConutedPointerBase { T* myRawT = reinterpret_cast<T*>(rawPtr); template<class U> CountedPointer( CountedPointer<U> u) { // Copying a CountedPointer<T> -> CountedPointer<U> if (dynamic_cast<U*>(myRawT) != NULL) { // Safe to copy one rawPtr to another } // check for all other conversions } } ``` There may be a lot of other complexities in seeing if two types are compatible. Maybe there's some Loki/Boost template slickness that can determine for two type arguments if you could cast one to another. Anyway, as you can see, this might be a much more complex solution then just adding a getter. Being able to get the raw pointer has other benefits also. You can pass raw pointers into library functions that only accept raw pointers, and use them as temporaries, for example. It can be dangerous, I suppose, if someone on your team decides to hold onto a copy of the raw pointer as opposed to the smart ptr. That person should probably be summarily trout slapped.
Problems writing a copy constructor for a smart pointer
[ "", "c++", "smart-pointers", "" ]
Currently I'm using XmlSerializer to serialize and deserialize an object. The xml is generated in an undefined order which is understandable but makes it annoying when comparing versions of the object, since the order of properties is different each time. So for instance I can't use a normal diff tool to see any differences. Is there an easy way to generate my xml in the same order every time, without writing the ReadXml and WriteXml methods myself? I have a lot of properties on the class, and add new ones every now and again, so would prefer to not have to write and then maintain that code. (C# .net 2.0)
The XmlElement attribute has an [order property](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.order.aspx). You can use that as a start. If you need to find the diff in Xml files, you might want to take a look at [this](http://msdn.microsoft.com/en-us/library/aa302294.aspx).
Decorate your properties with the [XmlElementAttribute](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.aspx), setting the [Order](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.order.aspx) parameter.
Any way to make XmlSerializer output xml in a defined order?
[ "", "c#", ".net", "xml", "xml-serialization", "" ]
Is there a way to `String.Format` a message without having to specify `{1}, {2},` etc? Is it possible to have some form of auto-increment? (Similar to plain old `printf`)
Afraid not -- where would it put the objects into the string? Using printf, you still need to put specifiers in somewhere.
You can use a [named string formatting](https://stackoverflow.com/questions/159017/named-string-formatting-in-c) solution, which may solve your problems.
Can I pass parameters to String.Format without specifying numbers?
[ "", "c#", ".net", "string", "formatting", "" ]
I've got a student table and an enrollment table; a student could have multiple enrollment records that can be active or inactive. I want to get a select that has a single student record and an indicator as to whether that student has active enrollments. I thought about doing this in an inline UDF that uses the student ID in a join to the enrollment table, but I wonder if there's a better way to do it in a single select statement. The UDF call might look something like: ``` Select Student_Name,Student_Email,isEnrolled(Student_ID) from Student ``` What might the alternative - with one SQL statement - look like?
``` select Student_Name, Student_Email, (select count(*) from Enrollment e where e.student_id = s.student_id ) Number_Of_Enrollments from Student e ``` will get the number of enrollments, which should help.
Why not join to a secondary select? Unlike other solutions this isn't firing a subquery for every row returned, but gathers the enrollment data for everyone all at once. The syntax may not be quite correct, but you should get the idea. ``` SELECT s.student_name, s.student_email, IsNull( e.enrollment_count, 0 ) FROM Students s LEFT OUTER JOIN ( SELECT student_id, count(*) as enrollment_count FROM enrollments WHERE active = 1 GROUP BY student_id ) e ON s.student_id = e.student_id ``` The select from enrollments could also be redone as a function which returns a table for you to join on. ``` CREATE FUNCTION getAllEnrollmentsGroupedByStudent() RETURNS @enrollments TABLE ( student_id int, enrollment_count int ) AS BEGIN INSERT INTO @enrollments ( student_id, enrollment_count ) SELECT student_id, count(*) as enrollment_count FROM enrollments WHERE active = 1 GROUP BY student_id RETURN END SELECT s.student_name, s.student_email, e.enrollment_count FROM Students s JOIN dbo.getAllEnrollmentsGroupedByStudent() e ON s.student_id = e.student_id ``` **Edit:** Renze de Waal corrected my bad SQL!
Getting single records back from joined tables that may produce multiple records
[ "", "sql", "select", "grouping", "user-defined-functions", "group-by", "" ]
I am trying to find a class or something that would allow me to do [Shamir's Secret Sharing](http://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing "Shamir's Secret Sharing"). I found a program in C# that allows you to do it but it does not supply source code. I was just wondering if anyone has a class that already does what I need.
EDIT: As noted in comments, this project doesn't actually have C# source code - but I can't delete the answer now as it's been accepted. Perhaps the OP was actually content to use a wrapper after all. [SecretSharp](http://sourceforge.net/projects/secretsharp/) (linked from the wikipedia article) is GPL - you can [browse the code here](http://secretsharp.svn.sourceforge.net/viewvc/secretsharp/).
I implemented [my own version](https://github.com/moserware/SecretSplitter) of it that also uses PGP encryption. I describe the math behind it and give examples on how to use it in my blog post "[Life, Death, and Splitting Secrets](http://www.moserware.com/2011/11/life-death-and-splitting-secrets.html)". **UPDATE:** It's now available as a [NuGet package](http://www.nuget.org/packages/Moserware.SecretSplitter/) (as well as a detailed [example package](http://www.nuget.org/packages/Moserware.SecretSplitter.Sample/))
Where can I find a C# class for "Shamir's Secret Sharing"?
[ "", "c#", ".net", "security", "" ]
I have a C# program that uses a class from another assembly, and this class calls an unmanaged DLL to do some processing. Here is a snippet: ``` public class Util { const string dllName = "unmanaged.dll"; [DllImport(dllName, EntryPoint = "ExFunc")] unsafe static extern bool ExFunc(StringBuilder path, uint field); public bool Func(string path, uint field) { return ExFunc(new StringBuilder(path), field); } ... } Util util = new Util(); bool val = util.Func("/path/to/something/", 1); ``` The problem I'm having is that if I call "Func" my main C# program will not unload. When I call Close() inside my main form the process will still be there if I look in Task Manager. If I remove the call to "Func" the program unloads fine. I have done some testing and the programs Main function definitely returns so I'm not sure what's going on here.
Do you have the source code to `unmanaged.dll` ? It must be doing something, either starting another thread and not exiting, or blocking in it's `DllMain`, etc.
It might dispatch a non background thread that is not letting go when your main application closes. Can't say for sure without seeing the code but that is what I would assume. It's probably less then ideal, but if you need a workaround you could probably use: ``` System.Diagnostics.Process.GetCurrentProcess().Kill(); ``` This will end your app at the process level and kill all threads that are spawned through the process.
C# program (process) will not unload
[ "", "c#", "interop", ".net-2.0", "unmanaged", "dllimport", "" ]
This is one of the strangest things I have seen. In Firefox 3 for PC, pages for a website we are developing become squeezed narrow, which makes the layout go completely nuts. If you type in <http://www.wms-clients.com/vcb>, the index page looks fine. If you type in <http://wms-clients.com/vcb>, everything is squished. Can anyone with FF3 for PC tell me if they are seeing the same thing, and if so, how I might go about fixing this? Thanks!
Have you been messing with the Text Zoom? I believe zoom settings are stored per domain. Try resetting the Zoom (View -> Zoom -> Reset)
It sounds like it's caching files according to the URL. Try "deleting private data", or press CTRL+F5 and see what happens.
Website page becomes narrow when www prefix is not typed in browser
[ "", "php", "firefox", "rendering", "" ]
I added a google map with two markers (i am just testing), the code is: ``` function load() { var map = new GMap2(document.getElementById("map")); var marker = new GMarker(new GLatLng(<%=coordinates%>)); var marker2 = new GMarker(new GLatLng(31.977211,35.951729)); var html="<%=maptitle%><br/>" + "<%=text%>"; var html2="<img src='simplemap_logo.jpg' width='20' height='20'/> " + "<%=maptitle%><br/>" + "<%=text%>" + "Alper"; map.setCenter(new GLatLng(<%=coordinates%>), 5); map.setMapType(G_HYBRID_MAP); map.addOverlay(marker); map.addOverlay(marker2); map.addControl(new GLargeMapControl()); map.addControl(new GScaleControl()); map.addControl(new GMapTypeControl()); marker.openInfoWindowHtml(html); marker2.openInfoWindowHtml(html2); } ``` The problem is, only one markers text is showing (the white triangle with text inside it) the other is not visible, why? Another thing, i have a table of Maps, its like: mapID, mapCoordinates, mapMarkerTitle, mapMarkerText, i can retrieve this table, but i want a way to be able to pass all its records to my javascript and create a Marker for each Map i have in my table, i know this is two much, but can anyone suggest or help me with the code? as i know nothing about javascript :D The HTML OUTPUT is: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title> Untitled Page </title> <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAANgu3GlobW5KtQorgXrnJ_xTHM4EYhrvsce8mdg4KdiCoPfCQKxSOZ_5sjy4O31twg6cxfZqam24TCw" type="text/javascript"></script> <script type="text/javascript"> function load() { var map = new GMap2(document.getElementById("map")); var marker = new GMarker(new GLatLng(32.523251,35.816068)); var marker2 = new GMarker(new GLatLng(31.977211,35.951729)); var html="maen<br/>" + " maen tamemi"; var html2="<img src='simplemap_logo.jpg' width='20' height='20'/> " + "maen<br/>" + " maen tamemi" + "Alper"; map.setCenter(new GLatLng(32.523251,35.816068), 5); map.setMapType(G_HYBRID_MAP); map.addOverlay(marker); map.addOverlay(marker2); map.addControl(new GLargeMapControl()); map.addControl(new GScaleControl()); map.addControl(new GMapTypeControl()); marker2.openInfoWindowHtml(html2); marker.openInfoWindowHtml(html); } //]]> </script> <script type="text/javascript"> function pageLoad() { } </script> </head> <body onload = "load()"> <form name="form1" method="post" action="Xhome.aspx" id="form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNDI5NDcxNTY4ZGTjxbb38769ZB2N9Ow9kAzPz2PIqA==" /> </div> <div id="map" style="width:400px;height:300px" > </div> </form> </body> </html> ```
In response to the second part of your question: > i want a way to be able to pass all its records to my javascript and create a Marker for each Map i have in my table I have (as an example - written a year or so ago) the following code: In the code-behind I have something like this (c# I'm afraid): ``` [WebMethod] public LatitudeLogitudeMessage[] GetPoints(string postCodes) { string[] postCodeArray = postCodes.Split(",".ToCharArray()); LatitudeLogitudeMessage[] pointArray = new LatitudeLogitudeMessage[postCodeArray.Length]; int index = 0; foreach (string postCode in postCodeArray) { pointArray[index] = GetPoint(postCode); index++; } return pointArray; } ``` LatitudeLogitudeMessage is a custom class that looks like this: ``` public class LatitudeLogitudeMessage { public decimal? Latitude { get; set; } public decimal? Longitude { get; set; } public string Message { get; set; } public string Details { get; set; } public string Address { get; set; } public LatitudeLogitudeMessage(string addressToFind) { Address = addressToFind; Details = addressToFind.Replace(",", ",<br />"); } } ``` The GetPoint method bascially fills in those details. In the code infront I then had: ``` PageMethods.GetPoints(address, showPoints); ``` Which calls the GetPoints method on the code behind, and passes the result to showPoints: ``` function showPoints(latLongs) { GLog.write("Showing points"); var points = []; var latLngBounds = new GLatLngBounds(); for (var i = 0; i < latLongs.length; i++) { if ("" == latLongs[i].Message) { points[i] = new GLatLng(latLongs[i].Latitude, latLongs[i].Longitude); var marker = new GMarker(points[i], {title: latLongs[i].Details, clickable: false}); map.addOverlay(marker); latLngBounds.extend(points[i]); } else { GLog.write(latLongs[i].Message); } } if (points.length > 1) { var bounds = new GBounds(points); var center = new GLatLng( (latLngBounds.getSouthWest().lat() + latLngBounds.getNorthEast().lat()) /2., (latLngBounds.getSouthWest().lng() + latLngBounds.getNorthEast().lng()) /2.); var newZoom = map.getBoundsZoomLevel(latLngBounds, map.getSize()); map.setCenter(center, newZoom); } else { map.setCenter(points[0], defaultZoomLevel); } } ``` So this takes the array of points, and iterates over them creating a marker as it goes, centering on the first item in the list (not clever, but it worked for me).
Try the [Marker Manager API](http://googlemapsapi.blogspot.com/2006/11/marker-manager.html), it's easier to deal with. Here's the Google example: ``` function setupMap() { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.setCenter(new GLatLng(41, -98), 4); window.setTimeout(setupWeatherMarkers, 0); } } function getWeatherMarkers(n) { var batch = []; for (var i = 0; i < n; ++i) { batch.push(new GMarker(getRandomPoint(), { icon: getWeatherIcon() })); } return batch; } function setupWeatherMarkers() { mgr = new GMarkerManager(map); mgr.addMarkers(getWeatherMarkers(20), 3); mgr.addMarkers(getWeatherMarkers(200), 6); mgr.addMarkers(getWeatherMarkers(1000), 8); mgr.refresh(); } ```
Multiple Markers on a Google Map
[ "", "asp.net", "javascript", "vb.net", "api", "google-maps", "" ]
I have Visual Studio 2008 and I find myself constantly adding the same 3 or 4 using statements with every file I create.... Is there a way that I can define these somewhere in VS so every time I create a file this standard set of includes are added?
You can create a template that matches what you want, as per <http://msdn.microsoft.com/en-us/magazine/cc188697.aspx>
You can do it by editing Visual Studio Item templates. More information [here](http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2761)
How to add a standard set of 'using' statements in VS?
[ "", "c#", "visual-studio-2008", "" ]
I have code similar to this: ``` class Foo { List<Bar> _myList; ... public IEnumerable<Bar> GetList() { return _myList; } } ``` The result of GetList() should **NOT** be mutable. To clarify, it is ok if instances of Bar are modified. I simply want to make sure the collection itself is not modified. I'm sure I read an answer somewhere on SO where someone pointed this was possible, but for the life of me, I can't find it again.
The answers already provided will work absolutely fine, but I just thought I'd add that you can use the *AsReadOnly* extension method in .NET 3.5, as such: ``` class Foo { List<Bar> _myList; ... public ReadOnlyCollection<Bar> GetList() { return _myList.AsReadOnly(); } } ```
You can use System.Collections.ObjectModel.ReadOnlyCollection ``` public ReadOnlyCollection<Bar> GetList() {return new ReadOnlyCollection<Bar>(_myList);} ```
Can I have a non-mutable IEnumerable<>?
[ "", "c#", ".net", "" ]
I'm writing a python application that will make heavy use of a graph data structure. Nothing horribly complex, but I'm thinking some sort of graph/graph-algorithms library would help me out. I've googled around, but I don't find anything that particularly leaps out at me. Anyone have any good recommendations?
There are two excellent choices: [NetworkX](http://networkx.github.io/) and [igraph](http://igraph.org/) I like NetworkX, but I read good things about igraph as well. I routinely use NetworkX with graphs with 1 million nodes with no problem (it's about double the overhead of a dict of size V + E) If you want a feature comparison, see this from the Networkx-discuss list [Feature comparison thread](http://groups.google.com/group/networkx-discuss/t/7597ca97abbb3f90?hl=en)
I would like to plug my own graph python library: [graph-tool](http://graph-tool.skewed.de). It is very fast, since it is implemented in C++ with the Boost Graph Library, and it contains lots of algorithms and extensive documentation.
Python Graph Library
[ "", "python", "graph", "" ]
I've got the following code : ``` public class A { ~A() { Console.WriteLine("destructor"); } } public static A Aref; static void Main(string[] args) { Aref = new A(); int gen = GC.GetGeneration(Aref); Aref = null; GC.Collect(gen, GCCollectionMode.Forced); Console.WriteLine("GC done"); } ``` I thought my Finalizer method would be called upon my call to GC.Collect, which is not the case. Can anyone explain me why ?
Finalizers aren't called before `GC.Collect()` returns. The finalizers are run in a separate thread - you can wait for them by calling `GC.WaitForPendingFinalizers()`.
The finalizer is not called during the collection in your example, cause it is still being rooted by the finalizable queue. It is however scheduled for finalization, which means that it will be collected during the next garbage collection. If you want to make sure instances of types with a finalizer are collected you need to do two collections like this. ``` GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); ``` But generally you should not call the `Collect()` method yourself.
Why isn't my .net destructor called in this very simple scenario?
[ "", "c#", ".net", "garbage-collection", "destructor", "finalizer", "" ]
**Note:** * Attempting to invoke a method of an interface, of which the return type is `_variant_t` **Code:** ``` _variant_t resultsDataString; _bstr_t simObjectNames; simObjectNames = SysAllocString (L"TEST example 3"); resultsDataString = pis8->GetSimObject (simObjectNames); ``` inline function **illustrated** below, contained in **.tli** FILE: ``` inline _variant_t IS8Simulation::GetSimObject ( _bstr_t Name ) { VARIANT _result; VariantInit(&_result); HRESULT _hr = get_SimObject(Name, &_result); if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this)); return _variant_t(_result, false); } ``` **Note:** * `resultsDataString` is of **`struct` `tagVARIANT`**: + **`VARTYPE vt`** is 9 (unsigned short) + **`IDispatch`** IDispatch interface pointer **Question** * How can I then **convert** or **extract** the value? * Possible using [VariantChangeType](http://msdn.microsoft.com/en-us/library/ms221258.aspx)? * Another way? ## Edit: **Note:** * Looking to transform the following, Visual Basic code to Visual C++ * MFC or ATL, if need be * Ideally, pure C++ **Visual basic** equivalent: ``` Public example1, example2 As SIMUL8.S8SimObject Dim numberOfexamples As Variant Dim resultString As Variant Set example1 = MySimul8.SimObject("Example 1") Set example2 = MySimul8.SimObject("Example 2") numberOfexamples = example1.CountContents + example2.CountContents resultString = CStr(numberOfexamples) & "*" ```
It appears you are using C++ as a COM client by relying on the VC++ compiler's built-in COM support. To make coding the client "easier" you've used `#import` to generate C++ wrapper classes that attempt to hide all the COM details from you - or at least make the COM details simpler. So you're *not* using the COM SDK directly, but are using a client-side framework (I think of it like a light-weight COM-only framework akin to ATL or MFC). Your example code, however, seems to be mixing the direct low-level COM SDK (`VARIANT`s, `BSTR`, `SysAllocString`) with the `#import` COM framework (`_variant_t`, `_bstr_t`, `XXXXPtr`). COM from C++ is complicated at first - so in a perfect world I would suggest getting to know the basics of COM before going too far forward. However, if you just want something to work I would ***guess*** this is `#import`-style-of-COM-clients version of the VB code you provided: ``` _variant_t example1Var; _variant_t example1Var; SIMUL8::S8SimObjectQIPtr example1; // I'm guessing at this type-name from the VB code SIMUL8::S8SimObjectQIPtr example2; example1Var = pis8->GetSimObject(_bstr_t(L"Example 1")); example2Var = pis8->GetSimObject(_bstr_t(L"Example 2")); if (example1Var.vt == VT_DISPATCH && example2Var.vt == VT_DISPATCH) { // **UPDATE** to try to spoon feed the QI ptr... example1 = IDispatchPtr((IDispatch*)example1Var); example2 = IDispatchPtr((IDispatch*)example2Var); // Does this screw-up reference counting? int numberOfexamples = example1->CountContents + example2->CountContents; } ``` **UPDATE:** [Documentation on `#import`](http://msdn.microsoft.com/en-us/library/8etzzkb6(VS.71).aspx) This makes using COM from C++ much easier, but is yet one other thing to learn...
Take a look at the MSDN docs for [\_variant\_t](http://msdn.microsoft.com/en-us/library/x295h94e.aspx) There is a [ChangeType](http://msdn.microsoft.com/en-us/library/2kc812h8.aspx) method as well as [Extractors](http://msdn.microsoft.com/en-us/library/ew0bcz27.aspx). **Edit:** Once you have an `IDispatch` pointer, you need to use `QueryInterface` to get a specific object type with members and methods, or use `IDispatch::Invoke`. You can look at the MSDN Docs for `IDispatch`. Either way, you need to know about the object type that is being returned by the `IS8Simulation::GetSimObject` call. **Edit #2:** Based on your VB code update, you want to use the same kind of code for C++, i.e. use the `S8SimObject` type in its C++ form (look in the generated .tlh file for `_COM_SMARTPTR_TYPEDEF`). Then you can directly do the same thing with `CountContents`. Otherwise, you would need to look up the `CountContents` DISPID with `IDispatch::GetIDsOfNames` and then call invoke.
Convert VARIANT to...?
[ "", "c++", "windows", "vb.net", "visual-studio-2008", "com", "" ]
I have a object that is my in memory state of the program and also have some other worker functions that I pass the object to to modify the state. I have been passing it by ref to the worker functions. However I came across the following function. ``` byte[] received_s = new byte[2048]; IPEndPoint tmpIpEndPoint = new IPEndPoint(IPAddress.Any, UdpPort_msg); EndPoint remoteEP = (tmpIpEndPoint); int sz = soUdp_msg.ReceiveFrom(received_s, ref remoteEP); ``` It confuses me because both `received_s` and `remoteEP` are returning stuff from the function. Why does `remoteEP` need a `ref` and `received_s` does not? I am also a c programmer so I am having a problem getting pointers out of my head. Edit: It looks like that objects in C# are pointers to the object under the hood. So when you pass an object to a function you can then modify the object contents through the pointer and the only thing passed to the function is the pointer to the object so the object itself is not being copied. You use ref or out if you want to be able to switch out or create a new object in the function which is like a double pointer.
Short answer: read my [article on argument passing](http://pobox.com/~skeet/csharp/parameters.html). Long answer: when a reference type parameter is passed by value, only the reference is passed, *not* a copy of the object. This is like passing a pointer (by value) in C or C++. Changes to the value of the parameter itself won't be seen by the caller, but changes in the object which the reference points to *will* be seen. When a parameter (of any kind) is passed *by* reference, that means that any changes to the parameter are seen by the caller - changes to the parameter *are* changes to the variable. The article explains all of this in more detail, of course :) Useful answer: **you almost never need to use ref/out**. It's basically a way of getting another return value, and should usually be avoided precisely because it means the method's probably trying to do too much. That's not always the case (`TryParse` etc are the canonical examples of reasonable use of `out`) but using ref/out should be a relative rarity.
Think of a non-ref parameter as being a pointer, and a ref parameter as a double pointer. This helped me the most. You should almost never pass values by ref. I suspect that if it wasn't for interop concerns, the .Net team would never have included it in the original specification. The OO way of dealing with most problem that ref parameters solve is to: **For multiple return values** * Create structs that represent the multiple return values **For primitives that change in a method as the result of the method call** (method has side-effects on primitive parameters) * Implement the method in an object as an instance method and manipulate the object's state (not the parameters) as part of the method call * Use the multiple return value solution and merge the return values to your state * Create an object that contains state that can be manipulated by a method and pass that object as the parameter, and not the primitives themselves.
When to use ref and when it is not necessary in C#
[ "", "c#", "ref", "" ]
Pointers present some special problems for overload resolution. Say for example, ``` void f(int* x) { ... } void f(char* x) { ...} int main() { f(0); } ``` What is wrong with calling f(0)? How can I fix the function call for f(0)?
`f((int*) 0)` or `f((char *) 0)` But if you find yourself doing this I would take another look at your design.
Cast it, or don't use it at all: ``` f((int*)0); ```
Pointer problems with overloading in C++?
[ "", "c++", "pointers", "overloading", "" ]
There exist tools for comparing code against a custom specified set of coding guidelines/standards for a variety of languages (rather than pure static analysis for common defects). Examples include [FxCop](http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx) for .Net code and [CheckStyle](http://checkstyle.sourceforge.net/) for Java, but I was wondering what examples people know of in the C++ world. [An existing question was asked regarding free tools](https://stackoverflow.com/questions/93260/a-free-tool-to-check-c-c-source-code-against-a-set-of-coding-standards) which provided examples like [Vera](http://www.inspirel.com/vera/) but I was also wondering about commercial tools that may be available.
The full list that I managed to generate: * [PRQA's QA C++](http://www.programmingresearch.com/QACPP_MAIN.html#1_1) * [Parasoft's C++Test](http://www.parasoft.com/jsp/products/home.jsp?product=CppTest&itemId=47) * [MS Visual Studio Team System](http://msdn.microsoft.com/en-us/library/ms181459(VS.80).aspx) seems to have some functionality but it's hard to tell via their website. * [GrammaTech CodeSonar](http://www.grammatech.com/products/codesonar/overview.html) * [Coverity Extend](http://www.coverity.com/products/static-analysis-extend.html) The last two provide some functionality but not particularly customisable ones: * [Klocwork Insight](http://www.klocwork.com/) * [Rational PurifyPlus](http://www-01.ibm.com/software/awdtools/purifyplus/win/features/?S_CMP=wspace)
A tool used by us was CodeWizard from Parasoft. But I think the new version is called "Parasoft C++ Test". From the homepage: * Static analysis of code for compliance with user-selected coding standards * Graphical RuleWizard editor for creating custom coding rules * Static code path simulation for identifying potential runtime errors * Automated code review with a graphical interface and progress tracking * Automated generation and execution of unit and component-level tests * Flexible stub framework * Full support for regression testing * Code coverage analysis with code highlighting * Runtime memory error checking during unit test execution * Full team deployment infrastructure for desktop and command line usage
What tools exist for comparing C++ code to coding guidelines?
[ "", "c++", "coding-style", "" ]
in c++, <stdexcept> has a base class for 'domain errors', std::domain\_error. i don't understand under what circumstances i should throw a domain error in my code. all of the other exception base classes are pretty self explanatory. i'm pretty sure that std::domain\_error has nothing to do with internet domain names, per se, so please explain what class of error a domain error is and provide some examples.
Domain and range errors are both used when dealing with mathematical functions. On the one hand, the domain of a function is the set of values that can be accepted by the function. For example, the domain of the root square function is the set of positive real numbers. Therefore, a [`domain_error`](http://en.cppreference.com/w/cpp/error/domain_error) exception is to be thrown when the arguments of a function are not contained in its domain On the other hand, the range of a function is the set of values that the function can return. For example, the range of a function like this one: ``` f(x) = -x² ``` is the set of negative real numbers. So what is the point of the `range_error`? If the arguments of the function are in its domain, then the result must be in its range, so we shouldn't have any errors wrt the range...However, sometimes the value can be *defined*, but without being *representable*. For example, in C, the functions in `<math.h>` generate errors if the return value is too large (or too small) in magnitude to represent
A *domain error* refers to issues with *mathematical domains* of functions. Functions are sometimes defined only for certain values. If you try to invoke such a function with an argument that is not part of its domain, that is a domain error. For example, trying to invoke `sqrt()` with a negative argument is a domain error, since negative numbers are not part of the domain of `sqrt()`.
what is a domain error
[ "", "c++", "stl", "" ]
I'm creating a web service, which run in GlassFish, and I want to have some custom properties. For this I'm using the `Properties` class. The code I'm using is: ``` Properties p=new Properties(); File f=new File(System.getProperty("user.dir"), "settings.properties"); p.load(new FileInputStream(f)); ``` But how do I get the `settings.properties`-file in my config directory? I'm not sure about my classpath, since this is managed by NetBeans and GlassFish. I assume my `.war`-file is added to the classpath, when deploying... I've added my own solution, but if anyone could come up with a better solution, it would be highly welcome...
The solution that works is actually pretty simple: ``` URL url = this.getClass().getResource("/package/name/file.properties"); p = new Properties(); p.load(new FileInputStream(new File(url.getFile()))); ``` Why didn't anybody come with this?
Place your property files in the ***<glassfish-install-dir>/glassfish/domains/<domain-name>/lib/classes*** directory and they will be accessible from within your applications via the *ResourceBundle* class. For example, add a property file named *settings.properties* to this directory and then access values from the file like this: > ResourceBundle.getBundle("settings").getString("my-property-key");
How to use a property-file with GlassFish
[ "", "java", "configuration", "jakarta-ee", "glassfish", "" ]
I am writing a simple C++ application which might be installed on Linux or Windows, and which will connect to a database. I want my application to be compatible at least with Oracle and MySQL (or PostgreSQL). Which C or C++ library would you recommend to handle the database queries: I am open to any library, whether it's very thin (just execute SQL queries) or very fat (a whole object persistence layer, clustering, etc.). One library per answer, please. A little description (pros & cons) would be great. Thanks a lot.
I enjoy using [SOCI](http://soci.sourceforge.net/), it's very C++ like. When it comes to performance with respect to Oracle database, it's comparable with native OCI. It provides backend to some RDBMS: * Oracle * PostgreSQL * MySQL And some more in the CVS repository. It's fairly simple to use, the documentation is thorough and rationale is pretty clear. It supports connection pooling, has nice extensible way of converting between datatypes.
I really liked [QtSql](https://doc.qt.io/qt-5/qtsql-index.html) * It has the advantage of being well designed and cross platform. * Disadvantage is that it's LGPLv3 (or commercial) licensed and that might not work for everybody. You don't have to use a Qt GUI, but if you need a GUI library too it's wonderful.
What is your favorite cross-platform solution to access multiple different databases (MySQL, Oracle...) in C/C++?
[ "", "c++", "c", "database", "cross-platform", "" ]
I've set a [website](http://www.dur.ac.uk/trevelyan.alumni/) up. If I try and click on a link such as [register](http://www.dur.ac.uk/trevelyan.alumni/register) I get the following error: ``` 404 | Not Found | sfError404Exception Empty module and/or action after parsing the URL "/trevelyan.alumni/register" (/). ``` The links are generated using ``` <?php print link_to( 'Register', 'register/index' ); ?> ``` And I have a 'register' module in apps/frontend/modules/register. I'm quite new to Symfony, any help is appreciated! --- routing.yml: ``` # default rules homepage: url: / param: { module: home, action: index } default_index: url: /:module param: { action: index } default: url: /trevelyan.alumni/:module/:action/* ```
I think that your problem is that you're running symfony out of a "sub-site" instead of directly off of the "root" url (<http://www.dur.ac.uk/trevelyan.alumni> instead of <http://www.dur.ac.uk/>). I think the easiest solution would be to add `trevelyan.alumni` to the front of all your urls in routing.yml. For example, for the `default` route, instead of ``` default: url: /:module/:action/* ``` use ``` default: url: /trevelyan.alumni/:module/:action/* ```
I managed to fix this by editing the symfony controller files to use the $\_SERVER variables to pick a module from, if one was not found.
link_to() generates route successfully, but clicking on that link results in a 404
[ "", "php", "symfony1", "" ]
I am trying to make a Visual C++ 2008 program that plots some data in a Window. I have read from [various](http://www.informit.com/articles/article.aspx?p=328647&seqNum=3) [places](http://msdn.microsoft.com/en-us/library/aa922023.aspx) the correct way to do this is to override WndProc. So I made a Windows Forms Application in Visual C++ 2008 Express Edition, and I added this code to Form1.h, but it won't compile: ``` public: [System::Security::Permissions::PermissionSet(System::Security::Permissions::SecurityAction::Demand, Name="FullTrust")] virtual void WndProc(Message %m) override { switch(m.Msg) { case WM_PAINT: { HDC hDC; PAINTSTRUCT ps; hDC = BeginPaint(m.HWnd, &ps); // i'd like to insert GDI code here EndPaint(m.Wnd, &ps); return; } } Form::WndProc(m); } ``` When I try to compile this in Visual C++ 2008 Express Edition, this error occurs: **error C2664: 'BeginPaint' : cannot convert parameter 1 from 'System::IntPtr' to 'HWND'** When I try using this->Handle instead of m.HWnd the same error occurs. When I try casting m.HWnd to (HWND), this error occurs: **error C2440: 'type cast' : cannot convert from 'System::IntPtr' to 'HWND'** Maybe I need to cast the m.HWnd to a pin\_ptr or something.
If you were making a raw Win32 application then you could use those functions. If, on the other hand, you are making a WinForms application then you need to override the OnPaint event. * Switch to the design view (The view that shows your form.) * Click on the title bar of your form * In the properties window (by default probably on your lower right screen) select the lightning bolt near the top. This will display a list of events. * Scroll down to the paint event and double click it. You will end up with a Paint routine shell from which you can use the drawing functions of the graphics object. ``` private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) { e->Graphics->DrawRectangle(...) } ``` If you really want to write raw Win32 code, let me know, and I can help you write a shell. In the time being if you are interested in Win32 I recommend Charles Petzold's Programming Windows 5th edition. If you want to learn C++ WinForms... well, I recommend switching to C# or VB.NET simply because they might be more intuitive. Hope this helps. Cheers.
The articles you refer to discuss how to do in a native C++ application, not in a WinForms app. You should override OnPaint method instead of handling the message in the WndProc.
Correct value for hWnd parameter of BeginPaint?
[ "", ".net", "c++", "gdi", "" ]
Is there a way to rewrite this query using the Django QuerySet object: ``` SELECT b.created_on, SUM(a.vote) FROM votes a JOIN votes b ON a.created_on <= b.created_on WHERE a.object_id = 1 GROUP BY 1 ``` Where votes is a table, object\_id is an int that occurs multiple times (foreign key - although that doesn't matter here), and created\_on which is a datetime. FWIW, this query allows one to get a score at any time in the past by summing up all previous votes on that object\_id.
I'm pretty sure that query cannot be created with the Django ORM. The new Django aggregation code is pretty flexible, but I don't think it can do exactly what you want. Are you sure that query works? You seem to be missing a check that b.object\_id is 1. This code should work, but it's more than one line and not that efficient. ``` from django.db.models import Sum v_list = votes.objects.filter(object__id=1) for v in v_list: v.previous_score = votes.objects.filter(object__id=1, created_on__lte=v.created_on).aggregate(Sum('vote'))["vote__sum"] ``` Aggregation is only available in trunk, so you might need to update your django install before you can do this.
Aggregation isn't the issue; the problem here is that Django's ORM simply doesn't do joins on anything that isn't a ForeignKey, AFAIK.
Django 1.0/1.1 rewrite of self join
[ "", "sql", "django", "group-by", "sum", "" ]
I'm going to be implementing a lightweight formatting language (probably Textile, maybe Markdown) in a project I'm working on, and I'm wonder how best to store it in the database. If the user is able to edit the content they're posting, it makes sense to me that the original, non-converted markup be stored so that the user doesn't have to edit HTML the next time around. But since the content is going to be displayed a whole lot more than edited, it also makes sense to store a converted copy of the content so that the original doesn't have to be sent through Textile on every page view. So, is the common practice to store both the original and converted content side-by-side in the database? Is there a better way? Thanks!
Store markdown: * Every view = conversion * Every edit = no processing Store html * Every view = no processing * Every edit = convert to markdown and back Store both * Every view = no processing * Every edit = convert to html after edit You have to weigh up your processing costs vs. your storage cost.
You should definetly store original Textile/Markdown markup and use either standard HTTP caching stuff (Last-modified, Expires-At, ETag) to cache rendered pages or just cache the result of processing markup.
How to store lightweight formatting (Textile, Markdown) in database?
[ "", "php", "database", "markdown", "markup", "textile", "" ]
I know that setCouponCode is catch inside \_\_call in Varien\_Object but I can't figure out where it is defined. I need it because I want to show the coupon code even if the discount equal zero. I believed it's done inside this function. So if anybody know where the function is defined or where I can modify the code to get the coupon code displayed all the time, please let me know.
Ok I figured it out. the SetCouponCode is setting the value for coupon\_code in the magic function.
Most text editors have a 'search in files/folders' option. Open the source folder and search for function \_\_setCouponCode.
Where is the setCouponCode function is defined in Magento
[ "", "php", "magento", "cart", "rule", "coupon", "" ]
Not sure if I worded this correctly ... but I have the following code: ``` public Guid ItemId { get; } public TransactionItem() { this.ItemId = Guid.Empty; } ``` Naturally I am getting a read-only issue ... which I do understand. Is there anyway to set this property value without having to do something like the below: ``` Guid _itemId = Guid.Empty; public Guid ItemId { get { return _itemId; } set { _itemId = value; } } ``` or ``` public Guid ItemId { get; internal set; } ``` Thanks in advance!
I would go for this: ``` public Guid ItemId { get; private set; // can omit as of C# 6 } public TransactionItem() { this.ItemId = Guid.Empty; } ``` Of course, it would be open for setting within this class, but since you are writing it I hope you have the sense to not break your own intentions... In my opinion, things like readonly properties, are mostly important when seen from the outside. From the inside, it doesn't really matter what it is, cause there, you are the King =)
If you just need the `ItemId` property to be read-only for external users of your class, then Svish's answer is the way to go. If you need `ItemId` to be read-only within the class itself then you'll need to do something like this: ``` private readonly Guid _ItemId public Guid ItemId { get { return _ItemId; } } public TransactionItem() { _ItemId = Guid.Empty; } ```
How to set the value of a read-only property with generic getters and setters?
[ "", "c#", "properties", "" ]
If I am correct, SimpleTest will allow you to assert a PHP error is thrown. However, I can't figure out how to use it, based on the documentation. I want to assert that the object I pass into my constructor is an instance of `MyOtherObject` ``` class Object { public function __construct(MyOtherObject $object) { //do something with $object } } //...and in my test I have... public function testConstruct_ExpectsAnInstanceOfMyOtherObject() { $notAnObject = 'foobar'; $object = new Object($notAnObject); $this->expectError($object); } ``` Where am I going wrong?
Type hinting throws E\_RECOVERABLE\_ERROR which can be caught by SimpleTest since PHP version 5.2. The following will catch any error containing the text "must be an instance of". The constructor of PatternExpectation takes a perl regex. ``` public function testConstruct_ExpectsAnInstanceOfMyOtherObject() { $notAnObject = 'foobar'; $this->expectError(new PatternExpectation("/must be an instance of/i")); $object = new Object($notAnObject); } ```
Turns out, SimpleTest doesn't actually support this. You can't catch Fatal PHP errors in SimpleTest. Type hinting is great, except you can't test it. Type hinting throws fatal PHP errors.
SimpleTest: How to assert that a PHP error is thrown?
[ "", "php", "unit-testing", "simpletest", "" ]
I have a string property that has a maximum length requirement because the data is linked to a database. What exception should I throw if the caller tries to set a string exceeding this length? For example, this C# code: ``` public string MyProperty { get { return _MyBackingField; } set { if (value.Length > 100) throw new FooException("MyProperty has a maximum length of 100."); _MyBackingField = value; } } ``` I considered `ArgumentException`, but it just doesn't seem right. *Technically*, it is a function - `MyProperty_set(string value)` - so a case for `ArgumentException` can be made, but it's not being called as a function to the consumer's eyes - it's on the right side of an assignment operator. This question could probably also be extended to include all kinds of data validation done in property setters, but I'm particularly interested in the above case.
Have a look through mscorlib.dll with Reflector, in a similar situation such as System.String.StringBuilder.Capacity Microsoft use ArgumentOutOfRangeException() similar to: ``` public int PropertyA { get { return //etc... } set { if (condition == true) { throw new ArgumentOutOfRangeException("value", "/* etc... */"); } // ... etc } } ```
To me ArgumentException (or a child) makes more sense, because the argument (value) you provided is not valid, and this is what ArgumentException was created for.
What exception to throw from a property setter?
[ "", "c#", "validation", "exception", "properties", "" ]
I have a table of player performance: ``` CREATE TABLE TopTen ( id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, home INT UNSIGNED NOT NULL, `datetime`DATETIME NOT NULL, player VARCHAR(6) NOT NULL, resource INT NOT NULL ); ``` What query will return the rows for each distinct `home` holding its maximum value of `datetime`? In other words, how can I filter by the maximum `datetime` (grouped by `home`) and still include other non-grouped, non-aggregate columns (such as `player`) in the result? For this sample data: ``` INSERT INTO TopTen (id, home, `datetime`, player, resource) VALUES (1, 10, '04/03/2009', 'john', 399), (2, 11, '04/03/2009', 'juliet', 244), (5, 12, '04/03/2009', 'borat', 555), (3, 10, '03/03/2009', 'john', 300), (4, 11, '03/03/2009', 'juliet', 200), (6, 12, '03/03/2009', 'borat', 500), (7, 13, '24/12/2008', 'borat', 600), (8, 13, '01/01/2009', 'borat', 700) ; ``` the result should be: | id | home | datetime | player | resource | | --- | --- | --- | --- | --- | | 1 | 10 | 04/03/2009 | john | 399 | | 2 | 11 | 04/03/2009 | juliet | 244 | | 5 | 12 | 04/03/2009 | borat | 555 | | 8 | 13 | 01/01/2009 | borat | 700 | I tried a subquery getting the maximum `datetime` for each `home`: ``` -- 1 ..by the MySQL manual: SELECT DISTINCT home, id, datetime AS dt, player, resource FROM TopTen t1 WHERE `datetime` = (SELECT MAX(t2.datetime) FROM TopTen t2 GROUP BY home) GROUP BY `datetime` ORDER BY `datetime` DESC ``` The result-set has 130 rows although database holds 187, indicating the result includes some duplicates of `home`. Then I tried joining to a subquery that gets the maximum `datetime` for each row `id`: ``` -- 2 ..join SELECT s1.id, s1.home, s1.datetime, s1.player, s1.resource FROM TopTen s1 JOIN (SELECT id, MAX(`datetime`) AS dt FROM TopTen GROUP BY id) AS s2 ON s1.id = s2.id ORDER BY `datetime` ``` Nope. Gives all the records. I tried various exotic queries, each with various results, but nothing that got me any closer to solving this problem.
You are so close! All you need to do is select BOTH the home and its max date time, then join back to the `topten` table on BOTH fields: ``` SELECT tt.* FROM topten tt INNER JOIN (SELECT home, MAX(datetime) AS MaxDateTime FROM topten GROUP BY home) groupedtt ON tt.home = groupedtt.home AND tt.datetime = groupedtt.MaxDateTime ```
The fastest `MySQL` solution, without inner queries and without `GROUP BY`: ``` SELECT m.* -- get the row that contains the max value FROM topten m -- "m" from "max" LEFT JOIN topten b -- "b" from "bigger" ON m.home = b.home -- match "max" row with "bigger" row by `home` AND m.datetime < b.datetime -- want "bigger" than "max" WHERE b.datetime IS NULL -- keep only if there is no bigger than max ``` **Explanation**: Join the table with itself using the `home` column. The use of `LEFT JOIN` ensures all the rows from table `m` appear in the result set. Those that don't have a match in table `b` will have `NULL`s for the columns of `b`. The other condition on the `JOIN` asks to match only the rows from `b` that have bigger value on the `datetime` column than the row from `m`. Using the data posted in the question, the `LEFT JOIN` will produce this pairs: ``` +------------------------------------------+--------------------------------+ | the row from `m` | the matching row from `b` | |------------------------------------------|--------------------------------| | id home datetime player resource | id home datetime ... | |----|-----|------------|--------|---------|------|------|------------|-----| | 1 | 10 | 04/03/2009 | john | 399 | NULL | NULL | NULL | ... | * | 2 | 11 | 04/03/2009 | juliet | 244 | NULL | NULL | NULL | ... | * | 5 | 12 | 04/03/2009 | borat | 555 | NULL | NULL | NULL | ... | * | 3 | 10 | 03/03/2009 | john | 300 | 1 | 10 | 04/03/2009 | ... | | 4 | 11 | 03/03/2009 | juliet | 200 | 2 | 11 | 04/03/2009 | ... | | 6 | 12 | 03/03/2009 | borat | 500 | 5 | 12 | 04/03/2009 | ... | | 7 | 13 | 24/12/2008 | borat | 600 | 8 | 13 | 01/01/2009 | ... | | 8 | 13 | 01/01/2009 | borat | 700 | NULL | NULL | NULL | ... | * +------------------------------------------+--------------------------------+ ``` Finally, the `WHERE` clause keeps only the pairs that have `NULL`s in the columns of `b` (they are marked with `*` in the table above); this means, due to the second condition from the `JOIN` clause, the row selected from `m` has the biggest value in column `datetime`. Read the [SQL Antipatterns: Avoiding the Pitfalls of Database Programming](https://pragprog.com/book/bksqla/sql-antipatterns) book for other SQL tips.
How can I SELECT rows with MAX(Column value), PARTITION by another column in MYSQL?
[ "", "mysql", "sql", "max", "distinct", "greatest-n-per-group", "" ]
Hello I am looking to install Apache-Tomcat on a RedHat linux and I am interested if there is a standard place for this to be installed. in other work I have seen tomcat installed at /opt/apache-tomcat-[VERSION]/ but I would expect it to be found under /usr. Best answer will have a link to authoritative site. Thanks so much, David.
I don't know if there's such a thing as an "official" place, but a reasonable thing to do would be to do what you've done and refer to tomcat through a softlink at /usr/local/tomcat or some such, which would allow you to upgrade versions by simply installing a new version in opt and changing the softlink.
It depends on who you ask, but I see it this way: /opt is typically for third-party add-on software. /usr/ is often for 'system' software. User compiled apps go in /usr/local. I put tomcat in /opt/apache-tomcat-VERSION. I then make a symlink to it as /opt/tomcat. The [Linux Standards Base](http://www.linuxfoundation.org/en/LSB) may have more info on the matter.
What is the recommended/standard install path for apache-tomcat on a linux box
[ "", "java", "linux", "tomcat", "" ]
I want to add the 2-dimentional array in the sql server 2000 using c#. But the problem is that there is not array data type in sql. Kindly help me that how can I add the 2-dimentional array in sql server. Thanx for viewing my question...
A 2-D array is, essentially, a `table`. So you need to add a table to your database to hold this array. If you need to hold multiple array instance than add an additional column to store a key that will be common to individual arrays.
***You don't need to create an additional column for each dimension*** as the currently accepted answer says. It's all about *serialization*. 1. In SQL Server create a column of type Image to store the n-dimensional array. If you are using SQL server 2005 or superior, use VARBINARY(MAX) instead of Image. 2. In C#, serialize your n-dimensional array so you can handle it as a 1-dimensional array (byte[]) 3. Save the serialized data into the Image field. Of course, when you need to fetch the information from the database, you will get a byte array. Then you will need to deserialize that to your orginal type (the n-dimensional array). **Need an example?** Look at this similar question where I posted an example for doing it with a varbinary field. It should be very similar in SQL 2000. <https://stackoverflow.com/a/11334237/354756>
How Can I add the 2D array in SQL server 2000 using c#
[ "", "c#", "sql-server", "" ]
Does .NET (C#) have built in libraries for FTP? I don't need anything crazy... very simple. I need to: 1. FTP into an account 2. Detect if the connection was refused 3. Obtain a text file 4. Delete the text file What's the easiest way to do this?
Use the [FtpWebRequest](http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx) class, or the plain old [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx) class. FTP into an account and retrieve a file: ``` WebClient request = new WebClient(); request.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com"); try { // serverUri here uses the FTP scheme ("ftp://"). byte[] newFileData = request.DownloadData(serverUri.ToString()); string fileString = Encoding.UTF8.GetString(newFileData); } catch (WebException ex) { // Detect and handle login failures etc here } ``` Delete the file: ``` FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri); request.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Delete status: {0}", response.StatusDescription); response.Close(); ``` (Code examples are from MSDN.)
[This article](http://www.codeguru.com/csharp/csharp/cs_internet/desktopapplications/article.php/c13163) implements a GUI for an FTP client using .NET 2.0 and has full source with examples. Sample code includes connection, download and upload as well as good comments and explanations.
Using .NET 2.0, how do I FTP to a server, get a file, and delete the file?
[ "", "c#", ".net", ".net-2.0", "ftp", "" ]
Is there a C# API to convert .eml to .pdf? Want to convert saved email files to pdf
Use OpenOffice (<http://www.openoffice.org>) This will basically convert anything to PDF (doc, xls, ppt, txt). Since eml are just txt, why not just use this? See <http://www.opendocument4all.com/download/OpenOffice.net.pdf> for how to use OpenOffice in C#.
We had a similar task, but on a much smaller scale and it was a temporary solution. We converted the EML files to HTML pages and then used the [ABC Pdf](http://www.websupergoo.com/abcpdf-1.htm) component (I think they had a free version back then?) to create the PDF files out of the HTML pages. We did everything directly from the ASP.NET page.
API for converting Eml/Msg to pdf in C#
[ "", "c#", "api", "pdf-generation", "msg", "eml", "" ]
I'm working on a game and I'm currently working on the part that handles input. Three classes are involved here, there's the `ProjectInstance` class which starts the level and stuff, there's a `GameController` which will handle the input, and a `PlayerEntity` which will be influenced by the controls as determined by the `GameController`. Upon starting the level the ProjectInstance creates the `GameController`, and it will call its `EvaluateControls` method in the Step method, which is called inside the game loop. The `EvaluateControls` method looks a bit like this: ``` void CGameController::EvaluateControls(CInputBindings *pib) { // if no player yet if (gc_ppePlayer == NULL) { // create it Handle<CPlayerEntityProperties> hep = memNew(CPlayerEntityProperties); gc_ppePlayer = (CPlayerEntity *)hep->SpawnEntity(); memDelete((CPlayerEntityProperties *)hep); ASSERT(gc_ppePlayer != NULL); return; } // handles controls here } ``` This function is called correctly and the assert never triggers. However, every time this function is called, `gc_ppePlayer` is set to NULL. As you can see it's not a local variable going out of scope. The only place `gc_ppePlayer` can be set to NULL is in the constructor or possibly in the destructor, neither of which are being called in between the calls to `EvaluateControls`. When debugging, `gc_ppePlayer` receives a correct and expected value before the return. When I press F10 one more time and the cursor is at the closing brace, the value changes to 0xffffffff. I'm at a loss here, how can this happen? Anyone?
Are you debugging a Release or Debug configuration? In release build configuration, what you see in the debugger isn't always true. Optimisations are made, and this can make the watch window show quirky values like you are seeing. Are you actually seeing the ASSERT triggering? ASSERTs are normally compiled out of Release builds, so I'm guessing you are debugging a release build which is why the ASSERT isn't causing the application to terminate. I would recommend build a Debug version of the software, and then seeing if gc\_ppePlayer is really NULL. If it really is, maybe you are seeing memory heap corruption of some sort where this pointer is being overridden. But if it was memory corruption, it would generally be much less deterministic than you are describing. As an aside, using global pointer values like this is generally considered bad practice. See if you can replace this with a singleton class if it is truly a single object and needs to be globally accessible.
set a watch point on `gc_ppePlayer == NULL` when the value of that expression changes (to NULL or from NULL) the debugger will point you to exactly where it happened. Try that and see what happens. Look for unterminated strings or mempcy copying into memory that is too small etc ... usually that is the cause of the problem of global/stack variables being overwritten randomly. To add a watchpoint in VS2005 (instructions by brone) > 1. Go to Breakpoints window > 2. Click New, > 3. Click Data breakpoint. Enter > 4. `&gc_ppePlayer` in Address box, leave > other values alone. > 5. Then run. > > When `gc_ppePlayer` changes, > breakpoint > will be hit. – brone
Pointer mysteriously resetting to NULL
[ "", "c++", "pointers", "" ]
This works, partially. More information may be needed, however, I thought I would post to get advice on anything obvious that might be wrong here. The problem is that if activity.get\_cost() returns a `False` value, the function seems to exit entirely, returning `None`. What I'd like it to do, of course, is accumulate `cost` Decimal values in the `costs = []` and return their sum. Simple, I would have thought... but my novice Python skills are apparently missing something. More information provided on request. Thank you. ``` def get_jobrecord_cost(self): costs = [] for activity in self.activity_set.all(): cost = activity.get_cost() if cost: costs.append(cost) if len(costs): return sum(costs) else: return False ```
``` def get_jobrecord_cost(self): return sum((activity.get_cost() or 0 for activity in activity_set.all()) or 0) ``` Depending on how much data you're dealing with, this version is just a bit more efficient than DNS's because it uses a generator comprehension and doesn't require loading up a whole list into memory. It's functionally equivalent to grieve's except the looping happens in C. Note that this doesn't necessarily mean this is *better*. This approach is obviously more dense and can be less readable.
I notice you're returning False if all the costs were None; I don't know if there's a specific reason for that, but it does make it a little bit harder to write. If that's not a requirement, you could write it like this: ``` def get_jobrecord_cost(self): costs = [activity.get_cost() or 0 for activity in self.activity_set.all()] return sum(costs) ```
Django, Python Loop Logic Problem
[ "", "python", "django-models", "" ]
I have an ASP.NET MVC (beta) application that I'm working on, and am having trouble figuring out if I'm doing something wrong, or if my `Application_Start` method in Global.asax.cs is in fact not firing when I try to debug the application. I put a breakpoint on a line in my `Application_Start` method, and am expecting that when I attempt to debug the application that the breakpoint should get hit... but it never does. Not after I reset IIS, not after I reboot, not ever. Am I missing something? Why is this method never getting called?
If this is in IIS, the app can get started before the debugger has attached. If so, I am not sure if you can thread sleep long enough to get attached. In Visual Studio, you can attach the debugger to a process. You do this by clicking Debug >> Attach to process. Attach to the browser and then hit your application. To be safe, then restart IIS and hit the site. I am not 100% convinced this will solve the problem, but it will do much better than firing off a thread sleep in App\_Start. Another option is temporarily host in the built in web server until you finish debugging application start.
Note : a nice **easy alternative to using the inbuilt "Visual Studio Development Server"** or **IIS Express** (e.g. because you are **developing against IIS and have particular settings** you need for proper functioning of your app) is to simply stay running run in IIS (I use the Custom Web Server + hosts file entry + IIS binding to same domain) 1. wait for debugging session to fire up ok 2. then just make a whitespace edit to the root web.config and save the file 3. refresh your page (Ctrl + F5) Your breakpoint should be hit nicely, and you can continue to debug in your **natural IIS habitat**. Great !
Application_Start not firing?
[ "", "c#", "asp.net-mvc", "" ]
Is there a method to use an XML file instead of a database in the Entity Framework?
Entity Framework itself is provider-based, and is *designed* to operate over a relational database. If you really wanted to, you could write your own provider for EF that reads from/writes to an xml file, but it would be a *huge* amount of work. I expect you should really be looking at one of: * LINQ-to-XML * XML (de)serialization * XPath/XQuery * XSLT Entity Framework doesn't have a *natural* fit in this scenario.
Linq to XML isn't all that much actually. I'd go with a serializable solution instead.
Entity Framework with XML Files
[ "", "c#", ".net", "xml", "entity-framework", "" ]
I am writing a small game, with one JFrame that holds the main game, and another JFrame that displays the score. the problem is, when I am done constructing them, the score JFrame always ends up focused! I have tried calling scoreDisplay.toFront(), scoreDisplay.requestFocus(), and even: ``` display.setState(JFrame.ICONIZED); display.setState(JFrame.NORMAL); ``` Is there any way to make this work? Thanks in advance, john murano
Have you consider setting the score in the same frame as the game frame? Other possible ( quick and dirty ) option is to create them in reverse order, or at least ( if score depends on game ) display them in reverse order. ``` score.setVisible( true ); game.setVisible( true ); ``` My guess is that currently they are: ``` game.setVisible( true ); score.setVisible( true ); ```
**Call the `requestFocus()` method.** This is not guaranteed to work, because there are many reasons why an operating system would not allow a frame to have focus. There could be another frame with higher priority in a different application. There are also some linux desktops which (if I recall correctly) do not allow frames to request focus. To give you a better chance of success, I also recommend calling the `toFront()` method before requesting focus. ``` frame.setVisible(true); frame.toFront(); frame.requestFocus(); ``` Please keep in mind, none of this is guaranteed because frame handling, especially with focus and layering, is very operating system-dependant. So set the frame to visible, move it to the front, and request the focus. Once you give up the EDT, the operating system will likely give the frame the focus. At the very least, the window should be on top.
How to focus a JFrame?
[ "", "java", "user-interface", "swing", "jframe", "" ]
I have an add-in loaded, and a solution loaded, how would I find the folder path of that solution programmatically in C# in my addin?
Alas I figured it out after a lot of goooogling!! In connect.cs: ``` public String SolutionPath() { return Path.GetDirectoryName(_applicationObject.Solution.FullName); } ```
The Solution.FullName answer is correct, but take care, you cannot access it until the OnStartupCompleted method is called in connect.cs.
Visual studio addin - finding current solution folder path
[ "", "c#", "visual-studio", "visual-studio-addins", "" ]
Consider this code: ``` #include <vector> void Example() { std::vector<TCHAR*> list; TCHAR* pLine = new TCHAR[20]; list.push_back(pLine); list.clear(); // is delete called here? // is delete pLine; necessary? } ``` Does `list.clear()` call `delete` on each element? I.e. do I have to free the memory before / after `list.clear()`?
No (you need to do the delete yourself at the end as you suggest in your example as the destruction of the bald pointer doesnt do anything). But you can use a boost [or other RAII-based idiom] smart pointer to make it Do The Right Thing (`auto_ptr` would not work correctly in a container as it has incompatible behaviour under copying etc.), but be sure you understand the pitfalls of such smart pointers before use. (As Benoit mentions, in this case, `basic_string` is what you're really looking for here.) Having said that there's a need to understand the pitfalls of smart pointers, having them take care of the memory management implicitly so you dont have to do it explicitly is far less error-prone. EDIT: Substantially revised to encompass the elements Benoit brought into his far more thorough answer, thanks to strong prodding from the Earwicker and James Matta - thanks for pushing me to do the due diligence on this!
`std::vector` does call the destructor of every element it contains when `clear()` is called. In your particular case, it destroys the pointer but the objects remain. Smart pointers are the right way to go, but be careful. `auto_ptr` cannot be used in std containers. `boost::scoped_ptr` can't either. `boost::shared_ptr` can, but it won't work in your case because you don't have a pointer to an object, you are actually using an array. So the solution to your problem is to use [`boost::shared_array`](http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_array.htm). But I suggest you use `std::basic_string<TCHAR>` instead, where you won't have to deal with memory management, while still getting the benefits of working with a string.
Does std::vector.clear() do delete (free memory) on each element?
[ "", "c++", "std", "" ]
So, this isn't my code and has been shortened to show the behavior, but it is giving very unexpected results. I have two function in a class and a lock ``` object mylock = new object(); List<string> temp = new List<string>(); Func1(string) { lock(mylock) { temp.Add(string); } } Func2() { lock(mylock) { temp.ForEach(p => Func1(p)); } } ``` Now, I know this makes no sense, but when Func2 is called, shouldn't Func1 deadlock? In our case, it executes. Thanks.
No, it shouldn't deadlock. `Func1` can get the lock if it's called by someone that already holds the lock (like `Func2`) The [MSDN doc for lock](http://msdn.microsoft.com/en-us/library/aa664735(VS.71).aspx) explains: "While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads is blocked from obtaining the lock until the lock is released." The goal of lock is to prevent **different threads** from accessing the same resource. `Func1` and `Func2` are on the **same thread**.
The `lock` statement (encapsulating the `Monitor` class) supports re-entrance (recursion) within a thread, i.e. you can nest the calls, which use the same monitor. Other locking approachs: * `Monitor` - recursion is supported * `ReaderWriterLock` - recursion is supported, but slow * `ReaderWriterLockSlim` - recursion is supported, but discouraged * `EventHandle` (`ManualResetEvent`, `AutoResetEvent`, `Mutex`, `Semaphore`) - recursion not supported
Weird lock() behavior with foreach
[ "", "c#", "multithreading", "" ]