Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I like the immutability concept but sometimes I wonder, when an application isn't meant to be parallel, should one avoid making things immutable? When an application isn't multi-threaded, you aren't plagued by shared state problems, right? Or is immutability a concept like OOP that you either use all the way or not? Excluding the cases when something shouldn't be immutable based on use/performance, etc. I am faced with this question when writing an application for myself, that is moderately big (maybe like 1-2k lines).
I love immutability because it means I don't have to trust other peoples code not to mess around with objects I expect to stay the same. When you pass an object off to another component such as a `List<T>`, you are at the mercy of what that component does. This is especially important when you return collections as properties. ``` public class Foo { private List<Bar> _barList; public ICollection<Bar> BarList { get return _barList; } } ``` There's nothing stopping a consumer of this class from clearing the collection out from under me. Even switching the return type to `IEnumerable<Bar>` is not entirely safe. There's nothing stopping some piece of badly written code from casting this back to `List<T>` and calling .Clear(). However if I really want the collection to stay consistent I could rewrite it as followis ``` public class Foo { private ImmutableCollection<Bar> _barList; public ImmutableCollection<Bar> BarList { get { return _barList; } } } ``` Now I'm safe from having to trust other code from using my class incorrectly. They can't mess it up.
I like the advantage from immutability that you need to validate it only once - at creation of object. That's a huge bonus actually.
Is immutability useful on non parallel applications?
[ "", "c#", ".net", "performance", "immutability", "" ]
Is there a built-in way to convert `IEnumerator<T>` to `IEnumerable<T>`?
You could use the following which will **kinda** work. ``` public class FakeEnumerable<T> : IEnumerable<T> { private IEnumerator<T> m_enumerator; public FakeEnumerable(IEnumerator<T> e) { m_enumerator = e; } public IEnumerator<T> GetEnumerator() { return m_enumerator; } // Rest omitted } ``` This will get you into trouble though when people expect successive calls to GetEnumerator to return different enumerators vs. the same one. But if it's a one time only use in a **very** constrained scenario, this could unblock you. I do suggest though you try and not do this because I think eventually it will come back to haunt you. A safer option is along the lines Jonathan suggested. You can expend the enumerator and create a `List<T>` of the remaining items. ``` public static List<T> SaveRest<T>(this IEnumerator<T> e) { var list = new List<T>(); while ( e.MoveNext() ) { list.Add(e.Current); } return list; } ```
The easiest way of converting I can think of is via the yield statement ``` public static IEnumerable<T> ToIEnumerable<T>(this IEnumerator<T> enumerator) { while ( enumerator.MoveNext() ) { yield return enumerator.Current; } } ``` compared to the list version this has the advantage of not enumerating the entire list before returning an IEnumerable. using the yield statement you'd only iterate over the items you need, whereas using the list version, you'd first iterate over all items in the list and then all the items you need. for a little more fun you could change it to ``` public static IEnumerable<K> Select<K,T>(this IEnumerator<T> e, Func<K,T> selector) { while ( e.MoveNext() ) { yield return selector(e.Current); } } ``` you'd then be able to use linq on your enumerator like: ``` IEnumerator<T> enumerator; var someList = from item in enumerator select new classThatTakesTInConstructor(item); ```
Is there a built-in way to convert IEnumerator to IEnumerable
[ "", "c#", ".net", "linq", "" ]
If I define a function: ``` def f(x): return x+3 ``` I can later store objects as attributes of the function, like so: ``` f.thing="hello!" ``` I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?
The same way, just use its name. ``` >>> def g(x): ... g.r = 4 ... >>> g <function g at 0x0100AD68> >>> g(3) >>> g.r 4 ```
Or use a closure: ``` def gen_f(): memo = dict() def f(x): try: return memo[x] except KeyError: memo[x] = x + 3 return f f = gen_f() f(123) ``` Somewhat nicer IMHO
Python: getting a reference to a function from inside itself
[ "", "python", "function", "self-reference", "" ]
I'm overriding my doSave() method to basically do the following: I have a sfWidgetFormPropelChoice field that the user can either choose from, or type a new option. How can I change the widget's value? Or maybe I am approaching this the wrong way. So here is how I overrode the doSave() method: ``` public function doSave($con = null) { // Save the manufacturer as either new or existing. $manufacturer_obj = ManufacturerPeer::retrieveByName($this['manufacturer_id']->getValue()); if (!empty($manufacturer_obj)) { $this->getObject()->setManufacturerId($manufacturer_obj->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET'S VALUE INSTEAD? } else { $new = new Manufacturer(); $new->setName($this['manufacturer_id']->getValue()); $new->save(); $this->getObject()->setManufacturerId($new->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET'S VALUE INSTEAD? } parent::doSave($con); } ```
You should use setDefault or setDefaults and then it will autopopulate with the bound values. ``` (sfForm) setDefault ($name, $default) (sfForm) setDefaults ($defaults) ``` usage ``` $form->setDefault('WidgetName', 'Value'); $form->setDefaults(array( 'WidgetName' => 'Value', )); ```
You could do it in the action : ``` $this->form->getObject()->setFooId($this->foo->getId()) /*Or get the manufacturer id or name from request here */ $this->form->save(); ``` But I prefer to do the kind of work you are doing with your manufacturer directly in my Peer so my business logic is always at the same place. What I put in my forms is mainly validation logic. Example of what to put in the save method of the Peer : ``` public function save(PropelPDO $con= null) { if ($this->isNew() && !$this->getFooId()) { $foo= new Foo(); $foo->setBar('bar'); $this->setFoo($foo); } } ```
In symfony, how to set the value of a form field?
[ "", "php", "mysql", "symfony1", "propel", "" ]
So I've set up a pagination system similar to Twitter's where where 20 results are shown and the user can click a link to show the next twenty or all results. The number of results shown can be controlled by a parameter at the end of the URL however, this isn't updated with AJAX so if the user clicks on one of the results and then chooses to go back they have to start back at only 20 results. One thought I've had is if I update the URL when while I'm pulling in the results with AJAX it should—I hope—enable users to move back and forth without losing how many results are shown. Is this actually possible or have I got things completely wrong? Also, how would I go about changing the URL? I have a way to edit the URL with javascript and have it be a variable but I'm not sure how to apply that variable to the URL. Any help here would be great! A side note: I'm using jQuery's load() function to do all my AJAX.
You can't actually change the url of the page from javascript without reloading the page. You may wish to consider using cookies instead. By setting a client cookie you could "remember" how many results that user likes to see. [A good page on javascript cookies.](http://www.quirksmode.org/js/cookies.html)
Not mentioned in the duplicate threads, but useful nonetheless: [Really Simple History (RSH)](http://code.google.com/p/reallysimplehistory/).
When using back button AJAX results have been lost
[ "", "javascript", "jquery", "ajax", "url-rewriting", "hashchange", "" ]
A SQL VIEW is a global, logical table that may or may not be persisted. But it's still a table. Therefore, should a VIEW always adhere to first normal form (1NF)? i.e. no duplicate rows, scalar types only, no top-to-bottom or left-to-right ordering, etc. What about the higher normal forms? For me, my applications 'consume' the results of stored procs, my VIEWs are 'consumed' by SQL queries, and these two usages are mutually exclusive (i.e. I don’t query the resultsets of stored procs using SQL and my applications do not contain SQL code). I've seen others use a VIEW to 'concatenate' multiple values in a column into a single row, usually comma-separated format. Writing predicates in a SQL query against such a column requires a kludges similar to this: ``` ',' + concat_col + ',' LIKE '%' + ',' + search_value + ',' + '%' ``` So it seems to me reasonable to expect all tables that can be queried to consist of only scalar types. Am I being too 'purist' by thinking this?
It makes perfect sense to ensure your views are normalized to at least 1NF. Permitting duplicates for example has the disadvantage that the meaning of the view is made ambiguous and information may be misidentified by users. Incorrect data could occur if tables are updated based on such ambiguities. E.F.Codd didn't necessarily agree though. In his RM version 2 book he proposes allowing views without keys - a big mistake I think. Codd's views don't actually permit duplicates but they do allow every column to be nullable and therefore don't have keys and aren't in 1NF. A string value containing a comma-delimitted list is not itself a violation of 1NF. A string value is a scalar like any other value, whatever it contains. Most SQL DBMSs don't permit multi-valued attributes.
No - I create views to match the output that my program requires.
Should a SQL VIEW always be in 1NF?
[ "", "sql", "normalization", "" ]
I am a C++ beginner, so sorry if the question is too basic. I have tried to collect the string constrcturs and try all them out (to remember them). ``` string strA(); // string(); empty string // incorrect string strB("Hello"); // string( const char* str) string strC("Hello",3); // string( const char* str, size_type length) string strD(2,'c'); // string( size_type lenght, const char &c) string strE(strB); // string( const string& s) cout << strA << endl; cout << strB << endl; cout << strC << endl; cout << strD << endl; cout << strE << endl; ``` All of them works except for the **strA**. It prints "1". **Why? Whats the type of the strA in this case? How can I check the type of stuff when I am unsure?** I have noticed that the correct way is this (which by the way seems to be inconsistent with the other constructors, sometimes parens sometimes no parens): ``` string strA; ``` ps: question in bold, usual irrelevant answers will be downvoted.
This is a very popular gotcha. C++ grammar is ambiguous. One of the rules to resolve ambiguities is "if something looks like declaration it is a declaration". In this case instead of defining a variable you declared a function prototype. ``` string strA(); ``` is equivalent to ``` string strA(void); ``` a prototype of a no-arg function which returns string. If you wish to explicitly call no-arg constructor try this: ``` string strA=string(); ``` It isn't fully equivalent - it means 'create a temporary string using no-arg constructor and then copy it to initialize variable strA', but the compiler is allowed to optimize it and omit copying. EDIT: [Here is an appropriate item in C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.2)
It considers ``` string strA(); ``` as a function declaration. For default constructor use: ``` string strA; ```
C++ empty String constructor
[ "", "c++", "string", "" ]
``` public class Foo { public string Bar {get; set;} } ``` How do I get the value of Bar, a string property, via reflection? The following code will throw an exception if the PropertyInfo type is a System.String ``` Foo f = new Foo(); f.Bar = "Jon Skeet is god."; foreach(var property in f.GetType().GetProperties()) { object o = property.GetValue(f,null); //throws exception TargetParameterCountException for String type } ``` It seems that my problem is that the property is an indexer type, with a System.String. Also, how do I tell if the property is an indexer?
You can just get the property by name: ``` Foo f = new Foo(); f.Bar = "Jon Skeet is god."; var barProperty = f.GetType().GetProperty("Bar"); string s = barProperty.GetValue(f,null) as string; ``` **Regarding the follow up question:** Indexers will always be named Item and have arguments on the getter. So ``` Foo f = new Foo(); f.Bar = "Jon Skeet is god."; var barProperty = f.GetType().GetProperty("Item"); if (barProperty.GetGetMethod().GetParameters().Length>0) { object value = barProperty.GetValue(f,new []{1/* indexer value(s)*/}); } ```
I couldn't reproduce the issue. Are you sure you're not trying to do this on some object with indexer properties? In that case the error you're experiencing would be thrown while processing the Item property. Also, you could do this: ``` public static T GetPropertyValue<T>(object o, string propertyName) { return (T)o.GetType().GetProperty(propertyName).GetValue(o, null); } ...somewhere else in your code... GetPropertyValue<string>(f, "Bar"); ```
How can I get the value of a string property via Reflection?
[ "", "c#", "string", "reflection", "properties", "" ]
I'm trying to replace an element's inline style tag value. The current element looks like this: ``` `<tr class="row-even" style="background: red none repeat scroll 0% 0%; position: relative; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" id="0000ph2009-06-10s1s02">` ``` and I'd like to remove all that style stuff so that it's styled by it's class rather than it's inline style. I've tried delete element.style; and element.style = null; and element.style = ""; to no avail. My current code breaks at these statement. The whole function looks like: function unSetHighlight(index){ ``` if(index < 10) index = "000" + (index); else if (index < 100) index = "000" + (index); else if(index < 1000) index = "0" + (index); if(index >= 1000) index = index; var mainElm = document.getElementById('active_playlist'); var elmIndex = ""; for(var currElm = mainElm.firstChild; currElm !== null; currElm = currElm.nextSibling){ if(currElm.nodeType === 1){ var elementId = currElm.getAttribute("id"); if(elementId.match(/\b\d{4}/)){ elmIndex = elementId.substr(0,4); if(elmIndex == index){ var that = currElm; //that.style.background = position: relative; } } } } clearInterval(highlight); alert("cleared Interval"); that.style.background = null; alert("unSet highlight called"); } ``` the clearInterval works but the alert never fires and the background stays the same. What's the problem? --- ``` function unSetHighlight(index){ alert(index); if(index < 10) index = "000" + (index); else if (index < 100) index = "000" + (index); else if(index < 1000) index = "0" + (index); if(index >= 1000) index = index; var mainElm = document.getElementById('active_playlist'); var elmIndex = ""; for(var currElm = mainElm.firstChild; currElm !== null; currElm = currElm.nextSibling){ if(currElm.nodeType === 1){ var elementId = currElm.getAttribute("id"); if(elementId.match(/\b\d{4}/)){ elmIndex = elementId.substr(0,4); alert("elmIndex = " + elmIndex + "index = " + index); if(elmIndex === index){ var that = currElm; alert("match found"); } } } } clearInterval(highlight); alert("cleared Interval"); that.removeAttribute("style"); //that.style.position = "relative"; //reColor(); alert("unSet highlight called"); } ```
you can just do: ``` element.removeAttribute("style") ```
In JavaScript: ``` document.getElementById("id").style.display = null; ``` In jQuery: ``` $("#id").css('display',null); ```
Removing HTML element styles via JavaScript
[ "", "javascript", "html", "dom", "styles", "" ]
I had an interview question that asked me for my 'feedback' on a piece of code a junior programmer wrote. They hinted there may be a problem and said it will be used heavily on large strings. ``` public string ReverseString(string sz) { string result = string.Empty; for(int i = sz.Length-1; i>=0; i--) { result += sz[i] } return result; } ``` I couldn't spot it. I saw no problems whatsoever. In hindsight I could have said the user should resize but it looks like C# doesn't have a resize (i am a C++ guy). I ended up writing things like use an iterator if its possible, [x] in containers could not be random access so it may be slow. and misc things. But I definitely said I never had to optimize C# code so my thinking may have not failed me on the interview. I wanted to know, what is the problem with this code, do you guys see it? -edit- I changed this into a wiki because there can be several right answers. Also i am so glad i explicitly said i never had to optimize a C# program and mentioned the misc other things. Oops. I always thought C# didnt have any performance problems with these type of things. oops.
A few comments on the answers given so far: * Every single one of them (so far!) will fail on surrogate pairs and combining characters. Oh the joys of Unicode. Reversing a string isn't the same as reversing a sequence of chars. * I like [Marc's optimisation](https://stackoverflow.com/questions/1009689/reversestring-a-c-interview-question/1009713#1009713) for null, empty, and single character inputs. In particular, not only does this get the right answer quickly, but it also handles null (which none of the other answers do) * I originally thought that `ToCharArray` followed by `Array.Reverse` would be the fastest, but it does create one "garbage" copy. * The `StringBuilder` solution creates a single string (not char array) and manipulates that until you call `ToString`. There's no extra copying involved... but there's a lot more work maintaining lengths etc. Which is the more efficient solution? Well, I'd have to benchmark it to have any idea at all - but even so that's not going to tell the whole story. Are you using this in a situation with high memory pressure, where extra garbage is a real pain? How fast is your memory vs your CPU, etc? As ever, readability is *usually* king - and it doesn't get much better than Marc's answer on that front. In particular, there's *no room* for an off-by-one error, whereas I'd have to actually put some thought into validating the other answers. I don't like thinking. It hurts my brain, so I try not to do it very often. Using the built-in `Array.Reverse` sounds much better to me. (Okay, so it still fails on surrogates etc, but hey...)
Most importantly? That will suck performance wise - it has to create **lots** of strings (one per character). The simplest way is something like: ``` public static string Reverse(string sz) // ideal for an extension method { if (string.IsNullOrEmpty(sz) || sz.Length == 1) return sz; char[] chars = sz.ToCharArray(); Array.Reverse(chars); return new string(chars); } ```
ReverseString, a C# interview-question
[ "", "c#", "" ]
> **Possible Duplicates:** > [Why does simple C code receive segmentation fault?](https://stackoverflow.com/questions/164194/why-does-simple-c-code-receive-segmentation-fault) > [Modifying C string constants?](https://stackoverflow.com/questions/480555/modifying-c-string-constants) Why does this code generate an access violation? ``` int main() { char* myString = "5"; *myString = 'e'; // Crash return 0; } ```
\*mystring is apparently pointing at read-only static memory. C compilers may allocate string literals in read-only storage, which may not be written to at run time.
String literals are considered constant.
Modifying a C string: access violation
[ "", "c++", "c", "string", "" ]
How I can capture event, close browser window, in jQuery or javascript ?
You're looking for the onclose event. see: <https://developer.mozilla.org/en/DOM/window.onclose> note that not all browsers support this (for example firefox 2)
<http://docs.jquery.com/Events/unload#fn> jQuery: ``` $(window).unload( function () { alert("Bye now!"); } ); ``` or javascript: ``` window.onunload = function(){alert("Bye now!");} ```
Capture event onclose browser
[ "", "javascript", "jquery", "events", "" ]
Is there any way to detect, whether the pointer points to array in C++? My problem is that I want to implement a class, that becomes the owner of the array. My class is initialized with the pointer and I would like to know, whether the pointer is really an array pointer. Here is the simplified code: ``` class ArrayOwner { public: explicit ArrayOwner( int* initialArray ) : _ptrToArray(initialArray) {} virtual ~ArrayOwner() { delete [] _ptrToArray; } private: int* _ptrToArray; } ``` * This usage will be ok: **ArrayOwner foo( new int[10] );** * But this usage leads to undefined behaviour: **ArrayOwner foo( new int() );** I would like to add assert in the constructor, that the "initialArray" pointer is really an array pointer. I cannot change the contract of the constructor, use vectors e.t.c. Is there any way to write this assert in C++?
No, unfortunately not. C++ [RTTI](http://www.devx.com/getHelpOn/Article/10202/1954) does not extend to primitive types.
There's no portable way to do it.
Any way to detect whether the pointer points to array?
[ "", "c++", "arrays", "pointers", "" ]
i just graduated from a polytechnic where i was taught quite basic programming (at least in my opinion, like VB Calculators and such) so now in my current job, i feel that that's not enuf. i am wondering from my basic foundation how can i build up my skills? i am picking up C# 3.0 (4.0 seems to be out soon) WPF, LINQ the issue that i face now is for windows applications, how can i have an app that can manage various database tables, ie. add, edit, delete, list dialogs. i dont want to have them as separate forms. i also dont want to spam everything in 1 screen. what i like is something like outlook. where i have a accordion side navigation. then when i click something, it loads up in the main screen, maybe with closable tabs. i was linked to [MSDN Patterns & Practices](http://msdn.microsoft.com/en-us/library/ms998572.aspx) when i posted something similar in MSDN. but it seems to be a big jump. i am missing alot in between. there are patterns, MVC, and such ... whats the best for Windows app? i use MVC for my web development
Try looking here: <http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx> Hope it helps :-)
"i am wondering from my basic foundation how can i build up my skills?" - the best way to do this is to read development blogs and join some opensource project and analyze sources of popular frameworks and tools. This will help you to grow exponentially. About MSDN P&P, it's not good, I can not recommend you to follow them. Yes, there are many good P&P but there much more not good ones. You can't build good guidance without community responses and reviews. But most of the guidance were created in this way - somebody (a "guru") wrote it, it was published and MS said "follow it!". Thanks for gods, this starts to change during last time. I recommend you to check out the following frameworks and blogs (the best ones from my rss feeds): <http://caliburn.codeplex.com/> <http://nhforge.org/Default.aspx> <http://code.google.com/p/sharp-architecture/> <http://www.castleproject.org/> <http://www.codeplex.com/xval> <http://ayende.com/blog> <http://www.lostechies.com/> <http://karlshifflett.wordpress.com/> <http://jeffreypalermo.com/> <http://fabiomaulo.blogspot.com/> <http://devlicio.us/> <http://codebetter.com/>
Windows Apps: Best Practices & Patterns (C#/WPF/LINQ)
[ "", "c#", "wpf", "linq", "design-patterns", "" ]
In the 2009 Wikipedia entry for the Strategy Pattern, there's a example [written in PHP](http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP). Most other code samples do something like: ``` a = Context.new(StrategyA.new) a.execute #=> Doing the task the normal way b = Context.new(StrategyB.new) b.execute #=> Doing the task alternatively c = Context.new(StrategyC.new) c.execute #=> Doing the task even more alternative ``` In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do. **Update:** Can it be shorter using first-class functions in Python?
The example in Python is not so different of the others. To mock the PHP script: ``` class StrategyExample: def __init__(self, func=None): if func: self.execute = func def execute(self): print("Original execution") def executeReplacement1(): print("Strategy 1") def executeReplacement2(): print("Strategy 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat2 = StrategyExample(executeReplacement2) strat0.execute() strat1.execute() strat2.execute() ``` Output: ``` Original execution Strategy 1 Strategy 2 ``` The main differences are: * You don't need to write any other class or implement any interface. * Instead you can pass a function reference that will be bound to the method you want. * The functions can still be used separately, and the original object can have a default behavior if you want to (the `if func == None` pattern can be used for that). * Indeed, it's clean short and elegant as usual with Python. But you lose information; with no explicit interface, the programmer is assumed as an adult to know what they are doing. Note that there are 3 ways to dynamically add a method in Python: * The way I've shown you. But the method will be static, it won't get the "self" argument passed. * Using the class name: `StrategyExample.execute = func` Here, all the instance will get `func` as the `execute` method, and will get `self` passed as an argument. * Binding to an instance only (using the `types` module): `strat0.execute = types.MethodType(executeReplacement1, strat0)` or with Python 2, the class of the instance being changed is also required: `strat0.execute = types.MethodType(executeReplacement1, strat0, StrategyExample)` This will bind the new method to `strat0`, and only `strat0`, like with the first example. But `start0.execute()` will get `self` passed as an argument. If you need to use a reference to the current instance in the function, then you would combine the first and the last method. If you do not: ``` class StrategyExample: def __init__(self, func=None): self.name = "Strategy Example 0" if func: self.execute = func def execute(self): print(self.name) def executeReplacement1(): print(self.name + " from execute 1") def executeReplacement2(): print(self.name + " from execute 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat1.name = "Strategy Example 1" strat2 = StrategyExample(executeReplacement2) strat2.name = "Strategy Example 2" strat0.execute() strat1.execute() strat2.execute() ``` You will get: ``` Traceback (most recent call last): File "test.py", line 28, in <module> strat1.execute() File "test.py", line 13, in executeReplacement1 print self.name + " from execute 1" NameError: global name 'self' is not defined ``` So the proper code would be: ``` import sys import types if sys.version_info[0] > 2: # Python 3+ create_bound_method = types.MethodType else: def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) class StrategyExample: def __init__(self, func=None): self.name = "Strategy Example 0" if func: self.execute = create_bound_method(func, self) def execute(self): print(self.name) def executeReplacement1(self): print(self.name + " from execute 1") def executeReplacement2(self): print(self.name + " from execute 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat1.name = "Strategy Example 1" strat2 = StrategyExample(executeReplacement2) strat2.name = "Strategy Example 2" strat0.execute() strat1.execute() strat2.execute() ``` This will output the expected result: ``` Strategy Example 0 Strategy Example 1 from execute 1 Strategy Example 2 from execute 2 ``` Of course, in the case the functions cannot be used stand alone anymore, but can still be bound to any other instance of any object, without any interface limitation.
Answering an old question for the Googlers who searched "python strategy pattern" and landed here... This pattern is practically non-existent in languages that support first class functions. You may want to consider taking advantage of this feature in Python: ``` def strategy_add(a, b): return a + b def strategy_minus(a, b): return a - b solver = strategy_add print solver(1, 2) solver = strategy_minus print solver(2, 1) ``` This approach is very clean and simple. Also, be sure to check out Joe Gregorio's PyCon 2009 talk about Python and design patterns (or lack thereof): <http://pyvideo.org/video/146/pycon-2009--the--lack-of--design-patterns-in-pyth>
How to write Strategy Pattern in Python differently than example in Wikipedia?
[ "", "python", "design-patterns", "" ]
From an example you can see a multiple OR query filter: ``` Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) ``` For example, this results in: ``` [<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>] ``` However, I want to create this query filter from a list. How to do that? e.g. `[1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))`
You could chain your queries as follows: ``` values = [1,2,3] # Turn list of values into list of Q objects queries = [Q(pk=value) for value in values] # Take one Q object from the list query = queries.pop() # Or the Q object with the ones remaining in the list for item in queries: query |= item # Query the model Article.objects.filter(query) ```
To build more complex queries there is also the option to use built in Q() object's constants Q.OR and Q.AND together with the add() method like so: ``` list = [1, 2, 3] # it gets a bit more complicated if we want to dynamically build # OR queries with dynamic/unknown db field keys, let's say with a list # of db fields that can change like the following # list_with_strings = ['dbfield1', 'dbfield2', 'dbfield3'] # init our q objects variable to use .add() on it q_objects = Q(id__in=[]) # loop trough the list and create an OR condition for each item for item in list: q_objects.add(Q(pk=item), Q.OR) # for our list_with_strings we can do the following # q_objects.add(Q(**{item: 1}), Q.OR) queryset = Article.objects.filter(q_objects) # sometimes the following is helpful for debugging (returns the SQL statement) # print queryset.query ```
How to dynamically compose an OR query filter in Django?
[ "", "python", "django", "django-q", "" ]
I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another way I could evaluate if my string is a rational number (ex: 1.25). Example code: ``` if self.components.txtZoomPos.text.isdigit(): step = int(self.components.txtZoomPos.text) ```
1.25 is a notation commonly used for [reals](http://en.wikipedia.org/wiki/Real_number), less so for [rational numbers](http://en.wikipedia.org/wiki/Rational_number). Python's [float](http://docs.python.org/library/functions.html#float) will raise a [ValueError](http://docs.python.org/library/exceptions.html#exceptions.ValueError) when conversion fails. Thus: ``` def isReal(txt): try: float(txt) return True except ValueError: return False ```
`try`/`catch` is very cheap in Python, and attempting to construct a `float` from a string that's not a number raises an exception: ``` >>> float('1.45') 1.45 >>> float('foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for float(): foo ``` You can just do something like: ``` try: # validate it's a float value = float(self.components.txtZoomPos.text) except ValueError, ve: pass # your error handling goes here ```
isDigit() for rational numbers?
[ "", "python", "string", "" ]
I'm trying to perform a Median filter on an image in Java but it's terribly slow. Firstly, if any of you know of a standalone implementation I could use it would be fantastic if you could let me know. I'm implementing on Android, trying to replicate a small part of the JAI. In my method I take each pixel, extract the R,G & B values using ``` r = pixel >> 16 & 0xFF ``` Or similar, find the median for the kernel and finish with ``` pixel = a | r <<16 | g << 8 | b ``` Is there any way I can grab the bytes from an int in such a way that this would be faster? Kind regards, Gavin --- EDIT: Full code to help diagnose my low performance upon request For the actual source file please go [here](http://code.google.com/p/miffed/source/browse/trunk/Miffed%20Demo/src/uk/ac/ic/doc/gea05/miffed/operators/bitmap/unary/impl/Median.java) that's where my implementation of **medianFilter** can be found. *width* and *height* variables are for the size of *dest* and are available as class member variables. The pixels are linearized into a one dimensional array. ``` private void medianFilterSquare(int[] source, int[] dest, int rWidth, int rHeight, int radius) { // Source has been reflected into a border of size radius // This makes it radius * 2 pixels wider and taller than the dest int r,g,b; int destOffset, rOffset, kOffset; // The first offset into the source to calculate a median for // This corresponds to the first pixel in dest int rFirst = radius + (rWidth*radius); // We use a square kernel with the radius passed int neighbours = (radius+radius+1)*(radius+radius+1); int index; // Arrays to accumulate the values for median calculation int[] rs = new int[neighbours]; int[] gs = new int[neighbours]; int[] bs = new int[neighbours]; // Declaring outside the loop helps speed? I'm sure this is done for me // by the compiler int pixel; // Iterate over the destination pixels for(int x = 0; x < height; x++){ for(int y = 0; y < width; y++){ // Offset into destination destOffset = x + (y * width); // Offset into source with border size radius rOffset = destOffset + rFirst + (y * (radius *2)); index = 0; // Iterate over kernel for(int xk = -radius; xk < radius ; xk ++){ for(int yk = -radius; yk < radius ; yk ++){ kOffset = rOffset + (xk + (rWidth*yk)); pixel = source[kOffset]; // Color.red is equivalent to (pixel>>16) & 0xFF rs[index] = Color.red(pixel); gs[index] = Color.green(pixel); bs[index] = Color.blue(pixel); index++; } } r = medianFilter(rs); g = medianFilter(gs); b = medianFilter(bs); dest[destOffset] = Color.rgb(r, g, b); } } } ```
As others have said, it's possible that it's the bit in between which is causing the problem. One thing I would say (which may be obvious, but anyway) - don't just profile the application on a desktop VM and assume that the bottleneck will be in the same place. I wouldn't be at all surprised to find entirely different bottlenecks within Dalvik. Is it possible for you to work with the values still shifted? For instance, if you were to *just* mask for different colours: ``` int r = pixel & 0xff0000; int g = pixel & 0xff00; int b = pixel & 0xff; ``` could you tweak your processing algorithm accordingly? One final thought: I always find the precedence of shift operators confusing. I'd *strongly* recommend that from a readability point of view, you bracket them: ``` r = (pixel >> 16) & 0xFF; pixel = a | (r <<16) | (g << 8) | b; ``` Irrelevant to performance, but if I were a maintainer I'd certainly appreciate it :)
The fastet way to get your r,g,b values should be ``` new byte[] { (byte)(value >>> 24), (byte)(value >>> 16), (byte)(value >>> 8), (byte)value }; ```
Get Bytes from an int to avoid bit shifting fun - Java (Median Filtering)
[ "", "java", "algorithm", "image-processing", "" ]
sorry if you'll find this question stupid, but I really need help. Here's some info about it. ## Database structure --- id | parent\_id | level | name 1 | 0 | 1 | Home page 2 | 1 | 2 | Child of homepage 3 | 1 | 2 | Another child of homepage 4 | 2 | 3 | Sub child of page id 2 5 | 3 | 3 | Sub child of page id 3 --- ## Question --- How do I make the SQL statement to group my rows by level and make this output. ## Desired output --- Home page ~~Child of homepage ~~~~Sub child of page id 2 ~~Another child of homepage ~~~~Sub child of page id 3 I know how to do this with a recursion method, but I want to know if I can accomplish this with one SQL statement.
Well, you could order the data by parent\_id so that it is sorted correctly: ``` $menu = mysql_query("SELECT * FROM menu ORDER BY parent_id, level, name"); ``` Then, use the level to determine your indent: ``` while ($row = mysql_fetch_object($menu)) { echo str_repeat('~~', $row->level).' '.$row->name.'<br />'; } ``` Say you want them in nested lists or some other element (rather than indented by a prefix such as '~~'): ``` $level = 0; echo '<ul>'; while ($row = mysql_fetch_object($menu)) { if ($row->level > $level) { echo '<ul>'; } else if ($row->level < $level) { echo '</ul>'; } echo '<li> '.$row->name.'</li>'; $level = $row->level; } for ($i = $level; $i >= 0; $i--) { echo '</ul>'; } ```
I often recommend this article on [Storing Hierarchical Data in a Database](http://www.sitepoint.com/article/hierarchical-data-database/1/) for questions like this. The answer to your question is yes, you can get it in just one query. Your method (recursive) is discussed on the first page. Check out page two for the alternative solution, which is the Modified Preorder Tree Traversal (MPTT) design. Using that set-up, you can run a single query and retrieve all the children of a given node of your structure. It's very similar to what you have now, but not quite the same, and will require a bit of work to implement. For a read-heavy application however, the MPTT is a great algorithm. It requires a bit more work when doing writes, since you have to modify the entire tree structure, but from what you've got set up there I think it might work very well for you.
Pages with level
[ "", "php", "" ]
we have an issue with an access database we are upgrading to use SQL Server as its data store. This particular database links to 2 sql databases, so I thought to simplify things, we have a view in the main database that linked to each table in the secondary database. That way access would only need to talk directly with one SQL database. When we linked access to the database views we choose which fields were the primary keys so the views were not readonly. We have standard code that refreshes all links when a database opens to pickup any changes and the linked views become readonly because the primary key information is lost. Is there a way of refreshing the links to views while retaining the primary key information? John
I have included my entire ODBC Reconnect function below. This function is predicated with the idea that I have a table called rtblODBC which stores all of the information I need to do the reconnecting. If you implement this function, you will NOT need to worry about connecting to multiple SQL databases, as that is handled smoothly with each table to be reconnected having its own connection string. When you get towards the end you will see that I use DAO to recreate the primary keys with db.Execute "CREATE INDEX " & sPrimaryKeyName & " ON " & sLocalTableName & "(" & sPrimaryKeyField & ")WITH PRIMARY;" If you have any questions, please ask. ``` Public Function fnReconnectODBC( _ Optional bForceReconnect As Boolean _ ) As Boolean ' Comments : ' Parameters: bForceReconnect - ' Returns : Boolean - ' Modified : ' --------------------------------------------------' On Error GoTo Err_fnReconnectODBC Dim db As DAO.Database Dim rs As DAO.Recordset Dim tdf As DAO.TableDef Dim sPrimaryKeyName As String Dim sPrimaryKeyField As String Dim sLocalTableName As String Dim strConnect As String Dim varRet As Variant Dim con As ADODB.Connection Dim rst As ADODB.Recordset Dim sSQL As String If IsMissing(bForceReconnect) Then bForceReconnect = False End If sSQL = "SELECT rtblODBC.LocalTableName, MSysObjects.Name, MSysObjects.ForeignName, rtblODBC.SourceTableName, MSysObjects.Connect, rtblODBC.ConnectString " _ & "FROM MSysObjects RIGHT JOIN rtblODBC ON MSysObjects.Name = rtblODBC.LocalTableName " _ & "WHERE (((rtblODBC.ConnectString)<>'ODBC;' & [Connect]));" Set con = Access.CurrentProject.Connection Set rst = New ADODB.Recordset rst.Open sSQL, con, adOpenDynamic, adLockOptimistic 'Test the recordset to see if any tables in rtblODBC (needed tables) are missing from the MSysObjects (actual tables) If rst.BOF And rst.EOF And bForceReconnect = False Then 'No missing tables identified fnReconnectODBC = True Else 'Table returned information, we don't have a perfect match, time to relink Set db = CurrentDb Set rs = db.OpenRecordset("rtblODBC", dbOpenSnapshot) 'For each table definition in the database collection of tables For Each tdf In db.TableDefs 'Set strConnect variable to table connection string strConnect = tdf.Connect If Len(strConnect) > 0 And Left(tdf.Name, 1) <> "~" Then If Left(strConnect, 4) = "ODBC" Then 'If there is a connection string, and it's not a temp table, and it IS an odbc table 'Delete the table DoCmd.DeleteObject acTable, tdf.Name End If End If Next 'Relink tables from rtblODBC With rs .MoveFirst Do While Not .EOF Set tdf = db.CreateTableDef(!localtablename, dbAttachSavePWD, !SourceTableName, !ConnectString) varRet = SysCmd(acSysCmdSetStatus, "Relinking '" & !SourceTableName & "'") db.TableDefs.Append tdf db.TableDefs.Refresh If Len(!PrimaryKeyName & "") > 0 And Len(!PrimaryKeyField & "") > 0 Then sPrimaryKeyName = !PrimaryKeyName sPrimaryKeyField = !PrimaryKeyField sLocalTableName = !localtablename db.Execute "CREATE INDEX " & sPrimaryKeyName & " ON " & sLocalTableName & "(" & sPrimaryKeyField & ")WITH PRIMARY;" End If db.TableDefs.Refresh .MoveNext Loop End With subTurnOffSubDataSheets fnReconnectODBC = True End If rst.Close Set rst = Nothing con.Close Set con = Nothing Exit_fnReconnectODBC: Set tdf = Nothing Set rs = Nothing Set db = Nothing varRet = SysCmd(acSysCmdClearStatus) Exit Function Err_fnReconnectODBC: fnReconnectODBC = False sPrompt = "Press OK to continue." vbMsg = MsgBox(sPrompt, vbOKOnly, "Error Reconnecting") If vbMsg = vbOK Then Resume Exit_fnReconnectODBC End If End Function ```
A good deal of DSN less code that re-links access tables to SQL server often deletes the links first, then recreates the link. The code then sets up the connection string. Thus, it is the deleting that causes you to lose what the primary key was/is. I actually recommend that you modify your re-link code as to not delete the table links. Try something like: ``` For Each tdfCurrent In dbCurrent.TableDefs If Len(tdfCurrent.Connect) > 0 Then If Left$(tdfCurrent.Connect, 5) = "ODBC;" Then strCon = "ODBC;DRIVER={sql server};" & _ "SERVER=" & ServerName & ";" & _ "DATABASE=" & DatabaseName & ";" & _ "UID=" & UserID & ";" & _ "PWD=" & USERpw & ";" & _ "APP=Microsoft Office 2003;" & _ "WSID=" & WSID & ";" End If End If tdfCurrent.Connect = strCon tdfCurrent.RefreshLink End If Next tdfCurrent ```
MS Access linked to SQL server views
[ "", "sql", "sql-server", "ms-access", "view", "" ]
I am preparing a web page with more data that can possibly be shown without making the page really cumbersome. I am considering different way to do this. One way would be to have the extra data magically appear on a small window when the user hovers over a particular part of text.Yahoo! Answers does something like that when you hover over a user. But I suppose that must be way to complex to code (for my level). SO I am looking for a simple way to get a small pop up window to appear next to the mouse pointer when the user hovers on a particularly interesting text. The window should disappear automatically once the user leaves the text. On this topic I have a few questions: * How can this be done? * Can it be done without using JavaScript? * What other solutions should I consider? (For example I have seen some web pages expand some sections, when the user hovers click on them)
Just use a DIV to show your text, to open a completely new window is overkill and seeing as most people have popup blockers in their browsers, the window won't even show. I suggest using JQuery (nice to start with if you are new as it will make your Javascript development WAY easier) and the JQuery Tooltip plugin found [here](http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/)
The prettiest solution would probably be using jQuery and the jQuery tooltip plugin, as mentioned above. If you are really keen on avoiding javascript, you can reach this goal with just the use of css: ``` <div id="bigdiv"> bla <div id="tooltip">this is a bla</div> </div> #tooltip{ display:none; } #bigdiv:hover #tooltip{ display:block; } ```
How can I open a small window when the user hovers over some text?
[ "", "javascript", "html", "popup", "" ]
I've seen in the post called something like "a small change you've done that has increased the performance of your application" a comment about changing from: ``` SELECT U.userid,groups_in=( SELECT COUNT(*) FROM usersgroup WHERE userid=U.userid) FROM tbl_users U ``` to: ``` SELECT U.userid, groups_in FROM users U LEFT JOIN ( select userid, groups_in=count(*) from usersgroup group by userid) GROUPS ON GROUPS.userid = U.userid ``` And I thought "oh, that's the kind of thing I've been doing wrong!!", however I tried both queries in the same environment and both gives me the same execution time and the db execution plan looks exactly the same. Is there a better way to do the same operation? are those queries both absolutely fine?
The SQL Server optimiser seems to get better and better with each new version, service pack and hotfix. I can't count the number of times I have seen it execute [horrible convoluted mess] using the same efficient plan as [simple elegant equivalent]. Look to your table and index design for efficiency savings first, then clean up your queries if they are still running slowly.
Try: ``` SELECT U.userid, COUNT(G.userid) as groups_in FROM users U LEFT JOIN usersgroup G ON G.userid = U.userid GROUP BY U.userid; ``` This avoid subqueries -- which is very bad for the optimizer. Make sure you have index on the "userid" column on both table
SQL counts performance (sql 2000)
[ "", "sql", "sql-server", "t-sql", "" ]
I have a J2EE application that has a lot of reports, the situation now is the following: Report filters' values are sent to the application over DWR mainly, the data are retrieved from Oracle DB throw DB procedures and returned back to the client. However, some customization is required every now and then (new data filters, columns, ordering, ...), and these changes are painful to implement since we need to modify the JSPs, DB Procedures, the application itself, ... What API do you recommend to use for such reports?
[JasperReports](http://jasperforge.org/plugins/project/project_home.php?group_id=102) is popular as I heard. [ILog JViews](http://www.ilog.com/products/jviews/features.cfm) if you want to take the commercial route.
You could try [Docmosis](http://www.docmosis.com) which is free and template based (though you need to pay for unlimited scalability options). To change layouts, fonts etc and such you can do it in the doc or odf template. Docmosis can spit out doc/pdf/odf/html etc from a Java server.
Whats a good API for generating reports for a java web application?
[ "", "java", "reporting", "" ]
In Ruby I frequently use `File.dirname(__FILE__)` to open configuration files and such. For those that don't know Ruby, this will give the location on the file system of the file it's called from. This allows me to package libraries with data and config files and open those files with relative paths. What's the Java equivalent of this? If there is a data file I want to package with a jar how would I open the data file from Java code that is also in the jar?
The equivalent API in Java is [`getResourceAsStream`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)). This will open a stream to a file stored in the JAR relative to the class on which it is invoked. There are variants, such as [`getResource`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getResource(java.lang.String)), which returns a URL, or methods on `ClassLoader` that use an absolute path inside the JAR file.
Please see [Java Applications and the "Current Directory"](http://www.devx.com/tips/Tip/13804): > In Java, you use File objects to > construct a relative view of the file > system. Two of the constructors for > the File object take a 'parent' > argument that specifies a parent path > that is prefixed to the path of the > file itself to create the full > abstract path to the file. What you do > is, create a File object with the path > that represents your current directory > and then create all your file objects > using that File object as the parent. > Voila, a current directory. Also I would recommend [Reading and Writing a Properties File](http://www.exampledepot.com/egs/java.util/Props.html): ``` // Read properties file. Properties properties = new Properties(); try { properties.load(new FileInputStream("filename.properties")); } catch (IOException e) { } // Write properties file. try { properties.store(new FileOutputStream("filename.properties"), null); } catch (IOException e) { } ```
Java's equivalent of Ruby's __FILE__?
[ "", "java", "ruby", "" ]
I'm trying to find the equivalent of PropertyInfo.AddValueChanged for FieldInfo. I basically just need to receive an event any time the field's value changes. I'm assuming there's nothing like this and I'll have to manipulate IL code or something like that. I'm willing to go that route, but any suggestions on how I should go about it? And is there an AddValueChanged equivalent for fields that I'm not aware of so I don't have to go that route? Thanks.
Why not just wrap the field in a property, and implement an event on change (ie: make your class INotifyPropertyChanged or your own equivelent)? That's one the beautiful things about properties - they allow you to define behavior in this manner. Fields do not have any equivelent, and manipulating IL is not going to change this. As long as it's a field, it will not notify.
Let me just confirm that there's nothing built-in like what you're after. Properties can easily implement that because the setter is a method, while fields by design don't have setter methods, their value is just modified and that can happen from any place in the code. To do what you're after, I think you could take a look at PostSharp.
PropertyInfo.AddValueChanged Equivalent for Fields?
[ "", "c#", "field", "reflection.emit", "" ]
Is there java utility that does `clone()` method for `HashMap` such that it does copy of the map elements not just the map object (as the `clone()` in `HashMap` class)?
What about other objects referred to in the elements? How deep do you want your clone? If your map elements don't have any deep references and/or everything is `Serializable`, you can serialize the map via `ObjectOutputStream` into a `ByteArrayOutputStream` and then deserialize it right away. The only other alternative is to do it manually.
Once you know your key/value pair elements are cloneable: ``` HashMap<Foo, Bar> map1 = populateHashmap(); HashMap<Foo, Bar> map2 = new HashMap<Foo, Bar>(); Set<Entry<Foo, Bar>> set1 = map1.entrySet(); for (Entry<Foo, Bar> e : l) map2.put(e.getKey().clone(), e.getValue().clone()); ```
clone utility for HashMap in java
[ "", "java", "" ]
What is a secure way of storing an a username and password (not asp.net membership details) within a database table that needs to be pulled out and decrypted to use for passing to a webservice. Each way I think about the problem I find security holes as the username and password need to be in plain text before being passed to the webservice.
Some suggestions: For storing the data 1. Encrypt the data (CryptoAPI calls are best) when you insert 2. Make sure you have encryption enabled between client and SQL Server 3. if you are using SQL 2008 enable the encryption of the MDF/LDF file Passing to the web service 1. If you are using .NET there is the SecureString to keep it secure in memory in your app. 2. Make sure the web service uses SSL to secure over the wire
IMHO is that you never unencript data... Use a 1 way encrytion to encrypt the data before you first save it, use this on password and user name. When the user logs on you encrpt the username and password and then check that the encrypted values match on the DB. I.e you do not need to unencrpt. Because its one way encryption is very hard to decrpy (some say its just takes to long to make it worth hacking) thats why is one way... MS encrypto class offers 1 way encryption. hope this helps Jules
SQL Server - Storing Sensitive Data
[ "", "asp.net", "sql", "web-services", "security", "" ]
How do I overload a destructor?
You can't. There is only one destructor per class in C++. What you can do is make a private destructor and then have several public methods which call the destructor in new and interesting ways. ``` class Foo { ~Foo() { ... } public: DestroyFoo(int) { ... }; DestroyFoo(std::string) { ... } }; ```
Overloading means having several functions with the same name which take different arguments. Like `swap(int &a, int &b)` and `swap(double &a, double &b)`. A destructor takes no arguments. Overloading it would not make sense. If you need to do different things when destroying an object depending on certain circumstances, then you just need the appropriate if statements in your destructor to check for those circumstances.
How to overload a destructor?
[ "", "c++", "" ]
is any such library available either commercial or open source?
As of today, there is no such open source library.
Just wanted to update this thread and note that we've created such a library at Frozen Mountain; it's called [IceLink](http://www.frozenmountain.com/downloads#icelink). The server portion (STUN/TURN, which is used for NAT traveral and IP discovery) is available on Java (in addition to .NET, Mac, etc) and there's a full Java library implementation for the actual P2P communication and audio/video encoding/decoding/rendering. It's also WebRTC-compliant, and communicates nicely with Chrome, etc. We've released out VP8 Java wrapper as well: <https://jvp8.codeplex.com/> (Disclaimer: I work @ FM).
java p2p video library?
[ "", "java", "web-services", "web-applications", "" ]
So I have some C++ code for back-tracking nodes in a BFS algorithm. It looks a little like this: ``` typedef std::map<int> MapType; bool IsValuePresent(const MapType& myMap, int beginVal, int searchVal) { int current_val = beginVal; while (true) { if (current_val == searchVal) return true; MapType::iterator it = myMap.find(current_val); assert(current_val != myMap.end()); if (current_val == it->second) // end of the line return false; current_val = it->second; } } ``` However, the `while (true)` seems... suspicious to me. I know this code works, and logically I know it should work. However, I can't shake the feeling that there should be some condition in the `while`, but really the only possible one is to use a `bool` variable just to say if it's done. Should I stop worrying? Or is this really bad form. **EDIT**: Thanks to all for noticing that there is a way to get around this. However, I would still like to know if there are other valid cases.
I believe that there are cases where it's fine for seemingly infinite loops to exist. However this does not appear to be one of them. It seems like you could just as easily write the code as follows ``` while (current_val != searchVal ) { MapType::iterator it = myMap.find(current_val); assert(current_val != myMap.end()); if (current_val == it->second) // end of the line return false; current_val = it->second } return true; ``` This seems to express the true intent of the loop better
My two cents is: code should be [self-documenting](http://en.wikipedia.org/wiki/Self-documenting). That is, when given a piece of code, I'd rather be able to look and tell the programmer's intent then have to read comments or trudge through the surrounding code. When I read: ``` while(true) ``` That tells me the programmer wanted an infinite loop; that the end condition couldn't be specified. This is the programmers intent in some circumstances; a server loop for instance, and that is when it should be used. In the above code, the loop isn't meant to be forever, it has a clear end condition, and in order to be semantically clear, as others have pointed out: ``` while (currentVal != searchVal) ``` works, so the while(true) is clearly inferior and should be avoided in this instance.
Are endless loops in bad form?
[ "", "c++", "language-agnostic", "coding-style", "infinite-loop", "" ]
I'm coming from a Java background, with its class-based inheritance model, trying to get my head around Javascript's prototype-based inheritance model. Part of what is throwing me off, I think is that I have Java's meaning of "this" solidly in mind - and Javascript's "this" is a very different beast. I understand that Javascript's "this" always refers to the function's caller, not the scope in which the function was defined - I mean, I have read that and understand superficially what it means. But I would like to have the understanding more deeply, and I think having another name for it would help. How do you think about JS "this"? Do you make a mental replacement every time you run across it? If so - what word or phrase do you use?
`this` might be reasonably renamed to `context` in Javascript. It's really referring to an execution context for the current scope, and while that context *can* be an instance of a class, it certainly doesn't have to be — it can be any object at all, and it can be modified at run-time. Proof that there is no guarantee whatsoever that a "method" in Javascript is operating on an instance of the "class" in which it is defined: ``` function Cat(){ this.texture = 'fluffy'; this.greet = function(){ alert("Pet me, I'm " + this.texture); } } var cat = new Cat(); // Default to using the cat instance as the this pointer cat.greet(); // Alerts "Pet me, I'm fluffy" // Manually set the value of the this pointer! cat.greet.call({texture: 'scaly'}); // Alerts "Pet me, I'm scaly" ``` It's important to note there that **the value of the `this` object is completely independent of where the containing function is defined**.
One possible alternative name would be `owner`. This would lead your mind in the direction that the owner can change depending on what code you are executing. This example is from [quirksmode](http://www.quirksmode.org/js/this.html): In JavaScript `this` always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to. In the following code, ``` function doSomething() { this.style.color = '#cc0000'; } ``` and ``` element.onclick = doSomething; ``` , `owner` points to the object that contains the method when it is executed. ``` ------------ window -------------------------------------- | / \ | | | | | this | | ---------------- | | | | HTML element | <-- this ----------------- | | ---------------- | | doSomething() | | | | | ----------------- | | -------------------- | | | onclick property | | | -------------------- | | | ---------------------------------------------------------- ```
What would be a better name for Javascript's "this"?
[ "", "javascript", "syntax", "this", "" ]
When i run an .exe file it prints stuff out to the screen. I don't know the specific line of where i want printed out but is there a way I can get python to print the next line after one that says "Summary" ? I know that is in there when it prints and I need the info right after. Thanks!
Really simple Python solution: ``` def getSummary(s): return s[s.find('\nSummary'):] ``` This returns everything after the first instance of **Summary** If you need to be more specific, I'd recommend regular expressions.
actually ``` program.exe | grep -A 1 Summary ``` would do your job.
Python and reading lines
[ "", "python", "printing", "command-prompt", "" ]
Ok I have an issue. I have a Linux web server (RHEL 4 with apache 2) that is used to house an application. Part of this application is a set of php scripts. I created a script that accepts some form variables and then downloads a file to the user. Here si the code: ``` header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.$destFileName); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($fullPath)); ob_clean(); flush(); readfile($fullPath); ``` This all works fine, and the file gets downloaded. But there is a problem. These files are being downloaded from the Linux box, to a Windows machine (ALWAYS). The problem is the encoding. When you look at the file on the Linux box all the text is aligned and all the columns look fine. (The files are just flat text files). But when the file gets downloaded onto the Windows box, and opened in Notepad, the file is all fouled up, and nothing is aligned. You also see weird charactors (the ones that look like a box, but that is just the generic representation for the unknow charactor). When this file is imported into another program, it does not work. However, when I open the file up in WordPad, all the text look correct. If I save it from wordpad it will import correctly, and look correct in Notpad. I don't have much knowlege on file encoding, so any information on how I can encode the file before sending to the user for download would be great. I did try replacing the `readfile($fullPath);` with: ``` $handle = @fopen($fullPath, "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle); $buffer = str_replace('\n', '\r\n', $buffer); echo $buffer; } fclose($handle); } ``` Thanks!
There's an issue with the following line: ``` $buffer = str_replace('\n', '\r\n', $buffer); ``` You'd need to use double quotes there. "\n" is newline. '\n' is the literal char sequence backslash-n: ``` # php -r "var_dump('\n', \"\n\");" string(2) "\n" string(1) " " ```
There is a Unix utility 'unix2dos' and 'dos2unix' that might help. You could call it from php as a system call. Or, I'm sure there is a php version of the same thing. But I'm not a php guy.
Fix file endcoding when downloading a file from Linux to Windows in php
[ "", "php", "linux", "text", "encoding", "character-encoding", "" ]
Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null. Example input csv, fields 'c' and 'd' are nullable: ``` a|b|c|d 1|2|| 1|2|3|4 3|4|| 2|3 ``` In something like the script below, how can I tell whether I am on the last line so I know how to handle it appropriately? ``` import csv reader = csv.reader(open('somefile.csv'), delimiter='|', quotechar=None) header = reader.next() for line_num, row in enumerate(reader): assert len(row) == len(header) .... ```
Basically you only know you've run out *after* you've run out. So you could wrap the `reader` iterator, e.g. as follows: ``` def isLast(itr): old = itr.next() for new in itr: yield False, old old = new yield True, old ``` and change your code to: ``` for line_num, (is_last, row) in enumerate(isLast(reader)): if not is_last: assert len(row) == len(header) ``` etc.
I am aware it is an old question, but I came up with a different answer than the ones presented. The `reader` object already increments the [`line_num`](https://docs.python.org/2/library/csv.html#csv.csvreader.line_num) attribute as you iterate through it. Then I get the total number of lines at first using `row_count`, then I compare it with the `line_num`. ``` import csv def row_count(filename): with open(filename) as in_file: return sum(1 for _ in in_file) in_filename = 'somefile.csv' reader = csv.reader(open(in_filename), delimiter='|') last_line_number = row_count(in_filename) for row in reader: if last_line_number == reader.line_num: print "It is the last line: %s" % row ```
Have csv.reader tell when it is on the last line
[ "", "python", "csv", "" ]
I need to get the X,Y coordinates (relative to the document's top/left) for a DOM element. I can't locate any plugins or jQuery property or method that can give these to me. I can get the top and left of the DOM element, but that can be either relative to its current container/parent or to document.
you can use [Dimensions](http://plugins.jquery.com/project/dimensions) plugin [Deprecated... included in jQuery 1.3.2+] > **offset()** > Get the current offset of the first matched element, in pixels, relative to the **document**. > > **position()** > Gets the top and left position of an element relative to its **offset parent**. knowing this, then it's easy... (using my little [svg project](https://stackoverflow.com/questions/536676) as an [example page](https://github.com/balexandre/Draggable-Line-to-Droppable/blob/master/index.htm)) ``` var x = $("#wrapper2").offset().left; var y = $("#wrapper2").offset().top; console.log('x: ' + x + ' y: ' + y); ``` output: ``` x: 53 y: 177 ``` hope it helps what you're looking for. **here's an image of offset() and position()** using [XRay](https://addons.mozilla.org/en-US/firefox/addon/1802) ![alt text](https://i.stack.imgur.com/buCcL.png) using [Web Developer](https://addons.mozilla.org/en-US/firefox/addon/60) toolbar ![alt text](https://i.stack.imgur.com/fFTEm.png)
My solution is a plugin with "workarounds" :+D . But Works! ``` jQuery.fn.getPos = function(){ var o = this[0]; var left = 0, top = 0, parentNode = null, offsetParent = null; offsetParent = o.offsetParent; var original = o; var el = o; while (el.parentNode != null) { el = el.parentNode; if (el.offsetParent != null) { var considerScroll = true; if (window.opera) { if (el == original.parentNode || el.nodeName == "TR") { considerScroll = false; } } if (considerScroll) { if (el.scrollTop && el.scrollTop > 0) { top -= el.scrollTop; } if (el.scrollLeft && el.scrollLeft > 0) { left -= el.scrollLeft; } } } if (el == offsetParent) { left += o.offsetLeft; if (el.clientLeft && el.nodeName != "TABLE") { left += el.clientLeft; } top += o.offsetTop; if (el.clientTop && el.nodeName != "TABLE") { top += el.clientTop; } o = el; if (o.offsetParent == null) { if (o.offsetLeft) { left += o.offsetLeft; } if (o.offsetTop) { top += o.offsetTop; } } offsetParent = o.offsetParent; } } return { left: left, top: top }; }; ``` Usage: ``` var p = $("#wrapper2").getPos(); alert("top:"+p.top+"; left:"+p.left); ```
jQuery x y document coordinates of DOM object
[ "", "javascript", "jquery", "user-interface", "location", "" ]
I have always wondered, if a PHP session times out during the middle of executing a script, will the contents of the $\_SESSION array still be available until script execution ends? For example: ``` session_start(); if(! isset($_SESSION['name'])) { echo 'Name is not set'; exit; } // imagine there is a bunch of code here and that the session times out while // this code is being executed echo 'Name is ', $_SESSION['name']; // will this line throw an error? ``` Is it practical to copy session variables to the local scope so I can read them later on in the script without having to keep checking for a session time out? Something like: ``` session_start(); if(isset($_SESSION['name'])) { $name = $_SESSION['name']; } else { echo 'Name is not set'; exit; } // bunch of code here echo 'Name is ', $name; ```
don't worry about such things. Nothing will happen to the session. It's initialised by `sessioni_start()` and `$_SESSION` will be always available within your script.
The default three-hour session lifetime is reset each time you open the session (see [`session_cache_expire`](http://us.php.net/manual/en/function.session-cache-expire.php)), so the only way a session could time out in the middle of a request is if a request takes three hours to process. By default PHP requests time out after just 30 seconds, so there's no danger of session expiry during a request. Furthermore, the `$_SESSION` variable won't suddenly change in the middle of a request. It's populated when the session starts, and that's it.
What happens to the $_SESSION array if a PHP session times out in the middle of a request?
[ "", "php", "session", "session-timeout", "" ]
When I entered my current (employer's) company a new database schema was designed and will be the base of a lot of the future tools that are/will be created. With my limited SQL knowledge I think the table is rather well designed. My only concern is that almost every table has a multy-part primary key. Every table has at least a CustomerId and key of it's own. While these are indeed defining for a certain record, I have the feeling that multiple keys (we're talking quadruple here) are very inefficient. Today I was seeing some unimaginable CPU usage over a simple, repeated query that joins two tables, selects a single string field from the first and distincts them. ``` select distinct(f.FIELDNAME) as fieldName from foo f inner join bar b on f.id = b.fId where b.cId = @id; ``` Checking the execution plan (I'm no EP Hero) I noticed that there are three major CPU points. The distinct (as expected) and two seeks over the indeces. I would personally think that the indices seek should be extremely fast, but they take up 18% of the cost each. Is this normal? Is it due to the (quadruple) clustered indexes? **--UPDATE--** The query is used for creating a Lucene index. It's a one-time processing that happens about weekly (sounds contradictive, I know). I can't re-use any results here as far as I see.
Could you please run the following queries and post their output: ``` SELECT COUNT(*), COUNT(DISTINCT fieldname) FROM foo SELECT COUNT(*), COUNT(DISTINCT cId), COUNT(DISTINCT fId) FROM bar ``` This will help to estimate which indexes best suit your needs. Meanwhile make sure you have the following indexes: ``` foo (FIELDNAME) bar (cId, fId) ``` and rewrite your query: ``` SELECT DISTINCT(fieldname) FROM foo f WHERE EXISTS ( SELECT 1 FROM bar b WHERE b.fId = f.id AND b.cId = @id ) ``` This query should use an index on `f.FIELDNAME` to build the `DISTINCT` list and the index on `bar` to filter out the non-existent values.
This kind of query looks familiar. Im guessing here, but, it's probably populating a combo box on a web/winform ui that is being hit pretty hard. Perhaps you should be caching the results on the application side so you don't end up executing it so often. Worse case scenario you could cache this on sql servers side, but its a massive kludge.
Is this execution plan a motivation for re thinking my primary keys
[ "", "sql", "clustered-index", "" ]
A comment to [What's wrong with this fix for double checked locking?](https://stackoverflow.com/questions/945232/whats-wrong-with-this-fix-for-double-checked-locking) says: > The issue is that the variable may be > assigned before the constructor is run > (or completes), not before the object > is allocated. Let us consider code: ``` A *a; void Test() { a = new A; } ``` To allow for more formal analysis, let us split the a = new A into several operations: ``` void *mem = malloc(sizeof(A)); // Allocation new(mem) A; // Constructor a = reinterpret_cast<A *>(mem); // Assignment ``` Is the comment quoted above true, and if it is, in what sense? Can Constructor be executed after the Assignment? If it can, what can be done against it when guaranteed order is needed because of MT safety?
The issue isn't so much when code executes, but more to do with write-ordering. Let's suppose: ``` A() { member = 7; } ``` Then later: ``` singleton = new A() ``` This results in code that does an allocation, a write to memory (member), and then a write to another memory location (singleton). Some CPU's can re-order writes such that the write to member will not be visible until after the write to singleton - in essence, code running on other CPU's in the system could have a view of memory where singleton is written to, but member is not.
`a` is a global object with static storage duration so it's going to be initialised in some pre-allocated storage sometime before the body of main get executed. Assuming that a call to Test isn't the result of some static object construction weirdness, `a` will be full constructed by the time Test is called. ``` a = new A; ``` This slightly unusual assignment isn't going to be (only) a standard copy assignment operation as you are assigning a pointer to `A` to a, not an object or reference. Whether it actually compiles and what exactly it calls depends on whether `A` has an assignment operator that takes a pointer to `A`, or something implicitly convertable from a pointer to `A` or whether `A` has an non-explicit constructor that takes a pointer to `A` (or a pointer to a base class of `A`). Post edit, your code does something rather different! Conceptually, it does something more like this: ``` A *tmpa; void *mem = ::operator new( sizeof(A) ); // ( or possibly A::operator new ) try { tmpa = new (mem) A; // placement new = default constructor call } catch (...) { ::operator delete( mem ); throw; } a = tmpa; // pointer assignment won't throw. ``` The peril with writing something out like this is that your implicitly adding a lot of sequence points that just aren't there in the original, and in addition the compiler is allowed to generate code that doesn't look like this so long as it behaves 'as if' it were written by this as far as the executing program could determine. This 'as if' rule only applies to the executing thread as the (current) language says nothing about interaction with other threads works. For this you need to use the specific behaviour guarantees (if any) proided by your implementation.
Can assignment be done before constructor is called?
[ "", "c++", "multithreading", "constructor", "multicore", "sequence-points", "" ]
In addition to this question: [iPhone network performance](https://stackoverflow.com/questions/1049050/iphone-network-performance), I would like to know if there are any (very) good XML parsing frameworks out there for PHP. PHP has great XML support already, but I wonder if it could be better (in terms of performance, memory usage, etc).
[XMLReader](http://nl2.php.net/manual/en/book.xmlreader.php) and [XMLWriter](http://nl2.php.net/manual/en/book.xmlwriter.php) are probably your best options when it comes to performance. These 2 have the benefit of not needing the full DOM tree of your xml in memory, although they aren't as convenient to work with.
There are several: * [SimpleXML](https://www.php.net/simplexml); * [DOMDocument](https://www.php.net/manual/en/class.domdocument.php); * [xml\_parse](https://www.php.net/manual/en/function.xml-parse.php); and * others. SimpleXML is pretty easy to use but has some serious limitations, like an apparent inability to deal with elements that contain both text and other elements, for which I've had to use DOMDocument instead.
XML frameworks in PHP
[ "", "php", "xml", "performance", "frameworks", "" ]
What are excellent C++ IDE options that support the new standard c++0x (windows os friendly) besides visual .net 2010 (the beta is way too slow/clunky)?
While not supporting the full C++0x standard, much of the TR1 stuff is included in the [SP1 update to Visual Studio 2008](http://www.microsoft.com/downloads/details.aspx?FamilyId=FBEE1648-7106-44A7-9649-6D9F6D58056E&displaylang=en). The SP1 update includes the [feature pack](http://blogs.msdn.com/vcblog/archive/2008/04/07/visual-c-2008-feature-pack-released.aspx) that was released last year.
Now, two years after the question was asked, VisualStudio 2010 supports the following core language features. 1. Lambda functions 2. Rvalue references (move semantics and perfect forwarding). 3. type inference (`auto` and `decltype`) 4. `nullptr` 5. Trailing return type specification `auto f() -> int` 6. `static_assert`
What Windows C++ IDEs support the new C++0X standard?
[ "", "c++", "windows", "ide", "c++11", "" ]
The windows form that I designed has 1 label. The text of this label changes dynamically depending on what data the user selects. Currently i'm creating a string and assigning it to the label's text property. I need a way to make certain parts of the string that I am creating bold. How can I accomplish this in c#?
You would need to use a custom control for this. You could either write your own or you can use an existing control. On CodeProject there is a control, [GMarkupLabel](http://www.codeproject.com/KB/miscctrl/GMarkupLabel.aspx), that looks good.
You can't format the text inside a `Label`. However, you could use a `RichTextBox` and make it look like a `Label`...
How can I programmatically make certain parts of a label, in a windows form, bold?
[ "", "c#", "winforms", "fonts", "" ]
I have a Dictionary to map a certain type to a certain generic object for that type. For example: ``` typeof(LoginMessage) maps to MessageProcessor<LoginMessage> ``` Now the problem is to retrieve this generic object at runtime from the Dictionary. Or to be more specific: To cast the retrieved object to the specific generic type. I need it to work something like this: ``` Type key = message.GetType(); MessageProcessor<key> processor = messageProcessors[key] as MessageProcessor<key>; ``` Hope there is a easy solution to this. Edit: I do not want to use Ifs and switches. Due to performance issues I cannot use reflection of some sort either.
Does this work for you? ``` interface IMessage { void Process(object source); } class LoginMessage : IMessage { public void Process(object source) { } } abstract class MessageProcessor { public abstract void ProcessMessage(object source, object type); } class MessageProcessor<T> : MessageProcessor where T: IMessage { public override void ProcessMessage(object source, object o) { if (!(o is T)) { throw new NotImplementedException(); } ProcessMessage(source, (T)o); } public void ProcessMessage(object source, T type) { type.Process(source); } } class Program { static void Main(string[] args) { Dictionary<Type, MessageProcessor> messageProcessors = new Dictionary<Type, MessageProcessor>(); messageProcessors.Add(typeof(string), new MessageProcessor<LoginMessage>()); LoginMessage message = new LoginMessage(); Type key = message.GetType(); MessageProcessor processor = messageProcessors[key]; object source = null; processor.ProcessMessage(source, message); } } ``` This gives you the correct object. The only thing I am not sure about is whether it is enough in your case to have it as an abstract MessageProcessor. Edit: I added an IMessage interface. The actual processing code should now become part of the different message classes that should all implement this interface.
The following seems to work as well, and it's a little bit shorter than the other answers: ``` T result = (T)Convert.ChangeType(otherTypeObject, typeof(T)); ```
Cast to generic type in C#
[ "", "c#", "generics", "casting", "" ]
I have a Hashmap that, for speed reasons, I would like to not require locking on. Will updating it and accessing it at the same time cause any issues, assuming I don't mind stale data? My accesses are gets, not iterating through it, and deletes are part of the updates.
Yes, it will cause major problems. One example is what could happen when adding a value to the hash map: this can cause a rehash of the table, and if that occurs while another thread is iterating over a collision list (a hash table "bucket"), that thread could erroneously fail to find a key that exists in the map. `HashMap` is explicitly unsafe for concurrent use. Use [`ConcurrentHashMap`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html) instead.
The importance of synchronising or using [ConcurrentHashMap](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html) can not be understated. I was under the misguided impression up until a couple of years ago that I could get away with only synchronising the put and remove operations on a HashMap. This is of course very dangerous and actually results in an infinite loop in HashMap.get() on some (early 1.5 I think) jdk's. What I did a couple of years ago (and really shouldn't be done): ``` public MyCache { private Map<String,Object> map = new HashMap<String,Object>(); public synchronzied put(String key, Object value){ map.put(key,value); } public Object get(String key){ // can cause in an infinite loop in some JDKs!! return map.get(key); } } ``` **EDIT**: thought I'd add an example of what **not** to do (see above)
Hashmap concurrency issue
[ "", "java", "concurrency", "" ]
I have a project that is deployed to production as a windows service. However for local development purposes it would be useful to run it as a console application. At the moment I have a class Called `ReportingHost` that provides my core functionality, And a class called ReportingServiceHost that inherits from `ServiceBase` and allows me to run the application as a service. There is also a program class with a main method that calls `ServiceBase.Run` on my ReportingServiceHost. I think I need to write a `ReportingConsoleHost` class that allows me to run the functionality in a console. Then I need to modify my `Main` to react to a command line switch and choose one or the other. These are the two bits I am having trouble with. I have had a look at [this](http://msdn.microsoft.com/en-us/library/ms731758.aspx) and attempted to use that code but my app exits immediately, it doesn't show a console window and it doesn't wait for Enter before closing. Part of the problem is that I dont have a deep understanding of how these things work. a definitive pattern for splitting my functionality, my two different ways of running that functionality, and a main method that chooses one of these ways based on a command line argument is what I am hoping to achieve.
I suspect your test project was configured as a windows exe, not a console exe. With a windows exe `Console.ReadLine` will return immediately. To have a console exe that works both as a service and at the command line, start it as a service project (in Visual Studio) - and add a check on `Environment.UserInteractive` - i.e. ``` static void Main() { if(Environment.UserInteractive) { // code that starts the listener and waits on ReadLine } else { // run the service code that the VS template injected } } ``` You can of course also use a command line switch. I have example on [microsoft.public.dotnet.languages.csharp](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/4d45e9ea5471cba4) that acts as: * an installer / uninstaller * a service * a console-mode app depending on the switches
I have done this before by implementing a normal Windows Service (by deriving from ServiceBase), but putting a check in the main method to check for a command line argument. If the args contain `/console`, start the console version, otherwise start the service. Something like this: ```` ``` internal class MyService : ServiceBase { internal static void Main(string[] args) { if (args.Length == 0) { // run as a service.... ServiceBase[] servicesToRun = new ServiceBase[] {new MyService()}; Run(servicesToRun); } else { // run as a console application.... } } } ``` ````
What is the accepted pattern for an application that can be run as a service or as a console application
[ "", "c#", "wcf", "windows-services", "" ]
For purposes of testing compression, I need to be able to create large files, ideally in text, binary, and mixed formats. * The content of the files should be neither completely random nor uniform. A binary file with all zeros is no good. A binary file with totally random data is also not good. For text, a file with totally random sequences of ASCII is not good - the text files should have patterns and frequencies that simulate natural language, or source code (XML, C#, etc). Pseudo-real text. * The size of each individual file is not critical, but for the set of files, I need the total to be ~8gb. * I'd like to keep the number of files at a manageable level, let's say o(10). For creating binary files, I can new a large buffer and do System.Random.NextBytes followed by FileStream.Write in a loop, like this: ``` Int64 bytesRemaining = size; byte[] buffer = new byte[sz]; using (Stream fileStream = new FileStream(Filename, FileMode.Create, FileAccess.Write)) { while (bytesRemaining > 0) { int sizeOfChunkToWrite = (bytesRemaining > buffer.Length) ? buffer.Length : (int)bytesRemaining; if (!zeroes) _rnd.NextBytes(buffer); fileStream.Write(buffer, 0, sizeOfChunkToWrite); bytesRemaining -= sizeOfChunkToWrite; } fileStream.Close(); } ``` With a large enough buffer, let's say 512k, this is relatively fast, even for files over 2 or 3gb. But the content is totally random, which is not what I want. For text files, the approach I have taken is to use [Lorem Ipsum](http://en.wikipedia.org/wiki/Lorem_ipsum), and repeatedly emit it via a StreamWriter into a text file. The content is non-random and non-uniform, but it does has many identical repeated blocks, which is unnatural. Also, because the Lorem Ispum block is so small (<1k), it takes many loops and a very, very long time. Neither of these is quite satisfactory for me. I have seen the answers to [Quickly create large file on a windows system?](https://stackoverflow.com/questions/982659/quickly-create-large-file-on-a-windows-system). Those approaches are very fast, but I think they just fill the file with zeroes, or random data, neither of which is what I want. I have no problem with running an external process like contig or fsutil, if necessary. The tests run on Windows. Rather than create new files, does it make more sense to just use files that already exist in the filesystem? I don't know of any that are sufficiently large. What about starting with a single existing file (maybe c:\windows\Microsoft.NET\Framework\v2.0.50727\Config\enterprisesec.config.cch for a text file) and replicating its content many times? This would work with either a text or binary file. Currently I have an approach that sort of works but it takes too long to run. Has anyone else solved this? Is there a much faster way to write a text file than via StreamWriter? Suggestions? **EDIT**: I like the idea of a Markov chain to produce a more natural text. Still need to confront the issue of speed, though.
I think you might be looking for something like a [Markov chain](http://en.wikipedia.org/wiki/Markov_chain) process to generate this data. It's both stochastic (randomised), but also structured, in that it operates based on a [finite state machine](http://en.wikipedia.org/wiki/Finite_state_machine). Indeed, Markov chains have been used for generating semi-realistic looking text in human languages. In general, they are not trivial things to analyse properly, but the fact that they exhibit certain properties should be good enough for you. (Again, see [Properties of Markov chains](http://en.wikipedia.org/wiki/Markov_chain#Properties_of_Markov_chains) section of the page.) Hopefully you should see how to design one, however - to implement, it is actually quite a simple concept. Your best bet will probably be to create a framework for a generic Markov process and then analyse either natural language or source code (whichever you want your random data to emulate) in order to "train" your Markov process. In the end, this should give you very high quality data in terms of your requirements. Well worth going to the effort, if you need these enormous lengths of test data.
For text, you could use the [stack overflow community dump](https://stackoverflow.com/questions/999185/is-there-a-script-or-program-that-will-efficiently-and-quickly-load-up-the-so-dum), there is 300megs of data there. It will only take about 6 minutes to load into a db with the app I wrote and probably about the same time to dump all the posts to text files, that would easily give you anywhere between 200K to 1 Million text files, depending on your approach (with the added bonus of having source and xml mixed in). You could also use something like the [wikipedia dump](http://en.wikipedia.org/wiki/Wikipedia_database), it seems to ship in MySQL format which would make it super easy to work with. If you are looking for a big file that you can split up, for binary purposes, you could either use a VM vmdk or a DVD ripped locally. **Edit** Mark mentions the project gutenberg download, this is also a really good source for text (and audio) which is available for [download via bittorrent](http://www.gutenberg.org/wiki/Gutenberg:The_CD_and_DVD_Project).
How can I quickly create large (>1gb) text+binary files with "natural" content? (C#)
[ "", "c#", ".net", "windows", "testing", "filesystems", "" ]
My self as a Front End Developer, for many years I have resolved many browser and CSS related issues for Developers coding in ASP, PHP and XSLT. I just want some Front End Designers and Developers to point out, which things to be consider when there is some Design issue in Programming. Firebug is one option.
Designers and developers often have a symbiotic relationship. In my opinion, all developers should have (at least) very basic design skills and all designers should know a thing or two about code. I don't mean that the two professions should be able to do the other's job; just that each should have a general idea of how the other goes about solving problems. Much of the animosity frequently seen between form and function comes from either side not understanding the other. On a more specific level, a developer can benefit from knowing HTML and CSS in that they can see what the designer is doing and make revisions if necessary. Better communication will result in better products, and the two professions can't communicate without knowing the same languages.
As a Front End Designer the key things that Backend Developers tend to not be aware of are: * **Internet Explorer** can and will take totally valid HTML, CSS & JS and botch the most basic expected behaviors * Develop / Test interfaces in (Firefox,Safari,Opera,Chrome,Arora etc.) first! then be sure to review in IE6, IE7, and IE8... * Take the HTML, CSS, & ECMAScript Specs with a grain of salt. "Guideline" often seems like the more appropriate term vs. Spec. * You've heard many a battle of Div's vs. Table's. Div's are great but sooner or later you will encounter a need to wrap something up in a table to stop browser X from wrapping your content when you clearly told it not to. It is ok to "give up" once in a while. Thus as an end result you want to pass information along to the Developers that help clarify what they really need to know (and hopefully save them the frustrating steps along the way). Although sites like *[A List Apart](http://www.alistapart.com/)* have great articles w/code, sometimes the solution gets lost in the story. For dealing with bugs I recommend this [**Knol**](http://knol.google.com/k/-/web-browser-bugs/) which links back into **[this browser bug list](http://webbugtrack.blogspot.com/)**. The Knol doesn't provide much info but it does provide an organized index to find what bug is causing you pain. Otherwise for general info check out the various developer blogs. [Snook.ca](http://snook.ca), [PPK's QuirksBlog](http://www.quirksmode.org/blog/), [The Man in Blue](http://themaninblue.com) etc.
What programmer should do before getting help from Designer in Design Issue?
[ "", "php", "asp.net", "jsp", "" ]
I'm trying to dump the contents of a particular schema in one IBM DB2 UDB server into an sql text file (much like the mysqldump functionality of mysql). I came across db2look, but it only dumps the structure of the schema (only ddl, no dml). So how can I get my thing done? jrh.
You could use [SQquirreL](http://www.squirrelsql.org/), an SQL Client implemented in Java, to accomplish this. In its "Objects"-Tree you would select all desired tables and select "Scripts > Create Data Script" from the context menu.
What you're looking for is the [db2move](https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0002079.html) command. For a particular schema you should use the "sn" switch. So for example to export the data: ``` db2move [your_db_name] EXPORT -sn [your_schema_name] ``` There are many options and switches available for db2move depending on exactly what you want to do. If db2move is not exactly what you need, you can review the table of [Data Movement Options available in DB2](https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.dm.doc/doc/r0024482.html).
SQL Dump from DB2
[ "", "sql", "db2", "dump", "" ]
Suppose I have: ``` unsafe { byte* start = GetStartLocation(); int something = start[4]; } ``` What is `something`? The value of the memory address 4 bytes down from start?
Say `start` points to memory location 0x12345678, and memory looks like this: ``` 0x12345678 0x12 0x12345679 0x34 0x1234567a 0x56 0x1234567b 0x78 0x1234567c 0x9a 0x1234567d 0xbc ``` then `something` equals `0x9a`. The fact that `something` has type `int` doesn't matter to how `start[4]` is interpreted - it gets the `byte` value of the byte 4 locations away from `start`.
The value of something is the byte value of offset 4 from start widened to an int type. It's equivalent to the following code ``` byte temp = start[4]; int something = temp; ```
Unsafe pointer/array notation in C#
[ "", "c#", "pointers", "" ]
Can I attach any event handlers to HTML hidden input fields? Basically I want to run a function when a hidden input field value changes.
Events are only triggered when the user performs the event in the browser, so if it's `<input type="hidden">` or an `<input>` hidden by CSS, the user won't be able to trigger events to your input. The only way you would get onchange to work is if you manually trigger onchange in Javascript. A quick example of this: ``` <form name="f" onsubmit="document.f.h.value='1'; document.f.h.onchange(); return false;" > <input type="hidden" name="h" value="0" onchange="alert(document.f.h.value);" /> <input type="submit" /> </form> ```
Yes, certain browsers (such as Firefox) will fire an `onclick` or `onfocus` event on hidden elements when they're activated via an `accesskey` attribute (meant to provide a keyboard hotkey to jump to an input). Open the below in firefox, focus the frame, then strike `Alt`+`Shift`+`x` (Windows and Linux) or `Ctrl`+`Alt`+`x` (Mac). ``` <input type="hidden" accesskey="x" onclick="alert('clicked!');" /> ```
Does HTML Hidden control have any events? Like onchange or something?
[ "", "javascript", "html", "dom", "" ]
I know that one of them is bitwise and the other is logical but I can not figure this out: ``` Scanner sc = new Scanner(System.in); System.out.println("Enter ur integer"); int x=sc.nextInt(); if(x=0)//Error...it can not be converted from int to boolean System.out.println("..."); ``` The error means that `x` cannot be converted to `boolean` or the result of `x=0` can not be converted to `boolean`.
== checks for equality. = is assignment. What you're doing is: `if( x = Blah )` - in Java this statement is illegal as you can not test the state of an assignment statement. Specifically, Java does not treat assignment as a boolean operation, which is required in an if statement. This is in contrast with C/C++, which DOES allow you to treat assignment as a boolean operation, and can be the result of many hair-pulling bugs.
When you write 'x = 0' you are saying "Store 0 in the variable x". The return value on the whole expression is '0' (it's like this so you can say silly things like x = y = 0). When you write 'x == 0' it says "Does x equal 0?". The return value on this expression is going to be either 'true' or 'false'. In Java, you can't just say if(0) because if expects a true/false answer. So putting if(x = 0) is not correct, but if(x == 0) is fine.
What is the difference between '==' and '='?
[ "", "java", "operators", "" ]
I have arrays of points that contain series data (x & y). Is there a quick way to output these arrays into an excel file? Thanks
Output the data to a file, separating the array elements with commas. Then save the file as name.csv Use FileWriter to output the file.
One of this nice things about range object is that you can assign a two dimensional array to directly to the value property. It *is* important that the range be the same number of cells as the array has elements. ``` //using Excel = Microsoft.Office.Interop.Excel; String[,] myArr = new string[10, 10]; for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { myArr[x, y] = "Test " + y.ToString() + x.ToString(); } } Excel.Application xlApp = new Excel.Application(); xlApp.Visible = true; Excel.Workbook wb = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1); Excel.Range rng = ws.Cells.get_Resize(myArr.GetLength(0), myArr.GetLength(1)); rng.Value2 = myArr; ```
is there quick way to export an array to Excel file using C#?
[ "", "c#", "excel", "" ]
I'm hoping someone can point in the direction of some useful information pertaining to the best practices surrounding the use of Reflection in Java. The current project I'm supporting uses Oracle ADF Faces and we've found that based on the objectives at hand certain pages end up with a vast number of components which need to be initialized in the backing beans. One of the developers on the team devised a solution using reflection in the bean constructor to initialize all of the member components for a particular page. The concern has been raised that this may violate best practices and though it may save individual developers some time it may impact the performance of the application. Has anyone utilized reflection in this way? Is it acceptable or should the developers manually write out the code?
Reflection should be avoided when possible, because you should take care of some tasks that are normally of the compiler competence; furthermore, the use of reflection makes refactoring harder, because some tools doesn't work on reflection (think about eclipse's refactor). Reflection have an impact on performances, but I think this is a minor problem in respect of the mantainability issues. If you have a solution that doesn't use reflection, use it.
I generally opt for explicit initialization using a framework such as Spring. Over use of reflection can lead to code that's hard to maintain or at the very least difficult to read. Although reflection is faster with modern JVM's you still suffer a performance hit.
Using Java Reflection to initialize member variables
[ "", "java", "reflection", "jsf", "" ]
I have a Java program and I want to send a command from my Win32 application. Normally I'd use `WM_COPYDATA` but what options do I have with Java?
There are some ways to interoperate between Java and Windows. Ordered in power and difficulty: * For handling window messages, you could use Jawin - it even features a [demo of how to handle window messages](http://jawinproject.cvs.sourceforge.net/viewvc/jawinproject/jawin/demos/src/demos/petzold/chap03/HelloJava.java?revision=1.4&view=markup) - or something similar. Of course, if you bind your Java program to a library like Jawin, it will never run on a non-Windows machine * For simple interaction between Win32 and Java, a socket bound to listen only on localhost would be my favourite choice. The protocol may be simple, but I would prefer a plain text protocol for easier debugging. Be aware that a socket connection can break down if the user terminates a program. * You can use (local) web services, like suggested in other posts here. On both sides make sure that you use your Webservice/XML libaries to construct and parse the messages, it is far too easy to construct malformed XML if you do string concatenation. * You can put the functionality of your Windows program into a COM component and use a Java-to-COM bridge: Jacob or j-Interop are popular free libaries for this, j-Integra seems a popular choice for businesses with legacy systems. * You can put the functionality of your Java program into a COM component and use Sun's Java-ActiveX bridge. From my personal experience, this is a rather awkward option: Development of the Java-ActiveX bridge has stalled since 1.4, the installation of the ActiveX causes your Java component to be installed somewhere in the JRE directory and debugging your Java components inside the ActiveX container is rather cumbersome. **Sidenote:** if you are dealing with strings on both sides, always take into account that Java handles strings as something quite different from byte arrays. Especially if you are using Windows ANSI strings be aware that the characters 81, 8D, 8F, 90, and 9D are specified as undefined in the Windows-1252 codepage, therefore Java will produce question marks or exceptions if your Windows strings contain these elements. Therefore, if at all possible, use WChar strings on the Windows side or restrict yourself to safe characters.
You will need to create a network server, as explained by J16 SDiZ. * One simple way is to use [XML-RPC](http://en.wikipedia.org/wiki/XML-RPC). There are ready-made libraries for Java and just about any other language, and it's simple. We use it in our app. But really, any network protocol will do. * For very simple cases, you could also just create a file and poll it from the Java side. * You can also use named pipes: <http://www.coderanch.com/t/328057/Java-General-advanced/java/Use-Named-Pipe-IPC-between> * Then there's also [RMI](http://en.wikipedia.org/wiki/Java_remote_method_invocation), but that is probably overkill for your (simple) purpose. Finally, you could use JNI to directly access Window's native communication mechanism. Personally, I'd use XML-RPC or some other simple, standardized protocol.
How can I send a command to a running Java program?
[ "", "java", "winapi", "ipc", "" ]
I have a program that uses enum types. ``` enum Type{a,b,}; class A { //use Type }; class B { // also use that Type }; ``` 2 class are located in 2 different files. Should I put the type definition in a headfile or in class definition for each class?
If the enum is going to be used in more than one .cpp file, you should put it in a header file that will be included by each. If there's a common header file, you should use that, otherwise you may as well create a new header file for this enum
You should always attempt to limit the scope of types in C++, so the enum should probably be declaread at class scope. The enum will typically belong slightly more naturally in one class than the other - lets say class A, so you put it in the declaration of A in the a.h header: ``` // a.h class A { public: enum Type { a, b }; ... }; ``` Now you need to include a.h in the header that declares B: ``` // b.h #include "a.h" class B { public: void f( A::Type t ); // use the Type enum ... }; ```
Where to put the enum in a cpp program?
[ "", "c++", "" ]
I've done a bit of searching around and was unsuccessful in finding an ample solution. Specs are: OS X 10.5 with Apache/2.2.11 (Unix) mod\_ssl/2.2.11 OpenSSL/0.9.7l DAV/2 PHP/5.2.8 Error: Fatal error: Call to undefined function zip\_open() in /includes/admin\_functions.php on line 18 Thank you for your help!
Check your phpinfo(); The only reason the function would be undefined is if the extension was not properly installed. Ensure that it appears when you run your phpinfo() page.
your zip module is not configured properly or missing ``` sudo apt-get install php7.0-zip ```
zip_open(); undefined on PHP 5.2.8
[ "", "php", "zip", "" ]
> **Possible Duplicate:** > [Is there an equivalent to Trac written in PHP?](https://stackoverflow.com/questions/349241/is-there-an-equivalent-to-trac-written-in-php) Are there any PHP alternatives to Edgewall's Trac solution which works on Python, and not really portable?
There isn't really a single project that duplicates all features of Trac. Here are a couple of PHP applications you could look at to see if they do what you need: * <http://www.dotproject.net/> * <http://www.mantisbt.org/>
I'd try [The Bug Genie](http://www.thebuggenie.com/)
PHP alternative to trac?
[ "", "php", "" ]
I have a module that imports unittest and has some TestCases. I would like to accept some command-line options (for example below, the name of a data file), but when I try to pass the option I get the message `option -i not recognized`. Is it possible to have `unittest` + provide options to the app (note: I'm using `optparse` to handle the options)? Thanks. ``` $ python test_app_data.py -i data_1.txt option -i not recognized ``` ===================== follow-up: this is an implementation of the suggested solution: ``` import cfg_master #has the optparse option-handling code ... if __name__ == '__main__': #add you app's options here... options_tpl = ('-i', '--in_dir', '-o', '--out_dir') del_lst = [] for i,option in enumerate(sys.argv): if option in options_tpl: del_lst.append(i) del_lst.append(i+1) del_lst.reverse() for i in del_lst: del sys.argv[i] unittest.main() ```
Building on Alex's answer, it's actually pretty easy to do using [`argparse`](http://docs.python.org/library/argparse.html): ``` if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input', default='My Input') parser.add_argument('filename', default='some_file.txt') parser.add_argument('unittest_args', nargs='*') args = parser.parse_args() # TODO: Go do something with args.input and args.filename # Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone) sys.argv[1:] = args.unittest_args unittest.main() ``` I haven't tested all of the flags you can pass into unittest to see if they work or not, but passing test names in does work, e.g.: ``` python test.py --input=foo data.txt MyTest ``` Runs MyTest with `foo` and `data.txt`.
In your `if __name__ == '__main__':` section, which you're not showing us, you'll need to `optparse` and then `del sys.argv[1:]` before you pass control to `unittest` code, so that the latter code doesn't try to interpret your command line options *again* when you've already dealt with them. (It's a bit harder to have some options of your own *and* also pass some down to `unittest`, though it can be done if you do have such complex needs).
python, unittest: is there a way to pass command line options to the app
[ "", "python", "unit-testing", "" ]
What is the "correct" way of comparing a code-point to a Java character? For example: ``` int codepoint = String.codePointAt(0); char token = '\n'; ``` I know I can probably do: ``` if (codepoint==(int) token) { ... } ``` but this code looks fragile. Is there a formal API method for comparing `codepoints` to `chars`, or converting the `char` up to a `codepoint` for comparison?
A little bit of background: When Java appeared in 1995, the `char` type was based on the original "[Unicode 88](http://www.unicode.org/history/unicode88.pdf)" specification, which was limited to 16 bits. A year later, when Unicode 2.0 was implemented, the concept of surrogate characters was introduced to go beyond the 16 bit limit. Java internally represents all `String`s in UTF-16 format. For code points exceeding U+FFFF the code point is represented by a surrogate pair, i.e., two `char`s with the first being the high-surrogates code unit, (in the range \uD800-\uDBFF), the second being the low-surrogate code unit (in the range \uDC00-\uDFFF). From the early days, all basic `Character` methods were based on the assumption that a code point could be represented in one `char`, so that's what the method signatures look like. I guess to preserve backward compatibility that was not changed when Unicode 2.0 came around and caution is needed when dealing with them. To quote from the [Java documentation](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html): * The methods that only accept a char value cannot support supplementary characters. They treat char values from the surrogate ranges as undefined characters. For example, Character.isLetter('\uD840') returns false, even though this specific value if followed by any low-surrogate value in a string would represent a letter. * The methods that accept an int value support all Unicode characters, including supplementary characters. For example, Character.isLetter(0x2F81A) returns true because the code point value represents a letter (a CJK ideograph). Casting the `char` to an `int`, as you do in your sample, works fine though.
The [Character](http://java.sun.com/javase/6/docs/api/java/lang/Character.html) class contains many useful methods for working with Unicode code points. Note methods like [Character.toChars(int)](http://java.sun.com/javase/6/docs/api/java/lang/Character.html#toChars(int)) that return an array of chars. If your codepoint lies in the supplementary range, then the array will be two chars in length. How you want to compare the values depends on whether you want to support the full range of Unicode values. This sample code can be used to iterate through a String's codepoints, testing to see if there is a match for the supplementary character MATHEMATICAL\_FRAKTUR\_CAPITAL\_G (𝔊 - U+1D50A): ``` public final class CodePointIterator { private final String sequence; private int index = 0; public CodePointIterator(String sequence) { this.sequence = sequence; } public boolean hasNext() { return index < sequence.length(); } public int next() { int codePoint = sequence.codePointAt(index); index += Character.charCount(codePoint); return codePoint; } public static void main(String[] args) { String sample = "A" + "\uD835\uDD0A" + "B" + "C"; int match = 0x1D50A; CodePointIterator pointIterator = new CodePointIterator(sample); while (pointIterator.hasNext()) { System.out.println(match == pointIterator.next()); } } } ``` For Java 8 onwards [CharSequence.codePoints()](http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#codePoints--) can be used: ``` public static void main(String[] args) { String sample = "A" + "\uD835\uDD0A" + "B" + "C"; int match = 0x1D50A; sample.codePoints() .forEach(cp -> System.out.println(cp == match)); } ``` I created a [table](http://illegalargumentexception.blogspot.com/2009/05/java-rough-guide-to-character-encoding.html#javaencoding_javadatatypes) to help get a handle on Unicode string length and comparison cases that sometimes need to be handled.
Comparing a char to a code-point?
[ "", "java", "unicode", "" ]
I've creating a Java Swing application and I realized that I have many many components on a form. It's not that my interface is [cluttered](http://stuffthathappens.com/blog/2008/03/05/simplicity/), but nevertheless the total amount can be quite high (hundreds) because the user can enable additional parts of the interface and there have to be list-like repeating panels on the form. Additionally many components are wrapped into a [JXLayer](https://jxlayer.dev.java.net/), again increasing the number of visual components. Until now I couldn't detect any problems besides lagging during scrolling and resizing. * Are there any theoretical limits on the number of components? (I doubt it, but I also have to code in VB6, so I've been there...) * Are there any pratical limits? At work we have some medium-end workstations which perform fine at first sight, but how does Java/Swing react on low-end workstations or extreme counts of components? * Is there any way to profile the GUI of my application besides checking the subjective impression of the user? Are there any objective indicators I can look for (Like total time spent in `javax.swing.SwingCoreClassWhichContainsBottleneckCode` or something...)
Swing can handle a significant number of components with only memory limitations, particularly using simple components (text box, label, radio button etc). There are some tricks eg reducing the window size and wrapping everything in a JScrollPane, but generally standard techniques such as doing heavy processing in the background will be all you need. One of the features my company is working on involves a dialog with a repeating JPanel that contains a handful of labels and a button. We tested it on our old Mac Mini (intel core solo with 512mb ram) and creating 500 panels took a few seconds to load but after that scrolling through the panel list or adding new panels was not slow at all. For serious performance concerns look at [JTable](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTable.html) which is pretty highly optimised for displaying large amounts of data. It's a little tough to create custom renderers and editors, but not impossible.
Only the memory and the underlying OS limits the number of components. The practical limit is a bit user-subjective. Try splitting the UI into separate tabs or JFrames, this will limit the rendering overhead per screen. JVisualVM is quite good in profiling java application. You will need to remove the class filters to see the sun\* and javax\* classes profiled.
In what way do many graphical components affect the performance of a Swing GUI?
[ "", "java", "performance", "user-interface", "swing", "profiling", "" ]
How can I check whether another application is minimized or not? For instance in a loop like this: ``` foreach(Process p in processes) { // Does a process have a window? // If so, is it minimized, normal, or maximized } ```
``` [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl); private struct WINDOWPLACEMENT { public int length; public int flags; public int showCmd; public System.Drawing.Point ptMinPosition; public System.Drawing.Point ptMaxPosition; public System.Drawing.Rectangle rcNormalPosition; } if (p.MainWindowHandle != IntPtr.Zero) { if (p.MainWindowTitle.Contains("Notepad")) { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); GetWindowPlacement(p.MainWindowHandle, ref placement); switch (placement.showCmd) { case 1: Console.WriteLine("Normal"); break; case 2: Console.WriteLine("Minimized"); break; case 3: Console.WriteLine("Maximized"); break; } } } ```
There is no such thing as a minimized "application." The best alternative would be to check whether the application's Main Window is Iconic (minimized). [IsIconic](http://msdn.microsoft.com/en-us/library/ms633527(VS.85).aspx) can be used to check for the iconic state of a window. It will return 1 if a window is minimized. You can call this with [process.MainWindowHandle](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainwindowhandle.aspx).
How to check whether another app is minimized or not?
[ "", "c#", "" ]
Why doesn't .NET regex treat \n as end of line character? Sample code: ``` string[] words = new string[] { "ab1", "ab2\n", "ab3\n\n", "ab4\r", "ab5\r\n", "ab6\n\r" }; Regex regex = new Regex("^[a-z0-9]+$"); foreach (var word in words) { Console.WriteLine("{0} - {1}", word, regex.IsMatch(word)); } ``` And this is the response I get: ``` ab1 - True ab2 - True ab3 - False - False ab5 - False ab6 - False ``` Why does the regex match `ab2\n`? **Update:** I don't think [Multiline](https://msdn.microsoft.com/en-us/library/yd1hzczs%28v=vs.110%29.aspx) is a good solution, that is, I want to validate login to match only specified characters, and it must be single line. If I change the constructor for MultiLine option ab1, ab2, ab3 and ab6 match the expression, ab4 and ab5 don't match it.
If the string ends with a line break the `RegexOptions.Multiline` will not work. The `$` will just ignore the last line break since there is nothing after that. If you want to match till the very end of the string and ignore any line breaks use `\z` ``` Regex regex = new Regex(@"^[a-z0-9]+\z", RegexOptions.Multiline); ``` This is for both MutliLine and SingleLine, that doesn't matter.
The .NET regex engine does treat `\n` as end-of-line. And that's a problem if your string has Windows-style `\r\n` line breaks. With RegexOptions.Multiline turned on `$` matches between `\r` and `\n` rather than before `\r`. `$` also matches at the very end of the string just like `\z`. The difference is that `\z` can match only at the very end of the string, while `$` also matches before a trailing `\n`. When using RegexOptions.Multiline, `$` also matches before any `\n`. If you're having trouble with line breaks, a trick is to first to a search-and-replace to replace all `\r` with nothing to make sure all your lines end with `\n` only.
.NET's Regex class and newline
[ "", "c#", ".net", "regex", "" ]
We have built a web application that accepts SOAP messages, does some processing, calls out to another web service, massages the response and sendd it back to the original caller. We'd like to log, in a single line, the different execution times for these different steps. We use log4j with the JBossWS stack. In other words, we'd like the log output to look something like: ``` 2009-06-10T16:19:31.487 3336/2449/861 ``` where 3336ms is the total time spent serving the request, 2449ms is the time spent waiting for the web service's response, and 861ms is the time spent internally massaging the data. These different computations happen in different places in our code and we cannot just time each one of them and make a call to the logger at the end of a single method. One of us has suggested using log4j's MDC for this as a poor man's set of global variables to track the different executions times. So my questions are the following: 1. Is this a horrible abuse of the MDC's primary intent? 2. If yes, how would you do this otherwise?
Please have a look at [SLF4J profiler](http://slf4j.org/extensions.html#profiler). Interestingly enough. tt was developed to answer the exact same need, that is to measure and improve the performance of SOAP calls.
Sounds like a job for [Perf4J](http://perf4j.codehaus.org/).
How would you break down and log the execution times of different parts of your application?
[ "", "java", "profiling", "log4j", "" ]
My application deals with percentages a lot. These are generally stored in the database in their written form rather than decimal form (50% would be stored as 50 rather than 0.5). There is also the requirement that percentages are formatted consistently throughout the application. To this end i have been considering creating a struct called percentage that encapsulates this behaviour. I guess its signature would look something like this: ``` public struct Percentage { public static Percentage FromWrittenValue(); public static Percentage FromDecimalValue(); public decimal WrittenValue { get; set; } public decimal DecimalValue { get; set; } } ``` Is this a reasonable thing to do? It would certianly encapsulate some logic that is repeated many times but it is straightforward logic that peopel are likely to understand. I guess i need to make this type behave like a normal number as much as possible however i am wary of creating implicit conversions to a from decimal in case these confuse people further. Any suggestions of how to implement this class? or compelling reasons not to.
`Percentage` class should not be concerned with formatting itself for the UI. Rather, implement [IFormatProvider](http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx) and [ICustomFormatter](http://msdn.microsoft.com/en-us/library/system.icustomformatter.aspx) to handle formatting logic. As for conversion, I'd go with standard [TypeConverter](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx) route, which would allow .NET to handle this class correctly, plus a separate `PercentageParser` utility class, which would delegate calls to `TypeDescriptor` to be more usable in external code. In addition, you can provide `implicit` or `explicit` conversion operator, if this is required. And when it comes to `Percentage`, I don't see any compelling reason to wrap simple `decimal` into a separate `struct` other than for semantic expressiveness.
I am actually a little bit flabbergasted at the cavalier attitude toward data quality here. Unfortunately, the colloquial term "percentage" can mean one of two different things: a probability and a variance. The OP doesn't specify which, but since variance is usually calculated, I'm guessing he may mean percentage as a probability or fraction (such as a discount). The **extremely good reason** for writing a `Percentage` class for this purpose has nothing to do with presentation, but with making sure that you prevent those silly silly users from doing things like entering invalid values like -5 and 250. I'm thinking really more about a `Probability` class: a numeric type whose valid range is strictly [0,1]. You can encapsulate that rule in ONE place, rather than writing code like this in 37 places: ``` public double VeryImportantLibraryMethodNumber37(double consumerProvidedGarbage) { if (consumerProvidedGarbage < 0 || consumerProvidedGarbage > 1) throw new ArgumentOutOfRangeException("Here we go again."); return someOtherNumber * consumerProvidedGarbage; } ``` instead you have this nice implementation. No, it's not fantastically obvious improvement, but remember, you're doing that value-checking in each time you're using this value. ``` public double VeryImportantLibraryMethodNumber37(Percentage guaranteedCleanData) { return someOtherNumber * guaranteedCleanData.Value; } ```
Creating a percentage type in C#
[ "", "c#", "" ]
I have a url like `example.com/page?a=1&ret=/user/page2`. I was using string.split('/') to figure out the paths but this case you can see it isn't very useful. How do i split the URL so i can get the page path?
If you make a System.Uri object from your string, it will have several properties for different parts of the path: ``` string path = "http://example.com/page?a=1&ret=/user/page2"; Uri uri = new Uri(path); Console.WriteLine(uri.AbsolutePath); // Prints "/page" ```
Assuming you mean you want to get the "page2" bit: ``` var ub = new UriBuilder("example.com/page?a=1&ret=/user/page2"); NameValueCollection nvc = HttpUtility.ParseQueryString(ub.Query); string page = nvc[nvc.Count - 1]; // gets "/user/page2" ``` Then you'll have to use split on the rest. Edit: Well, you could use System.IO.Path.GetFileNameWithoutExtension(page) to return "page2", but I am not sure it feels right to me. `System.IO.Path.GetFileNameWithoutExtension("example.com/page?a=1&ret=/user/page2")` returns "page2" as well.
URL split in C#?
[ "", "c#", "asp.net", "" ]
Is it possible to auto close a Flash banner after it's done playing in a browser? Can it be done through javascript? Or should it be configured in the flash file itself?
you could use ExternalInterface to call javascript to remove the object from your actionscript. in your flash: ``` import flash.external.ExternalInterface; ExternalInterface.call("removemovie"); ``` in javascript: ``` function removemovie(){ //do stuff here to remove movie } ``` Josh
What do you mean by "close" do you intend to collapse the space as well or just make it hidden? For the second the easy way is to end on an empty transparent frame. For the first you'd probably need javascript to remove it from the DOM.
auto close a flash file
[ "", "javascript", "flash", "" ]
I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them. ### Example: ``` #!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" ``` So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.
There are several blog entries &c pointing out some problems with Python on Dreamhost and how to work around them to run several web frameworks that could suit you. (Most of the posts are over a year old so it may be that dreamhost has fixed some of the issues since then, of course, but the only way to really find out is to try!-). Start with [this page](http://wiki.dreamhost.com/Python), dreamhost's own wikipage about Python -- at least you know it's quite current (was last updated earlier today!-). It gives instructions on using virtual env, building a custom Python &c if you absolutely need that, and running WSGI apps -- WSGI is the common underpinning of all modern Python web frameworks, including Django which everybody's recommending but also Pylons &c. Some notes on running Pylons on Dreamhost are [here](http://www.heikkitoivonen.net/blog/2008/02/03/pylons-on-dreamhost/) (but it does look like Dreamhost has since fixed some issues, e.g. `flup` *is* now the dreamhost-recommended FCGI layer for WSGI as you'll see at the previously mentioned URL) and links therefrom. If you do go with Pylons, [here](http://wiki.pylonshq.com/display/pylonscookbook/Authentication+and+Authorization) is the best place to start considering how best to do auth (authentication and authorization) with it. I'm trying to play devil's advocate since everybody else's recommending django, but for a beginner django may in fact be better than pylons (still, spending a day or so lightly researching each main alternative, before you commit to one, is a good investment of your time!-). For Django, again there's an official dreamhost [wiki page](http://wiki.dreamhost.com/Django) and it's pretty thorough -- be sure to read through it and briefly to the other URLs it points to. The contributed `auth` module is no doubt the best way to do authentication and authorization if you do decide to go with Django. And, whichever way you do choose -- best of luck!
Let me share my own experience with django. My prerequisits: * average knowledge of python * very weak idea of how web works (no js skills, just a bit of css) * my day job is filled with coding in C and I just wanted to try something different, so there certainly was a passion to learn (I think this is the most important one) Why I've chosen django: * I've already knew bits and pieces of python * django has excelent documentation, including tutorial, which explained everything in very clear and simple manner It is worth to read complete [manual](http://docs.djangoproject.com/en/dev/) first (it took me two or three weekends. I remember I could not remember/understand everything at first pass, but it helped me to learn where the information can be found when needed. There is also another source of documentaion called [djangobook](http://www.djangobook.com/ "djangobook"). Djangobook contains same information as manual, but things are explained more in detail. It's worth to read it also, it helps to catch up with MVC concept, if you have not tried that before. And finally to answer your question best: there are already also [OpenId](http://openid.net) modules ready for you. I'm considering to use [django-authopenid](http://bitbucket.org/benoitc/django-authopenid/wiki/Home) for my new project. It supports OpenId, while providing fallback to locally managed users. There is certain learning curve if you are going learn django. The more you know about the web and python the steeper the curve is. I had to also learn bits and pieces of javascript and it took me also some time. If you are able to spend full time learning django, then you can expect you'll be able to deliver first results within 4-6 weeks. It took me 6 months, since I was doing my django studies in free time.
How do I set up a basic website with registration in Python on Dreamhost?
[ "", "python", "dreamhost", "" ]
My app monitors a directory where users can upload a file. When a new file is detected it is added to a queue. I have a timer that runs through the queue and determines if the file has finished uploading. If there are any files that are complete it will take the most recent and begin running a background task (using BackgroundWorker). My problem is that I don't know how to handle the timer while the background task is running. For example, if the timer is set to 10 seconds and the background worker is still working I want the timer to skip execution of another background worker until its next iteration. Also, the information for each task is stored in the Queue (a ListView control) and I pass the ListViewItem to the background worker. I'm curious if passing the ListViewItem has any side effects. Thanks!
You could store ready-to-process files in another queue (like a Queue< string> ) and have the BgWorker continuously poll that Queue. You might get better performance too, less idle time. You will have to protect the Queue (with Monitor) and have the BgWorker use Monitor.Wait when the Queue is empty. To get an idea, look for Marc Gravell's answer on [this question](https://stackoverflow.com/questions/530211/creating-a-blocking-queuet-in-net).
Really hard to answer this without seeing the code you are talking about. However, if you have to synchronize multiple asynchronous events (detecting a file is downloaded, adding the file to a queue, processing the queue) I suggest creating a single BackgroundWorker that does all tasks. Then it is easy in your worker to test what state each step is at. I would avoid creating multiple threads and attempting to synchronize them, this is very very problematic. I would also not store any background task information in a UI data structure (like a ListView control). Create a callback or event in your BackgroundWorker that will alert the UI when it needs to display something.
BackgroundWorker and Timer, handling one item at a time
[ "", "c#", "winforms", "backgroundworker", "" ]
In SQL Server 2008, we can define a table type and use it as a stored procedures' parameter. But how can I use it in C# invocation of this stored procedure? In other words, how to create a table or list and pass it into a stored procedure in C# code with this new feature of SQL Server 2008?
You need to see this [example on CodeProject](http://www.codeproject.com/KB/database/sqlserver2008.aspx). ``` SqlParameter param = cmd.Parameters.AddWithValue("@FileDetails", dt); ``` where dt is a DataTable, and the @fileDetails parameter is a table type in SQL: ``` create type FileDetailsType as table ( FileName varchar(50), CreatedDate varchar(50), Size decimal(18,0) ) ``` **Edit**: [This MSDN Developer's Guide article](http://msdn.microsoft.com/en-us/library/bb675163.aspx) also would help.
The easiest way is by passing a `DataTable` as the parameter. Check out some examples [here](http://msdn.microsoft.com/en-us/library/bb675163.aspx).
How to pass User Defined Table Type as Stored Procedured parameter in C#
[ "", "c#", "sql-server-2008", "" ]
I have the following Java socket client app, that sends same string to socket server: ``` import java.net.*; import java.io.*; public class ServerClient { public static void main(String[] args) throws IOException { System.out.println("Starting a socket server client..."); Socket client = new Socket("XXX.X.XXX.XX", 12001); BufferedOutputStream stream = new BufferedOutputStream(client.getOutputStream()); String message = "ABC"; BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)); String input = null; while ( true ) { System.out.print("Would you like to send a message to Server? "); input = inputReader.readLine(); if ( !input.equals("Y") ) break; System.out.println("Message to send: " + message); System.out.println("Message length is: " + message.length()); byte[] messageBytes = message.getBytes("US-ASCII"); stream.write(messageBytes, 0, messageBytes.length); stream.flush(); } System.out.println("Shutting down socket server client..."); stream.close(); client.close(); inputReader.close(); } } ``` The first time message is sent, server receives the message; however, every subsequent time I'm trying to send this message, server is not receiving anything. Message simply disappears. I am writing to the socket successfully (no exceptions) but nothing is coming on the other side of the pipe (or so I'm told). I do not have access to the server app, logs or code, so I'm wondering if there is any approach you can recommend to figure out why server is not receiving subsequent messages. Any ideas would be greatly appreciated! **Clarification**: 1. New lines are not expected by the server; otherwise, how would it even receive message the first time? As a trial and error, I did try sending '\n' and "\r\n" and 0x00 characters at the end of the string - all without any luck. 2. I thought flushing was an issue, so I tried various outputstream classes (PrintStream, PrintWriter, FilterOutputStream), but was still running into same exact issues. Then, if "flushing" is an issue, how is it working the first time?
Other tests: 1 - use a network sniffer to see what is realy hapening on the network 2 - use some program like [TCP Test Tool](http://www.simplecomtools.com/tcptesttool.html) to send data to the server and simulate your program. (netcat can also be used, but it sends a newline after each line)
Remember: * TCP is stream oriented. not message oriented. * One write on the client could take several reads on the server to .. read * Multiple writes on the client could get read by the server in one read * You'll hardly see the above scenarios in a test application on a local network, you will see them very quick in a production environemnt, or when you start to really speed up the sending/receiving. Following this, if you are sending **messages** you need a delimiter, or some other way of indicating 'here's one message', e.g. defining the protocol to be 'the first byte is the length of the following message'. And you'd need to check the receiving end wether it read a partial message, a whole message, and any combination thereof (e.e.g one read might have read 3 and a half message..). A quick solution for your test app, write lines. That is, a string followed by a newline character. A bufferedreader's ReadLine() could then take care of the reassembly for you on the receiving end.
Server not receiving bytes written to a socket by Java app
[ "", "java", "sockets", "" ]
I have a class defined like so: ``` public class Test { static <T> List<Class<T>> filter(List<Class<T>> input) { // code here } public static void main(String[] args) { List<Class<? extends Throwable>> list = new ArrayList<Class<? extends Throwable>>(); filter(list); } } ``` The `filter` method call in `main` gives the following compile error: ``` The method filter(List<Class<T>>) in the type Test is not applicable for the arguments (List<Class<? extends Throwable>>) ``` I don't understand why `<T>` doesn't bind to `<? extends Throwable>`. Are there any generics gurus who can help me?
I believe the problem here is that there is no type for `?` that would do. Consider if we, for simplicity, replaced `Class` with `AtomicReference`. ``` static <T> void filter(List<AtomicReference<T>> input) { T value = input.get(0).get(); input.get(1).set(value); } ``` If the `input` consisted of an `AtomicReference<Integer>` and an `AtomicReference<String>` we would be in trouble. The underlying problem that pointers to pointers in the presence of polymorphism is difficult. Without generics we can just hand wave. With generics we need to actually mean something.
Ah, the joys of generic signatures. You can fix it by declaring the parameter as: ``` static <T> List<Class<T>> filter(List<Class<? extends T>> input) { // code here } ``` As to exactly why, I'm not sure. Too many compilation problems with generics are fixed by trying various things until the red line goes away. Not satisfying.
Unable to call generic method with wildcard
[ "", "java", "generics", "" ]
First of all I apologize for the long lead up to such a simplistic question. I am implementing a class which serves as a very long 1 dimensional index on a space filling curve or the n-tuple representing the Cartesian coordinate that index corresponds to. ``` class curvePoint { public: friend class curveCalculate; //Construction and Destruction curvePoint(): point(NULL), dimensions(0) {} virtual ~curvePoint(){if(point!=NULL) delete[] point;} //Mutators void convertToIndex(){ if(isTuple()) calc(this); } void convertToTuple(){ if(isIndex()) calc(this); } void setTuple(quint16 *tuple, int size); void setIndex(quint16 *index, int size); void setAlgorithm(curveType alg){algorithm = alg;} //Inspectors bool isIndex(){return current==Index;} bool isTuple(){return current==Tuple;} size_t size(){return dimensions;} quint16 operator[](size_t index); enum curveType{HilbertCurve, ZCurve, GrayCodeCurve}; enum status{Index, Tuple}; private: curveCalculate calc; curveType algorithm; quint16 *point; size_t dimensions; status current; }; ``` (The length of the array pointed to by *point* is *dimensions*) Anyways in the implementation of operator[] I was wondering what the best method to achieve bounds checking is. I want to avoid throwing exceptions if at all possible, and the full range of values is usable for each number in the array so a special value to return in case of an out of bounds error is not possible either; I was thinking of something like this though implemented in the class definition: ``` quint16 curvePoint::operator[](size_t index) { return point[ index % dimensions ]; } ``` This makes it so that we never leave the bounds of the array and if well documented I think it would be fine; nevertheless, I am leary of this particular implementation. Does this look acceptable to others? Is there any other way of doing bounds checking while still satisfying my constraints? Edit: Calculation of things like Hilbert curves etc are highly messy, messy enough that I do not not want the additional interface for the stl libraries in the way. Additionally because I will have to convert many thousands of these every time the multidimensional database is queried I do not want the additional cost of the stl function calls in the mix, if at all possible. I rather like the idea of the assert; but, if I remember correctly that breaks in release builds does it not? I suppose I can use exceptions, that seems to be what everyone is rooting for, but I am using the Qt libraries and those avoid exceptions for both performance and portability and I was hoping to do the same.
The easiest solution is to do as C++ itself does. This limits the amount of surprises that your users will experience. C++ itself is fairly consistent. Both the built-in `[]` on pointers and `std::vector::operator[]` have undefined behavior if you use an out-of-bound array index. If you want bounds checking, be explicit and use `std::vector::at` Hence, if you do the same for your class, you can document the out-of-bound behavior as "standard".
> Anyways in the implementation of > operator[] I was wondering what the > best method to achieve bounds checking > is. I want to avoid throwing > exceptions if at all possible, and the > full range of values is usable for > each number in the array so a special > value to return in case of an out of > bounds error is not possible either; Then the remaining options are: * **Flexible design.** What you did. "Fix" the invalid input so that it tries to do something which makes sense. Advantage: Function won't crash. Disadvantage: Clueless callers who access an out of bounds element will get a **lie** as a result. Imagine a 10-floor building with floors 1 to 10: > You: *"Who lives in the 3rd floor?"* > > Me: *"Mary".* > > You: *"Who lives in the 9th floor?"* > > Me: *"Joe".* > > You: *"Who lives in the 1,203rd floor?"* > > Me: (Wait... 1,203 % 10 = 3...) > *> "Mary"*. > > You: *"Wow, Mary must enjoy great views from [up there](http://www.e-architect.co.uk/dubai/jpgs/burj_dubai_emaar_properties_cb210707_1.jpg). So she owns two apartments then?"* * A **bool output parameter** indicates success or failure. This option usually ends up in not very usable code. Many users will ignore the return code. You are still left with what you return in the other return value. * **Design by Contract.** Assert that the caller is within bounds. (For a practical approach in C++, see [An exception or a bug? by Miro Samek](http://www.state-machine.com/writings/samek0308.pdf) or [Simple Support for Design by Contract in C++ by Pedro Guerreiro](http://portal.acm.org/citation.cfm?id=884714).) * **Return a `System.Nullable<quint16>`**. Oops, wait, this is not C#. Well, you could return a pointer to a quint16. This of course has lots of implications which I shall not discuss here and which probably make this option not usable. **My favorite choices are:** * For the public interface of a publicly released library: Input will be checked and an exception will be thrown. You ruled out this option, so it is not an option for you. It is still *my* choice for the interface of a publicly released library. * For internal code: Design by contract.
When implementing operator[] how should I include bounds checking?
[ "", "c++", "operator-overloading", "" ]
I am getting strange behaviour using the built-in C# List.Sort function with a custom comparer. For some reason it sometimes calls the comparer class's Compare method with a null object as one of the parameters. But if I check the list with the debugger there are no null objects in the collection. My comparer class looks like this: ``` public class DelegateToComparer<T> : IComparer<T> { private readonly Func<T,T,int> _comparer; public int Compare(T x, T y) { return _comparer(x, y); } public DelegateToComparer(Func<T, T, int> comparer) { _comparer = comparer; } } ``` This allows a delegate to be passed to the List.Sort method, like this: ``` mylist.Sort(new DelegateToComparer<MyClass>( (x, y) => { return x.SomeProp.CompareTo(y.SomeProp); }); ``` So the above delegate will throw a null reference exception for the *x* parameter, even though no elements of *mylist* are null. **UPDATE:** Yes I am absolutely sure that it is parameter *x* throwing the null reference exception! **UPDATE:** Instead of using the framework's List.Sort method, I tried a custom sort method (i.e. *new BubbleSort().Sort(mylist)*) and the problem went away. As I suspected, the List.Sort method passes null to the comparer for some reason.
This problem will occur when the comparison function is not consistent, such that x < y does not always imply y < x. In your example, you should check how two instances of the type of SomeProp are being compared. Here's an example that reproduces the problem. Here, it's caused by the pathological compare function "compareStrings". It's dependent on the initial state of the list: if you change the initial order to "C","B","A", then there is no exception. I wouldn't call this a bug in the Sort function - it's simply a requirement that the comparison function is consistent. ``` using System.Collections.Generic; class Program { static void Main() { var letters = new List<string>{"B","C","A"}; letters.Sort(CompareStrings); } private static int CompareStrings(string l, string r) { if (l == "B") return -1; return l.CompareTo(r); } } ```
Are you sure the problem isn't that `SomeProp` is `null`? In particular, with strings or `Nullable<T>` values. With strings, it would be better to use: ``` list.Sort((x, y) => string.Compare(x.SomeProp, y.SomeProp)); ``` (edit) For a null-safe wrapper, you can use `Comparer<T>.Default` - for example, to sort a list by a property: ``` using System; using System.Collections.Generic; public static class ListExt { public static void Sort<TSource, TValue>( this List<TSource> list, Func<TSource, TValue> selector) { if (list == null) throw new ArgumentNullException("list"); if (selector == null) throw new ArgumentNullException("selector"); var comparer = Comparer<TValue>.Default; list.Sort((x,y) => comparer.Compare(selector(x), selector(y))); } } class SomeType { public override string ToString() { return SomeProp; } public string SomeProp { get; set; } static void Main() { var list = new List<SomeType> { new SomeType { SomeProp = "def"}, new SomeType { SomeProp = null}, new SomeType { SomeProp = "abc"}, new SomeType { SomeProp = "ghi"}, }; list.Sort(x => x.SomeProp); list.ForEach(Console.WriteLine); } } ```
List.Sort in C#: comparer being called with null object
[ "", "c#", "list", "sorting", "" ]
I've been trying to use TeamCity 4.5 in order to automate builds of an XNA project but I have a small problem. My projects compile correctly under Visual Studio 2008, but not when compiled with TeamCity as the builder. The configuration file uses the sln2008 setting, and compiling goes well for a while, but as soon as it goes compiling .png textures to .xnb, I get the following error: ``` [11:28:41]: [Project "Content.contentproj" (default targets):] Content\head.png Building content threw InvalidOperationException: D3DERR_INVALIDCALL at Microsoft.Xna.Framework.Content.Pipeline.CommonHelperFunctions.InitD3D() at Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.InitD3D() at Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.Import(String filename, ContentImporterContext context) at Microsoft.Xna.Framework.Content.Pipeline.ContentImporter`1.Microsoft.Xna.Framework.Content.Pipeline.IContentImporter.Import(String filename, ContentImporterContext context) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.ImportAssetDirectly(BuildItem item, String importerName) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.ImportAsset(BuildItem item) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAssetWorker(BuildItem item) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.BuildAsset(BuildItem item) at Microsoft.Xna.Framework.Content.Pipeline.BuildCoordinator.RunTheBuild() at Microsoft.Xna.Framework.Content.Pipeline.Tasks.BuildContent.RemoteProxy.RunTheBuild(BuildCoordinatorSettings settings, TimestampCache timestampCache, ITaskItem[] sourceAssets, String[]& outputContent, String[]& rebuiltContent, String[]& intermediates, Dictionary`2& dependencyTimestamps, KeyValuePair`2[]& warnings) Inner exception: COMException: Exception from HRESULT: 0x8876086C ``` I do not have any ideas what is causing this. Like I said, it's able to compile .fbx models correctly as well as my ContentPipeline project and my SharedContent project (part of the solution). What I would actually like is some pointers to what would be the source of the problem (and if possible, a solution to the problem). As far as I understand, there seems to be a problem with the D3D library. I will also remind you that this whole solution compiles under Visual Studio 2008, thus there is a small problem with TeamCity, either I haven't provided something, or something is actually incorrectly set.
Almost certainly, Team City is running it's build process as Local System in a non-interactive mode, and not as a user that actually has the access and ability to grab the graphics device. I know I've had problems even attempting to batch process textures through a Remote Desktop interface because DirectX can't grab the graphics device. The solution may be to see if Team City offers you the ability to request that it's builder run as a logged on user, not as Local System, or as a service, though I can't tell you that that's actually even possible in Team City.
I don't have a solution but I've been thinking about it. The error is D3DERR\_INVALIDCALL so I'm thinking the device isn't available at that time for some reason. 1) Do the machines running the build have DirectX installed/a graphics card? I'm assuming yes since XNA requires a card with shaders but TeamCity is a build distribution so maybe it's running on a machine without it? 2) Maybe TeamCity is causing too too many Direct3D devices to be created on the same machine/process (complete guess)? Do the model files that compile correctly use textures or are they just geometry data? I have a feeling the content builder doesn't need access to DirectX to build models but does for texture data. Can you build anything else that requires access Direct3D? Can you build a project using TeamCity that just has one texture in it's content folder? I'm not sure if this would work but can you get more information by running DirectX in Debug Mode and looking at the output? Hope this helps somewhat.
D3DERR_INVALIDCALL error, TeamCity builder
[ "", "c#", "xna", "teamcity", "" ]
How do I add a new key to an existing dictionary? It doesn't have an `.add()` method.
You create a new key/value pair on a dictionary by assigning a value to that key ``` d = {'key': 'value'} print(d) # {'key': 'value'} d['mynewkey'] = 'mynewvalue' print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'} ``` If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.
I feel like consolidating info about Python dictionaries: ## Creating an empty dictionary ``` data = {} # OR data = dict() ``` ## Creating a dictionary with initial values ``` data = {'a': 1, 'b': 2, 'c': 3} # OR data = dict(a=1, b=2, c=3) # OR data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))} ``` ## Inserting/Updating a single value ``` data['a'] = 1 # Updates if 'a' exists, else adds 'a' # OR data.update({'a': 1}) # OR data.update(dict(a=1)) # OR data.update(a=1) ``` ## Inserting/Updating multiple values ``` data.update({'c':3,'d':4}) # Updates 'c' and adds 'd' ``` ### Python 3.9+: The *update operator* `|=` now works for dictionaries: ``` data |= {'c':3,'d':4} ``` ## Creating a merged dictionary without modifying originals ``` data3 = {} data3.update(data) # Modifies data3, not data data3.update(data2) # Modifies data3, not data2 ``` ### Python 3.5+: This uses a new feature called *dictionary unpacking*. ``` data = {**data1, **data2, **data3} ``` ### Python 3.9+: The *merge operator* `|` now works for dictionaries: ``` data = data1 | {'c':3,'d':4} ``` ## Deleting items in dictionary ``` del data[key] # Removes specific element in a dictionary data.pop(key) # Removes the key & returns the value data.clear() # Clears entire dictionary ``` ## Check if a key is already in dictionary ``` key in data ``` ## Iterate through pairs in a dictionary ``` for key in data: # Iterates just through the keys, ignoring the values for key, value in d.items(): # Iterates through the pairs for key in d.keys(): # Iterates just through key, ignoring the values for value in d.values(): # Iterates just through value, ignoring the keys ``` ## Create a dictionary from two lists ``` data = dict(zip(list_with_keys, list_with_values)) ```
How can I add new keys to a dictionary?
[ "", "python", "dictionary", "lookup", "" ]
I have two different domains that both point to my homepage in the same server. I want to log every single access made to my homepage and log which domain the user used to access my homepage, how can I do this? I tried mod\_rewrite in Apache and logging to a MySQL database with PHP but all I could do was infinite loops. Any ideas? **EDIT:** By your answers, I see you didn't get what I want... As far as I know Google Analytics does not allow me to differentiate the domain being used if they both point to the same site and it also does not allow me to see that some files like images were accessed directly instead of through my webpages. I can't also just use $\_SERVER['HTTP\_HOST'] cause like I just said, I want to log EVERYTHING, like images and all other files, every single request, even if it doesn't exist. As for Webalizer, I never saw it differentiate between domains, it always assumes the default domain configure in the account and use that as root, it doesn't even display it. I'll have to check it again, but I'm not sure it will do what I want... **INFINITE LOOP:** The approach I tried involved rewriting the urls in Apche with a simple Rewrite rule pointing to a PHP script, the PHP script would log the entry into a MySQL database and the send the user back to the file with the header() function. Something like this: **.htaccess:** ``` RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.net [NC] RewriteRule ^(.*)$ http://www.domain1.net/logscript?a=$1 [NC,L] RewriteCond %{HTTP_HOST} ^(www\.)?domain2\.net [NC] RewriteRule ^(.*)$ http://www.domain2.net/logscript?a=$1 [NC,L] ``` **PHP Script:** ``` $url = $_GET['a']; $domain = $_SERVER['HTTP_HOST']; // Code to log the entry into the MySQL database header("Location: http://$domain/$url"); exit(); ``` So, I access some file, point that file to the PHP script and the script will log and redirect to that file... However, when PHP redirects to that file, the htaccess rules will pick it up and redirect again too the PHP script, creating an infinite loop.
The best thing do would be to parse the server logs. Those will show the domain and request. Even most shared hosting accounts provide access to the logs. If you're going to go the rewrite route, you could use `RewriteCond` to check the `HTTP_REFERER` value to see if the referer was a local link or not. ``` RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.net [NC] RewriteCond %{HTTP_REFERER} !^(.*)domain1(.*)$ [NC] RewriteRule ^(.*)$ http://www.domain1.net/logscript?a=$1 [NC,L] RewriteCond %{HTTP_HOST} ^(.*)domain2\.net [NC] RewriteCond %{HTTP_REFERER} !^(.*)domain2(.*)$ [NC] RewriteRule ^(.*)$ http://www.domain2.net/logscript?a=$1 [NC,L] ``` You may also want to post in the [mod\_rewrite](http://forum.modrewrite.com/viewforum.php?f=9) forum. They have a whole section about handling domains.
If Google Analytics is not your thing, ``` $_SERVER['HTTP_HOST'] ``` holds the domain that is used, you can log that (along with time, browser, filepath etc). No need for mod\_rewrite I think. Check print\_r($\_SERVER) to see other things that might be interesting to log. Make sure to still escape (mysql\_real\_escape\_string()) all the log values, it's trivially easy to inject SQL via the browser's user-agent string for example. --- > So, I access some file, point that file to the PHP script and the script will log and redirect to that file... However, when PHP redirects to that file, the htaccess rules will pick it up and redirect again too the PHP script, creating an infinite loop. Can you check for HTTP headers in the RewriteCond? If so, try setting an extra header alongside the redirect in PHP (by convention custom HTTP headers start with 'X-' so it could be header('X-stayhere: 1');), and if the X-stayhere header is present, the RewriteCond fails and it doesn't forward the browser to the PHP script. If, however, you can cron a script to download the server logs and run them through some freeware logfile analyzer, I'd go with that instead. Having two redirects for every request is a fair bit of overhead.. (and if I was more awake I might be able to come up with different solutions)
How to log every single access to my website with 2 different domains
[ "", "php", "apache", "logging", "dns", "" ]
I am creating an invoice application and in the section where the user can enter line items, some of the fields will include: Quantity, Price, Extended Price, Description, etc. If the user enters something into any of the fields, the corresponding fields are required, but if no data is entered into any field, then nothing is required in the corresponding fields. What is an efficient and clean way of doing this without doing a bunch of if statements? I guess this is like doing validation if only one textbox has text.
You could try something like this in the ServerValidate event of a CustomValidator. ``` // test for all textboxes having some text in them... e.IsValid = (from TextBox c in this.Controls where c is TextBox select c).All(tb => !string.IsNullOrEmpty(tb.Text)); ``` That might need some tinkering to get right - but you get the idea. Change accordingly to test for all textboxes being blank. You could also use jQuery for the client side validation in your CustomValidator ``` function clientValidate(sender, e) { // get array of textboxes with a common css class var textBoxes = $("#SomeCssSelector input").val(); // loop here to test for having text or no text. e.IsValid = ... ; } ```
You could create a TextBox array and store references to all related text boxes in the array. When ever you need to you could then iterate over the array in a for loop looking for the first item with a value. As soon as you find one with a value you know all the other items in that array also need values. Additionally, if you have other groups of related text boxes you could create additional arrays to help keep them grouped.
How to check if either none or all textboxes in an ASP.NET page have text entered?
[ "", "c#", "asp.net", "" ]
class `String` contains very useful method - `String.Join(string, string[])`. It creates a string from an array, separating each element of array with a symbol given. But general - it doesn't add a separator after the last element! I uses it for ASP.NET coding for separating with "`<br />`" or `Environment.NewLine`. So I want to add an empty row after each row in `asp:Table`. What method of `IEnumerable<TableRow>` can I use for the same functionality?
I wrote an extension method: ``` public static IEnumerable<T> Join<T>(this IEnumerable<T> src, Func<T> separatorFactory) { var srcArr = src.ToArray(); for (int i = 0; i < srcArr.Length; i++) { yield return srcArr[i]; if(i<srcArr.Length-1) { yield return separatorFactory(); } } } ``` You can use it as follows: ``` tableRowList.Join(()=>new TableRow()) ```
The Linq equivalent of `String.Join` is `Aggregate` For instance: ``` IEnumerable<string> strings; string joinedString = strings.Aggregate((total,next) => total + ", " + next); ``` If given an IE of TableRows, the code will be similar.
An analog of String.Join(string, string[]) for IEnumerable<T>
[ "", "c#", "linq", "extension-methods", "ienumerable", "" ]
I've seen some interesting claims on SO re Java hashmaps and their `O(1)` lookup time. Can someone explain why this is so? Unless these hashmaps are vastly different from any of the hashing algorithms I was bought up on, there must always exist a dataset that contains collisions. In which case, the lookup would be `O(n)` rather than `O(1)`. Can someone explain whether they *are* O(1) and, if so, how they achieve this?
A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic. In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be. For a hash map, that of course is the case of a collision with respect to how full the map happens to be. A collision is pretty easy to estimate. > pcollision = n / capacity So a hash map with even a modest number of elements is pretty likely to experience at least one collision. Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k. > O(n) = O(k \* n) We can use this feature to improve the performance of the hash map. We could instead think about the probability of at most 2 collisions. > pcollision x 2 = (n / capacity)2 This is much lower. Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm! We can generalzie this to > pcollision x k = (n / capacity)k And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for. You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm. We talk about this by saying that the hash-map has O(1) access ***with high probability***
You seem to mix up worst-case behaviour with average-case (expected) runtime. The former is indeed O(n) for hash tables in general (i.e. not using a perfect hashing) but this is rarely relevant in practice. Any dependable hash table implementation, coupled with a half decent hash, has a retrieval performance of O(1) with a very small factor (2, in fact) in the expected case, within a very narrow margin of variance.
Is a Java hashmap search really O(1)?
[ "", "java", "hashmap", "big-o", "time-complexity", "" ]
I have 2 z-index layers in a map application I'm building. I have a problem when I click on the layers to zoom in. The click handler is on the underlying z-index layer and I don't want it to fire when a control in the overlying layer is clicked. The problem i have is that the event gets raised no matter what but the originalTarget property of the event is not the image in the underlying layer when something on the top layer is clicked. Is there anyway to change this?
It's called event-bubbling, and you can control it with the `event.stopPropagation()` method (`event.cancelBubble()` in IE). You can also control it by returning true/false from handlers called by onwhatever attributes on elements. It's a tricky subject so I suggest you do some [research](http://www.quirksmode.org/js/events_order.html). Info: [cancelBubble](http://msdn.microsoft.com/en-us/library/ms533545(VS.85).aspx), [stopPropagation](http://www.w3.org/TR/2001/WD-DOM-Level-3-Events-20010823/events.html)
Although this does not address the problem directly it may be a viable workaround until a more fitting solution presents itself. Write a single function to be called onClick and allow the function enough smarts to know who called it. The function then takes the appropriate action based upon who clicked it. You could send it pretty much anything that would be unique and then use a switch. simplified example : ``` <html> <body> <script type="text/javascript"> function myClickHandle(anID) { switch(anID){ case 'bottom': alert("I am on the bottom"); break; case 'top': alert("I am on the top"); break; } } </script> <html> <div style="z-index:10"><input type=button value='top' onclick="myClickHandle(this.value)"/></div> <div style="z-index:11"><input type=button value='bottom' onclick="myClickHandle(this.value)"/></div> </body> </html> ```
Handling click events on z-index'd layers
[ "", "javascript", "event-handling", "z-index", "" ]
I have a situation in which I am attempting to keep my model and implementation as loosely coupled as possible, however I am faced with a situation where the coupling could potentially get a lot closer than I want. I have a selection of 'Model' classes, all implementing interfaces. Additionally I have 'Data Access' classes, which provide a number of functions, one of which is decoding integer lookup values into their full 'object' representation. Within my model classes I want to provide access to these decoded values without requiring the model to know about the data access classes. A simplified example is: ``` /// Core classes -- class Car : ICar { public int MakeId { get {...} set { ... } } public IMakeInfo Make { get {...} } public string Registration { get { ... } set { ... } } public int CurrentOwnerId { get { ... } set { ... } } public IPerson CurrentOwner { get { ... } } } class MakeInfo : IMakeInfo { public string Name { ... } public int Id { ... } public decimal Weight { ... } // etc etc } /// Data Access Classes -- class ResolveMake { public IMakeInfo GetMakeInfo(int id) { // Implementation here... } } ``` How do I enable the `Car` class to provide the `IMakeInfo` object to any consuming classes without directly making it aware of the ResolveMake class? In the actual instance I am working with the Car class is not in the same namespace as the ResolveMake class and it contains no references to any instances of it. Some of my options: * Implement a delegate in `Car` which can be supplied with an instance of the `GetMakeInfo` method. * Some kind of dependency injection * Closely couple Car to ResolveMake and be done with it. * Any other options? Any suggestions welcome!
[Extension Methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx)? ``` namespace CarStuff { class Car : ICar { public int MakeId { get {...} set { ... } } // no Make property... public string Registration { get { ... } set { ... } } public int CurrentOwnerId { get { ... } set { ... } } public IPerson CurrentOwner { get { ... } } } } namespace MakeExts { class ResolveMake { public static IMakeInfo Make(this Car myCar) { //implementation here } } } ``` elsewhere: ``` using MakeExts; Car c = new Car(); Console.WriteLine(c.Make().ToString()); ``` Edit: For using Extension Methods in .NET 2.0, you need something like: * <http://kohari.org/2008/04/04/extension-methods-in-net-20/> * <http://www.danielmoth.com/Blog/2007/05/using-extension-methods-in-fx-20.html> Basically, a class containing: ``` namespace System.Runtime.CompilerServices { class ExtensionAttribute : Attribute { } } ``` and a "using System.Runtime.CompilerServices" scattered in relevant places.
It sounds like Dependency Injection to me. I have done similar things with MS PP Unity and both contructor injection as well as method and property injection. Then your Car class would have some sort of injection of the IMakeInfo...example: ``` [InjectionMethod] public void Initialize([Dependency] IMakeInfo makeInfo) { this.MakeInfo = makeInfo; } ```
Any suitable patterns for this problem?
[ "", "c#", "design-patterns", ".net-2.0", "loose-coupling", "" ]
We're starting to make heavier use of GWT in our projects, and the performance of the GWT compiler is becoming increasingly annoying. We're going to start altering our working practices to mitigate the problem, including a greater emphasis on the hosted-mode browser, which defers the need to run the GWT compiler until a later time, but that brings its own risks, particularly that of not catching issues with real browsers until much later than we'd like. Ideally, we'd like to make the GWT compiler itself quicker - a minute to compile a fairly small application is taking the piss. However, we are using the compile if a fairly naive fashion, so I'm hoping we can make some quick and easy gains. We're currently invoking com.google.gwt.dev.Compiler as a java application from ant Ant target, with 256m max heap and lots of stack space. The compiler is launched by Ant using fork=true and the latest Java 6 JRE, to try and take advantage of Java6's improved performance. We pass our main controller class to the compiler along with the application classpath, and off it goes. What else can we do to get some extra speed? Can we give it more information so it spends less time doing discovery of what to do? I know we can tell it to only compile for one browser, but we need to do multi-browser testing, so that's not really practical. All suggestions welcome at this point.
Let's start with the uncomfortable truth: GWT compiler performance is really lousy. You can use some hacks here and there, but you're not going to get significantly better performance. A nice performance hack you can do is to compile for only specific browsers, by inserting the following line in your `gwt.xml`: ``` <define-property name="user.agent" values="ie6,gecko,gecko1_8"></define-property> ``` or in gwt 2.x syntax, and for one browser only: ``` <set-property name="user.agent" value="gecko1_8"/> ``` This, for example, will compile your application for IE and FF only. If you know you are using only a specific browser for testing, you can use this little hack. Another option: if you are using several locales, and again using only one for testing, you can comment them all out so that GWT will use the default locale, this shaves off some additional overhead from compile time. Bottom line: you're not going to get order-of-magnitude increase in compiler performance, but taking several relaxations, you can shave off a few minutes here and there.
If you run the GWT compiler with the -localWorkers flag, the compiler will compile multiple permutations in parallel. This lets you use all the cores of a multi-core machine, for example -localWorkers 2 will tell the compiler to do compile two permutations in parallel. You won't get order of magnitudes differences (not everything in the compiler is parallelizable) but it is still a noticable speedup if you are compiling multiple permutations. If you're willing to use the trunk version of GWT, you'll be able to use hosted mode for any browser ([out of process hosted mode](http://code.google.com/p/google-web-toolkit/wiki/DesignOOPHM)), which alleviates most of the current issues with hosted mode. That seems to be where the GWT is going - always develop with hosted mode, since compiles aren't likely to get magnitudes faster.
How do I speed up the gwt compiler?
[ "", "java", "performance", "gwt", "" ]
I'm a bit confused about the exact use cases for jqueryui. What do you use it for? And why?
If you're working on a rich, interactive UI you'll find jQuery UI interactions such as draggable, droppable, resizable etc to be a handy base to build upon. These things aren't straightforward to code yourself. jQuery UI is not really designed to make your website pretty, as someone suggested - its primary purpose is to provide helpful javascript tools to facilitate a few common user interactions. If you're making an information-intensive CMS-based site, this might not be very helpful. However, if you're building a spreadsheet app or a wysiwyg editor or a sophisticated dashboard -- in short, a highly interactive app -- then jQuery UI will give you a good starting point.
I used it for an Adobe AIR project. The tabs worked well, as did the modal alert, and I was able to theme my divs with Themeroller, but I wasn't pleased with much else. Just aren't enough good gadgets in it. I'd probably hit ExtJS next time I tried a heavily-gadgeted RIA. I would have used ExtJS by now, except the license confuses me every time I look at it. I can't quite figure out who would be satisfied with jQueryUI at this point, but maybe as more "stuff" rolls in it will be worth using. But progress on the widgets seems glacial to me. Also, I was irritated that "hover" and "click" aren't differentiated. [Hover over a date in the datepicker](http://jqueryui.com/demos/datepicker/), then click & hold (don't release). Did you see anything to indicate that you clicked? So, having used it, I too am a bit confused about the exact use cases. However, I know some of the guys from Twitter. I really like them, and I wish them well as it shapes up.
What exactly does one use JQueryUI for?
[ "", "javascript", "jquery-ui", "" ]
Further to my [last question](https://stackoverflow.com/questions/963679/do-browsers-widely-support-numeric-quotes-in-attributes), I'd like to know if current browsers can read attribute values [without any quotes](http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#attribute-value-(unquoted)-state), even if the value contains slashes, like: ``` <script src=/path/to/script.js type=text/javascript></script> ``` Will it work without causing a DOM parsing error and corrupting the entire document?
It is valid in HTML4/5 as long as their are no spaces in the value. It is not valid in XHTML though it is still properly rendered on some (all?) browsers. Using a quick sample HTML doc (at end of answer), I tested this with Firefox 3.5 Beta 4, Google Chrome 2, and IE 7. The sample doc was also tested with HTML 4 Strict, HTML 4 Transitional, HTML 5, and XHTML doc types. All were rendered successfully. Some other things to consider... Many modern browsers attempt to render pages in standards compliant mode. If you're trying to use XHTML, and you use unquoted values, browsers will revert back to quirks mode, possibly affecting the rendering of your otherwise standards compliant documents. As browsers become more and more standards compliant as well, future specs may look to deprecate unquoted values. Additionally, in some web frameworks, applications may be parsing templates prior to serving them up. Again, if these parsers are expecting valid XHTML, this type of thing could cause failures. As long as you are sticking to HTML and not XHTML you should be fine without quotes, but there is no guarantee what will happen with XHTML browser to browser. Adding quotes seems like a small cost and keeps your code generally in line with standards for the future. ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>No Quotes Test</title> </head> <body> <input type="text" value="with/quotes and spaces" ></input> <input type=text value=no/quotes and spaces ></input> <input type=text value=no/quotes_no_spaces ></input> </body> </html> ```
It's [valid HTML 5](http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#before-attribute-value-state), but not valid XHTML. As a best practise, I would always include the quotes, even if you're not using XHTML.
Can browsers understand unquoted attributes values?
[ "", "javascript", "html", "tags", "" ]
I'm having trouble with the sql below. Basically I have rows that contains strings according to the format: 129&c=cars. I only want the digits part, e.g. 129. The sql query is: ``` $result = mysql_query("SELECT * FROM " . $db_table . " WHERE id LIKE '" . $id . "%'"); ``` Why doesn't % work? I can't use %...% because it catches too much.
I would actually recommend using regular expressions fo the matching, but unfortunately, there is no way to capture the matching part with mysql. You will have to do the extraction in php. If you have an array containing all the results called `$array`: ``` $array = preg_replace('/^(\d+).*/', '$1', $array); ```
You can use the MySQL 'regexp' stuff in the WHERE clause to reduce the amount of data retrieved to just the rows you want. The basic for of your query would look like: ``` SELECT * FROM table WHERE field REGEXP '^$id&' ``` where $id is inserted by PHP and the data you want is always at the start of the field and followed by a &. If not, adjust the regex to suit, of course. MySQL's regex engine can't do capturing, unfortunately, so you'll still have to do some parsing in PHP as soulmerge showed above, but with the 'where regexp' stuff in MySQL, you'll only have to deal with rows you know contain the data you want, not the entire table.
Sql: search column that starts with digits
[ "", "php", "mysql", "" ]
*(I wish I could have come up with a more descriptive title... suggest one or edit this post if you can name the type of query I'm asking about)* Database: **SQL Server 2000** **Sample Data (assume 500,000 rows):** ``` Name Candy PreferenceFactor Jim Chocolate 1.0 Brad Lemon Drop .9 Brad Chocolate .1 Chris Chocolate .5 Chris Candy Cane .5 499,995 more rows... ``` Note that the number of rows with a given 'Name' is unbounded. **Desired Query Results:** ``` Jim Chocolate 1.0 Brad Lemon Drop .9 Chris Chocolate .5 ~250,000 more rows... ``` (Since Chris has equal preference for Candy Cane and Chocolate, a consistent result is adequate). **Question:** How do I Select Name, Candy from data where each resulting row contains a unique Name such that the Candy selected has the highest PreferenceFactor for each Name. (speedy efficient answers preferred). What indexes are required on the table? Does it make a difference if Name and Candy are integer indexes into another table (aside from requiring some joins)?
``` select c.Name, max(c.Candy) as Candy, max(c.PreferenceFactor) as PreferenceFactor from Candy c inner join ( select Name, max(PreferenceFactor) as MaxPreferenceFactor from Candy group by Name ) cm on c.Name = cm.Name and c.PreferenceFactor = cm.MaxPreferenceFactor group by c.Name order by PreferenceFactor desc, Name ```
You will find that the following query outperforms every other answer given, as it works with a single scan. This simulates MS Access's First and Last aggregate functions, which is basically what you are doing. Of course, you'll probably have foreign keys instead of names in your CandyPreference table. To answer your question, it is in fact very much best if Candy and Name are foreign keys into another table. If there are other columns in the CandyPreferences table, then having a covering index that includes the involved columns will yield even better performance. Making the columns as small as possible will increase the rows per page and again increase performance. If you are most often doing the query with a WHERE condition to restrict rows, then an index that covers the WHERE conditions becomes important. Peter was on the right track for this, but had some unneeded complexity. ``` CREATE TABLE #CandyPreference ( [Name] varchar(20), Candy varchar(30), PreferenceFactor decimal(11, 10) ) INSERT #CandyPreference VALUES ('Jim', 'Chocolate', 1.0) INSERT #CandyPreference VALUES ('Brad', 'Lemon Drop', .9) INSERT #CandyPreference VALUES ('Brad', 'Chocolate', .1) INSERT #CandyPreference VALUES ('Chris', 'Chocolate', .5) INSERT #CandyPreference VALUES ('Chris', 'Candy Cane', .5) SELECT [Name], Candy = Substring(PackedData, 13, 30), PreferenceFactor = Convert(decimal(11,10), Left(PackedData, 12)) FROM ( SELECT [Name], PackedData = Max(Convert(char(12), PreferenceFactor) + Candy) FROM CandyPreference GROUP BY [Name] ) X DROP TABLE #CandyPreference ``` I actually don't recommend this method unless performance is critical. The "canonical" way to do it is OrbMan's standard Max/GROUP BY derived table and then a join to it to get the selected row. Though, that method starts to become difficult when there are several columns that participate in the selection of the Max, and the final combination of selectors can be duplicated, that is, when there is no column to provide arbitrary uniqueness as in the case here where we use the name if the PreferenceFactor is the same. Edit: It's probably best to give some more usage notes to help improve clarity and to help people avoid problems. * As a general rule of thumb, when trying to improve query performance, you can do a LOT of extra math if it will save you I/O. Saving an entire table seek or scan speeds up the query substantially, even with all the converts and substrings and so on. * Due to precision and sorting issues, use of a floating point data type is probably a bad idea with this method. Though unless you are dealing with extremely large or small numbers, you shouldn't be using float in your database anyway. * The best data types are those that are not packed and sort in the same order after conversion to binary or char. Datetime, smalldatetime, bigint, int, smallint, and tinyint all convert directly to binary and sort correctly because they are not packed. With binary, avoid left() and right(), use substring() to get the values reliably returned to their originals. * I took advantage of Preference having only one digit in front of the decimal point in this query, allowing conversion straight to char since there is always at least a 0 before the decimal point. If more digits are possible, you would have to decimal-align the converted number so things sort correctly. Easiest might be to multiply your Preference rating so there is no decimal portion, convert to bigint, and then convert to binary(8). In general, conversion between numbers is faster than conversion between char and another data type, especially with date math. * Watch out for nulls. If there are any, you must convert them to something and then back.
Efficient SQL 2000 Query for Selecting Preferred Candy
[ "", "sql", "database", "sql-server-2000", "" ]
For some reason, when using this code the file it outputs is just called ".jpg". ``` <? $title = $GET['title']; $url = $GET['url']; $ourFileName = $title.jpg; $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); fclose($ourFileHandle); $ch = curl_init ("http://www.address.com/url=$url"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen("images/$ourFileName",'w'); fwrite($fp, $rawdata); fclose($fp); echo ("<img src=images/$ourFileName>"); ?> ``` Pretty sure it has to do with declaring $ourFileName, any help would be appreciated.
Looks like this line ``` $ourFileName = $title.jpg; ``` Should be ``` $ourFileName = $title . ".jpg"; ``` That should do it as long as you are sure there is a value in $\_GET['title'];
Are you sure `$GET['title']` is correct? The superglobal variable for accessing the GET parameter values is `$_GET`, not `$GET`.
cant get php to save filename with correct name
[ "", "php", "curl", "fopen", "" ]
Is there any way to get at least some information inside of here? ``` ... catch(...) { std::cerr << "Unhandled exception" << std::endl; } ``` I have this as a last resort around all my code. Would it be better to let it crash, because then I at least could get a crash report?
No, there isn't any way. Try making all your exception classes derive from one single class, like `std::exception`, and then catch that one. You could rethrow in a nested `try`, though, in an attempt to figure out the type. But then you could aswell use a previous catch clause (and **`...`** only as fall-back).
You can do this using gdb or another debugger. Tell the debugger to stop when any exception is throw (in gdb the command is hilariously `catch throw`). Then you will see not only the type of the exception, but where exactly it is coming from. Another idea is to comment out the `catch (...)` and let your runtime terminate your application and hopefully tell you more about the exception. Once you figure out what the exception is, you should try to replace or augment it with something that does derive from `std::exception`. Having to `catch (...)` at all is not great. If you use GCC or Clang you can also try `__cxa_current_exception_type()->name()` to get the name of the current exception type.
Is there any way to get some information at least for catch(...)?
[ "", "c++", "exception", "" ]
If you need your web application to translate between timezones on a per-user basis, why not use TIMESTAMP across the board for all date/time fields? Consider that TIMESTAMP values are stored in UTC and converted to the timezone set for the connection when retrieved. I have asked this question on IRC, read the MySQL documentation, searched Google extensively, and asked my co-workers, and I have yet to find a compelling reason to not use TIMESTAMP. Note: I understand TIMESTAMP has a limited range of 1970 - 2038; that is not going to be an issue in my case. Also, I am using PHP with MySQL.
DATETIME is for arbitrary dates and times that you utilize in your data. TIMESTAMP is for when you want the time to be automatically updated. If you want to know when the row was inserted/updated, use a TIMESTAMP. Also, keep in mind that a TIMESTAMP is only *stored* in UTC -- it is converted to the local timezone of the server before it is transmitted back as part of a query. In your case, you're better off using a DATETIME. If you're worried about UTC, that's fine -- just create your dates in UTC rather than using the local time. Use [UTC\_TIMESTAMP](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_utc-timestamp).
I think your answer is here: > I understand TIMESTAMP has a limited range of 1970 - 2038; *that is not going to be an issue in my case.* I would be careful making assumptions about the longevity of projects ***especially when it comes to database schemas***. Databases have a tendency to remain in place and in use long after the applications that used them have gone away.
Why not use MySQL's TIMESTAMP across the board?
[ "", "php", "mysql", "timezone", "" ]
Given 2 tables called "table1" and "table1\_hist" that structurally resemble this: ``` TABLE1 id status date_this_status 1 open 2008-12-12 2 closed 2009-01-01 3 pending 2009-05-05 4 pending 2009-05-06 5 open 2009-06-01 TABLE1_hist id status date_this_status 2 open 2008-12-24 2 pending 2008-12-26 3 open 2009-04-24 4 open 2009-05-04 ``` With table1 being the current status and table1\_hist being a history table of table1, how can I return the rows for each id that has the earliest date. In other words, for each id, I need to know it's earliest status and date. ``` EXAMPLE: For id 1 earliest status and date is open and 2008-12-12. For id 2 earliest status and date is open and 2008-12-24. ``` I've tried using MIN(datetime), unions, dynamic SQL, etc. I've just reached tsql writers block today and I'm stuck. **Edited to add:** Ugh. This is for a SQL2000 database, so Alex Martelli's answer won't work. ROW\_NUMBER wasn't introduced until SQL2005.
The following code sample is completely self-sufficient, just copy and paste it into a management studio query and hit F5 =) ``` DECLARE @TABLE1 TABLE ( id INT, status VARCHAR(50), date_this_status DATETIME ) DECLARE @TABLE1_hist TABLE ( id INT, status VARCHAR(50), date_this_status DATETIME ) --TABLE1 INSERT @TABLE1 SELECT 1, 'open', '2008-12-12' UNION ALL SELECT 2, 'closed', '2009-01-01' UNION ALL SELECT 3, 'pending', '2009-05-05' UNION ALL SELECT 4, 'pending', '2009-05-06' UNION ALL SELECT 5, 'open', '2009-06-01' --TABLE1_hist INSERT @TABLE1_hist SELECT 2, 'open', '2008-12-24' UNION ALL SELECT 2, 'pending', '2008-12-26' UNION ALL SELECT 3, 'open', '2009-04-24' UNION ALL SELECT 4, 'open', '2009-05-04' SELECT x.id, ISNULL(y.[status], x.[status]) AS [status], ISNULL(y.date_this_status, x.date_this_status) AS date_this_status FROM @TABLE1 x LEFT JOIN ( SELECT a.* FROM @TABLE1_hist a INNER JOIN ( SELECT id, MIN(date_this_status) AS date_this_status FROM @TABLE1_hist GROUP BY id ) b ON a.id = b.id AND a.date_this_status = b.date_this_status ) y ON x.id = y.id ```
SQL Server 2005 and later support an interesting (relatively recent) aspect of SQL Standards, "ranking/windowing functions", allowing: ``` WITH AllRows AS ( SELECT id, status, date_this_status, ROW_NUMBER() OVER(PARTITION BY id ORDER BY date_this_status ASC) AS row, FROM (SELECT * FROM Table1 UNION SELECT * FROM Table1_hist) Both_tables ) SELECT id, status, date_this_status FROM AllRows WHERE row = 1 ORDER BY id; ``` where I'm also using the nice (and equally "new") `WITH` syntax to avoid nesting the sub-query in the main `SELECT`. [This article](http://sqlservercode.blogspot.com/2006/03/ranking-in-sql-server-2000.html) shows how one could hack the equivalent of `ROW_NUMBER` (and also `RANK` and `DENSE_RANK`, the other two "new" ranking/windowing functions) in SQL Server 2000 -- but that's not necessarily pretty nor especially well-performing, alas.
TSQL: Return row(s) with earliest dates
[ "", "sql", "t-sql", "" ]
I am following the [Jetty HttpClient Example](http://docs.codehaus.org/display/JETTY/Jetty+HTTP+Client), but I am unable to get an SSL connection working. When I connect using a proxy, it throws a "Not Implemented" exception. When I don't use a proxy, it doesn't return anything. ``` HttpClient client = new HttpClient(); client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL); client.setProxy(new Address("www.example.com", 80)); client.start(); // create the exchange object, which lets you define where you want to go // and what you want to do once you get a response ContentExchange exchange = new ContentExchange() { // define the callback method to process the response when you get it // back protected void onResponseComplete() throws IOException { super.onResponseComplete(); String responseContent = this.getResponseContent(); // do something with the response content System.out.println(responseContent); } }; exchange.setMethod("GET"); exchange.setURL("https://www.example.com"); exchange.setScheme(HttpSchemes.HTTPS_BUFFER); // start the exchange client.send(exchange); exchange.waitForDone(); System.err.println("Response status: " + exchange.getResponseStatus()); ```
Jetty v7.4.1: ``` if (dest.isSecure()) { if (dest.isProxied()) { SSLEngine engine=newSslEngine(channel); ep = new ProxySelectChannelEndPoint(channel, selectSet, key, _sslBuffers, engine, (int)_httpClient.getIdleTimeout()); } else { ... ```
Yeah weird, the source code for the Jetty-Client's SelectConnector looks like the following: ``` if (dest.isProxied()) { String connect = HttpMethods.CONNECT+" "+dest.getAddress()+HttpVersions.HTTP_1_0+"\r\n\r\n"; // TODO need to send this over channel unencrypted and setup endpoint to ignore the 200 OK response. throw new IllegalStateException("Not Implemented"); } ``` so the functionality doesn't exist at present - at least in the version I'm using (6.1.16) for using a proxy in this kind of way. It's also the same in the milestone Jetty 7 version (I found after downloading the source code). I suggest your try a different client - check out Apache HttpClient: <http://hc.apache.org/httpclient-3.x/> The Jetty developers should really have marked this clearly in the Javadocs. another alternative is to implementinghave a go at implementing the feature for them and submitting it back as a patch.
Jetty HTTP Client with SSL
[ "", "java", "https", "" ]
Is there any downside to calling pthread\_cond\_timedwait without taking a lock on the associated mutex first, and also not taking a mutex lock when calling pthread\_cond\_signal ? In my case there is really no condition to check, I want a behavior very similar to Java wait(long) and notify(). According to the documentation, there can be "unpredictable scheduling behavior". I am not sure what that means. An example program seems to work fine without locking the mutexes first.
The first is not OK: > The `pthread_cond_timedwait()` and > `pthread_cond_wait()` functions shall > block on a condition variable. They > shall be called with mutex locked by > the calling thread or undefined > behavior results. <http://opengroup.org/onlinepubs/009695399/functions/pthread_cond_timedwait.html> The reason is that the implementation may want to rely on the mutex being locked in order to safely add you to a waiter list. And it may want to release the mutex without first checking it is held. The second is disturbing: > if predictable scheduling behaviour is > required, then that mutex is locked by > the thread calling > `pthread_cond_signal()` or > `pthread_cond_broadcast()`. <http://www.opengroup.org/onlinepubs/007908775/xsh/pthread_cond_signal.html> Off the top of my head, I'm not sure what the specific race condition is that messes up scheduler behaviour if you signal without taking the lock. So I don't know how bad the undefined scheduler behaviour can get: for instance maybe with broadcast the waiters just don't get the lock in priority order (or however your particular scheduler normally behaves). Or maybe waiters can get "lost". Generally, though, with a condition variable you want to set the condition (at least a flag) and signal, rather than just signal, and for this you need to take the mutex. The reason is that otherwise, if you're concurrent with another thread calling wait(), then you get completely different behaviour according to whether wait() or signal() wins: if the signal() sneaks in first, then you'll wait for the full timeout even though the signal you care about has already happened. That's rarely what users of condition variables want, but may be fine for you. Perhaps this is what the docs mean by "unpredictable scheduler behaviour" - suddenly the timeslice becomes critical to the behaviour of your program. Btw, in Java you have to have the lock in order to notify() or notifyAll(): > This method should only be called by a > thread that is the owner of this > object's monitor. <http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#notify()> The Java synchronized {/}/wait/notifty/notifyAll behaviour is analogous to pthread\_mutex\_lock/pthread\_mutex\_unlock/pthread\_cond\_wait/pthread\_cond\_signal/pthread\_cond\_broadcast, and not by coincidence.
Butenhof's excellent "Programming with POSIX Threads" discusses this right at the end of chapter 3.3.3. Basically, signalling the condvar without locking the mutex is a **potential** performance optimisation: if the signalling thread has the mutex locked, then the thread waking on the condvar has to immediately block on the mutex that the signalling thread has locked even if the signalling thread is not modifying any of the data the waiting thread will use. The reason that "unpredictable scheduler behavior" is mentioned is that if you have a high-priority thread waiting on the condvar (which another thread is going to signal and wakeup the high priority thread), any other lower-priority thread can come and lock the mutex so that when the condvar is signalled and the high-priority thread is awakened, it has to wait on the lower-priority thread to release the mutex. If the mutex is locked whilst signalling, then the higher-priority thread will be scheduled on the mutex before the lower-priority thread: basically you know that that when you "awaken" the high-priority thread it will awaken as soon as the scheduler allows it (of course, you might have to wait on the mutex before signalling the high-priority thread, but that's a different issue).
Not locking mutex for pthread_cond_timedwait and pthread_cond_signal ( on Linux )
[ "", "c++", "c", "multithreading", "pthreads", "mutex", "" ]
Can I have object with the same name as class in javascript?
There are no classes per se in javascript, only methods that build objects. **UPDATE: ES6, also known as ECMAScript2015, introduced classes.** To directly answer your question, yes and no. You can create a function that builds your object, but as soon as you have a variable of the same name, the function is destroyed. there is no difference between ``` function bob() { //code goes here this.name = "bob"; } ``` and ``` var bob = function() { //code goes here this.name = "bob"; } ``` --- What would then happen if you declared a variable named bob like: ``` var bob = new bob(); ``` In this case, the function bob would be called, the object created, and the function bob clobbered by the new variable bob. --- If you want to create a singleton, then you might as well use a closure as follows: ``` var bob = new (function() { //code goes here this.name = "bob"; })(); ```
What about jQuery: `$('string')`, a function as far as I can tell, and `$.ajax`, a class with a method named ajax. Function named `$` and class named `$`. I know I am wrong but this is what it looks like.
Can I have object with the same name as class in javascript?
[ "", "javascript", "class", "oop", "" ]
I have the following code ``` $str = "keyword keyword 'keyword 1 and keyword 2' another 'one more'".'"another keyword" yes,one,two'; preg_match_all('/"[^"]+"|[^"\' ,]+|\'[^\']+\'/', $str, $matches); echo "<pre>"; print_r($matches); echo "</pre>"; ``` Where I want it to extract keywords from a string, and keep those wrapped within single or double quotes together, this above code works OK, but it returns the values with the quotes in it. I know I can remove these via str\_replace or similar, but I'm really looking for a way to solve this via the preg\_match\_all function. Output: ``` Array ( [0] => Array ( [0] => keyword [1] => keyword [2] => 'keyword 1 and keyword 2' [3] => another [4] => 'one more' [5] => "another keyword" [6] => yes [7] => one [8] => two ) ) ``` Also, I think my regex is a little be soppy, so any suggestions for a better would would be good :) Any suggestions / help would be greatly appreciated.
You've almost got it; you just need to use lookarounds to match the quotes: ``` '/(?<=\')[^\'\s][^\']*+(?=\')|(?<=")[^"\s][^"]*+(?=")|[^\'",\s]+/' ```
``` preg_match_all('/"([^"]+)"|[^"\' ,]+|\'([^\']+)\'/',$str,$matches); ``` and use `$matches[1]` and `$matches[2]`.
Extract keywords/tags from string using Preg_match_all
[ "", "php", "regex", "preg-match-all", "" ]
I want to compare several strings to each other, and find the ones that are the most similar. I was wondering if there is any library, method or best practice that would return me which strings are more similar to other strings. For example: * "The quick fox jumped" -> "The fox jumped" * "The quick fox jumped" -> "The fox" This comparison would return that the first is more similar than the second. I guess I need some method such as: ``` double similarityIndex(String s1, String s2) ``` Is there such a thing somewhere? EDIT: Why am I doing this? I am writing a script that compares the output of a MS Project file to the output of some legacy system that handles tasks. Because the legacy system has a very limited field width, when the values are added the descriptions are abbreviated. I want some semi-automated way to find which entries from MS Project are similar to the entries on the system so I can get the generated keys. It has drawbacks, as it has to be still manually checked, but it would save a lot of work
Yes, there are many well documented algorithms like: * Cosine similarity * Jaccard similarity * Dice's coefficient * Matching similarity * Overlap similarity * etc etc A good summary ("Sam's String Metrics") [can be found here](https://web.archive.org/web/20081224234350/http://www.dcs.shef.ac.uk/~sam/stringmetrics.html) (original link dead, so it links to Internet Archive) Also check these projects: * [Simmetrics](https://github.com/Simmetrics) * [jtmt](http://jtmt.sourceforge.net/)
The common way of **calculating the similarity between two strings in a 0%-100% fashion**, as used in many libraries, is to measure how much (in %) you'd have to change the longer string to turn it into the shorter: ``` /** * Calculates the similarity (a number within 0 and 1) between two strings. */ public static double similarity(String s1, String s2) { String longer = s1, shorter = s2; if (s1.length() < s2.length()) { // longer should always have greater length longer = s2; shorter = s1; } int longerLength = longer.length(); if (longerLength == 0) { return 1.0; /* both strings are zero length */ } return (longerLength - editDistance(longer, shorter)) / (double) longerLength; } // you can use StringUtils.getLevenshteinDistance() as the editDistance() function // full copy-paste working code is below ``` ### Computing the `editDistance()`: The `editDistance()` function above is expected to calculate the **edit distance** between the two strings. There are [several implementations](http://en.wikipedia.org/wiki/String_metric) to this step, each may suit a specific scenario better. The most common is the ***[Levenshtein distance algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance)*** and we'll use it in our example below (for very large strings, other algorithms are likely to perform better). Here's two options to calculate the edit distance: * You can use **[Apache Commons Text](https://commons.apache.org/proper/commons-text/)**'s implementation of Levenshtein distance: [`apply(CharSequence left, CharSequence rightt)`](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/similarity/LevenshteinDistance.html) * Implement it in your own. Below you'll find an example implementation. ### Working example: [**See online demo here.**](http://ideone.com/oOVWYj) ``` public class StringSimilarity { /** * Calculates the similarity (a number within 0 and 1) between two strings. */ public static double similarity(String s1, String s2) { String longer = s1, shorter = s2; if (s1.length() < s2.length()) { // longer should always have greater length longer = s2; shorter = s1; } int longerLength = longer.length(); if (longerLength == 0) { return 1.0; /* both strings are zero length */ } /* // If you have Apache Commons Text, you can use it to calculate the edit distance: LevenshteinDistance levenshteinDistance = new LevenshteinDistance(); return (longerLength - levenshteinDistance.apply(longer, shorter)) / (double) longerLength; */ return (longerLength - editDistance(longer, shorter)) / (double) longerLength; } // Example implementation of the Levenshtein Edit Distance // See http://rosettacode.org/wiki/Levenshtein_distance#Java public static int editDistance(String s1, String s2) { s1 = s1.toLowerCase(); s2 = s2.toLowerCase(); int[] costs = new int[s2.length() + 1]; for (int i = 0; i <= s1.length(); i++) { int lastValue = i; for (int j = 0; j <= s2.length(); j++) { if (i == 0) costs[j] = j; else { if (j > 0) { int newValue = costs[j - 1]; if (s1.charAt(i - 1) != s2.charAt(j - 1)) newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; costs[j - 1] = lastValue; lastValue = newValue; } } } if (i > 0) costs[s2.length()] = lastValue; } return costs[s2.length()]; } public static void printSimilarity(String s, String t) { System.out.println(String.format( "%.3f is the similarity between \"%s\" and \"%s\"", similarity(s, t), s, t)); } public static void main(String[] args) { printSimilarity("", ""); printSimilarity("1234567890", "1"); printSimilarity("1234567890", "123"); printSimilarity("1234567890", "1234567"); printSimilarity("1234567890", "1234567890"); printSimilarity("1234567890", "1234567980"); printSimilarity("47/2010", "472010"); printSimilarity("47/2010", "472011"); printSimilarity("47/2010", "AB.CDEF"); printSimilarity("47/2010", "4B.CDEFG"); printSimilarity("47/2010", "AB.CDEFG"); printSimilarity("The quick fox jumped", "The fox jumped"); printSimilarity("The quick fox jumped", "The fox"); printSimilarity("kitten", "sitting"); } } ``` **Output:** ``` 1.000 is the similarity between "" and "" 0.100 is the similarity between "1234567890" and "1" 0.300 is the similarity between "1234567890" and "123" 0.700 is the similarity between "1234567890" and "1234567" 1.000 is the similarity between "1234567890" and "1234567890" 0.800 is the similarity between "1234567890" and "1234567980" 0.857 is the similarity between "47/2010" and "472010" 0.714 is the similarity between "47/2010" and "472011" 0.000 is the similarity between "47/2010" and "AB.CDEF" 0.125 is the similarity between "47/2010" and "4B.CDEFG" 0.000 is the similarity between "47/2010" and "AB.CDEFG" 0.700 is the similarity between "The quick fox jumped" and "The fox jumped" 0.350 is the similarity between "The quick fox jumped" and "The fox" 0.571 is the similarity between "kitten" and "sitting" ```
Similarity String Comparison in Java
[ "", "java", "string-comparison", "" ]
My adventures in Java have lead me to look into Clojure, which then lead me to (re)discover Emacs and that lead me to SLIME. I have a fairly decent handle on Emacs itself, and I have the emacs-starter-kit as well as clojure-mode/slime/swank as well as a few other unrelated modes and tweaks setup and running. But setting up a program and understanding its capabilities are not the same. So now before I get back into experimenting with Clojure I'd like to first figure out a little more about the Slime IDE itself and what it can do. Can anyone recommend a tutorial/screencast which will teach me some fundamental Slime usage? I am already familiar with executing Clojure interactively with Slime, but surely that cant be Slime's only feature. The tutorial doesn't need to involve Clojure but if it does then that would be a plus, but the main focus of my interest is Slime so please don't post Clojure tutorials unless they highlight Slime usage beyond merely executing Clojure code interactively.
I really liked Marco Barringer's SLIME movie when I started out: <http://www.guba.com/watch/3000054867> Also, having a transcript of it helps: <http://www.pchristensen.com/blog/articles/reference-for-the-slimelispemacs-screencast/> I also found Bill Clementson's post helpful but it's more about set-up and not usage. <http://bc.tech.coop/blog/081205.html>
You could do worse than read the SLIME manual. On my system (Ubuntu), it is located at `/usr/share/doc/slime/slime.pdf`.
Please recommend a good Slime tutorial or screencast
[ "", "java", "emacs", "clojure", "slime", "" ]
How can I receive a file as a command-line argument?
Just the path of the file is passed, inside your program use the Java File class to handle it This takes the first parameter as the file path: ``` import java.io.File; public class SomeProgram { public static void main(String[] args) { if(args.length > 0) { File file = new File(args[0]); // Work with your 'file' object here } } } ```
in Java, the `main` method receives an array of String as argument, as you probably have noticed. you can give another name to the parameter `args`, but this is the most used one. the array `args` contains the values of what the user has typed when launching your program, after the class name. for example, to run a class named Foo, the user must type: > [user@desktop ~]$ java Foo everything the user types after the class name is considered to be a parameter. for example: > [user@desktop ~]$ java Foo **bar baz** now your program has received two parameters: **bar** and **baz**. those parameters are stored in the array `args`. as a regular Java array, the first parameter can be retrieved by accessing `args[0]`, the second parameter can be retrieved by accessing `args[1]`, and so on. if you try to access an invalid position (when the user didn't type what you expected), that statement will throw an `ArrayIndexOutOfBoundsException`, just like it would with any array. you can check how many parameters were typed with `args.length`. so, back to your question. the user may inform a file name as a command line parameter and you can read that value through the argument of the `main` method, usually called `args`. you have to check if he really typed something as an argument (checking the array length), and if it's ok, you access `args[0]` to read what he's typed. then, you may create a `File` object based on that string, and do what you want to do with it. always check if the user typed the number of parameters you are expecting, otherwise you'll get an exception when accessing the array. here's a full example of how to use command line parameters: ``` public class Foo { public static void main(String[] args) { if (args.length == 0) { System.out.println("no arguments were given."); } else { for (String a : args) { System.out.println(a); } } } } ``` this class will parse the parameters informed by the user. if he hasn't type anything, the class will print the message "no arguments were given." if he informs any number of parameters, those parameters will be shown on the screen. so, running this class with the two examples I've given on this answer, the output would be: > [user@desktop ~]$ java Foo > no arguments were given. > [user@desktop ~]$ java Foo bar baz > bar > baz
Using command-line argument for passing files to a program
[ "", "java", "file", "argument-passing", "" ]
Do all boost exceptions derive from std::exception? If not do they all derive from some base exception class?
According to [the documentation](http://www.boost.org/doc/libs/1_39_0/libs/exception/doc/exception_exception_hpp.html) `boost::exception` doesn't inherit `std::exception`. The [FAQ](http://www.boost.org/doc/libs/1_61_0/libs/exception/doc/frequently_asked_questions.html) explains why. However [this page](http://www.boost.org/doc/libs/1_39_0/libs/exception/doc/exception_types_as_simple_semantic_tags.html) explains how to correctly use Boost exceptions.
A "good Boost citizen" library should throw using `boost::throw_exception`, in order to support configurations where exception handling is disabled. The `boost::throw_exception` function requires that the type of the passed exception derives publicly from `std::exception` (as of version 1.37.0 or thereabouts `boost::throw_exception` will issue a compile error if that requirement is not met.) In addition and by default, exceptions emitted using `boost::throw_exception` derive from `boost::exception`. However, there is no requirement for Boost libraries to throw exceptions through `boost:throw_exception` or to derive from `std::exception`.
boost exceptions
[ "", "c++", "boost", "exception", "" ]
How can I copy a `string[]` from another `string[]`? Suppose I have `string[] args`. How can I copy it to another array `string[] args1`?
Allocate space for the target array, that use Array.CopyTo(): ``` targetArray = new string[sourceArray.Length]; sourceArray.CopyTo( targetArray, 0 ); ```
* To create a completely new array with the same contents (as a shallow copy): call [`Array.Clone`](http://msdn.microsoft.com/en-us/library/system.array.clone.aspx) and just cast the result. * To copy a portion of a string array into another string array: call [`Array.Copy`](http://msdn.microsoft.com/en-us/library/system.array.copy.aspx) or [`Array.CopyTo`](http://msdn.microsoft.com/en-us/library/system.array.copyto.aspx) For example: ``` using System; class Test { static void Main(string[] args) { // Clone the whole array string[] args2 = (string[]) args.Clone(); // Copy the five elements with indexes 2-6 // from args into args3, stating from // index 2 of args3. string[] args3 = new string[5]; Array.Copy(args, 2, args3, 0, 5); // Copy whole of args into args4, starting from // index 2 (of args4) string[] args4 = new string[args.Length+2]; args.CopyTo(args4, 2); } } ``` Assuming we start off with `args = { "a", "b", "c", "d", "e", "f", "g", "h" }` the results are: ``` args2 = { "a", "b", "c", "d", "e", "f", "g", "h" } args3 = { "c", "d", "e", "f", "g" } args4 = { null, null, "a", "b", "c", "d", "e", "f", "g", "h" } ```
Copy one string array to another
[ "", "c#", "arrays", "copy", "" ]
I have need to create 2 buttons on my site that would change the browser zoom level (+) (-). I'm requesting browser zoom and not css zoom because of image size and layout issues. Well, is this even possible? I've heard conflicting reports.
I would say not possible in most browsers, at least not without some additional plugins. And in any case I would try to avoid relying on the browser's zoom as the implementations vary (some browsers only zoom the fonts, others zoom the images, too etc). Unless you don't care much about user experience. If you need a more reliable zoom, then consider zooming the page fonts and images with JavaScript and CSS, or possibly on the server side. The image and layout scaling issues could be addressed this way. Of course, this requires a bit more work.
Possible in IE and chrome although it does not work in firefox: ``` <script> function toggleZoomScreen() { document.body.style.zoom = "80%"; } </script> <img src="example.jpg" alt="example" onclick="toggleZoomScreen()"> ```
Changing the browser zoom level
[ "", "javascript", "browser", "zooming", "" ]
I'm trying to launch an external updater application for a platform that I've developed. The reason I'd like to launch this updater is because my configuration utility which handles updates and license configuration for the platform has shared dependencies with other assemblies in the folder where the update will be deployed. So, while I can rename the configuration utility and overwrite it when deploying the update, I can't rename or overwrite the DLLs it depends on. Hence, the external updater application. I'm handling all of the update gathering logic in the configuration utility, then attempting to launch the updater to handle the actual file copy/overwrite operations. Obviously, because of the file in use issues, I need the configuration utility to exit right after the updater begins. The problem I'm having is that I'm using the standard Process.Start method of launching the updater, and as soon as the configuration utility exits, the updater process gets killed too. Is there any way that I can create a Process that outlives its parent, or launch an external application that can run beyond the program that launched it? EDIT: Apparently, in my updater application, I miscalculated the number of command line arguments which are passed to it. Because of this, the updater would exit immediately. I misinterpreted this to mean that the launcher application was killing the "child" process, when in fact, it wasn't. The answers below are correct.
It seems that the problem you are seeing has a different reason because the `Process` class will not kill any processes started using `Process.Start` when your application exits. See this simple sample program, the calculator will stay open: ``` using System.Diagnostics; class Program { static void Main(string[] args) { Process.Start(@"C:\windows\system32\calc.exe"); } } ```
There's no reason why a process started with `Process.Start` should automatically die when the launcher exits. My guess is that you're doing something odd in the updater. I've written an updater doing exactly this kind of thing before, and it's been fine. For example: Launcher.cs: ``` using System; using System.Diagnostics; class Launcher { static void Main() { Console.WriteLine("Launching launchee"); Process.Start("Launchee.exe"); Console.WriteLine("Launched. Exiting"); } } ``` Launchee.cs: ``` using System; using System.Threading; class Launchee { static void Main() { Console.WriteLine(" I've been launched!"); Thread.Sleep(5000); Console.WriteLine(" Exiting..."); } } ``` Compile both of them, separately, and run Launcher.exe. The "launchee" process definitely lasts longer than the launcher.
How to create a Process that outlives its parent
[ "", "c#", "windows", "process", "" ]