Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Why would someone use `WHERE 1=1 AND <conditions>` in a SQL clause (Either SQL obtained through concatenated strings, either view definition) I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird. If there is injection `WHERE 1 = 1 AND injected OR 1=1` would have the same result as `injected OR 1=1`. Later edit: What about the usage in a view definition? --- Thank you for your answers. Still, I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure. Take this for example: ``` CREATE VIEW vTest AS SELECT FROM Table WHERE 1=1 AND table.Field=Value ```
If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like: ``` and <condition> ``` and concatenate them all together. With the `1=1` at the start, the initial `and` has something to associate with. I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I *have* seen it used as an implementation convenience. The SQL query engine will end up ignoring the `1=1` so it should have no performance impact.
Just adding a example code to Greg's answer: ``` dim sqlstmt as new StringBuilder sqlstmt.add("SELECT * FROM Products") sqlstmt.add(" WHERE 1=1") ''// From now on you don't have to worry if you must ''// append AND or WHERE because you know the WHERE is there If ProductCategoryID <> 0 then sqlstmt.AppendFormat(" AND ProductCategoryID = {0}", trim(ProductCategoryID)) end if If MinimunPrice > 0 then sqlstmt.AppendFormat(" AND Price >= {0}", trim(MinimunPrice)) end if ```
Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?
[ "", "sql", "dynamic-sql", "" ]
I have a loader.exe with Main() that loads the 'UI' in WPF, the thing is that I want only one instance of the loader.exe, how can I achieve it? Is there a way a user clicks loader.exe it should check if an existing loader.exe is running and does nothing. currently I have loader.exe with ``` main() .... .. Load UI ... ``` the loader has no idea what its loading etc so I can't do many things with the loader project... Any help n code is highly appreciated Thanks in advance.
We use the following C# code to detect if an application is already running: ``` using System.Threading; string appSpecificGuid = "{007400FE-003D-00A5-AFFE-DA62E35CC1F5}"; bool exclusive; Mutex m = new Mutex(true, appSpecificGuid, out exclusive); if (exclusive) { // run } else { // already running } ``` Regards, tamberg
Have a look at: <http://yogesh.jagotagroup.com/blog/post/2008/07/03/Ways-of-making-a-WPF-application-Single-Instance.aspx> Also, you might find a more detailed answer in the following post here on StackOverflow: [What is the correct way to create a single-instance application?](https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application)
c# WPF Maintain Single Instance of loader
[ "", "c#", "wpf", "single-instance", "" ]
If you read other people's source code, how do you approach the code? What patterns are you looking for (datatypes, loops, use of control flow, ...)? How long can you read other people's code without getting bored? What is the most exciting patterns that you have discovered so far?
Aside from the obvious "work from the top down" general approach, it depends on **why** I'm reading it: code review, trying to understand a bit of avaialable code to adapt for my own use, trying to learn a new technique, etc. It also depends heavily on the language. If it is an OOPL, I'll probably do something like this: 1. Look first for the primary class relationships and try to understand the primary responsibility of each class. 2. Look at the interactions between classes to see how they collaborate. 3. Look at the interfaces of the key classes to see what "services" they offer their collaborators. 4. Look inside the non-trivial methods if it's important to understand **how** they are working instead of **what** they are responsible for.
At first, I ignore the urge to change the code. Which is sometimes hard to do. But understanding first and change later saves yourself a lot of nasty "learning experiences." Next if the format is bad, reformat. Use a code formatter if you have one. This is because you tend to look at the indentation and if that is bad, your understanding of the code is also questionable. Then, if there are complex datastructures, I like to draw a little diagram. The challenge here is keep it as simple as possible. Large diagrams are fun on the wall, but most of the time, they are to cumbersome to look at. So it is wasted time. If you finally understand what a piece of code does, write a comment. This is essential, because else you won't understand it the next time you are here. The following step is to create unit tests. Now you can not only test the code, but you can also test your understanding of the code. Last, if you understand it al and you know it can (and need to be) better, change it. But be sure to run the tests. Unless you are paid by each solved bug.
What should I take note of when reading others' source code?
[ "", "java", "design-patterns", "" ]
I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this? Edit: The scope of the problem is as follows: I'm trying to hack a program for class, and essentially I'm putting my shellcode into an environment variable and then overwriting one byte on the victim code with the address of my environment variable. I need to find a way to automate this in Python, so my question is two-fold: * Is there a way to get the address in memory of an environment variable? * Can this only be done in bash/C or can I do it purely in Python?
The built in function id() returns a unique id for any object, which just happens to be it's memory address. <http://docs.python.org/library/functions.html#id>
For accessing and setting environment variables, read up on the os.environ dictionary. You can also use os.putenv to set an environment variable.
Python - Setting / Getting Environment Variables and Addrs
[ "", "python", "linux", "environment-variables", "" ]
After creating a instance of a class, can we invoke the constructor explicitly? For example ``` class A{ A(int a) { } } A instance; instance.A(2); ``` Can we do this?
You can use [placement new](http://en.wikipedia.org/wiki/Placement_new), which permits ``` new (&instance) A(2); ``` However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do ``` A instance(2); ``` Placement new is usually only used when you need to pre-allocate the memory (e.g. in a custom memory manager) and construct the object later.
No. Create a method for the set and call it from the constructor. This method will then also be available for later. ``` class A{ A(int a) { Set(a); } void Set(int a) { } } A instance; instance.Set(2); ``` You'll also probably want a default value or default constructor.
Can you invoke an instantiated object's class constructor explicity in C++?
[ "", "c++", "constructor", "" ]
I need to get execution time in milliseconds. **Note**: I originally asked this question back in 2008. The accepted answer then was to use [`new Date().getTime()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) However, we can all agree now that using the standard [`performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance.now) API is more appropriate. I am therefore changing the accepted answer to this one.
## Using [**performance.now()**](https://developer.mozilla.org/en-US/docs/Web/API/Performance.now): ``` var startTime = performance.now() doSomething() // <---- measured code goes between startTime and endTime var endTime = performance.now() console.log(`Call to doSomething took ${endTime - startTime} milliseconds`) ``` > In `Node.js` it is required to import the [`performance`](https://nodejs.org/api/perf_hooks.html#perf_hooks_class_performance) class importing performance ``` const { performance } = require('perf_hooks'); ``` --- ## Using **[console.time](https://developer.mozilla.org/en-US/docs/DOM/console.time)**: ([living standard](https://console.spec.whatwg.org/#time)) ``` console.time('doSomething') doSomething() // <---- The function you're measuring time for console.timeEnd('doSomething') ``` ***Note:*** The string being passed to the `time()` and `timeEnd()` methods must match (*for the timer to finish as expected*). > ### `console.time()` documentations: > > * [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Console/time) > * [Node.js documentation](https://nodejs.org/api/console.html#console_console_timeend_label)
use [new Date().getTime()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) > The getTime() method returns the number of milliseconds since midnight of January 1, 1970. ex. ``` var start = new Date().getTime(); for (i = 0; i < 50000; ++i) { // do something } var end = new Date().getTime(); var time = end - start; alert('Execution time: ' + time); ```
How to measure time taken by a function to execute
[ "", "javascript", "profiling", "" ]
I'm experimenting with WCF Services, and have come across a problem with passing Interfaces. This works: ``` [ServiceContract] public interface IHomeService { [OperationContract] string GetString(); } ``` but this doesn't: ``` [ServiceContract] public interface IHomeService { [OperationContract] IDevice GetInterface(); } ``` When I try to compile the client it fails on the GetInterface method. I get an Exception saying that it can't convert Object to IDevice. On the clientside the IHomeService class correctly implements GetString with a string as it's returntype, but the GetInterface has a returntype of object. Why isn't it IDevice?
You need to tell the WCF serializer which class to use to serialize the interface ``` [ServiceKnownType(typeof(ConcreteDeviceType)] ```
Thanks, it works when I changed it like this: ``` [ServiceContract] [ServiceKnownType(typeof(PhotoCamera))] [ServiceKnownType(typeof(TemperatureSensor))] [ServiceKnownType(typeof(DeviceBase))] public interface IHomeService { [OperationContract] IDevice GetInterface(); } ``` I also got help from this site: <http://www.thoughtshapes.com/WCF/UsingInterfacesAsParameters.htm>
Passing Interface in a WCF Service?
[ "", "c#", ".net", "wcf", "" ]
I'm trying to work my way through Ron Jeffries's Extreme Programming Adventures in C#. I am stuck, however, in Chapter 3 because the code does not, and **cannot**, do what the author says it does. Basically, the text says that I should be able to write some text in a word-wrap enabled text box. If I then move the cursor to an intermediate line and hit enter, the code should re-display the lines before the cursor, add a couple of lines and a set of HTML paragraph tags, then append the rest of the lines. The code doesn't match the text because it uses the textbox.lines property. Well, no matter how many word-wrapped lines there are in a text box, there's only ONE line in the Lines property until you hit a carriage return. So, the statement that the code should, "Copy the rest of the lines into the buffer" appears wrong to me. I'd appreciate anybody having experience with the book telling me what I'm reading, or doing, wrong! Thanks. EoRaptor
Try emailing Ron Jeffries directly. I have the book - somewhere, but I don't remember it not working. His email address is ronjeffries at acm dot org and put [Ron] in the subject line. (And for those wondering - his email info was right from his website [Welcome page](http://www.xprogramming.com/welcome.htm))
I've also just started this book and had exactly the same problem although the code you have included looks further along than where I am. The 'subscript out of range' occurred for 2 reasons, first as Ron explains he was just testing and so returned a hard-coded value of 3 before he wrote the CursorLine() function, which means you I think at least 4? lines of text which as you say need to be pasted in, or maybe set the text to this value before running, also as you say they need to have carriage returns to make txtbox.Lines return an array of strings. The second reason occurs even after CursorLine() has been implemented but only happens if the text box is empty as txtbox.Lines returns string[0] but I think Ron is implementing a 'User Story' which says that when text has been entered and user presses enter, so not sure if he fixes this later, but will probably find out! The author's do state that they are learning C# and will show the development wart's and all, which is one of the reasons I have chosen to study this book as I think it is encouraging me to develop projects. I also try to do the code first before looking at his solutions to see if I'm thinking the same way, but maybe I know C# a little better than I give myself credit for, or I'm completly crap, but I've noticed a few things, first he says that overriding OnKeyDown() doesn't work, but I think he must have got confused and tried to do in Form, instead of deriving from TextBox and overriding there. This was my code when reading the 'User Story': ``` int curPos = txtbox.SelectionStart; string Wrd = Environment.NewLine + "<P></P>" + Environment.NewLine; txtbox.SelectedText = Wrd; int pl = Environment.NewLine.Length + 3; // "<P>" length is 3 // Put text cursor inbetween <P> tags txtbox.SelectionStart = curPos + pl; ``` It works differently to Ron's code, but was just my interpretation of the 'User Story' and not sure how should act if text is selected or wether to split line if text cursor in the middle etc. Also in 'My Adventures' in Extreme Programming Adventures in C# ``` txtbox.GetLineFromCharIndex(txtbox.SelectionStart) ``` gets the cursor line position and doesn't matter if no carriage returns or resized, as far as I can tell, I done little test with: ``` txtbox.GetLineFromCharIndex(txtbox.TextLength) ``` which returns the total amount of lines, which will vary if you resize the text box. Using C# I always look for solutions which already exsist and people may slate me for this but I think MS have created a great language with great components which do what you expect them to do, so don't have to re-create the wheel each time. Although like I say it's early days in this book and perhaps these simple solutions aren't extensible enough and maybe Ron's taking that into account, although he did mention just get it working then worry about that later is more the XP way. Warren.
Errata in Extreme Programming Adventures in C#?
[ "", "c#", "textbox", "extreme-programming", "" ]
``` class Score { var $score; var $name; var $dept; var $date; function Score($score, $name, $dept, $date) { $this->scores = ($score); $this->name = ($name); $this->dept = ($dept); $this->date = ($date); } function return_score(){ return $this->scores; return $this->name; return $this->dept; return $this->date; } } $newscore = new Score("131313","James", "Marketing", "19/05/2008"); echo $newscore->return_score(); ``` The above code is only echoing 131313. I am just beginning to learn OO PHP so please go easy! Totally lost, so any help would be much appreciated.
You can't return more than once in a function. You *could* return a concatenated string: ``` return $this->scores.' '.this->name.' '.$this->dept.' '.$this->date; //added spaces for readability, but this is a silly thing to do anyway... ``` I wouldn't recommend it though as you'd be mixing you presentation of the object with its functionality - don't. I'd suggest making a template of some sort (I'm imagining you might want to tabulate this data?). Each row would look something like: ``` <tr> <td><?php echo $score->name; ?></td> <td><?php echo $score->scores; ?></td> <!-- more cells for more properies? --> </tr> ``` and giving it your object or objects in array (you know about foreach{} ?). I know it looks more long-winded, but separating these concerns **is** going to be better for you in the long run. Assigning with = : you don't need the parentheses around the thing being assigned (usually). **Also:** Are you running PHP4? Your constructor function indicates you are. I'd recommend moving to 5.21 or higher if at all possible as classes and objects are much better. You can also use the rather useful \_\_construct method (as opposed to using the class named method - in your case: Score()). This makes inheritance and extending easier because your classes are no longer having to remember in two places what class they are extending from.
You can only return one value in each function or method. In your situation, you should have a method for each of the class members: ``` public function getScore() { return $this->score; } public function getName() { return $this->name; } public function getDept() { return $this->dept; } public function getDate() { return $this->date; } ``` Edit after the comments: You could also need a method that returns all the members as a single string: ``` public function getAll() { return $this->getScore(). " " .$this->getName() . " " .$this->getDept(). " " .$this->getDate(); } ```
Only getting one element returned, OO PHP
[ "", "php", "oop", "" ]
At the XmlSerializer constructor line the below causes an InvalidOperationException which also complains about not having a default accesor implemented for the generic type. ``` Queue<MyData> myDataQueue = new Queue<MyData>(); // Populate the queue here XmlSerializer mySerializer = new XmlSerializer(myDataQueue.GetType()); StreamWriter myWriter = new StreamWriter("myData.xml"); mySerializer.Serialize(myWriter, myDataQueue); myWriter.Close(); ```
It would be easier (and more appropriate IMO) to serialize the *data* from the queue - perhaps in a flat array or `List<T>`. Since `Queue<T>` implements `IEnumerable<T>`, you should be able to use: ``` List<T> list = new List<T>(queue); ```
Not all parts of the framework are designed for XML serialization. You'll find that dictionaries also are lacking in the serialization department. A queue is pretty trivial to implement. You can easily create your own that also implements IList so that it will be serializable.
In C#, How can I serialize Queue<>? (.Net 2.0)
[ "", "c#", ".net", "generics", "serialization", ".net-2.0", "" ]
Does this pattern: ``` setTimeout(function(){ // do stuff }, 0); ``` Actually return control to the UI from within a loop? When are you supposed to use it? Does it work equally well in all browsers?
It runs code asynchronously (not in parallel though). The delay is usually changed to a minimum of 10ms, but that doesn't matter. The main use for this trick is to avoid limit of call stack depth. If you risk reaching limit (walk deep tree structure and plan to do a lot of work on leafs), you can use timeout to start function with a new, empty call stack. You can also use it to avoid blocking current thread. For example if you don't want `<script>` element to delay loading of a page: ``` <script>compute_last_pi_digit()</script> <!-- blocking --> <script>setTimeout(compute_last_pi_digit,0)</script> <!-- non-blocking --> ```
<http://blog.thinkature.com/index.php/2006/11/26/escaping-the-javascript-call-stack-with-settimeout/> Some good info in there. Basically, you are correct and it works on pretty much all browsers. Cool trick. You would want to use this in the example that the author of the post gave, as well as instances where you need to return execution back to the calling function before your code is executed. Javascript is, apparently, not multi-threaded, but this comes close. Hope this helps :)
What is setTimeout(function(){//dostuff}, 0); actually supposed to do?
[ "", "javascript", "performance", "" ]
I have a sql query that runs super fast, around one second, when not using variables, like: ``` WHERE id BETWEEN 5461094 and 5461097 ``` But when I have: ``` declare @firstId int declare @lastId int set @firstId = 5461094 set @lastId = 5461097 ... WHERE id BETWEEN @firstId and @lastId ``` ... the query runs really slow, finishing only after some minutes. Why does it happen? I need to use variables. Can I do any improvement to avoid this performance problems?
It's because when the values are hard coded, it can look up [the statistics](http://www.microsoft.com/technet/prodtechnol/sql/2005/qrystats.mspx) it has on the data in the table, and figure out the best query to run. Have a look at the execution plans of each of these queries. It must be scanning when your using variables. if the range is always small you might be able to use an index hint to help this.
OK, 1. You are the Optimizer and the Query Plan is a vehicle. 2. I will give you a query and you have to choose the vehicle. 3. All the books in the library have a sequential number My query is Go to the library and get me all the books between 3 and 5 You'd pick a bike right, quick, cheap, efficient and big enough to carry back 3 books. New query. Go to the library and get all the books between @x and @y. Pick the vehicle. Go ahead. That's what happens. Do you pick a dump truck in case I ask for books between 1 and Maxvalue? That's overkill if x=3 and y=5. SQL has to pick the plan before it sees the numbers.
Why SQL Server go slow when using variables?
[ "", "sql", "sql-server", "stored-procedures", "" ]
I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a `JProgressBar` widget, which I would like to show the current progress of the download. For that I would need to know the size of the file. How do you get the size of the file prior to downloading the file.
Any HTTP response is *supposed* to contain a Content-Length header, so you could query the URLConnection object for this value. ``` //once the connection has been opened List values = urlConnection.getHeaderFields().get("content-Length") if (values != null && !values.isEmpty()) { // getHeaderFields() returns a Map with key=(String) header // name, value = List of String values for that header field. // just use the first value here. String sLength = (String) values.get(0); if (sLength != null) { //parse the length into an integer... ... } ``` It might not always be possible for a server to return an accurate Content-Length, so the value could be inaccurate, but at least you would get *some* usable value most of the time. **update:** Or, now that I look at the URLConnection javadoc more completely, you could just use the [getContentLength()](http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getContentLength%28%29) method.
As mentioned, URLConnection's [`getContentLengthLong()`](https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#getContentLengthLong--) is your best bet, but it won't always give a definite length. That's because the HTTP protocol (and others that could be represented by a `URLConnection`) doesn't always convey the length. In the case of HTTP, the length of dynamic content typically isn't known in advance—when the `content-length` header would normally be sent. Instead, another header, `transfer-encoding`, specifies that a "chunked" encoding is used. With chunked encoding, the length of the entire response is unspecified, and the response is sent back in pieces, where the size of each piece is specified. In practice, the server buffers output from the servlet. Whenever the buffer fills up, another chunk is sent. Using this mechanism, HTTP could actually start streaming a response of infinite length. If a file is larger than 2 Gb, its size can't be represented as an `int`, so the older method, [`getContentLength()`](https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#getContentLength--) will return -1 in that case.
Java URLConnection : how can I find out the size of a web file?
[ "", "java", "http", "http-headers", "" ]
I need to build a function which parses the domain from a URL. So, with ``` http://google.com/dhasjkdas/sadsdds/sdda/sdads.html ``` or ``` http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html ``` it should return `google.com` with ``` http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html ``` it should return `google.co.uk`.
Check out [`parse_url()`](http://php.net/parse_url): ``` $url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'; $parse = parse_url($url); echo $parse['host']; // prints 'google.com' ``` `parse_url` doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls.
``` $domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST)); ``` **This would return the `google.com` for both <http://google.com/>... and <http://www.google.com/>...**
Parsing domain from a URL
[ "", "php", "" ]
I am battling regular expressions now as I type. I would like to determine a pattern for the following example file: `b410cv11_test.ext`. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. ***Further clarification of question:*** I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'
Now that you have a human readable description of your file name, it's quite straight forward to translate it into a regular expression (at least in this case ;) > must start with The caret (`^`) anchors a regular expression to the beginning of what you want to match, so your re has to start with this symbol. > 'b', Any non-special character in your re will match literally, so you just use "b" for this part: `^b`. > followed by [...] digits, This depends a bit on which flavor of re you use: The most general way of expressing this is to use brackets (`[]`). Those mean "match any one of the characters listed within. `[ASDF]` for example would match either `A` or `S` or `D` or `F`, `[0-9]` would match anything between 0 and 9. Your re library probably has a shortcut for "any digit". In `sed` and `awk` you could use `[[:digit:]]` [sic!], in python and many other languages you can use `\d`. So now your re reads `^b\d`. > followed by three [...] The most simple way to express this would be to just repeat the atom three times like this: `\d\d\d`. Again your language might provide a shortcut: braces (`{}`). Sometimes you would have to escape them with a backslash (if you are using sed or awk, read about "extended regular expressions"). They also give you a way to say "at least x, but no more than y occurances of the previous atom": `{x,y}`. Now you have: `^b\d{3}` > followed by 'cv', Literal matching again, now we have `^b\d{3}cv` > followed by two digits, We already covered this: `^b\d{3}cv\d{2}`. > then an underscore, followed by 'release', followed by .'ext' Again, this should all match literally, but the dot (`.`) is a special character. This means you have to escape it with a backslash: `^\d{3}cv\d{2}_release\.ext` Leaving out the backslash would mean that a filename like "b410cv11\_test\_ext" would also match, which may or may not be a problem for you. Finally, if you want to guarantee that there is nothing else following ".ext", anchor the re to the end of the thing to match, use the dollar sign (`$`). Thus the complete regular expression for your specific problem would be: ``` ^b\d{3}cv\d{2}_release\.ext$ ``` Easy. Whatever language or library you use, there has to be a reference somewhere in the documentation that will show you what the exact syntax in your case should be. Once you have learned to break down the problem into a suitable description, understanding the more advanced constructs will come to you step by step.
To avoid confusion, read the following, in order. First, you have the [glob](http://www.python.org/doc/2.5.2/lib/module-glob.html) module, which handles file name regular expressions just like the Windows and unix shells. Second, you have the [fnmatch](http://www.python.org/doc/2.5.2/lib/module-fnmatch.html) module, which just does pattern matching using the unix shell rules. Third, you have the [re](http://www.python.org/doc/2.5.2/lib/module-re.html) module, which is the complete set of regular expressions. Then ask another, more specific question.
How can I translate the following filename to a regular expression in Python?
[ "", "python", "regex", "" ]
I want to convert a `std::string` to lowercase. I am aware of the function `tolower()`. However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a `std::string` would require iterating over each character. Is there an alternative which works 100% of the time?
Adapted from [*Not So Frequently Asked Questions*](http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/): ``` #include <algorithm> #include <cctype> #include <string> std::string data = "Abc"; std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c){ return std::tolower(c); }); ``` You're really not going to get away without iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise. If you really hate [`tolower()`](https://en.cppreference.com/w/cpp/string/byte/tolower), here's a specialized ASCII-only alternative that I don't recommend you use: ``` char asciitolower(char in) { if (in <= 'Z' && in >= 'A') return in - ('Z' - 'z'); return in; } std::transform(data.begin(), data.end(), data.begin(), asciitolower); ``` Be aware that `tolower()` can only do a per-single-byte-character substitution, which is ill-fitting for many scripts, especially if using a multi-byte-encoding like UTF-8.
[Boost provides a string algorithm for this](https://www.boost.org/doc/libs/1_70_0/doc/html/boost/algorithm/to_lower.html): ``` #include <boost/algorithm/string.hpp> std::string str = "HELLO, WORLD!"; boost::algorithm::to_lower(str); // modifies str ``` [Or, for non-in-place](https://www.boost.org/doc/libs/1_70_0/doc/html/boost/algorithm/to_lower_copy.html): ``` #include <boost/algorithm/string.hpp> const std::string str = "HELLO, WORLD!"; const std::string lower_str = boost::algorithm::to_lower_copy(str); ```
How to convert an instance of std::string to lower case
[ "", "c++", "string", "std", "tolower", "" ]
The default generated hashCode and equals implementations are ugly at best. Is it possible to make eclipse generate ones from HashCodeBuilder and EqualsBuilder, and perhaps even a toString with ToStringBuilder?
Take a look at [Commons4E](http://marketplace.eclipse.org/content/commons4e) It hasn't been updated in a while, but then I don't guess it needs to change much? Update: Just checked against 3.4.1 and it works fine.
You can configure Eclipse to generate `toString()` using a custom builder. In our case `ToStringBuilder` from [Apache Commons Lang](http://commons.apache.org/lang/). You can see here <http://azagorneanu.blogspot.com/2011/08/how-to-generate-equals-hashcode.html> how to do it. That blog post contains also Eclipse templates for generating `equals()`, `hashCode()` and `compareTo()` using Apache Commons Lang builders.
Is it possible to make eclipse generate hashCode and equals with HashCodeBuilder and EqualsBuilder
[ "", "java", "eclipse", "" ]
This is a contrived example, but lets say I have declared objects: ``` CustomObj fooObj; CustomObj barObj; CustomObj bazObj; ``` And I have an string array: ``` string[] stringarray = new string[] {"foo","bar","baz"}; ``` How can I programmatically access and instantiate those objects using the string array, iterating using something like a foreach: ``` foreach (string i in stringarray) { `i`Obj = new CustomObj(i); } ``` Hope the idea I'm trying to get across is clear. Is this possible in C#?
You need to be clear in your mind about the difference between an object and a variable. Objects themselves don't have names. Variable names are decided at compile-time. You can't access variables via an execution-time-determined name except via reflection. It sounds like you *really* just want a `Dictionary<string, CustomObj>`: ``` Dictionary<string, CustomObj> map = new Dictionary<string, CustomObj>(); foreach (string name in stringArray) { map[name] = new CustomObj(name); } ``` You can then access the objects using the indexer to the dictionary. If you're really trying to set the values of variables based on their name at execution time, you'll have to use reflection (see [Type.GetField](http://msdn.microsoft.com/en-us/library/system.type.getfield.aspx)). Note that this won't work for local variables.
You can't. You can place them into a dictionary: ``` Dictionary<String, CustomObj> objs = new Dictionary<String, CustomObj>(); foreach (string i in stringarray) { objs[i] = new CustomObj(i); } ``` But that's about as good as it gets. If you store the objects in fields in your class, like this: ``` public class SomeClass { private CustomObj fooObj; private CustomObj barObj; private CustomObj bazObj; } ``` Then you can reach them through reflection. Let me know if that's the route you want to take.
Programmatically using a string as object name when instantiating an object
[ "", "c#", "oop", "" ]
I am using CYGWIN as a platform and would like to use wxPython. Is there a way to get the source compiled and working in cygwin?
I found this link to [build wxPython under Cygwin](http://gnuradio.org/redmine/projects/gnuradio/wiki/WxPythonCygwin). To me this is a much better option than installing all the X11 stuff. I tried it out using wxPython-src-2.8.12.1, and following the instructions to a tee, it worked perfectly.
You would need a full working X environment to get it to work. It would be much easier to just use Python and wxPython under plain vanilla Windows. Do you have a special case?
How do you compile wxPython under cygwin?
[ "", "python", "installation", "wxpython", "cygwin", "compilation", "" ]
So I have xml that looks like this: ``` <todo-list> <id type="integer">#{id}</id> <name>#{name}</name> <description>#{description}</description> <project-id type="integer">#{project_id}</project-id> <milestone-id type="integer">#{milestone_id}</milestone-id> <position type="integer">#{position}</position> <!-- if user can see private lists --> <private type="boolean">#{private}</private> <!-- if the account supports time tracking --> <tracked type="boolean">#{tracked}</tracked> <!-- if todo-items are included in the response --> <todo-items type="array"> <todo-item> ... </todo-item> <todo-item> ... </todo-item> ... </todo-items> </todo-list> ``` How would I go about using .NET's serialization library to deserialize this into C# objects? Currently I'm using reflection and I map between the xml and my objects using the naming conventions.
Create a class for each element that has a property for each element and a List or Array of objects (use the created one) for each child element. Then call System.Xml.Serialization.XmlSerializer.Deserialize on the string and cast the result as your object. Use the System.Xml.Serialization attributes to make adjustments, like to map the element to your ToDoList class, use the XmlElement("todo-list") attribute. A shourtcut is to load your XML into Visual Studio, click the "Infer Schema" button and run "xsd.exe /c schema.xsd" to generate the classes. xsd.exe is in the tools folder. Then go through the generated code and make adjustments, such as changing shorts to ints where appropriate.
Boils down to using xsd.exe from tools in VS: ``` xsd.exe "%xsdFile%" /c /out:"%outDirectory%" /l:"%language%" ``` Then load it with reader and deserializer: ``` public GeneratedClassFromXSD GetObjectFromXML() { var settings = new XmlReaderSettings(); var obj = new GeneratedClassFromXSD(); var reader = XmlReader.Create(urlToService, settings); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(GeneratedClassFromXSD)); obj = (GeneratedClassFromXSD)serializer.Deserialize(reader); reader.Close(); return obj; } ```
Deserializing XML to Objects in C#
[ "", "c#", ".net", "serialization", "" ]
I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the `<head>` note: I am working with a local server, so pageload in instant. ``` function changeVisibility() { var a = document.getElementById('invisible'); a.style.display = 'block'; } var changed = document.getElementById('click1'); changed.onchange = changeVisibility; ``` This here is the corresponding HTML ``` <input type="file" name="click[]" size="35" id="click1" /> <div id="invisible" style="display: none;"> <a href="javascript:addFileInput();">Attach another File</a> </div> ``` So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block. Problem is, I keep getting this error: "changed is null: changed.onchange = changeVisibility;" i don't get it, I seriously don't get what I'm overlooking here. --- EDIT: question answered, thank you Mercutio for your help and everyone else too of course. Final code: ``` function loadEvents() { var changed = document.getElementById('click1'); var a = document.getElementById('invisible'); document.getElementById('addField').onclick = addFileInput; changed.onchange = function() { a.style.display = 'block'; } } if (document.getElementById) window.onload = loadEvents; ``` This here is the corresponding HTML: ``` <input type="file" name="click[]" size="35" id="click1" /> <div id="invisible" style="display: none;"> <a href="#">Attach another File</a> </div> ``` Also, thanks for the link to [JSbin](http://www.jsbin.com), didn't know about that, looks nifty.
This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page) > note: I am working with a local server, so pageload in instant. that's not the issue - the constituent parts of a document are loaded in order. It doesn't matter how fast they are loaded, some things happen before others :D > The onlything I'd like to do now is remove the Javascript link from the ... Place an id on there, and inside your function do this: ``` document.getElementById('addField').onclick = addFileInput; ``` Or, as you already have the div as the variable 'a': ``` a.firstChild.onclick = addFileInput; ``` But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.
mercutio is correct. If that code is executing in the HEAD, the call to "document.getElementById('click1')" will always return null since the body hasn't been parsed yet. Perhaps you should put that logic inside of an onload event handler.
Javascript: var is null
[ "", "javascript", "html", "null", "" ]
I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong? Function: ``` std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField ) { ... return it; ... } ``` Error: ``` error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'std::_Vector_const_iterator<_Ty,_Alloc> *__w64 ' to 'const std::_Vector_iterator<_Ty,_Alloc> &' ```
Your search function is returning a const\_iterator. You should either return the same type, i.e. `std::vector< CClass >::const_iterator`, or cast it to a `std::vector< CClass >::iterator` if you intend the caller to be able to modify the found item through the iterator. EDIT: after seeing your update, it seems the problem is your iterator (it) has a different type than your function return. They should be the same. ``` std::vector< CClass >::iterator it; ```
Sounds like you have your const\_iterators mixed up. Please post more code, specifically how you are declaring your iterator.
Returning an Iterator
[ "", "c++", "stl", "iterator", "" ]
What is the *best* way to print the cells of a `String[][]` array as a right-justified table? For example, the input ``` { { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } } ``` should yield the output ``` x xxx yyy y zz zz ``` This seems like something that one *should* be able to accomplish using `java.util.Formatter`, but it doesn't seem to allow non-constant field widths. The best answer will use some standard method for padding the table cells, not the manual insertion of space characters.
Indeed, if you specify a width for the fields, it should be right-justified. If you need to have a dynamic padding, minimal for the longest string, you have to walk the array, getting the maximal width, generate the format string with the width computed from this maxima, and use it for format the output.
Here's an answer, using dynamically-generated format strings for each column: ``` public static void printTable(String[][] table) { // Find out what the maximum number of columns is in any row int maxColumns = 0; for (int i = 0; i < table.length; i++) { maxColumns = Math.max(table[i].length, maxColumns); } // Find the maximum length of a string in each column int[] lengths = new int[maxColumns]; for (int i = 0; i < table.length; i++) { for (int j = 0; j < table[i].length; j++) { lengths[j] = Math.max(table[i][j].length(), lengths[j]); } } // Generate a format string for each column String[] formats = new String[lengths.length]; for (int i = 0; i < lengths.length; i++) { formats[i] = "%1$" + lengths[i] + "s" + (i + 1 == lengths.length ? "\n" : " "); } // Print 'em out for (int i = 0; i < table.length; i++) { for (int j = 0; j < table[i].length; j++) { System.out.printf(formats[j], table[i][j]); } } } ```
Java: Print a 2D String array as a right-justified table
[ "", "java", "formatting", "printf", "" ]
Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why? Let's say we have an array of associative arrays: ``` var myArray = [{'key': 'value'}, {'key': 'value1'}]; ``` So we can iterate: ``` for (var i = 0; i < myArray.length; i++) ``` And: ``` for (var i in myArray) ``` I don't see a big difference. Are there any performance issues?
The choice should be based on the which idiom is best understood. An array is iterated using: ``` for (var i = 0; i < a.length; i++) //do stuff with a[i] ``` An object being used as an associative array is iterated using: ``` for (var key in o) //do stuff with o[key] ``` Unless you have earth shattering reasons, stick to the established pattern of usage.
Douglas Crockford recommends in [JavaScript: The Good Parts](http://oreilly.com/catalog/9780596517748/) (page 24) to avoid using the `for in` statement. If you use `for in` to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods. Everything but the properties can be filtered out with `.hasOwnProperty`. This code sample does what you probably wanted originally: ``` for (var name in obj) { if (Object.prototype.hasOwnProperty.call(obj, name)) { // DO STUFF } } ```
JavaScript for...in vs for
[ "", "javascript", "" ]
We are developing a new web service and are looking into the "best practice" for returning errors in the soap response. We were looking into creating a error response object which every response would contain as a property. This seems a little heavy however and are wondering if it is possible to use the SOAP header to carry this information? How do you normally deal with custom errors using SOAP?
SOAPFault is used to hold error and status information, and server returns 500 in the HTTP header for it to state it as fault. see the specification from W3.org <http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383507> You can design your own information token by either placing it into soap header or even within an element in your return result as long as you document it clearly for third party. However that is not the standard way to go for raising errors.
Soap already uses custom headers for error info, all you need to do is throw an exception on the server side, and exception is raised on the client side as a [SoapException](http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapexception.aspx). You can thrown SoapExceptions on the serverside if you want more control over the exception message/info. Edit: For extra information along with the request, custom soap headers can be used. Here's an [example article on CodeProject](http://www.codeproject.com/KB/webservices/SOAPHeaderAuthentication.aspx) that used custom soap headers for authentication, but custom soap headers can be used for other purposes like sending extra info that is not necessarily an error condition (can be business logic info)
Error handling using Soap Headers
[ "", "c#", ".net", "web-services", "soap", "error-handling", "" ]
How can I return the result of a different action or move the user to a different action if there is an error in my `ModelState` without losing my `ModelState` information? The scenario is; `Delete` action accepts a POST from a DELETE form rendered by my `Index` Action/View. If there is an error in the `Delete` I want to move the user back to the `Index` Action/View and show the errors that are stored by the `Delete` action in the `ViewData.ModelState`. How can this be done in ASP.NET MVC? ``` [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)] public ActionResult Delete([ModelBinder(typeof(RdfUriBinder))] RdfUri graphUri) { if (!ModelState.IsValid) return Index(); //this needs to be replaced with something that works :) return RedirectToAction("Index"); } ```
Store your view data in `TempData` and retrieve it from there in your `Index` action, if it exists. ``` ... if (!ModelState.IsValid) TempData["ViewData"] = ViewData; RedirectToAction( "Index" ); } public ActionResult Index() { if (TempData["ViewData"] != null) { ViewData = (ViewDataDictionary)TempData["ViewData"]; } ... } ``` [EDIT] I checked the on-line source for MVC and it appears that the `ViewData` in the Controller is settable, so it is probably easiest just to transfer all of the `ViewData`, including the `ModelState`, to the Index action.
Use Action Filters (PRG pattern) (as easy as using attributes) Mentioned [here](https://stackoverflow.com/questions/658747/how-do-i-maintain-modelstate-errors-when-using-redirecttoaction) and [here](https://web.archive.org/web/20130702160308/http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx).
How can I maintain ModelState with RedirectToAction?
[ "", "c#", "asp.net-mvc", "" ]
How can I transform a time value into YYYY-MM-DD format in Java? ``` long lastmodified = file.lastModified(); String lasmod = /*TODO: Transform it to this format YYYY-MM-DD*/ ```
Something like: ``` Date lm = new Date(lastmodified); String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(lm); ``` See the javadoc for [SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html).
``` final Date modDate = new Date(lastmodified); final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd"); final String lasmod = f.format(modDate); ``` [SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html)
How to transform a time value into YYYY-MM-DD format in Java?
[ "", "java", "time", "" ]
I'm calling a web service that returns an array of objects in JSON. I want to take those objects and populate a div with HTML. Let's say each object contains a url and a name. If I wanted to generate the following HTML for each object: ``` <div><img src="the url" />the name</div> ``` Is there a best practice for this? I can see a few ways of doing it: 1. Concatenate strings 2. Create elements 3. Use a templating plugin 4. Generate the html on the server, then serve up via JSON.
Options #1 and #2 are going to be your most immediate straight forward options, however, for both options, you're going to feel the performance and maintenance impact by either building strings or creating DOM objects. Templating isn't all that immature, and you're seeing it popup in most of the major Javascript frameworks. Here's an example in [JQuery Template Plugin](http://api.jquery.com/jQuery.template/) that will save you the performance hit, and is really, really straightforward: ``` var t = $.template('<div><img src="${url}" />${name}</div>'); $(selector).append( t , { url: jsonObj.url, name: jsonObj.name }); ``` I say go the cool route (and better performing, more maintainable), and use templating.
If you absolutely have to concatenate strings, instead of the normal : ``` var s=""; for (var i=0; i < 200; ++i) {s += "testing"; } ``` use a temporary array: ``` var s=[]; for (var i=0; i < 200; ++i) { s.push("testing"); } s = s.join(""); ``` Using arrays is much faster, especially in IE. I did some testing with strings a while ago with IE7, Opera and FF. Opera took only 0.4s to perform the test, but IE7 hadn't finished after 20 MINUTES !!!! ( No, I am not kidding. ) With array IE was very fast.
Is there a best practice for generating html with javascript
[ "", "javascript", "html", "ajax", "dynamic", "dhtml", "" ]
I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492'). In other words, I need to add correct amount of leading zeros to the number. ``` int n = 999; string str = some_function(n,6); //str = '000999' ``` Is there a function like this in C++?
or using the stringstreams: ``` #include <sstream> #include <iomanip> std::stringstream ss; ss << std::setw(10) << std::setfill('0') << i; std::string s = ss.str(); ``` I compiled the information I found on [arachnoid.com](http://www.arachnoid.com/cpptutor/student3.html) because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.
``` char str[7]; snprintf (str, 7, "%06d", n); ``` See [snprintf](http://libslack.org/manpages/snprintf.3.html)
Convert a number to a string with specified length in C++
[ "", "c++", "integer", "stdstring", "" ]
Yes, I know you could use regular objects as associative arrays in JavaScript, but I'd like to use something closer to java's Map's implementation (HashMap, LinkedHashMap etc). Something that could have any kind of data used as key. Are there any good hash(code/table) in JavaScript implementation out there?
In javascript, **objects are literally a hash implementation**. A Java HashMap will be a little bit of a fake-out, so I'd **challenge you** to re-think your needs. The **straight answer is no**, I don't believe that there is a great implementation of Java's HashMap in javascript. If there is, it's bound to be part of a library that you may or may not want to use, and you certainly **don't need to include a library** just to have a little hash table. So let's go ahead and write one, just to **examine the problem**. You can use it if you like. We'll just start by writing a constructor, and we'll piggyback off of Array, which is Object, but has some useful methods that will keep this example from getting too tedious: ``` function HashMap () { var obj = []; return obj; } var myHashMap = HashMap(); ``` We'll add some methods straight from the world of Java, but translate into javascript as we go... ``` function HashMap() { var obj = []; obj.size = function () { return this.length; }; obj.isEmpty = function () { return this.length === 0; }; obj.containsKey = function (key) { for (var i = 0; i < this.length; i++) { if (this[i].key === key) { return i; } } return -1; }; obj.get = function (key) { var index = this.containsKey(key); if (index > -1) { return this[index].value; } }; obj.put = function (key, value) { if (this.containsKey(key) !== -1) { return this.get(key); } this.push({'key': key, 'value': value}); }; obj.clear = function () { this = null; // Just kidding... }; return obj; } ``` We could continue to build it out, but I think it's the wrong approach. At the end of the day, we end up using what javascript provides behind the scenes, because we just simply don't have the HashMap type. In the process of **pretending**, it lends itself to all kinds of **extra work**. It's a bit ironic that one of the things that makes javascript such an interesting and diverse language is the ease with which it handles this kind of **wrestling**. We can literally do anything we'd like, and the quick example here does nothing if it doesn't illustrate the deceptive power of the language. Yet given that power, it seems **best not to use it**. I just think javascript wants to be lighter. My personal recommendation is that you re-examine the problem before you try implement a proper Java HashMap. **Javascript neither wants nor affords for one**. **Remember the native alternative**: ``` var map = [{}, 'string', 4, {}]; ``` ..so fast and easy by comparison. On the other hand, I don't believe that there are any hard-and-fast answers here. This implementation really **may be a perfectly acceptable solution**. If you feel you can use it, I'd say **give it a whirl**. But I'd never use it if I felt that we have **reasonably simpler and more natural means** at our disposal.. which I'm almost certain that we do. **Sidenote:** Is efficiency related to style? Notice the **performance hit**.. there's a big O staring us in the face at HashMap.put()... The less-than-optimal performance probably isn't a show-stopper here, and you'd probably need to be doing something very ambitious or have a large set of data before you'd even notice a performance hickup a modern browser. It's just interesting to note that operations tend to become less efficient when you're working against the grain, almost as if there is a natural entropy at work. Javascript is a high level language, and should offer efficient solutions when we keep in line with its conventions, just as a HashMap in Java will be a much more natural and high performing choice.
I have released a standalone JavaScript hash table implementation that goes further than those listed here. <http://www.timdown.co.uk/jshashtable/>
Is there any good JavaScript hash(code/table) implementation out there?
[ "", "javascript", "hash", "" ]
Is there a way to get all methods (private, privileged, or public) of a javascript object from within? Here's the sample object: ``` var Test = function() { // private methods function testOne() {} function testTwo() {} function testThree() {} // public methods function getMethods() { for (i in this) { alert(i); // shows getMethods, but not private methods } } return { getMethods : getMethods } }(); // should return ['testOne', 'testTwo', 'testThree', 'getMethods'] Test.getMethods(); ``` The current issue is the code in `getMethods()`, the simplified example will return just the public methods, but not to private ones. **edit**: my test code may (or may not) be overcomplicating what i'm hoping to get at. given the following: ``` function myFunction() { var test1 = 1; var test2 = 2; var test3 = 3; } ``` is there a way to find out what variables exist in `myFunction()` from within `myFunction()`. the pseudo-code would look like this: ``` function myFunction() { var test1 = 1; var test2 = 2; var test3 = 3; alert(current.properties); // would be nice to get ['test1', 'test2', 'test3'] } ```
The technical reason why those methods are hidden is twofold. First, when you execute a method on the Test object, "this" will be the untyped object returned at the end of the anonymous function that contains the public methods per the [Module Pattern](http://yuiblog.com/blog/2007/06/12/module-pattern/). Second, the methods testOne, testTwo, and testThree aren't attached to a specific object, and exist only in the context of the anonymous function. You could attach the methods to an internal object and then expose them through a public method, but it wouldn't be quite as clean as the original pattern and it won't help if you're getting this code from a third party. The result would look something like this: ``` var Test = function() { var private = { testOne : function () {}, testTwo : function () {}, testThree : function () {} }; function getMethods() { for (i in this) { alert(i); // shows getMethods, but not private methods } for (i in private) { alert(i); // private methods } } return { getMethods : getMethods } }(); // will return ['getMethods', 'testOne', 'testTwo', 'testThree'] Test.getMethods(); ``` **edit:** Unfortunately, no. The set of local variables aren't accessible via a single, automatic keyword. If you remove the "var" keyword they would be attached to the global context (usually the window object), but that's the only behavior that I know of that is similar to what you're describing. There would be a lot of other properties and methods on that object if you did that, though.
From <http://netjs.codeplex.com/SourceControl/changeset/view/91169#1773642> ``` //Reflection ~function (extern) { var Reflection = this.Reflection = (function () { return Reflection; }); Reflection.prototype = Reflection; Reflection.constructor = Reflection; Reflection.getArguments = function (func) { var symbols = func.toString(), start, end, register; start = symbols.indexOf('function'); if (start !== 0 && start !== 1) return undefined; start = symbols.indexOf('(', start); end = symbols.indexOf(')', start); var args = []; symbols.substr(start + 1, end - start - 1).split(',').forEach(function (argument) { args.push(argument); }); return args; }; extern.Reflection = extern.reflection = Reflection; Function.prototype.getArguments = function () { return Reflection.getArguments(this); } Function.prototype.getExpectedReturnType = function () { /*ToDo*/ } } (this); ```
Javascript Reflection
[ "", "javascript", "reflection", "closures", "" ]
We are developing an application that involves a lot of different tests where each test lead the users to a number of steps. We are thinking of using a state machine framework to capture the states/transitions out of the code. We are also thinking of using rule engine to supplement on the rules. Anyone has experience with any state machine framework that would work with JBoss and/or Java? Thanks in advance. -nguyen
[jbpm](http://jboss.org/jbpm) does this and integrates well with jboss. In my experience, it's pretty easy to use and is powerful.
You might want to look at [StatefulJ](http://www.statefulj.org). It is built off of Spring Data for Persistence support and the State Model itself is defined using Annotations. This approach makes it easier to set up and maintain vs. XML. Regarding rules - I've used Drools in the past and seems very well supported. Disclaimer: I am the author of StatefulJ
State Machine Framework for JBoss/Java?
[ "", "java", "frameworks", "fsm", "" ]
Is there any difference between a `volatile` Object reference and `AtomicReference` in case I would just use `get()` and `set()`-methods from `AtomicReference`?
Short answer is: No. From the [`java.util.concurrent.atomic`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/atomic/package-summary.html) package documentation. To quote: > The memory effects for accesses and updates of atomics generally follow the rules for volatiles: > > * `get` has the memory effects of reading a `volatile` variable. > * `set` has the memory effects of writing (assigning) a `volatile` variable. By the way, that documentation is very good and everything is explained. --- [`AtomicReference::lazySet`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/atomic/AtomicReference.html#lazySet(V)) is a newer (Java 6+) operation introduced that has semantics unachievable through `volatile` variables. See [this post](https://stackoverflow.com/a/1468020/591495)) for more information.
No, there is not. The additional power provided by AtomicReference is the compareAndSet() method and friends. If you do not need those methods, a volatile reference provides the same semantics as AtomicReference.set() and .get().
Java volatile reference vs. AtomicReference
[ "", "java", "concurrency", "" ]
What would be the easiest way to move the mouse around (and possibly click) using Python on OS X? This is just for rapid prototyping, it doesn't have to be elegant.
I dug through the source code of Synergy to find the call that generates mouse events: ``` #include <ApplicationServices/ApplicationServices.h> int to(int x, int y) { CGPoint newloc; CGEventRef eventRef; newloc.x = x; newloc.y = y; eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc, kCGMouseButtonCenter); //Apparently, a bug in xcode requires this next line CGEventSetType(eventRef, kCGEventMouseMoved); CGEventPost(kCGSessionEventTap, eventRef); CFRelease(eventRef); return 0; } ``` Now to write Python bindings!
Try the code at [this page](http://web.archive.org/web/20111229234504/http://www.geekorgy.com:80/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/). It defines a couple of functions, `mousemove` and `mouseclick`, which hook into Apple's integration between Python and the platform's Quartz libraries. This code works on 10.6, and I'm using it on 10.7. The nice thing about this code is that it generates mouse events, which some solutions don't. I use it to control BBC iPlayer by sending mouse events to known button positions in their Flash player (very brittle I know). The mouse move events, in particular, are required as otherwise the Flash player never hides the mouse cursor. Functions like `CGWarpMouseCursorPosition` will not do this. ``` from Quartz.CoreGraphics import CGEventCreateMouseEvent from Quartz.CoreGraphics import CGEventPost from Quartz.CoreGraphics import kCGEventMouseMoved from Quartz.CoreGraphics import kCGEventLeftMouseDown from Quartz.CoreGraphics import kCGEventLeftMouseUp from Quartz.CoreGraphics import kCGMouseButtonLeft from Quartz.CoreGraphics import kCGHIDEventTap def mouseEvent(type, posx, posy): theEvent = CGEventCreateMouseEvent( None, type, (posx,posy), kCGMouseButtonLeft) CGEventPost(kCGHIDEventTap, theEvent) def mousemove(posx,posy): mouseEvent(kCGEventMouseMoved, posx,posy); def mouseclick(posx,posy): # uncomment this line if you want to force the mouse # to MOVE to the click location first (I found it was not necessary). #mouseEvent(kCGEventMouseMoved, posx,posy); mouseEvent(kCGEventLeftMouseDown, posx,posy); mouseEvent(kCGEventLeftMouseUp, posx,posy); ``` Here is the code example from above page: ``` ############################################################## # Python OSX MouseClick # (c) 2010 Alex Assouline, GeekOrgy.com ############################################################## import sys try: xclick=intsys.argv1 yclick=intsys.argv2 try: delay=intsys.argv3 except: delay=0 except: print "USAGE mouseclick [int x] [int y] [optional delay in seconds]" exit print "mouse click at ", xclick, ",", yclick," in ", delay, "seconds" # you only want to import the following after passing the parameters check above, because importing takes time, about 1.5s # (why so long!, these libs must be huge : anyone have a fix for this ?? please let me know.) import time from Quartz.CoreGraphics import CGEventCreateMouseEvent from Quartz.CoreGraphics import CGEventPost from Quartz.CoreGraphics import kCGEventMouseMoved from Quartz.CoreGraphics import kCGEventLeftMouseDown from Quartz.CoreGraphics import kCGEventLeftMouseDown from Quartz.CoreGraphics import kCGEventLeftMouseUp from Quartz.CoreGraphics import kCGMouseButtonLeft from Quartz.CoreGraphics import kCGHIDEventTap def mouseEventtype, posx, posy: theEvent = CGEventCreateMouseEventNone, type, posx,posy, kCGMouseButtonLeft CGEventPostkCGHIDEventTap, theEvent def mousemoveposx,posy: mouseEventkCGEventMouseMoved, posx,posy; def mouseclickposx,posy: #mouseEvent(kCGEventMouseMoved, posx,posy); #uncomment this line if you want to force the mouse to MOVE to the click location first (i found it was not necesary). mouseEventkCGEventLeftMouseDown, posx,posy; mouseEventkCGEventLeftMouseUp, posx,posy; time.sleepdelay; mouseclickxclick, yclick; print "done." ```
How to control the mouse in Mac using Python?
[ "", "python", "macos", "mouse", "" ]
Is it possible to share a single 'god' instance among everyone that links to this code, to be placed in a shared object? ``` god* _god = NULL; extern "C" { int set_log_level(int level) { if(_god == NULL) return -1; _stb->log_level(level); return 0; } int god_init(){ if(_god == NULL){ _god = new god(); //Magic happens here } } } ``` Provided that I perform a lock synchronization at the beginning of every function, and considering that God itself can new/malloc other things, but those things will never be returned themselves to the caller (God mallocs only for internal use), what is the simplest way of doing this, if possible. How can that be extended to an arbitrary number of programs linked to this shared library?
[Boost Interprocess](http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess.html) library has high(er) level, portable shared memory objects.
This isn't the correct approach at all. By doing what you suggest, the variable, yes, is global to the library, and thus the program, but the data is private to the actual running process. You won't be able to share the values across running programs. @grieve is referring to a global accessed by multiple threads, but threads share the same parent process instance. Across actual processes, you need to break out to an OS specific shared memory facility. Take a look at [Shared Memory](http://en.wikipedia.org/wiki/Shared_memory) for details. It's a doable issue, but it's not particularly trivial to pull off. You'll also need a interprocess synchronization system like Semaphores as well to coordinate usage.
Creating an object in shared memory inside a Shared Lib (so) in C++
[ "", "c++", "memory", "shared-libraries", "" ]
How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A? ``` $A = array(1,2,3,4,5,6,7,8); $B = array(1,2,3,4); $C = array_intersect($A,$B); //equals (1,2,3,4) $A = array_diff($A,$B); //equals (5,6,7,8) ``` Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.
You've got it. Just use `array_diff` or `array_intersect`. Doesn't get much easier than that. **Edit:** For example: ``` $arr_1 = array_diff($arr_1, $arr_2); $arr_2 = array_diff($arr_2, $arr_1); ``` [Source](https://stackoverflow.com/a/8691348/2210140)
Dear easy and clean way ``` $clean1 = array_diff($array1, $array2); $clean2 = array_diff($array2, $array1); $final_output = array_merge($clean1, $clean2); ```
How to compare two arrays and remove matching elements from one for the next loop?
[ "", "php", "arrays", "" ]
I'm developing a Java application using Eclipse. My project has two source directories that are both built and then some files are copied into the output folder. From the output directory I then run my application and all works well. However, I keep having these warnings: [Snapshot from Problems tab in Eclipse http://www.freeimagehosting.net/uploads/128c1af93f.png](http://www.freeimagehosting.net/uploads/128c1af93f.png) Anyone know how to get rid of these warnings? Maybe by excluding some files, maybe based on the .svn extension or filename, from the build process? If so, how would I go about excluding those?
Have you tried to add `**/.svn/` to the *Exclusion patterns* at the *Source* preferences of the project's build path settings?
You could also try installing the Subversion plugin ([Subclipse](http://subclipse.tigris.org/)) for Eclipse.
In Eclipse, how can I exclude some files (maybe based on the .svn extension or filename) from being copied to the output folder?
[ "", "java", "eclipse", "svn", "build-process", "" ]
I'm working with LINQ to objects and have a function where in some cases I need to modify the underlying collection before calling `Aggregate(...)` and then return it to its original state before the funciton returns the results of `Aggregate(...)`. My current code looks something like this: ``` bool collectionModified = false; if(collectionNeedsModification) { modifyCollection(); collectionModified = true; } var aggregationResult = from a in (from b in collection where b.SatisfysCondition) .Aggregate(aggregationFunction) select a.NeededValue; if(collectionModified) modifyCollection(); return aggregationResult; ``` However, as written, if I modify the collection, I will get the wrong result because I'm putting the collection back in its original state before `aggregationResult` is enumerated and LINQ results are lazy-evaluated. My current solution is to use `.ToArray()` on my LINQ query like this: ``` var aggregationResult = (from a in (from b in collection where b.SatisfysCondition) .Aggregate(aggregationFunction) select a.NeededValue).ToArray(); ``` The size of the resulting array will always be small (< 100 items) so memory / processing time is not a concern. Is this the best way to handle my problem, or is there a better way to force the evaluation of a LINQ query?
Just to check I understand you - you basically want to iterate through all of the results, just to force any side effects to take place? Side effects are generally a bad idea precisely because things are harder to understand with this kind of logic. Having said that, the easiest way to do it and force full evaluation is probably to just iterate through it: ``` foreach (var result in aggregationResult) { // Deliberately empty; simply forcing evaluation of the sequence. } ``` Alternatively you could use [LastOrDefault()](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.lastordefault.aspx) to avoid all the copying involved in ToArray(). [Count()](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.count.aspx) will be okay so long as the result doesn't implement `IList<T>` (which involves a short-cut).
(Note: typing without a compiler at hand, so the code is untested) If you have Reactive Extensions for .NET as a dependency already you can use Run(): ``` aggregationResult.Run(); ``` But it might not be worth adding a dependency for this. You can also implement the Run method yourself as an extension method: ``` public static MyLinqExtensions { public static void Run<T>(this IEnumerable<T> e) { foreach (var _ in e); } } ```
Something better than .ToArray() to force enumeration of LINQ output
[ "", "c#", "linq", ".net-3.5", "" ]
How can I make this java generic cast ? ``` public interface IField { } class Field implements IField { // package private class } public class Form { private List<Field> fields; public List<IField> getFields() { return this.fields; } } ``` The return statement throws a compiler error (I know the reason - I read the generics tutorial) but it would be very handy to write such code. If I declared "fields" as List I would need to use a lot of casts to Field in other methods of a Form class . Can I force that damn compiler to bend it's rules and compile that return statement ? Thanks in advance.
A better solution, IMO, is to change the signature of your method to use a bounded wildcard: ``` public List<? extends IField> getFields() ``` This will let the caller treat anything coming "out" of the list as an IField, but it won't let the caller add anything into the list (without casting or warnings), as they don't know what the "real" type of the list is.
As it happens, you can, because Java generics are just grafted on, not part of the type system. You can do ``` return (List<IField>)(Object)this.fields; ``` because all `List<T>` objects are the same underlying type. Bear in mind that this allows anyone to put any type implementing `IField` in your list, so if your collection is not read-only, you may run into difficulties.
How can I make this java generic cast?
[ "", "java", "" ]
[Javascript Developer Tools](http://wiki.eclipse.org/index.php/ATF/JSDT) (JSDT) for Eclipse provides a nice outline view of Javascript classes, with a little symbol next to them to indicate visibility. Looking at *Preferences->Javascript->Appearance->Members Sort Order*, it seems able to indicate whether a method is public, private or protected, but all of my use the "default" marker, a blue triangle. Does anyone know how it determines which symbol to use? I've tried using Javadoc and JSDoc formatted comments. My private methods start with a leading underscore, and that doesn't give it a hint either. Not a big deal, just would be nice to know...
Seems that it is just a standard Java-based settings tree (used in many plugins) but without real implementation of JS [private members](http://javascript.crockford.com/private.html) stuff. Oh, we can hope that it is reserved for future use :)
There's no syntactical way of making a method *private, public* or *protected* in JavaScript, it strictly relies on where the method is defined (scope). *Marking* a methods privacy is something else, there really isn't a standard for that. All I've ever heard of is the "underscore" for private members. So maybe JSDT doesn't implement this.
How to indicate public/protected/private members in JSDT outline view?
[ "", "javascript", "eclipse", "ide", "jsdt", "" ]
I am using Infragistics UltraGrid in a Windows Forms application. I need an event which is raised on cell value change. I've tried many events like `AfterCellActivate`, `AfterCellUpdate` but was unable to find the right one.
AfterCellUpdate is what you want, but you may need to call: * YourGridControl.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.EnterEditMode) * YourGridControl.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.ExitEditMode) to actually trigger the update, depending on when you want it triggered. I've noticed that it can sometimes be finicky on when it'll fire off the event, otherwise.
There is a CellChange event which fires when the user begins to type a value in the cell. This event is useful if you need to know exactly when a cell is modified as the AfterCellUpdate event only fires when the user exits from the cell s/he is changing.
Which event raise on cell value change in Infragistics UltraGrid?
[ "", "c#", "vb.net", "winforms", "infragistics", "ultrawingrid", "" ]
I'm an end-user of one of my company's products. It is not very suitable for integration into Spring, however I am able to get a handle on the context and retrieve the required bean by name. However, I would still like to know if it was possible to inject a bean into this class, even though the class is not managed by Spring itself. Clarification: The same application which is managing the lifecycle of some class MyClass, is also managing the lifecycle of the Spring context. Spring does not have any knowledge of the instance of MyClass, and I would like to some how provide the instance to the context, but cannot create the instance in the context itself.
You can do this: ``` ApplicationContext ctx = ... YourClass someBeanNotCreatedBySpring = ... ctx.getAutowireCapableBeanFactory().autowireBeanProperties( someBeanNotCreatedBySpring, AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true); ``` You can use `@Autowired` and so on within `YourClass` to specify fields to be injected etc.
suppose that u have the following dependency chain: A --> B --> C --> x --> y -- > Z A, B, C are spring managed beans (constructed and manged by spring framework) x, y are really simple POJOs that constructed by your application, without spring assistance now if you want that y will get a reference to Z using spring that you need to have a 'handle' to the spring ApplicationContext one way to do it is to implement [ApplicationContextAware](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationContextAware.html) interface . In this case I would suggest that either A, B or C will implement this interface and will store the applicationContext reference in a static member. so lets take Class C for example: ``` class C implmenets ApplicationContextAware{ public static ApplicationContex ac; void setApplicationContext(ApplicationContext applicationContext) { ac = applicationContext; } ............. } ``` now, in class y you should have: ``` (Z)(C.ac.getBean("classZ")).doSomething() ``` HTH -- Yonatan
Injecting beans into a class outside the Spring managed context
[ "", "java", "spring", "" ]
Consider the following use of template template parameters... ``` #include <iostream> template <typename X> class A { X _t; public: A(X t) :_t(t) { } X GetValue() { return _t; } }; template <typename T, template <typename T> class C > class B { C<T> _c; public: B(T t) :_c(t) { } T GetValue() { return _c.GetValue(); } }; using namespace std; int main() { B<int, A> b(10); cout<<b.GetValue(); return 0; } ``` Is there a way by which the template parameter T can be removed? For example is there a way to make the following work? ``` //Does not compile template <template <typename T> class C > class B { C _c; public: B(T t) :_c(t) { } T GetValue() { return _c.GetValue(); } }; int main() { B< A<int> > b(10); cout<<b.GetValue(); return 0; } ```
I assume you're after X, as well as A, in your code. The usual pattern is to have ``` template<typename C> struct B { C c; }; ``` and then, inside classes eligible for substitution: ``` template<typename X> class A { typedef X type_name; X t; }; ``` Then you can access the template parameter using `C::type_name`.
This is not possible. Note that this is a common misunderstanding: `A<int>` is not a class template anymore! So it would not fit to a template-template parameter, but would have to be accepted using a type-parameter: ``` template<typename C> struct B { C c; }; B< A<int> > b; ``` Your way of using a separate parameter is alright. If you want to accept `A<int>` but want to re-bind it to another parameter, you can use this pattern, also used by standard-allocators: ``` template<typename T> struct A { template<typename U> struct rebind { typedef A<U> type; }; }; template<typename C> struct B { typename C::template rebind<float>::type c; }; B< A<int> > b; ``` Now, `B< A<int> >::c` is of type `A<float>`. The `typename` before `C::` tells the compiler the `::type` at the end is a type and not a static non-type member. The `template` after `C::` tells the compiler the `rebind<float>` is a template instantiation, and not a comparision.
How to declare/define a class with template template parameters without using an extra template parameter
[ "", "c++", "templates", "metaprogramming", "" ]
What's wrong with the following snippet ? ``` #include <tr1/functional> #include <functional> #include <iostream> using namespace std::tr1::placeholders; struct abc { typedef void result_type; void hello(int) { std::cout << __PRETTY_FUNCTION__ << std::endl; } void hello(int) const { std::cout << __PRETTY_FUNCTION__ << std::endl; } abc() {} }; int main(int argc, char *argv[]) { const abc x; int a = 1; std::tr1::bind(&abc::hello, x , _1)(a); return 0; } ``` Trying to compile it with g++-4.3, it seems that *cv*-qualifier overloaded functions confuse both `tr1::mem_fn<>` and `tr1::bind<>` and it comes out the following error: ``` no matching function for call to ‘bind(<unresolved overloaded function type>,... ``` Instead the following snippet compiles but seems to break the **const-correctness**: ``` struct abc { typedef void result_type; void operator()(int) { std::cout << __PRETTY_FUNCTION__ << std::endl; } void operator()(int) const { std::cout << __PRETTY_FUNCTION__ << std::endl; } abc() {} }; ... const abc x; int a = 1; std::tr1::bind( x , _1)(a); ``` Any clue?
The lookup is done at a time when the constness of `this` is not known. You just have to give it a hint via casting. Try this: ``` typedef void (abc::*fptr)(int) const; // or remove const std::tr1::bind((fptr)&abc::hello, x , _1)(a); ``` You may also notice here that removing the `const` still works. This is because you should be passing x by pointer (because the first argument to a C++ member function, the implicit `this` parameter, is always a pointer). Try this instead: ``` typedef void (abc::*fptr)(int) const; // won't compile without const (good!) std::tr1::bind((fptr)&abc::hello, &x , _1)(a); ``` As discovered during within my comments below, if you omit the `&` as you originally did, you'll be passing x *by value*, which is usually not what you want (though it makes little practical difference in your particular example). This actually seems like an unfortunate pitfall for `bind`.
As John suggested, the problems arisen in those snippets are the following: 1. When passing a *member-function-pointer* it's necessary to specify its signature (if overloaded) 2. `bind()` are passed arguments by value. The first problem is solved by casting the member function pointer provided to bind: ``` std::tr1::bind(static_cast< void(abc::*)(int) const >(&abc::hello), x, _1)(a); ``` The second can be solved by passing the callable object by address (as John suggested), or by means of TR1 `reference_wrapper<>` -- otherwise it will be passed by value, making the *const-correctness breaking hallucination*. Given x a callable object: ``` std::tr1::bind( std::tr1::ref(x) , _1)(a); ``` `bind()` will forward `a` to the proper `operator()` in accordance to the x **constness**.
tr1::mem_fn and tr1::bind: on const-correctness and overloading
[ "", "c++", "c++11", "functional-programming", "tr1", "" ]
Does anybody have experience using the open source offering from Terracotta as opposed to their enterprise offering? Specifically, I'm interested if it is worth the effort to use terracotta without the enterprise tools to manage your cluster? Over-simplified usage summary: we're a small startup with limited budget that needs to process millions of records and scale for hundreds-of-thousands of page views per day.
At the moment, the Terracotta enterprise tools provide only a few features beyond the open source version around things like visualization and management (like the ability to kick a client out of the cluster). That will continue to diverge and the enterprise tools are likely to boast more operator-level functionality around things like managing and monitoring, but you can certainly manage and tune an app even with the open source tools. The enterprise license also gives you things like support, indemnification, etc which may or may not be as important to you as the tooling. I would urge you to try it for yourself. If you'd like to see an example of a real app using Terracotta, you should check out this reference web app that was just released: [The Examinator](http://reference.terracotta.org)
I am in a process of integrating Terracotta with my project (a sensor node network simulator). About three weeks ago I found out about Terracotta from one of my colleagues. And now my application takes advantage of grid computing using Terracotta. Below I summarized some essential points of my experience with Terracotta. * The Terracotta site contains pretty detailed documentation. This article probably a good starting point for a developer [Concept and Architecture Guide](http://www.terracotta.org/web/display/docs/Concept+and+Architecture+Guide "Concept and Architecture Guide") * When you are stuck with a problem and found no answer in the documentation, the [Terracotta community forum](http://forums.terracotta.org/forums/forums/list.page) is a good place to ask questions. It seems that Terracotta developers check it on a regular basis and pretty responsive. * Even though Terracotta is running under JVM and it is advertised that it is only a matter of configuration to make you application running in a cluster, you should be ready that it may require to introduce some serious changes in you application to make it perform reasonably well. E.g. I had to completely rewrite synchronization logic of my application. * Good integration with Eclipse. * Admin Console is a great tool and it helped me a lot in tweaking my application to perform decently under Terracotta. It collects all performance metrics from servers and clients you can only think of. It certainly has some GUI related issues, but who does not :-) * Prefer standard Java Synchronization primitives (synchronized/wait/notify) over java.util.concurrent.\* citizens. I found that standard primitives provide higher flexibility (can be configured to be a read or write cluster lock or even not-a-lock at all), easier to track in the Admin Console (you see the class name of the object being locked rather then e.g. some ReentrantLock). Hope that helps.
Any experience using Terracotta open source?
[ "", "java", "load-balancing", "terracotta", "" ]
I have a set of core, complicated JavaScript data structures/classes that I'd like to be able to use both in the browser as JavaScript and run on the desktop with .NET 3.5. Is it possible to compile web-friendly JavaScript into assemblies that my C# code can access? * Managed JScript - Is there a compiler for this available that will produce something that can run on the desktop CLR? I've only seen released examples for the Silverlight runtime. It doesn't sound like it's officially available on the desktop but I'm willing to try something less blessed, like can I compile with the Silverlight tools and then run on the desktop CLR? * JScript .NET - Sounds like it's got enough custom language extensions where having the same code run in a browser would be really hard, but maybe there's a way...? If neither of those work, I guess my options are to: * Have a C# version and a JavaScript version which I have to keep in sync (yuck). * Write a preprocessor of sorts that runs at compile time to turn my JavaScript into JScript .NET or something that I can compile into .NET assemblies. * Script#: Looks like this turns C# code into JavaScript code. Not awesome since I'd prefer to be able to heavily tune JavaScript code directly, but it could work. Anyone have success with any of these options?
JScript.Net is actually mostly EMCAScript3 compliant. As long as you treat your code as a processing library (only have it do crunching, etc - use callbacks to interact with the program), you should be fine. I'm doing something similar, using javascript as my core parsing library, and then using it within python, dotnet, and php.
Managed JavaScript (IronJScript) appears to have been killed. See [this answer](https://stackoverflow.com/questions/775339/where-can-you-download-managed-jscript-for-the-dlr/886173#886173):
Sharing JavaScript code between .NET desktop and browser
[ "", ".net", "javascript", "script#", "jscript.net", "managed-jscript", "" ]
Is there an easy way within C# to check to see if a DateTime instance has been assigned a value or not?
The only way of having a variable which hasn't been assigned a value in C# is for it to be a local variable - in which case at compile-time you can tell that it isn't definitely assigned by trying to read from it :) I suspect you really want `Nullable<DateTime>` (or `DateTime?` with the C# syntactic sugar) - make it `null` to start with and then assign a normal `DateTime` value (which will be converted appropriately). Then you can just compare with `null` (or use the `HasValue` property) to see whether a "real" value has been set.
do you mean like so: ``` DateTime datetime = new DateTime(); if (datetime == DateTime.MinValue) { //unassigned } ``` or you could use Nullable ``` DateTime? datetime = null; if (!datetime.HasValue) { //unassigned } ```
Checking to see if a DateTime variable has had a value assigned
[ "", "c#", "datetime", "" ]
Is there any way to access the Windows Event Log from a java class. Has anyone written any APIs for this, and would there be any way to access the data from a remote machine? The scenario is: I run a process on a remote machine, from a controlling Java process. This remote process logs stuff to the Event Log, which I want to be able to see in the controlling process. Thanks in advance.
On the Java side, you'll need a library that allows you to make native calls. Sun offers [JNI](http://java.sun.com/javase/6/docs/technotes/guides/jni/index.html), but it sounds like sort of a pain. Also consider: * <https://github.com/twall/jna/> * <http://johannburkard.de/software/nativecall/> On the Windows side, the function you're after is [OpenEventLog](http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx). This should allow you to access a remote event log. See also [Querying for Event Information](http://msdn.microsoft.com/en-us/library/bb427356(VS.85).aspx). If that doesn't sound right, I also found this for parsing the log files directly (not an approach I'd recommend but interesting nonetheless): * <http://msdn.microsoft.com/en-us/library/bb309026.aspx> * <http://objectmix.com/java/75154-regarding-windows-event-log-file-parser-java.html>
[http://www.j-interop.org/](http://www.j-interop.org/ "J-Interop") is an open-source Java library that implements the DCOM protocol specification ***without using any native code***. (i.e. you can use it to access DCOM objects on a remote Windows host from Java code running on a non-Windows client). Microsoft exposes a plethora of system information via [Windows Management Instrumentation](http://msdn.microsoft.com/en-us/library/aa393258(VS.85).aspx "Windows Management Instrumentation") (WMI). WMI is remotely accessible via DCOM, and considerable documentation on the subject exists on Microsoft's site. As it happens, you can access the [Windows Event Logs](http://msdn.microsoft.com/en-us/library/aa394226(VS.85).aspx "Windows Event Logs") via this remotely accessible interface. By using j-interop you can create an instance of the [WbemScripting.SWbemLocator](http://msdn.microsoft.com/en-us/library/aa393719(VS.85).aspx "WbemScripting.SWbemLocator") WMI object remotely, then connect to Windows Management Instrumentation (WMI) services on the remote Windows host. From there you can submit a [query](http://msdn.microsoft.com/en-us/library/aa393864(VS.85).aspx "query") that will inform you whenever a new event log entry is written. Note that this does require that you have DCOM properly enabled and configured on the remote Windows host, and that appropriate exceptions have been set up in any firewalls. Details on this can be searched online, and are also referenced from the j-interop site, above. The following example connects to a remote host using its NT domain, hostname, a username and a password, and sits in a loop, dumping every event log entry as they are logged by windows. The user must have been granted appropriate remote DCOM access permissions, but does not have to be an administrator. ``` import java.io.IOException; import java.util.logging.Level; import org.jinterop.dcom.common.JIException; import org.jinterop.dcom.common.JISystem; import org.jinterop.dcom.core.JIComServer; import org.jinterop.dcom.core.JIProgId; import org.jinterop.dcom.core.JISession; import org.jinterop.dcom.core.JIString; import org.jinterop.dcom.core.JIVariant; import org.jinterop.dcom.impls.JIObjectFactory; import org.jinterop.dcom.impls.automation.IJIDispatch; public class EventLogListener { private static final String WMI_DEFAULT_NAMESPACE = "ROOT\\CIMV2"; private static JISession configAndConnectDCom( String domain, String user, String pass ) throws Exception { JISystem.getLogger().setLevel( Level.OFF ); try { JISystem.setInBuiltLogHandler( false ); } catch ( IOException ignored ) { ; } JISystem.setAutoRegisteration( true ); JISession dcomSession = JISession.createSession( domain, user, pass ); dcomSession.useSessionSecurity( true ); return dcomSession; } private static IJIDispatch getWmiLocator( String host, JISession dcomSession ) throws Exception { JIComServer wbemLocatorComObj = new JIComServer( JIProgId.valueOf( "WbemScripting.SWbemLocator" ), host, dcomSession ); return (IJIDispatch) JIObjectFactory.narrowObject( wbemLocatorComObj.createInstance().queryInterface( IJIDispatch.IID ) ); } private static IJIDispatch toIDispatch( JIVariant comObjectAsVariant ) throws JIException { return (IJIDispatch) JIObjectFactory.narrowObject( comObjectAsVariant.getObjectAsComObject() ); } public static void main( String[] args ) { if ( args.length != 4 ) { System.out.println( "Usage: " + EventLogListener.class.getSimpleName() + " domain host username password" ); return; } String domain = args[ 0 ]; String host = args[ 1 ]; String user = args[ 2 ]; String pass = args[ 3 ]; JISession dcomSession = null; try { // Connect to DCOM on the remote system, and create an instance of the WbemScripting.SWbemLocator object to talk to WMI. dcomSession = configAndConnectDCom( domain, user, pass ); IJIDispatch wbemLocator = getWmiLocator( host, dcomSession ); // Invoke the "ConnectServer" method on the SWbemLocator object via it's IDispatch COM pointer. We will connect to // the default ROOT\CIMV2 namespace. This will result in us having a reference to a "SWbemServices" object. JIVariant results[] = wbemLocator.callMethodA( "ConnectServer", new Object[] { new JIString( host ), new JIString( WMI_DEFAULT_NAMESPACE ), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), new Integer( 0 ), JIVariant.OPTIONAL_PARAM() } ); IJIDispatch wbemServices = toIDispatch( results[ 0 ] ); // Now that we have a SWbemServices DCOM object reference, we prepare a WMI Query Language (WQL) request to be informed whenever a // new instance of the "Win32_NTLogEvent" WMI class is created on the remote host. This is submitted to the remote host via the // "ExecNotificationQuery" method on SWbemServices. This gives us all events as they come in. Refer to WQL documentation to // learn how to restrict the query if you want a narrower focus. final String QUERY_FOR_ALL_LOG_EVENTS = "SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent'"; final int RETURN_IMMEDIATE = 16; final int FORWARD_ONLY = 32; JIVariant[] eventSourceSet = wbemServices.callMethodA( "ExecNotificationQuery", new Object[] { new JIString( QUERY_FOR_ALL_LOG_EVENTS ), new JIString( "WQL" ), new JIVariant( new Integer( RETURN_IMMEDIATE + FORWARD_ONLY ) ) } ); IJIDispatch wbemEventSource = (IJIDispatch) JIObjectFactory.narrowObject( ( eventSourceSet[ 0 ] ).getObjectAsComObject() ); // The result of the query is a SWbemEventSource object. This object exposes a method that we can call in a loop to retrieve the // next Windows Event Log entry whenever it is created. This "NextEvent" operation will block until we are given an event. // Note that you can specify timeouts, see the Microsoft documentation for more details. while ( true ) { // this blocks until an event log entry appears. JIVariant eventAsVariant = (JIVariant) ( wbemEventSource.callMethodA( "NextEvent", new Object[] { JIVariant.OPTIONAL_PARAM() } ) )[ 0 ]; IJIDispatch wbemEvent = toIDispatch( eventAsVariant ); // WMI gives us events as SWbemObject instances (a base class of any WMI object). We know in our case we asked for a specific object // type, so we will go ahead and invoke methods supported by that Win32_NTLogEvent class via the wbemEvent IDispatch pointer. // In this case, we simply call the "GetObjectText_" method that returns us the entire object as a CIM formatted string. We could, // however, ask the object for its property values via wbemEvent.get("PropertyName"). See the j-interop documentation and examples // for how to query COM properties. JIVariant objTextAsVariant = (JIVariant) ( wbemEvent.callMethodA( "GetObjectText_", new Object[] { new Integer( 1 ) } ) )[ 0 ]; String asText = objTextAsVariant.getObjectAsString().getString(); System.out.println( asText ); } } catch ( Exception e ) { e.printStackTrace(); } finally { if ( null != dcomSession ) { try { JISession.destroySession( dcomSession ); } catch ( Exception ex ) { ex.printStackTrace(); } } } } } ``` ~
How do I access Windows Event Viewer log data from Java
[ "", "java", "windows", "logging", "" ]
I have a directory with 500,000 files in it. I would like to access them as quickly as possible. The algorithm requires me to repeatedly open and close them (can't have 500,000 file open simultaneously). How can I do that efficiently? I had originally thought that I could cache the inodes and open the files that way, but \*nix doesn't provide a way to open files by inode (security or some such). The other option is to just not worry about it and hope the FS does good job on file look up in a directory. If that is the best option, which FS's would work best. Do certain filename patterns look up faster than others? eg 01234.txt vs foo.txt BTW this is all on Linux.
Assuming your file system is [ext3](http://en.wikipedia.org/wiki/Ext3), your directory is indexed with a hashed B-Tree if dir\_index is enabled. That's going to give you as much a boost as anything you could code into your app. If the directory is indexed, your file naming scheme shouldn't matter. <http://lonesysadmin.net/2007/08/17/use-dir_index-for-your-new-ext3-filesystems/>
A couple of ideas: a) If you can control the directory layout then put the files into subdirectories. b) If you can't move the files around, then you might try different filesystems, I think xfs might be good for directories with lots of entries?
Quick file access in a directory with 500,000 files
[ "", "c++", "linux", "file-io", "filesystems", "inode", "" ]
I have a time represented as the number of seconds elapsed since midnight, January 1, 1970, UTC (the results of an earlier call to time()). How do I add one day to this time? Adding 24 \* 60 \* 60 works in most cases, but fails if the daylight saving time comes on or off in between. In other words, I mostly want to add 24 hours, but sometimes 23 or 25 hours. To illustrate - the program: ``` #include <time.h> #include <iostream> int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { time_t time = base + i * 24 * 60 * 60; std::cout << ctime(&time); } return 0; ``` } Produces: ``` Sat Mar 11 08:00:00 2006 Sun Mar 12 09:00:00 2006 Mon Mar 13 09:00:00 2006 Tue Mar 14 09:00:00 2006 ``` I want the times for March 12, 13, ... to also be 8 AM. --- The answer provided by FigBug pointed me in the right direction. But I had to use localtime instead of gmtime. ``` int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { struct tm* tm = localtime(&base); tm->tm_mday += i; std::cout << asctime(tm); } return 0; } ``` Give me: ``` Sat Mar 11 08:00:00 2006 Sat Mar 12 08:00:00 2006 Sat Mar 13 08:00:00 2006 Sat Mar 14 08:00:00 2006 ``` Which is what I want. Using gmtime gives me the times at 14:00:00 However, note that all days are Sat. Also, it goes to March 32, 33, etc. If I throw in the mktime function I am back where I started: ``` #include <time.h> #include <iostream> int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { struct tm* tm = localtime(&base); tm->tm_mday += i; time_t time = mktime(tm); std::cout << asctime(tm); } return 0; } ``` Gives me: ``` Sat Mar 11 08:00:00 2006 Sun Mar 12 09:00:00 2006 Mon Mar 13 09:00:00 2006 Tue Mar 14 09:00:00 2006 ``` What am I missing??? --- OK, I have tried out FigBug's latest suggestion that is to use: ``` std::cout << ctime(&time); ``` instead of asctime, but I get the same results. So I guess that my library and/or compiler is messed up. I am using g++ 3.4.4 on cygwin. I copied the files over to Solaris 5.8 and used g++ 3.3 there to compile. I get the correct results there! In fact I get the correct results whether I use ctime or asctime for output: ``` Sat Mar 11 08:00:00 2006 Sun Mar 12 08:00:00 2006 Mon Mar 13 08:00:00 2006 Tue Mar 14 08:00:00 2006 ``` I also get the correct results (with both output functions) on Red Hut Linux with g++ 3.4.6. So I guess that I have come across a Cygwin bug. Thank you for all your help and advice....
use *gmtime()* to convert the *time\_t* to a *struct tm* add one to the day (*tm\_mday*) use *mktime()* to convert the *struct tm* back to a *time\_t* see [time.h](http://www.cplusplus.com/reference/clibrary/ctime/) for more info Edit: I just tried it, this works: ``` int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { struct tm* tm = localtime(&base); tm->tm_mday += i; time_t next = mktime(tm); std::cout << ctime(&next); } return 0; } ```
FigBug's solution will work **almost** every time, but it needs DST fix: **tm->tm\_isdst = -1** > A positive or 0 value for tm\_isdst > causes mktime() to presume initially > that Daylight Savings Time, > respectively, is or is not in effect > for the specified time. A negative > value for tm\_isdst causes mktime() to > attempt to determine whether Daylight > Saving Time is in effect for the > specified time. (quoted from [mktime spec](http://www.opengroup.org/onlinepubs/009695399/functions/mktime.html)) ``` int main() { time_t base = 1142085600; for(int i = 0; i < 4; ++i) { struct tm* tm = localtime(&base); tm->tm_mday += i; tm->tm_isdst = -1; // don't know if DST is in effect, please determine // this for me time_t next = mktime(tm); std::cout << ctime(&next); } return 0; } ``` Otherwise there will be a bug (example for Moscow Daylight Saving Time which starts 29 March 2009 01:59:59): ``` int main() { // 28 March 2009 05:00:00 GMT ( local - 08:00 (MSK) ) time_t base = 1238216400; std::time_t start_date_t = base; std::time_t end_date_t = base; std::tm start_date = *std::localtime(&start_date_t); std::tm end_date = *std::localtime(&end_date_t); end_date.tm_mday += 1; // end_date.tm_isdst = -1; std::time_t b = mktime(&start_date); std::time_t e = mktime(&end_date); std::string start_date_str(ctime(&b)); std::string stop_date_str(ctime(&e)); cout << " begin (MSK) (DST is not active): " << start_date_str; cout << " end (MSD) (DST is active): " << stop_date_str; } ``` Output: ``` begin (MSK) (DST is not active): Sat Mar 28 08:00:00 2009 end (MSD) (DST is active): Sun Mar 29 09:00:00 2009 ```
How to add one day to a time obtained from time()
[ "", "c++", "c", "date", "dst", "" ]
How do I check that I have an open network connection and can contact a specific ip address in c#? I have seen example in VB.Net but they all use the 'My' structure. Thank you.
If you just want to check if the network is up then use: ``` bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); ``` To check a specific interface's status (or other info) use: ``` NetworkInterface[] networkCards = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); ``` To check the status of a remote computer then you'll have to connect to that computer (see other answers)
If you want to monitor for changes in the status, use the [`System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged`](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.networkavailabilitychanged.aspx) event: ``` NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged); _isNetworkOnline = NetworkInterface.GetIsNetworkAvailable(); // ... void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { _isNetworkOnline = e.IsAvailable; } ```
Checking network status in C#
[ "", "c#", ".net", "network-programming", "" ]
**The background** I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks. The only decision I'm having trouble with, is whether we use Python or Jython to develop our application. Now I'm pretty familiar with Java and could possibly benefit from the libraries within the JDK. I know minimal Python, but am using this project as an opportunity to learn a new language - so the majority of work will be written in Python. The attractiveness of Jython is of course the JVM. The number of python/django enabled web-hosts is extremely minimal - whereas I'm assuming I could drop a jython/django application on a huge variety of hosts. This isn't a massive design decision, but still one I think needs to be decided. I'd really prefer jython over python for the jvm accessibility alone. **Questions** Does Jython have many limitations compared to regular python? Will running django on jython cause problems? How quick is the Jython team to release updates alongside Python? Will Django work as advertised on Jython (with very minimal pre-configuration)? **Decision** Thanks for the helpful comments. What I think I'm going to do is develop in Jython for the JVM support - but to try to only use Python code/libraries. Portability isn't a major concern so if I need a library in the JDK (not readily available in python), I'll use it. As long as Django is fully supported, I'm happy.
Django does [work on Jython](http://wiki.python.org/jython/DjangoOnJython), although you'll need to use the development release of Jython, since technically Jython 2.5 is still in beta. However, Django 1.0 and up should work unmodified. So as to whether you should use the regular Python implementation or Jython, I'd say it's a matter of whether you prefer having all the Java libraries available or all of the Python libraries. At this point you can expect almost everything in the Python standard library to work with Jython, but there are still plenty of third-party packages which will not work, especially C extension modules. I'd personally recommend going with regular Python, but if you've got a ton of JVM experience and want to stick with what you know, then I can respect that. As for finding Python hosting, [this page might be helpful](http://wiki.python.org/moin/PythonHosting).
I'd say that if you like Django, you'll also like Python. Don't make the (far too common) mistake of mixing past language's experience while you learn a new one. Only after mastering Python, you'll have the experience to judge if a hybrid language is better than either one. It's true that very few cheap hostings offer Django preinstalled; but it's quite probable that that will change, given that it's the most similar environment to Google's app engine. (and most GAE projects can be made to run on Django)
Are there problems developing Django on Jython?
[ "", "python", "django", "jvm", "jython", "" ]
I have a List object being accessed by multiple threads. There is mostly one thread, and in some conditions two threads, that updates the list. There are one to five threads that can read from this list, depending on the number of user requests being processed. The list is not a queue of tasks to perform, it is a list of domain objects that are being retrieved and updated concurrently. Now there are several ways to make the access to this list thread-safe: -use synchronized block -use normal *Lock* (i.e. read and write ops share same lock) -use *ReadWriteLock* -use one of the new *ConcurrentBLABLBA* collection classes **My question:** What is the optimal approach to use, given that the cricital sections typically do not contain a lot of operations (mostly just adding/removing/inserting or getting elements from the list)? Can you recommend another approach, not listed above? **Some constrains** -optimal performance is critical, memory usage not so much -it must be an ordered list (currently synchronizing on an *ArrayList*), although not a sorted list (i.e. not sorted using Comparable or Comparator, but according to insertion order) -the list will is big, containing up to 100000 domain objects, thus using something like CopyOnWriteArrayList not feasible -the write/update ciritical sections are typically very quick, doing simple add/remove/insert or replace (set) -the read operations will do primarily a elementAt(index) call most of the time, although some read operations might do a binary search, or indexOf(element) -no direct iteration over the list is done, though operation like indexOf(..) will traverse list
Do you have to use a sequential list? If a map-type structure is more appropriate, you can use a `ConcurrentHashMap`. With a list, a `ReadWriteLock` is probably the most effective way. Edit to reflect OP's edit: Binary search on insertion order? Do you store a timestamp and use that for comparison, in your binary search? If so, you may be able to use the timestamp as the key, and `ConcurrentSkipListMap` as the container (which maintains key order).
I don't know if this is a posible solution for the problem but... it makes sense to me to use a Database manager to hold that huge amount of data and let it manage the transactions
Best approach to use in Java 6 for a List being accessed concurrently
[ "", "java", "collections", "concurrency", "" ]
I have used getopt in Python and was hoping there would be something similar in Java. Please give a reason why your answer is better than the others.
[Commons CLI](http://commons.apache.org/cli/)
I use [Jewelcli](http://jewelcli.sourceforge.net/index.html) and it's quite good. You can also find a discussion of different available libraries [here](http://furiouspurpose.blogspot.com/2008/07/command-line-parsing-libraries-for-java.html).
What is the best way of parsing many complex command-line arguments in Java?
[ "", "java", "command-line", "" ]
Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write: ``` assertEquals(expectedValue, actualValue); ``` hit `Ctrl` + `Shift` + `O` and have Eclipse add: ``` import static org.junit.Assert.assertEquals; ``` Maybe I'm asking too much.
I'm using Eclipse Europa, which also has the Favorite preference section: > Window > Preferences > Java > Editor > Content Assist > Favorites In mine, I have the following entries (when adding, use "New Type" and omit the `.*`): ``` org.hamcrest.Matchers.* org.hamcrest.CoreMatchers.* org.junit.* org.junit.Assert.* org.junit.Assume.* org.junit.matchers.JUnitMatchers.* ``` All but the third of those are static imports. By having those as favorites, if I type "`assertT`" and hit **`Ctrl`+`Space`**, Eclipse offers up `assertThat` as a suggestion, and if I pick it, it will add the proper static import to the file.
If you highlight the method `Assert.assertEquals(val1, val2)` and hit `Ctrl` + `Shift` + `M` (Add Import), it will add it as a static import, at least in Eclipse 3.4.
Eclipse Optimize Imports to Include Static Imports
[ "", "java", "eclipse", "keyboard-shortcuts", "" ]
Let's say we have a concrete `class Apple`. (Apple objects can be instantiated.) Now, someone comes and derives an abstract `class Peach` from Apple. It's abstract because it introduces a new pure virtual function. The user of Peach is now forced to derive from it and define this new function. Is this a common pattern? Is this correct to do? Sample: ``` class Apple { public: virtual void MakePie(); // more stuff here }; ``` class Peach : public Apple { public: virtual void MakeDeliciousDesserts() = 0; // more stuff here }; Now let's say we have a concrete `class Berry`. Someone derives an abstract `class Tomato` from Berry. It's abstract because it overwrites one of Berry's virtual functions, and makes it pure virtual. The user of Tomato has to re-implement the function previously defined in Berry. Is this a common pattern? Is this correct to do? Sample: ``` class Berry { public: virtual void EatYummyPie(); // more stuff here }; ``` class Tomato : public Berry { public: virtual void EatYummyPie() = 0; // more stuff here }; Note: The names are contrived and do not reflect any actual code (hopefully). No fruits have been harmed in the writing of this question.
Re Peach from Apple: * Don't do it if Apple is a value class (i.e. has copy ctor, non-identical instances can be equal, etc). See Meyers More Effective C++ Item 33 for why. * Don't do it if Apple has a public nonvirtual destructor, otherwise you invite undefined behaviour when your users delete an Apple through a pointer to Peach. * Otherwise, you're probably safe, because you haven't violated [Liskov substitutability](http://www.objectmentor.com/resources/articles/lsp.pdf). A Peach IS-A Apple. * If you own the Apple code, prefer to factor out a common abstract base class (Fruit perhaps) and derive Apple and Peach from it. Re Tomato from Berry: * Same as above, plus: * Avoid, because it's unusual * If you must, document what derived classes of Tomato must do in order not to violate Liskov substitutability. The function you are overriding in Berry - let's call it `Juice()` - imposes certain requirements and makes certain promises. Derived classes' implementations of `Juice()` must require no more and promise no less. Then a DerivedTomato IS-A Berry and code which only knows about Berry is safe. Possibly, you will meet the last requirement by documenting that DerivedTomatoes must call `Berry::Juice()`. If so, consider using Template Method instead: ``` class Tomato : public Berry { public: void Juice() { PrepareJuice(); Berry::Juice(); } virtual void PrepareJuice() = 0; }; ``` Now there is an excellent chance that a Tomato IS-A Berry, contrary to botanical expectations. (The exception is if derived classes' implementations of `PrepareJuice` impose extra preconditions beyond those imposed by `Berry::Juice`).
It would seem to me like an indication of a bad design. Could be forced if you wanted to take a concrete definition from a closed library and extend it and branch a bunch of stuff off it, but at that point I'd be seriously considering the guideline regarding Encapsulation over Inheritance.. If you possibly can encapsulate, you probably should. Yeah, the more I think about it, this is a Very Bad Idea.
Deriving an abstract class from concrete class
[ "", "c++", "inheritance", "abstract-class", "pure-virtual", "" ]
I am using this HTML ``` <html> <head> <Title>EBAY Search</title> </head> <script language="JavaScript" src="ajaxlib.js"></script> <body> Click here <a href="#" OnClick="GetEmployee()">link</a> to show content <div id="Result"><The result will be fetched here></div> </body> </html> ``` With this Javascript ``` var xmlHttp function GetEmployee() { xmlHttp=GetXmlHttpObject() if(xmlHttp==null) { alert("Your browser is not supported") } var url="get_employee.php" url=url+"cmd=GetEmployee" url=url+"&sid="+Math.random() xmlHttp.open("GET",url,true) xmlHttp.send(null) } function FetchComplete() { if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("Result").innerHTML=xmlHttp.responseText } if(xmlHttp.readyState==1 || xmlHttp.readyState=="loading") { document.getElementById("Result").innerHTML="loading" } } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp =new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } ``` However it is not being called. get\_employee.php works fine when I call it by itself, so that is not the problem. Is there anything wrong in my code that would prevent it from being called? I cannot test with any firefox extensions, I do not have access, so please don't give that as an answer. edit: the problem is the javascript is not being called at all. I fixed the question mark problem, but even just a simple javascript with an alert is not being called.
use a javascript debugging tool like firebug, this will make your life simpler. you had a syntax error in your code that made the error "GetEmployee is not defined" it was a missing "catch" after the last try in "GetXmlHttpObject()". this is the same function after adding the missing "catch". ``` function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); }catch (e) { try { xmlHttp =new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } return xmlHttp; } ```
``` var url="get_employee.php?" ``` Needs the "?". It's better to use this markup to include your scripts: ``` <script type="text/javascript" src="ajaxlib.js"></script> ```
javascript not being called
[ "", "javascript", "html", "ajax", "" ]
> **Possible Duplicate:** > [PDO Prepared Statements](https://stackoverflow.com/questions/210564/pdo-prepared-statements) I'm using the mysqli extension in PHP and I'm wondering, is there possibly any way to see a prepared query as it will be executed on the server, e.g. The query is something like this ``` select * from table1 where id = ? and name = ? ``` but I want to see the query after the values are filled in, like this: ``` select * from table1 where id = 20 and name = "John" ```
**Duplicate of [PDO Prepared Statements](https://stackoverflow.com/questions/210564/pdo-prepared-statements)** Short answer: no. A prepared query will never be converted to the query you expect. It's executed directly by the database server. You can use mysql's query log or PDO's undocumented function `debugDumpParams`, but both are just approximations.
Turn on [mysql query logging](http://dev.mysql.com/doc/refman/5.0/en/query-log.html) and it will log all queries to a text file for you to review.
Is there a way to see a prepared query as it will be executed on the database?
[ "", "php", "mysql", "mysqli", "" ]
EDIT: For the inner queries, there could be more than one match per inner query. It grabs a bunch of tags with the same game\_ID. Thats why .First or .Max won't work. Need some help, I have a query in LINQ that looks like this: ``` from yy in Tags_Lookups where yy.Tag_ID == (from xx in Tags_Lookups where xx.Game_ID == new Guid("4962d645-711c-4db8-a7ce-ae9b36dd730c") select xx.Tag_ID) select yy ``` I am getting an error that looks like this: Operator '==' cannot be applied to operands of type 'int' and 'System.Linq.IQueryable' I have also tried this with no luck: ``` from yy in Tags_Lookups where yy.Tag_ID.Contains(from xx in Tags_Lookups where xx.Game_ID == new Guid("4962d645-711c-4db8-a7ce-ae9b36dd730c") select xx.Tag_ID) select yy ``` With this Error: 'int' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'int' could be found Can anyone help me write a good query that will work?
Since your inner query can return multiple matches, you just need to convert the inner query to a list and reverse the sense of the contains clause, I think. ``` from yy in Tags_Lookups where (from xx in Tags_Lookups where xx.Game_ID == new Guid("4962d645-711c-4db8-a7ce-ae9b36dd730c") select xx.Tag_ID).ToList() .Contains( yy.Tag_ID ) select yy ``` **EDIT** Changed query based on new information.
Just saw the edit - I think this is what you want (check my syntax, though): ``` from yy in Tags_Lookups join xx in Tags_Lookups on yy.Tag_ID Equals xx.Tag_ID where xx.Game_ID == new Guid("4962d645-711c-4db8-a7ce-ae9b36dd730c") select yy ``` That will get you a Tags\_Lookups value for every matching Game\_ID. You may want to wrap the whole thing in parenthesis and add ".Distinct" as well in case you might get multiple hits.
Linq Help. int.Contains and int == iqueryable doesn't work
[ "", "c#", "asp.net", "linq", "" ]
another request sorry.. Right now I am reading the tokens in one by one and it works, but I want to know when there is a new line.. if my file contains ``` Hey Bob Now ``` should give me ``` Hey Bob [NEW LINE] NOW ``` Is there a way to do this without using getline?
Yes the operator>> when used with string read 'white space' separated words. A 'White space' includes space tab and new line characters. If you want to read a line at a time use std::getline() The line can then be tokenized separately with a string stream. ``` std::string line; while(std::getline(std::cin,line)) { // If you then want to tokenize the line use a string stream: std::stringstream lineStream(line); std::string token; while(lineStream >> token) { std::cout << "Token(" << token << ")\n"; } std::cout << "New Line Detected\n"; } ``` Small addition: ## Without using getline() So you really want to be able to detect a newline. This means that newline becomes another type of token. So lets assume that you have words separated by 'white spaces' as tokens and newline as its own token. Then you can create a Token type. Then all you have to do is write the stream operators for a token: ``` #include <iostream> #include <fstream> class Token { private: friend std::ostream& operator<<(std::ostream&,Token const&); friend std::istream& operator>>(std::istream&,Token&); std::string value; }; std::istream& operator>>(std::istream& str,Token& data) { // Check to make sure the stream is OK. if (!str) { return str; } char x; // Drop leading space do { x = str.get(); } while(str && isspace(x) && (x != '\n')); // If the stream is done. exit now. if (!str) { return str; } // We have skipped all white space up to the // start of the first token. We can now modify data. data.value =""; // If the token is a '\n' We are finished. if (x == '\n') { data.value = "\n"; return str; } // Otherwise read the next token in. str.unget(); str >> data.value; return str; } std::ostream& operator<<(std::ostream& str,Token const& data) { return str << data.value; } int main() { std::ifstream f("PLOP"); Token x; while(f >> x) { std::cout << "Token(" << x << ")\n"; } } ```
I don't know why you think `std::getline` is bad. You can still recognize newlines. ``` std::string token; std::ifstream file("file.txt"); while(std::getline(file, token)) { std::istringstream line(token); while(line >> token) { std::cout << "Token :" << token << std::endl; } if(file.unget().get() == '\n') { std::cout << "newline found" << std::endl; } } ```
C++ Reading file Tokens
[ "", "c++", "file", "token", "" ]
I'm creating some big files (DB exports) with Java and I need to put them somewhere on our SharePoint server. Right now, I'm doing this with IE but I'd like to automate this step, too. I searched the web and I found some hints to use SOAP but I don't really see to the ground of all this, yet. Can someone provide me with some sample code or a recipe what I need to do? Please note: the SharePoint server asks for NT domain authentication. I can't even login with Firefox :( **EDIT** * How do I convert the scary URL in IE into a WebDAV path? * Is there a WebDAV "explorer" which I can use before I ruin the production system with my code? I tried "DAV Explorer 0.91" from <http://www.davexplorer.org/> but that can't connect (probably because of NT domain auth).
Okay ... after several hours of work and biting myself through the "documentation" MicroSoft provides and all the hints randomly spread over the 'net, I've managed to write some sample code to browse the content of a SharePoint server: [Navigating SharePoint Folders With Axis2](http://blog.pdark.de/2008/11/navigating-sharepoint-folders-with.html). Next stop: Uploading something.
In addition to [Sacha's suggestions](https://stackoverflow.com/questions/314258/how-do-i-upload-a-document-to-sharepoint-with-java/314283#314283), you can use the SharePoint SOAP web services. Each SharePoint site exposes a bunch of web services via the path `http://<Site>/_vti_bin/`. In your case, you probably want the [Lists web service](http://msdn.microsoft.com/en-us/library/lists.aspx) (`http://<Site>/_vti_bin/Lists.asmx`). You can grab the WSDL from `http://<Site>/_vti_bin/Lists.asmx?WSDL`. The WSS 3.0 SDK has details on how to use the web service (you'll probably want to use the `UpdateListItems` and `AddAttachment` methods). All that said, Sacha's first option (mapping a document library to a drive) is probably the easiest way assuming you can get around the NTLM issues. If you're using Windows you can simply navigate to a UNC path for a document library. For example, if the browser URL for your document library is: `http://<Site>/Foo/BarDocs/Forms/AllItems.aspx` you can simply type the corresponding UNC path in the Windows Explorer address bar: `\\<Site>\Foo\BarDocs` and then drag and drop files to this location. If you'd like you can map this location to a drive letter using Windows Explorer or the SUBST.EXE command-line utility.
How do I upload a document to SharePoint with Java?
[ "", "java", "sharepoint", "soap", "upload", "" ]
Say I have a stored procedure that returns data from a SELECT query. I would like to get a slightly different cut on those results depending on what parameters I pass through. I'm wondering whether it is better design to have multiple stored procedures that take one or no parameters to do this (for example, GetXByDate or GetXByUser), or one stored procedure with multiple parameters that does the lot (for example, GetX)? The advantage of the first option is that it's simpler and maybe faster, but disadvantage is that the essence of the query is duplicated across the stored procedures and needs to be maintained in several places. The advantage of the second option is that the query is only present once, but the disadvantage is that the query is more complex and harder to troubleshoot. What do you use in your solutions and why?
The more complex stored procedures are more complex for the SQL server to compile correctly and execute quickly and efficiently. Even in the big stored procedure you have to either have to have several copies of the query or add lots of CASEs and IFs in it which reduce performance. So you don't really gain much from lumping everything together. From my personal experience I also consider large SQL sp code with lots of branches more difficult to maintain that several smaller and straightforward sprocs. You could consider using views and UDFs to reduce copy-pasting of the query code. Saying that if you don't care about performance (intranet app, the queries are not that heavy, don't run that often) you might find having a universal sproc quite handy.
I would treat stored procedures much in the same way as I would a method on a class. It ought to do one thing and do it simply. Consider applying the same sorts of refactoring/code smell rules to your stored procedures that you would to your application code.
Is it better to write a more targeted stored procedure with fewer parameters?
[ "", "sql", "stored-procedures", "" ]
I need to replace our [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) Modal Popup controls with a JavaScript equivalent. We use this as a simple context sensitive help type popup. I did a quick browse but didn't see quite what I was looking for. I just need some text and a simple Close button/link, but I would like the page darkened below the popup, as it does with the Ajax modal control. Can anyone suggest a nice JavaScript popup/help type solution that you've used?
I can provide you the code. Do your modifications as necessary, OK? Page JavaScript: ``` function myPop() { this.square = null; this.overdiv = null; this.popOut = function(msgtxt) { //filter:alpha(opacity=25);-moz-opacity:.25;opacity:.25; this.overdiv = document.createElement("div"); this.overdiv.className = "overdiv"; this.square = document.createElement("div"); this.square.className = "square"; this.square.Code = this; var msg = document.createElement("div"); msg.className = "msg"; msg.innerHTML = msgtxt; this.square.appendChild(msg); var closebtn = document.createElement("button"); closebtn.onclick = function() { this.parentNode.Code.popIn(); } closebtn.innerHTML = "Close"; this.square.appendChild(closebtn); document.body.appendChild(this.overdiv); document.body.appendChild(this.square); } this.popIn = function() { if (this.square != null) { document.body.removeChild(this.square); this.square = null; } if (this.overdiv != null) { document.body.removeChild(this.overdiv); this.overdiv = null; } } } ``` Now the HTML page, using the JavaScript file: ``` <html> <head> <script type="text/javascript" src="NAME OF THE PAGE!.js"></script> <style> div.overdiv { filter: alpha(opacity=75); -moz-opacity: .75; opacity: .75; background-color: #c0c0c0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; } div.square { position: absolute; top: 200px; left: 200px; background-color: Menu; border: #f9f9f9; height: 200px; width: 300px; } div.square div.msg { color: #3e6bc2; font-size: 15px; padding: 15px; } </style> </head> <body> <div style="background-color: red; width: 200px; height: 300px; padding: 20px; margin: 20px;"></div> <script type="text/javascript"> var pop = new myPop(); pop.popOut("Jose leal"); </script> </body> </html> ``` Hope that this can help.
I've used the simplemodal jQuery plugin and I've been quite happy with it. You can check it out [here](http://www.ericmmartin.com/projects/simplemodal/).
How to code a JavaScript modal popup (to replace Ajax)?
[ "", "javascript", "modalpopups", "" ]
I have an application that needs to send a moderately high volume of messages between a number of AppDomains. I know that I could implement this using remoting, but I have also noticed that there are cross-domain delegates. Has anyone looked at this kind of problem?
I have had good success using WCF with a named pipes binding. Using named pipes creates no network traffic and uses binary encoding, so it should be pretty fast without sacrificing the ability to distribute in future scaling scenarios. EDIT: Refer [here](https://stackoverflow.com/questions/50153/interprocess-communication-for-windows-in-c-net-20) for more detailed information including a link to an implementation example.
A cross-domain delegate only allows a void method with zero parameters, and it's probably not what you think it is. It's only barely useful as a simple callback for notification purposes from one appdomain to another, e.g. a method like InitComplete() or something. Remoting is the ONLY choice, whether you call it WCF or whatever else, passing serializable types, or using MBRO types (MarshalByRefObjects). It's not as hard as you think. -Oisin
How best to communicate between AppDomains?
[ "", "c#", ".net", "remoting", "appdomain", "" ]
I am running a java program that sets up a database connection to an SQL database. It works fine on Mac OS X, but when I try to run the same code on Linux, I get a Exception in thread "main" java.lang.NoClassDefFoundError: java/sql/SQLClientInfoException. I am using jdk-1.6.0\_02 - if I unzip src.zip, it turns out that SQLClientInfoException.java is not contained therein. Also, the API documentation shows that there are exactly two methods that use this exception, both in java.sql.Connection. However, if I look at both methods in the source code, both of them seem to throw the more general SQLException instead. Is that a bug in my java version or am I doing something wrong?
SQLClientInfoException is new in Java 1.6 and should be present in the src.zip. I have a `jdk1.6.0_03` in Windows and a `jdk1.6.0_06` in Linux and the class is included in both. Try to upgrade to the latest version.
Make sure you're actually running the sun JDK and not the GCJ version that ships as standard on many linux distributions. That version is a bit outdated and prone to weird bugs like this.
SQLClientInfoException / Linux
[ "", "java", "linux", "" ]
Is there a way I can set up callbacks on (or automataically log) method parameters, entries, and exits without making explicit calls within each method? I basically want to log this information to my logger class (which is static) without having to do it manually for each method. Right now I have to call Logger::logEntry() and Logger::logExit() in every method to accomplish this. I would love to not have to do this: ``` class TestClass { public function tester($arg) { Logger::logEntry(); Logger::info('Parameter $arg => ' . $arg); // Do some stuff... Logger::logExit(); } } ```
use a wrapper class. this method has the following benefits: * no need to change your underlying class structure / method signatures * change logging? just update this class * update object calls vs inserting code into every class you want to log . ``` class LogWatch { function __construct($class) { $this->obj = $class; } function __call($method, $args) { if (in_array($method, get_class_methods($this->obj) ) ) { Logger::logEntry(); Logger::info('Parameter '.implode(', ', $args) ); call_user_func_array(array($this->obj, $method), $args); Logger::logExit(); } else { throw new BadMethodCallException(); } } } $test = new LogWatch(new TestClass() ); $test->tester(); // you can use instances of `LogWatch()` just like your watched class // including passing appropriate params: $test->tester($param1, $param2); ```
If you want to do function logging for the sake of debugging you may want to look into the Xdebug extension. There's no good way to intercept function calls at at runtime, and any automated interception will add great runtime overhead. Using XDebug you could instead turn it on as-needed, as well as get lots of other stuff ( XDebug is thus used with PHPUnit to do unit testing and coverage analysis. ) * [Xdebug](http://www.xdebug.org/docs/execution_trace) * [PHPUnit](http://www.phpunit.de/wiki/Documentation) ### The Problem with \_\_call \_\_call may look to be a fun solution to the problem, but there are *3* problems with this, namely * Significant Execution Overhead. your doing \_\_call --> call\_user\_func\_array , which will literally add not one, but **two** function calls to every execution. * Backtraces become indecipherable: The actual function you were trying to call gets lost in a sea of \_\_call and call\_user\_func\_array making backtracing exceedingly hard, especially if your backtraces come with their arguent lists included. * Stupid Hidden Functions: You're going back to PHP4 style "hiding" of functions by prefixing them with \_ to stop the user directly calling it or seeing it, because if the function name happens to be named what they wan't, the \_\_call wont trigger, so you have already got a whole class full of really horrible function names, which developers will be tempted to call directly anyway in various places. ( And if you want to get rid of \_\_call later, you will have to rename all these functions as to not break the code! ) Thus, if you are utilising php code to implement this will result in epically horrible code, that any future user of your codebase will *NOT* want to work with. You are far better getting something ( like Xdebug ) that can be added transparently when you need it, and save greatly polluting your code.
PHP: Callback on Entry/Exit of Class Methods?
[ "", "php", "logging", "methods", "callback", "stack-trace", "" ]
I am creating a large table dynamically using Javascript. I have realised the time taken to add a new row grows exponentially as the number of rows increase. I suspect the Page is getting refreshed in each loop per row (I am also adding input elements of type text on each cell) Is there a way to stop the page "refreshing" until I am done with the whole table? Any suggestion on how to do this or go around it? --- I have tried all the suggestions above, but I am still getting the performance bottlenecks. I tried to analyse line after line, and I have noted that document.getElementById() is one of the lines taking a lot of time to execute when the table is very large. I am using getElementById() to dynamically access an HTML input of type text loaded on each cell of the table. Any ideas on which DOM method I should use instead of getElementById()?
Use the table DOM to loop trough the rows and cells to populate them, instead of using document.getElementByID() to get each individual cell. ``` E.g. thisTable = document.getElementByID('mytable');//get the table oneRow = thisTable.rows[0].cells; //for instance the first row for (var colCount = 0; colCount <totalCols; colCount ++) { oneCell =oneRow[colCount]; oneCell.childNodes[0].value = 'test';//if your cell contains an input element oneCell.innerHTML = 'test'; // simply write on the cell directly } ``` Hope that helps someone else... Cheers.
You can create the table object without adding it to the document tree, add all the rows and then append the table object to the document tree. ``` var theTable = document.createElement("table"); // ... // add all the rows to theTable // ... document.body.appendChild(theTable); ```
How to "pause" refresh of page when drawing HTML table dynamically
[ "", "javascript", "html", "" ]
I have two tables: a source table and a target table. The target table will have a subset of the columns of the source table. I need to update a single column in the target table by joining with the source table based on another column. The update statement is as follows: ``` UPDATE target_table tt SET special_id = ( SELECT source_special_id FROM source_table st WHERE tt.another_id = st.another_id ) ``` For some reason, this statement seems to run indefinitely. The inner select happens almost immediately when executed by itself. The table has roughly 50,000 records and its hosted on a powerful machine (resources are not an issue). Am I doing this correctly? Any reasons the above wouldn't work in a timely manner? Any better way to do this?
Your initial query executes the inner subquery once for every row in the outer table. See if Oracle likes this better: ``` UPDATE target_table SET special_id = st.source_special_id FROM target_table tt INNER JOIN source_table st WHERE tt.another_id = st.another_id ``` (edited after posted query was corrected) **Add:** If the join syntax doesn't work on Oracle, how about: ``` UPDATE target_table SET special_id = st.source_special_id FROM target_table tt, source_table st WHERE tt.another_id = st.another_id ``` The point is to join the two tables rather than using the outer query syntax you are currently using.
Is there an index on source\_table(another\_id)? If not source\_table will be fully scanned once for each row in target\_table. This will take some time if target\_table is big. Is it possible for there to be no match in source\_table for some target\_table rows? If so, your update will set special\_id to null for those rows. If you want to avoid that do this: ``` UPDATE target_table tt SET special_id = ( SELECT source_special_id FROM source_table st WHERE tt.another_id = st.another_id ) WHERE EXISTS( SELECT NULL FROM source_table st WHERE tt.another_id = st.another_id ); ``` **If** target\_table.another\_id was declared as a foreign key referencing source\_table.another\_id (unlikely in this scenario), this would work: ``` UPDATE ( SELECT tt.primary_key, tt.special_id, st.source_special_id FROM tatget_table tt JOIN source_table st ON st.another_id = tt.another_id ) SET special_id = source_special_id; ```
How can I speed up a joined update in SQL? My statement seems to run indefinitely
[ "", "sql", "oracle", "performance", "" ]
I'm trying to get a handle on if there's a good time to use standard linq keywords or linq extension methods with lambda expressions. They seems to do the same thing, just are written differently. Is it purely a matter of style? ``` var query = from p in Products where p.Name.Contains("foo") orderby c.Name select p; // or with extension methods: var query = Products .Where(p => p.Name.Contains("foo")) .OrderBy(p => p.Name); ``` They're very similar with the second example being a bit more terse, but perhaps less expressive if you don't know what the => is doing. **Other than writing terse code, are there other advantages to using the extension methods as opposed to the LINQ syntax?**
Honestly, sometimes it can be situational once you start using Funcs and Actions. Say you are using these three funcs: ``` Func<DataClasses.User, String> userName = user => user.UserName; Func<DataClasses.User, Boolean> userIDOverTen = user => user.UserID < 10; Func<DataClasses.User, Boolean> userIDUnderTen = user => user.UserID > 10; ``` As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let's face it, the third should be pretty easy to understand now. NOTE: This is a silly example but it works. ``` var userList = from user in userList where userIDOverTen(user) select userName; ``` Versus ``` var otherList = userList .Where(IDIsBelowNumber) .Select(userName) ``` In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can't since it is look just for a Boolean rather than a Func that returns boolean. However, this is where it might be better to use the expression language. Say you already had a method that takes in more than just a user: ``` private Boolean IDIsBelowNumber(DataClasses.User user, Int32 someNumber, Boolean doSomething) { return user.UserID < someNumber; } ``` Note: doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean. Kind of annoying for this example. Now if you look at the Linq query: ``` var completeList = from user in userList where IDIsBelowNumber(user, 10, true) select userName; ``` You're good for it. Now the Extension Method: ``` var otherList = userList .Where(IDIsBelowNumber????) .Select(userName) ``` Without a lambda expression, I really can't call that method. So now what I have to do is create a method that creates a Func based off the original method call. ``` private Func<DataClasses.User, Boolean> IDIsBelowNumberFunc(Int32 number) { return user => IDIsBelowNumber(user, number, true); } ``` And then plug it in: ``` var otherList = userList .Where(IDIsBelowNumberFunc(10)) .Select(userName) ``` So you can see, sometimes it may just be easier to use the query approach at times.
One advantage to using LINQ extension methods (*method-based queries*) is that you can define custom extension methods and it will still read fine. On the other hand, when using a LINQ *query expression*, the custom extension method is not in the keywords list. It will look a bit strange mixed with the other keywords. # Example I am using a custom extension method called `Into` which just takes a string: ## Example with query ``` var query = (from p in Products where p.Name.Contains("foo") orderby c.Name select p).Into("MyTable"); ``` ## Example with extension methods ``` var query = Products .Where(p => p.Name.Contains("foo")) .OrderBy(p => p.Name) .Into("MyTable"); ``` In my opinion the latter, using a *method-based query*, reads better when you have custom extension methods.
Extension methods syntax vs query syntax
[ "", "c#", ".net", "linq", "extension-methods", "linq-query-syntax", "" ]
I haven't used regular expressions at all, so I'm having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions. ``` string compare = "1234=4321"; Regex regex = new Regex(@"[\d]"); if (regex.IsMatch(compare)) { //true } regex = new Regex("[0-9]"); if (regex.IsMatch(compare)) { //true } ``` In case it matters, I'm using C# and .NET2.0.
Use the beginning and end anchors. ``` Regex regex = new Regex(@"^\d$"); ``` Use `"^\d+$"` if you need to match more than one digit. --- Note that `"\d"` will match `[0-9]` and other digit characters like the Eastern Arabic numerals `٠١٢٣٤٥٦٧٨٩`. Use `"^[0-9]+$"` to restrict matches to just the Arabic numerals 0 - 9. --- If you need to include any numeric representations other than just digits (like decimal values for starters), then see [@tchrist](https://stackoverflow.com/users/471272/tchrist)'s [comprehensive guide to parsing numbers with regular expressions](https://stackoverflow.com/a/4247184/1288).
Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers: ``` regex = new Regex("^[0-9]+$"); ``` The `^` will anchor the beginning of the string, the `$` will anchor the end of the string, and the `+` will match one or more of what precedes it (a number in this case).
Regex for numbers only
[ "", "c#", "regex", "" ]
I am using Eclipse 3.3 ("Europa"). Periodically, Eclipse takes an inordinately long time (perhaps forever) to start up. The only thing I can see in the Eclipse log is: ``` !ENTRY org.eclipse.core.resources 2 10035 2008-10-16 09:47:34.801 !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes. ``` Googling reveals [someone's suggestion](http://dev.zhourenjian.com/blog/2007/11/07/eclipse-freezing-on-start.html) that I remove the folder: ``` workspace\.metadata\.plugins\org.eclipse.core.resources\.root\.indexes ``` This does not appear to have helped. Short of starting with a new workspace (something which I am not keen to do, as it takes me hours to set up all my projects again properly), is there a way to make Eclipse start up properly?
This may not be an exact solution for your issue, but in my case, I tracked the files that Eclipse was polling against with [SysInternals Procmon](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx), and found that Eclipse was constantly polling a fairly large snapshot file for one of my projects. Removed that, and everything started up fine (albeit with the workspace in the state it was at the previous launch). The file removed was: ``` <workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\.markers.snap ```
try: 1. cd to **<workspace>\.metadata\.plugins\org.eclipse.core.resources** 2. remove the file **\*.snap** (or **.markers** in Indigo)
How do I prevent Eclipse from hanging on startup?
[ "", "java", "eclipse", "eclipse-3.3", "" ]
[C++11](http://en.wikipedia.org/wiki/C%2B%2B11) introduces [user-defined literals](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2378.pdf) which will allow the introduction of new literal syntax based on existing literals (`int`, `hex`, `string`, `float`) so that any type will be able to have a literal presentation. **Examples:** ``` // imaginary numbers std::complex<long double> operator "" _i(long double d) // cooked form { return std::complex<long double>(0, d); } auto val = 3.14_i; // val = complex<long double>(0, 3.14) // binary values int operator "" _B(const char*); // raw form int answer = 101010_B; // answer = 42 // std::string std::string operator "" _s(const char* str, size_t /*length*/) { return std::string(str); } auto hi = "hello"_s + " world"; // + works, "hello"_s is a string not a pointer // units assert(1_kg == 2.2_lb); // give or take 0.00462262 pounds ``` At first glance this looks very cool but I'm wondering how applicable it really is, when I tried to think of having the suffixes `_AD` and `_BC` create dates I found that it's problematic due to operator order. `1974/01/06_AD` would first evaluate `1974/01` (as plain `int`s) and only later the `06_AD` (to say nothing of August and September having to be written without the `0` for octal reasons). This can be worked around by having the syntax be `1974-1/6_AD` so that the operator evaluation order works but it's clunky. So what my question boils down to is this, do you feel this feature will justify itself? What other literals would you like to define that will make your C++ code more readable? --- Updated syntax to fit the final draft on June 2011
Here's a case where there is an advantage to using user-defined literals instead of a constructor call: ``` #include <bitset> #include <iostream> template<char... Bits> struct checkbits { static const bool valid = false; }; template<char High, char... Bits> struct checkbits<High, Bits...> { static const bool valid = (High == '0' || High == '1') && checkbits<Bits...>::valid; }; template<char High> struct checkbits<High> { static const bool valid = (High == '0' || High == '1'); }; template<char... Bits> inline constexpr std::bitset<sizeof...(Bits)> operator"" _bits() noexcept { static_assert(checkbits<Bits...>::valid, "invalid digit in binary string"); return std::bitset<sizeof...(Bits)>((char []){Bits..., '\0'}); } int main() { auto bits = 0101010101010101010101010101010101010101010101010101010101010101_bits; std::cout << bits << std::endl; std::cout << "size = " << bits.size() << std::endl; std::cout << "count = " << bits.count() << std::endl; std::cout << "value = " << bits.to_ullong() << std::endl; // This triggers the static_assert at compile time. auto badbits = 2101010101010101010101010101010101010101010101010101010101010101_bits; // This throws at run time. std::bitset<64> badbits2("2101010101010101010101010101010101010101010101010101010101010101_bits"); } ``` The advantage is that a run-time exception is converted to a compile-time error. You couldn't add the static assert to the bitset ctor taking a string (at least not without string template arguments).
At first sight, it seems to be simple syntactic sugar. But when looking deeper, we see it's more than syntactic sugar, as **it extends the C++ user's options to create user-defined types that behave exactly like distinct built-in types.** In this, this little "bonus" is a very interesting C++11 addition to C++. ## Do we really need it in C++? I see few uses in the code I wrote in the past years, but just because I didn't use it in C++ doesn't mean it's not interesting for *another C++ developer*. We had used in C++ (and in C, I guess), compiler-defined literals, to type integer numbers as short or long integers, real numbers as float or double (or even long double), and character strings as normal or wide chars. **In C++, we had the possibility to create our own types** (i.e. classes), with potentially no overhead (inlining, etc.). We had the possibility to add operators to their types, to have them behave like similar built-in types, which enables C++ developers to use matrices and complex numbers as naturally as they would have if these have been added to the language itself. We can even add cast operators (which is usually a bad idea, but sometimes, it's just the right solution). **We still missed one thing to have user-types behave as built-in types: user-defined literals.** So, I guess it's a natural evolution for the language, but to be as complete as possible: "*If you want to create a type, and you want it to behave as much possible as a built-in types, here are the tools...*" I'd guess it's very similar to .NET's decision to make every primitive a struct, including booleans, integers, etc., and have all structs derive from Object. This decision alone puts .NET far beyond Java's reach when working with primitives, no matter how much boxing/unboxing hacks Java will add to its specification. ## Do YOU really need it in C++? This question is for **YOU** to answer. Not Bjarne Stroustrup. Not Herb Sutter. Not whatever member of C++ standard committee. This is why **you have the choice in C++**, and they won't restrict a useful notation to built-in types alone. If **you** need it, then it is a welcome addition. If **you** don't, well... Don't use it. It will cost you nothing. Welcome to C++, the language where features are optional. ## Bloated??? Show me your complexes!!! There is a difference between bloated and complex (pun intended). Like shown by Niels at [What new capabilities do user-defined literals add to C++?](https://stackoverflow.com/questions/237804/user-defined-literals-in-c0x-a-much-needed-addition-or-making-c-even-more-bloat#237821), being able to write a complex number is one of the two features added "recently" to C and C++: ``` // C89: MyComplex z1 = { 1, 2 } ; // C99: You'll note I is a macro, which can lead // to very interesting situations... double complex z1 = 1 + 2*I; // C++: std::complex<double> z1(1, 2) ; // C++11: You'll note that "i" won't ever bother // you elsewhere std::complex<double> z1 = 1 + 2_i ; ``` Now, both C99 "double complex" type and C++ "std::complex" type are able to be multiplied, added, subtracted, etc., using operator overloading. But in C99, they just added another type as a built-in type, and built-in operator overloading support. And they added another built-in literal feature. In C++, they just used existing features of the language, saw that the literal feature was a natural evolution of the language, and thus added it. In C, if you need the same notation enhancement for another type, you're out of luck until your lobbying to add your quantum wave functions (or 3D points, or whatever basic type you're using in your field of work) to the C standard as a built-in type succeeds. In C++11, you just can do it yourself: ``` Point p = 25_x + 13_y + 3_z ; // 3D point ``` **Is it bloated? No**, the need is there, as shown by how both C and C++ complexes need a way to represent their literal complex values. **Is it wrongly designed? No**, it's designed as every other C++ feature, with extensibility in mind. **Is it for notation purposes only? No**, as it can even add type safety to your code. For example, let's imagine a CSS oriented code: ``` css::Font::Size p0 = 12_pt ; // Ok css::Font::Size p1 = 50_percent ; // Ok css::Font::Size p2 = 15_px ; // Ok css::Font::Size p3 = 10_em ; // Ok css::Font::Size p4 = 15 ; // ERROR : Won't compile ! ``` It is then very easy to enforce a strong typing to the assignment of values. ## Is is dangerous? Good question. Can these functions be namespaced? If yes, then Jackpot! Anyway, **like everything, you can kill yourself if a tool is used improperly**. C is powerful, and you can shoot your head off if you misuse the C gun. C++ has the C gun, but also the scalpel, the taser, and whatever other tool you'll find in the toolkit. You can misuse the scalpel and bleed yourself to death. Or you can build very elegant and robust code. So, like every C++ feature, do you really need it? It is the question you must answer before using it in C++. If you don't, it will cost you nothing. But if you do really need it, at least, the language won't let you down. ## The date example? Your error, it seems to me, is that you are mixing operators: ``` 1974/01/06AD ^ ^ ^ ``` This can't be avoided, because / being an operator, the compiler must interpret it. And, AFAIK, it is a good thing. To find a solution for your problem, I would write the literal in some other way. For example: ``` "1974-01-06"_AD ; // ISO-like notation "06/01/1974"_AD ; // french-date-like notation "jan 06 1974"_AD ; // US-date-like notation 19740106_AD ; // integer-date-like notation ``` Personally, I would choose the integer and the ISO dates, but it depends on YOUR needs. Which is the whole point of letting the user define its own literal names.
What new capabilities do user-defined literals add to C++?
[ "", "c++", "c++11", "user-defined-literals", "" ]
I've got a console application that compiles and executes fine with Visual C++ 6.0, except that it will then only get as far as telling me about missing command line parameters. There doesn't seem to be anywhere obvious to enter these. How do I run or debug it with command line parameters?
I assume you're talking about setting the command line parameters for running in the IDE. Open the Project/Settings property page and go to the Debug tab. There's a "Program arguments" field you can put them into.
If I remember correctly, under Project/Settings/Debug tab there is a place to enter the command line parameters. It's the "Program arguments" field.
How to run a console application with command line parameters in Visual C++ 6.0?
[ "", "c++", "command-line", "parameters", "visual-c++-6", "" ]
Let's say you have a text file like this one: <http://www.gutenberg.org/files/17921/17921-8.txt> Does anyone has a good algorithm, or open-source code, to extract words from a text file? How to get all the words, while avoiding special characters, and keeping things like "it's", etc... I'm working in Java. Thanks
This sounds like the right job for regular expressions. Here is some Java code to give you an idea, in case you don't know how to start: ``` String input = "Input text, with words, punctuation, etc. Well, it's rather short."; Pattern p = Pattern.compile("[\\w']+"); Matcher m = p.matcher(input); while ( m.find() ) { System.out.println(input.substring(m.start(), m.end())); } ``` The pattern `[\w']+` matches all word characters, and the apostrophe, multiple times. The example string would be printed word-by-word. Have a look at the [Java Pattern class documentation](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html) to read more.
Here's a good approach to your problem: This function receives your text as an input and returns an array of all the words inside the given text ``` private ArrayList<String> get_Words(String SInput){ StringBuilder stringBuffer = new StringBuilder(SInput); ArrayList<String> all_Words_List = new ArrayList<String>(); String SWord = ""; for(int i=0; i<stringBuffer.length(); i++){ Character charAt = stringBuffer.charAt(i); if(Character.isAlphabetic(charAt) || Character.isDigit(charAt)){ SWord = SWord + charAt; } else{ if(!SWord.isEmpty()) all_Words_List.add(new String(SWord)); SWord = ""; } } return all_Words_List; } ```
Extract words out of a text file
[ "", "java", "text", "" ]
I've noticed, using visual studio 2003, that I can "comment out" my comments to make them no longer be comments. This one needs an example: If I have: ``` /* int commented_out = 0; */ ``` I can comment out the /\* and \*/ with // and code within the /\* and \*/ is no longer "commented out" (the text changes to non-comment color **and** the compiler treats it as code once again). Like so: ``` ///* int commented_out = 0; //*/ ``` I've found this is true for msvc 2003, is this normal C++ behavior or is it just a fluke that works with this compiler?
Yep, this is perfectly normal behavior. The C++ standard says that a `/*` is the start of a comment block only if it itself is not commented out. I often use what you've written above to comment or uncomment a block of code by adding/deleting one character. A nice little trick for switching between two blocks of code, one of which is always commented out is: ``` //* code block 1 (uncommented) /*/ code block 2 (commented) //*/ ``` Now, delete one slash from the start, and it becomes ``` /* code block 1 (commented) /*/ code block 2 (uncommented) //*/ ``` Not something to use in production code, but very useful for quick debugging changes.
It should work in any compiler as the `//` is encountered first in the input stream. I tend to use `#if 0` for this sort of stuff and change it to `#if 1` to uncomment, shown here: ``` #if 0 int commented_out = 0; #endif ``` Then I don't have to worry about comment markers at all.
Commenting out comments
[ "", "c++", "comments", "" ]
I'm looking for a .NET library that will allow creation of a Word document. I need to export HTML based content to a Word doc (97-2003 format, not docx). I know that there are the Microsoft Office Automation libraries and Office interop, but as far as I can tell, they require that you have office actually installed and they do the conversion by opening word itself. But I don't want to have the requirement of having office installed for the conversion to work. Edit: Converting to RTF may even work, if possible.
*Would it work if I somehow converted the CSS to be embedded in the HTML??* Yes. I use an internal style sheet, as I mentioned. Document Example: ``` <html> <head> <STYLE type="text/css"> h1 {text-align:center; font-size:12.0pt; font-family:Arial; font-weight:bold;} p {margin:0in; margin-bottom:0pt; font-size: 10.0pt;font-family: Arial;} p.Address {text-align:center;font-family:Times; margin-bottom: 10px;} </style></head> <body> <p class="Address">The Street</p> <h1>Head</h1> ```
I use Aspose for working with Word, makes everything a breeze: <http://www.aspose.com/>
Export to Word Document in C#
[ "", "c#", "ms-word", "export", "" ]
I am binding the dropdown with db entity. ``` ddlCustomer.DataSource = Customer.GetAll(); ddlCustomer.DataTextField = "CustomerName"; ddlCustomer.DataBind(); ``` I want to add "SELECT" as the first itemlist in dropdown and bind then entity to the dropdown. How can i do this?
Add: ``` ddlCustomer.Items.Insert(0, "SELECT"); ``` After ddlCustomer.DataBind(); The item must be inserted after the data bind because the data bind clears the items.
I know there is an answer already, but you can also do this: ``` <asp:DropDownList AppendDataBoundItems="true" ID="ddlCustomer" runat="server"> <asp:ListItem Value="0" Text="Select"/> </asp:DropDownList> ``` That way, you won't have to worry about when you call Databind and when you add the select-item.
Databinding DropDown Control in .Net
[ "", "c#", ".net", "winforms", "data-binding", ".net-2.0", "" ]
Imagine I have a property defined in global.asax. ``` public List<string> Roles { get { ... } set { ... } } ``` I want to use the value in another page. how to I refer to it?
You can access the class like this: ``` ((Global)this.Context.ApplicationInstance).Roles ```
It looks to me like that only depends on the session - so why not make it a pair of static methods which take the session as a parameter? Then you can pass in the value of the "Session" property from the page. (Anything which *does* have access to the HttpApplication can just reference its Session property, of course.)
How do I access properties from global.asax in some other page's code behind
[ "", "c#", "asp.net", "global-asax", "" ]
I am using Borland Turbo C++ with some inlined assembler code, so presumably Turbo Assembler (TASM) style assembly code. I wish to do the following: ``` void foo::bar( void ) { __asm { mov eax, SomeLabel // ... } // ... SomeLabel: // ... } ``` So the address of SomeLabel is placed into EAX. This doesn't work and the compiler complains of: Undefined symbol 'SomeLabel'. In Microsoft Assembler (MASM) the dollar symbol ($) serves as the current location counter, which would be useful for my purpose. But again this does not seem to work in Borlands Assember (expression syntax error). Update: To be a little more specific, I need the compiler to generate the address it moves into eax as a constant during compilation/linking and not at run time, so it will compile like "mov eax, 0x00401234". Can anybody suggest how to get this working? UPDATE: To respond to Pax's question (see comment), If the base address is changed at run time by the Windows loader the DLL/EXE PE image will still be relocated by the Windows loader and the labels address will be patched at run time by the loader to use the re-based address so using a compile/link time value for the label address is not an issue. Many thanks in advance.
Last time I tried to make some assembly code Borland-compatible I came across the limitation that you can't forward-reference labels. Not sure if that's what you're running into here.
Everything I can find about Borland suggests this ought to work. Similar questions on other sites ([here](http://www.experts-exchange.com/Programming/Languages/Assembly/Q_21731289.html) and [here](http://www.tek-tips.com/viewthread.cfm?qid=972872&page=10)) suggest that Borland can handle forward-references for labels, but insists on labels being outside asm blocks. However, as your label was already outside the asm block... I am curious whether your compiler would allow you to use this label within, for instance, a jmp instruction. When toying around with it (admittedly, on a completely different compiler), I found a pesky tendency for the compiler to complain about operand types. The syntax is quite different, and it's my first attempt at inline asm in a long time, but I believe I've munged this enough to work under gcc. Perhaps, despite the differences, this might be of some use to you: ``` #include <stdio.h> int main() { void *too = &&SomeLabel; unsigned int out; asm ( "movl %0, %%eax;" :"=a"(out) :"r"(&&SomeLabel) ); SomeLabel: printf("Result: %p %x\n", too, out); return 0; } ``` This generates: ``` ... movl $.L2, %eax ... .L2: ``` The && operator is a non-standard extension, I wouldn't expect it to work anywhere other than gcc. Hopefully this may have stirred up some new ideas... Good luck! Edit: Though it's listed as Microsoft specific, [here](http://msdn.microsoft.com/en-us/library/78cxesy1.aspx) is another instance of jumping to labels.
Borland x86 inlined assembler; get a label's address?
[ "", "c++", "assembly", "x86", "turbo-c++", "" ]
The [var](http://msdn.microsoft.com/en-us/library/bb384061.aspx) keyword does away with the need for an explicit type declaration and I have read with interest the [SO discussion](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c) of when it might be appropriate. I have also read about (but not used) [Boo](https://github.com/boo-lang/boo) which seems to take things a step further by making it [optional to declare a local variable](https://github.com/boo-lang/boo/wiki/Type-Inference). With Boo, both the type and the declaration can be implied. Which leads me to wonder, why did the C# language designers bother to include a var keyword at all? **Update**: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword... ``` var anon = new { Name = "Terry", Age = 34 }; ``` versus ``` anon = new { Name = "Terry", Age = 34 }; ```
**Update:** There are two related questions here, actually: 1. Why do I have to declare variables at all? 2. What use is "var" in a language that makes you declare variables? The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below: As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider: ``` SomeGeneric<VeryLongTypename<NestedTypename>> thing = new SomeGeneric<VeryLongTypename<NestedTypename>>(); ``` Verbose and error-prone, right? So now they let you do this: ``` var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>(); ``` By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.
Without the var keyword it becomes possible to accidentally create a new variable when you had actually intended to use an already existing variable. e.g. ``` name = "fred"; ... Name = "barney"; // whoops! we meant to reuse name ```
What's the point of the var keyword?
[ "", "c#", "variables", "boo", "" ]
I am working on implementing Zend Framework within an existing project that has a public marketing area, a private members area, an administration site, and a marketing campaign management site. Currently these are poorly organized with the controller scripts for the marketing area and the members area all being under the root of the site and then a separate folder for admin and another folder for the marketing campaign site. In implementing the Zend Framework, I would like to create be able to split the controllers and views into modules (one for the members area, one for the public marketing area, one for the admin site, and one for the marketing campaign admin site) but I need to be able to point each module to the same model's since all three components work on the same database and on the same business objects. However, I haven't been able to find any information on how to do this in the documentation. Can anyone help with either a link on how to do this or some simple instructions on how to accomplish it?
What I do is keep common classes in a "library" directory outside of the modules hierarchy. Then set my `INCLUDE_PATH` to use the "models" directory of the respective module, plus the common "library" directory. ``` docroot/ index.php application/ library/ <-- common classes go here default/ controllers/ models/ views/ members/ controllers/ models/ views/ admin/ controllers/ models/ views/ . . . ``` In my bootstrap script, I'd add "`application/library/`" to the `INCLUDE_PATH`. Then in each controller's `init()` function, I'd add that module's "`models/`" directory to the `INCLUDE_PATH`. **edit:** Functions like `setControllerDirectory()` and `setModuleDirectory()` don't add the respective models directories to the `INCLUDE_PATH`. You have to do this yourself in any case. Here's one example of how to do it: ``` $app = APPLICATION_HOME; // you should define this in your bootstrap $d = DIRECTORY_SEPARATOR; $module = $this->_request->getModuleName(); // available after routing set_include_path( join(PATH_SEPARATOR, array( "$app{$d}library", "$app{$d}$module{$d}models", get_include_path() ) ) ); ``` You could add the "`library`" to your path in the bootstrap, but you can't add the "`models`" directory for the correct module in the bootstrap, because the module depends on routing. Some people do this in the `init()` method of their controllers, and some people write a plugin for the ActionController's preDispatch hook to set the `INCLUDE_PATH`.
This can also be accomplished through a naming convention to follow `Zend_Loader`. Keep your model files in the models folder under their module folder. Name them as `Module_Models_ModelName` and save them in a file name ModelName.php in the models folder for that module. Make sure the application folder is in your include path and assuming you are using `Zend_Loader` for auto loading, you can then just reference the models by their class name. This has the advantage of keeping your model code grouped in with the actual module it is for. This keeps the module contained within a single folder structure which helps encourage encapsulation. This will also help in the future if you need to port the module to another project.
How to Use Same Models in Different Modules in Zend Framework?
[ "", "php", "model-view-controller", "zend-framework", "module", "" ]
If I've got an array of values that are basically zero-padded string representations of various numbers and another array of integers, will `array_intersect()` still match elements of different types? For example, would this work: ``` $arrayOne = array('0003', '0004', '0005'); $arrayTwo = array(4, 5, 6); $intersect = array_intersect($arrayOne, $arrayTwo); // $intersect would then be = "array(4, 5)" ``` And if not, what would be the most efficient way to accomplish this? Just loop through and compare, or loop through and convert everything to integers and run `array_intersect()` after?
$ cat > test.php ``` <?php $arrayOne = array('0003', '0004', '0005'); $arrayTwo = array(4, 5, 6); $intersect = array_intersect($arrayOne, $arrayTwo); print_r($intersect ); ?> ``` $ php test.php Array ( ) $ So no, it will not. But if you add ``` foreach($arrayOne as $key => $value) { $arrayOne[$key] = intval($value); } ``` you will get $ php test.php Array ( [1] => 4 [2] => 5 )
From <https://www.php.net/manual/en/function.array-intersect.php>: > ``` > Note: Two elements are considered equal if and only if > (string) $elem1 === (string) $elem2. > In words: when the string representation is the same. > ``` In your example, $intersect will be an empty array because 5 !== "005" and 4 !== "004"
Filtering array with array_intersect() - values are equal as integers, but not as strings
[ "", "php", "arrays", "casting", "types", "array-intersect", "" ]
I'm trying to find a way to get the open tasks in C#. I've been searching on google and can only find how to get a list of the **processes**. I want the only the tasks that would show up on the taskbar. Also, along with that, it would be cool if I could get the process the task is associated with. And if possible get the thumbnail images that Vista uses for the ALT-TAB menu, like in this image: [![alt-tab](https://i.stack.imgur.com/CcPQP.png)](https://i.stack.imgur.com/CcPQP.png) I assume that I will have to use pinvokes because it really doesn't look like there are any libraries to do this already. Any ideas?
This article should pretty much tell you exactly what to do, it shows how to build your own task switch and includes the code needed to enumerate all windows and determine if they are "tasks" and it shows you how to use PrintWindow api to get the previews on XP. <http://msdn.microsoft.com/en-us/library/ms997649.aspx> Also, here is [a blog post](http://blogs.msdn.com/oldnewthing/archive/2007/10/08/5351207.aspx) that talks about the algorithm used to determine what shows up in the Alt+Tab view. Basically you need to check the WS\_EX\_APPWINDOW and WS\_EX\_TOOLWINDOW along with if the window has an owner.
From an API (Win32) perspective there is no such thing as Tasks (at least not the one that Windows Task Manager/Alt-Tab shows). Those "Tasks" are actually top level windows. So in order to get a list of those, you need to [enumerate the windows](http://msdn.microsoft.com/en-us/library/ms682615(VS.85).aspx) (here is the [PInvoke](http://www.pinvoke.net/default.aspx/user32/EnumDesktopWindows.html) for it). Then look at the style of the windows to determine if they are actually top level windows.
C# - Get list of open tasks
[ "", "c#", ".net", "taskbar", "task", "" ]
I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words: ``` >>> my_ar = numpy.array((0,5,10)) [0, 5, 10] >>> transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful array([ [ 0, 0, 0], [ 5, 10, 15], [10, 20, 30]]) >>> transformed.shape (3, 3) ``` I've tried: ``` def my_fun_e(val): return numpy.array((val, val*2, val*3)) my_fun = numpy.frompyfunc(my_fun_e, 1, 3) ``` but get: ``` my_fun(my_ar) (array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object), array([None, None, None], dtype=object), array([None, None, None], dtype=object)) ``` and I've tried: ``` my_fun = numpy.frompyfunc(my_fun_e, 1, 1) ``` but get: ``` >>> my_fun(my_ar) array([[0 0 0], [ 5 10 15], [10 20 30]], dtype=object) ``` This is close, but not quite right -- I get an array of objects, not an array of ints. **Update 3!** OK. I've realized that my example was too simple beforehand -- I don't just want to replicate my data in a third dimension, I'd like to transform it at the same time. Maybe this is clearer?
Use map to apply your transformation function to each element in my\_ar: ``` import numpy my_ar = numpy.array((0,5,10)) print my_ar transformed = numpy.array(map(lambda x:numpy.array((x,x*2,x*3)), my_ar)) print transformed print transformed.shape ```
Does numpy.dstack do what you want? The first two indexes are the same as the original array, and the new third index is "depth". ``` >>> import numpy as N >>> a = N.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = N.dstack((a,a,a)) >>> b array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]], [[7, 7, 7], [8, 8, 8], [9, 9, 9]]]) >>> b[1,1] array([5, 5, 5]) ```
Adding a dimension to every element of a numpy.array
[ "", "python", "arrays", "numpy", "" ]
Is it necessary for setter methods to have one argument? Usually setter methods accept one argument as the value of a certain property of an Object. What if I want to test first the validity which depends on another argument which is a boolean, if true, validate first, else just set the value. I am getting the values from clients through ftp server. Sometimes those files contain garbage values. For instance, a phone number like #3432838#9. So before I set the value I need to remove those garbage characters. Can I do it in the setter methods? Is it a valid approach? Thanks a bunch in advance! **EDIT:** Is this valid: ``` public void setSomething(String strValue){ if(checkValidity(strValue)){ // set the value } else { // set the value to an empty string } } ```
It is necessary specifically in the java bean framework model, but it s not mandatory in general. You can have setter with no argument when they are meant to "swith" a value. ``` void setCheck() ``` could for instance be meant to set the "check" boolean attribute to true. So even if it is not a "setter" in the java bean sense of the term, you can imagine setter used for other purposes. Plus, according to section 7 of JavaBean specifications, a setter can have **more than one argument**, for instance for Indexed properties (An indexed property supports a range of values. Whenever the property is read or written you just specify an index to identify which value you want.) ``` void setter(int index, PropertyType value); // indexed setter void setter(PropertyType values[]); // array setter ``` --- In your case, a valid approach would be to **add a [runtime exception](https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions#73355)** to the signature of our function. That way you do not put any unnecessary compilation-time exception checking for all of the other classes which are already calling your setter. Or you could consider your property as a **Constrained property** and add a non-runtime exception. Constrained property setter methods are required to support the PropertyVetoException. This documents to the users of the constrained property that attempted updates may be vetoed. So a simple constrained property might look like: ``` PropertyType getFoo(); void setFoo(PropertyType value) throws PropertyVetoException; ``` which allows for VetoableChangeListener to be added if needed. --- Regarding your snippet, it is "valid" but may not be optimal because (as said in [this question](https://stackoverflow.com/questions/2750/data-verifications-in-gettersetter-or-elsewhere#2754)): * **Validation should be captured separately from getters or setters** in a validation method. That way if the validation needs to be reused across multiple components, it is available. * It is better to **fail fast** (hence my proposition to add exception to the setter).
By Java Bean specification setter have one argument. If you add another one, for whatever reason, it is not considered setter anymore. Setter is perfectly valid to "clean up" its argument, or throw exception if is invalid.
Is it necessary for setter methods to have one argument?
[ "", "java", "setter", "" ]
When reading a stack trace like: ``` [FormatException: Input string was not in a correct format.] System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +2755599 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +112 System.Convert.ToInt32(String value) +68 ``` What do the +68, +112, etc. numbers mean. I'm guessing that they're offsets to something. If so, what?
It means: > it’s an offset into the native instructions for the method. Read [this](http://odetocode.com/blogs/scott/archive/2005/01/24/funny-numbers-in-my-stack-trace.aspx) for more details.
I believe they're offsets into the code of the method - whether IL or JIT-compiled-assembly bytes, I'm not sure... (Basically they're taking the place of line numbers, which of course aren't available without the pdbs.)
What do the "+n" values mean at the end of a method name in a stack trace?
[ "", "c#", ".net", "" ]
I am trying to write a decorator to do logging: ``` def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() ``` I would like this to print: ``` Entering C.f ``` but instead I get this error message: ``` AttributeError: 'function' object has no attribute 'im_class' ``` Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.
Claudiu's answer is correct, but you can also cheat by getting the class name off of the `self` argument. This will give misleading log statements in cases of inheritance, but will tell you the class of the object whose method is being called. For example: ``` from functools import wraps # use this to preserve function signatures and docstrings def logger(func): @wraps(func) def with_logging(*args, **kwargs): print "Entering %s.%s" % (args[0].__class__.__name__, func.__name__) return func(*args, **kwargs) return with_logging class C(object): @logger def f(self): pass C().f() ``` As I said, this won't work properly in cases where you've inherited a function from a parent class; in this case you might say ``` class B(C): pass b = B() b.f() ``` and get the message `Entering B.f` where you actually want to get the message `Entering C.f` since that's the correct class. On the other hand, this might be acceptable, in which case I'd recommend this approach over Claudiu's suggestion.
Functions only become methods at runtime. That is, when you get `C.f` you get a bound function (and `C.f.im_class is C`). At the time your function is defined it is just a plain function, it is not bound to any class. This unbound and disassociated function is what is decorated by logger. `self.__class__.__name__` will give you the name of the class, but you can also use descriptors to accomplish this in a somewhat more general way. This pattern is described [in a blog post on Decorators and Descriptors](http://blog.ianbicking.org/2008/10/24/decorators-and-descriptors/), and an implementation of your logger decorator in particular would look like: ``` class logger(object): def __init__(self, func): self.func = func def __get__(self, obj, type=None): return self.__class__(self.func.__get__(obj, type)) def __call__(self, *args, **kw): print 'Entering %s' % self.func return self.func(*args, **kw) class C(object): @logger def f(self, x, y): return x+y C().f(1, 2) # => Entering <bound method C.f of <__main__.C object at 0x...>> ``` Obviously the output can be improved (by using, for example, `getattr(self.func, 'im_class', None)`), but this general pattern will work for both methods and functions. However it will *not* work for old-style classes (but just don't use those ;)
Python decorator makes function forget that it belongs to a class
[ "", "python", "reflection", "metaprogramming", "" ]
I have a site made with php which uses server side sessions throughout the site. In fact, it's a site with a user login which depends on session variables and if there were a problem with *all* session variables, no pages would load at all. On the site, there's an iframe that holds a feed of little messages from other users. Those little messages have clickable photos next to them that open the user's profile. Now, each page requires some formatting to open the user's profile on that specific page...there's really only a few *problem* pages, but those pages have to have the onclick functions formatted a little differently or they break the page. So I set a session variable on each page (`$_SESSION["current_page"]`) that lets the feed know how to format the clickable photos. Now Firefox, Opera, Chrome, Safari all work as they are supposed to. But IE6 and IE7 are having problems on the pages that require special formatting. So after pulling my hair out a bit, I eventually got around to printing my session variables form the server. And lo and behold, on the special pages, (`$_SESSION["current_page"]`) is always set to "main" instead of "special1" or "special2". I printed the same session variable in Firefox and all the other browsers I mentioned and they print out "special1" or "special2" as they're supposed to. Can anyone think of something - possibly related to the fact that the feed is in an iframe??? - that would cause IE to treat server side session variables differently or somehow launch page "main" silently in the background? I have checked the feed very carefully for any reference to page "main" - it doesn't seem like there's any ways it's loading that page. this doesn't make sense to me.
I thought some people might find the solution to this problem interesting. Fiddler certainly helped here. Thanks to Fiddler, I could see that I was, in fact, hitting the page main.php (thus setting the session variable moments after setting it on the target page), but the server was defaulting there after getting a 302 on the root of the site. This was all happening silently in the background, and *before* my onload="" javascript ran. So I was sure something *on* those pages was causing an error, but not a catastrophic one. here it is: `<img src= "" >` IE was freaking out about the blank src attribute and hitting the server root and the defaulting to page main. I don't fully understand the mechanics happening here. I also don't understand if this is how IE is supposed to behave (it is a malformed img tag after all) or not. Is this a bug?
Check the name of the server machine. IE has problems with machine names that contain '-' or '\_' - they cannot maintain a session! I've had this problem twice in the past, and it always takes me weeks to figure out, and I'm shocked IE hasn't fixed it. Just rename the machine to have no strange characters! You can get it working if you just use the IP address of the server in the url to test.
PHP session doesn't work with IE
[ "", "php", "internet-explorer", "session", "" ]
There is two available Eclipse plugins for Maven : * [Eclipse IAM](http://www.eclipse.org/proposals/iam/) (old name is Q4E) * [m2eclipse](http://m2eclipse.codehaus.org/) m2eclipse seems to be the oldest but the more robust. Is there any key differences between the two ? Which one should be chosen for a project starting today and why ? **UPDATE:** m2eclipse is moving to eclipse.org and will be included in the Indigo release train (Eclipse 3.7). See [m2e at Eclipse: What will this mean for you?](http://www.sonatype.com/people/2010/12/m2e-at-eclipse-what-will-this-mean-for-you/) and [m2eclipse is moving to eclipse.org!](http://www.eclipse.org/m2e/). The accepted answer is thus even more correct.
I choose **m2eclipse** since it is stable and have all that I need. Especially ability to resolve dependencies inside workspace. I tried the other one some time ago and didn't like it. It was to buggy so I gave up quickly.
The side by side comparison is moved to <http://web.archive.org/web/20150526230611/http://docs.codehaus.org/display/MAVENUSER/Eclipse+Integration>
Which is the best Maven Eclipse plugin?
[ "", "java", "eclipse", "maven-2", "eclipse-plugin", "" ]
How do I write the getDB() function and use it properly? Here is a code snippet of my App Object: ``` public class MyApp extends UiApplication { private static PersistentObject m_oStore; private static MyBigObjectOfStorage m_oDB; static { store = PersistentStore.getPersistentObject(0xa1a569278238dad2L); } public static void main(String[] args) { MyApp theApp = new MyApp(); theApp.enterEventDispatcher(); } public MyApp() { pushScreen(new MyMainScreen()); } // Is this correct? Will it return a copy of m_oDB or a reference of m_oDB? public MyBigObjectOfStorage getDB() { return m_oDB; // returns a reference } } ```
``` public MyBigObjectOfStorage getDB() { return m_oDB; } ``` As you put it is correct. It will return a *copy of the reference*, which is kind of in between a copy and a reference. The actual object instance returned by getDB() is the same object referenced by m\_oDB. However, you can't change the reference returned by getDB() to point at a different object and have it actually cause the local private m\_oDB to point at the new object. m\_oDB will still point at the object it was already. See <http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html> for more detail. Although looking through your code there, you never set m\_oDB at all, so getDB() will always return null.
I am one of those folks that are very much against using singletons and/or statics as it tends to make unit testing impossible. As this is posted under best practices, I suggest that you take a look at using a dependency injection framework. Personally I am using and prefer [Google Guice](http://code.google.com/p/google-guice/).
Java Application/Class Design - How do accessors in Java work?
[ "", "java", "" ]
I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using `#!/usr/bin/env groovy` at the top of my script.
If you really have to you can also load a JAR at runtime with: ``` this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL()) ```
Starting a groovy script with `#!/usr/bin/env groovy` has a very important limitation - **No additional arguments can be added.** No classpath can be configured, no running groovy with defines or in debug. This is not a [groovy](http://jira.codehaus.org/browse/GMOD-226 "groovy issue") issue, but a limitation in how the shebang (`#!`) works - all additional arguments are treated as single argument so `#!/usr/bin/env groovy -d` is telling `/usr/bin/env` to run the command `groovy -d` rathen then `groovy` with an argument of `d`. There is a workaround for the issue, which involves bootstrapping groovy with bash **in the groovy script.** ``` #!/bin/bash //usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $@; exit $? import org.springframework.class.from.jar //other groovy code println 'Hello' ``` All the magic happens in the first two lines. The first line tells us that this is a `bash` script. `bash` starts running and sees the first line. In `bash` `#` is for comments and `//` is collapsed to `/` which is the root directory. So `bash` will run `/usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $@` which starts groovy with all our desired arguments. The `"$0"` is the path to our script, and `$@` are the arguments. Now groovy runs and it ignores the first two lines and sees our groovy script and then exits back to `bash`. `bash` then exits (`exit $?1`) with status code from groovy.
How do I include jars in a groovy script?
[ "", "java", "groovy", "jar", "classpath", "" ]
I am having trouble deleting orphan nodes using JPA with the following mapping ``` @OneToMany (cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "owner") private List<Bikes> bikes; ``` I am having the issue of the orphaned roles hanging around the database. I can use the annotation `org.hibernate.annotations.Cascade` Hibernate specific tag but obviously I don't want to tie my solution into a Hibernate implementation. **EDIT**: It seems JPA 2.0 will include support for this.
If you are using it with Hibernate, you'll have to explicitly define the annotation `CascadeType.DELETE_ORPHAN`, which can be used in conjunction with JPA `CascadeType.ALL`. If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records. execution sequence 1. fetch main row to be deleted 2. fetch child elements 3. delete all child elements 4. delete main row 5. close session With JPA 2.0, you can now use the option **orphanRemoval = true** ``` @OneToMany(mappedBy="foo", orphanRemoval=true) ```
If you are using JPA 2.0, you can now use the `orphanRemoval=true` attribute of the `@xxxToMany` annotation to remove orphans. Actually, `CascadeType.DELETE_ORPHAN` has been deprecated in 3.5.2-Final.
JPA CascadeType.ALL does not delete orphans
[ "", "java", "hibernate", "orm", "jpa", "jpa-2.0", "" ]
More detail to my question: HTML and JavaScript are called "client-side code". C# and VB in the code behind files are termed "server-side code". So what is inline-asp, and 'runat=server' code blocks called? ``` <!-- This is called "client-side" --> <p>Hello World</p> <script>alert("Hello World");</script> ``` ... ``` // This is called "server-side" public void Page_Load(object sender, EventArgs e) { Response.Write("Hello World"); } ``` ... ``` <%-- What is this called ??? --%> <asp:Label ID="MyLabel" runat="server" /> <% Response.Write("Hello World"); %> ``` The best term I can come up with is "Web Forms Code".
To be explicit, Microsoft calls them Embedded Code Blocks. <http://msdn.microsoft.com/en-us/library/ms178135.aspx> They are code blocks embeded into the page lifecycle by being called during the Render phase.
The sections of an ASP page that start with *`<%`* and end with *`%>`* are [**code render blocks**](https://msdn.microsoft.com/en-us/library/k6xeyd4z(v=vs.90).aspx "MSDN: Code Render Blocks") and `<script>` elements with `runat=server` are called [**code declaration blocks**](http://msdn.microsoft.com/en-us/library/2cy7sxha(v=vs.90).aspx "MSDN: Code Declaration Blocks"). The code inside them is *server code*. The parts that begin with *`<%@`* are **directives**. The code render blocks that begin with *`<%=`* is just short hand for a call to `writer.Write()` in the `Page.Render()` method.
In ASP.NET, What is the 'ASP' code called?
[ "", "c#", "asp.net", "terminology", "" ]
From googling around it looks like Xcode (3.1 in my case) should be at least trying to give me a sane debug view of STL containers - or at least vectors. However, whenever I go to look at a vector in the debugger I just see M\_impl, with M\_start and M\_finish members (and a couple of others) - but nothing in-between! (it's a debug build, btw). Am I missing a setting or something somewhere? I've also read that there are macros available that can augment the debug viewer even further to inspect more complex containers - but have been unable to find any. I'd also like to be able to view std::wstrings, without having to drop to the memory viewer. It shows std::string fine. Is there anything I can do to show std::wstring? I realise this is a bit of a composite question - but it's all really part of the same subject.
The ability to view the container's items may rely on the complexity of the templated type. For trivial objects like int, bool, etc., and even simple class templates like ``` template <class T> struct S { T m_t; } ``` I *normally* have no problem viewing vector items in the debugger variable view. I say normally because there seem to be occasional bugs that cause stuff--particularly when debugging--not to behave the way I expected. One of those things is garbage or totally useless information in the variable view. Usually a clean rebuild of the target (or sometimes even a more drastic restarting of XCode followed by a clean rebuild) fixes the problem. As for the other container types, it's most likely hard to efficiently view this information. For example a map is often implemented as a red-black tree. The debugger would have to know that in advance in order to properly walk the tree and show you all the keys and values. That's probably asking a lot from Xcode or GDB--especially since the former focuses more on Objective-C and plain C than C++ (hence the fact that namespaces tend to kill code completion despite their ubiquity and importance).
You can create [Data formatters](https://web.archive.org/web/20090812202145/http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeDebugging/600-Viewing_Variables_and_Memory/variables_and_memory.html) for different variable types so they show up nicer :-).
Inspecting STL containers in Xcode
[ "", "c++", "xcode", "debugging", "macos", "stl", "" ]
I'm looking for a good Java obfuscator. I've done initial research into the following Java obfuscators: proguard, yguard, retroguard, dasho, allatori, jshrink, smokescreen, jobfuscate, marvin, jbco, jode, javaguard, jarg, joga, cafebabe, donquixote, mwobfu, bbmug, zelix klassmaster, sandmark, jcloak, thicket, blufuscator, and java code protector. I tried proguard and it has a really nice GUI, seems really stable, and seems to be the most popular, but it seemed to not like some enumeration on a referenced jar file (not within the code I was trying to obfuscate) which was weird. Yguard seems to require some interaction with ant, which I didn't know too much about. What is a good java obfuscator? It doesn't need to be free, it just needs to work well and be easy to use.
I use [ProGuard](http://proguard.sourceforge.net) heavily for all my release builds and I have found it is excellent. I can't recommend it enough! I *have* encountered obscure bugs caused by it's optimizations on several occasions and I now disable optimizations across the board - haven't had a problem caused by ProGuard since. Though, to be fair, these were all quite some versions ago - YMMV. I used to use the GUI *only* to get a config started, and then I resort to editing the text config myself, which is really very simple to do. These days I do the config by hand. I have quite complex projects all of which involve dynamic loading and reflection. I also heavily use reflection for a callback implementation. ProGuard has coped with these very well. EDIT: We also use DashO Pro for one of our products - I looked into it for packaging the products I am responsible for and concluded that it's configuration was too convoluted and complex; also integrating it into the build script seemed like a bit of a pain. But again, to be fair, this was circa 2001... so it might be better in current versions.
A good collection of links to free and commercial tools is given in this arcticle ["Protect Your Java Code - Through Obfuscators And Beyond"](http://www.excelsior-usa.com/articles/java-obfuscators.html) The author also discusses the strong and weak points of bytecode obfuscation
Java obfuscators
[ "", "java", "obfuscation", "" ]
I am using Delphi 7 and ICS components to communicate with php script and insert some data in mysql database... How to post unicode data using http post ? After using utf8encode from tnt controls I am doing it to post to PHP script ``` <?php echo "Note = ". $_POST['note']; if($_POST['action'] == 'i') { /* * This code will add new notes to the database */ $sql = "INSERT INTO app_notes VALUES ('', '" . mysql_real_escape_string($_POST['username']) . "', '" . mysql_real_escape_string($_POST['note']) . "', NOW(), '')"; $result = mysql_query($sql, $link) or die('0 - Ins'); echo '1 - ' . mysql_insert_id($link); ?> ``` Delphi code : ``` data := Format('date=%s&username=%s&password=%s&hash=%s&note=%s&action=%s', [UrlEncode(FormatDateTime('yyyymmddhh:nn',now)), UrlEncode(edtUserName.Text), UrlEncode(getMd51(edtPassword.Text)), UrlEncode(getMd51(dataHash)),UrlEncode(Utf8Encode(memoNote.Text)),'i' ]); // try function StrHtmlEncode (const AStr: String): String; from IdStrings HttpCli1.SendStream := TMemoryStream.Create; HttpCli1.SendStream.Write(Data[1], Length(Data)); HttpCli1.SendStream.Seek(0, 0); HttpCli1.RcvdStream := TMemoryStream.Create; HttpCli1.URL := Trim(ActionURLEdit.Text); HttpCli1.PostAsync; ``` But when I post that unicode value is totally different then original one that I see in Tnt Memo Is there something I am missing ?! Also anybody knows how to do this with Indy? Thanks.
Your example code shows your data coming from a TNT Unicode control. That value will have type `WideString`, so to get UTF-8 data, you should call `Utf8Encode`, which will return an `AnsiString` value. Then call `UrlEncode` on that value. Make sure `UrlEncode`'s input type is `AnsiString`. So, something like this: ``` var data, date, username, passhash, datahash, note: AnsiString; date := FormatDateTime('yyyymmddhh:nn',now); username := Utf8Encode(edtUserName.Text); passhash := getMd51(edtPassword.Text); datahash := getMd51(data); note := Utf8Encode(memoNote.Text); data := Format('date=%s&username=%s&password=%s&hash=%s&note=%s&action=%s', [UrlEncode(date), UrlEncode(username), UrlEncode(passhash), UrlEncode(datahash), UrlEncode(note), 'i' ]); ``` There should be no need to UTF-8-encode the MD5 values since MD5 string values are just hexadecimal characters. However, you should double-check that your `getMd51` function accepts `WideString`. Otherwise, you may be losing data before you ever send it anywhere. Next, you have the issue of receiving UTF-8 data in PHP. I expect there's nothing special you need to do there or in MySQL. Whatever you store, you should get back identically later. Send that back to your Delphi program, and decode the UTF-8 data back into a `WideString`. In other words, your Unicode data *will* look different in your database because you're storing it as UTF-8. In your database, you're seeing UTF-8-encoded data, but in your TNT controls, you're seeing the regular Unicode characters. So, for instance, if you type the character "ش" into your edit box, that's Unicode character U+0634, Arabic letter sheen. As UTF-8, that's the two-byte sequence 0xD8 0xB4. If you store those bytes in your database, and then view the raw contents of the field, you may see characters interpreted as though those bytes are in some ANSI encoding. One possible interpretation of those bytes is as the two-character sequence "Ø´", which is the Latin capital letter o with stroke followed by an acute accent. When you load that string back out of your database, it's still encoded as UTF-8, just as it was when you stored it, so you will need to decode it. As far as I can tell, neither PHP nor MySQL does any massaging of your data, so whatever UTF-8 character you give them will be returned to you as-is. If you are using the data in Delphi, then call `Utf8Decode`, which is the complement to the `Utf8Encode` function that you called previously. If you are using the data in PHP, then you might be interested in PHP's `utf8_decode` function, although that converts to ISO-8859-1, which doesn't include our example Arabic character. Stack Overflow already has a few questions related to using UTF-8 in PHP, so I won't attempt to add to them here. For example: * [Best practices in PHP and MySQL with international strings](https://stackoverflow.com/questions/140728/best-practices-in-php-and-mysql-with-international-strings) * [UTF-8 all the way through…](https://stackoverflow.com/questions/279170/utf-8-all-the-way-through)
Encode the UTF-8 data in application/x-www-form-urlencoded. This will ensure that the server can read the data over the http connection
How to do HTTP POST in Utf-8 -> php script -> mysql
[ "", "php", "delphi", "unicode", "" ]
I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing. The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying... Thanks PG ``` SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer WHERE (Forms!FrmSearchCompany!SearchName Is Null Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*") And (Forms!FrmSearchCompany.SearchPostcode Is Null Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*") And (Forms!FrmSearchCompany!SearchSortCode Is Null Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*") And (Forms!FrmSearchCompany!Searchaccount Is Null Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*") And (Forms!FrmSearchCompany!Searchcheque Is Null Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*"); "); ``` --- **EDIT** The Hold up seems to be in the union query that forms the QryAllTransactons query. ``` SELECT "TPC" AS Type, TabTPC.TPCRef, TabTPC.TPCBranch, TabTPC.TPCDate, TabTPC.TPCChequeNumber, TabTPC.TPCChequeValue, TabTPC.TPCFee, TabTPC.TPCAction, TabTPC.TPCMember, tabtpc.tpcdrawer, TabTPC.TPCUser, TabTPC.TPCDiscount, tabcustomers.* FROM TabTPC INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID UNION ALL SELECT "CTP" AS Type, TabCTP.CTPRef, TabCTP.CTPBranch, TabCTP.CTPDate, TabCTP.CTPChequeNumb, TabCTP.CTPAmount, TabCTP.CTPFee, TabCTP.CTPAction, TabCTP.CTPMember, 0 as CTPXXX, TabCTP.CTPUser, TabCTP.CTPDiscount, TABCUSTOMERS.* FROM TabCTP INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID; ``` I've done a fair bit of work with simple union queries, but never had this before...
Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc. Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will improve performance.
At first, try compacting and repairing the .mdb file. Then, simplify your WHERE clause: ``` WHERE [drawername] Like Nz(Forms!FrmSearchCompany!SearchName, "") & "*" And [Drawerpostcode] Like Nz(Forms!FrmSearchCompany!Searchpostcode, "") & "*" And [drawersortcode] Like Nz(Forms!FrmSearchCompany!Searchsortcode, "") & "*" And [draweraccountno] Like Nz(Forms!FrmSearchCompany!Searchaccount, "") & "*" And [tpcchequenumber] Like Nz(Forms!FrmSearchCompany!Searchcheque, "") & "*" ``` Does it still run slowly? **EDIT** As it turned out, the question was not clear in that it is an up-sized Access Database with an SQL Server back end-and an Access Project front-end. This sheds a different light on the whole problem. Can you explain in more detail *how* this whole query is intended to be used? If you use it to populate the RecordSource of some Form or Report, I think you will be able to refactor the whole thing like this: * make a view on the SQL server that returns the right data * query that view with a SQL server syntax, not with Access syntax * let the server sort it out
Slow SQL Code on local server in MS Access
[ "", "sql", "ms-access", "" ]
I have an Informix SQL query which returns a set of rows. It was slightly modified for the new version of the site we've been working on and our QA noticed that the new version returns different results. After investigation we've found that the only difference between two queries were in the number of fields returned. FROM, WHERE and ORDER BY clauses are identical and the column names in the SELECT part did not affect the results. It was only the number of fields which caused the problem. Any ideas?
The Informix SQL engine uses the indices on the tables based on the columns we want to retrieve. When retrieving different columns we were using different indices and therefore getting the results in different order.
Adding `--+ ORDERED` join-order directive fixes the problem by allowing you to get your results in predictable order each time. The links goes to the description of how the directive works <http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls1144.htm> > Use the ORDERED join-order directive > to force the optimizer to join tables > or views in the order in which they > appear in the FROM clause of the > query. ``` SELECT --+ ORDERED name, title, salary, dname FROM dept, job, emp WHERE title = 'clerk' AND loc = 'Palo Alto' AND emp.dno = dept.dno AND emp.job= job.job; ```
Informix SQL query: Two similar queries returning different results
[ "", "sql", "database", "informix", "" ]
We would need to embed mathematical formulas through [AsciiMathML](http://www1.chapman.edu/~jipsen/asciimath.html) into [Google Sites](http://sites.google.com) pages (internal wiki for a research team). I am stuck with the limitation of Google Sites. Any idea how to do that? (ps: I have finally found a [poorly practical work-around](http://blog.vermorel.com/?p=91), but better ideas would still be appreciated)
I used to use [texify.com](http://www.texify.com/), but they're no longer available. Now I use [Google Infographics Mathematical Formulas](http://code.google.com/apis/chart/infographics/docs/formulas.html), which has more features *and* (IMO) is more likely to continue being available in the future.
I had the same problem, but found texify: <http://www.texify.com/> as a complete solution. Texify is an online tex editor rendering gifs, and not AsciiMathML, but I found it quick to get the hang of. Just add the html code generated into your source in Google Sites, or insert picture from the GUI.
How to embed AsciiMathML in Google Sites?
[ "", "javascript", "math", "mathml", "google-sites", "" ]
I am trying to declare and use a class B inside of a class A and define B outside A. I know for a fact that this is possible because Bjarne Stroustrup uses this in his book "The C++ programming language" (page 293,for example the String and Srep classes). So this is my minimal piece of code that causes problems ``` class A{ struct B; // forward declaration B* c; A() { c->i; } }; struct A::B { /* * we define struct B like this becuase it * was first declared in the namespace A */ int i; }; int main() { } ``` This code gives the following compilation errors in g++ : ``` tst.cpp: In constructor ‘A::A()’: tst.cpp:5: error: invalid use of undefined type ‘struct A::B’ tst.cpp:3: error: forward declaration of ‘struct A::B’ ``` I tried to look at the C++ Faq and the closeset I got was [here](http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.12) and [here](http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.13) but those don't apply to my situation. I also [read this](https://stackoverflow.com/questions/237064/c-nested-classes-driving-me-crazy) from here but it's not solving my problem. Both gcc and MSVC 2005 give compiler errors on this
Define the constructor for A AFTER the definition of struct B.
The expression `c->i` dereferences the pointer to `struct A::B` so a full definition must be visible at this point in the program. The simplest fix is to make the constructor of `A` non-inline and provide a body for it after the defintion of `struct A::B`.
C++ Nested classes forward declaration error
[ "", "c++", "class", "nested", "declaration", "forward", "" ]