Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In C/C++, if a multi-byte wide character (wchar\_t) value is transmitted from a big-endian system to a little-endian system (or vice-versa), will it come out the same value on the other side? Or will the bytes need to be swapped?
Yes you will need to swap them. The bytes will be retrieved from the transport in the same order they were put in. Just at the other end the ordering of these bytes has a different meaning. So you need to convert them to the correct endian-ness (is that a word?). The tried and true method is to convert to network byte order before transport. Then convert back to host specific byte order (from network byte order) on receipt. A set of function to help with endian conversion: ``` ntohs Convert a 16-bit quantity from network byte order to host byte order ntohl Convert a 32-bit quantity from network byte order to host byte order htons Convert a 16-bit quantity from host byte order to network byte order htonl Convert a 32-bit quantity from host byte order to network byte order ``` Just to add another note of caution. Different systems use different size for wchar\_t so do not assume sizeof(wchar\_t) == 2. Additionally each host may use a different representational format for wchar\_t. To help deal with this most systems convert the text to a known format for transport (UTF-8 or UTF-16 are good choices). The convert the text back to the host specific format at the other end. You could look at IBM's icu this has all this functionality.
Endian conversion is not sufficient and as a consequence not needed. Sizeof(wchar\_t) differs, and therefore the encoding too. Hence, you need to agree on an interchange format. The logical choice is UTF-8. But since UTF-8 is byte-oriented, you do not have endianness issues anymore.
Is endian conversion required for wchar_t data?
[ "", "c++", "c", "endianness", "data-transfer", "wchar-t", "" ]
Imagine that I will make an async call in .NET, i.e. HttpWebRequest.BeginGetResponse, and the HttpWebRequest object isn't referenced at a broader scope. Will the Garbage Collector destroy it and cause problems? Example code: ``` using System; using System.Net; public class AsyncHttpWebRequest { void Main() { var Request = HttpWebRequest.Create("http://www.contoso.com"); var result = Request.BeginGetResponse(GetResponseCallback, null); } private void GetResponseCallback(IAsyncResult AsyncResult) { // Do Something.. } } ``` Alternate version (with the request being passed as an AsyncState): ``` using System; using System.Net; public class AsyncHttpWebRequest { void Main() { var Request = HttpWebRequest.Create("http://www.contoso.com"); var result = Request.BeginGetResponse(GetResponseCallback, Request); } private void GetResponseCallback(IAsyncResult AsyncResult) { // Do Something.. } } ```
An object is considered alive and non-eligible for garbage collection if any live thread contains a reference to it, or if it's referenced statically (directly or indirectly in both cases). In both examples the async API keeps a reference to your request (within the thread pool where async IO operations are lodged) and so it won't be garbage collected until it completes.
No, the garbage collector won't cause you problems. Don't assume that because **you** don't have access to the object, the garbage collector is going to clean it up. The garbage collector starts with a number of "roots" - objects and references that are known reachable. Then, all the objects reachable from those roots are found, and everything else is collected. Each running thread - including the thread(s) that process the Async calls are included in the list of roots.
Does the Garbage Collector destroy temporarily unreferenced objects during async calls in .NET?
[ "", "c#", ".net", "asynchronous", "garbage-collection", "" ]
I have a bunch of old classic ASP pages, many of which show database data in tables. None of the pages have any sorting functionality built in: you are at the mercy of whatever ORDER BY clause the original developer saw fit to use. I'm working on a quick fix to tack on sorting via client-side javascript. I have a script already written that mostly does what I need. However, I still need to add one bit of functionality. The table rows in these pages will often have alternating row colors, and the mechanism used to achieve this varies among the pages. It might be as simple as changing a CSS class or the styles may have been rendered inline by the ASP code. Right now after sorting the table each row keeps the coloring scheme is was rendered with and so the alternating rows no longer alternate. I was hoping to fix it with something simple like this: ``` /* "table" is a var for the table element I'm sorting. I've already verified it exists, and that there are at least three rows. At this point the first row (index 0) is always the header row. */ // check for alternating row styles: var RowStyle = table.rows[1].style; var AltStyle = table.rows[2].style; // SORT HAPPENS HERE!! // snip // Apply alternating row styles if (RowStyle === AltStyle) return true; for (var i=1,il=table.rows.length;i<il;i+=1) { if (i%2==0) table.rows[i].style=RowStyle; else table.rows[i].style=AltStyle; } ``` Unfortunately, you can't just set to an element's style property like this. It complains that the object has no setter. How else can I do this simply? No frameworks like jQuery allowed here- that's out of my hands. **Update:** While it would be the best solution, it's just not practical to refactor 100+ pages to all use classes rather than inline style. Also, sometimes there's more involved than just the background color. For example, a row may be much darker or lighter than the alternating row, with one style having a different foreground color as well to accommodate. Or an alternating style may set borders differently. I really don't know what is used on all of these pages, so I need something that will generically apply *all* styles from one row to another.
You can try grabbing the `cssText` and `className`. ``` var css1 = table.rows[1].style.cssText; var css2 = table.rows[2].style.cssText; var class1 = table.rows[1].className; var class2 = table.rows[2].className; // sort // loop if (i%2==0) { table.rows[i].style.cssText = css1; table.rows[i].className = class1; } else { table.rows[i].style.cssText = css2; table.rows[i].className = class2; } ``` Not entirely sure about browser compatibility with `cssText`, though.
You can set the style attribute of any element... the trick is that in IE you have to do it differently. ([bug 245](http://webbugtrack.blogspot.com/2007/10/bug-245-setattribute-style-does-not.html)) ``` //Standards base browsers elem.setAttribute('style', styleString); //Non Standards based IE browser elem.style.setAttribute('cssText', styleString); ``` Note that in IE8, in Standards Mode, the first way does work.
Set HTML element's style property in javascript
[ "", "javascript", "html", "styles", "" ]
I know how to do a regular php mysql search and display the results. However, because of the nature of what I'm trying to accomplish I need to be able to sort by relevancy. Let me explain this better: Normal Query "apple iphone applications" will search the database using %apple iphone application%, but if there aren't records which display that phrase in that exact order the search will produce nothing. What I basically need to do is search for 'apple', 'iphone' and 'applications' all separately and then merge the results into one, and then I need to grade the relevancy by how many instances of the word are found in the records. For example if I did what I wanted to do and it returned them following: ``` Iphone Applications From Apple Apple Make The Best Apple Iphone Applications Iphone Applications ``` They would rank as follows: ``` Apple Make The Best Apple Iphone Applications Iphone Applications From Apple Iphone Applications ``` Because of how many instances of the search terms are found. See highlighted: ``` [Apple] Make The Best [Apple] [Iphone] [Applications] [Iphone] [Applications] From [Apple] [Iphone] [Applications] ``` I hope I have explained this well enough and I would be extremely grateful if anyone could give me any pointers.
take a look at the [MySQL FULLTEXT search functions](http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html), These should automatically return results by relevancy, and give you much more control over your searches The only potential issue with using fulltext indexes is that they aren't supported by InnoDB tables.
Maybe this might help someone (order by relevance and keep word count): None full-text: ``` SELECT *, ( (value_column LIKE '%rusten%') + (value_column LIKE '%dagen%') + (value_column LIKE '%bezoek%') + (value_column LIKE '%moeten%') ) as count_words FROM data_table WHERE (value_column LIKE '%dagen%' OR value_column LIKE '%rusten%' OR value_column LIKE '%bezoek%' OR value_column LIKE '%moeten%') ORDER BY count_words DESC ``` Full-text: ``` SELECT * FROM data_table WHERE MATCH(value_column) AGAINST('+dagen +rusten +bezoek +moeten' IN BOOLEAN MODE) ORDER BY MATCH(value_column) AGAINST('+dagen +rusten +bezoek +moeten' IN BOOLEAN MODE) DESC; ```
PHP MySQL Search And Order By Relevancy
[ "", "php", "mysql", "search", "" ]
I read about using the CASE expression inside the WHERE clause here: <http://scottelkin.com/sql/using-a-case-statement-in-a-sql-where-clause/> I'm trying to use this to filter results from my select statement, based on a contract number which will be passed in by the user's application. My code currently throws an error of 'Invalid parameter' no matter what is passed in. I verified SELECT/FROM are working fine, as where as a WHERE clause without a CASE expression. Here is my code. ``` WHERE (CASE WHEN @ContractNo = 0 THEN @ContractNo ELSE @ContractNo END = tblContracts.ContractNo) ``` The redundancy of the code is for troubleshooting purposes, I'm planning on using wildcard filtering on the CASE later. I'm focusing on getting the syntax down right now. I believe this should return all records for which the parameter matches the contract number stored in the table. Any help or advice would be greatly appreciated.
After reading your explanation, there's a better way to do this without `CASE`: ``` WHERE @ContractNo = 0 OR tblContracts.ContractNo = @ContractNo ``` This will return only matching contract numbers, unless `@ContractNo` is 0, in which case it will return all records. **Edit:** I've just noticed that [casperOne proposed the same thing](https://stackoverflow.com/questions/414431/sql-case-expression-inside-where/414454#414454). I didn't see that. Big up yourself.
Are you sure you want to do this? Your case statement ALWAYS returns `@ContractNo`. I think what you are looking for is this: ``` where case @ContractNo when 0 then tblContracts.ContractNo else @ContractNo end = tblContracts.ContractNo ``` The filter above says "give me the contract where the `ContractNo` equals the parameter, or all of them if the parameter is 0. The previous filter only filtered where the contract number field is exactly equal to the parameter. Regardless, you should do this instead: ``` where @ContractNo = 0 or @ContractNo = tblContracts.ContractNo ``` The logic is much easier to understand, and on top of that (don't quote me on this), the optimizer probably will work better outside of the case statement.
SQL - CASE expression inside WHERE
[ "", "sql", "where-clause", "" ]
I can't find the answer to this anywhere, and before I start pawing through generated code with Reflector I thought it'd be worth asking: Suppose I have the following LINQ query run against DataTables in a DataSet: ``` var list = from pr in parentTable.AsEnumerable() join cr in childTable.AsEnumerable() on cr.Field<int>("ParentID") equals pr.Field<int>("ID") where pr.Field<string>("Value") == "foo" select cr; ``` If there's a DataRelation between the parent table and the child table that uses the key fields shown, will LINQ use it? That is, will it find the rows in the parent table for which Value is "foo" and then call `GetChildRows` to project the child rows? Or is this something that I have to specify explicitly? (And if so, how do I do this?)
I don't think so. In this case, LINQ to Objects will probably just treat the two sides as regular enumerable objects, and do the join manually (without looking at the `DataRelation`).
Digging around in Reflector didn't seem to give any indication that LINQ uses DataRelations, but that code's awfully hard to read. So I wrote a little performance test, and unless there's something dumb about the test that I missed, the results are pretty definitive: no, LINQ doesn't use DataRelations and GetChildRows() to project joined rows. If you want to iterate over child rows, you have to formulate the LINQ query to call GetChildRows() explicitly. And neither approach is anywhere near as performant as writing code that iterates over the array returned by GetChildRows(). Kind of unfortunate, because the difference in performance on large DataSets is significant enough that replacing LINQ with explicitly-implemented code is often going to be worthwhile, which generally isn't true of LINQ. My test code is below. The timing of the LINQ iteration using the join remains the same (about 580-590 ms on my machine) irrespective of whether the DataRelation is created before or after it. The LINQ iteration that uses GetChildRows() takes around 280 ms, The iteration directly over GetChildRows() takes under a millisecond. That's pretty surprising to me - enough so that I assumed I had a bug in the code when I first ran the test. (That's why I'm writing out the count each time - to make sure that the loops haven't been optimized out of existence by the compiler.) ``` class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); DataSet ds = new DataSet(); DataTable t1 = new DataTable(); t1.Columns.Add(new DataColumn { ColumnName = "ID", DataType = typeof (int), AutoIncrement = true }); t1.PrimaryKey = new [] { t1.Columns["ID"]}; ds.Tables.Add(t1); DataTable t2 = new DataTable(); t2.Columns.Add(new DataColumn { ColumnName = "ID", DataType = typeof(int), AutoIncrement = true }); t2.Columns.Add("ParentID", typeof(int)); t2.PrimaryKey = new[] { t2.Columns["ID"] }; ds.Tables.Add(t2); sw.Reset(); sw.Start(); PopulateTables(t1, t2); sw.Stop(); Console.WriteLine("Populating tables took {0} ms.", sw.ElapsedMilliseconds); Console.WriteLine(); var list1 = from r1 in t1.AsEnumerable() join r2 in t2.AsEnumerable() on r1.Field<int>("ID") equals r2.Field<int>("ParentID") where r1.Field<int>("ID") == 1 select r2; sw.Reset(); sw.Start(); int count = 0; foreach (DataRow r in list1) { count += r.Field<int>("ID"); } sw.Stop(); Console.WriteLine("count = {0}.", count); Console.WriteLine("Completed LINQ iteration in {0} ms.", sw.ElapsedMilliseconds); Console.WriteLine(); sw.Reset(); sw.Start(); ds.Relations.Add(new DataRelation("FK_t2_t1", t1.Columns["ID"], t2.Columns["ParentID"])); sw.Stop(); Console.WriteLine("Creating DataRelation took {0} ms.", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); var list2 = from r1 in t1.AsEnumerable() from r2 in r1.GetChildRows("FK_t2_t1") where r1.Field<int>("ID") == 1 select r2; count = 0; foreach (DataRow r in list2) { count += r.Field<int>("ID"); } sw.Stop(); Console.WriteLine("count = {0}.", count); Console.WriteLine("Completed LINQ iteration using nested query in {0} ms.", sw.ElapsedMilliseconds); Console.WriteLine(); sw.Reset(); sw.Start(); DataRow parentRow = t1.Select("ID = 1")[0]; count = 0; foreach (DataRow r in parentRow.GetChildRows("FK_t2_t1")) { count += r.Field<int>("ID"); } sw.Stop(); Console.WriteLine("count = {0}.", count); Console.WriteLine("Completed explicit iteration of child rows in {0} ms.", sw.ElapsedMilliseconds); Console.WriteLine(); Console.ReadLine(); } private static void PopulateTables(DataTable t1, DataTable t2) { for (int count1 = 0; count1 < 1000; count1++) { DataRow r1 = t1.NewRow(); t1.Rows.Add(r1); for (int count2 = 0; count2 < 1000; count2++) { DataRow r2 = t2.NewRow(); r2["ParentID"] = r1["ID"]; t2.Rows.Add(r2); } } } } ```
Does LINQ use DataRelations to optimize joins?
[ "", "c#", "linq", "join", "dataset", "datarelation", "" ]
I am trying to pass an XML list to a view but I am having trouble once I get to the view. My controller: ``` public ActionResult Search(int isbdn) { ViewData["ISBN"] = isbdn; string pathToXml= "http://isbndb.com/api/books.xml?access_key=DWD3TC34&index1=isbn&value1="; pathToXml += isbdn; var doc = XDocument.Load(pathToXml); IEnumerable<XElement> items = from m in doc.Elements() select m; ``` What would my view look like? Do I need to incorporate some type of XML data controller?
first.. you have to return the data to the view modal... ``` public ActionResult Search(int isbdn) { ViewData["ISBN"] = isbdn; string pathToXml= "http://isbndb.com/api/books.xml?access_key=DWD3TC34&index1=isbn&value1="; pathToXml += isbdn; var doc = XDocument.Load(pathToXml); IEnumerable<XElement> items = from m in doc.Elements() select m; return view(m); } ``` in your code behind you have to inherit ``` ViewPage < IEnumerable<XElement>> ``` and than your ViewData.Modal will be a strongly typed `IEnumerable<XElement>`. and you will be able to work with data as in the controller.
I don't know if you intentionally cut off your code half way through the method. But you should be able to do the following to get your elements from your controller action to the view: ``` ViewData["XmlItems"] = items; ``` then in your view you call ``` <% foreach(XElement e in ViewData["XmlItems"] as IEnumerable<XElement>) { %> <!-- do work here --> <% } %> ```
Passing a XML parsed list from a controller to a view in ASP.NET MVC
[ "", "c#", "asp.net-mvc", "xml", "" ]
I'd like to dynamicly parse in text wiki-content. I found [JsWiki](http://sourceforge.net/projects/jswiki) but its in beta form, and looks like with no community even developers). Any other?
It depends what you mean by wiki content. There are many wiki frameworks just as there are many formats for wiki text. If you're looking for something that parses mediawiki content, such as wikipedia, there's a [good list of parsers here](http://www.mediawiki.org/wiki/Alternative_parsers). Some are Javascript based and I've had a good experience with one of them, [InstaView](https://github.com/cscott/instaview). It may be that you're just looking for a form of simple markup, in which case you could try using a library like [ShowDown](http://attacklab.net/showdown/) instead.
You could use the [Ra-Ajax InPlaceEdit](http://ra-ajax.org/samples/Ajax-InPlaceEdit.aspx) for such things if you're on ASP.NET. It doesn't have automated built in wiki parsing, but it allows for adding up any control you wish including LinkButtons and Literals which you can then build up with the HTML you want yourself...
JavaScript edit-inplace-holders which work with Wiki sources
[ "", "javascript", "wiki-engine", "" ]
I'm fiddling with calling DLLs from C#, and came across the need to define my own structs. Lots of articles force a sequential layout for the struct with ``` [StructLayout(LayoutKind.Sequential)] struct Foo ... ``` So, I followed suite, and my programme worked. Now, when I took the line out, it still works. Why do I need it?
The internal layout of a managed struct is undocumented and undiscoverable. Implementation details like member order and packing are intentionally hidden. With the [StructLayout] attribute, you force the P/Invoke marshaller to impose a specific layout and packing. That the default just happens to match what you need to get your code to work is merely an accident. Although not an uncommon one. Note the Type.StructLayoutAttribute property.
Interesting point. I'm sure I had code that failed until I put in an explicit LayoutKind.Sequential, however I have confirmed Sequential is the default for structures even in 1.1. Note the [VB Reference for Structure](http://msdn.microsoft.com/en-us/library/k69kzbs1.aspx) implies at Remarks > Behaviour > Memory Consumption that you do need to specify StructLayout to confirm the memory layout, but the documentation for [StructLayoutAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx) states Sequential is the default for structures in Microsoft compilers.
When should I explicitly specify a StructLayout?
[ "", "c#", "interop", "struct", "marshalling", "" ]
I am developing a Java based desktop application. There are some data generated from the application object model that I need to persist (preferably to a file). There is also a requirement to protect the persisted file so that others can't derive the object model details from the data. What's the best strategy for doing these? I was in the impression that these requirements are very common for desktop apps. However, I haven't been able to found much useful info on it. Any suggestion appreciated.
Your question has two parts. 1st: How to persist data? 2nd: How to protect them? There is a lot of ways how to persist data. From simple XML, java serialization to own data format. There is no way how to prevent revers engineering data just by "plain text". You can just make it harder, but not impossible. To make it quite impossible you need to use strong encryption and here comes a problem. How to encrypt data and don't reveal secure token. If you are distributing secure token with your application it is just a matter of time to find it and problem is solved. So entering a secure token during installation is not an option. If user has to authenticate to use application it should help, but it is the same problem. The next option is to use custom protected bijection algorithm to obfuscate data. And the last option is to do nothing just keep the data format private and don't publish them and obfuscate your application to prevent from reverse engineering. At the best value comes simple obfuscation of data (XOR primenumber) with custom data format and obfuscated application.
If you don't need to modify this file you can serialize the object graph to a file. The contents are binary and they could only be read using the classes where they were written. You can also use Java DB ( shipped with java since 1.5 I think ) and an ORM tool for that such as Hibernate. **EDIT** It is bundled since 1.6 <http://developers.sun.com/javadb/>
Object persistence strategy for desktop application
[ "", "java", "desktop", "object-persistence", "" ]
That is, if I had two or more sets, and I wanted to return a new set containing either: 1. All of the elements each set has in common (AND). 2. All of the elements total of each set (OR). 3. All of the elements unique to each set. (XOR). Is there an easy, pre-existing way to do that? **Edit:** That's the wrong terminology, isn't it?
Assuming 2 Set objects a and b AND(intersection of two sets) ``` a.retainAll(b); ``` OR(union of two sets) ``` a.addAll(b); ``` XOR either roll your own loop: ``` foreach item if(a.contains(item) and !b.contains(item) || (!a.contains(item) and b.contains(item))) c.add(item) ``` or do this: ``` c.addAll(a); c.addAll(b); a.retainAll(b); //a now has the intersection of a and b c.removeAll(a); ``` See the [Set documentation](http://java.sun.com/javase/6/docs/api/java/util/Set.html) and this [page](http://java.sun.com/docs/books/tutorial/collections/interfaces/set.html). For more.
You can use the [Google-Collections Sets class](https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/Sets.java) which has the methods intersection() union() and symmetricDifference(). ``` Sets.intersection(set1, set2); Sets.union(set1, set2); SetView view = Sets.intersection(Sets.union(set1, set2), set3); Set result = view.copyInto(new HashSet()); ```
Java: Is there an easy, quick way to AND, OR, or XOR together sets?
[ "", "java", "union", "set", "intersection", "" ]
I have a .NET assembly which I am accessing from VBScript (classic ASP) via COM interop. One class has an indexer (a.k.a. default property) which I got working from VBScript by adding the following attribute to the indexer: `[DispId(0)]`. It works in most cases, but not when accessing the class as a member of another object. How can I get it to work with the following syntax: `Parent.Member("key")` where Member has the indexer (similar to accessing the default property of the built-in `Request.QueryString`: `Request.QueryString("key")`)? In my case, there is a parent class `TestRequest` with a `QueryString` property which returns an `IRequestDictionary`, which has the default indexer. VBScript example: ``` Dim testRequest, testQueryString Set testRequest = Server.CreateObject("AspObjects.TestRequest") Set testQueryString = testRequest.QueryString testQueryString("key") = "value" ``` The following line causes an error instead of printing "value". This is the syntax I would like to get working: ``` Response.Write(testRequest.QueryString("key")) ``` > Microsoft VBScript runtime (0x800A01C2) > Wrong number of arguments or invalid property assignment: 'QueryString' However, the following lines *do* work without error and output the expected "value" (note that the first line accesses the default indexer on a temporary variable): ``` Response.Write(testQueryString("key")) Response.Write(testRequest.QueryString.Item("key")) ``` Below are the simplified interfaces and classes in C# 2.0. They have been registered via `RegAsm.exe /path/to/AspObjects.dll /codebase /tlb`: ``` [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IRequest { IRequestDictionary QueryString { get; } } [ClassInterface(ClassInterfaceType.None)] public class TestRequest : IRequest { private IRequestDictionary _queryString = new RequestDictionary(); public IRequestDictionary QueryString { get { return _queryString; } } } [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IRequestDictionary : IEnumerable { [DispId(0)] object this[object key] { [DispId(0)] get; [DispId(0)] set; } } [ClassInterface(ClassInterfaceType.None)] public class RequestDictionary : IRequestDictionary { private Hashtable _dictionary = new Hashtable(); public object this[object key] { get { return _dictionary[key]; } set { _dictionary[key] = value; } } } ``` I've tried researching and experimenting with various options but have not yet found a solution. Any help would be appreciated to figure out why the `testRequest.QueryString("key")` syntax is not working and how to get it working. Note: This is a followup to [Exposing the indexer / default property via COM Interop](https://stackoverflow.com/questions/299251/exposing-the-indexer-default-property-via-com-interop). Update: Here is some the generated IDL from the type library (using [oleview](http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en)): ``` [ uuid(C6EDF8BC-6C8B-3AB2-92AA-BBF4D29C376E), version(1.0), custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, AspObjects.IRequest) ] dispinterface IRequest { properties: methods: [id(0x60020000), propget] IRequestDictionary* QueryString(); }; [ uuid(8A494CF3-1D9E-35AE-AFA7-E7B200465426), version(1.0), custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, AspObjects.IRequestDictionary) ] dispinterface IRequestDictionary { properties: methods: [id(00000000), propget] VARIANT Item([in] VARIANT key); [id(00000000), propputref] void Item( [in] VARIANT key, [in] VARIANT rhs); }; ```
I stumbled upon this exact problem a few days ago. I couldn't find a reasonable explanation as to why it doesn't work. After spending long hours trying different workarounds, I think I finally found something that seems to work, and is not so dirty. What I did is implement the accessor to the collection in the container object as a method, instead of a property. This method receives one argument, the key. If the key is "missing" or null, then the method returns the collection (this handles expressions like "testRequest.QueryString.Count" in VbScript). Otherwise, the method returns the specific item from the collection. The dirty part with this approach is that this method returns an object (because sometimes the return reference is the collection, and sometimes an item of the collection), so using it from managed code needs castings everywhere. To avoid this, I created another property (this time a proper property) in the container that exposes the collection. This property is NOT exposed to COM. From C#/managed code I use this property, and from COM/VbScript/unmanaged code I use the method. Here is an implementation of the above workaround using the example of this thread: ``` [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IRequest { IRequestDictionary ManagedQueryString { get; } // Property to use form managed code object QueryString(object key); // Property to use from COM or unmanaged code } [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] public class TestRequest : IRequest { private IRequestDictionary _queryString = new RequestDictionary(); public IRequestDictionary ManagedQueryString { get { return _queryString; } } public object QueryString(object key) { if (key is System.Reflection.Missing || key == null) return _queryString; else return _queryString[key]; } } [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IRequestDictionary : IEnumerable { [DispId(0)] object this[object key] { [DispId(0)] get; [DispId(0)] set; } int Count { get; } } [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] public class RequestDictionary : IRequestDictionary { private Hashtable _dictionary = new Hashtable(); public object this[object key] { get { return _dictionary[key]; } set { _dictionary[key] = value; } } public int Count { get { return _dictionary.Count; } } #region IEnumerable Members public IEnumerator GetEnumerator() { throw new NotImplementedException(); } #endregion } ```
Results of my investigation on this subject: The problem is relative to IDispatch implementation the common language runtime uses when exposing dual interfaces and dispinterfaces to COM. Scripting language like VBScript (ASP) use OLE Automation IDispatch implementation when accessing to COM Object. Despite it seems to work, I want to keep the property as a property and don't want to have a function (workaround explained above). You have 2 possible solutions : 1 - Use the deprecated IDispatchImplAttribute with IDispatchImplType.CompatibleImpl. ``` [ClassInterface(ClassInterfaceType.None)] [IDispatchImpl(IDispatchImplType.CompatibleImpl)] public class TestRequest : IRequest { private IRequestDictionary _queryString = new RequestDictionary(); public IRequestDictionary QueryString { get { return _queryString; } } } ``` As said in MSDN, this attribute is deprecated but still working with .Net 2.0, 3.0, 3.5, 4.0. You have to decide if the fact that it is "deprecated" could be a problem for you... 2 - Or implement IReflect as a custom IDispatch in your class TesRequest or create a generic class that implement IReflect and make your class inherits this new created one. Generic class sample (the interresting part is in the InvokeMember Method): ``` [ComVisible(false)] public class CustomDispatch : IReflect { // Called by CLR to get DISPIDs and names for properties PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) { return this.GetType().GetProperties(bindingAttr); } // Called by CLR to get DISPIDs and names for fields FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) { return this.GetType().GetFields(bindingAttr); } // Called by CLR to get DISPIDs and names for methods MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) { return this.GetType().GetMethods(bindingAttr); } // Called by CLR to invoke a member object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { try { // Test if it is an indexed Property if (name != "Item" && (invokeAttr & BindingFlags.GetProperty) == BindingFlags.GetProperty && args.Length > 0 && this.GetType().GetProperty(name) != null) { object IndexedProperty = this.GetType().InvokeMember(name, invokeAttr, binder, target, null, modifiers, culture, namedParameters); return IndexedProperty.GetType().InvokeMember("Item", invokeAttr, binder, IndexedProperty, args, modifiers, culture, namedParameters); } // default InvokeMember return this.GetType().InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } catch (MissingMemberException ex) { // Well-known HRESULT returned by IDispatch.Invoke: const int DISP_E_MEMBERNOTFOUND = unchecked((int)0x80020003); throw new COMException(ex.Message, DISP_E_MEMBERNOTFOUND); } } FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) { return this.GetType().GetField(name, bindingAttr); } MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) { return this.GetType().GetMember(name, bindingAttr); } MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) { return this.GetType().GetMembers(bindingAttr); } MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr) { return this.GetType().GetMethod(name, bindingAttr); } MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) { return this.GetType().GetMethod(name, bindingAttr, binder, types, modifiers); } PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { return this.GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers); } PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) { return this.GetType().GetProperty(name, bindingAttr); } Type IReflect.UnderlyingSystemType { get { return this.GetType().UnderlyingSystemType; } } } ``` and for Mike's code: ``` [ClassInterface(ClassInterfaceType.None)] public class TestRequest : CustomDispatch, IRequest { private IRequestDictionary _queryString = new RequestDictionary(); public IRequestDictionary QueryString { get { return _queryString; } } } ```
Why is the indexer on my .NET component not always accessible from VBScript?
[ "", "c#", ".net", "vbscript", "com-interop", "" ]
I know downcasting like this won't work. I need a method that WILL work. Here's my problem: I've got several different derived classes all from a base class. My first try was to make an array of base class. The program has to select (more or less at random) different derived classes. I had tried casting from a base class to the derived class, putting it in the array of the base, but obviously that didn't work. I was sincerely hoping for another method than simply sticking arrays of all the derived classes, because there could be quite a few derived classes. Is there any better way to do this that I'm just brainfarting on? If y'all need code examples or more information, just let me know. It all makes sense to me, but It's late and it may not make sense to everybody else heh. Any help is very much appreciated, guys.
Not sure what you mean. Sounds like you store the objects by value, and you you have an array of `Base`. That won't work, because as soon as you assign a Derived, that object will be converted to a Base, and the Derived part of the object is sliced away. But i think you want to have a array of pointers to base: ``` Base * bases[NUM_ITEMS]; for(int i=0; i<NUM_ITEMS; i++) { int r = get_random_integer(); if(r == 0) bases[i] = new Derived1; else if(r == 1) bases[i] = new Derived2; // ... } ``` If you ever haved worked with pointers, you will know it's a pain in the ass to manage them, espacially pass around and not lose them, since you will need to call delete on them to free the memory and call the destructor of the objects. You can use shared\_ptr, and it will manage that for you: ``` shared_ptr<Base> bases[NUM_ITEMS]; for(int i=0; i<NUM_ITEMS; i++) { int r = get_random_integer(); if(r == 0) bases[i].reset(new Derived1); else if(r == 1) bases[i].reset(new Derived2); // ... } ``` Now, you can pass `bases[x]` to another shared\_ptr, and it will note you have got more than one reference - it will call automatically delete if the last reference to the objects go out of scope. Ideally, you would also replace the raw array by std::vector: ``` std::vector< shared_ptr<Base> > bases; for(int i=0; i<NUM_ITEMS; i++) { int r = get_random_integer(); if(r == 0) bases.push_back(shared_ptr<Base>(new Derived1)); else if(r == 1) bases.push_back(shared_ptr<Base>(new Derived2)); // ... } ``` Then you can pass the vector around, and don't lose the size of it, and you can dynamically add items to it on demand. Get the size of the vector using `bases.size()`. Read about `shared_ptr` [here](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm). Conversion from a Base class to a Derived class should *only be done when absolutely necessary*. Normally, you want to use a technique called `polymorphism`, which means you call a function on the base pointer, but it will actually call a function defined in the derived class, having the same signature (name and parameters are the same type) and is said to `override` it. Read the [article](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming) on wikipedia about it. If you really need to cast, you can do it like this for a raw pointer: ``` Derived1 * d = &dynamic_cast<Derived1&>(*bases[x]); ``` Using dynamic\_cast ensures, that when you cast to the wrong type (i.e the type you cast is not the type that was created and assigned to the base pointer), you get an exception thrown by the operator. For the shared\_ptr case, there are ways too: ``` shared_ptr<Derived1> d = dynamic_pointer_cast<Derived1>(bases[x]); if(d) { // conversion successful, it pointed to a derived. d and bases[x] point still // to the same object, thus share it. } ```
Casting from a base class to a derived class is a bad code smell in most circumstances. **Polymorphism**, through the use of virtual methods, is a better approach. The calling code should invoke a method using the base class pointer, allowing it to be dispatched to the appropriate implementation in the derived class. I know this is a fairly generic answer, but without some code snippets as examples it's difficult to recommend a more specific answer in your situation.
a better way than casting from a base class to derived class
[ "", "c++", "class-design", "" ]
I'm working on a document application and part of this application I've to add support to read the keyboard pressed events and replace the pre-defined characters set if that keyboard entry is match with the pre-defind short form/word.The actual application has implemented in C++. Please provide me your thoughts on how to implement this. Is there any sample C++ program for reference? algorithm/concepts?
Standard C++ doesn't support keypress events, so you'll have to look at either an OS function, or a framework function. Portable C++ frameworks like wxWidgets or Qt support keypress events on Windows, Mac and Linux.
Learn how to catch the keydown events using wxWidgets api, maybe here: <http://docs.wxwidgets.org/stable/wx_eventhandlingoverview.html#eventhandlingoverview> pay attention to [key events](http://docs.wxwidgets.org/stable/wx_wxkeyevent.html#wxkeyevent). Implement a switch in C++ to see what key combination was pressed, and set the text to the edit accordingly. What I'm thinking about here is to convert a CTRL-SHIFT-A keypress to a text like Ctrl-Shift-a in a edit box. If you are thinking of converting a combination of characters to other character, for example kanji or hiragana, the algorithm could be longer and more data structures required.
Read keyboard characters to determine shortcuts
[ "", "c++", "text", "keyboard-shortcuts", "keyboard-events", "" ]
Is it possible to determine if an ASP.NET page is a postback from javascript? So basically a javascript equivalent of C# Page.IsPostBack. Thanks.
I would just put a render tag in the javascript ``` var isPostBack = <%= Page.IsPostBack ? "true" : "false" %>; ``` Putting the "true" and "false" as strings should be done to eliminate any possible issues converting the type to a string as in C# true.ToString() is usually "True" which is an error in javascript.
Sure. Just use your server code to write out a javascript flag, if you really need this. But I suspect you're barking up the wrong tree here.
Use javascript to determine if an ASP.NET page is a postback
[ "", "asp.net", "javascript", "" ]
I have an `IDictionary<TKey,TValue>` implementation that internally holds n other `Dictionary<TKey, TValue>` and distributes that insertions by the HashCode of the key to the invidual sub-dictionaries. With 16 sub-dictionaries, the number of collisions is pretty low on a 4-core machine. For parallel insertions, i locked the Add-method with a `ReaderWriterLockSlim`, locking only the individual sub-dictionary: ``` public void Add(TKey key, TValue value) { int poolIndex = GetPoolIndex(key); this.locks[poolIndex].EnterWriteLock(); try { this.pools[poolIndex].Add(key, value); } finally { this.locks[poolIndex].ExitWriteLock(); } } ``` When inserting items with four threads, i only got about 32% cpu usage and bad performance. So i replaced the ReaderWriterLockSlim by a Monitor (i.e., the `lock` keyword). CPU usage was now at nearly 100% and the performance was more than doubled. My question is: Why did the CPU usage increase? The number of collisions should not have changed. What makes ReaderWriterLock.EnterWriteLock wait so many times?
For write-only load the Monitor is cheaper than ReaderWriterLockSlim, however, if you simulate read + write load where read is much greater than write, then ReaderWriterLockSlim should out perform Monitor.
I'm no guru, but my guess is that RWLS is more geared towards heavy contention (e.g., hundreds of threads) whereas `Monitor` is more attuned towards those one-off synchronization issues. Personally I use a `TimerLock` class that uses the `Monitor.TryEnter` with a timeout parameter.
ReaderWriterLockSlim vs. Monitor
[ "", "c#", "multithreading", "locking", "readerwriterlock", "" ]
I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A *(quite pointless)* example in Java: **a)** declaration before loop: ``` double intermediateResult; for(int i=0; i < 1000; i++){ intermediateResult = i; System.out.println(intermediateResult); } ``` **b)** declaration (repeatedly) inside loop: ``` for(int i=0; i < 1000; i++){ double intermediateResult = i; System.out.println(intermediateResult); } ``` Which one is better, **a** or **b**? I suspect that repeated variable declaration (example **b**) creates more overhead *in theory*, but that compilers are smart enough so that it doesn't matter. Example **b** has the advantage of being more compact and limiting the scope of the variable to where it is used. Still, I tend to code according example **a**. ***Edit:*** I am especially interested in the Java case.
Which is better, **a** or **b**? From a performance perspective, you'd have to measure it. (And in my opinion, if you can measure a difference, the compiler isn't very good). From a maintenance perspective, **b** is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't leave a gaping hole between the declaration and the initialization, and don't pollute namespaces you don't need to.
Well I ran your A and B examples 20 times each, looping 100 million times.(JVM - 1.5.0) A: average execution time: .074 sec B: average execution time : .067 sec To my surprise B was slightly faster. As fast as computers are now its hard to say if you could accurately measure this. I would code it the A way as well but I would say it doesn't really matter.
Difference between declaring variables before or in loop?
[ "", "java", "performance", "loops", "variables", "initialization", "" ]
this is what I did. is there a better way in python? ``` for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 ``` Thanks
Use defaultdict ``` from collections import defaultdict kvmap= defaultdict(int) for k in a_list: kvmap[k] += 1 ```
Single element: ``` a_list.count(k) ``` All elements: ``` counts = dict((k, a_list.count(k)) for k in set(a_list)) ```
what's the pythonic way to count the occurrence of an element in a list?
[ "", "python", "" ]
I'm writing a piece of code that requires the `DOM` of a website to remain frozen while arbitrary JavaScript runs. Attributes changing is fine but I can't have anything changing the original tag structure of the page! I know in JavaScript there are a base number of functions that can modify the `DOM`: ``` appendChild( nodeToAppend ) cloneNode( true|false ) createElement( tagName ) createElemeentNS( namespace, tagName ) createTextNode( textString ) innerHTML insertBefore( nodeToInsert, nodeToInsertBefore ) removeChild( nodetoRemove ) replacechild( nodeToInsert, nodeToReplace ) ``` My initial thought was simply to overwrite these functions as no ops: ``` >>> document.write('<p>Changing your DOM. Mwwhaha!</p>') >>> document.write = function() {} >>> document.write('<p>No-op now!</p>') ``` While it's easy to do this for the `document` object the `DOM` modification functions can be called from many different JavaScript objects! If I could overwrite these functions at top level perhaps it would work? Update from sktrdie: ``` >>> HTMLElement.prototype.appendChild = function(){} >>> $("a").get(0).appendChild(document.createElement("div")) # Still works argh. >>> HTMLAnchorElement.prototype.appendChild = function(){} >>> $("a").get(0).appendChild(document.createElement("div")) # No-op yeah! ``` So it would seem I could just gather the constructors of all `DOM` elements and run over them putting in no-ops but that still seems pretty messy ... **How can I protect the `DOM` from modification from arbitrary JavaScript?**
Have you tried **HTMLElement**.prototype.appendChild = function(){} to overwrite DOM methods at a higher level?
While this is really hackish, the only way to maintain the current DOM structure is to store a "snapshot" of the DOM and check it periodically. ``` //place in anonymous function to prevent global access (function() { //storing the whole DOM as objects would be ideal, but too memory intensive, so a string will have to do. var originalDOM = document.body.innerHTML; var checkDOM = function() { if (document.body.innerHTML != originalDOM) document.body.innerHTML = originalDOM //check that the code is running if (arbitraryCodeIsRunning) setTimeout("checkDOM", 100); } checkDOM(); })(); ``` Probably not what your looking for, but after some testing it's the only way I can think of to maintain DOM structure regardless.
Freezing the DOM to JavaScript: Overwriting DOM modification functions as no-ops
[ "", "javascript", "dom", "sandbox", "" ]
If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like: > HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA............................................................................................................................................. I've tried just using `wordwrap()` in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks. There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE. How do you solve this problem?
I haven't personally used it, but [Hyphenator](http://code.google.com/p/hyphenator/) looks promising. Also see related (possibly duplicate) questions: * [word wrap in css / js](https://stackoverflow.com/questions/322929/word-wrap-in-css-js) * [Who has solved the long-word-breaks-my-div problem? (hint: not stackoverflow)](https://stackoverflow.com/questions/320184/who-has-solved-the-long-word-breaks-my-div-problem-hint-not-stackoverflow)
in CSS3: ``` word-wrap:break-word ```
How to wrap long lines without spaces in HTML?
[ "", "php", "html", "css", "word-wrap", "" ]
Here's a question for those of you with experience in larger projects and API/framework design. I am working on a framework that will be used by many other projects in the future, so I want to make it nice and extensible, but at the same time it needs to be simple and easy to understand. I know that a lot of people complain that the .NET framework contains too many sealed classes and private members. Should I avoid this criticism and open up all my classes with plenty of protected virtual members? Is it a good idea to make as many of my methods and properties **protected virtual** as possible? Under what situations would you avoid **protected virtual** and make members private.
Your class includes data members; methods that perform basic internal operations on those data members where the functionality should never change should always be private. So methods that do basic operations with your data members such as initialization and allocation should be private. Otherwise, you run the risk of "second order" derivative classes getting an incomplete set of behaviors enabled; first derivative members could potentially redefine the behavior of the class. That all said, I think you should be very careful with defining methods as "protected virtual". I would use great caution in defining methods as "protected virtual", because doing so not only declares the **possibility** of overriding the functionality, but in some ways define an **expectation** of overridden functionality. That sounds to me like an underdefined set of behaviors to override; I would rather have a well-defined set of behaviors to override. If you want to have a very large set of overridable behaviors, I would rather look into Aspect Oriented Programming, which allows for that sort of thing in a very structured way.
When you mark a method with the word virtual, you're allowing the users to change the way that piece of logic is executed. For many purposes, that is exactly what you want. I believe you already know that. However, types should be designed for this sort of extension. You have to actively pick out the methods, where it makes sense to let the user change the behavior. If you just slap on virtual all over the place you risk ruining the integrity of the type, it doesn't really help the user to understand the type, and you may introduce a number of bugs including security related issues. I prefer the conservative approach. I mark all my classes with `sealed` unless I specifically want to enable inheritance and in those (few) cases I only make the required methods virtual. It is easy to remove the `sealed` tag if the class needs to change to allow inheritance in the future. However, if you want to change a class, which is already being used as a base class for some other type, you risk breaking the subclass when you change the base class.
Can you ever have too many "protected virtual" methods?
[ "", "c#", ".net", "virtual", "protected", "" ]
I ran across this case of `UnboundLocalError` recently, which seems strange: ``` import pprint def main(): if 'pprint' in globals(): print 'pprint is in globals()' pprint.pprint('Spam') from pprint import pprint pprint('Eggs') if __name__ == '__main__': main() ``` Which produces: ``` pprint is in globals() Traceback (most recent call last): File "weird.py", line 9, in <module> if __name__ == '__main__': main() File "weird.py", line 5, in main pprint.pprint('Spam') UnboundLocalError: local variable 'pprint' referenced before assignment ``` `pprint` is clearly bound in `globals`, and is going to be bound in `locals` in the following statement. Can someone offer an explanation of why it isn't happy resolving `pprint` to the binding in `globals` here? **Edit:** Thanks to the good responses I can clarify my question with relevant terminology: At compile time the identifier `pprint` is marked as local to the frame. Does the execution model have no distinction *where* within the frame the local identifier is bound? Can it say, "refer to the global binding up until this bytecode instruction, at which point it has been rebound to a local binding," or does the execution model not account for this?
Looks like Python sees the `from pprint import pprint` line and marks `pprint` as a name local to `main()` *before* executing any code. Since Python thinks pprint ought to be a local variable, referencing it with `pprint.pprint()` before "assigning" it with the `from..import` statement, it throws that error. That's as much sense as I can make of that. The moral, of course, is to always put those `import` statements at the top of the scope.
Where's the surprise? *Any* variable global to a scope that you reassign within that scope is marked local to that scope by the compiler. If imports would be handled differently, *that* would be surprising imho. It may make a case for not naming modules after symbols used therein, or vice versa, though.
Python globals, locals, and UnboundLocalError
[ "", "python", "binding", "scope", "identifier", "" ]
I have an assortment of database objects (tables, functions, views, stored procedures) each scripted into its own file (constraints are in the same file as the table they alter) that I'd like to be able execute in an arbitrary order. Is this possible in SQL Server 2005? Some objects as an example: Table A (references Table B) Table B (references Function A) Function A (references View A) View A (references Table C) Must be run in the following order: Table C View A Function A Table B Table A If the scripts are run out of order, errors about the missing objects are thrown. The reason I ask is that in a project I'm working on we maintain each database object in its own file (for source control purposes), and then maintain a master script that creates each database object in the correct order. This requires the master script to be manually edited any time an object is added to the schema. I'd like to be able to just execute each script as it is found in the file system.
In my experience the most problematic issue is with views, which can reference recursively. I once wrote a utility to iterate through the scripts until the errors were all resolved. Which only works when you're loading everything. Order was important - I think I did UDTs, tables, FKs, views (iteratively), SPs and UDFs (iteratively until we decided that SPs calling SPs was a bad idea, and UDFs are generally a bad idea.)
If you script the foreign keys into separate files, you can get rid of table-table dependencies, if you run the FK script after creating all tables. As far as I'm aware, functions and procedures check for object existence only in JOIN clauses. The only difficulty I found was views depending on views, as a view definition requires that the objects the view depends on do exist.
Can I disable identifier checking in SQL Server 2005?
[ "", "sql", "sql-server", "sql-server-2005", "version-control", "" ]
We have a fairly large group of Maven2 projects, with a root POM file listing 10+ modules and a lot of properties used by the modules (dependency version numbers, plugin configuration, common dependencies, etc). Some of the modules are, like the root project, parents to other sets of modules. To clarify, the root project and said parent projects are set to pom packaging (as opposed to e.g. jar). Because there are many dependencies between the different projects, I like to use mvn eclipse:eclipse on the root project, which enables me to debug/step into any project at any time. However, with this approach, the root POM itself, and all other pom-packaged projects, are unavailable in Eclipse. So, if I want to edit them, I have to open them some other way. This is becoming a bit of a hassle. So, my question is: is it possible to somehow make pom-packaged projects available in Eclipse? If not, do you have any tips that could make my work with these projects easier? For the record, I'm currently using MyEclipse 7.0.
I tried this again, with Galileo and the latest version of m2eclipse. It is now possible to import Maven projects directly (without mvn eclipse:eclipse), and it turns out that the root POM is also imported as a project, which is excactly what I wanted.
Well. Lots of people do this by making the parent POM a sibling project, and having a simple reactor POM in the root. However this can cause problems with website generation and the release plugin, as neither supports this mode as fully as one might like. A big problem we often have is that people try to check out the trunk using Subclipse, which adds a .project file in the root, which then prevents importing projects below that level. Instead we have to go outside to check out, then import the projects. I have heard rumor that Subversive might handle nested projects better, which is really the problem here. Other than that, I don't have an absolute solution here.
With multi-module Maven projects, is it possible to make my root (pom-packaged) project available in Eclipse?
[ "", "java", "eclipse", "maven-2", "pom.xml", "" ]
For example: ``` using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.Web.Script.Serialization; using System.Web.Script.Services; using System.Web.Security; using System.Data; using System.IO; using System.Net; using System.Text; using System.Xml; using System.Xml.XPath; using System.Web.Configuration; using System.Collections.Generic; ``` I have something like that in a class that I have inherited. I could remove each namespace one by one to see if the class builds, BUT does it matter? If I am not sure if System.Xml is needed, should I remove it?
**In general** all they do is add clutter. However, they can *in some specific circumstances* cause problems with duplicate names in scope, or duplicate extension methods. For example, if there are classes `Foo.SomeType` and `Bar.SomeType`, and you have `using Foo;` and `using Bar;`, then references to `SomeType` will need disambiguating. The extension methods work similarly where static classes in different namespaces contribute conflicting extension methods. The VS2008 tools (including express) include options to remove unnecessary `using` statements, which is very useful for tidying the code.
In general I like to remove unused using statements as they clutter up the code. [ReSharper](https://www.jetbrains.com/resharper/) grays out unused using statements. [![alt text](https://web.archive.org/web/20061025220507/http://codebetter.com:80/photos/jeffrey.palermo/images/147903/original.aspx)](https://web.archive.org/web/20061025220507/http://codebetter.com:80/photos/jeffrey.palermo/images/147903/original.aspx) It has a right click menu for, "Remove unused using statements" also.
Does it matter if I include more references and namespaces in a class
[ "", "c#", "" ]
it's a really weird thing - i have a website that works perfectly in maxthon (internet explorer based browser). i started it in opera and found out that the data put in the Session dictionary on one site, is not available on the other... i mean i have Welcome.aspx, where when you click next the following code is executed: ``` Session["sessionData"] = sessionData; Response.Redirect("~/Models.aspx"); ``` while debugging i can see that in models.aspx Session in empty when executing in opera but everything is fine when executing in maxthon. has anyone got any idea what can be wrong? because i'm clueless.. is this some opera preferences thing or is it something in code? Edit: i checked Session.IsNewSession and while executing in maxthon isnewsession is set to false but in opera it's true. it seems that in opera when moving to a new page it somehow creates new session...
If your write the session on the first hit then you should do ``` Response.Redirect("nextpage.asp", false); ``` Otherwise it wont write the whole responsestream and the cookie might not have been written. You can instead choose to have cookiless sessions. But then your open to session hijacking.
ASP.NET session is stored by a key that is saved as a cookie in the browser. Check Opera to see if it is accepting cookies - it will need to in order for ASP.NET session to work properly.
asp.net: data put in session is available while working in internet explorer but not in opera
[ "", "c#", "asp.net", "session", "opera", "" ]
I'm building a site that's sort of a cross between StackOverflow and Digg (only a different genre). Typically in the past I would have just built it using ASP.Net web forms. However I want to use this project as a way to learn new technologies. I'm using ASP.Net Mvc which is really great, but I need to learn/use some kind of javascript libraries. For instance, when someone votes on a post I want it to be updated with the vote count immediately, or if someone types in text into the "tags" textbox, I want it to give a drop-down of currently used tags etc. Basically I want to provide a lot of the AJAXy stuff for my site. So my question is where to I begin? I feel bombarded with so many options and I'm not sure where to start or even what they are. Can someone straighten me out and provide some explanation and direction? * JSON * JQuery * MS-AJAX I'm sure there are bunch of others I can recall at the moment.
You should definitely start with the basics of Javascript. Start with things like printing "Hello World" to the page. Move on to basic language features like variables, loops, conditionals, and functions. I recommend the [W3Schools Introduction to Javascript](http://www.w3schools.com/jS/js_intro.asp "W3Schools Introduction to Javascript"). Don't get too caught up in trying to do object-oriented programming in Javascript. It is painful and confusing, even for some experienced Javascript programmers. Next I strongly recommend learning to use a cross-browser Javascript library, rather than trying to do everything by hand (specifically: interacting with the [DOM](http://en.wikipedia.org/wiki/Document_Object_Model "DOM"), performing [XmlHttpRequests](http://en.wikipedia.org/wiki/XHR "XmlHttpRequests") aka AJAX calls, etc.). I recommend the [jQuery library](http://www.jquery.com "jQuery library"). It provides a solid foundation for all of the cool AJAX-y things you want to do, and there are loads of [plugins](http://plugins.jquery.com/ "jQuery Plugins") available for it. **jQuery is a Javascript framework that allows easy and reliable interactions with the Document Object Model** (DOM). In simplest terms, the DOM is the representation of all the HTML elements in a web page. The DOM is slightly different from browser to browser, and interacting with it "by hand" is tedious and error prone. jQuery solves this problem by essentially doing all the hard work behind the scenes. It is much more powerful than that, really, but that's the major feature. It also provides support for page events, custom events, plugins, CSS manipulation, and much more. [JSON](http://www.json.org/ "JSON") is another term you mentioned. It stands for JavaScript Object Notation. **JSON is simply a lightweight way to represent structures in Javascript** (and other languages too, actually). To be honest, the [Wikipedia JSON Article](http://en.wikipedia.org/wiki/JSON "Wikipedia JSON Page") provides a much better summary of how JSON is used with AJAX than I ever could, so you might want to [give it a read](http://en.wikipedia.org/wiki/JSON "Wikipedia JSON Page"). Here is the basic order of events: 1. Your Javascript code makes an AJAX call to a web page. You can do this using the AJAX functions in jQuery. 2. The result produced by that web page is a JSON object. For example, it might produce a string that looks like: `{ 'firstname':'Robert', 'lastname':'Smith' }` 3. The result is received by your AJAX call and evaluated using the special Javascript "eval" function. 4. You are left with a native Javascript object that you can work with in your code. You can then do stuff like: `document.write('Hello ' + result.firstname + ' ' + result.lastname)` Here are a few useful links I have collected over the past year or so that have helped me. I hope they help you too! * [How jQuery Works](http://docs.jquery.com/How_jQuery_Works "How jQuery Works") * [jQuery Plugins](http://plugins.jquery.com/ "jQuery Plugins") * [20 Amazing jQuery Plugins and 65 Excellent jQuery Resources](http://speckyboy.com/2008/07/21/20-amazing-jquery-plugins-and-65-excellent-jquery-resources/ "20 Amazing jQuery Plugins and 65 Excellent jQuery Resources") * [75 (Really) Useful JavaScript Techniques](http://www.smashingmagazine.com/2008/09/11/75-really-useful-javascript-techniques/ "75 (Really) Useful JavaScript Techniques") * [AutoCompleter Tutorial](http://nodstrum.com/2007/09/19/autocompleter/ "AutoCompleter Tutorial") The most important thing to remember is: **learn by doing**. Experiment. Try new things. Make a bunch of proof of concept pages. With Javascript, that's really the best way to get your feet wet. Good luck!
Start by learning the basics of Javascript. It's important you know how to use it's internals before you dive into deeper abstractions. Mozila has [a fantastic resource](http://developer.mozilla.org/en/JavaScript) on Javascript, including an [overview guide](http://developer.mozilla.org/en/Core_JavaScript_1.5_Guide). Next, pick up a good framework, it will help you a great deal performing DOM manipulations, which is what Javascript is generally used for. A framework will save much time on cross-browser implementation differences and provide a good base to develop from. There is plenty of selection here, and you'll do fine with either of the popular choices. Personally, I'd pick [jQuery](http://jquery.com/) for its concise API and great plug-in library. Along the way you'll learn the definitions of distinct features / notations, such as [JSON](http://www.json.org/) (which means Javascript Object Notation, and is used to define portable data structures in Javascript). For any specific questions you have, you can always google or come back to SO ;)
Where do I begin learning all the different JavaScript technologies/libraries?
[ "", "javascript", "" ]
What is a good way of parsing command line arguments in Java?
Check these out: * <http://commons.apache.org/cli/> * <http://www.martiansoftware.com/jsap/> Or roll your own: * <http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html> --- **For instance,** this is how you use [`commons-cli`](https://mvnrepository.com/artifact/commons-cli/commons-cli/1.3.1) to parse 2 string arguments: ``` import org.apache.commons.cli.*; public class Main { public static void main(String[] args) throws Exception { Options options = new Options(); Option input = new Option("i", "input", true, "input file path"); input.setRequired(true); options.addOption(input); Option output = new Option("o", "output", true, "output file"); output.setRequired(true); options.addOption(output); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null;//not a good practice, it serves it purpose try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); System.exit(1); } String inputFilePath = cmd.getOptionValue("input"); String outputFilePath = cmd.getOptionValue("output"); System.out.println(inputFilePath); System.out.println(outputFilePath); } } ``` usage from command line: ``` $> java -jar target/my-utility.jar -i asd Missing required option: o usage: utility-name -i,--input <arg> input file path -o,--output <arg> output file ```
Take a look at the more recent [JCommander](http://jcommander.org/). I created it. I’m happy to receive questions or feature requests.
How do I parse command line arguments in Java?
[ "", "java", "command-line", "command-line-arguments", "" ]
To summarize, as we all know, a) Silverlight is expected to be hosted by a browser, and runs in an isolated sandbox so that there won’t be any security issues 1. Silverlight don’t have direct access to the file system, other than the isolated storage area 2. There is no direct way to open common dialog boxes like File Save in Silverlight (Though Opendialog box is supported). b) Silverlight can’t access local resources like a printer What are the ways to go beyond the sandbox, so that I can host a Silverlight application locally, to read files and save them back if required, to hand over data to a printer, and so on.. **Update:** Is full WPF is not an option for me? No. I'm also interested in a cross platform solution - for instance, you could host Silverlight in Mono Web browser control, so that you can run it virtually anywhere. The idea is to re-use the same application that I'm building for web in my desktop as well, by providing separation of concerns at some areas - like persistence, resource access etc. Scenarios: 1- Some kind of gadget container, with access to local resources. 2 - A desktop Silver light based media application **Update:** I just did a POC to enable me to access printer and save files locally, of course through a shell where I'm hosting my Silverlight application. If you wan't you can have a look at the post [here in my blog](http://amazedsaint.blogspot.com/2008/12/thinking-outside-silverlight-sandbox.html)
Two ways I can think about is, **Create a "Shell"** Host the HTML Page with Silverlight, in a Winforms desktop application, using a web browser control, and communicate to and fro using HTML DOM. Then I can request the hosted shell to do things like printing. [See details here](http://amazedsaint.blogspot.com/2008/12/thinking-outside-silverlight-sandbox.html) Mono also has a web browser control - based on FireFox XULRunner instead of IE - not yet succeeded in loading Silverlight inside that. Another option might be using Webkit. ![Desktop Shell](https://3.bp.blogspot.com/__Mw4iY-4nuY/SUYUVhMcMtI/AAAAAAAAAXU/5vYVQz2EBnw/s400/image001.gif) **Embed a web server** Embed a light weight web server with in the Host application, and handle requests to perform such operations. You can probably define a protocol on top of HTTP for things like saving to a local folder, sending data to print etc. ![Embedding A Server](https://3.bp.blogspot.com/__Mw4iY-4nuY/SUYUW8Rf2PI/AAAAAAAAAXc/kb-6LCr17gA/s400/image002.gif)
Is a full WPF application not an option for your situation? As you probably know Silverlight uses a subset of WPF so you may be able to change your application relatively easy. A wpf app would be easier than having a web server etc bundled within your application. You wont in the foreseeable future be able to have access to resources such as printer and files (apart from isolated storage) through Silverlight as you know. You could have a seperate part of your app to upload files to the webserver then read these in your silverlight app from a service. Depending on your printing requirements (e.g. if you just want to send everything to an office printer) you could send the informaton you wanted printed to a service that will then print it for you. However I am guessing you want each client machine to be able to print in which case this wont work for you.
Thoughts about using Silverlight In Desktop Apps?
[ "", "c#", ".net", "silverlight", "silverlight-2.0", "" ]
Is there a collation type which is officially recommended by MySQL, for a general website where you aren't 100% sure of what will be entered? I understand that all the encodings should be the same, such as MySQL, Apache, the HTML and anything inside PHP. In the past I have set PHP to output in "UTF-8", but which collation does this match in MySQL? I'm thinking it's one of the UTF-8 ones, but I have used `utf8_unicode_ci`, `utf8_general_ci`, and `utf8_bin` before, and I do not know which of these "utf8" maps to, or if that is the best to use.
The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8\_bin which is for comparing characters in binary format. `utf8_general_ci` is somewhat faster than `utf8_unicode_ci`, but less accurate (for sorting). The *specific language utf8 encoding* (such as `utf8_swedish_ci`) contain additional language rules that make them the most accurate to sort for those languages. Most of the time I use `utf8_unicode_ci` (I prefer accuracy to small performance improvements), unless I have a good reason to prefer a specific language. You can read more on specific unicode character sets on the MySQL manual - <http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html>
Actually, you probably want to use `utf8_unicode_ci` or `utf8_general_ci`. * `utf8_general_ci` sorts by stripping away all accents and sorting as if it were ASCII * `utf8_unicode_ci` uses the Unicode sort order, so it sorts correctly in more languages However, if you are only using this to store English text, these shouldn't differ.
What is the best collation to use for MySQL with PHP?
[ "", "php", "mysql", "encoding", "collation", "" ]
I'm making a simple remove link with an onClick event that brings up a confirm dialog. I want to confirm that the user wants to delete an entry. However, it seems that when Cancel is clicked in the dialog, the default action (i.e. the href link) is still taking place, so the entry still gets deleted. Not sure what I'm doing wrong here... Any input would be much appreciated. EDIT: Actually, the way the code is now, the page doesn't even make the function call... so, no dialog comes up at all. I did have the onClick code as: ``` onClick="confirm('Delete entry?')" ``` which did bring up a dialog, but was still going to the link on Cancel. ``` <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <script type="text/javascript"> function delete() { return confirm('Delete entry?') } </script> ... <tr> <c:if test="${userIDRO}"> <td> <a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}"/>" /> <img src="images/edit.GIF" ALT="Edit this skill." border="1"/></a> </td> <td> <a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}&remove=1"/>" onClick="return delete()"/> <img src="images/remove.GIF" ALT="Remove this skill." border="1"/></a> </td> </c:if> </tr> ```
There's a typo in your code (the tag **a** is closed too early). You can either use: ``` <a href="whatever" onclick="return confirm('are you sure?')"><img ...></a> ``` note the **return (confirm)**: the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you need to run a big piece of code you can of course call another function: ``` <script type="text/javascript"> function confirm_delete() { return confirm('are you sure?'); } </script> ... <a href="whatever" onclick="return confirm_delete()"><img ...></a> ``` (note that delete is a keyword) For completeness: modern browsers also support DOM events, allowing you to register more than one handler for the same event on each object, access the details of the event, stop the propagation and much more; see [DOM Events](http://en.wikipedia.org/wiki/DOM_Events).
Well, I used to have the same problem and the problem got solved by adding the word "**return**" before confirm: ``` onclick="return confirm('Delete entry?')" ``` I wish this could be heplful for you.. Good Luck!
Simple JavaScript problem: onClick confirm not preventing default action
[ "", "javascript", "html", "" ]
Does anyone know a good .NET dictionary API? I'm not interested in meanings, rather I need to be able to query words in a number of different ways - return words of x length, return partial matches and so on...
Grab the flat text file from an open source spellchecker like ASpell (<http://aspell.net/>) and load it into a List or whatever structure you like. for example, ``` List<string> words = System.IO.File.ReadAllText("MyWords.txt").Split(new string[]{Environment.NewLine}).ToList(); // C# 3.0 (LINQ) example: // get all words of length 5: from word in words where word.length==5 select word // get partial matches on "foo" from word in words where word.Contains("foo") select word // C# 2.0 example: // get all words of length 5: words.FindAll(delegate(string s) { return s.Length == 5; }); // get partial matches on "foo" words.FindAll(delegate(string s) { return s.Contains("foo"); }); ```
You might want to look for a [Trie](http://en.wikipedia.org/wiki/Trie) implementation. That will certainly help with "words starting with XYZ" as well as exact matches. You may well want to have all of your data in multiple data structures, each one tuned for the particular task - e.g. one for anagrams, one for "by length" etc. Natural language dictionaries are relatively small compared with RAM these days, so if you really want speedy lookup, that's probably the way to go.
Dictionary API (lexical)
[ "", "c#", ".net", "api", "" ]
I am having some difficulty accessing the value of the selected radio button in a radiogroup. I've attempted a number of different approaches based upon discussion in other posts on the forum and around the web. Unfortunately haven't been lucky (or skilled) enough to get it working. Based on the following FormPanel config I was hoping someone could show me how to get the value of the selected radio in the group 'mainPhone'. Thanks! **Wanted to update to indicate that I was able to get a response from stackoverflow while the EXT-JS forums didn't provide me with any help. Way to go stackoverflow!** Matt ``` function createForm(elem) { var myForm2 = new Ext.form.FormPanel({ renderTo:elem, width:425, frame:true, style:"margin: 10px auto 10px auto;", items: [{xtype:'fieldset', title: 'Contact Info', autoHeight:true, items :[new Ext.form.RadioGroup({ fieldLabel: 'Main Phone', vertical: false, id:"mainPhone", items: [ {boxLabel: 'Home', name: 'id-1', inputValue: 'H', checked:true}, {boxLabel: 'Work', name: 'id-1', inputValue: 'W'}, {boxLabel: 'Other', name: 'id-1', inputValue: 'O'} ] }), new Ext.form.TextField({ id:"frm_CreateCustomerHomePhone", fieldLabel:"Home Phone", width:275, allowBlank:true }), new Ext.form.TextField({ id:"frm_CreateCustomerWorkPhone", fieldLabel:"Work Phone", width:275, allowBlank:true }) new Ext.form.TextField({ id:"frm_CreateCustomerOtherPhone", fieldLabel:"Other Phone", width:275, allowBlank:true }) ]}]}); } ```
This is something of a wild guess, but how about this: ``` myForm2.getForm().getValues()['id-1']; ```
The method `getValue()` on the radio group itself will return the object that is checked, if any, otherwise, it returns undefined. (by the way I set value instead of inputValue for my boxes, although I don't think it makes much of a difference, maybe it does on the last "getValue"), I'm using extjs 3.0, and my radiogroup configuration is slightly different than yours. ``` var checkedItem = Ext.getCmp('mainPhone').getValue(); if (checkedItem == undefined) return ''; return checkedItem.getGroupValue(); // The getGroupValue will return the value of the checked option in a group, // unfortunately, it only seems to work on the items and not the radiogroup // itself ```
Ext RadioGroup - How to Access the value of selected radio button?
[ "", "javascript", "extjs", "" ]
Parameterized Queries in .Net always look like this in the examples: ``` SqlCommand comm = new SqlCommand(@" SELECT * FROM Products WHERE Category_ID = @categoryid ", conn); comm.Parameters.Add("@categoryid", SqlDbType.Int); comm.Parameters["@categoryid"].Value = CategoryID; ``` But I'm running into a brick wall trying to do the following: ``` SqlCommand comm = new SqlCommand(@" SELECT * FROM Products WHERE Category_ID IN (@categoryids) OR name LIKE '%@name%' ", conn); comm.Parameters.Add("@categoryids", SqlDbType.Int); comm.Parameters["@categoryids"].Value = CategoryIDs; comm.Parameters.Add("@name", SqlDbType.Int); comm.Parameters["@name"].Value = Name; ``` Where * CategoryIDs is a comma separated list of numbers "123,456,789" (without quotes) * Name is a string, possibly with single quotes and other bad characters What's the right syntax for this?
Let's say that you have your category ids in an integer array and Name is a string. The trick is to create the command text to allow you to enter all of your category ids as individual parameters and construct the fuzzy match for name. To do the former, we use a loop to construct a sequence of parameter names @p0 through @pN-1 where N is the number of category ids in the array. Then we construct a parameter and add it to the command with the associated category id as the value for each named parameter. Then we use concatenation on the name in the query itself to allow the fuzzy search on name. ``` string Name = "someone"; int[] categoryIDs = new int[] { 238, 1138, 1615, 1616, 1617, 1618, 1619, 1620, 1951, 1952, 1953, 1954, 1955, 1972, 2022 }; SqlCommand comm = conn.CreateCommand(); string[] parameters = new string[categoryIDs.Length]; for(int i=0;i<categoryIDs.Length;i++) { parameters[i] = "@p"+i; comm.Parameters.AddWithValue(parameters[i], categoryIDs[i]); } comm.Parameters.AddWithValue("@name",$"%{Name}%"); comm.CommandText = "SELECT * FROM Products WHERE Category_ID IN ("; comm.CommandText += string.Join(",", parameters) + ")"; comm.CommandText += " OR name LIKE @name"; ``` This is a fully parameterized query that should make your DBA happy. I suspect that since these are integers, though it would not be much of a security risk just to construct the command text directly with the values, while still parameterizing the name. If your category ids are in a string array, just split the array on commas, convert each to an integer, and store it in the integer array. **Note:** I say array and use it in the example, but it should work for any collection, although your iteration will probably differ. Original idea from <http://www.tek-tips.com/viewthread.cfm?qid=1502614&page=9>
You need "%" in value of sql parameter. ``` SqlCommand comm = new SqlCommand("SELECT * FROM Products WHERE Category_ID IN (@categoryid1, @categoryid2) OR name LIKE @name", conn); comm.Parameters.Add("@categoryid1", SqlDbType.Int); comm.Parameters["@categoryid1"].Value = CategoryID[0]; comm.Parameters.Add("@categoryid2", SqlDbType.Int); comm.Parameters["@categoryid2"].Value = CategoryID[1]; comm.Parameters.Add("@name", SqlDbType.NVarChar); comm.Parameters["@name"].Value = "%" + Name + "%"; ```
Parameterized Queries with LIKE and IN conditions
[ "", ".net", "sql", "parameters", "sql-injection", "parameterized", "" ]
How the variables can be transferred between the Winforms? Example customer id Thanks
You must declare a public property in the form you wish to pass to. Then, after instantiating your new form, it's a simple assignment: C#: `MyOtherInstantiatedForm.CustomerID = CurrentCustomerID;` Do you need to pass around CustomerID to several forms? How about other customer information? If you provide more information we can probably give you a better solution.
The most important thing to note here is that a Form is nothing more than a C# class. If you think about a Form in these terms, the answer will probably jump out, by itself. Essentially, there are two options that you have. The first is to expose a property on the Form, for which you wish to pass data to. This is a decent method if your form does not rely on the data being passed, in order to function. ``` CoolForm myForm = new CoolForm(); myForm.MyProp = "Hello World"; myForm.ShowDialog(); ``` The second option is to pass data through the constructor. I prefer this approach when the form relies on the data, in order to function. I also tend to mark the parameter-less constructor as private to ensure that the form is properly instantiated. ``` CoolForm myForm = new CoolForm("Hello World"); myForm.ShowDialog(); ``` Hope that helps...
Windows application
[ "", "c#", "vb.net", "winforms", "" ]
How accurate is **System.Diagnostics.Stopwatch**? I am trying to do some metrics for different code paths and I need it to be exact. Should I be using stopwatch or is there another solution that is more accurate? I have been told that sometimes stopwatch gives incorrect information.
Why don't you profile your code instead of focusing on microbenchmarks? There are some good open source profilers, like: * [NProf](http://code.google.com/p/nprof/) * [Prof-It for C#](http://dotnet.jku.at/projects/Prof-It/) * [NProfiler](http://chimpswithkeyboards.com/projects/nprofiler/) * [ProfileSharp](http://www.softprodigy.net/)
I've just written an article that explains how a test setup must be done to get an high accuracy (better than 0.1 ms) out of the stopwatch. I *think* it should explain everything. *[Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch](http://www.codeproject.com/KB/testing/stopwatch-measure-precise.aspx)*
How accurate is System.Diagnostics.Stopwatch?
[ "", "c#", ".net", "performance", "stopwatch", "" ]
I have an application that I want to export high-resolution (or rather, high pixel density?) images for printing - for example, I want images that print at 250 dots per inch (DPI), instead of the default, which I understand to be 72 DPI. I'm using a BufferedImage with a Graphics2D object to draw the image, then ImageIO.write() to save the image. Any idea how I can set the DPI?
Kurt's answer showed the way, still it took me quite some time to get it run, so here is the code that sets DPI when saving a PNG. There is a lot to do to get the proper writers and such... ``` private BufferedImage gridImage; ... private void saveGridImage(File output) throws IOException { output.delete(); final String formatName = "png"; for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) { ImageWriter writer = iw.next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam); if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) { continue; } setDPI(metadata); final ImageOutputStream stream = ImageIO.createImageOutputStream(output); try { writer.setOutput(stream); writer.write(metadata, new IIOImage(gridImage, null, metadata), writeParam); } finally { stream.close(); } break; } } private void setDPI(IIOMetadata metadata) throws IIOInvalidTreeException { // for PMG, it's dots per millimeter double dotsPerMilli = 1.0 * DPI / 10 / INCH_2_CM; IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize"); horiz.setAttribute("value", Double.toString(dotsPerMilli)); IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize"); vert.setAttribute("value", Double.toString(dotsPerMilli)); IIOMetadataNode dim = new IIOMetadataNode("Dimension"); dim.appendChild(horiz); dim.appendChild(vert); IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0"); root.appendChild(dim); metadata.mergeTree("javax_imageio_1.0", root); } ```
# Seting up TIFF DPI If you want to set dpi for TIFF, try to do that by next steps: ``` private static IIOMetadata createMetadata(ImageWriter writer, ImageWriteParam writerParams, int resolution) throws IIOInvalidTreeException { // Get default metadata from writer ImageTypeSpecifier type = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY); IIOMetadata meta = writer.getDefaultImageMetadata(type, writerParams); // Convert default metadata to TIFF metadata TIFFDirectory dir = TIFFDirectory.createFromMetadata(meta); // Get {X,Y} resolution tags BaselineTIFFTagSet base = BaselineTIFFTagSet.getInstance(); TIFFTag tagXRes = base.getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION); TIFFTag tagYRes = base.getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION); // Create {X,Y} resolution fields TIFFField fieldXRes = new TIFFField(tagXRes, TIFFTag.TIFF_RATIONAL, 1, new long[][] { { resolution, 1 } }); TIFFField fieldYRes = new TIFFField(tagYRes, TIFFTag.TIFF_RATIONAL, 1, new long[][] { { resolution, 1 } }); // Add {X,Y} resolution fields to TIFFDirectory dir.addTIFFField(fieldXRes); dir.addTIFFField(fieldYRes); // Add unit field to TIFFDirectory (change to RESOLUTION_UNIT_CENTIMETER if necessary) dir.addTIFFField(new TIFFField(base.getTag(BaselineTIFFTagSet.TAG_RESOLUTION_UNIT), BaselineTIFFTagSet.RESOLUTION_UNIT_INCH)); // Return TIFF metadata so it can be picked up by the IIOImage return dir.getAsMetadata(); } ``` Also, similar way you can setting up any TIFF tag. Read more at the [source](http://www.jochenhebbrecht.be/site/2012-11-25/java/creating-a-tif-file-a-resolution-x-ppi-a-pdfbox-pdpage)
How to set DPI information in an image?
[ "", "java", "image", "" ]
I wonder if it is a good practice to use JUnit's @Ignore. And how people are using it? I came up with the following use case: Let's say I am developing a class and writing a JUnit test for it, which doesn't pass, because I'm not quite done with the class. Is it a good practice to mark it with @Ignore? I'm a little concerned that we might miss the ignored test case later on or that people start using it to "force" tests to pass CI.
Thats pretty much fine, I suppose. The [docs](https://github.com/junit-team/junit/wiki/Ignoring-tests) says, > Test runners will report the number of ignored tests, along with the number of tests > that ran and the number of tests that failed. Hence, it means even if you forget to remove that afterwards, you should have been notified about that. The example given in the [docs](https://github.com/junit-team/junit/wiki/Ignoring-tests), is completely resembling your case. ``` @Ignore("not ready yet") ```
I routinely use @Ignore for tests which fail because of a known bug. Once the bug is acknowledged and logged in the bug databases, the test failure serves no purpose, since the bug is already known. Still it makes sense to keep the test code, because it will be useful again once the bug is fixed. So I mark it to be ignored, with a comment indicating the related bug, and ideally note in the bug report that the test should be reactivated to test the fix.
JUnit's @Ignore
[ "", "java", "unit-testing", "testing", "" ]
Is there a way to undefine the += on strings and wstrings for chars and wchar\_t? Basically I want to avoid bugs like the following: ``` int age = 27; std::wstring str = std::wstring(L"User's age is: "); str += age; std::string str2 = std::string("User's age is: "); str2 += age; ``` The above code will add the ascii character 27 to the string instead of the number 27. **I obviously know how to fix this, but my question is: how do I produce a compiler error in this situation?** Note: You can override += on std::string and int to properly format the string, but this is not what I want to do. I want to completely disallow this operator on these operands.
**You cannot deactivate a specific function** of a class (here std::basic\_string) as it is it's interface that clearly (and officially) allow that manipulation. Trying to overload the operator will only mess things up. Now, **you can "wrap" std::basic\_string in another class**, using private inheritance or composition and then use the public interface as a proxy to the std::basic\_string part, but only the functions you want to be usable. I recommand first replacing you string types with typedefs : ``` namespace myapp { typedef std::string String; typedef std::wstring UTFString; } ``` Then once your application compile fine after having replaced std::string and std::wstring by myapp::String and myapp::UTFString (those are example names), you define the wrapper class somewhere : ``` namespace myapp { /** std::basic_string with limited and controlled interface. */ template< class _Elem, class _Traits, class _Ax > class limited_string { public: typedef std::basic_string< _Elem , _Traits, _Ax > _String; // this is for easier writing typedef limited_string< _Elem, _Traits, _Ax > _MyType; // this is for easier writing private: _String m_string; // here the real std::basic_string object that will do all the real work! public: // constructor proxies... (note that those ones are not complete, it should be exactly the same as the original std::basic_string // see some STL docs to get the real interface to rewrite) limited_string() : m_string {} limited_string( const _MyType& l_string ) : m_string( l_string.m_string ) {} limited_string( const _Elem* raw_string ) : m_string( raw_string ) {} //... etc... // operator proxies... _MyType& operator= ( const _MyType& l_string ) { m_string = l_string.m_string; } // etc... // but we don't want the operator += with int values so we DON'T WRITE IT! // other function proxies... size_t size() const { return m_string.size(); } // simply forward the call to the real string! // etc...you know what i mean... // to work automatically with other STL algorithm and functions we add automatic conversion functions: operator const _Elem*() const { return m_string.c_str(); } // etc.. }; } ``` ...then, you simply replace those lines : ``` // instead of those lines... //typedef std::string String; //typedef std::wstring UTFString; // use those ones typedef limited_string< char, std::char_traits<char>, std::allocator<char> > String; // like std::string typedef typedef limited_string< wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > UTFString; // like std::wstring typedef ``` ... and your example will crash : ``` error C2676: binary '+=' : 'myapp::UTFString' does not define this operator or a conversion to a type acceptable to the predefined operator error C2676: binary '+=' : 'myapp::String' does not define this operator or a conversion to a type acceptable to the predefined operator ``` Here is the full test application code i wrote to prove that (compiled on vc9) : ``` #include <string> #include <iostream> namespace myapp { /** std::basic_string with limited and controlled interface. */ template< class _Elem, class _Traits, class _Ax > class limited_string { public: typedef std::basic_string< _Elem , _Traits, _Ax > _String; // this is for easier writing typedef limited_string< _Elem, _Traits, _Ax > _MyType; // this is for easier writing private: _String m_string; // here the real std::basic_string object that will do all the real work! public: // constructor proxies... (note that those ones are not complete, it should be exactly the same as the original std::basic_string // see some STL docs to get the real interface to rewrite) limited_string() : m_string {} limited_string( const _MyType& l_string ) : m_string( l_string.m_string ) {} limited_string( const _Elem* raw_string ) : m_string( raw_string ) {} //... etc... // operator proxies... _MyType& operator= ( const _MyType& l_string ) { m_string = l_string.m_string; } // etc... // but we don't want the operator += with int values so we DON'T WRITE IT! // other function proxies... size_t size() const { return m_string.size(); } // simply forward the call to the real string! // etc...you know what i mean... // to work automatically with other STL algorithm and functions we add automatic conversion functions: operator const _Elem*() const { return m_string.c_str(); } // etc.. }; // instead of those lines... //typedef std::string String; //typedef std::wstring UTFString; // use those ones typedef limited_string< char, std::char_traits<char>, std::allocator<char> > String; // like std::string typedef typedef limited_string< wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > UTFString; // like std::wstring typedef } int main() { using namespace myapp; int age = 27; UTFString str = UTFString(L"User's age is: "); str += age; // compilation error! std::wcout << str << std::endl; String str2 = String("User's age is: "); str2 += age; // compilation error! std::cout << str2 << std::endl; std::cin.ignore(); return 0; } ``` I think it would cleanly resolve your problem, but you'll have to wrapp all the functions.
Most source control systems allow you to run sanity checks against your code during checkin. So you could set up a test the performs the validation and refuses the checkin on failure: Example: Test Script: ``` #!/bin/tcsh # Pass the file to test as the first argument. echo "#include <string>\ void operator+=(std::string const& , int const&);\ void operator+=(std::string const& , int);"\ | cat - $1 \ | g++ -c -x c++ - >& /dev/null echo $status ``` This script fakes the addition of the two operators above (without actually altering the source). This will cause any use of the operator+ with strings and a char to fail even if the original code compiles. NB: operator+= idea stolen from litb. Who has since deleted his example. But credit where it was due.
How to avoid a common bug in a large codebase?
[ "", "c++", "string", "" ]
Does such a thing exist for [YAML](http://en.wikipedia.org/wiki/Yaml) (aka [YAML](http://yaml.org))? If this existed at one time, it must have been obliterated because the latest search turned up nada. It looks like there are plenty of implementations that **dump** from Javascript to YAML output only, but having trouble finding an implementation that supports both dump and load. Is anyone working on such a thing ... or is the demand simply far too low for this.
Possibly newer version of js-yaml here: <http://github.com/visionmedia/js-yaml>
Was just looking for the same, here's a basic [Javascript-based YAML parser](http://refactormycode.com/codes/1045-js-yaml-parser) written by [Tj Holowaychuk](http://refactormycode.com/users/634) over at [refactormycode.com](http://refactormycode.com/). I'm duplicating it here to ensure it isn't lost, appears the JsYaml link on yaml.org has been broken a while. Haven't tested it yet. ``` ;(function(){ YAML = { valueOf: function(token) { return eval('(' + token + ')') }, tokenize: function(str) { return str.match(/(---|true|false|null|#(.*)|\[(.*?)\]|\{(.*?)\}|[\w\-]+:|-(.+)|\d+\.\d+|\d+|\n+)/g) }, strip: function(str) { return str.replace(/^\s*|\s*$/, '') }, parse: function(tokens) { var token, list = /^-(.*)/, key = /^([\w\-]+):/, stack = {} while (token = tokens.shift()) if (token[0] == '#' || token == '---' || token == "\n") continue else if (key.exec(token) && tokens[0] == "\n") stack[RegExp.$1] = this.parse(tokens) else if (key.exec(token)) stack[RegExp.$1] = this.valueOf(tokens.shift()) else if (list.exec(token)) (stack.constructor == Array ? stack : (stack = [])).push(this.strip(RegExp.$1)) return stack }, eval: function(str) { return this.parse(this.tokenize(str)) } } })() print(YAML.eval(readFile('config.yml')).toSource()) // config.yml --- # just a comment list: ['foo', 'bar'] hash: { foo: "bar", n: 1 } lib: - lib/cart.js - lib/cart.foo.js specs: - spec/cart.spec.js - spec/cart.foo.spec.js # - Commented out environments: all: options: failuresOnly: true verbose: false ```
Pure Javascript YAML library that supports both dump and load?
[ "", "javascript", "serialization", "markup", "yaml", "parsing", "" ]
I would like to map a many-to-many in Hibernate using a link table. I have two classes, Parent and Child class, for example: ``` public class Parent{ private List<Child> _children; //...getters and setters } ``` I use a link table (link\_table) with three columns `link_id`, `parent_id`, and `child_id`. The database is SQL server and id types are uniqueidentifier. So, I usually use guid for the id fields. How can you implement this using the **`<list />`** tag if this is the correct tag to use? Do you know of any good documentation to accomplish this? I am currently getting a ConstraintViolationException but have not been able to find any good documentation or examples of this. **I think a main issue is: how to specify the `link_id` to be automatically generated in the link table.**
I don't think that it is possible (or necessary) to add a link\_id primary key to the join table. The join table will usually consist of the primary keys of the two participating tables. Using XML you will need syntax like this: ``` <class name="Parent"> .... <list name="children" table="link_table"> <key column="parent_id"/> <many-to-many column="child_id" class="Children"/> </list> ... </class> <class name="Child"> ... <list name="parents" inverse="true" table="link_table"> <key column="child_id"/> <many-to-many column="parent_id" class="Parent"/> </list> ... </class> ``` Although I find annotations better to use.
I do this using annotations, specifically @ManyToMany and @JoinTable: [Hibernate Docs:](http://www.hibernate.org/hib_docs/annotations/reference/en/html/entity.html#eentity-mapping-association-collection-manytomany) ``` @Entity public class Employer implements Serializable { @ManyToMany( targetEntity=org.hibernate.test.metadata.manytomany.Employee.class, cascade={CascadeType.PERSIST, CascadeType.MERGE} ) @JoinTable( name="EMPLOYER_EMPLOYEE", joinColumns=@JoinColumn(name="EMPER_ID"), inverseJoinColumns=@JoinColumn(name="EMPEE_ID") ) public Collection getEmployees() { return employees; } } @Entity public class Employee implements Serializable { @ManyToMany( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "employees", targetEntity = Employer.class ) public Collection getEmployers() { return employers; } } ```
How to map many-to-many List in Hibernate with a Link Table
[ "", "java", "hibernate", "mapping", "" ]
We have a site that needs to (as part of our process) generate a document (e.g. Word docx document) that is derived from data within our application merged with a template document. This document can be edited at run time by the user after it is generated. We know we are looking at a CMS like system (since the users will need to be able to edit/create new templates) but I was wondering if Sharepoint could be of better use (since we don;t need a lot of the overhead of a traditional CMS system). Can any sharepoint experts weigh in and give me some pointers of where to look.
I am working on a similar problem -- generating word documents from information stored in a SharePoint site. The real magic here relies on using Content Controls in office 2007 - as the new version of the Office suite is based on Office Open XML, generating documents from data is almost trivial. Enabling the documents to be editable after creation is a simple configuration change that can be made either programmatically or in the document template itself. In fact I think the true value of the platform wills shine when you can see how easily you can your organizations business processes to SharePoint. Getting content from deep within a segment of your company, through the various approval steps to the public facing internet site is breathtakingly simple, once everything is configured properly. Here are some good blog posts on generating OOXML docs on the server * [ECMA Office Open XML - Options for Generating Word Documents (on the server;))](http://blogs.msdn.com/mszcool/archive/2007/07/09/ecma-office-open-xml-options-for-generating-word-documents-on-the-server.aspx) * [Generating Word Documents on the Server (Part 2) - Dynamically Adding Content Controls / Structured Document Tags (SDT) using System.IO.Packaging](http://blogs.msdn.com/mszcool/archive/2007/07/31/generating-word-documents-on-the-server-part-2-dynamically-adding-content-controls-structured-document-tags-sdt-using-system-io-packaging.aspx) Note that clients DO NOT need to run Office 2007 to open these documents, you can either have a conversion process, or you can install the [free compatibility packs for Office XP, 2000 & 2003](http://office.microsoft.com/en-us/products/HA101686761033.aspx) As far as SharePoint as CMS, I think its a pretty compelling proposition. There is definitely some configuration and implementation challenges, but I think that will be the case with any enterprise CMS package. One important consideration is the amount of traffic your CMS'd site will see. I don't think SharePoint is ready to scale up to google-esque traffic, but its certainly going to be good enough for a typical corporate internet presence. Here is a list of some [public sites that are running MOSS](http://blogs.msdn.com/sharepoint/archive/2007/05/03/top-17-case-studies-for-microsoft-office-sharepoint-server-2007-and-several-new-moss-based-web-sites.aspx) Once you get past the hurdle of initial configuration, it becomes very easy to enable CMS tasks across the organization as it works so well on both sides of the Firewall. I think its a great product, and amazed by its flexibility and extensibility. jt
[Infopath](http://msdn.microsoft.com/en-us/library/ms573938.aspx) is the forms technology that Sharepoint people are going to recommend to you. Most Infopath forms features require a full MOSS installation and the associated licensing fees. I think you can acheive what you want here with just WSS however. If DOCX files as the form template is a hard and fast requirement of your app you can; 1. Automate Word (physically isolate this), this is **not** officially supported by MS 2. Explore using [OpenXML](http://openxmldeveloper.org/) (assuming all clients are using Word 2007). If you ultimately need to generate PDFs or Word 2003 DOC files as output you are stuck automating Word otherwise #2 is the most server friendly solution. Either way I think you can use a [SP document library](http://msdn.microsoft.com/en-us/library/ms954724.aspx) to hold the DOCX files and your users can share and edit the templates with versioning this way. You can programatically access these files in your application specific code and perform the data merging 'out of band'.
Sharepoint as template application
[ "", "c#", "sharepoint", "sharepoint-2007", "" ]
Trying to add an onclick handler to my tabs, and can't seem to get the DOM selection right. Can you guys help? ``` <div id="tabstrip"> <ul> <li id="a" class="selected"><a href="#">A</a></li> <li id="b"><a href="#">B</a></li> <li id="b"><a href="#">C</a></li> </ul> </div> function initTabStrip() { var lis = document.getElementById('tabstrip').getElementsByTagName('li'); for (var i=0;i<items.length;i++) { var as = items[i].getElementsByTagName('a'); for (var j=0;j<as.length;j++) { as[j].onclick=function(){changeTab(items[i].id);return false} } } } ```
Seems like your closure is wrong. Try ``` as[j].onclick = function(items, i) { return function() { changeTab(items[i].id); return false; }; }(items, i); ``` If it works then the question is a dupe of [jQuery Closures, Loops and Events](https://stackoverflow.com/questions/359467/jquery-closures-loops-and-events#359505)
I agree to RoBorg and suggest reading about JavaScript scopes. It will explain a lot.
Trouble adding onclick handler to hyperlink tag inside listitem
[ "", "javascript", "onclick", "handler", "" ]
I'm building a site where users can track their collection of figures for Dungeons & Dragons (www.ddmdb.com). The models/relationships involved in this funcitonality are the following: **User:** * id * login (username) * *a bunch of other fields* **Miniature:** * id * name * number (# in the set, not count) * release\_id (foreign key) * *a bunch of other fields and foreign keys* **Ownership:** * id (is this really even needed?) * user\_id * miniature\_id * have\_count * favorite (boolean) The pertinent relationships I have set up are as follows: **User:** * has\_many :ownerships * has\_many :miniatures, :through => :ownerships, :uniq => true, :conditions => "ownerships.have\_count > 0" * has\_many :favorites, :through => :ownerships, :source => :miniature, :uniq => true, :conditions => "ownerships.favorite = true" **Miniatures:** * has\_many :ownerships * has\_many :owners, :through => :ownerships, :source => :user, :uniq => true, :conditions => "ownerships.have\_count > 0" **Ownership:** * belongs\_to :user * belongs\_to :miniature I have a page where user's can both view and update their collection, as well as view other user's collections. It contains a list of all the miniatures on the site and a text box next to each where the user can enter how many of each miniature they have. This functionality also exists in sub-lists of miniatures (filtered by type, release, size, rarity, etc.) When a user creates an account they have no entries in the ownership. When they use the collection page or sub-list of miniatures to update their collection, I create entries in the ownership table for only the miniatures on the submitting page. So if it's the full Collection list I update all minis (even if the count is 0) or if it's a sub-list, I only update those miniatures. So at any time a particular user I may have: - no entries in ownership - entries for some of the miniatures - entries for all the miniatures. The problem I'm having is that I don't know how to query the database with a LEFT JOIN using a "Rails method" so that if a user doesn't have an entry for a miniature in Ownerships it defaults to a have\_count of 0. Currently I query for each user\_id/miniature\_id combination individually as I loop through all miniatures and it's obviously really inefficient. **View:** ``` <% for miniature in @miniatures %> <td><%= link_to miniature.name, miniature %></td> <td><%= text_field_tag "counts[#{miniature.id}]", get_user_miniature_count(current_user, miniature), :size => 2 %></td> <% end %> ``` **Helper:** ``` def get_user_miniature_count(user, miniature) ownerships = user.ownerships ownership = user.ownerships.find_by_miniature_id(miniature.id) if ownership.nil? return 0 else return ownership.have_count end end ``` An alternate solution would be creating entries for all miniatures when a user signs up, but then I would also have to add a 0 have\_count for all users when a new miniature is added to the database after they sign up. That seems like it could get a bit complex, but perhaps it's the right way to go? Is there a way to do the join and supply a default value for miniatures where there's no entries in the Ownership table for that particular user?
Using fd's suggestion and information found at <http://www.ruby-forum.com/topic/52385>, I created the following method: ``` def miniature_count(miniature_id) if @counts.nil? @counts = Hash.new ownerships.collect{|o| @counts[o.miniature_id] = o.have_count } end count = @counts[miniature_id] || 0 end ``` This ends up being faster than the *detect* approach. I picked *miniature\_count* over *owns* for the name because *owns* sounds like a method that should return a boolean instead of an integer. **Query Every Entry** Completed in 2.61783 (0 reqs/sec) | Rendering: 1.14116 (43%) | DB: 1.34131 (51%) | 200 OK [<http://ddmdb/collection/1]> **Detect Methods** Completed in 2.20406 (0 reqs/sec) | Rendering: 1.87113 (84%) | DB: 0.21206 (9%) | 200 OK [<http://ddmdb/collection/1]> **Hash Method** Completed in 0.41957 (2 reqs/sec) | Rendering: 0.19290 (45%) | DB: 0.10735 (25%) | 200 OK [<http://ddmdb/collection/1]> I will definitely need to add caching, but this is definitely an improvement. I also suspect I am prematurely optimizing this code, but it's a small site and a 2.5 second load time was not making me happy.
The first thing I would say is that the User model should own the code that works out how many of a given miniature the user owns, since it seems like "business logic" rather than view formatting. My suggestion would be to add a method to your User model: ``` def owns(miniature_id) o = ownerships.detect { |o| o.miniature_id == miniature_id } (o && o.have_count) || 0 end ``` Dry-coded, ymmv. Edit: Note that ownerships is cached by Rails once loaded and detect is not overridden by ActiveRecord like find is, and so acts as you would expect it to on an Array (ie no database operations).
How can I make this Ruby on Rails page more efficient?
[ "", "sql", "ruby-on-rails", "activerecord", "performance", "" ]
Given a function: ``` function x(arg) { return 30; } ``` You can call it two ways: ``` result = x(4); result = new x(4); ``` The first returns 30, the second returns an object. How can you detect which way the function was called **inside the function itself**? Whatever your solution is, it must work with the following invocation as well: ``` var Z = new x(); Z.lolol = x; Z.lolol(); ``` All the solutions currently think the `Z.lolol()` is calling it as a constructor.
**NOTE: This is now possible in ES2015 and later. See [Daniel Weiner's answer](https://stackoverflow.com/a/31060154/96100).** I don't think what you want is possible [prior to ES2015]. There simply isn't enough information available within the function to make a reliable inference. Looking at the ECMAScript 3rd edition spec, the steps taken when `new x()` is called are essentially: * Create a new object * Assign its internal [[Prototype]] property to the prototype property of `x` * Call `x` as normal, passing it the new object as `this` * If the call to `x` returned an object, return it, otherwise return the new object Nothing useful about how the function was called is made available to the executing code, so the only thing it's possible to test inside `x` is the `this` value, which is what all the answers here are doing. As you've observed, a new instance of\* `x` when calling `x` as a constructor is indistinguishable from a pre-existing instance of `x` passed as `this` when calling `x` as a function, **unless** you assign a property to every new object created by `x` as it is constructed: ``` function x(y) { var isConstructor = false; if (this instanceof x // <- You could use arguments.callee instead of x here, // except in in EcmaScript 5 strict mode. && !this.__previouslyConstructedByX) { isConstructor = true; this.__previouslyConstructedByX = true; } alert(isConstructor); } ``` Obviously this is not ideal, since you now have an extra useless property on every object constructed by `x` that could be overwritten, but I think it's the best you can do. **(\*)** "instance of" is an inaccurate term but is close enough, and more concise than "object that has been created by calling `x` as a constructor"
### As of ECMAScript 6, this is possible with [`new.target`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target) `new.target` will be set as `true` if the function is called with `new` (or with `Reflect.construct`, which acts like `new`), otherwise it's `undefined`. ``` function Foo() { if (new.target) { console.log('called with new'); } else { console.log('not called with new'); } } new Foo(); // "called with new" Foo(); // "not called with new" Foo.call({}); // "not called with new" ```
How to detect if a function is called as constructor?
[ "", "javascript", "constructor", "" ]
I have an application that has several objects (about 50 so far, but growing). There is only one instance of each of these objects in the app and these instances get shared among components. What I've done is derive all of the objects from a base BrokeredObject class: ``` class BrokeredObject { virtual int GetInterfaceId() = 0; }; ``` And each object type returns a unique ID. These IDs are maintained in a header file. I then have an ObjectBroker "factory". When someone needs an object, then call GetObjectByID(). The boker looks in an STL list to see if the object already exists, if it does, it returns it. If not, it creates it, puts it in the list and returns it. All well and good. ``` BrokeredObject *GetObjectByID(int id) { BrokeredObject *pObject; ObjectMap::iterator = m_objectList.find(id); // etc. if(found) return pObject; // not found, so create switch(id) { case 0: pObject = new TypeA; break; case 1: pObject = new TypeB; break; // etc. // I loathe this list } // add it to the list return pObject; } ``` What I find painful is maintaining this list of IDs and having to have each class implement it. I have at least made my consumer's lives slightly easier by having each type hold info about it's own ID like this: ``` class TypeA : public BrokeredObject { static int get_InterfaceID() { return IID_TYPEA; } int GetInterfaceID() { return get_InterfaceID(); } }; ``` So I can get an object like this: ``` GetObjectByID(TypeA::get_InterfaceID()); ``` Intead of having to actually know what the ID mapping is but I still am not thrilled with the maintenance and the potential for errors. It seems that if I know the type, why should I also have to know the ID? What I long for is something like this in C#: ``` BrokeredObject GetOrCreateObject<T>() where T : BrokeredObject { return new T(); } ``` Where the ObjectBroker would create the object based on the *type* passed in. Has C# spoiled me and it's just a fact of life that C++ can't do this or is there a way to achieve this that I'm not seeing?
My use-case tended to get a little more complex - I needed the ability to do a little bit of object initialization and I needed to be able to load objects from different DLLs based on configuration (e.g. simulated versus actual for hardware). It started looking like COM and ATL was where I was headed, but I didn't want to add the weight of COM to the OS (this is being done in CE). What I ended up going with was template-based (thanks [litb](https://stackoverflow.com/users/34509/litb) for putting me on track) and looks like this: ``` class INewTransModule { public: virtual bool Init() { return true; } virtual bool Shutdown() { return true; } }; template <typename T> struct BrokeredObject { public: inline static T* GetInstance() { static T t; return &t; } }; template <> struct BrokeredObject<INewTransModule> { public: inline static INewTransModule* GetInstance() { static INewTransModule t; // do stuff after creation ASSERT(t.Init()); return &t; } }; class OBJECTBROKER_API ObjectBroker { public: // these calls do configuration-based creations static ITraceTool *GetTraceTool(); static IEeprom *GetEeprom(); // etc }; ``` Then to ensure that the objects (since they're templated) actually get compiled I added definitions like these: ``` class EepromImpl: public BrokeredObject<EepromImpl>, public CEeprom { }; class SimEepromImpl: public BrokeredObject<SimEepromImpl>, public CSimEeprom { }; ```
Yes, there is a way. A pretty simple even in C++ to what that C# code does (without checking for inheritance though): ``` template<typename T> BrokeredObject * GetOrCreateObject() { return new T(); } ``` This will work and do the same as the C# code. It is also type-safe: If the type you pass is not inherited from BrokeredObject (or isn't that type itself), then the compiler moans at the return statement. It will however always return a new object. ### Singleton As another guy suggested (credits to him), this all looks very much like a fine case for the singleton pattern. Just do `TypeA::getInstance()` to get the one and single instance stored in a static variable of that class. I suppose that would be far easier than the above way, without the need for IDs to solve it (i previously showed a way using templates to store IDs in this answer, but i found it effectively is just what a singleton is). I've read that you will leave the chance open to have multiple instances of the classes. One way to do that is to have a *Mingleton* (i made up that word :)) ``` enum MingletonKind { SINGLETON, MULTITON }; // Singleton template<typename D, MingletonKind> struct Mingleton { static boost::shared_ptr<D> getOrCreate() { static D d; return boost::shared_ptr<D>(&d, NoopDel()); } struct NoopDel { void operator()(D const*) const { /* do nothing */ } }; }; // Multiton template<typename D> struct Mingleton<D, MULTITON> { static boost::shared_ptr<D> getOrCreate() { return boost::shared_ptr<D>(new D); } }; class ImASingle : public Mingleton<ImASingle, SINGLETON> { public: void testCall() { } // Indeed, we have to have a private constructor to prevent // others to create instances of us. private: ImASingle() { /* ... */ } friend class Mingleton<ImASingle, SINGLETON>; }; class ImAMulti : public Mingleton<ImAMulti, MULTITON> { public: void testCall() { } // ... }; int main() { // both do what we expect. ImAMulti::getOrCreate()->testCall(); ImASingle::getOrCreate()->testCall(); } ``` Now, you just use `SomeClass::getOrCreate()` and it cares about the details. The custom deleter in the singleton case for shared\_ptr makes deletion a no-op, because the object owned by the shared\_ptr is allocated statically. However, be aware of problems of destruction order of static variables: [Static initialization order fiasco](https://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems)
Looking for a better C++ class factory
[ "", "c++", "design-patterns", "" ]
I can create a literal long by appending an L to the value; why can't I create a literal short or byte in some similar way? Why do I need to use an int literal with a cast? And if the answer is "Because there was no short literal in C", then why are there no short literals in C? This doesn't actually affect my life in any meaningful way; it's easy enough to write (short) 0 instead of 0S or something. But the inconsistency makes me curious; it's one of those things that bother you when you're up late at night. Someone at some point made a design decision to make it possible to enter literals for some of the primitive types, but not for all of them. Why?
In C, `int` at least was meant to have the "natural" word size of the CPU and `long` was probably meant to be the "larger natural" word size (not sure in that last part, but it would also explain why `int` and `long` have the same size on x86). Now, my guess is: for `int` and `long`, there's a natural representation that fits exactly into the machine's registers. On most CPUs however, the smaller types `byte` and `short` would have to be padded to an `int` anyway before being used. If that's the case, you can as well have a cast.
I suspect it's a case of "don't add anything to the language unless it really adds value" - and it was seen as adding sufficiently little value to not be worth it. As you've said, it's easy to get round, and frankly it's rarely necessary anyway (only for disambiguation). The same is true in C#, and I've never particularly missed it in either language. What I do miss in Java is an unsigned byte type :)
Why are there no byte or short literals in Java?
[ "", "java", "primitive", "" ]
I'm trying to enforce integrity on a table in a way which I do not think a Constraint can... ``` CREATE TABLE myData ( id INTEGER IDENTITY(1,1) NOT NULL, fk_item_id INTEGER NOT NULL, valid_from DATETIME NOT NULL, invlaid_from DATETIME NOT NULL ) ``` The constraint I want to apply is that there should never be any entries for the same "fk\_item\_id" with overlapping dates. Note: invalid\_from is the instant immediately after the valid period. This means that the following two periods are fine... * '2008 Jan 01 00:00' -> '2008 Feb 01 00:00' (All of Jan) * '2008 Feb 01 00:00' -> '2008 Mar 01 00:00' (All of Feb) I can check that rule in a trigger. When the trigger does find an illegal insert/update, however, what is the best way to prevent the "illegal" inserts/updates from happening? (If *inserted* includes two valid records and two invalid records, can I stop just the two invalid records?) Cheers, Dems. **EDIT:** In the case I had above, a constraint using a function worked well. But I never worked out why the RAISERROR didn't work in the trigger version. I thought it was because the trigger is an AFTER trigger, and that I'd need a BEFORE trigger, but that doesn't appear to be an option...
You can't delete directly from inserted (updates to the logical tables raise an error) but you can join back to the source table as seen below ``` create table triggertest (id int null, val varchar(20)) Go create trigger after on [dbo].triggertest for Update as Begin delete tt from triggertest tt inner join inserted i on tt.id = i.id where i.id = 9 End GO insert into triggertest values (1,'x') insert into triggertest values (2,'y') Update triggertest set id = 9 where id = 2 select * from triggertest 1, x ``` Also, you don't have to go the trigger route, you can also bind a check constraint to the return value of a function ``` Alter table myData WITH NOCHECK add Constraint CHK_VALID CHECK (dbo.fx_CheckValid(id, valid_from , invalid_from) = 1 ); ```
Don't delete the records from the inserted table... that's silent failure. The road to hell is paved in Partial Commits. You need to [RAISERROR](http://msdn.microsoft.com/en-us/library/ms178592.aspx), which is essentially what a [constraint](http://msdn.microsoft.com/en-us/library/ms188066.aspx) would do.
Using Triggers To Enforce Constraints
[ "", "sql", "sql-server", "sql-server-2005", "triggers", "constraints", "" ]
I am creating an HTML form with some radio button options. I'd like to have one option as "Other - please specify" and allow the user to type something in. Two questions: 1) How can I make a "hybrid" input type of `radio/text`? 2) On the PHP back end, if the input has the same `name` attribute as the radio inputs, will the user's input be part of the same array?
#1: To the "other:" radio field, add a `<input type="text" ...>` with style display:none and only display it when user selects the "other:" radio field. However, I'm not entirely sure if #2 would work. You'd get `rboption=other` from the radio button AND `rboption=some%20text` from the text field. One will usually overwrite the other, but it's not sure which (read: depends on position in page, browser and phase of the moon). To be sure, make the textfield name different and only process it when `rboption == 'other'` (like Salty said)
Why not just add a different *name* attribute to the input and only validate it if the *other* radio button has been selected?
How can I make a radio button for "Other - please specify?"
[ "", "php", "html", "forms", "radio-button", "" ]
When I click on a row in my GridView, I want to go to a other page with the ID I get from the database. In my RowCreated event I have the following line: ``` e.Row.Attributes.Add( "onClick", ClientScript.GetPostBackClientHyperlink( this.grdSearchResults, "Select$" + e.Row.RowIndex)); ``` To prevent error messages i have this code: ``` protected override void Render(HtmlTextWriter writer) { // .NET will refuse to accept "unknown" postbacks for security reasons. // Because of this we have to register all possible callbacks // This must be done in Render, hence the override for (int i = 0; i < grdSearchResults.Rows.Count; i++) { Page.ClientScript.RegisterForEventValidation( new System.Web.UI.PostBackOptions( grdSearchResults, "Select$" + i.ToString())); } // Do the standard rendering stuff base.Render(writer); } ``` How can I give a row a unique ID (from the DB) and when I click the row, another page is opened (like clicking on a href) and that page can read the ID.
I have the solution. This is what i have done: ``` if(e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes["onClick"] = "location.href='view.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "id") + "'"; } ``` I have putted the preceding code in the RowDataBound event.
Martijn, Here's another example with some nifty row highlighting and a href style cursor: ``` protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ceedfc'"); e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''"); e.Row.Attributes.Add("style", "cursor:pointer;"); e.Row.Attributes.Add("onclick", "location='patron_detail.aspx?id=" + e.Row.Cells[0].Text + "'"); } } ``` The code above works in .NET 3.5. However, you can't set your id column to Visible="false" because you'll get a blank query string value for your id key: ``` <asp:GridView ID="gvSearch" runat="server" OnRowDataBound="gvSearch_RowDataBound" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="id" Visible="false" /> <asp:BoundField DataField="first_name" HeaderText="First" /> <asp:BoundField DataField="last_name" HeaderText="Last" /> <asp:BoundField DataField="email" HeaderText="Email" /> <asp:BoundField DataField="state_name" HeaderText="State" /> </Columns> </asp:GridView> ``` So change the first column to this instead: ``` <asp:BoundField DataField="id" ItemStyle-CssClass="hide" /> ``` Add this css to the top of your page: ``` <head> <style type="text/css"> .hide{ display:none; } </style> <head> ``` But to hide the first cell of your header row, add this to your gvSearch\_RowDataBound() in code-behind: ``` if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[0].CssClass = "hide"; } ``` Obviously, you could have hidden the id column in code-behind too, but this will result in more text in your markup than a css class: ``` e.Row.Cells[0].Attributes.Add("style", "display:none;"); e.Row.Attributes.Add("style", "cursor:pointer;"); ```
c# gridview row click
[ "", "c#", "gridview", "click", "" ]
Suppose I have a `std::vector` (let's call it `myVec`) of size `N`. What's the simplest way to construct a new vector consisting of a copy of elements X through Y, where 0 <= X <= Y <= N-1? For example, `myVec [100000]` through `myVec [100999]` in a vector of size `150000`. If this cannot be done efficiently with a vector, is there another STL datatype that I should use instead?
``` vector<T>::const_iterator first = myVec.begin() + 100000; vector<T>::const_iterator last = myVec.begin() + 101000; vector<T> newVec(first, last); ``` It's an O(N) operation to construct the new vector, but there isn't really a better way.
Just use the vector constructor. ``` std::vector<int> data(); // Load Z elements into data so that Z > Y > X std::vector<int> sub(&data[100000],&data[101000]); ```
Best way to extract a subvector from a vector?
[ "", "c++", "stl", "vector", "range", "" ]
I have the following table and data in SQL Server 2005: ``` create table LogEntries ( ID int identity, LogEntry varchar(100) ) insert into LogEntries values ('beans') insert into LogEntries values ('beans') insert into LogEntries values ('beans') insert into LogEntries values ('cabbage') insert into LogEntries values ('cabbage') insert into LogEntries values ('beans') insert into LogEntries values ('beans') ``` I would like to group repeated LogEntries so that I have the following results: ``` LogEntry EntryCount beans 3 cabbage 2 beans 2 ``` Can you think of any way to do this in TSQL outside of using a cursor?
This is a set-based solution for the problem. The performance will probably suck, but it works :) ``` CREATE TABLE #LogEntries ( ID INT IDENTITY, LogEntry VARCHAR(100) ) INSERT INTO #LogEntries VALUES ('beans') INSERT INTO #LogEntries VALUES ('beans') INSERT INTO #LogEntries VALUES ('beans') INSERT INTO #LogEntries VALUES ('cabbage') INSERT INTO #LogEntries VALUES ('cabbage') INSERT INTO #LogEntries VALUES ('carrots') INSERT INTO #LogEntries VALUES ('beans') INSERT INTO #LogEntries VALUES ('beans') INSERT INTO #LogEntries VALUES ('carrots') SELECT logentry, COUNT(*) FROM ( SELECT logentry, ISNULL((SELECT MAX(id) FROM #logentries l2 WHERE l1.logentry<>l2.logentry AND l2.id < l1.id), 0) AS id FROM #LogEntries l1 ) AS a GROUP BY logentry, id DROP TABLE #logentries ``` Results: ``` beans 3 cabbage 2 carrots 1 beans 2 carrots 1 ``` The ISNULL() is required for the first set of beans.
I think this will do it... didn't check too thoroughly though ``` select COUNT(*),subq.LogEntry from ( select ROW_NUMBER() OVER(ORDER BY id)-ROW_NUMBER() OVER(PARTITION BY logentry ORDER BY id) as t,* from LogEntries ) subq group by subq.t,subq.LogEntry order by MIN(subq.ID) ```
Group repeated rows in TSQL
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I want in a good performance way (I hope) replace a named parameter in my string to a named parameter from code, example, my string: ``` "Hi {name}, do you like milk?" ``` How could I replace the {name} by code, Regular expressions? To expensive? Which way do you recommend? How do they in example NHibernates HQL to replace :my\_param to the user defined value? Or in ASP.NET (MVC) Routing that I like better, "{controller}/{action}", new { controller = "Hello", ... }?
Have you confirmed that regular expressions are too expensive? The cost of regular expressions is greatly exaggerated. For such a simple pattern performance will be quite good, probably only slightly less good than direct search-and-replace, in fact. Also, have you experimented with the `Compiled` flag when constructing the regular expression? That said, can't you just use the simplest way, i.e. `Replace`? ``` string varname = "name"; string pattern = "{" + varname + "}"; Console.WriteLine("Hi {name}".Replace(pattern, "Mike")); ```
Regex is certainly a viable option, especially with a `MatchEvaluator`: ``` Regex re = new Regex(@"\{(\w*?)\}", RegexOptions.Compiled); // store this... string input = "Hi {name}, do you like {food}?"; Dictionary<string, string> vals = new Dictionary<string, string>(); vals.Add("name", "Fred"); vals.Add("food", "milk"); string q = re.Replace(input, delegate(Match match) { string key = match.Groups[1].Value; return vals[key]; }); ```
C# Named parameters to a string that replace to the parameter values
[ "", "c#", "regex", "performance", "string", "named-parameters", "" ]
I have a site where users can post stuff (as in forums, comments, etc) using a customised implementation of TinyMCE. A lot of them like to copy & paste from Word, which means their input often comes with a plethora of associated MS inline formatting. I can't just get rid of `<span whatever>` as TinyMCE relies on the span tag for some of it's formatting, and I can't (and don't want to) force said users to use TinyMCE's "Paste From Word" feature (which doesn't seem to work that well anyway). Anyone know of a library/class/function that would take care of this for me? It must be a common problem, though I can't find anything definitive. I've been thinking recently that a series of brute-force regexes looking for MS-specific patterns might do the trick, but I don't want to re-write something that may already be available unless I must. Also, fixing of curly quotes, em-dashes, etc would be good. I have my own stuff to do this now, but I'd really just like to find one MS-conversion filter to rule them all.
[HTML Purifier](http://htmlpurifier.org/) will create standards compliant markup and filter out many possible attacks (such as XSS). For faster cleanups that don't require XSS filtering, I use the PECL extension [Tidy](http://www.php.net/tidy) which is a binding for the [Tidy HTML](http://www.w3.org/People/Raggett/tidy/) utility. If those don't help you, I suggest you switch to FCKEditor which has this feature [built-in](http://docs.fckeditor.net/FCKeditor_2.x/Users_Guide/Common_Tasks/Cut%2C_Copy_and_Paste).
In my case, this worked just fine: ``` $text = strip_tags($text, '<p><a><em><span>'); ``` Rather than trying to pull out stuff you don't want such as embedded word xml, you can just specify you're allowed tags.
PHP to clean-up pasted Microsoft input
[ "", "php", "ms-word", "tinymce", "user-input", "" ]
At my current job I've been working on making web apps with Java, Tapestry, Hibernate, MSSQL, and Tomcat. I've got an idea for a little web game I'd like to write. I'd like to know what the SO community would use for something like this. Should I stick to what I know? I was thinking it would be very beneficial for me to learn different languages and frameworks. Any suggestions?
My recommendation would be to see what you could do with a combination of Google App Engine, Django, and JavaFX. In doing so, you'd learn some new technologies (App Engine) and languages (Python for Django, JavaFX) while taking advantage of what you already know about web apps and Java.
If its a personal project then take this as an opportunity to learn something new.
What would you use to build a web app?
[ "", "java", "" ]
So, I have an API that I need to implement in to an existing framework. This API manages interactions with an external server. I've been charged with coming up with a way to create an easily repeatable "pattern," so that if people are working on new projects in the given framework they have a simple solution for integrating the API. My first idea was to create a class for your "main" class of the framework to extend that, would provide all the virtual functions necessary to interact with the API. However, my boss vetoed this, since the existing framework is "inheritence heavy" and he wants to avoid adding to the madness. I obviously can't incapsulate my API, because that is what the API itself is supposed to be doing, and doing so might hide functionality. Short of asking futures developers to copy and paste my example, what do I do?
If your boss is hostile to inheritance, try aggregation. (*Has-a* relationships rather than inheritance's *is-a* relationship.) Assuming you interface with the API in question via an object, maybe you can just keep that object in a property of your framework 'main' class, so you'd interact with it like `main->whateverapi->doWhatever()`. If the API isn't object-implemented or you need to load a lot of functionality specific to your environment onto it, that points toward making your own class that goes into that role and relates to the third party API however it needs to. Yeah, this basically means you're building an API to the API. Aggregation allows you to avoid the masking-functionality problem, though; even if you do have to do an intermediary layer, you can expose the original API as `main->yourobject->originalapi` and not have to worry about inheritance mucking things up.
Sounds to me like what your boss is having a problem with is the Framework part of this. There is an important distiction between Framework and API, in order to code to a framework you must have a good understanding of it and how it fits within your overall development, much more of a wholeistic view, adding to frameworks should never be taken lightly. API's on the other hand are just an interface to your application / Framework and usually just a library of utility calls, I can't see that he would have a problem with inheritance or aggregation in a library, seems to me that the issue would be creating additional complexity in the framework itself, i.e. requiring developers to extend the main class of the framework is much more onerous than creating a stand alone API library that people can just call into (if they choose) I would be willing to bet that your boss would not care (in fact probably support) if the library itself contained inheritance.
Avoiding Inheritance Madness
[ "", "c++", "design-patterns", "" ]
I have a std::vector containing a handful of numbers, which are not in any particular order, and may or may not have gaps between the numbers - for example, I may have { 1,2,3, 6 } or { 2,8,4,6 } or { 1, 9, 5, 2 }, etc. I'd like a simple way to look at this vector and say 'give me the lowest number >= 1 which does *not* appear in the vector'. So, for the three examples above, the answers would be 4, 1 and 3 respectively. It's not performance critical, and the list is short so there aren't any issues about copying the list and sorting it, for example. I am not really stuck for a way to do this, but my STL skills are seriously atrophied and I can feel that I'm about to do something inelegant - I would be interested to see what other people came up with.
The checked answer uses < for comparison. != is much simpler: ``` int find_gap(std::vector<int> vec) { std::sort(vec.begin(), vec.end()); int next = 1; for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) { if (*it != next) return next; ++next; } return next; } find_gap(1,2,4,5) = 3 find_gap(2) = 1 find_gap(1,2,3) = 4 ``` I'm not passing a reference to the vector since a) he said time doesn't matter and b) so I don't change the order of the original vector.
The standard algorithm you are looking for is **[std::adjacent\_find](http://en.cppreference.com/w/cpp/algorithm/adjacent_find)**. Here is a solution that also uses a lambda to make the predicate clean: ``` int first_gap( std::vector<int> vec ) { // Handle the special case of an empty vector. Return 1. if( vec.empty() ) return 1; // Sort the vector std::sort( vec.begin(), vec.end() ); // Find the first adjacent pair that differ by more than 1. auto i = std::adjacent_find( vec.begin(), vec.end(), [](int l, int r){return l+1<r;} ); // Handle the special case of no gaps. Return the last value + 1. if ( i == vec.end() ) --i; return 1 + *i; } ```
Finding gaps in sequence of numbers
[ "", "c++", "stl", "" ]
When using auto implemnted properies like public string MyProperty { get; set; } This is great until you come to naming conventions. I use underscore for class level fields ie string \_MyProperty; so with auto implemented means that it is not obvious what the variable is and it scope. If you get my meaning, any thoughts?? Malcolm Edit: As the property is public you dont want to use a underscore either.
PascalCasing tells you its class level AND public. (Look at this [article about naming conventions for .NET](http://www.irritatedvowel.com/Programming/Standards.aspx))
you don't need the \_ at all when you use the automatic properties and a modern IDE (like visual studio). intellisense will work correctly if you use automatic properties and different visibilities. the compiler will also check it. ``` public string SomeString { private set; get; } private string some2string; public string Some3string { set; get; } ``` this means that SomeString is only internal writeable. you will not get the property outside of the class. so no magic \_ etc. if you have a really class-only property, then there is no need to make property, make just a field.
C# - Using auto implemented properties and naming conventions
[ "", "c#", "" ]
I am asking about that as I am going to develop a client side application using c# to display stock data and make some user-interaction, so give me links for best tutorials you read before
[Jeremy Miller's guide](http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx) is an excellent starting place. It covers several important patterns including: * [Model - View - Controller](http://codebetter.com/blogs/jeremy.miller/archive/2007/05/23/build-your-own-cab-part-2-the-humble-dialog-box.aspx) - There are several flavours, make sure you examine them all * [Automated unit testing](http://codebetter.com/blogs/jeremy.miller/archive/2007/06/26/build-your-own-cab-part-10-unit-testing-the-ui-with-nunitforms.aspx) of GUI binding code * [Command pattern](http://codebetter.com/blogs/jeremy.miller/pages/build-your-own-cab-14-managing-menu-state-with-microcontroller-s-command-s-a-layer-supertype-some-structuremap-pixie-dust-and-a-dollop-of-fluent-interface.aspx) * [Registry](http://codebetter.com/blogs/jeremy.miller/archive/2008/01/15/build-your-own-cab-17-boil-down-the-quot-wiring-quot-to-a-registry.aspx) You will also want to look at inversion of control and dependency inversion. [Fowler's overview](http://martinfowler.com/articles/injection.html) does a good job of explaining the concept. When you've looked at this, here is a [tutorial](http://aspadvice.com/blogs/insane_world/archive/2007/06/25/Windsor-Container-Tutorials-_2D00_-BitterCoder_2700_s-Wiki.aspx) on just one implementation of an IoC tool. If you are still hungry for more, check out [Rich Newman's series](http://richnewman.wordpress.com/intro-to-cab-toc/) on Microsoft's Composite Application Block. The CAB is chock full of patterns, but avoid the official documentation as it is notoriously difficult.
To answer your question, the most common pattern appears to be generalized hacking in my experience, however if you want a nice pattern check out the [MVP (Model View Presenter)](http://www.codeplex.com/websf/Wiki/View.aspx?title=MVP_landing_page) pattern from Microsoft's Patterns and Practices group. Although it's an ASP.NET pattern, I modify it slightly to use on Winforms all the time. It's a nice separation of concerns, and allows for unit test to be built through programming to interfaces (design by composition).
What is the most common design patterns for any windows forms application?
[ "", "c#", "winforms", "design-patterns", "" ]
I have to pass some parameter from an action to another action,for example to keep trace of an event. What is the best way to do that? I would not use session parameters. Thanks
Assuming you are serverside within one action and wishing to invoke another action with some parameters. You can use the s:action tag to invoke another action, possibly with additional/other parameters than the original action: ``` <s:action name="myAction" ignoreContextParams="true" executeResult="true"> <s:param name="foo" value="bar"/> </s:action> ``` You can also use a standard struts-xml result type with a parameter: ``` <result name="success" type="redirect" > <param name="location">foo.jsp?foo=${bar}</param> <param name="parse">true</param> <param name="encode">true</param> </result> ``` If you want a client side redirect you have to send an url back to the client with the proper parameters, and maybe use some javascript to go there. ``` <s:url action="myAction" > <s:param name="foo" value="bar"/> </s:url> ```
``` <td> <s:url id="url" action="Logging"> <s:param name="m_userNameInAction"><s:property value="m_userNameInForm"/></s:param> </s:url> <s:a href="%{url}">English</s:a> </td> ```
Struts2 parameters between actions
[ "", "java", "jsp", "struts2", "parameters", "action", "" ]
I'm currently writing an implementation of a JDBC driver (*yes, you read that correctly*) in a TDD manner and while I have only finished class stubs at this point and only some minor functionality, it just occured to me that since `Statement` is a superclass for `PreparedStatement` which is a superclass for `CallableStatement`, what should I do when I really start to write tests for my implementations of those classes, which one of these should I do: 1. Create a test suite for `Statement` and then extend that suite for additional tests for `PreparedStatement` and then do the same for `CallableStatement`. 2. Test each implementation individually ignoring the methods inherited from superclass(es). 3. Rigorously test every single method individually for each implementation class; It is possible that some inherited methods work differently depending on implementation after all. Mild variation of this would be that I'd test all those inherited methods the implementation uses. Number two feels the most natural but due to the reason I put to the third one I'm not that sure if it'd be wise to do so. So, what do **you** think I should do?
I would specifically never do alternative 1 (letting the test-class hierarchy be the same as the actual class hierarchy) if this means you will be running the same tests repeatedly for each test subclass. I am also generally sceptical of subclassing test classes other than the general utility base class. I normally make 1 test for each class in a hierarchy, abstract or not. So the base class has a separate test (usually with a test-local private subclass that is used for testing it specifically), and I use my knowledge of the subclasses to write proper tests for each subclass. I can see in coverage runs what is missing tests, so I'm usually not too formalized up-front.
"test every single method individually for each implementation class" In particular, failure to override a superclass method properly is a common bug. The author of the subclass makes assumptions about the superclass. The superclass changes, and the subclass is now broken.
Should I unit test methods which are inherited from super class?
[ "", "java", "unit-testing", "tdd", "junit", "" ]
Netbeans tells me it's bad to access a static method from a non static method. Why is this bad? "Accessing static method getInstance" is the warning: ``` import java.util.Calendar; public class Clock { // Instance fields private Calendar time; /** * Constructor. Starts the clock at the current operating system time */ public Clock() { System.out.println(getSystemTime()); } private String getSystemTime() { return this.time.getInstance().get(Calendar.HOUR)+":"+ this.time.getInstance().get(Calendar.MINUTE); } ``` }
You're probably accessing the static method from an instance instead of directly. Try using `Calendar.getInstance()` instead: ``` private String getSystemTime() { return Calendar.getInstance().get(Calendar.HOUR)+":"+ Calendar.getInstance().get(Calendar.MINUTE); } ```
What do you mean by "return a static method"? It's fine to call a static method from an instance method in my view - depending on the circumstances, of course. Could you post some code which Netbeans complains about? One thing I *could* imagine is if you only use static methods from an instance method, without using any of the data of the instance. Sometimes that's what's required to implement an interface or override a method from a base class, but if you're not overriding anything and you're not using any instance variables, it's nice to make the method static to show that it really doesn't depend on a particular instance. EDIT: With the edited question, this makes a lot of sense. IMO it's a deficiency in Java that allows it in the first place. It can make for very misleading code. My favourite example (which means old-timers may well have seen me post it before :) is with `Thread.sleep`. What does it *look* like this code does? ``` Thread t = new Thread(someRunnable); t.start(); t.sleep(1000); ``` To my mind, it looks like the new thread is asked to sleep - similar to a call to `suspend`. But no - you can only ask the currently executing thread to sleep, which is why `Thread.sleep` is a static method. The above code is legal Java, and will make the currently executing thread sleep for a second while the newly created thread (probably) runs... not at all what the code looks like at first glance.
Why is accessing a static method from a non-static method bad?
[ "", "java", "oop", "static", "methods", "" ]
Using the standard MVC set up in Zend Framework, I want to be able to display pages that have anchors throughout. Right now I'm just adding a meaningless parameter with the '#anchor' that I want inside the .phtml file. ``` <?= $this->url(array( 'controller'=>'my.controller', 'action'=>'my.action', 'anchor'=>'#myanchor' )); ``` This sets the URL to look like /my.controller/my.action/anchor/#myanchor Is there a better way to accomplish this? After navigation to the anchor link, the extra item parameter gets set in the user's URL which is something I would rather not happen.
one of possibilities is to override url helper, or to create a new one. ``` class My_View_Helper_Url extends Zend_View_Helper_Url { public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true) { if (isset($urlOptions['anchor']) && !empty($urlOptions['anchor'])) { $anchor = $urlOptions['anchor']; unset($urlOptions['anchor']); } else { $anchor = ''; } return parent::url($urlOptions, $name, $reset, $encode).$anchor; } } ``` this helper override url helper, problem is, that you can't use parameter called 'anchor', because it will be changed into anchor in url. you will call it as in your's example ``` <?= $this->url(array( 'controller'=>'my.controller', 'action'=>'my.action', 'anchor'=>'#myanchor' )); ``` I hope it helps
There are multiple ways you could go about implementing a [fragment id](http://www.w3.org/TR/REC-html40/intro/intro.html#fragment-uri) into your URLs. Below are some options, along with some pros and cons for each. ## Direct Add You could simply add the `"#$fragment_id"` after your `url()` call. Inelegant, but simple. If you don't use page anchors much (i.e. One or two pages only), this is the way to go. ## Write a custom `url()` helper You could write a custom version of `url()` appending an optional 5th argument for the fragment id: ``` class My_View_Helper_Url extends Zend_View_Helper_Url { public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true, $fragment_id = null) { $uri = parent::url($urlOptions, $name, $reset, $encode); if(!is_null($fragment_id)) { $uri .= "#$fragment_id"; } return $uri; } } ``` This way, anchor (and anchor/fragment id) information is kept strictly withing the realm of the View. This is good for general use, but can get a little unwieldy for the default route. Also, this is still a little too hard-coded for some uses. ## Write a custom `Route` class (Extreme) As a third option, you could write a custom version of the `Zend_Controller_Router_Route` class(es), specifically the `assemble($data, $reset, $encode)` method (the `match($path)` method ignores fragment ids by default). Using this method can be quite tricky, but very useful, especially if use is only limited to specific routes (this method can be used to base the fragment id off of any variable). ## Caveat Certain considerations *must* be taken into account when using fragment ids. For example, query strings have to precede the fragment id in the uri, otherwise, the query string ignored by PHP. However, most ZF applications tend to avoid use of query strings, so it may not be an issue.
How Can I Write Zend Framework URLs That Have Anchor Tags In The Body?
[ "", "php", "zend-framework", "zend-framework-mvc", "" ]
I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using [a library that provides connection pooling](http://www.sqlalchemy.org/) (SQLAlchemy) won't actually help you that much if you enable the connection pool. Does anyone have any experience with this? I'm leery of enabling it because of the possibility that if some code does something stateful to a db connection and (perhaps mistakenly) doesn't clean up after itself, that state which would normally get cleaned up upon closing the connection will instead get propagated to subsequent code that gets a recycled connection.
There's no need to worry about residual state on a connection when using SQLA's connection pool, unless your application is changing connectionwide options like transaction isolation levels (which generally is not the case). SQLA's connection pool issues a connection.rollback() on the connection when its checked back in, so that any transactional state or locks are cleared. It is possible that MySQL's connection time is pretty fast, especially if you're connecting over unix sockets on the same machine. If you do use a connection pool, you also want to ensure that connections are recycled after some period of time as MySQL's client library will shut down connections that are idle for more than 8 hours automatically (in SQLAlchemy this is the pool\_recycle option). You can quickly do some benching of connection pool vs. non with a SQLA application by changing the pool implementation from the default of QueuePool to NullPool, which is a pool implementation that doesn't actually pool anything - it connects and disconnects for real when the proxied connection is acquired and later closed.
Even if the connection part of MySQL itself is pretty slick, presumably there's still a network connection involved (whether that's loopback or physical). If you're making a *lot* of requests, that could get significantly expensive. It will depend (as is so often the case) on exactly what your application does, of course - if you're doing a lot of work per connection, then that will dominate and you won't gain a lot. When in doubt, benchmark - but I would by-and-large trust that a connection pooling library (at least, a reputable one) should work properly and reset things appropriately.
Mysql connection pooling question: is it worth it?
[ "", "python", "mysql", "sqlalchemy", "connection-pooling", "" ]
This question is for the java language in particular. I understand that there is a static protion of memory set aside for all static code. My question is how is this static memory filled? Is a static object put into static memory at import, or at first reference? Also, do the same garbage collection rules apply to static objects as they do for all other objects? ``` public class Example{ public static SomeObject someO = new SomeObject(); } /********************************/ // Is the static object put into static memory at this point? import somepackage.Example; public class MainApp{ public static void main( Sting args[] ){ // Or is the static object put into memory at first reference? Example.someO.someMethod(); // Do the same garbage collection rules apply to a // static object as they do all others? Example.someO = null; System.gc(); } } ```
Imports don't correlate with any instructions in compiled code. They establish aliases for use at compile time only. There are some reflective methods that allow the class to be loaded but not yet initialized, but in most cases, you can assume that whenever a class is referenced, it has been initialized. Static member initializers and static blocks are executed as if they were all one static initializer block in source code order. An object referenced through a static member variable is strongly referenced until the class is unloaded. A normal `ClassLoader` never unloads a class, but those used by application servers do under the right conditions. However, it's a tricky area and has been the source of many hard-to-diagnose memory leaks—yet another reason not to use global variables. --- As a (tangential) bonus, here's a tricky question to consider: ``` public class Foo { private static Foo instance = new Foo(); private static final int DELTA = 6; private static int BASE = 7; private int x; private Foo() { x = BASE + DELTA; } public static void main(String... argv) { System.out.println(Foo.instance.x); } } ``` What will this code print? Try it, and you'll see that it prints "6". There are a few things at work here, and one is the order of static initialization. The code is executed as if it were written like this: ``` public class Foo { private static Foo instance; private static final int DELTA = 6; private static int BASE; static { instance = null; BASE = 0; instance = new Foo(); /* BASE is 0 when instance.x is computed. */ BASE = 7; } private int x; private Foo() { x = BASE + 6; /* "6" is inlined, because it's a constant. */ } } ```
There is normally no such thing as "static" memory. Most vm's have the permanent generation of the heap (where classes get loaded), which is normally not garbage collected. Static objects are allocated just like any other object. But, if they live for long they will be moved between the different generations in the garbage collector. But they will not end up in permgenspace. If your class is holding onto this object permanently, it will only be released when the vm exits.
Whats up with static memory in java?
[ "", "java", "memory-management", "static", "" ]
Does anyone know anywhere there's a wide collection of Python source code on the net with decent documentation? If so, can someone post it up here?
Perhaps the [Python Standard Library](http://docs.python.org/library/)? Or are you looking for something more specific?
I am not sure what you meant by "source code"? Source code of Python libraries or code examples and recipes? Well the link to Python STL is great (@zenazn). In addition to that if you are looking for specific issues and their solutions and recipes, I will suggest: 1. <http://code.activestate.com/recipes/langs/python/> 2. Stack overflow itself. Though you won't find much documentation at these sources, but that is supplemented by great answers, comments and discussions.
Python source code collection
[ "", "python", "" ]
I am designing a helper method that does lazy loading of certain objects for me, calling it looks like this: ``` public override EDC2_ORM.Customer Customer { get { return LazyLoader.Get<EDC2_ORM.Customer>( CustomerId, _customerDao, ()=>base.Customer, (x)=>Customer = x); } set { base.Customer = value; } } ``` when I compile this code I get the following warning: > Warning 5 Access to member > 'EDC2\_ORM.Billing.Contract.Site' > through a 'base' keyword from an > anonymous method, lambda expression, > query expression, or iterator results > in unverifiable code. Consider moving > the access into a helper method on the > containing type. What exactly is the complaint here and why is what I'm doing bad?
"base.Foo" for a virtual method will make a non-virtual call on the parent definition of the method "Foo". Starting with CLR 2.0, the CLR decided that a non-virtual call on a virtual method can be a potential security hole and restricted the scenarios in which in can be used. They limited it to making non-virtual calls to virtual methods within the same class hierarchy. Lambda expressions put a kink in the process. Lambda expressions often generate a closure under the hood which is a completely separate class. So the code "base.Foo" will eventually become an expression in an entirely new class. This creates a verification exception with the CLR. Hence C# issues a warning. Side Note: The equivalent code will work in VB. In VB for non-virtual calls to a virtual method, a method stub will be generated in the original class. The non-virtual call will be performed in this method. The "base.Foo" will be redirected into "StubBaseFoo" (generated name is different).
I suspect the problem is that you're basically saying, "I don't want to use the most derived implementation of Customer - I want to use *this* particular one" - which you wouldn't be able to do normally. You're allowed to do it within a derived class, and for good reasons, but from other types you'd be violating encapsulation. Now, when you use an anonymous method, lambda expression, query expression (which basically uses lambda expressions) or iterator block, sometimes the compiler has to create a new class for you behind the scenes. Sometimes it can get away with creating a new method in the same type for lambda expressions, but it depends on the context. Basically if any local variables are captured in the lambda expression, that needs a new class (or indeed multiple classes, depending on scope - it can get nasty). If the lambda expression only captures the `this` reference, a new instance method can be created for the lambda expression logic. If nothing is captured, a static method is fine. So, although the C# compiler knows that really you're not violating encapsulation, the CLR doesn't - so it treats the code with some suspicion. If you're running under full trust, that's probably not an issue, but under other trust levels (I don't know the details offhand) your code won't be allowed to run. Does that help?
What is 'unverifiable code' and why is it bad?
[ "", "c#", "" ]
Coming from a C++ background, I've run into a snag with overloading based on a specific instance of a generic type. The following doesn't work since only once instance of the code for the `Foo<T>` class is ever generated, so inside the `Method`, the type of `this` is simply `Foo<T>`, not `Foo<A>` or `Foo<B>` as I'd hoped. In C++ I'm used to templates being instantiated as unique types. ``` using System.Collections.Generic; class A { // Concrete class } class B { // Concrete class } class Bar { public void OverloadedMethod(Foo<A> a) {} // do some A related stuff public void OverloadedMethod(Foo<B> b) {} // do some B related stuff public void OverloadedMethod(OtherFoo of) {} // do some other stuff public void VisitFoo(FooBase fb) { fb.Method(this); } } abstract class FooBase { public abstract void Method(Bar b); } class Foo<T> : FooBase { // Class that deals with As and Bs in an identical fashion. public override void Method(Bar b) { // Doesn't compile here b.OverloadedMethod(this); } } class OtherFoo : FooBase { public override void Method(Bar b) { b.OverloadedMethod(this); } } class Program { static void Main(string[] args) { List<FooBase> ListOfFoos = new List<FooBase>(); ListOfFoos.Add(new OtherFoo()); ListOfFoos.Add(new Foo<A>()); ListOfFoos.Add(new Foo<B>()); Bar b = new Bar(); foreach (FooBase fb in ListOfFoos) b.VisitFoo(fb); // Hopefully call each of the Bar::Overloaded methods } } ``` Is there a way to get something like this to work in C#? I'd rather not have to duplicate the code in Foo as separate classes for every type I want to use it for. Edit: Hopefully this is a little clearer.
This works for the static case. Dealing with instance functions would be a bit more complicated. This [post from Jon Skeet](http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx) might provide a reasonable way to deal with instance methods. ``` class Program { static void Main(string[] args) { var testA = new Foo<A>(); testA.Method(); var testB = new Foo<B>(); testB.Method(); Console.ReadLine(); var testString = new Foo<string>(); //Fails testString.Method(); Console.ReadLine(); } } class A { } class B { } class Bar { public static void OverloadedMethod(Foo<A> a) { Console.WriteLine("A"); } public static void OverloadedMethod(Foo<B> b) { Console.WriteLine("B"); } } class Foo<T> { static Foo() { overloaded = (Action<Foo<T>>)Delegate.CreateDelegate(typeof(Action<Foo<T>>), typeof(Bar).GetMethod("OverloadedMethod", new Type[] { typeof(Foo<T>) })); } public void Method() { overloaded(this); } private static readonly Action<Foo<T>> overloaded; } ```
I now have a genuinely complete piece of code which demonstrates the problem. Note to OP: please try compiling your code before posting it. There were a bunch of things I had to do to get this far. It's good to make it as easy as possible for other people to help you. I've also removed a bunch of extraneous bits. OtherFoo isn't really relevant here, nor is FooBase. ``` class A {} class B {} class Bar { public static void OverloadedMethod(Foo<A> a) { } public static void OverloadedMethod(Foo<B> b) { } } class Foo<T> { // Class that deals with As and Bs in an identical fashion. public void Method() { // Doesn't compile here Bar.OverloadedMethod(this); } } ``` Yes, this doesn't compile. What did you expect it to do, exactly? Bear in mind that the overload resolution is performed at *compile time*, not execution time. As fallen888 says, you could cast and call the appropriate overloaded method - but which of the two overloads would you expect the compiler to pick otherwise? What do you want it to do with `Foo<string>` instead of `Foo<A>` or `Foo<B>`? This all goes to demonstrate that .NET generics are indeed significantly different from C++ templates, of course...
How can I overload a C# method by specific instances of a generic type
[ "", "c#", "generics", "overloading", "" ]
I want to fill a map with class name and method, a unique identifier and a pointer to the method. ``` typedef std::map<std::string, std::string, std::string, int> actions_type; typedef actions_type::iterator actions_iterator; actions_type actions; actions.insert(make_pair(class_name, attribute_name, identifier, method_pointer)); //after which I want call the appropriate method in the loop while (the_app_is_running) { std::string requested_class = get_requested_class(); std::string requested_method = get_requested_method(); //determine class for(actions_iterator ita = actions.begin(); ita != actions.end(); ++ita) { if (ita->first == requested_class && ita->second == requested_method) { //class and method match //create a new class instance //call method } } } ``` If the method is static then a simple pointer is enough and the problem is simple, but I want to dynamically create the object so I need to store a pointer to class and an offset for the method and I don't know if this works (if the offset is always the same etc). The problem is that C++ lacks reflection, the equivalent code in a interpreted language with reflection should look like this (example in PHP): ``` $actions = array ( "first_identifier" => array("Class1","method1"), "second_identifier" => array("Class2","method2"), "third_identifier" => array("Class3","method3") ); while ($the_app_is_running) { $id = get_identifier(); foreach($actions as $identifier => $action) { if ($id == $identifier) { $className = $action[0]; $methodName = $action[1]; $object = new $className() ; $method = new ReflectionMethod($className , $methodName); $method -> invoke($object); } } } ``` PS: Yes I'm trying to make a (web) MVC front controller in C++. I know I know why don't use PHP, Ruby, Python (insert your favorite web language here) etc?, I just want C++.
I wrote that stuff last hours, and added it to my collection of useful stuff. The most difficult thing is to cope with the factory function, if the types you want to create are not related in any way. I used a `boost::variant` for this. You have to give it a set of types you ever want to use. Then it will keep track what is the current "active" type in the variant. (boost::variant is a so-called discriminated union). The second problem is how you store your function pointers. The problem is that a pointer to a member of `A` can't be stored to a pointer to a member of `B`. Those types are incompatible. To solve this, i store the function pointers in an object that overloads its `operator()` and takes a boost::variant: ``` return_type operator()(variant<possible types...>) ``` Of course, all your types' functions have to have the same return type. Otherwise the whole game would only make little sense. Now the code: ``` #include <boost/variant.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/tuple/tuple.hpp> #include <boost/mpl/identity.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_arity.hpp> #include <boost/preprocessor/repetition.hpp> #include <map> #include <string> #include <iostream> // three totally unrelated classes // struct foo { std::string one() { return "I "; } }; struct bar { std::string two() { return "am "; } }; struct baz { std::string three() const { return "happy!"; } }; // The following are the parameters you have to set // // return type typedef std::string return_type; // variant storing an object. It contains the list of possible types you // can store. typedef boost::variant< foo, bar, baz > variant_type; // type used to call a function on the object currently active in // the given variant typedef boost::function<return_type (variant_type&)> variant_call_type; // returned variant will know what type is stored. C++ got no reflection, // so we have to have a function that returns the correct type based on // compile time knowledge (here it's the template parameter) template<typename Class> variant_type factory() { return Class(); } namespace detail { namespace fn = boost::function_types; namespace mpl = boost::mpl; // transforms T to a boost::bind template<typename T> struct build_caller { // type of this pointer, pointer removed, possibly cv qualified. typedef typename mpl::at_c< fn::parameter_types< T, mpl::identity<mpl::_> >, 0>::type actual_type; // type of boost::get we use typedef actual_type& (*get_type)(variant_type&); // prints _2 if n is 0 #define PLACEHOLDER_print(z, n, unused) BOOST_PP_CAT(_, BOOST_PP_ADD(n, 2)) #define GET_print(z, n, unused) \ template<typename U> \ static variant_call_type get( \ typename boost::enable_if_c<fn::function_arity<U>::value == \ BOOST_PP_INC(n), U>::type t \ ) { \ /* (boost::get<actual_type>(some_variant).*t)(n1,...,nN) */ \ return boost::bind( \ t, boost::bind( \ (get_type)&boost::get<actual_type>, \ _1) BOOST_PP_ENUM_TRAILING(n, PLACEHOLDER_print, ~) \ ); \ } // generate functions for up to 8 parameters BOOST_PP_REPEAT(9, GET_print, ~) #undef GET_print #undef PLACEHOLDER_print }; } // incoming type T is a member function type. we return a boost::bind object that // will call boost::get on the variant passed and calls the member function template<typename T> variant_call_type make_caller(T t) { return detail::build_caller<T>::template get<T>(t); } // actions stuff. maps an id to a class and method. typedef std::map<std::string, std::pair< std::string, std::string > > actions_type; // this map maps (class, method) => (factory, function pointer) typedef variant_type (*factory_function)(); typedef std::map< std::pair<std::string, std::string>, std::pair<factory_function, variant_call_type> > class_method_map_type; // this will be our test function. it's supplied with the actions map, // and the factory map std::string test(std::string const& id, actions_type& actions, class_method_map_type& factory) { // pair containing the class and method name to call std::pair<std::string, std::string> const& class_method = actions[id]; // real code should take the maps by const parameter and use // the find function of std::map to lookup the values, and store // results of factory lookups. we try to be as short as possible. variant_type v(factory[class_method].first()); // execute the function associated, giving it the object created return factory[class_method].second(v); } int main() { // possible actions actions_type actions; actions["first"] = std::make_pair("foo", "one"); actions["second"] = std::make_pair("bar", "two"); actions["third"] = std::make_pair("baz", "three"); // connect the strings to the actual entities. This is the actual // heart of everything. class_method_map_type factory_map; factory_map[actions["first"]] = std::make_pair(&factory<foo>, make_caller(&foo::one)); factory_map[actions["second"]] = std::make_pair(&factory<bar>, make_caller(&bar::two)); factory_map[actions["third"]] = std::make_pair(&factory<baz>, make_caller(&baz::three)); // outputs "I am happy!" std::cout << test("first", actions, factory_map) << test("second", actions, factory_map) << test("third", actions, factory_map) << std::endl; } ``` It uses pretty fun techniques from boost preprocessor, function types and bind library. Might loop complicated, but if you get the keys in that code, it's not much to grasp anymore. If you want to change the parameter count, you just have to tweak variant\_call\_type: ``` typedef boost::function<return_type (variant_type&, int)> variant_call_type; ``` Now you can call member functions that take an int. Here is how the call side would look: ``` return factory[class_method].second(v, 42); ``` Have fun! --- If you now say the above is too complicated, i have to agree with you. It *is* complicated because C++ is *not* really made for such dynamic use. If you can have your methods grouped and implemented in each object you want create, you can use pure virtual functions. Alternatively, you could throw some exception (like std::runtime\_error) in the default implementation, so derived classes do not need to implement everything: ``` struct my_object { typedef std::string return_type; virtual ~my_object() { } virtual std::string one() { not_implemented(); } virtual std::string two() { not_implemented(); } private: void not_implemented() { throw std::runtime_error("not implemented"); } }; ``` For creating objects, a usual factory will do ``` struct object_factory { boost::shared_ptr<my_object> create_instance(std::string const& name) { // ... } }; ``` The map could be composed by a map mapping IDs to a pair of class and function name (the same like above), and a map mapping that to a boost::function: ``` typedef boost::function<my_object::return_type(my_object&)> function_type; typedef std::map< std::pair<std::string, std::string>, function_type> class_method_map_type; class_method_map[actions["first"]] = &my_object::one; class_method_map[actions["second"]] = &my_object::two; ``` Calling the function would work like this: ``` boost::shared_ptr<my_object> p(get_factory(). create_instance(actions["first"].first)); std::cout << class_method_map[actions["first"]](*p); ``` Of course, with this approach, you loose flexibility and (possibly, haven't profiled) efficiency, but you greatly simplify your design.
Perhaps you're looking for [member function pointers](http://www.parashift.com/c++-faq-lite/pointers-to-members.html). Basic usage: ``` class MyClass { public: void function(); }; void (MyClass:*function_ptr)() = MyClass::function; MyClass instance; instance.*function_ptr; ``` As stated in the C++ FAQ Lite, macros and `typedef`s would greatly increase readability when using member function pointers (because their syntax isn't common in code).
What is the simplest way to create and call dynamically a class method in C++?
[ "", "c++", "model-view-controller", "object", "" ]
I want to move the form title, icon and close, and help buttons from left side to right side (change the layout). I moved the form controls manually to keep background image but now I want to change the form title. When I set rightToLeft property to yes and rightToLeftLayout to true in the form properties the background image disappears, but it uses the property "BackColor" My code is as follows: ``` if (_lang == 'Arabic') { this.RightToLeft = RightToLeft.Yes; this.RightToLeftLayout = true; } ``` But it keeps buttons image. So why is that?
To further Blounty's answer, the MSDN specs clearly state that BackgroundImage, Opacity and others aren't supported when using RightToLeftLayout: [<http://msdn.microsoft.com/en-us/library/system.windows.forms.form.righttoleftlayout(vs.80).aspx>](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.righttoleftlayout(vs.80).aspx): > Owner draw is not supported when RightToLeftLayout is set to Yes. The owner draw events will still occur, but the behavior of any code you author in these events is not defined. Additionally, BackgroundImage, Opacity, TransparencyKey, and the painting events are not supported.
BackgroundImage, Opacity, TransparencyKey, and the painting events are not supported when RightToLeftLayout is set to yes.
RightToLeft property in Form in C#
[ "", "c#", "winforms", "internationalization", "" ]
Simple question: do I have to `delete` or `delete []` `c`? Does the language matter? ``` char c[] = "hello" ```
In c++ that is not dynamic memory allocation. No `delete[]` will be needed. Your example is basically a short-cut for this: ``` char c[6]={'h','e','l','l','o','\0'}; ```
The rule in C++ is that you use `delete[]` whenever you use `new[]`, and `delete` whenever you use `new`. If you don't use `new`, as in your example, you do not need to `delete` anything. In your example, the six bytes for the `c` array are allocated on the stack, instead of on the heap, if declared within a function. Since those bytes are on the stack, they vanish as soon as the function where they are declared returns. If that declaration is outside any function, then those six bytes are allocated in the global data area and stay around for the whole lifetime of your program.
Is this dynamic memory allocation?
[ "", "c++", "c", "memory", "memory-management", "new-operator", "" ]
How can we write an update sql statement that would update records and the 'set' value changes every time? For example: If we have records like this ``` SomeNumber SomeV CurCode WhatCodeShouldBe 200802754 432 B08 B09 200802754 432 B08 B09 200802754 432 B08 B09 200808388 714 64B C00 200804119 270 64B C00 ``` I wish to update each 'SomeNumber' record so that 'CurCode' will be same as 'WhatCodeShouldBe' Thanks for any help!
``` update a set 3rdColumn = b.2ndColumn from tableA a inner join tableB b on a.linkToB = b.linkToA ``` That is based on [your new comments](https://stackoverflow.com/questions/317822/update-with-changing-set-value#317942)
i have got that data by forming some temptables and gathering information from different tables. :( updating this temp table wont be a help...I need to be able to carry the changes over to the original table. I'll try to give better example... Table A: 200802754 432 B08 200802754 432 B08 200802754 432 B08 200808388 714 64B 200804119 270 64B Table B 432 B09 432 B09 432 B09 714 C00 So I want to be making 3rd column of table A same as second column of table B...joining the tables on column 2. 200804119 270 64B C00
Update with changing set value
[ "", "sql", "sql-update", "" ]
Is there some equivalent of "friend" or "internal" in php? If not, is there any pattern to follow to achieve this behavior? **Edit:** Sorry, but standard Php isn't what I'm looking for. I'm looking for something along the lines of what ringmaster did. I have classes which are doing C-style system calls on the back end and the juggling has started to become cumbersome. I have functions in object A which take in object B as a parameter and have to call a method in object B passing in itself as an argument. The end user could call the method in B and the system would fall apart.
PHP doesn't support any friend-like declarations. It's possible to simulate this using the PHP5 \_\_get and \_\_set methods and inspecting a backtrace for only the allowed friend classes, although the code to do it is kind of clumsy. There's some [sample code](http://bugs.php.net/bug.php?id=34044) and discussion on the topic on PHP's site: ``` class HasFriends { private $__friends = array('MyFriend', 'OtherFriend'); public function __get($key) { $trace = debug_backtrace(); if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) { return $this->$key; } // normal __get() code here trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR); } public function __set($key, $value) { $trace = debug_backtrace(); if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) { return $this->$key = $value; } // normal __set() code here trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR); } } ``` (Code proved by tsteiner at nerdclub dot net [on bugs.php.net](https://bugs.php.net/bug.php?id=34044))
It is also possible to elevate privileges, aka leaking data selectively, using a handshake and closures in php >=5.3.3. Basically, the interaction goes: class A has a public method which accepts a class B object, and calls B->grantAccess (or whatever your interface defines), passing it a closure. The closure `use($that,$anythingelseyouneed)` where $that=$this, and anything else you need to determine what properties are allowed to be accessed. The closure has one argument - the property to return; if it is a property on $that and everything is cool, the closure returns the property. Otherwise, it returns '', or throws an exception, or maybe a default value. Class B->grantAccess accepts a callable and stores it, using it in other methods to pluck out private properties the closure allows to be leaked. Make class B's default constructor private. Construct a B using a static factory method that takes a Class A argument, to ensure the handshake happens. Gist here: <https://gist.github.com/mcamiano/00592fb400e5043d8acd>
PHP equivalent of friend or internal
[ "", "php", "oop", "friend", "" ]
Title might be a bit confusing, so let me explain. I have a website that has a side-panel, which contains information about the user, things the user can do, etc. When the user is not logged in, this side-panel becomes the area for logging in or registration. The code for this is: ``` <?php if($user->loggedIn) { ?> <!-- side-panel for logged in users here --> <?php } else { ?> <!-- login/registration etc --> <?php } ?> ``` What I want to do is load this snippet of code again when the user clicks login with AJAX, and use a jQuery effect (probably fade) that smoothly makes the side-panel transition from login/registration to the shiny users-only panel. I know I could do this if I put that code in another file, and loaded it through AJAX into the div for the side-panel... but I would rather not make a separate file for the side-panel only. Is this possible?
You could load the page with an AJAX request and then strip out the data other than the side panel, but what would be the point? Your best option would be to simply separate the side panel into its own file. Oh, and that would also be considered the proper way of doing it, so you can edit the sidebar without editing the pages it occurs on.
If i understand corectly what you neey, you may try this way: ``` $.ajax({ type: "GET", url: "url", // replace 'url' with your url cache: false, success: function(data){ alert($(data).find('#sidebar').html()); } }); ``` Maybe will work with $.load() or $.get(), dunno.
AJAX - Reload a part of a webpage without the use of a separate file to load
[ "", "javascript", "jquery", "ajax", "xmlhttprequest", "httprequest", "" ]
I have a problem that seems like its a result of a deadlock-situation. Whe are now searching for the root of the problem but meantime we wanted to restart the server and get the customer going. And now everytime we start the program it just says "SqlConnection does not support parallel transactions". We have not changed anything in the program, its compiled and on the customers server, but after the "possible deadlock"-situation it want go online again. We have 7 clients (computers) running the program, each client is talking to a webservice on a local server, and the webservice is talking to the sql-server (same machine as webserver). We have restarted both the sql-server and the iis-server, but not rebooted the server because of other important services running on the server so its the last thing we do. We can se no locks or anything in the management tab. So my question is, why does the "SqlConnection does not support parallel transactions" error comming from one time to another without changing anything in the program and it still lives between sql-restart. It seems like it happens at the first db-request the program does when it start. If you need more information just ask. Im puzzled... **More information:** I dont think I have "long" running transactions. The scenario is often that I have a dataset with 20-100 rows (ContractRows) in that Ill do a .Update on the tableAdapter. I also loop throug those 20-100 rows and for some of them Ill create ad-hook-sql-querys (for example if a rented product is marked as returned I create a sql-query to mark the product as returned in the database) So I do this very simplified: ``` Create objTransactionObject Create objtableadapter (objTransactionObject) for each row in contractDS.contractrows if row.isreturned then strSQL &= "update product set instock=1 where prodid=" & row.productid & vbcrlf End if next objtableadapter.update(contractDS) objData.ExecuteQuery(strSQL, objTransactionObject) if succsesfull objtransactionobject.commit else objtransactionobject.rollback end if objTran.Dispose() ``` And then Im doing commit or rollback depending on if It went well or not. Edit: None of the answers have solved the problem, but I'll thank you for the good trouble shooting pointers. The "SqlConnection does not support parallel transactions" dissapeared suddenly and now the sql-server just "goes down" 4-5 times a day, I guess its a deadlock that does that but I have not the right knowledge to find out and are short on sql-experts who can monitor this for me at the moment. I just restart the sql-server and everything works again. 1 of 10 times I also have to restart the computer. Its really bugging me (and my customers of course). Anyone knowing a person with **good** knowledge in analyzing troubles with deadlocks or other sql problems in sweden (or everywhere in the world,english speaking) are free to contact me. I know this is'nt a contact site but I take my chanse to ask the question because I have run out of options, I have spent 3 days and nights optimizing the clients to be sure we close connections and dont do too much stupid things there. Without luck.
It seems to be that you are sharing connections and creating new transactions on the same open connection (this is the parallel part of the exception you are seeing). Your example seems to support this as you have no mention of how you acquire the connection in it. You should do a review of your code and make sure that you are only opening a connection and then disposing of it when you are done (and by all means, use the using statement to make sure that you close the connection), as it seems like you are leaving one open somewhere.
Yours doesn't appear to be an unusual problem. Google found a lot of hits when I pasted your error string into the query box. Reading past answers, it sounds like it has something to do with interleaving transactions improperly or isolation level. How long are connections held open? Do you have long-running transactions?
Strange SQL2005 problem. "SqlConnection does not support parallel transactions"
[ "", "sql", "transactions", "" ]
I'm working on an assignment that is telling me to assume that I have a singly linked list with a header and tail nodes. It wants me to insert an item y before position p. Can anybody please look over my code and tell me if I'm on the right track? If not, can you provide me with any tips or pointers (no pun intended)? ``` tmp = new Node(); tmp.element = p.element; tmp.next = p.next; p.element = y; p.next = tmp; ``` I think I may be wrong because I do not utilize the header and tail nodes at all even though they are specifically mentioned in the description of the problem. I was thinking of writing a while loop to traverse the list until it found p and tackle the problem that way but that wouldn't be constant-time, would it?
Just write it down if you get stuck with an algorithm: ``` // First we have a pointer to a node containing element (elm) // with possible a next element. // Graphically drawn as: // p -> [elm] -> ??? tmp = new Node(); // A new node is created. Variable tmp points to the new node which // currently has no value. // p -> [elm] -> ??? // tmp -> [?] tmp.element = p.element; // The new node now has the same element as the original. // p -> [elm] -> ??? // tmp -> [elm] tmp.next = p.next; // The new node now has the same next node as the original. // p -> [elm] -> ??? // tmp -> [elm] -> ??? p.element = y; // The original node now contains the element y. // p -> [y] -> ??? // tmp -> [elm] -> ??? p.next = tmp; // The new node is now the next node from the following. // p -> [y] -> [elm] -> ??? // tmp -> [elm] -> ??? ``` You have the required effect, but it can be more efficient and I bet you can now find out yourself. It is more clear to write something like: ``` tmp = new Node(); tmp.element = y; tmp.next = p; p = tmp; ``` Which of course does not work if p is not mutable. But your algorithm fails if p == NULL. But what I meant to say, is, if you have problems with an algorithm, just write the effects out. Especially with trees and linked lists, you need to be sure all pointers are pointing to the righ direction, else you get a big mess.
**Hint**: insertion into a linked list is only constant when position *n* = 0, or the head of the list. Otherwise, the worst-case complexity is *O(n)*. That's not to say that you cannot create a reasonably efficient algorithm, but it will always have *at least* linear complexity.
Inserting a node into a linked list in constant-time?
[ "", "java", "linked-list", "" ]
The callstack shows the following: ``` [MissingMethodException: No parameterless constructor defined for this object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230 System.Activator.CreateInstance(Type type, Boolean nonPublic) +67 System.Activator.CreateInstance(Type type) +6 System.Web.Mvc.DefaultModelBinder.CreateModel(ModelBindingContext bindingContext, Type modelType) +277 System.Web.Mvc.<>c__DisplayClass1.<BindModel>b__0() +98 System.Web.Mvc.ModelBindingContext.get_Model() +51 System.Web.Mvc.DefaultModelBinder.BindModelCore(ModelBindingContext bindingContext) +2600 System.Web.Mvc.DefaultModelBinder.BindModel(ModelBindingContext bindingContext) +1067 System.Web.Mvc.DefaultModelBinder.BindProperty(ModelBindingContext parentContext, Type propertyType, Func`1 propertyValueProvider, String propertyName) +208 System.Web.Mvc.DefaultModelBinder.BindModelCore(ModelBindingContext bindingContext) +1787 System.Web.Mvc.DefaultModelBinder.BindModel(ModelBindingContext bindingContext) +1067 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ParameterInfo parameterInfo) +355 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(MethodInfo methodInfo) +439 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +288 System.Web.Mvc.Controller.ExecuteCore() +180 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +96 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +36 System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +377 System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +71 System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +36 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75 ``` I have a tiny form with a bunch of hidden fields and one submit button. When I press it, I never even hit the requested method. How do I go on and debug this? It would be a great start if I knew WHAT object didn't have a parameterless constructor. Where is this object? How can I solve this? I know the question is rather vague, but currently it's all I've got.. **--EDIT--** In my form I added Html.Hidden() inputs. Depending on previous actions, these can have a value of "". The action makes use of ModelBinding. Whenever the value is "" and the datatype is a SelectList, the modelbinder goes berzerk on me. I feel more and more uncomfortable with how the SelectList is doing it's thing... The idea is good, but there are some issues with it.
I solved the issue which is caused of SelectList object because it does not provide the default constructor so we cant have in out ViewModel.
For those Googling this exception, here is a more general way to diagnose it: The only easy way I've found to diagnose this problem is to override MVC as close to the exception as possible with your own code. Then your code will break inside Visual Studio when this exception occurs, and you can read the Type causing the problem from the stack trace. This seems like a horrible way to approach this problem, but it's very fast, and very consistent. For example, if this error is occurring inside the MVC DefaultModelBinder (which you will know by checking the stack trace), then replace the DefaultModelBinder with this code: ``` public class MyDefaultModelBinder : System.Web.Mvc.DefaultModelBinder { protected override object CreateModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext, Type modelType) { return base.CreateModel(controllerContext, bindingContext, modelType); } } ``` And update your Global.asax.cs: ``` public class MvcApplication : System.Web.HttpApplication { ... protected void Application_Start(object sender, EventArgs e) { ModelBinders.Binders.DefaultBinder = new MyDefaultModelBinder(); } } ``` Now the next time you get that exception, Visual Studio will stop inside your MyDefaultModelBinder class, and you can check the "modelType" property to see what type caused the problem. The example above works for when you get the "No parameterless constructor defined for this object" exception during model binding, only. But similar code can be written for other extension points in MVC (e.g. controller construction).
Server Error in '/' Application. No parameterless constructor defined for this object
[ "", "c#", "asp.net-mvc", "" ]
I have this PHP code ``` echo '<a href="#" onclick="updateByQuery(\'Layer3\', ' . json_encode($query) . ');">Link 1</a>'; ``` which generates a link like this: ``` <a href="#" onclick="updateByQuery('Layer3', "Ed Hardy");">Link 1</a><li>Link 2</li> ``` Causing the javascript to not be called. How would I make it generate single quotes around the result of $query, in this case ed hardy?
Try to do the reverse... use single quotes for html, and double quotes for javascript. That's how we do that in fact.
You should [html encode](http://www.php.net/htmlentities) it: ``` echo '<a href="#" onclick="updateByQuery(\'Layer3\', ' . htmlentities(json_encode($query)) . ');">Link 1</a>'; ``` You could also use `htmlspecialchars`
php quoting problem
[ "", "php", "" ]
How can I calculate the width and height of a `<div>` element, so as to be able to center it in the browser's display (viewport)? What browsers support each technique?
You should use the [`.offsetWidth`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth) and [`.offsetHeight`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight) properties. Note they belong to the element, not `.style`. ``` var width = document.getElementById('foo').offsetWidth; ``` The [`.getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) function returns the dimensions and location of the element as floating-point numbers after performing CSS transforms. ``` > console.log(document.getElementById('foo').getBoundingClientRect()) DOMRect { bottom: 177, height: 54.7, left: 278.5,​ right: 909.5, top: 122.3, width: 631, x: 278.5, y: 122.3, } ```
Take a look at [`Element.getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). This method will return an object containing the `width`, `height`, and some other useful values: ``` { width: 960, height: 71, top: 603, bottom: 674, left: 360, right: 1320 } ``` For Example: ``` var element = document.getElementById('foo'); var positionInfo = element.getBoundingClientRect(); var height = positionInfo.height; var width = positionInfo.width; ``` I believe this does not have the issues that `.offsetWidth` and `.offsetHeight` do where they sometimes return `0` (as discussed in the [comments here](https://stackoverflow.com/a/294273/363701)) Another difference is `getBoundingClientRect()` may return fractional pixels, where `.offsetWidth` and `.offsetHeight` will round to the nearest integer. **IE8 Note**: `getBoundingClientRect` does not return height and width on **IE8** and below.\* If you *must* support IE8, use `.offsetWidth` and `.offsetHeight`: ``` var height = element.offsetHeight; var width = element.offsetWidth; ``` Its worth noting that the Object returned by this method is not really a *normal* object. Its properties are not [*enumerable*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) (so, for example, `Object.keys` doesn't work out-of-the-box.) More info on this here: [How best to convert a ClientRect / DomRect into a plain Object](https://stackoverflow.com/questions/39417566/how-best-to-convert-a-clientrect-domrect-into-a-plain-object) Reference: * [HTMLElement: `offsetHeight` property](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight) - MDN Docs * [HTMLElement: `offsetWidth` property](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth) - MDN Docs * [Element: `getBoundingClientRect()` method](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) - MDN Docs
How do I retrieve an HTML element's actual width and height?
[ "", "javascript", "html", "dhtml", "" ]
I have a column in my database (a flag) with type varchar(1) that is populated either Y or NULL (not in my control). In SQL Server, doing an ascending order by query, NULL is ordered at the top. Is this SQL Server behaviour consistent with Oracle and DB2? If, instead, I have a COALESCE on the column to ensure it is not null in the query, what performance issues (due to table scans and the like) could I hit? The query needs to be consistent over all 3 databases, otherwise I will have to handle it in code, hence my thinking of using the COALESCE function. <http://en.wikipedia.org/wiki/Order_by_(SQL)>
I know for a fact that DB2 Express and DB2 (at least up to v8) does **not** support the `NULLS FIRST` clause. If you want a portable solution, you may have to opt for something like: ``` select * from tbl where fld is null union all select * from tbl where fld is not null ``` I think the result of the union (at least in DB2, you'll need to check the others) is guaranteed to be ordered correctly. The coalesce **will** have performance implications since you're running a function for every row returned. However, it depends on the number of rows in the database. You may well have to resort to doing two queries in code into two different record sets, then processing them in order. EDIT: I've just checked the SQL standard and it's not guaranteed that the queries joined with a `UNION ALL` are sequenced; they might be inter-mixed. So it looks like you may have to resort to code running two different queries as mentioned above.
> In SQL Server, doing an ascending order by query, NULL is ordered at the top. Should this behaviour be consistent for Oracle and DB2? [Apparently this is a relative newcomer to the standard](http://en.wikipedia.org/wiki/Order_by_(SQL)). > The SQL standard's core functionality does not explicitly define a default sort order for Nulls. With the SQL:2003 extension T611, "Elementary OLAP operations", nulls can be sorted before or after all data values by using the NULLS FIRST or NULLS LAST clauses of the ORDER BY list, respectively. Not all DBMS vendors implement this functionality, however. Vendors who do not implement this functionality may specify different treatments for Null sorting in the DBMS.
consistent behaviour among DBMSs with SQL Order By and nulls
[ "", "sql", "null", "sql-order-by", "" ]
How would you call the constructor of the following class in these three situations: Global objects, arrays of objects, and objects contained in another class/struct? The class with the constructor (used in all three examples): ``` class Foo { public: Foo(int a) { b = a; } private: int b; }; ``` And here are my attempts at calling this constructor: ## Global objects ``` Foo global_foo(3); // works, but I can't control when the constructor is called. int main() { // ... } ``` ## Arrays of objects ``` int main() { // Array on stack Foo array_of_foos[30](3); // doesn't work // Array on heap Foo *pointer_to_another_array = new Foo(3) [30]; // doesn't work } ``` There I'm attempting to call the constructor for all elements of the arrays, but I'd also like to know how to call it on individual elements. ## Objects contained in classes/structs ``` class Bar { Foo foo(3); // doesn't work }; int main() { Bar bar; } ```
### Global objects Yours is the only way. On the other hand, try to avoid this. It’s better to use functions (or even other objects) as factories instead. That way, you can control the time of creation. ### Arrays of objects There’s no way to do this directly. Non-POD objects will always be default-constructed. `std::fill` is often a great help. You might also want to look into allocators and `std::uninitialized_fill`. ### Objects contained in classes/structs Use initialization lists in your constructor: ``` class Bar { Foo foo; Bar() : foo(3) { } }; ``` Static members must actually be defined outside the class: ``` class Bar { static Foo foo; }; Foo Bar::foo(3); ```
To correct some misconceptions about globals: * The order is well defined within a compilation unit. + It is the same as the order of definition * The order across compilation units is undefined. * The order of destruction is the **EXACT** opposite of creation. Not something I recommend but: So a simple solution is to to put all globals into a single compilation unit. Alternatively you can tweak the use of function static variables. Basically you can have a function the returns a reference to the global you want (defining the global inside the function). It will be created on first use (and destroyed in reverse order of creation). ``` Foo& getGlobalA() // passed parameters can be passed to constructor { static Foo A; return A; } Foo& getGlobalB() { static Foo B; return B; } etc. ```
How do you call a constructor for global objects, for arrays of objects, and for objects inside classes/structs?
[ "", "c++", "oop", "constructor", "" ]
I have two questions: 1) How can I make an array which points to objects of integers? ``` int* myName[5]; // is this correct? ``` 2) If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method? ie) I want to impliment the method: ``` int **getStuff() { // what goes here? return *(myName); // im pretty sure this is not correct } ``` Thanks for the help!
> How can I make an array which points > to objects? ``` int * myName[5]; /* correct */ ``` > If I want to return a pointer to an > array, which points to objects (like > (1)) how can I do this in a method? Technically, you write this function: ``` int * (* getStuff() )[5] { return &myName; } ``` That returns a pointer to that array. However, you don't want to do that. You wanted to return *a pointer to the first element of the array*: ``` int ** getStuff() { return myName; /* or return &myName[0]; */ } ``` That way, you can now access items as you want like `getStuff()[0] = &someInteger;`
Note that your code, ``` int* myName[5]; ``` declares an array containing 5 values, each of which is a "pointer to int", which is what you asked. However this being C++, that's all it does. As a Python scripter, that might cause you some surprises. It does not give any of those 5 pointers sensible values, and it does not create any integers for them to point to. If you put it in a function body, then it creates the array on the stack. This means that the array will cease to exist when the current scope ends (which, to put it simply, means when you get to the enclosing close-curly, so for example return does it). So in particular, the following code is bad: ``` int **myFunction() { int *myArray[5]; return myArray; } // <-- end of scope, and return takes us out of it ``` It might compile, but the function returns a pointer to something that no longer exists by the time the caller sees it. This leads to what we call "undefined behaviour". If you want the array to exist outside the function it's created in, you could create one on the heap each time your function is called, and return a pointer, like this: ``` int **myFunction() { int **myArray = new int[5]; return myArray; } ``` The function returns a different array each time it's called. When the caller has finished with it, it should destroy the array, like this: ``` delete[] myArray; ``` otherwise it will never be freed, and will sit around using up memory forever (or when your program exits on most OSes). Alternatively, you can use the keyword "static" to create an array with "global storage duration" (meaning that it exists as long as the program is running, but there's only one of it rather than a new one each time). That means the function returns the same array each time it's called. The caller could store some pointers in it, forget about it, call the function again, and see the same pointers still there: ``` int **myFunction() { static int *myArray[5]; return myArray; } ``` Note how similar this code is to the very bad code from earlier. Finally, if you just want to create an array of integers, not an array of pointers to integers, you can do this: ``` int myArray[5] = { 1, 2, 3, 4, 5}; ``` That actually creates 5 integers (meaning, it assigns space which can store the integer values themselves. That's different from the array of pointers, which stores the addresses of space used to store integer values). It also stores the specified values in that space: myArray[0] is now 1, myArray[1] is 2, etc.
Pointer Pointer Methods C++
[ "", "c++", "pointers", "methods", "" ]
I'm a C++ newbie, but I wasn't able to find the answer to this (most likely trivial) question online. I am having some trouble compiling some code where two classes include each other. To begin, should my #include statements go inside or outside of my macros? In practice, this hasn't seemed to matter. However, in this particular case, I am having trouble. Putting the #include statements outside of the macros causes the compiler to recurse and gives me "#include nested too deeply" errors. This seems to makes sense to me since neither class has been fully defined before #include has been invoked. However, strangely, when I try to put them inside, I am unable to declare a type of one of the classes, for it is not recognized. Here is, in essence, what I'm trying to compile: A.h ``` #ifndef A_H_ #define A_H_ #include "B.h" class A { private: B b; public: A() : b(*this) {} }; #endif /*A_H_*/ ``` B.h ``` #ifndef B_H_ #define B_H_ #include "A.h" class B { private: A& a; public: B(A& a) : a(a) {} }; #endif /*B_H_*/ ``` main.cpp ``` #include "A.h" int main() { A a; } ``` If it makes a difference, I am using g++ 4.3.2. And just to be clear, in general, where should #include statements go? I have always seen them go outside of the macros, but the scenario I described clearly seems to break this principle. Thanks to any helpers in advance! Please allow me to clarify my intent if I have made any silly mistakes!
By "the macros" I assume you mean the #ifndef include guards? If so, #includes should definitely go inside. This is one of the major reasons why include guards exists, because otherwise you easily end up with an infinite recursion as you noticed. Anyway, the problem is that at the time you use the A and B classes (inside the other class), they have not yet been declared. Look at what the code looks like after the #includes have been processed: ``` //#include "A.h" start #ifndef A_H_ #define A_H_ //#include "B.h" start #ifndef B_H_ #define B_H_ //#include "A.h" start #ifndef A_H_ // A_H_ is already defined, so the contents of the file are skipped at this point #endif /*A_H_*/ //#include "A.h" end class B { private: A& a; public: B(A& a) : a(a) {} }; #endif /*B_H_*/ //#include "B.h" end class A { private: B b; public: A() : b(*this) {} }; #endif /*A_H_*/ //#include "A.h" end int main() { A a; } ``` Now read the code. B is the first class the compiler encounters, and it includes an `A&` member. What is `A`? The compiler hasn't encountered any definition of `A` yet, so it issues an error. The solution is to make a forward declaration of A. At some point before the definition of B, add a line `class A;` This gives the compiler the necessary information, that A is a class. We don't know anything else about it yet, but since B only needs to include a reference to it, this is good enough. In the definition of A, we need a member of type B (not a reference), so here the entire definition of B has to be visible. Which it is, luckily.
> And just to be clear, in general, where should #include statements go? Inside the include guards, for the reason you mentioned. For your other problem: you need to forward-declare at least one of the classes, e.g. like this: ``` #ifndef B_H_ #define B_H_ // Instead of this: //#include "A.h" class A; class B { private: A& a; public: B(A& a) : a(a) {} }; #endif /*B_H_*/ ``` This only works for declarations though: as soon as you really *use* an instance of `A`, you need to have defined it as well. By the way, what Nathan says is true: you can't put class instances into each other recursively. This only works with *pointers* (or, in your case, references) to instances.
Headers Including Each Other in C++
[ "", "c++", "recursion", "header", "include", "" ]
I would like to add an operator to a class. I currently have a `GetValue()` method that I would like to replace with an `[]` operator. ``` class A { private List<int> values = new List<int>(); public int GetValue(int index) => values[index]; } ```
``` public int this[int key] { get => GetValue(key); set => SetValue(key, value); } ```
I believe this is what you are looking for: **[Indexers (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/6x16t2tx(v=VS.100).aspx)** ``` class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get => arr[i]; set => arr[i] = value; } } // This class shows how client code uses the indexer class Program { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = "Hello, World"; System.Console.WriteLine(stringCollection[0]); } } ```
How do I overload the [] operator in C#
[ "", "c#", "operator-overloading", "indexer", "" ]
Is there a class/example application for a message-only window that is in C++ [Win32](http://en.wikipedia.org/wiki/Windows_API)?
If I recall, the standard solution is to create a basic styleless window with a message pump as you normally would, but never call ShowWindow on it. This way you can receive and process the standard messages like WM\_QUERYENDSESSION which are sent to all windows.
From the docs for [CreateWindow](http://msdn.microsoft.com/en-us/library/ms632679(VS.85).aspx): > hWndParent > [in] Handle to the parent or owner window of the window being created. To > create a child window or an owned > window, supply a valid window handle. > This parameter is optional for pop-up > windows. > > Windows 2000/XP: **To create a message-only window, supply HWND\_MESSAGE or a > handle to an existing message-only window**. [Here](http://www.google.com/codesearch/p?hl=en#N6Qhr5kJSgQ/WebCore/platform/win/SharedTimerWin.cpp&q=HWND_MESSAGE) is some code, from WebKit I think, that sets up a message-only window for timer events. Here is an article that shows a (possibly overly) fancy way to create an invisible, message-only window: <http://www.codeguru.com/cpp/w-p/win32/tutorials/article.php/c12689>
Message Window C++ Win32 class/example
[ "", "c++", "winapi", "window", "message", "" ]
I have a utility that I put together that uses the .NET Framework to capture an image of a web page so that I can use the thumbnail image to preview a page. There are sites which offer this service like websnapr.com, kwiboo.com and shrinktheweb.com. I would like to instead do it myself and leverage Firefox (Gecko) and Safari (WebKit) to render the image. Is there anything available to do this currently? Is there a C# project that hooks into Gecko and/or WebKit to create images of a loaded web page. My project is called WebPreview and it uses the WebBrowser control from the .NET Framework, but since that can be a bit outdated the rendered screenshots will not look as accurate as a recent Gecko or WebKit build. <http://www.smallsharptools.com/Projects/WebPreview/> Please post a comment for any Open Source projects which can help me.
I use a Firefox add-on called [Screengrab](http://addons.mozilla.org/en-US/firefox/addon/1146)
checkout <http://browsershots.org/> its free and open. it says somewhere on the site what plugins and techniques they use...
Capturing the image of a web page using Firefox and Safari
[ "", "c#", ".net", "" ]
I'm binding a GridView to an LINQ query. Some of the fields in the objects created by the LINQ statement are strings, and need to contain new lines. Apparently, GridView HTML-encodes everything in each cell, so I can't insert a <br /> to create a new line within a cell. How do I tell GridView not to HTML encode the contents of cells? Maybe I should use a different control instead?
Can you subscribe to the RowDataBound event? If you can, you can run: ``` if (e.Row.RowType == DataControlRowType.DataRow) { string decodedText = HttpUtility.HtmlDecode(e.Row.Cells[0].Text); e.Row.Cells[0].Text = decodedText; } ```
What about setting the [`HtmlEncode` property](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.htmlencode.aspx) to `false`? To me, this is much simpler. ``` <asp:BoundField DataField="MyColumn" HtmlEncode="False" /> ```
How to render decoded HTML in a (i.e. a <br>) in GridView cell
[ "", "c#", "asp.net", "gridview", "newline", "" ]
Why do we need both `using namespace` and `include` directives in C++ programs? For example, ``` #include <iostream> using namespace std; int main() { cout << "Hello world"; } ``` Why is it not enough to just have `#include <iostream>` or just have `using namespace std` and get rid of the other? (I am thinking of an analogy with Java, where `import java.net.*` will import everything from `java.net`, you don't need to do anything else.)
In `C++` the concepts are separate. This is by design and useful. You can include things that without namespaces would be ambiguous. With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the `using` directive or if you did you would have to specify the namespace of the other stuff in the namespace you wanted. Note also that you don't NEED the using - you can just used std::cout or whatever you need to access. You preface the items with the namespace.
using directives and include preprocessor directives are two different things. The `include` roughly corresponds to the `CLASSPATH` environment variable of Java, or the `-cp` option of the java virtual machine. What it does is making the types known to the compiler. Just including `<string>` for example will make you able to refer to `std::string` : ``` #include <string> #include <iostream> int main() { std::cout << std::string("hello, i'm a string"); } ``` Now, using directives are like `import` in Java. They make names visible in the scope they appear in, so you don't have to fully qualify them anymore. Like in Java, names used must be known before they can be made visible: ``` #include <string> // CLASSPATH, or -cp #include <iostream> // without import in java you would have to type java.lang.String . // note it happens that java has a special rule to import java.lang.* // automatically. but that doesn't happen for other packages // (java.net for example). But for simplicity, i'm just using java.lang here. using std::string; // import java.lang.String; using namespace std; // import java.lang.*; int main() { cout << string("hello, i'm a string"); } ``` It's bad practice to use a using directive in header files, because that means every other source file that happens to include it will see those names using unqualified name lookup. Unlike in Java, where you only make names visible to the package the import line appears in, In C++ it can affect the whole program, if they include that file directly or indirectly. Be careful when doing it at global scope even in implementation files. Better to use them as local as possible. For namespace std, i never use that. I, and many other people, just always write `std::` in front of names. But if you happen to do it, do it like this: ``` #include <string> #include <iostream> int main() { using namespace std; cout << string("hello, i'm a string"); } ``` --- For what namespaces are and why you need them, please read the proposal Bjarne Stroustrup gave 1993 for adding them to the upcoming C++ Standard. It's well written: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0262.pdf>
Why do we need both using-directives and include-directives?
[ "", "c++", "namespaces", "header-files", "language-design", "" ]
It looks like if I load dynamic content using `$.get()`, the result is cached in browser. Adding some random string in QueryString seems to solve this issue (I use `new Date().toString()`), but this feels like a hack. Is there any other way to achieve this? Or, if unique string is the only way to achieve this, any suggestions other than `new Date()`?
I use `new Date().getTime()`, which will avoid collisions unless you have multiple requests happening within the same millisecond: ``` $.get('/getdata?_=' + new Date().getTime(), function(data) { console.log(data); }); ``` **Edit:** This answer is several years old. It still works (hence I haven't deleted it), but **there are better/cleaner ways of achieving this now**. My preference is for [this](https://stackoverflow.com/a/735084/43140) method, but [this](https://stackoverflow.com/a/735101/43140) answer is also useful if you want to disable caching for *every* request during the lifetime of a page.
The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.) ``` $.ajaxSetup({ cache: false }); ```
Prevent browser caching of AJAX call result
[ "", "javascript", "jquery", "ajax", "browser-cache", "" ]
In a method, I want to be able to insert a value into a div which is part of the html document I choose to parse. ``` public void AddToDiv(string div) { //Code to read the html document and look for the div //(name specified as the parameter of this method). } ``` Question is, I could specify a div called "abc" but the html document may not have this div. Fair enough, but what is the difference between me saying: ``` try { //Method logic to parse document for the div } catch(ArgumentException ex) { // (I wouldn't supress this catch block in production code, // just omitting body details for simplicity. } ``` OR ``` public void ParseDocument { //Logic here... if(!document.Contains(div) { throw new ArgumentException(); } } ``` In short, what is the difference between a catch block and saying throw new [ExceptionType here] in the main logic block? How do I decide which is to use? Thanks
Personally, I'd check for existence, rather than allowing the exception to be thrown, it's easier to determine the flow of logic, and fits better with the intent of your code. See these questions and answers for a broader discussion [When to throw an exception](https://stackoverflow.com/questions/77127/when-to-throw-an-exception) [Is there any valid reason to ever ignore a caught exception](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception) [How slow are .net exceptions?](https://stackoverflow.com/questions/161942/how-slow-are-net-exceptions) **EDIT:** On second thoughts, you should consider the expense of the "containts" check. If it's likely to be as expensive as actually getting the div, and it's doubling the time it takes the routine to run and **if this lag degrades performance to the point where it'll be noticed**, then possibly it's better to just go and get the div. I'd still catch it and throw the ArgumentException, with the original exception as the inner exception. **NB:** Don't optimise unless you need to.
There is a third option, but I'll write more about it later. First of all, catching exception is all about catching errors you don't expect, handling them and either continue or close down gracefully. Throwing exceptions should be used when you encounter situation which shouldn't occur or should be handled elsewhere. If you want to handle this error outside your method, this might be your solution. The third alternative is to actually avoid errors you know may occur. You could for example check if the div exists and not do anything if it doesn't, also known as defensive programming.
Difference between catch block and throw new Exception in method
[ "", "c#", "exception", "" ]
I want to have a abstract view for any type of UI (web or window). In order to do that I must use Interface (IView ) in which I can only apply just rules about view. In fact, I want to set a some basic comple function to provide to its inheritances. So in this way, I must use abstract class. The problem is 1) Interface only have rules 2) The view (web form or window form) can't inherit any more since that's already inherited from window or web form How can I do that? Many thanks
Will the functions you add change the definition of what the class is, or will you simply be creating functions to manipulate data that is already a part of the class? If you need to redefine aspects of the base class of these two classes then yes, you will need to change your inheritance structure. But if the functions will simply manipulate data that is already part of the class now then I would suggest you use the interface and create utility functions. Here is a clumsy example of what I mean: ``` using System; abstract class Pet { } class Dog : Pet, IPet { public String Name { get; set; } public Int32 Age { get; set; } } class Cat : Pet, IPet { public String Name { get; set; } public Int32 Age { get; set; } } interface IPet { String Name { get; set; } Int32 Age { get; set; } } static class PetUtils { public static void Print(this IPet pet) { Console.WriteLine(pet.Name + " is " + pet.Age); } } ``` Your two UI classes are perhaps related in this way. I would imagine that what you need to do in a cross-cutting fashion would be solved by a utility method like the one I have created. I did create the `PetUtils.Print` method as an extension method as this will create the expressive illusion of an instance method. If you are not using C# 3 just remove "`this`" from `public static void Print(this IPet pet)`.
You can inherit a concrete class (web form/window form), declare your class abstract, and still implement an interface. System.Web.UI.Page example: ``` public interface IView { void Foo(); } public abstract class BasePage : Page, IView { //honor the interface //but pass implementation responsibility to inheriting classes public abstract void Foo(); //concrete method public void Bar() { //do concrete work } } public class ConcretePage : BasePage { //implement Foo public override void Foo() { } } ``` This gives you the benefit of the interface and the concrete method Bar();
Interface or Abstract Class to fulfill requirement
[ "", "c#", ".net", "" ]
I've faced strange problem. While user change of check box input element on form produces adequate event programmatic change don't. How should I face this challenge? Code following: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script> <script type="text/javascript"> jQuery(document).ready( function() { jQuery("#cb").change( function() { alert("Changed!"); return true; } ); jQuery("#b").click( function() { var newState = !jQuery("#cb").attr('checked'); jQuery("#cb").attr('checked', newState); }); }); </script> </head> <body> <form action="#"> <p> <input type="button" id="b" /> <input type="checkbox" id="cb" /> </p> </form> </body> </html> ``` **Update** I do not control element changes, I just need to handle them. It's general-propose code I write.
It's impossible to track object's state within javascript language as it could be done in Objective-C (KVO). Nor it possible using DOM features - DOM do not fire events on every property change - instead it only fires events on certain user actions: mouse clicks, key presses, or page life cycle and their derivatives. One could achieve that only firing event every time she modifies some property. Certainly this could be encapsulated in a function as AnthonyWJones had mentioned.
use the trigger function to trigger a click event on the checkbox. You won't need to grab the existing state as the checkbox will just be toggled by the click. ``` jQuery("#cb").trigger('click'); ```
How to handle programmatic change of the input element state in javascript
[ "", "javascript", "jquery", "html", "dom", "" ]
I've seen a number of examples that have a thread procedure that looks like this. ``` private void ThreadProc() { while (serviceStarted) { // do some work Thread.Sleep(new TimeSpan(0, 0, 5)); } Thread.CurrentThread.Abort(); } ``` Is the `Abort()` really necessary at the end? There are number of arguments against calling `Abort()` 1. Once the procedure exited - it is expected it has already cleaned up after itself. 2. Calling `Abort()` throws an exception, which is generally more resource intensive than just exiting a procedure. I'd like to read an explanation for why this is or isn't a good practice.
Calling `Thread.Abort()` does raise an exception, and if you're writing code that will be re-used (or part of a base library) it's difficult for other developers to handle `ThreadAbortExcpetion`s. It's explained in this article about [Reliability Best Practices](http://msdn.microsoft.com/en-us/library/ms228970(VS.80).aspx). I've always heard that calling [`Thread.Join()`](http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx) is a better way to do it, if you can wait until the thread is completed processing. I don't know if anyone thinks it's a good practice. It can cause deadlocks (because unmanaged resources aren't properly cleaned up when you throw an exception) Here's [another article about it](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation), and other methods to deal with the issue.
Once the loop exits, the thread will terminate on its own. There is not need to abort the thread. The `CurrentThread.Abort` is not only superfluous, but genuinely harmful since it raises a `ThreadAbortException`. If another thread attempts to `Join()` your service loop thread, it will have to handle an exception unnecessarily. Your best bet is just to delete the line `CurrentThread.Abort()`.
To CurrentThread.Abort or not to CurrentThread.Abort
[ "", "c#", ".net", "multithreading", "" ]
I`m writing a chat using WinSock2 and WinAPI functions. And I have a little trouble. I store the std::vector of client connections on server. When new client connects, new thread starts and all work with the client is done in this new thread. I do not use classes (I know it is not very good) so this list of connections is just defined as global variable. It seems to me that it can be a situation when several threads try to access this list simultaneously. Though I have not noticed that there are any problems with that, do I need to do something like this: ``` template class SharedVector { std::vector vect; CRITICAL_SECTION cs; SharedVector(const SharedVector& rhs) {} public: SharedVector(); explicit SharedVector(const CRITICAL_SECTION& CS); void PushBack(const T& value); void PopBack(); unsigned int size(); T& operator[](int index); virtual ~SharedVector(); }; template SharedVector::SharedVector() { InitializeCriticalSection(&cs); } template SharedVector::SharedVector(const CRITICAL_SECTION& r): cs(r) { InitializeCriticalSection(&cs); } template void SharedVector::PushBack(const T& value) { EnterCriticalSection(&cs); vect.push_back(value); LeaveCriticalSection(&cs); } template void SharedVector::PopBack() { EnterCriticalSection(&cs); vect.pop_back(); LeaveCriticalSection(&cs); } ``` So, does my situation require using CRITICAL\_SECTION and am I just the lucky guy who did not find a mistake?
Yes, you are just lucky never to experience any problems. This is the problem with synchronization issues and race conditions, that the code will work in 99.9% of all cases, and when disaster strikes you won't know why. I would take away the constructor taking a CRITICAL\_SECTION as a parameter since it is not clear without looking at (presumably non-existing) documentation to realize that the constructor will initialize it.
The biggest question I have for you is architectural. Does the thread for each connection really need direct access to this array of **other** connections? Shouldn't they really be enqueueing abstract messages of some sort? If each connection thread is conscious of the implementation details of the universe in which it lives, I expect you will run into trouble somewhere down the line. But let's assume connection threads really do need direct access to each other... Global variables aren't inherently evil; schools just teach that because it's easier than providing a nuanced understanding. You do have to know the exact implications of a global variable, and it's a decent rule of thumb to assume that a global is the wrong choice until you discover you have no alternative. One alternative which solves a number of problems is to write a function like this: ``` SharedVector & GetSharedVector (void) { static SharedVector sharedVector; return sharedVector; } ``` This buys you more control over when the class gets instantiated than you would have with a global variable, which can be critical if you have dependencies among global variables which have constructors, especially if those global variables spawn threads. It also gives you an opportunity to intercede when someone wants access to this "global" variable rather than just powerlessly suffer while they poke at it directly. A number of other thoughts also spring to mind. In no particular order... * You doubtless already know the template syntax you use here is weird; I'll assume you just typed this code in without compiling it. * You need a do-nothing assignment operator in your private section to prevent accidents (for the same reason you have a do-nothing copy constructor there). * The explicit copy constructor is broken in a number of ways. It needs to explicitly copy the vector or you'll end up with an empty vector in your new instance of SharedVector. And it should simply initialize its own critical section rather than copy it (and then initialize it). Really for your case it probably doesn't make sense to have this function at all because network connections don't have reasonable copy semantics. * You can make exception safety easier by creating a class EnteredCriticalSection whose constructor calls EnterCriticalSection and whose destructor calls LeaveCriticalSection. (It needs to hold onto a reference to the critical section, of course.) This makes it a ton easier to safely serialize your other member functions in the face of exceptions.
Critical section - to be or not to be?
[ "", "c++", "winapi", "critical-section", "" ]
I have a Django model (schedule) with the class of entity, that is the parent of `Activity`, that is the parent of `Event`. ``` class Entity(models.Model): <...> class Activity(models.Model): <...> team_entity = models.ForeignKey(Entity) <...> class Event(models.Model): <...> activity = models.ForeignKey(Activity) <...> ``` How do I serialize and get both the child object and grand children as part of the JSON file?
I now use django-piston. This does the trick.
Before you do serialization, when retrieving your objects, to preserve the relationships use select\_related() to get children, grandchildren, etc see <http://docs.djangoproject.com/en/dev/ref/models/querysets/>
Django serialize to JSON
[ "", "python", "django", "json", "" ]
Given this field: ``` char lookup_ext[8192] = {0}; // Gets filled later ``` And this statement: ``` unsigned short *slt = (unsigned short*) lookup_ext; ``` What happens behind the scenes? lookup\_ext[1669] returns 67 = 0100 0011 (C), lookup\_ext[1670] returns 78 = 0100 1110 (N) and lookup\_ext[1671] returns 68 = 0100 0100 (D); yet slt[1670] returns 18273 = 0100 0111 0110 0001. I'm trying to port this to C#, so besides an easy way out of this, I'm also wondering what really happens here. Been a while since I used C++ regularly. Thanks!
The statement that you show doesn't cast a char to an unsigned short, it casts a *pointer* to a char to a *pointer* to an unsigned short. This means that the usual arithmetic conversions of the pointed-to-data are not going to happen and that the underlying char data will just be interpreted as unsigned shorts when accessed through the `slt` variable. Note that `sizeof(unsigned short)` is unlikely to be one, so that `slt[1670]` won't necessarily correspond to `lookup_ext[1670]`. It is more likely - if, say, `sizeof(unsigned short)` is two - to correspond to `lookup_ext[3340]` and `lookup_ext[3341]`. Do you know why the original code is using this aliasing? If it's not necessary, it might be worth trying to make the C++ code cleaner and verifying that the behaviour is unchanged before porting it.
If I understand correctly, the type conversion will be converting a char array of size 8192 to a short int array of size half of that, which is 4096. So I don't understand what you are comparing in your question. slt[1670] should correspond to lookup\_ext[1670\*2] and lookup\_ext[1670\*2+1].
Casting a char to an unsigned short: what happens behind the scenes?
[ "", "c#", "c", "casting", "" ]
I am currently working on a project that spans accross multiple domains. What I want is for the user to be able to login on one site and be logged in on all the others at the same time. The users session is stored in the database, the cookies that I set on each domain contain the session id. So basically when a user logs in to example.com a cookie is created with their session id, the session data is stored in the database. Once this is done a cookie needs to be created on all the other domains with this unique session id so that as the user travels from site to site they will automatically be logged in. Now I have found a way to do this in Firefox (using image tags that executes PHP scripts on the other domains, essentially creating the different cookies on the different domains) but this method doesn't work in IE (havn't tested Opera or Safari etc. yet). Does anyone have any ideas about how I can get this to work in IE?
Have a look at my question [Cross Domain User Tracking](https://stackoverflow.com/questions/216430/cross-domain-user-tracking). What you need to do is to add another HTTP header to the "image". Quote from [Session variables are lost if you use FRAMESET in Internet Explorer 6](http://support.microsoft.com/kb/323752/EN-US/): > You can add a P3P compact policy > header to your child content, and you > can declare that no malicious actions > are performed with the data of the > user. If Internet Explorer detects a > satisfactory policy, then Internet > Explorer permits the cookie to be set. > > A simple compact policy that fulfills > this criteria follows: > > P3P: CP="CAO PSA OUR" > > This code sample shows that your site > provides you access to your own > contact information (CAO), that any > analyzed data is only > "pseudo-analyzed", which means that > the data is connected to your online > persona and not to your physical > identity (PSA), and that your data is > not supplied to any outside agencies > for those agencies to use (OUR). > > You can set this header if you use the > Response.AddHeader method in an ASP > page. In ASP.NET, you can use the > Response.AppendHeader method. You can > use the IIS Management Snap-In > (inetmgr) to add to a static file. > > Follow these steps to add this header > to a static file: > > 1. Click Start, click Run, and then type inetmgr. > 2. In the left navigation page, click the appropriate file or > directory in your Web site to which > you want to add the header, > right-click the file, and then click > Properties. > 3. Click the HTTP Headers tab. > 4. In the Custom HTTP Headers group box, click Add. > 5. Type P3P for the header name, and then for the compact policy > string, type CP=..., where "..." is > the appropriate code for your compact > policy.
Is it just me, or does it sound like your CSRFing yourself with your technique using images that works in Firefox? Interesting approach, although I hope you're not opening yourself up to a security threat there.
PHP Multi site login
[ "", "php", "authentication", "single-sign-on", "multiple-domains", "" ]
I am just getting started with Grails. How do I add Java libraries to my Grails project? I added the Smack library jar to the lib folder of my Grails project, but I still cannot import any of its packages into my Java or Groovy classes. I am using the Netbeans IDE. Any help would be appreciated.. Buzzy
This is a know bug in NetBeans: <http://www.netbeans.org/issues/show_bug.cgi?id=144243> Maybe you can help the devolpers to fix it by adding a comment to this issue in the NetBeans bug tracker.
Here is what I did to solve the problem when running SpringSource Toolsuite: 1. Configure the build path by adding external jars (e.g. javax.mail, adwords-api, etc.) 2. Imported the same jars in to the lib folder (where mysql connector jar is located). This should fix the compile time errors you would receive from missing imports in your java files. Hope this helps
Add Java Libraries to a Netbeans Grails Project
[ "", "java", "grails", "netbeans", "groovy", "jar", "" ]
It would be really handy to be able to somehow say that certain properties in the generated entity classes should, for example, be decorated by (say) validation attributes (as well as Linq To SQL column attributes). Is it a T4 template someplace? Or are there other ways to skin the cat?
Damien Guard has written T4 templates that can be customized. See: <http://damieng.com/blog/2008/09/14/linq-to-sql-template-for-visual-studio-2008> ...and: <http://visualstudiomagazine.com/listings/list.aspx?id=560>
No, the SqlMetal tool is what handles the generation of the C# and it is defined within itself how the C# is generated (or VB for that matter). I'm not familiar with the template style you want but you could try exteding the generated classes (if they aren't that big a change) since they are just partial classes. Otherwise you would need to write/ look for a custom implementation of SqlMetal
Possible to modify the C# that Linq To SQL generates?
[ "", "c#", "linq-to-sql", "templates", "code-generation", "" ]
How can I change the master volume level? Using this code ``` [DllImport ("winmm.dll")] public static extern int waveOutSetVolume (IntPtr hwo, uint dwVolume); waveOutSetVolume (IntPtr.Zero, (((uint)uint.MaxValue & 0x0000ffff) | ((uint)uint.MaxValue << 16))); ``` I can set the wave volume but if the master volume is too low this won't have any effect. Thanks for any help.
Okay, here goes: ``` const int MAXPNAMELEN = 32; const int MIXER_SHORT_NAME_CHARS = 16; const int MIXER_LONG_NAME_CHARS = 64; [Flags] enum MIXERLINE_LINEF : uint{ ACTIVE = 0x00000001, DISCONNECTED = 0x00008000, SOURCE = 0x80000000 } [Flags] enum MIXER : uint{ GETLINEINFOF_DESTINATION = 0x00000000, GETLINEINFOF_SOURCE = 0x00000001, GETLINEINFOF_LINEID = 0x00000002, GETLINEINFOF_COMPONENTTYPE = 0x00000003, GETLINEINFOF_TARGETTYPE = 0x00000004, GETLINEINFOF_QUERYMASK = 0x0000000F, GETLINECONTROLSF_ALL = 0x00000000, GETLINECONTROLSF_ONEBYID = 0x00000001, GETLINECONTROLSF_ONEBYTYPE = 0x00000002, GETLINECONTROLSF_QUERYMASK = 0x0000000F, GETCONTROLDETAILSF_VALUE = 0x00000000, GETCONTROLDETAILSF_LISTTEXT = 0x00000001, GETCONTROLDETAILSF_QUERYMASK = 0x0000000F, OBJECTF_MIXER = 0x00000000, OBJECTF_WAVEOUT = 0x10000000, OBJECTF_WAVEIN = 0x20000000, OBJECTF_MIDIOUT = 0x30000000, OBJECTF_MIDIIN = 0x40000000, OBJECTF_AUX = 0x50000000, OBJECTF_HANDLE = 0x80000000, OBJECTF_HMIXER = OBJECTF_HANDLE | OBJECTF_MIXER, OBJECTF_HWAVEOUT = OBJECTF_HANDLE | OBJECTF_WAVEOUT, OBJECTF_HWAVEIN = OBJECTF_HANDLE | OBJECTF_WAVEIN, OBJECTF_HMIDIOUT = OBJECTF_HANDLE | OBJECTF_MIDIOUT, OBJECTF_HMIDIIN = OBJECTF_HANDLE | OBJECTF_MIDIIN } [Flags] enum MIXERCONTROL_CT : uint{ CLASS_MASK = 0xF0000000, CLASS_CUSTOM = 0x00000000, CLASS_METER = 0x10000000, CLASS_SWITCH = 0x20000000, CLASS_NUMBER = 0x30000000, CLASS_SLIDER = 0x40000000, CLASS_FADER = 0x50000000, CLASS_TIME = 0x60000000, CLASS_LIST = 0x70000000, SUBCLASS_MASK = 0x0F000000, SC_SWITCH_BOOLEAN = 0x00000000, SC_SWITCH_BUTTON = 0x01000000, SC_METER_POLLED = 0x00000000, SC_TIME_MICROSECS = 0x00000000, SC_TIME_MILLISECS = 0x01000000, SC_LIST_SINGLE = 0x00000000, SC_LIST_MULTIPLE = 0x01000000, UNITS_MASK = 0x00FF0000, UNITS_CUSTOM = 0x00000000, UNITS_BOOLEAN = 0x00010000, UNITS_SIGNED = 0x00020000, UNITS_UNSIGNED = 0x00030000, UNITS_DECIBELS = 0x00040000, /* in 10ths */ UNITS_PERCENT = 0x00050000, /* in 10ths */ } [Flags] enum MIXERCONTROL_CONTROLTYPE : uint{ CUSTOM = MIXERCONTROL_CT.CLASS_CUSTOM | MIXERCONTROL_CT.UNITS_CUSTOM, BOOLEANMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_BOOLEAN, SIGNEDMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_SIGNED, PEAKMETER = SIGNEDMETER + 1, UNSIGNEDMETER = MIXERCONTROL_CT.CLASS_METER | MIXERCONTROL_CT.SC_METER_POLLED | MIXERCONTROL_CT.UNITS_UNSIGNED, BOOLEAN = MIXERCONTROL_CT.CLASS_SWITCH | MIXERCONTROL_CT.SC_SWITCH_BOOLEAN | MIXERCONTROL_CT.UNITS_BOOLEAN, ONOFF = BOOLEAN + 1, MUTE = BOOLEAN + 2, MONO = BOOLEAN + 3, LOUDNESS = BOOLEAN + 4, STEREOENH = BOOLEAN + 5, BASS_BOOST = BOOLEAN + 0x00002277, BUTTON = MIXERCONTROL_CT.CLASS_SWITCH | MIXERCONTROL_CT.SC_SWITCH_BUTTON | MIXERCONTROL_CT.UNITS_BOOLEAN, DECIBELS = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_DECIBELS, SIGNED = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_SIGNED, UNSIGNED = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_UNSIGNED, PERCENT = MIXERCONTROL_CT.CLASS_NUMBER | MIXERCONTROL_CT.UNITS_PERCENT, SLIDER = MIXERCONTROL_CT.CLASS_SLIDER | MIXERCONTROL_CT.UNITS_SIGNED, PAN = SLIDER + 1, QSOUNDPAN = SLIDER + 2, FADER = MIXERCONTROL_CT.CLASS_FADER | MIXERCONTROL_CT.UNITS_UNSIGNED, VOLUME = FADER + 1, BASS = FADER + 2, TREBLE = FADER + 3, EQUALIZER = FADER + 4, SINGLESELECT = MIXERCONTROL_CT.CLASS_LIST | MIXERCONTROL_CT.SC_LIST_SINGLE | MIXERCONTROL_CT.UNITS_BOOLEAN, MUX = SINGLESELECT + 1, MULTIPLESELECT = MIXERCONTROL_CT.CLASS_LIST | MIXERCONTROL_CT.SC_LIST_MULTIPLE | MIXERCONTROL_CT.UNITS_BOOLEAN, MIXER = MULTIPLESELECT + 1, MICROTIME = MIXERCONTROL_CT.CLASS_TIME | MIXERCONTROL_CT.SC_TIME_MICROSECS | MIXERCONTROL_CT.UNITS_UNSIGNED, MILLITIME = MIXERCONTROL_CT.CLASS_TIME | MIXERCONTROL_CT.SC_TIME_MILLISECS | MIXERCONTROL_CT.UNITS_UNSIGNED } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] struct MIXERLINE{ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] public struct TargetInfo{ public uint dwType; public uint dwDeviceID; public ushort wMid; public ushort wPid; public uint vDriverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAXPNAMELEN)] public string szPname; } public uint cbStruct; public uint dwDestination; public uint dwSource; public uint dwLineID; public MIXERLINE_LINEF fdwLine; public uint dwUser; public uint dwComponentType; public uint cChannels; public uint cConnection; public uint cControls; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_SHORT_NAME_CHARS)] public string szShortName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_LONG_NAME_CHARS)] public string szName; public TargetInfo Target; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] struct MIXERCONTROL{ [StructLayout(LayoutKind.Explicit)] public struct BoundsInfo{ [FieldOffset(0)] public int lMinimum; [FieldOffset(4)] public int lMaximum; [FieldOffset(0)] public uint dwMinimum; [FieldOffset(4)] public uint dwMaximum; [FieldOffset(8), MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] public uint[] dwReserved; } [StructLayout(LayoutKind.Explicit)] public struct MetricsInfo{ [FieldOffset(0)] public uint cSteps; [FieldOffset(0)] public uint cbCustomData; [FieldOffset(4), MarshalAs(UnmanagedType.ByValArray, SizeConst=5)] public uint[] dwReserved; } public uint cbStruct; public uint dwControlID; public MIXERCONTROL_CONTROLTYPE dwControlType; public uint fdwControl; public uint cMultipleItems; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_SHORT_NAME_CHARS)] public string szShortName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MIXER_LONG_NAME_CHARS)] public string szName; public BoundsInfo Bounds; public MetricsInfo Metrics; } [StructLayout(LayoutKind.Explicit)] struct MIXERLINECONTROLS{ [FieldOffset(0)] public uint cbStruct; [FieldOffset(4)] public uint dwLineID; [FieldOffset(8)] public uint dwControlID; [FieldOffset(8)] // not a typo! overlaps previous field public uint dwControlType; [FieldOffset(12)] public uint cControls; [FieldOffset(16)] public uint cbmxctrl; [FieldOffset(20)] public IntPtr pamxctrl; } [StructLayout(LayoutKind.Explicit)] struct MIXERCONTROLDETAILS{ [FieldOffset(0)] public uint cbStruct; [FieldOffset(4)] public uint dwControlID; [FieldOffset(8)] public uint cChannels; [FieldOffset(12)] public IntPtr hwndOwner; [FieldOffset(12)] // not a typo! public uint cMultipleItems; [FieldOffset(16)] public uint cbDetails; [FieldOffset(20)] public IntPtr paDetails; } [StructLayout(LayoutKind.Sequential)] struct VOLUME{ public int left; public int right; } struct MixerInfo{ public uint volumeCtl; public uint muteCtl; public int minVolume; public int maxVolume; } [DllImport("WinMM.dll", CharSet=CharSet.Auto)] static extern uint mixerGetLineInfo (IntPtr hmxobj, ref MIXERLINE pmxl, MIXER flags); [DllImport("WinMM.dll", CharSet=CharSet.Auto)] static extern uint mixerGetLineControls (IntPtr hmxobj, ref MIXERLINECONTROLS pmxlc, MIXER flags); [DllImport("WinMM.dll", CharSet=CharSet.Auto)] static extern uint mixerGetControlDetails(IntPtr hmxobj, ref MIXERCONTROLDETAILS pmxcd, MIXER flags); [DllImport("WinMM.dll", CharSet=CharSet.Auto)] static extern uint mixerSetControlDetails(IntPtr hmxobj, ref MIXERCONTROLDETAILS pmxcd, MIXER flags); static MixerInfo GetMixerControls(){ MIXERLINE mxl = new MIXERLINE(); MIXERLINECONTROLS mlc = new MIXERLINECONTROLS(); mxl.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERLINE)); mlc.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERLINECONTROLS)); mixerGetLineInfo(IntPtr.Zero, ref mxl, MIXER.OBJECTF_MIXER | MIXER.GETLINEINFOF_DESTINATION); mlc.dwLineID = mxl.dwLineID; mlc.cControls = mxl.cControls; mlc.cbmxctrl = (uint)Marshal.SizeOf(typeof(MIXERCONTROL)); mlc.pamxctrl = Marshal.AllocHGlobal((int)(mlc.cbmxctrl * mlc.cControls)); mixerGetLineControls(IntPtr.Zero, ref mlc, MIXER.OBJECTF_MIXER | MIXER.GETLINECONTROLSF_ALL); MixerInfo rtn = new MixerInfo(); for(int i = 0; i < mlc.cControls; i++){ MIXERCONTROL mxc = (MIXERCONTROL)Marshal.PtrToStructure((IntPtr)((int)mlc.pamxctrl + (int)mlc.cbmxctrl * i), typeof(MIXERCONTROL)); switch(mxc.dwControlType){ case MIXERCONTROL_CONTROLTYPE.VOLUME: rtn.volumeCtl = mxc.dwControlID; rtn.minVolume = mxc.Bounds.lMinimum; rtn.maxVolume = mxc.Bounds.lMaximum; break; case MIXERCONTROL_CONTROLTYPE.MUTE: rtn.muteCtl = mxc.dwControlID; break; } } Marshal.FreeHGlobal(mlc.pamxctrl); return rtn; } static VOLUME GetVolume(MixerInfo mi){ MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS(); mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS)); mcd.dwControlID = mi.volumeCtl; mcd.cMultipleItems = 0; mcd.cChannels = 2; mcd.cbDetails = (uint)Marshal.SizeOf(typeof(int)); mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails); mixerGetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER); VOLUME rtn = (VOLUME)Marshal.PtrToStructure(mcd.paDetails, typeof(VOLUME)); Marshal.FreeHGlobal(mcd.paDetails); return rtn; } static bool IsMuted(MixerInfo mi){ MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS(); mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS)); mcd.dwControlID = mi.muteCtl; mcd.cMultipleItems = 0; mcd.cChannels = 1; mcd.cbDetails = 4; mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails); mixerGetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER); int rtn = Marshal.ReadInt32(mcd.paDetails); Marshal.FreeHGlobal(mcd.paDetails); return rtn != 0; } static void AdjustVolume(MixerInfo mi, int delta){ VOLUME volume = GetVolume(mi); if(delta > 0){ volume.left = Math.Min(mi.maxVolume, volume.left + delta); volume.right = Math.Min(mi.maxVolume, volume.right + delta); }else{ volume.left = Math.Max(mi.minVolume, volume.left + delta); volume.right = Math.Max(mi.minVolume, volume.right + delta); } SetVolume(mi, volume); } static void SetVolume(MixerInfo mi, VOLUME volume){ MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS(); mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS)); mcd.dwControlID = mi.volumeCtl; mcd.cMultipleItems = 0; mcd.cChannels = 2; mcd.cbDetails = (uint)Marshal.SizeOf(typeof(int)); mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails); Marshal.StructureToPtr(volume, mcd.paDetails, false); mixerSetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER); Marshal.FreeHGlobal(mcd.paDetails); } static void SetMute(MixerInfo mi, bool mute){ MIXERCONTROLDETAILS mcd = new MIXERCONTROLDETAILS(); mcd.cbStruct = (uint)Marshal.SizeOf(typeof(MIXERCONTROLDETAILS)); mcd.dwControlID = mi.muteCtl; mcd.cMultipleItems = 0; mcd.cChannels = 1; mcd.cbDetails = 4; mcd.paDetails = Marshal.AllocHGlobal((int)mcd.cbDetails); Marshal.WriteInt32(mcd.paDetails, mute ? 1 : 0); mixerSetControlDetails(IntPtr.Zero, ref mcd, MIXER.GETCONTROLDETAILSF_VALUE | MIXER.OBJECTF_MIXER); Marshal.FreeHGlobal(mcd.paDetails); } ``` This code is huge and ugly. It's a translation of some C++ code, and with having to define all the P/Invoke stuff, it's a lot more code. But I've tested it, and it works. To use it, you simply need something like: ``` MixerInfo mi = GetMixerControls(); AdjustVolume(mi, 100); // add 100 to the current volume ``` or ``` MixerInfo mi = GetMixerControls(); AdjustVolume(mi, (mi.maxVolume - mi.minVolume) / 10); // increase the volume by 10% of total range ``` or ``` MixerInfo mi = GetMixerControls(); SetVolume(mi, mi.maxVolume); // let's get this party crunk'd! ``` or ``` MixerInfo mi = GetMixerControls(); SetMute(mi, true); // shhhh!!!!!! ``` **WARNING** Due to the use of fixed-sized ints and field offsets, this may fail fantastically on 64-bit Windows. I don't know, I haven't tested it and haven't paid enough attention to know if these field sizes expand to 64 bits. *caveat codor* **EDIT** For the sake of simplicity (relatively speaking), I've left out any error handling. You should really check the return codes of all the mixerXXX functions, but I'll leave that as an exercise for the reader (read as: I was too lazy to do this).
For the master volume (for Vista and above), that would be: [ISimpleAudioVolume::SetMasterVolume](http://msdn.microsoft.com/en-us/library/ms679141(VS.85).aspx) As explained [here](http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.mmedia/2007-01/msg00045.html), you may refer to the section: [Core Audio APIs in Windows Vista](http://msdn.microsoft.com/en-us/library/ms678710.aspx) for more. This call is not a Media Foundation call but a WASAPI (Windows Audio Session API) call: ISimpleAudioVolume::SetMasterVolume (The SetMasterVolume method sets the master volume level for the audio session.) This may be difficult however to make the UI of the Media Center reflect the new sound level set by that call, as this [thread illustrates](http://discuss.mediacentersandbox.com/forums/thread/6758.aspx) it. For windows Xp, you can study this [script](http://www.vbfrance.com/codes/AUGMENTER-BAISSER-VOLUME-WAVE-BALANCE_498.aspx) and maybe [this other script](http://www.tech-archive.net/Archive/VB/microsoft.public.vb.winapi/2005-07/msg00218.html). [Audio Library](http://www.codeproject.com/KB/audio-video/AudioLib.aspx) might also be of interest. There is also this old [Audio Project](http://www.codeguru.com/cpp/g-m/multimedia/article.php/c1575/) which hasa master volume part: ``` BOOL CVolumeDlg::amdInitialize() { ASSERT(m_hMixer == NULL); // get the number of mixer devices present in the system m_nNumMixers = ::mixerGetNumDevs(); m_hMixer = NULL; ::ZeroMemory(&m_mxcaps, sizeof(MIXERCAPS)); m_strDstLineName.Empty(); m_strVolumeControlName.Empty(); m_dwMinimum = 0; m_dwMaximum = 0; m_dwVolumeControlID = 0; // open the first mixer // A "mapper" for audio mixer devices does not currently exist. if (m_nNumMixers != 0) { if (::mixerOpen(&m_hMixer, 0, reinterpret_cast<DWORD>(this->GetSafeHwnd()), NULL, MIXER_OBJECTF_MIXER | CALLBACK_WINDOW) != MMSYSERR_NOERROR) { return FALSE; } if (::mixerGetDevCaps(reinterpret_cast<UINT>(m_hMixer), &m_mxcaps, sizeof(MIXERCAPS)) != MMSYSERR_NOERROR) { return FALSE; } } return TRUE; } BOOL CVolumeDlg::amdUninitialize() { BOOL bSucc = TRUE; if (m_hMixer != NULL) { bSucc = (::mixerClose(m_hMixer) == MMSYSERR_NOERROR); m_hMixer = NULL; } return bSucc; } BOOL CVolumeDlg::amdGetMasterVolumeControl() { if (m_hMixer == NULL) { return FALSE; } // get dwLineID MIXERLINE mxl; mxl.cbStruct = sizeof(MIXERLINE); mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; if (::mixerGetLineInfo(reinterpret_cast<HMIXEROBJ>(m_hMixer), &mxl, MIXER_OBJECTF_HMIXER | MIXER_GETLINEINFOF_COMPONENTTYPE) != MMSYSERR_NOERROR) { return FALSE; } // get dwControlID MIXERCONTROL mxc; MIXERLINECONTROLS mxlc; mxlc.cbStruct = sizeof(MIXERLINECONTROLS); mxlc.dwLineID = mxl.dwLineID; mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; mxlc.cControls = 1; mxlc.cbmxctrl = sizeof(MIXERCONTROL); mxlc.pamxctrl = &mxc; if (::mixerGetLineControls(reinterpret_cast<HMIXEROBJ>(m_hMixer), &mxlc, MIXER_OBJECTF_HMIXER | MIXER_GETLINECONTROLSF_ONEBYTYPE) != MMSYSERR_NOERROR) { return FALSE; } // store dwControlID m_strDstLineName = mxl.szName; m_strVolumeControlName = mxc.szName; m_dwMinimum = mxc.Bounds.dwMinimum; m_dwMaximum = mxc.Bounds.dwMaximum; m_dwVolumeControlID = mxc.dwControlID; return TRUE; } BOOL CVolumeDlg::amdGetMasterVolumeValue(DWORD &dwVal) const { if (m_hMixer == NULL) { return FALSE; } MIXERCONTROLDETAILS_UNSIGNED mxcdVolume; MIXERCONTROLDETAILS mxcd; mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS); mxcd.dwControlID = m_dwVolumeControlID; mxcd.cChannels = 1; mxcd.cMultipleItems = 0; mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); mxcd.paDetails = &mxcdVolume; if (::mixerGetControlDetails(reinterpret_cast<HMIXEROBJ>(m_hMixer), &mxcd, MIXER_OBJECTF_HMIXER | MIXER_GETCONTROLDETAILSF_VALUE) != MMSYSERR_NOERROR) { return FALSE; } dwVal = mxcdVolume.dwValue; return TRUE; } BOOL CVolumeDlg::amdSetMasterVolumeValue(DWORD dwVal) const { if (m_hMixer == NULL) { return FALSE; } MIXERCONTROLDETAILS_UNSIGNED mxcdVolume = { dwVal }; MIXERCONTROLDETAILS mxcd; mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS); mxcd.dwControlID = m_dwVolumeControlID; mxcd.cChannels = 1; mxcd.cMultipleItems = 0; mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); mxcd.paDetails = &mxcdVolume; if (::mixerSetControlDetails(reinterpret_cast<HMIXEROBJ>(m_hMixer), &mxcd, MIXER_OBJECTF_HMIXER | MIXER_SETCONTROLDETAILSF_VALUE) != MMSYSERR_NOERROR) { return FALSE; } return TRUE; } ```
Changing master volume level
[ "", "c#", "winapi", "volume", "" ]