Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am having problems with getting a HTML editor working. We are using “contentEditable” to implement it, however when any paragraph formatting option is done without contents selected, IE removes the ID from one of the divs in the page. The problem repeats for me with the HTML, 1. just save it to a file, 2. then open it in IE 3. enable jscript when asked 4. push the button 5. check you get two message boxes 2. first one says “MainContents = object” 3. second one says “MainContents = NULL” I am using IE 6.0.2900.5512 with XP SP3 **So does this repeat for you?** **What is going on?** ``` <html> <head> </head> <body id="BODY"> <div contentEditable="true" id="EDITBOX"> </div> <div id="MAINCONTENTS" unselectable="on"> <button title="Ordered List" unselectable="on" onclick='alert("MainContents = " + document.getElementById("MAINCONTENTS")); document.execCommand("InsertOrderedList"); alert("MainContents = " + document.getElementById("MAINCONTENTS")); '> Push Me </button> </div> </body> </html> <script type="text/javascript"> document.getElementById("EDITBOX").focus(); </script> ``` --- **Background** I work for an ISV that sell software to corporations, at present all our customers use IE and there is no market depend to support other browsers. I have been told to implement an HTML editor using contentEditable. All the formatting options are based on document.execCommand(), e.g. document.execCommand(“bold”); Due to licensing restrictions (LGPL is not liked) and/or cost it is very hard to get approval to use a 3rd party HTML editor. It took us a log time just to be allowed to use jquery. I have the editor working apart from the case of paragraph formatting commands when the user does not have any items selected. The HTML I posted is a small bit of HTML I wrote to reproduce the problem I am having. see also <http://www.maconstateit.net/tutorials/JSDHTML/JSDHTML12/jsdhtml12-02.htm> and [Risk of using contentEditable in IE](https://stackoverflow.com/questions/491790/risk-of-using-contenteditable-in-ie)
Thanks for everyone’s help, anyone thinking of using “contentEditable” should read the other answers to my question and then think **very hard** before using “contentEditable”. I have found that if I use an iframe e.g. ``` <iframe id=EditorIFrame > </iframe> ``` And create the div that is editable in the iframe eg ``` theEditorIFrame = document.getElementById('EditorIFrame'); theEditorDoc = theEditorIFrame.contentWindow.document; theEditorDoc.body.innerHTML = '<body><div contentEditable="true" id="EDITBOX"></div></body>'; theEditorDiv = theEditorDoc.getElementById("EDITBOX") theEditorDiv.focus(); theEditorDoc.execCommand("InsertOrderedList") ``` It seems to all work for me, at present until I get the next nasty surprise from “contentEditable” and “execCommand” *Ps How do I get the first line of my code to lineup with the rest?*
The first issue, as [Gary](https://stackoverflow.com/questions/527866/why-is-contenteditable-removing-id-from-div/527925#527925) pointed out is the inconsistency in case although it won't affect IE as explorer getElementById goes against W3 specs and is not case sensitive. Changing the exec command to be: `document.execCommand("insertOrderedList",true,"");` seems to get be objects for both alerts and also makes the code work a bit better in firefox (which wasn't working at all). I guess my first question would be, do you really need to do this using execCommand? I know you're probably trying to do more than just insert an ordered list, but I'd hazard a guess that implementing what you're trying to do with the DOM would likely be a cleaner way to do it. I'm adding an edit to this reply, because the more I play with your test code the more inconsistent my results are becoming. I get different results the first time I run it in different browsers and I get different results after running it a few times and then restarting the browser. To be perfectly honest this is exactly the kind of stuff you desperately want to avoid when doing javascript development so I'll reiterate my initial question. Do you *really* need to use this technique to achieve your goals. There are better and easier ways to do insertion into the DOM.
Why is ContentEditable removing “ID” from div
[ "", "javascript", "html", "internet-explorer", "internet-explorer-6", "" ]
How can I check programmatically, how much memory my program currently has allocated ? I need it for an ASP .NET app, but i suspect the solution is general for all types of .NET applications. Ideally, the operation to get the currently allocated amount of memory, should be fast, since I will need to query it often. EDIT: Thanks for your answers. I will be using GC.GetTotalMemory for this task, since I need to use it for an ASP .NET application. After some experimenting, I have determined that it is fast and accurate enough for my needs. The suggestion to use Process' PrivateMemorySize64 property will also work in general; but as pointed out in the answers, for an ASP.NET application there will often be multiple AppDomain's running in one process. I need the memory total per-AppDomain.
There is a [**GC.GetTotalMemory**](http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory(VS.80).aspx) Method but this will only give you an approximation. Is this enough? If you call it with `GC.GetTotalMemory(false)` it will be faster ...
And also note that for asp.net its very common to have more than one application in one process. So that restricts the usefulness of the PrivateMemorySize64. The GC.GetTotalMemory is per app domain afaik.
How to get the total allocated memory by an (ASP).NET app programatically?
[ "", "c#", ".net", "asp.net", "memory", "" ]
I have a DropDownList populated from a LINQ query. As per the design requirements of this project, I need to append 4 " " to the DDL's ListItem.Text. It works when I add the ListItems manually like so: ``` <asp:ListItem Value="NULL">&nsbp;&nsbp;&nsbp;&nsbp;Select One</asp:ListItem> ``` but not when I DataBind() and use: ``` DataTextFormatString = "&nsbp;&nsbp;&nsbp;&nsbp;{0}"; ``` Any help is appreciated. AND: Before someone says something about the HTML code, I had to call it a "&nsbp" since it wouldn't allow me to use Non-Breaking Space char code. Thanks!
The only thing that I can think to do is sub-class the dropdownlist control and override the render method and see if you can't circumvent the trimming that the base dropdownlist control is doing on its items collection. If sub-classing is too much work, then use some client side Javascript code to update those items upon page load. This would be a snap with JQuery. I hope that helps.
``` DropDownList ddl = new DropDownList(); ddl.Items.Add(new ListItem(Server.HtmlDecode("& n b s p;&n b s p ;& n b s p ;&n bs p;abc"), "abc")); ``` Hope this helps ! **Note :** remove the spaces between characters..
Adding html in DataTextFormatString
[ "", "c#", "html", "data-binding", "string-formatting", "" ]
I have a situation where I need to do an update on a very large set of rows that I can only identify by their ID (since the target records are selected by the user and have nothing in common other than it's the set of records the user wanted to modify). The same property is being updated on all these records so I would I like to make a single UPDATE call. Is it bad practice or is there a better way to do this update than using "WHERE IN (1,2,3,4,.....10000)" in the UPDATE statement? Would it make more sense to use individual update statements for each record and stick them into a single transaction? Right now I'm working with SQL Server and Access but,if possible, I'd like to hear more broad best-practice solutions across any kind of relational database.
I would always use ``` WHERE id IN (1,2,3,4,.....10000) ``` unless your in clause was **stupidly** large, which shouldn't really happen from user input. edit: For instance, Rails does this a lot behind the scenes It would definitely not be better to do separate update statements in a single transaction.
Another alternative is to store those numbers in a temp table and use it in a join to do the update. If you are able to execute a single update statement is definitely better than executing one statement per record.
Using "IN" in a WHERE clause where the number of items in the set is very large
[ "", "sql", "sql-server", "ms-access", "" ]
It's time to implement sorting on my blog-like web application. In addition to browsing by creation date, I want users to be able to sort by the number of replies, too. Given that I have two tables blog\_posts and replies, and that replies has a field called blog\_post\_id (a foreign key for the blog\_post it's a reply to), how do I write this query? "Select the 30 blog posts with the most replies, sorted by the number of replies for each blog post in descending order." I also want to paginate this. Will it be hard to get the next 30, the next 30, etc.? My feeling is that this isn't too hard to do with SQL, I just don't know how to do it (still learning).
This should do the trick: ``` SELECT blog_posts.*, count(replies.blog_post_id) as blog_replies FROM blog_posts LEFT JOIN replies ON replies.blog_post_id = blog_posts.id GROUP BY blog_posts.id ORDER BY blog_replies DESC ``` You could tack on a LIMIT and OFFSET clause at the end to get the paging working.
I don't have a copy of MySQL locally that I can mess around with, but you could do something like this: ``` SELECT blog_post.id, [other relevant fields from blog_post], (SELECT COUNT(*) FROM replies WHERE blog_post_id = blog_post.id) 'replies' FROM blog_post ORDER BY FIELD('replies') ``` Not sure if the order by field will work with a sub query, but it's worth a shot. Good luck! Ian
Writing a query ordered by the number of associations between objects
[ "", "sql", "mysql", "database", "" ]
This is my first stackoverflow question, so try to be nice. ;-D My issue is this, I am refactoring some existing javascript code and using jQuery to do it. In several places I've come across javascript code similar to the following: ``` // some js code working with the customAttribute value javascriptElementObject.customAttribue = void(0); ``` The javascriptElementObject is now a jQuery object and I have been attempting to use the following code to do the same thing: ``` // some js code working with the customAttribute value javascriptElementObject.attr("customAttribute", void(0)); ``` However, this does not seem to be doing anything. The following code works however: ``` javascriptElementObject.get(0).customAttribute = void(0); ``` I'm aware of jQuery's removeAttr() function, but have not used it so far because I don't know if it's equivalent to setting the attribute value to void(0). So I guess that really means I have 2 questions: 1. Why doesn't the first jQuery version work? 2. Are .get(0).customAttribue = void(0); and .removeAttr("customAttribute); equivalent? Thanks.
jQuery likes to overload its methods so: ``` obj.attr( name ) //retrieves the attribute value obj.attr( name, value ) //sets the attribute obj.attr( name, void(0) ) == obj.attr( name, null ) == obj.attr( name ) //i.e retrieving the attribute ``` You might want to try the following if you want to set an empty attribute ``` obj.attr( name, '' ) ``` This will also apply to other methods `jQuery.html()` for example
What are you trying to accomplish? If the goal is to remove the value in the name/value pair, you might as well just remove the attribute entirely. I'm not aware of any intrinsic value in maintaining an attribute that has no value; in less standards-compliant browsers it may even cause a problem. In general, the syntax of $(selector).attr(name, value) and $(selector).removeAttr(name) work very well (at least I've never seen it fail.) If you're trying to use void(0) to keep A HREFs from firing you'd be better off using a "return false" as the click event on those A tags.
jQuery 1.3 - Issue with Setting an Attribute Value
[ "", "javascript", "jquery", "attributes", "" ]
I'm trying to split text in a `JTextArea` using a regex to split the String by `\n` However, this does not work and I also tried by `\r\n|\r|n` and many other combination of regexes. Code: ``` public void insertUpdate(DocumentEvent e) { String split[], docStr = null; Document textAreaDoc = (Document)e.getDocument(); try { docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset()); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } split = docStr.split("\\n"); } ```
This should cover you: ``` String lines[] = string.split("\\r?\\n"); ``` There's only really two newlines (UNIX and Windows) that you need to worry about.
[`String#split​(String regex)`](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#split(java.lang.String)) method is using regex (regular expressions). Since Java 8 regex supports `\R` which represents (from [documentation of Pattern class](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)): > **Linebreak matcher** > \R         Any Unicode linebreak sequence, is equivalent to > `\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]` So we can use it to match: * `\u000D\000A` -> `\r\n` pair * [\u000A](http://www.fileformat.info/info/unicode/char/000a/index.htm) -> line feed (`\n`) * [\u000B](http://www.fileformat.info/info/unicode/char/000b/index.htm) -> line tabulation (DO NOT confuse with [character tabulation `\t` which is `\u0009`](http://www.fileformat.info/info/unicode/char/0009/index.htm)) * [\u000C](http://www.fileformat.info/info/unicode/char/000c/index.htm) -> form feed (`\f`) * [\u000D](http://www.fileformat.info/info/unicode/char/000d/index.htm) -> carriage return (`\r`) * [\u0085](http://www.fileformat.info/info/unicode/char/0085/index.htm) -> next line (NEL) * [\u2028](http://www.fileformat.info/info/unicode/char/2028/index.htm) -> line separator * [\u2029](http://www.fileformat.info/info/unicode/char/2029/index.htm) -> paragraph separator As you see `\r\n` is placed at start of regex which ensures that regex will try to match this *pair* first, and only if that match fails it will try to match *single character* line separators. --- So if you want to split on line separator use `split("\\R")`. If you [don't want to remove from resulting array trailing empty strings `""`](https://stackoverflow.com/questions/14602062/java-string-split-removed-empty-values) use `split(regex, limit)` with negative `limit` parameter like `split("\\R", -1)`. If you want to treat one or more continues empty lines as single delimiter use `split("\\R+")`.
Split Java String by New Line
[ "", "java", "regex", "split", "newline", "" ]
I have a method like this: ``` public static <T> boolean isMemberOf(T item, T[] set) { for (T t : set) { if (t.equals(item)) { return true; } } return false; } ``` Now I try to call this method using a `char` for `T`: ``` char ch = 'a'; char[] chars = new char[] { 'a', 'b', 'c' }; boolean member = isMemberOf(ch, chars); ``` This doesn't work. I would expect the `char` and `char[]` to get autoboxed to `Character` and `Character[]`, but that doesn't seem to happen. Any insights?
There is no autoboxing for arrays, only for primitives. I believe this is your problem.
Why would `char[]` be boxed to `Character[]`? Arrays are *always* reference types, so no boxing is required. Furthermore, it would be hideously expensive - it would involve creating a new array and then boxing each char in turn. Yikes!
Java: Array of primitive data types does not autobox
[ "", "java", "generics", "autoboxing", "" ]
I'm new to web services and as an introduction I'm playing around with the Twitter API using the Twisted framework in python. I've read up on the different formats they offer, but it's still not clear to me which one I should use in my fairly simple project. Specifically the practical difference between using JSON or XML is something I'd like guidance on. All I'm doing is requesting the public timeline and caching it locally. Thanks.
For me it boils down to convenience. Using XML, I have to parse the response in to a DOM (or more usually an ElementTree). Using JSON, one call to simplejson.loads(json\_string) and I have a native Python data structure (lists, dictionaries, strings etc) which I can start iterating over and processing. Anything that means writing a few less lines of code is usually a good idea in my opinion. I often use JSON to move data structures between PHP, Python and JavaScript - again, because it saves me having to figure out an XML serialization and then parse it at the other end. And like jinzo said, JSON ends up being slightly fewer bytes on the wire. You might find my blog entry on JSON from a couple of years ago useful: <http://simonwillison.net/2006/Dec/20/json/>
RSS and Atom are XML formats. JSON is a string which can be evaluated as Javascript code.
What is the practical difference between xml, json, rss and atom when interfacing with Twitter?
[ "", "python", "xml", "json", "twitter", "twisted", "" ]
What I want to achieve is very simple: I have a Windows Forms (.NET 3.5) application that uses a path for reading information. This path can be modified by the user, by using the options form I provide. Now, I want to save the path value to a file for later use. This would be one of the many settings saved to this file. This file would sit directly in the application folder. I understand three options are available: * ConfigurationSettings file (appname.exe.config) * Registry * Custom XML file I read that the .NET configuration file is not foreseen for saving values back to it. As for the registry, I would like to get as far away from it as possible. Does this mean that I should use a custom XML file to save configuration settings? If so, I would like to see code example of that (C#). I have seen other discussions on this subject, but it is still not clear to me.
If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist. Use the Settings tab to create application settings. Visual Studio creates the files `Settings.settings` and `Settings.Designer.settings` that contain the singleton class `Settings` inherited from [ApplicationSettingsBase](http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx). You can access this class from your code to read/write application settings: ``` Properties.Settings.Default["SomeProperty"] = "Some Value"; Properties.Settings.Default.Save(); // Saves settings in application configuration file ``` This technique is applicable both for console, Windows Forms, and other project types. Note that you need to set the *scope* property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only. Reference: [How To: Write User Settings at Run Time with C#](https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-write-user-settings-at-run-time-with-csharp) - Microsoft Docs
If you are planning on saving to a file within the same directory as your executable, here's a nice solution that uses the [JSON](http://en.wikipedia.org/wiki/JSON) format: ``` using System; using System.IO; using System.Web.Script.Serialization; namespace MiscConsole { class Program { static void Main(string[] args) { MySettings settings = MySettings.Load(); Console.WriteLine("Current value of 'myInteger': " + settings.myInteger); Console.WriteLine("Incrementing 'myInteger'..."); settings.myInteger++; Console.WriteLine("Saving settings..."); settings.Save(); Console.WriteLine("Done."); Console.ReadKey(); } class MySettings : AppSettings<MySettings> { public string myString = "Hello World"; public int myInteger = 1; } } public class AppSettings<T> where T : new() { private const string DEFAULT_FILENAME = "settings.json"; public void Save(string fileName = DEFAULT_FILENAME) { File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(this)); } public static void Save(T pSettings, string fileName = DEFAULT_FILENAME) { File.WriteAllText(fileName, (new JavaScriptSerializer()).Serialize(pSettings)); } public static T Load(string fileName = DEFAULT_FILENAME) { T t = new T(); if(File.Exists(fileName)) t = (new JavaScriptSerializer()).Deserialize<T>(File.ReadAllText(fileName)); return t; } } } ```
How can I save application settings in a Windows Forms application?
[ "", "c#", "xml", "winforms", "configuration-files", "application-settings", "" ]
I'm currently in the process of learning C++, and because I'm still learning, I keep making mistakes. With a language as permissive as C++, it often takes a long time to figure out exactly what's wrong -- because the compiler lets me get away with a lot. I realize that this flexibility is one of C++'s major strengths, but it makes it difficult to learn the basic language. Is there some tool I can use to analyze my code and make suggestions based on best practices or just sensible coding? Preferably as an Eclipse plugin or linux application.
Enable maximum compiler warnings (that's the `-Wall` option if you're using the Gnu compiler). 'Lint' is the archetypical static analysis tool. `valgrind` is a good run-time analyzer.
I think you'd better have some lectures about good practices and why they are good. That should help you more than a code analysis tool (in the beginning at least). I suggest you read the series of [**Effective C++**](https://rads.stackoverflow.com/amzn/click/com/0201924889) and \*\*[Effective STL](https://rads.stackoverflow.com/amzn/click/com/0201749629) books, at least. See alsot [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)
C++ code analysis tools
[ "", "c++", "code-analysis", "" ]
The indexer into `Dictionary` throws an exception if the key is missing. Is there an implementation of `IDictionary` that instead will return `default(T)`? I know about the `TryGetValue()` method, but that's impossible to use with LINQ. Would this efficiently do what I need?: ``` myDict.FirstOrDefault(a => a.Key == someKeyKalue); ``` I don't think it will as I think it will iterate the keys instead of using a Hash lookup.
Indeed, that won't be efficient at all. As per comments, in .Net Core 2+ / NetStandard 2.1+ / Net 5, [MS added the extension method `GetValueOrDefault()`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.getvalueordefault?view=netstandard-2.1) For earlier versions you can write the extension method yourself: ``` public static TValue GetValueOrDefault<TKey,TValue> (this IDictionary<TKey, TValue> dictionary, TKey key) { TValue ret; // Ignore return value dictionary.TryGetValue(key, out ret); return ret; } ``` Or with C# 7.1: ``` public static TValue GetValueOrDefault<TKey,TValue> (this IDictionary<TKey, TValue> dictionary, TKey key) => dictionary.TryGetValue(key, out var ret) ? ret : default; ``` That uses: * An expression-bodied method (C# 6) * An out variable (C# 7.0) * A default literal (C# 7.1)
If you're using .NET Core 2 or above (C# 7.x), the [CollectionExtensions](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions?view=netcore-2.2) class is introduced and you can use the [GetValueOrDefault](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.getvalueordefault?view=netcore-2.2#System_Collections_Generic_CollectionExtensions_GetValueOrDefault__2_System_Collections_Generic_IReadOnlyDictionary___0___1____0_) method to get default value if key is not there in a dictionary. ``` Dictionary<string, string> colorData = new Dictionary<string, string>(); string color = colorData.GetValueOrDefault("colorId", string.Empty); ```
Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?
[ "", "c#", ".net", "hash", "dictionary", "" ]
Working with a program that uses 16bytes 4v4 one byte matrices : ``` unsigned char matrix[4][4]; ``` and a few 256bytes 16v16 one byte matrices: ``` unsigned char bigMatrix[16][16]; ``` Very often due to data manipulation I am forced to loop column wise in the program making cache misses. Will the performance improve if I use an array instead, i.e. ``` unsigned char matrix[16]; unsigned char matrix[256]; ``` and access the elements by using some variables to retrieve elements, i.e. ``` matrix[variableA*variableB + i]; ``` where variableA\*variableB+i needs to be recalculated every time I want to access an element. I only want speed optimization and memory is of no problem. Will this help, as in give some performance hit or loss, or is the difference too small to even care ?
It makes no difference. The data is laid out in the exact same way in either case, and is accessed in the same way too. I'd be surprised if it didn't generate exactly the same assembly, even. However, with a 256byte table, you're unlikely to get cache misses in any case. The CPU's L1 cache is typically between 32 and 128KB, so I doubt you're getting many cache misses in any case.
jalf is mostly right. L1 cache is divided up into chunks, the size of the chunks is dependant on the processor but is in the order of 32 bytes. So, if you were stepping through memory a byte at a time, you'd get a cache miss every 32 bytes (or whatever the chunk size is). Now, the Intel chip is quite clever here and can detect sequential reads and prefetch the data reducing the impact of a cache miss. The 4x4 matrix is highly likely to reside in a single L1 chunk (or cache line), so accessing it by row or by column makes little difference. Of course, you don't want to split the matrix across two cache lines, so well aligned memory is important. The 16x16 matrix, however, won't fit in a cache line. So, if you're skipping through the array processing columns you're going to get lots of cache misses. The computation of the index, as jalf said, makes little difference as the ratio between CPU and memory is high (i.e. you can do a lot of CPU work for each cache miss). Now, if you are mainly processing the matrix in a column orientated way, then your best option is to transpose all your matrices (swap rows with columns), thus your memory accesses will be more sequential and the number of cache misses will be reduced and the CPU will be able to prefetch data better. So, instead of organising the matrix like this: ``` 0 1 2 .... 15 16 17 18 .... 31 .... 240 241 242 .... 255 ``` where the number is the memory offset from the start of the matrix, organise thus: ``` 0 16 32 ... 240 1 17 33 ... 241 ... 15 31 47 ... 255 ```
C/C++ optimize data structures, array of arrays or just array
[ "", "c++", "c", "arrays", "" ]
I'm trying to look at the best way of changing the value of an element in XML. ``` <MyXmlType> <MyXmlElement>Value</MyXmlElement> </MyXmlType> ``` What is the easiest and/or best way to change "Value" in C#? I've looked at XMLDocument and it will cause a load of the whole XML document to memory. Could you do it safely with the XMLReader. The problem is changing the value and emitting it back seems like an interesting conundrum. Cheers :D
You could use the System.Xml.Linq namespace stuff for the easiest to read code. This will load the full file into memory. ``` XDocument xdoc = XDocument.Load("file.xml"); var element = xdoc.Elements("MyXmlElement").Single(); element.Value = "foo"; xdoc.Save("file.xml"); ```
EDIT: didn't see your clause about XmlDocument. XmlReader does just that. You can't edit xml files with this class. You want XmlWriter. However, in case it's still helpful, here's the code for XmlDocument. ``` private void changeXMLVal(string element, string value) { try { string fileLoc = "PATH_TO_XML_FILE"; XmlDocument doc = new XmlDocument(); doc.Load(fileLoc); XmlNode node = doc.SelectSingleNode("/MyXmlType/" + element); if (node != null) { node.InnerText = value; } else { XmlNode root = doc.DocumentElement; XmlElement elem; elem = doc.CreateElement(element); elem.InnerText = value; root.AppendChild(elem); } doc.Save(fileLoc); doc = null; } catch (Exception) { /* * Possible Exceptions: * System.ArgumentException * System.ArgumentNullException * System.InvalidOperationException * System.IO.DirectoryNotFoundException * System.IO.FileNotFoundException * System.IO.IOException * System.IO.PathTooLongException * System.NotSupportedException * System.Security.SecurityException * System.UnauthorizedAccessException * System.UriFormatException * System.Xml.XmlException * System.Xml.XPath.XPathException */ } } ```
Best way to change the value of an element in C#
[ "", "c#", ".net", "xml", "" ]
I have a COM Callable Wrapper that I'm using from a VB6 program, but the program won't receive COM events unless the CCW is registered. Otherwise, the CCW works fine, just no events until I remove the program's manifest file and register the CCW using "regasm /tlb /codebase theccw.dll". This is in WinXP SP3. What could be the problem? Maybe my CCW is built wrong for use as an "early bound" VB6 object. Here are my declarations: ``` [ComVisible(false)] public delegate void AnEventDelegate(int arg1); [ ComVisible(true), GuidAttribute("XXXX-XXXX-XXXX-XXXX"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch) ] public interface IComEvents { void AnEvent(int arg1); } [ ComVisible(true), Guid("YYYY-YYYY-YYYY-YYYY"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(IComEvents)) ] public class TheComClass: IComContract { public TheComClass(){} // Implicit implementation of IComContract. // Implicit implementation of IComEvents. // // eg. public event AnEventDelegate AnEvent; } [ ComVisible(true), Guid("ZZZZ-ZZZZ-ZZZZ-ZZZZ") ] public interface IComContract { [ComVisible(true)] string AProp{ get; set; } [ComVisible(true)] void AMethod(); } ``` One thing I just realized. I don't have [ComVisible(true)] attributes on my public event declarations inside of TheComClass. I don't think that's the problem because I do get the events when the thing is registered, but we'll see...
The only answer that I found is that this doesn't work and I must register the CCW.
In COM events aren't early bound. Where events in .NET are just a specialised usage of the delegates and are ultimately just function calls, COM events are much more involved. You will need the component registered for events to work.
.Net CCW no events with registration-free COM!
[ "", "c#", ".net", "com", "interop", "regfreecom", "" ]
Have read through the [MSDN naming guidelines](http://msdn.microsoft.com/en-us/library/ms229002.aspx) and could not find a clear answer, other than that you should try to avoid underscores in general. Let's say I have the following: ``` public class Employee { private string m_name; //to store property value called Name public string Name { get { return m_name; } set { m_name = value; } } public void ConvertNameToUpper() { //by convention should you use this return m_name.ToUpper(); //or this return Name.ToUpper(); } } ``` **What is the proper naming convention for m\_name in the above?** For example, in code I inherit I commonly see: * m\_name * \_name * name * myName or some other random identifier Which one (or another) is most commonly accepted? **As a follow-up, in the methods of the class, do you refer to the internal (private) identifier or to the public property accessor?**
I think that, whatever naming convention you use, the most important thing is that you stay consistent. I mean, if you choose to name private members like \_name , then always do it like this instead of once using \_name, and the other time m\_name. I personally use the underscore-prefix convention. (one of the reasons is because I use NHibernate, and NHibernate has a 'field.camelcase-underscore' access strategy. For your other question: It depends on what you want to do. Does your property contain extra logic, and do you want this logic to be executed when you refer it ? Then use the property. You don't want to execute the logic ? Use the field. Eric Lippert has written a [post](http://blogs.msdn.com/ericlippert/archive/2009/01/14/automatic-vs-explicit-properties.aspx) regarding this on his weblog. For your folluw-up: it all depends on the situation. If your property contains some additional logic, and you don't want to execute that additional logic when accessed from within the class, then use the backing field ...
First of all - for the simple get/set cases I would recommend that you use automatically implemented properties. If you do that the compiler will generate the underlying variable, and you only reference the property itself. Other than that, I suggest you pick one of the above or anything similar and just stick to that. The company I work for uses vName where the "v" indicates that this is the value of the property.
In C#, what is the generally accepted way to refer to member properties within the class?
[ "", "c#", "naming-conventions", "class-design", "" ]
I have a template class, C\_Foo<T>, which is specialised in a number of ways. ``` struct Bar_Base { ... }; struct Bar_1 : public Bar_Base { ... }; struct Bar_2 : public Bar_Base { ... }; struct Bar_3 : public Bar_Base { ... }; class C_Foo<T> { ... }; class C_Foo_1 : public C_Foo<Bar_1> { ... }; class C_Foo_2 : public C_Foo<Bar_2> { ... }; class C_Foo_3 : public C_Foo<Bar_3> { ... }; ``` And instantiations as follows: ``` C_Foo_1 foo1; C_Foo_2 foo2; C_Foo_3 foo3; ``` I have a set of common operations, all of which are defined on C\_Foo, that I want to perform on foo1, foo2, and foo3. I've tried the following: ``` vector<C_Foo *> v; v.push_back(&foo1); v.push_back(&foo2); v.push_back(&foo3); ``` But I get compile errors, presumably because the compiler isn't sure how to go from a C\_Foo\_1 to a C\_Foo. Is it possible to do something like this? I want to be able to loop through foo1 .. fooN and perform the same operations on all of them, without having to copy and paste boilerplate code like so: ``` foo1.do_stuff(); foo2.do_stuff(); foo3.do_stuff(); ``` Thanks for your help.
You can do that, if the function does not depend on the template parameter: ``` // note: not a template class C_Foo_Common { public: virtual void do_stuff() = 0; }; template<typename T> class C_Foo : public C_Foo_Common { virtual void do_stuff() { // do stuff... } }; vector<C_Foo_Common *> v; v.push_back(&foo1); v.push_back(&foo2); v.push_back(&foo3); // now, you can iterate and call do_stuff on them. ``` But if the function in C\_Foo\_Common needs to know the type `T` (for example to have another return type that depends on T), then that's not possible anymore. `C_Foo<Bar_1>` is a different type than `C_Foo<Bar_2>`. You can use discriminated unions instead. Those keep track about what is stored in them and are completely generic: ``` typedef boost::variant< C_Foo<Bar_1>*, C_Foo<Bar_2>*, C_Foo<Bar_3>* > variant_type; vector<variant_type> v; v.push_back(&foo1); v.push_back(&foo2); v.push_back(&foo3); ``` The variant knows what it stores, and can call functions overloaded on the types of what can be stored in it. Read the documentation of [`boost::variant`](http://www.boost.org/doc/libs/1_37_0/doc/html/variant.html) for more information on how to get at what the variants contain.
The problem is that `C_Foo` cannot be instantiated because it requires template parameters. You can make another base class, and have your set of common operations within that: ``` class C_FooBase { ... }; template<typename T> class C_Foo<T> : public C_FooBase { ... }; class C_Foo_1 : public C_Foo<Bar_1> { ... }; class C_Foo_2 : public C_Foo<Bar_2> { ... }; class C_Foo_3 : public C_Foo<Bar_3> { ... }; ```
Adding C++ template classes to a list
[ "", "c++", "templates", "" ]
Do you think C# TCP/UDP socket use in the managed application can handle (roughly) same amount of data as native C++ version? If not, what is data amount we shall consider native or c# is better to use and what is the biggest obstacle in the implementation on managed side?
It is my experience that the network speed and latency are bigger factors in regards to performance than managed or unmanaged code. Actually that is the same in regards to database access.
The answer must depend, to some extent, on the hardware. I suggest that you write little prototype programs, to experiment.
Is there performance penalty on managed code when reading/writing high data volume on TCP/UDP socket compare to unmanaged code?
[ "", "c#", "performance", "tcp", "sockets", "unmanaged", "" ]
I have a vb project which calls functions in a dll. The dll is created in a separate vs project (portaudio), which is written in c. The dll c project compiles clean and builds the required dll, which I am currently dropping in c:\windows\system to vb runtime can see it. VB Project lives in c:\devprojects\vbtest C Project lives in c:\devprojects\portaudio with the project file in c:\devprojects\portaudio\build\msvc. Dll created in Win32\debug under this msvc directory. When I call the dll function, is it possible for the vs debugger to step through the c function in the dll - I have all the code etc, but I don't know if VS2005 supports this kind of mixed language debugging. If this is possible, could you advise how I should set up my Visual Studio to achieve this. Many thanks David
It is not necessary to have both projects in the same solution, but you should compile both projects with debug symbols enabled. Now in your VB net solution Project/Properties, in the Debug tab make sure that "Enable unmanaged code debugging" is checked. Also make sure that the dll loaded is in the same place where it was compiled, else it may not found the pdb where the debug symbols are stored.
If its VB.NET then this is very easy, just set up a solution with both projects under it, set up their dependencies and ensure that on build the debug version of the VB project links to the debug lib/dll produced from your C++ project. Visual Studio does the rest. I've done this before a couple of times with C# applications calling a C++ dll. I didn't intend to set this up, but tried stepping through whilst debugging assuming I would get the assembly listing and could at least work out somethig of what was going wrong with my code... however it loaded the correct .cpp file and allowed me to continue stepping through that code.
Visual Studio 2005 VB debugging with c++ dll - Mixed Language debugging
[ "", "c++", "debugging", "visual-studio-2005", "mixed", "" ]
I am trying to find a way to query rows of data by using a "multivalue" pipe delimited column in another table as a WHERE clause. SQL SERVER 2005 This is my best description of the problem: Imagine a pipe delimited column set to a variable like @LIST = 'Bob|Mary|Joe' then I am trying to find a match like this ``` Select * from Users where FirstName = 'Joe' ``` but extended to be ``` Select * from Users where FirstName "IS CONTAINED IN" @List ``` which would return all the Bob, Mary and Joe entries. Thanks for your help.
You can use a split udf and join it to your main query. see this [link](http://www.sqlmag.com/Article/ArticleID/21071/sql_server_21071.html) for the code and an example. Your query would end up looking like this. This is untested but hopefully this points you in the right direction. ``` Select A.* from Users A JOIN dbo.Fn_Split(@ValueArrayString, '|') B on A.FirstName = B.value ```
How about ``` Select * from Users where CHARINDEX(FirstName + '|', @List + '|') > 0 ``` A little annoying that you have to append the pipe delimiter to both strings, but it works, and it's probably faster than a function.
T-SQL Pattern matching
[ "", "sql", "t-sql", "pattern-matching", "sql-like", "" ]
I've got a base class which is compatible with XML serialization and a derived class which implements IXmlSerializable. In this example, the base class does implement IXmlSerializable: ``` using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace XmlSerializationDerived { public class Foo { public int fooProp; public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { fooProp = int.Parse (reader.ReadElementString ("fooProp")); } public void WriteXml(XmlWriter writer) { writer.WriteElementString ("fooProp", fooProp.ToString ()); } } public class Bar : Foo, IXmlSerializable { public new void ReadXml(XmlReader reader) { base.ReadXml (reader); } public new void WriteXml(XmlWriter writer) { base.WriteXml (writer); } static void Main(string[] args) { StringBuilder sb = new StringBuilder (); XmlWriter writer = XmlWriter.Create (sb); Bar bar = new Bar (); bar.fooProp = 42; XmlSerializer serializer = new XmlSerializer (typeof (Bar)); serializer.Serialize (writer, bar); Debug.WriteLine (sb.ToString ()); } } } ``` This produces this output: ``` <?xml version="1.0" encoding="utf-16"?><Bar><fooProp>42</fooProp></Bar> ``` However, i'd like to use a base class which does **not** implement IXmlSerializable. This prevents using `base.Read/WriteXml`. The result will be: ``` <?xml version="1.0" encoding="utf-16"?><Bar /> ``` Is there any way to still get the desired result?
" This prevents using base.Read/WriteXml." Typically, if the base-class implemented `IXmlSerializable`, you might make it a `virtual` method so that the concrete version is used. Typically, you'd also use explicit implementation (rather than public properties) - perhaps with some `protected virtual` methods for the implementation details (although keeping track of where the reader/writer is across different classes would be a nightmare). AFAIK, there is no way to re-use `XmlSerializer` to write the *base* bits, while you add the *derived* bits. `IXmlSerializable` is all-or-nothing.
Improving mtlung's answer, why don't you use XmlSerializer? You can tune up your class with attribute so it can be serialized the way you want, and it's pretty simple to do. ``` using System.Xml.Serialization; ... [XmlRoot("someclass")] public class SomeClass { [XmlAttribute("p01")] public int MyProperty01 { get { ... } } [XmlArray("sometypes")] public SomeType[] MyProperty02 { get { ... } } [XmlText] public int MyProperty03 { get { ... } } public SomeClass() { } } ``` Then, serializing and deserializing it would be pretty simple: ``` void Save(SomeClass obj) { XmlSerializer xs = new XmlSerializer(typeof(SomeClass)); using (FileStream fs = new FileStream("c:\\test.xml", ...)) { xs.Serialize(fs, obj); } } void Load(out SomeClass obj) { XmlSerializer xs = new XmlSerializer(typeof(SomeClass)); using (FileStream fs = new FileStream("c:\\test.xml", ...)) { obj = xs.Deserialize(fs); } } ``` And the resulting XML would be something like this: ``` <someclass p01="..."> <sometype> <!-- SomeType serialized objects as child elements --> </sometype> # value of "MyProperty03" as text # </someclass> ``` This method works better with "POCO" classes, and it's simple and clean. You don't even have to use the attributes, they are there to help you customize the serialization.
C# Xml-Serializing a derived class using IXmlSerializable
[ "", "c#", "xml", "serialization", "" ]
I am looking for constant time algorithm can change an ordered integer index value into a random hash index. It would nice if it is reversible. I need that hash key is unique for each index. I know that this could be done with a table look up in a large file. I.E. create an ordered set of all ints and then shuffle them randomly and write to a file in random sequence. You could then read them back as you need them. But this would require a seek into a large file. I wonder if there is a simple way to use say a pseudo random generator to create the sequence as needed? [Generating shuffled range using a PRNG rather than shuffling](https://stackoverflow.com/questions/464476/generating-shuffled-range-using-a-prng-rather-than-shuffling) the [answer](https://stackoverflow.com/questions/464476/generating-shuffled-range-using-a-prng-rather-than-shuffling/515755#515755) by [erikkallen](https://stackoverflow.com/users/47161/erikkallen) of Linear Feedback Shift Registers looks like the right sort of thing. I just tried it but it produces repeats and holes. Regards David Allan Finch
The question is now if you need a really random mapping, or just a "weak" permutation. Assuming the latter, if you operate with unsigned 32-bit integers (say) on 2's complement arithmetics, multiplication by any odd number is a bijective and reversible mapping. Of course the same goes for XOR, so a simple pattern which you might try to use is e.g. ``` unsigned int hash(int x) { return (((x ^ 0xf7f7f7f7) * 0x8364abf7) ^ 0xf00bf00b) * 0xf81bc437; } ``` There is nothing magical in the numbers. So you can change them, and they can be even randomized. The only thing is that the multiplicands must be odd. And you must be calculating with rollaround (ignoring overflows). This can be inverted. To do the inversion, you need to be able to calculate the correct complementary multiplicands A and B, after which the inversion is ``` unsigned int rhash(int h) { return (((x * B) ^ 0xf00bf00b) * A) ^ 0xf7f7f7f7; } ``` You can calculate A and B mathematically, but the easier thing for you is just to run a loop and search for them (once offline, that is). The equation uses XORs mixed with multiplications to make the mapping nonlinear.
You could try building a suitable [Feistel network](http://en.wikipedia.org/wiki/Feistel_cipher). These are normally used for cryptography (e.g. DES), but with at least 64 bits, so you may need to build one yourself that suits your needs. They are invertible by construction.
Looking for a Hash Function /Ordered Int/ to /Shuffled Int/
[ "", "c++", "algorithm", "hash", "" ]
I have a page that is pulling in via an iframe a page of html content from a pre-existing content management system, whose content I can not directly change. I want to use jquery to alter some of the links and button locations dynamically. For links within the page I was able to change the href attr values of ``` <a href="/content.asp">more</a> ``` from content.asp to content2.asp using ``` $("a[href^='/content.asp']") .each(function() { this.href = this.href.replace("content.asp", "content2.asp"); }); ``` But the page pulled in also has form buttons that contains javascript onclick functions e.g. ``` <INPUT type="button" value="Add to basket" onClick="document.location='/shopping-basket.asp?mode=add&id_Product=1076';"> ``` I basically want to use jquery to select any such buttons and change the shopping-basket.asp to shopping-basket2.asp How can I select these buttons/onclick functions and change the location string?
Not very proud of this solution, but it works.... ``` var getid = /id_Product=(\d+)/; $('input[type="button"]').each(function() { var onclick = String(this.onclick); var id = onclick.match(getid); if(id) { this.onclick = function() { window.location = "/shopping-basket2.asp?mode=add&id_Product=" + id[1]; }; } }); ```
<http://docs.jquery.com/Selectors/attributeContains#attributevalue> ``` $("input[onClick*='shopping-basket.asp']").each( ... ) ```
Change the value of an existing onclick function
[ "", "javascript", "jquery", "" ]
I am working to improve performance of a function that takes an XML string and replaces certain characters (encoding) before returning the string. The function gets pounded, so it is important to run as quickly as possible. The USUAL case is that none of the characters are present - so I would like to especially optimize for that. As you will see in the sample code, the strings to be replaced are short, and relatively few. The source strings will often be short (e.g. 10-20 characters) but could be longer (e.g. 200 characters or so). So far I have ensured that the regexes are precompiled and I've eliminated nested functions which slowed down operation (partial milliseconds matter at this point.) ``` var objXMLToString = new XMLToStringClass(); function XMLToStringClass(){ this.tester= /\\34|\\39|\\62|\\60|\\13\\10|\\09|\\92|&amp/; this.replacements=[]; var self=this; function init(){ var re = new regexReplacePair(/\\34/g,'"'); self.replacements.push(re); re = new regexReplacePair(/\\39/g,"'"); self.replacements.push(re); re = new regexReplacePair(/\\62/g,">"); self.replacements.push(re); re = new regexReplacePair(/\\60/g,"<"); self.replacements.push(re); re = new regexReplacePair(/\\13\\10/g,"\n"); self.replacements.push(re); re = new regexReplacePair(/\\09/g,"\t"); self.replacements.push(re); re = new regexReplacePair(/\\92/g,"\\"); self.replacements.push(re); re = new regexReplacePair(/\&amp;/g,"&"); self.replacements.push(re); } init(); } function regexReplacePair(regex,replacementString){ this.regex = regex; this.replacement = replacementString; } String.prototype.XMLToString = function() { newString=this; if(objXMLToString.tester.test(this)){ for (var x = 0;x<objXMLToString.replacements.length;x++){ newString=newString.replace(objXMLToString.replacements[x].regex,objXMLToString.replacements[x].replacement); } return newString; } return this; } ``` * Is it possible that in this scenario `String.replace` functions will be better? * Currently I am replacing all characters if a single character matches - is it possible that testing and then conditionally replacing would be better? If so, might `indexOf` be quicker than a regex for this dataset?
I have benchmarked your original version, Ates Gorals hash, my improved hash, a version using switch, and the simple solution. The winner? The simple solution! With matching data (string of 85 chars) ``` original simple hash switch ag-hash FF3 194 188 250 240 424 IE7 188 172 641 906 2203 Chrome1 161 156 165 165 225 Opera9 640 625 531 515 734 ``` With non matching data (string of 85 chars): ``` original simple hash switch ag-hash FF3 39 4 34 34 39 IE7 125 15 125 125 156 Chrome1 45 2 54 54 57 Opera9 156 15 156 156 156 ``` (tested on my window xp laptop, 1.7GHz, ymmv) The simple solution: ``` function XMLToString(str) { return (str.indexOf("\\")<0 && str.indexOf("&")<0) ? str : str .replace(/\\34/g,'"') .replace(/\\39/g,"'") .replace(/\\62/g,">") .replace(/\\60/g,"<") .replace(/\\13\\10/g,"\n") .replace(/\\09/g,"\t") .replace(/\\92/g,"\\") .replace(/\&amp;/g,"&"); } ``` Explanation: First there is a check if there is a backslash or ampersand (it was faster to use indexOf instead of a regexp in all browsers). If there isn't the string is returned untouched, otherwise all the replacements are executed. In this case it don't makes mush difference to cache the regexps. I tried with two arrays, one with the regexps and one with the replacements, but it was not a big difference. In your original version you have a test for all combinations just to detect if you should do the replacements or not. That is expensive since the regexp engine has to compare every position with every combination. I simplified it. I improved Ates Gorals by moving the hash object outside (so it wasn't created and thrown away for every call to the inner function), moving the inner function outside so it can be reused instead of thrown away. *UPDATE 1* Bugfix: moved a parenthesis in the ampersand test. **UPDATE 2** One of your comments made me believe that you encode the string yourself, and if that is the case I suggest that you switch encoding to a standard one, so you can use the built in functions. Instead of "\dd" where dd is a decimal number, use "%xx" where xx is the hexadecimal number. Then you can use the built in decodeURIComponent that is much faster and as a bonus can decode any characters, including unicode. ``` matching non match FF3 44 3 IE7 93 16 Chrome1 132 1 Opera9 109 16 ``` . ``` function XMLToString_S1(str) { return (str.indexOf("%")<0) ? str : decodeURIComponent(str).replace(/\x0D\x0A/g,"\n") } ``` So instead of having a string like "\09test \60\34string\34\62\13\10\" you have a string like "%09test %3c%22string%22%3e%0d%0a".
You can use a hash lookup: ``` str.replace( /(\\34|\\39|\\62|\\60|\\13\\10|\\09|\\92|&amp)/g, function () { return { "\\34": "\"", "\\39": "'", //... "&amp": "&" }[arguments(1)]; } ); ``` Or you insists on extending the prototype: ``` var hash = { "\\34": "\"", "\\39": "'", //... "&amp": "&" }; String.prototype.XMLToString = function () { return this.replace( /(\\34|\\39|\\62|\\60|\\13\\10|\\09|\\92|&amp)/g, function () { return hash[arguments(1)]; } } ); ``` This might be faster (need to benchmark): ``` String.prototype.XMLToString = function () { var s = this; for (var r in hash) { s = s.split(r).join(hash[r]); } return s; ); ``` --- ## Update You can generate your regex from the hash: ``` var arr = []; for (var r in hash) { arr.push(r); } var re = new RegExp("(" + arr.join("|") + ")", "g"); ``` and then use it as: ``` s = s.replace(re, function () { ... }); ```
What is the optimal way to replace a series of characters in a string in JavaScript
[ "", "javascript", "regex", "" ]
Good morning, I am currently writing a python library. At the moment, modules and classes are deployed in an unorganized way, with no reasoned design. As I approach a more official release, I would like to reorganize classes and modules so that they have a better overall design. I drew a diagram of the import dependencies, and I was planning to aggregate classes by layer level. Also, I was considering some modification to the classes so to reduce these dependencies. What is your strategy for a good overall design of a potentially complex and in-the-making python library? Do you have interesting suggestions ? Thanks **Update:** I was indeed looking for a rule of thumb. For example, suppose this case happens (**init**.py removed for clarity) ``` foo/bar/a.py foo/bar/b.py foo/hello/c.py foo/hello/d.py ``` now, if you happen to have d.py importing bar.b and a.py importing hello.c, I would consider this a bad setting. Another case would be ``` foo/bar/a.py foo/bar/baz/b.py foo/bar/baz/c.py ``` suppose that both a.py and b.py import c. you have three solutions: 1) b imports c, a import baz.c 2) you move c in foo/bar. a.py imports c, b.py imports .c 3) you move c somewhere else (say foo/cpackage/c.py) and then both a and b import cpackage.c I tend to prefer 3), but if c.py has no meaning as a standalone module, for example because you want to keep it "private" into the bar package, I would preferentially go for 1). There are many other similar cases. My rule of thumb is to reduce the number of dependencies and crossings at a minimum, so to prevent a highly branched, highly interweaved setup, but I could be wrong.
**"I drew a diagram of the import dependencies, and I was planning to aggregate classes by layer level."** Python must read like English (or any other natural language.) An import is a first-class statement that should have real meaning. Organizing things by "layer level" (whatever that is) should be clear, meaningful and obvious. Do not make arbitrary technical groupings of classes into modules and modules into packages. Make the modules and package obvious and logical so that the list of imports is obvious, simple and logical. **"Also, I was considering some modification to the classes so to reduce these dependencies."** Reducing the dependencies sounds technical and arbitrary. It may not be, but it sounds that way. Without actual examples, it's impossible to say. Your goal is clarity. Also, the module and package are the stand-alone units of reuse. (Not classes; a class, but itself isn't usually reusable.) Your dependency tree should reflect this. You're aiming for modules that can be imported neatly and cleanly into your application. If you have many closely-related modules (or alternative implementations) then packages can be used, but used sparingly. The Python libraries are relatively flat; and there's some wisdom in that. --- **Edit** One-way dependency between layers is an essential feature. This is more about proper software design than it is about Python. You should (1) design in layers, (2) design so that the dependencies are very strict between the layers, and then (3) implement that in Python. The packages may not necessarily fit your layering precisely. The packages may physically be a flat list of directories with the dependencies expressed only via `import` statements.
The question is very vague. You can achieve this by having base/core things that import nothing from the remainder of the library, and concrete implementations importing from here. Apart from "don't have two modules importing from each-other at import-time", you should be fine. module1.py: ``` import module2 ``` module2.py: ``` import module1 ``` This won't work!
How to properly organize a package/module dependency tree?
[ "", "python", "" ]
What is the command to drop all tables in SQLite? Similarly I'd like to drop all indexes.
``` rm db/development.sqlite3 ```
While it is true that there is no DROP ALL TABLES command you can use the following set of commands. **Note:** These commands have the potential to corrupt your database, so make sure you have a backup ``` PRAGMA writable_schema = 1; delete from sqlite_master where type in ('table', 'index', 'trigger'); PRAGMA writable_schema = 0; ``` you then want to recover the deleted space with ``` VACUUM; ``` and a good test to make sure everything is ok ``` PRAGMA INTEGRITY_CHECK; ```
Drop all tables command
[ "", "sql", "sqlite", "rdbms", "database", "" ]
I'm putting together a quick and dirty animation using swing. I would like the window to be maximized. How can I do that?
Provided that you are extending JFrame: ``` public void run() { MyFrame myFrame = new MyFrame(); myFrame.setVisible(true); myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH); } ```
Something like `this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);` ``` import java.awt.*; import javax.swing.*; public class Test extends JFrame { public Test() { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); this.setMaximizedBounds(env.getMaximumWindowBounds()); this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH); } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); Test t = new Test(); t.setVisible(true); } } ```
JFrame Maximize window
[ "", "java", "swing", "maximize-window", "" ]
I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this: ``` -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- ``` I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following: ``` openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); ``` Also, if I'm confused about any terminology, please let me know.
The data between the markers is the base64 encoding of the ASN.1 DER-encoding of a PKCS#8 PublicKeyInfo containing an PKCS#1 RSAPublicKey. That is a lot of standards, and you will be best served with using a crypto-library to decode it (such as M2Crypto as [suggested by joeforker](https://stackoverflow.com/questions/544433/how-do-you-verify-an-rsa-sha1-signature-in-python/546043#546043)). Treat the following as some fun info about the format: If you want to, you can decode it like this: Base64-decode the string: ``` 30819f300d06092a864886f70d010101050003818d0030818902818100df1b822e14eda1fcb74336 6a27c06370e6cad69d4116ce806b3d117534cf0baa938c0f8e4500fb59d4d98fb471a8d01012d54b 32244197c7434f27c1b0d73fa1b8bae55e70155f907879ce9c25f28a9a92ff97de1684fdaff05dce 196ae76845f598b328c5ed76e0f71f6a6b7448f08691e6a556f5f0d773cb20d13f629b6391020301 0001 ``` This is the DER-encoding of: ``` 0 30 159: SEQUENCE { 3 30 13: SEQUENCE { 5 06 9: OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1) 16 05 0: NULL : } 18 03 141: BIT STRING 0 unused bits, encapsulates { 22 30 137: SEQUENCE { 25 02 129: INTEGER : 00 DF 1B 82 2E 14 ED A1 FC B7 43 36 6A 27 C0 63 : 70 E6 CA D6 9D 41 16 CE 80 6B 3D 11 75 34 CF 0B : AA 93 8C 0F 8E 45 00 FB 59 D4 D9 8F B4 71 A8 D0 : 10 12 D5 4B 32 24 41 97 C7 43 4F 27 C1 B0 D7 3F : A1 B8 BA E5 5E 70 15 5F 90 78 79 CE 9C 25 F2 8A : 9A 92 FF 97 DE 16 84 FD AF F0 5D CE 19 6A E7 68 : 45 F5 98 B3 28 C5 ED 76 E0 F7 1F 6A 6B 74 48 F0 : 86 91 E6 A5 56 F5 F0 D7 73 CB 20 D1 3F 62 9B 63 : 91 157 02 3: INTEGER 65537 : } : } : } ``` For a 1024 bit RSA key, you can treat `"30819f300d06092a864886f70d010101050003818d00308189028181"` as a constant header, followed by a 00-byte, followed by the 128 bytes of the RSA modulus. After that 95% of the time you will get `0203010001`, which signifies a RSA public exponent of 0x10001 = 65537. You can use those two values as `n` and `e` in a tuple to construct a RSAobj.
Use [M2Crypto](http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.X509-module.html). Here's how to verify for RSA and any other algorithm supported by OpenSSL: ``` pem = """-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY-----""" # your example key from M2Crypto import BIO, RSA, EVP bio = BIO.MemoryBuffer(pem) rsa = RSA.load_pub_key_bio(bio) pubkey = EVP.PKey() pubkey.assign_rsa(rsa) # if you need a different digest than the default 'sha1': pubkey.reset_context(md='sha1') pubkey.verify_init() pubkey.verify_update('test message') assert pubkey.verify_final(signature) == 1 ```
How do you verify an RSA SHA1 signature in Python?
[ "", "python", "cryptography", "rsa", "sha1", "signature", "" ]
In .Net, I would like to enumerate all loaded assemblies over all AppDomains. Doing it for my program's AppDomain is easy enough `AppDomain.CurrentDomain.GetAssemblies()`. Do I need to somehow access every AppDomain? Or is there already a tool that does this?
**Using Visual Studio** 1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process) 2. While debugging, show the Modules window (Debug > Windows > Modules) This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information). [![enter image description here](https://i.stack.imgur.com/vEhgX.png)](https://i.stack.imgur.com/vEhgX.png) **Using Process Explorer** If you want an external tool you can use the [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) (freeware, published by Microsoft) Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc. **Programmatically** Check [this SO](https://stackoverflow.com/questions/383686/how-do-you-loop-through-currenlty-loaded-assemblies) question that explains how to do it.
Here's what I ended up with. It's a listing of all properties and methods, and I listed all parameters for each method. I didn't succeed on getting all of the values. ``` foreach(System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies()){ System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString()); foreach(Type type in asm.GetTypes()){ //PROPERTIES foreach (System.Reflection.PropertyInfo property in type.GetProperties()){ if (property.CanRead){ Response.Write("<br>" + an.ToString() + "." + type.ToString() + "." + property.Name); } } //METHODS var methods = type.GetMethods(); foreach (System.Reflection.MethodInfo method in methods){ Response.Write("<br><b>" + an.ToString() + "." + type.ToString() + "." + method.Name + "</b>"); foreach (System.Reflection.ParameterInfo param in method.GetParameters()) { Response.Write("<br><i>Param=" + param.Name.ToString()); Response.Write("<br> Type=" + param.ParameterType.ToString()); Response.Write("<br> Position=" + param.Position.ToString()); Response.Write("<br> Optional=" + param.IsOptional.ToString() + "</i>"); } } } } ```
How do I list all loaded assemblies?
[ "", "c#", ".net", "assemblies", "" ]
I am trying to write a function to determine if a file exists. The two methods prove to return inconsistent results (fileExists() seems to provide accurate results, compared to isFileFound(), that returns false positives - i would have expected an exception when trying to create the instance). ``` protected bool isFileFound(string path, string fileName) { System.IO.FileInfo fi = null; bool found = false; try { fi = new System.IO.FileInfo(path + fileName); found = true; } catch (Exception e) { baselogger.Fatal(e.Message + " " + e.StackTrace + " \n" + path + fileName); } return found; } protected bool fileExists(string path, string pattern) { bool success = false; try { success = File.Exists(path + pattern); } catch (Exception e) { baselogger.Warn(e.Message + " " + e.StackTrace + " " + e.Source); } return success; } ``` Neither seems to be able to resolve a UNC path of the following syntax: ***\\abcserver\c$\xyzfolder\foo.bar*** Any idea why the unc path is failing for these methods would be greatly appreciated.
You can create a FileInfo for an non-existing file. But then you can check the FileInfo.Exists property to determine whether the file exists, e.g: ``` FileInfo fi = new FileInfo(somePath); bool exists = fi.Exists; ``` **Update**: In a short test this also worked for UNC paths, e.g. like this: ``` FileInfo fi = new FileInfo(@"\\server\share\file.txt"); bool exists = fi.Exists; ``` Are you sure that the account (under which your application is running) has access to the share. I think that (by default) administrative rights are required to access the share "c$".
See this question: [how can you easily check if access is denied for a file in .NET?](https://stackoverflow.com/questions/265953/c-how-can-you-easily-check-if-access-is-denied-for-a-file) The short version of that question is that you don't, because the file system is volatile. Just try to open the file and catch the exception if it fails. The reason your `isFileFound` method doesn't work is because the `FileInfo` structure you are using can also be used to create files. You can create a FileInfo object with the desired info for a non-existing file, call it's `.Create()` method, and you've set your desired properties all at once. I suspect the reason the UNC path fails is either 1) a permissions issue accessing the admin share from the user running your app, *or* 2) The `$` symbol is throwing the method off, either because it's not being input correctly or because of a bug in the underlying .Exists() implementation. **Update:** When I post this suggestion, I nearly always get a complaint about exception performance. Let's talk about that. Yes, handling exceptions is expensive: *very* expensive. There are few things you can do in programming that are slower. But you know what one those few things is? Disk and network I/O. Here's a link that demonstrates just how much disk I/O and network I/O cost: > <https://gist.github.com/jboner/2841832> ``` Latency Comparison Numbers -------------------------- L1 cache reference 0.5 ns Branch mispredict 5 ns L2 cache reference 7 ns 14x L1 cache Mutex lock/unlock 25 ns Main memory reference 100 ns 20x L2 cache, 200x L1 cache Compress 1K bytes with Zippy 3,000 ns Send 1K bytes over 1 Gbps network 10,000 ns 0.01 ms Read 4K randomly from SSD* 150,000 ns 0.15 ms Read 1 MB sequentially from memory 250,000 ns 0.25 ms Round trip within same datacenter 500,000 ns 0.5 ms Read 1 MB sequentially from SSD* 1,000,000 ns 1 ms 4X memory Disk seek 10,000,000 ns 10 ms 20x datacenter roundtrip Read 1 MB sequentially from disk 20,000,000 ns 20 ms 80x memory, 20X SSD Send packet CA->Netherlands->CA 150,000,000 ns 150 ms ``` If thinking in nanoseconds isn't your thing, here's another link that normalizes one CPU cycle as 1 second and scales from there: > <http://blog.codinghorror.com/the-infinite-space-between-words/> ``` 1 CPU cycle 0.3 ns 1 s Level 1 cache access 0.9 ns 3 s Level 2 cache access 2.8 ns 9 s Level 3 cache access 12.9 ns 43 s Main memory access 120 ns 6 min Solid-state disk I/O 50-150 μs 2-6 days Rotational disk I/O 1-10 ms 1-12 months Internet: SF to NYC 40 ms 4 years Internet: SF to UK 81 ms 8 years Internet: SF to AUS 183 ms 19 years OS virt. reboot 4 s 423 years SCSI command time-out 30 s 3000 years Hardware virt. reboot 40 s 4000 years Physical system reboot 5 m 32 millenia ``` Taking even the best-case scenario for exceptions, you can access memory at least 480 times while waiting on the first response from a disk, and that's assuming a very fast SSD. Many of us still need spinning hard-drives, where things get much, much worse. And that's only the beginning of the story. When you use `.Exists()`, you incur this *additional* cost (and it is an addition: you have to do the same work again when you go to open the file) on *every* attempt. You pay this costs whether the file exists or not, because the disk still has to go look for it in it's file tables. With the exception method, you only pay the extra cost of unwinding the call stack in the case of failure. In other words, yes: exceptions are horribly costly. But compared to the disk check, it's still faster: and not by just a small margin. Thankfully, this is unlikely to drive your app's general performance... but I still want to put to bed the "exceptions are slow" argument for this specific task.
Determining if file exists using c# and resolving UNC path
[ "", "c#", "filesystems", "" ]
In the following c# code, how do I get rid of the objects when it's no longer useful? Does it get taken care of automatically, or do I need to do something? ``` public void Test() { object MyObject = new object(); ... code ... } ```
The short answer is: unless it has unmanaged resources (file handles etc) you don't need to worry. The long answer is a bit more involved. When .NET decides it wants to free up some memory, it runs the *garbage collector*. This looks for all the objects which are still in use, and marks them as such. Any local variable (in any stack frame of any thread) which may still be read counts as a *root* as do static variables. (In fact I believe that static variables are referenced via live Type objects, which are referenced via live AppDomain objects, but for the most part you can regard static variables as roots.) The garbage collector looks at each object referred to by a root, and then finds more "live" references based on the instance variables within those objects. It recurses down, finding and marking more and more objects as "live". Once it's finished this process, it can then look at all the *rest* of the objects and free them. That's a very broad conceptual picture - but it gets a lot more detailed when you think of the *generational* model of garbage collection, finalizers, concurrent collection etc. I strongly recommend that you read Jeff Richter's [CLR via C#](https://rads.stackoverflow.com/amzn/click/com/0735621632) which goes into this in a lot of detail. He also has a [two](http://msdn.microsoft.com/en-us/magazine/bb985010.aspx) [part](http://msdn.microsoft.com/en-us/magazine/bb985011.aspx) article (back from 2000, but still very relevant) if you don't want to buy the book. Of course all this doesn't mean you don't need to worry about memory usage and object lifetimes in .NET. In particular: * Creating objects pointlessly *will* cost performance. In particular, the garbage collector is fast but not free. Look for *simple* ways to reduce your memory usage as you code, but micro-optimising before you know you have a problem is also bad. * It's possible to "leak" memory by making objects reachable for longer than you intended. Two reasonably common causes of this are static variables and event subscriptions. (An event subscription makes the event handler reachable from the event publisher, but not the other way round.) * If you use more memory (in a live, reachable way) than you have available, your app will crash. There's not a lot .NET can do to prevent that! * Objects which use non-memory resources typically implement [`IDisposable`](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx). You should call `Dispose` on them to release those resources when you're finished with the object. Note that this *doesn't* free the object itself - only the garbage collector can do that. The `using` statement in C# is the most convenient way of calling `Dispose` reliably, even in the face of an exception.
Automatically. When MyObject goes out of scope (at the end of Test), it's flagged for garbage collection. At some point in the future, the .NET runtime will clean up the memory for you Edit: (I should point out for the sake of completeness that if you pass MyObject somewhere, it gets passed by reference, and will not be garbage collected - it's only when no more references to the object are floating around that the GC is free to collect it) Edit: in a release build, MyObject will usually be collected as soon as it's unused (see my answer for more details --dp)
How do you get rid of an object in c#
[ "", "c#", ".net", "oop", "garbage-collection", "" ]
I would like to detect (on the server side) which requests are from bots. I don't care about malicious bots at this point, just the ones that are playing nice. I've seen a few approaches that mostly involve matching the user agent string against keywords like 'bot'. But that seems awkward, incomplete, and unmaintainable. So does anyone have any more solid approaches? If not, do you have any resources you use to keep up to date with all the friendly user agents? If you're curious: I'm not trying to do anything against any search engine policy. We have a section of the site where a user is randomly presented with one of several slightly different versions of a page. However if a web crawler is detected, we'd always give them the same version so that the index is consistent. Also I'm using Java, but I would imagine the approach would be similar for any server-side technology.
You can find a very thorough database of data on known "good" web crawlers in the robotstxt.org [Robots Database](http://www.robotstxt.org/db.html). Utilizing this data would be far more effective than just matching *bot* in the user-agent.
You said matching the user agent on ‘bot’ may be awkward, but we’ve found it to be a pretty good match. Our studies have shown that it will cover about 98% of the hits you receive. We also haven’t come across any false positive matches yet either. If you want to raise this up to 99.9% you can include a few other well-known matches such as ‘crawler’, ‘baiduspider’, ‘ia\_archiver’, ‘curl’ etc. We’ve tested this on our production systems over millions of hits. Here are a few c# solutions for you: ### 1) Simplest Is the fastest when processing a miss. i.e. traffic from a non-bot – a normal user. Catches 99+% of crawlers. ``` bool iscrawler = Regex.IsMatch(Request.UserAgent, @"bot|crawler|baiduspider|80legs|ia_archiver|voyager|curl|wget|yahoo! slurp|mediapartners-google", RegexOptions.IgnoreCase); ``` ### 2) Medium Is the fastest when processing a hit. i.e. traffic from a bot. Pretty fast for misses too. Catches close to 100% of crawlers. Matches ‘bot’, ‘crawler’, ‘spider’ upfront. You can add to it any other known crawlers. ``` List<string> Crawlers3 = new List<string>() { "bot","crawler","spider","80legs","baidu","yahoo! slurp","ia_archiver","mediapartners-google", "lwp-trivial","nederland.zoek","ahoy","anthill","appie","arale","araneo","ariadne", "atn_worldwide","atomz","bjaaland","ukonline","calif","combine","cosmos","cusco", "cyberspyder","digger","grabber","downloadexpress","ecollector","ebiness","esculapio", "esther","felix ide","hamahakki","kit-fireball","fouineur","freecrawl","desertrealm", "gcreep","golem","griffon","gromit","gulliver","gulper","whowhere","havindex","hotwired", "htdig","ingrid","informant","inspectorwww","iron33","teoma","ask jeeves","jeeves", "image.kapsi.net","kdd-explorer","label-grabber","larbin","linkidator","linkwalker", "lockon","marvin","mattie","mediafox","merzscope","nec-meshexplorer","udmsearch","moget", "motor","muncher","muninn","muscatferret","mwdsearch","sharp-info-agent","webmechanic", "netscoop","newscan-online","objectssearch","orbsearch","packrat","pageboy","parasite", "patric","pegasus","phpdig","piltdownman","pimptrain","plumtreewebaccessor","getterrobo-plus", "raven","roadrunner","robbie","robocrawl","robofox","webbandit","scooter","search-au", "searchprocess","senrigan","shagseeker","site valet","skymob","slurp","snooper","speedy", "curl_image_client","suke","www.sygol.com","tach_bw","templeton","titin","topiclink","udmsearch", "urlck","valkyrie libwww-perl","verticrawl","victoria","webscout","voyager","crawlpaper", "webcatcher","t-h-u-n-d-e-r-s-t-o-n-e","webmoose","pagesinventory","webquest","webreaper", "webwalker","winona","occam","robi","fdse","jobo","rhcs","gazz","dwcp","yeti","fido","wlm", "wolp","wwwc","xget","legs","curl","webs","wget","sift","cmc" }; string ua = Request.UserAgent.ToLower(); bool iscrawler = Crawlers3.Exists(x => ua.Contains(x)); ``` ### 3) Paranoid Is pretty fast, but a little slower than options 1 and 2. It’s the most accurate, and allows you to maintain the lists if you want. You can maintain a separate list of names with ‘bot’ in them if you are afraid of false positives in future. If we get a short match we log it and check it for a false positive. ``` // crawlers that have 'bot' in their useragent List<string> Crawlers1 = new List<string>() { "googlebot","bingbot","yandexbot","ahrefsbot","msnbot","linkedinbot","exabot","compspybot", "yesupbot","paperlibot","tweetmemebot","semrushbot","gigabot","voilabot","adsbot-google", "botlink","alkalinebot","araybot","undrip bot","borg-bot","boxseabot","yodaobot","admedia bot", "ezooms.bot","confuzzledbot","coolbot","internet cruiser robot","yolinkbot","diibot","musobot", "dragonbot","elfinbot","wikiobot","twitterbot","contextad bot","hambot","iajabot","news bot", "irobot","socialradarbot","ko_yappo_robot","skimbot","psbot","rixbot","seznambot","careerbot", "simbot","solbot","mail.ru_bot","spiderbot","blekkobot","bitlybot","techbot","void-bot", "vwbot_k","diffbot","friendfeedbot","archive.org_bot","woriobot","crystalsemanticsbot","wepbot", "spbot","tweetedtimes bot","mj12bot","who.is bot","psbot","robot","jbot","bbot","bot" }; // crawlers that don't have 'bot' in their useragent List<string> Crawlers2 = new List<string>() { "baiduspider","80legs","baidu","yahoo! slurp","ia_archiver","mediapartners-google","lwp-trivial", "nederland.zoek","ahoy","anthill","appie","arale","araneo","ariadne","atn_worldwide","atomz", "bjaaland","ukonline","bspider","calif","christcrawler","combine","cosmos","cusco","cyberspyder", "cydralspider","digger","grabber","downloadexpress","ecollector","ebiness","esculapio","esther", "fastcrawler","felix ide","hamahakki","kit-fireball","fouineur","freecrawl","desertrealm", "gammaspider","gcreep","golem","griffon","gromit","gulliver","gulper","whowhere","portalbspider", "havindex","hotwired","htdig","ingrid","informant","infospiders","inspectorwww","iron33", "jcrawler","teoma","ask jeeves","jeeves","image.kapsi.net","kdd-explorer","label-grabber", "larbin","linkidator","linkwalker","lockon","logo_gif_crawler","marvin","mattie","mediafox", "merzscope","nec-meshexplorer","mindcrawler","udmsearch","moget","motor","muncher","muninn", "muscatferret","mwdsearch","sharp-info-agent","webmechanic","netscoop","newscan-online", "objectssearch","orbsearch","packrat","pageboy","parasite","patric","pegasus","perlcrawler", "phpdig","piltdownman","pimptrain","pjspider","plumtreewebaccessor","getterrobo-plus","raven", "roadrunner","robbie","robocrawl","robofox","webbandit","scooter","search-au","searchprocess", "senrigan","shagseeker","site valet","skymob","slcrawler","slurp","snooper","speedy", "spider_monkey","spiderline","curl_image_client","suke","www.sygol.com","tach_bw","templeton", "titin","topiclink","udmsearch","urlck","valkyrie libwww-perl","verticrawl","victoria", "webscout","voyager","crawlpaper","wapspider","webcatcher","t-h-u-n-d-e-r-s-t-o-n-e", "webmoose","pagesinventory","webquest","webreaper","webspider","webwalker","winona","occam", "robi","fdse","jobo","rhcs","gazz","dwcp","yeti","crawler","fido","wlm","wolp","wwwc","xget", "legs","curl","webs","wget","sift","cmc" }; string ua = Request.UserAgent.ToLower(); string match = null; if (ua.Contains("bot")) match = Crawlers1.FirstOrDefault(x => ua.Contains(x)); else match = Crawlers2.FirstOrDefault(x => ua.Contains(x)); if (match != null && match.Length < 5) Log("Possible new crawler found: ", ua); bool iscrawler = match != null; ``` **Notes:** * It’s tempting to just keep adding names to the regex option 1. But if you do this it will become slower. If you want a more complete list then linq with lambda is faster. * Make sure .ToLower() is outside of your linq method – remember the method is a loop and you would be modifying the string during each iteration. * Always put the heaviest bots at the start of the list, so they match sooner. * Put the lists into a static class so that they are not rebuilt on every pageview. **Honeypots** The only real alternative to this is to create a ‘honeypot’ link on your site that only a bot will reach. You then log the user agent strings that hit the honeypot page to a database. You can then use those logged strings to classify crawlers. `Postives:` It will match some unknown crawlers that aren’t declaring themselves. `Negatives:` Not all crawlers dig deep enough to hit every link on your site, and so they may not reach your honeypot.
Detecting honest web crawlers
[ "", "c#", "web-crawler", "bots", "" ]
What is the difference between `InvokeRequired` and `somecontrol.InvokeRequired`? like this, ``` delegate void valueDelegate(string value); private void SetValue(string value) { if (InvokeRequired) { BeginInvoke(new valueDelegate(SetValue),value); } else { someControl.Text = value; } } ``` and ``` delegate void valueDelegate(string value); private void SetValue(string value) { if (someControl.InvokeRequired) { someControl.Invoke(new valueDelegate(SetValue),value); } else { someControl.Text = value; } } ```
The first version checks the thread responsible for *this* control. The second version checks the thread responsible for `someControl`. (And ditto for which control's thread they then delegate the invocation to.) They could potentially be different - although they really *shouldn't* be if the two controls are in the same top-level window. (All controls in one window should be running on the same thread.)
The difference is the control of which you accessing the property. If you access InvokeRequired from within a method on the form, you're effectively access the form's InvokeRequired property. If the form and the someControl are created in the same thread, then they will return the same value.
Using InvokeRequired vs control.InvokeRequired
[ "", "c#", "" ]
Does anybody know how to make a 'always-on-bottom'-windows, or a window pinned to the desktop? It should receive focus and mouseclicks, but should stay at the bottom of the Z-order. It would also be great if it could stay on the desktop even when user do a minimize all or show desktop operation. Both delphi and c# solutions (or partial solutions/hints) would be great.
**Warning** It was suggested that you can accomplish this by calling SetParent and setting the window to be a child of the Desktop. If you do this, you cause the Win32 Window Manager to combine the input queue of the Desktop to your child window, this is a *bad thing* - [Raymond Chen explains why.](http://blogs.msdn.com/oldnewthing/archive/2004/02/24/79212.aspx) Also, keep in mind that calling SetWindowPos with HWND\_BOTTOM is incomplete. You need to do this whenever your window is changing zorder. Handle the WM\_WINDOWPOSCHANGING event, look at SWP\_NOZORDER for more info.
SetWindowPos can make windows AlwaysOnTop. Most likely it can give the opposite result. Try something along these lines: ``` [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); public const uint SWP_NOSIZE = 0x0001; public const uint SWP_NOMOVE = 0x0002; public const uint SWP_NOACTIVATE = 0x0010; public const int HWND_BOTTOM = 1; SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); ``` Note: * Haven't tested this approach (for making windows always on bottom) * If it happens to work, then most likely the show desktop operation will hide the window. So maybe you should go even deeper into this 'nice' API. EDIT: Done some searching along these lines to confirm whether it will do the trick and found something interesting - [a duplicate](https://stackoverflow.com/questions/365094/window-on-desktop).
How to make 'always-on-bottom'-window
[ "", "c#", "delphi", "" ]
When comparing enums that come from different sources such as those of the following code GCC emits warnings. Is there a way to avoid these warnings without c-style casts? ``` struct Enumerator { enum { VALUE = 5 }; }; template<int V> struct TemplatedEnumerator { enum { VALUE = V }; }; if(Enumerator::VALUE == TemplatedEnumerator<5>::VALUE) { ... } ``` And GCC emits the following type of warning: ``` GCC: warning: comparison between 'enum ...' and 'enum ...' ```
Simple answer in your case: don't use an `enum`, use an inline-defined `static const int`: ``` struct Enumerator { static int const VALUE = 5; }; template<int V> struct TemplatedEnumerator { static int const VALUE = V; }; ``` In this special case, that's equivalent and all compilers of the last few years should treat it so (I know for a fact that all the major ones do). See also: [static const Member Value vs. Member enum : Which Method is Better & Why?](https://stackoverflow.com/questions/204983#205000)
I believe you can provide your own comparison operators, but you'll have to name the enums first: ``` struct Enumerator { enum Values { VALUE = 5 }; }; template<int V> struct TemplatedEnumerator { enum Values { VALUE = V }; }; template <int V> bool operator==(Enumerator::Values lhs, typename TemplatedEnumerator<V>::Values rhs) { return static_cast<int>(lhs) == static_cast<int>(rhs); } template <int V> bool operator==(typename TemplatedEnumerator<V>::Values rhs, Enumerator::Values lhs) { return static_cast<int>(lhs) == static_cast<int>(rhs); } ``` Interestingly Visual Studio doesn't actually warn about comparing the two enumerator types, but rather warns about a constant value in a `if` statement - just like it will if you do this: ``` if (true) {...} ```
Is there a correct way to avoid warnings when comparing two different enums?
[ "", "c++", "templates", "gcc", "enums", "" ]
I am having small problem in making a global variable works. I am using Visual Studio 2008 and standard C++. I have two projects, one is a static library and second one is a test program which uses this library. I have a global variable in global.h like ``` #ifndef GLOBAL_H #define GLOBAL_H #include <string> extern std::string globalWord; #endif // GLOBAL_H! ``` I have a global.cpp where I am initializing this variable. This variable is used inside my library project. I am setting a value to this variable from the test project, but that value is not getting reflected in the library project. I have debugged and it shows the new value in test project, but when the control reaches the library project, this variable value shows empty. So is this global variable's scope only limited to the project where it belongs to? Or is there a better way to do this? I don't want to modify my function or constructor parameters in my library to pass this value. Any help would be great. Edit: Here is how this variable is declared in global.cpp ``` #include <string> #include "../global.h" std::string globalWord = ""; ``` This is how I used it in my library ``` #include "../global.h" string text = globalWord; ``` Thanks
Don't use global variables. Just don't. Much better, if you HAVE to have globally accessible data, is to use a global function which will return globalWord, like this: ``` std::string globalWord() { static std::string word("Hi Mom"); return word; } ``` This saves you from initialization order issues (read Effective C++ item #4).
With the "extern" keyword, you're telling the compiler that the actual variable exists somewhere else. You should also create a variable with the same name without the extern, in one and **only one** place. Ordinarily you'll get an error from the linker if you define two of them, but if one's in the library and one's not it might not figure it out. Edit: make sure global.cpp is only in the library or test program, not both.
Global variables and scope - C++
[ "", "c++", "variables", "global-variables", "scope", "" ]
I am a new php and mysql programmer. I am handling quite large amount of data, and in future it will grow slowly, thus I am using hash table. I have couple of questions: 1. Does mysql have hash table built in function? If yes, how to use that? 2. After couple of days doing research about hash table. I briefly know what hash table is but I just could not understand how to start creating one. I saw a lot of hash table codes over the internet. Most of them, in the first step in to create a hashtable class. Does it mean, they store the hash table value in the temporary table instead of insert into mysql database? For questions 3,4 & 5, example scenario: User can collect items in the website. I would like to use hash table to insert and retrieve the items that the user collected. 3. [Important] What are the possible mysql database structure looks like? e.g, create items and users table in items table have: item\_id, item\_name, and item\_hash\_value in users table have: user\_id, username, item\_name, item\_hash\_value I am not sure if the users table is correct? 4. [Important] What are the steps of creating hash table in php and mysql? (If there is any sample code would be great :)) 5. [Important] How to insert and retrieve data from hash table? I am talking about php and mysql, so I hope the answers can be like: "you can use mysql query i.e SELECT \* from blabla..."
(sorry about the italics, underscores can trigger them but I can't find a good way to disable that in the middle of a paragraph. Ignore the italics, I didn't mean to put them there) You don't need to worry about using a hashtable with MySQL. If you intend to have a large number of items in memory while you operate on them a hashtable is a good data structure to use since it can find things much faster than a simple list. But at the database level, you don't need to worry about the hashtable. Figuring out how to best hold and access records is MySQL's job, so as long as you give it the correct information it will be happy. ## Database Structure ``` items table would be: item_id, item_name Primary key is item_id users table would be: user_id, username Primary key is user_id user_items table would be: user_id, item_id Primary key is the combination of user_id and item_id Index on item_id ``` Each item gets one (and only one) entry in the items table. Each user gets one (and only one) entry in the users table. When a user selects an item, it goes in the user items table. Example: ``` Users: 1 | Bob 2 | Alice 3 | Robert Items 1 | Headphones 2 | Computer 3 | Beanie Baby ``` So if Bob has selected the headphones and Robert has selected the computer and beanie baby, the user\_items table would look like this: ``` User_items (user_id, item_id) 1 | 1 (This shows Bob (user 1) selected headphones (item 1)) 3 | 2 (This shows Robert (user 3) selected a computer (item 2)) 3 | 3 (This shows Robert (user 3) selected a beanie baby (item 3)) ``` Since the user\_id and item\_id on the users and items tables are primary keys, MySQL will let you access them very fast, just like a hashmap. On the user\_items table having both the user\_id and item\_id in the primary key means you won't have duplicates and you should be able to get fast access (an index on item\_id wouldn't hurt). ## Example Queries With this setup, it's really easy to find out what you want to know. Here are some examples: Who has selected item 2? ``` SELECT users.user_id, users.user_name FROM users, user_items WHERE users.user_id = user_items.user_id AND user_items.item_id = 2 ``` How many things has Robert selected? ``` SELECT COUNT(user_items.item_id) FROM user_items, users WHERE users.user_id = user_items.user_id AND users.user_name = 'Robert' ``` I want a list of each user and what they've selected, ordered by the user name ``` SELECT user.user_name, item.item_name FROM users, items, user_items WHERE users.user_id = user_items.user_id AND items.item_id = user_items.item_id ORDER BY user_name, item_name ``` There are many guides to SQL on the internet, such as the [W3C's tutorial](http://www.w3schools.com/sql/default.asp).
1) Hashtables do exist in MySQL but are used to keep internal track of keys on tables. 2) Hashtables work by hashing a data cell to create a number of different keys that separate the data by these keys making it easier to search through. The hashtable is used to find what the key is that should be used to bring up the correct list to search through. Example, you have 100 items, searching 100 items in a row takes 10 seconds. If you know that they can be separated by type of item and break it up into 25 items of t-shirts, 25 items of clocks, items rows of watches, and items rows of shoes. Then when you need to find a t-shirt, you can only have to search through the 25 items of t-shirts which then takes 2.5 seconds. 3) Not sure what your question means, a MySQL database is a binary file that contains all the rows in the database. 4) As in #2 you would need to decide what you want your key to be. 5) #2 you need to know what your key is.
Questions about Php and Mysql Hash Table
[ "", "php", "mysql", "hash", "hashtable", "" ]
Do **out** parameters in **C#** have any performance implications I should know about? (Like exceptions) I mean, is it a good idea to have a method with an `out` parameter in a loop that will run a couple of million times a second? I know it's ugly but I am using it the same way as `Int32.TryParse` is using them - returning a `bool` to tell if some validation was successful and having an `out` parameter containing some additional data if it was successful.
I doubt that you'll find any significant performance penalty to using an `out` parameter. You've got to get information back to the caller somehow or other - `out` is just a different way of doing it. You may find there's *some* penalty if you use the out parameter extensively within the method, as it may well mean an extra level of redirection for each access. However, I wouldn't expect it to be significant. As normal, write the most readable code and [test whether performance is already good enough](http://blogs.msdn.com/ericlippert/archive/2009/02/06/santalic-tailfans-part-two.aspx) before trying to optimise further. EDIT: The rest of this is an aside, effectively. It's only really relevant for large value types, which should usually be avoided anyway :) I disagree with Konrad's assertion about "return values for all types > 32 bit are handled similar or identical to out arguments on the machine level anyway" though. Here's a little test app: ``` using System; using System.Diagnostics; using System.Runtime.CompilerServices; struct BigStruct { public Guid guid1, guid2, guid3, guid4; public decimal dec1, dec2, dec3, dec4; } class Test { const int Iterations = 100000000; static void Main() { decimal total = 0m; // JIT first ReturnValue(); BigStruct tmp; OutParameter(out tmp); Stopwatch sw = Stopwatch.StartNew(); for (int i=0; i < Iterations; i++) { BigStruct bs = ReturnValue(); total += bs.dec1; } sw.Stop(); Console.WriteLine("Using return value: {0}", sw.ElapsedMilliseconds); sw = Stopwatch.StartNew(); for (int i=0; i < Iterations; i++) { BigStruct bs; OutParameter(out bs); total += bs.dec1; } Console.WriteLine("Using out parameter: {0}", sw.ElapsedMilliseconds); } [MethodImpl(MethodImplOptions.NoInlining)] public static BigStruct ReturnValue() { return new BigStruct(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void OutParameter(out BigStruct x) { x = new BigStruct(); } } ``` Results: ``` Using return value: 11316 Using out parameter: 7461 ``` Basically by using an out parameter we're writing the data directly to the final destination, rather than writing it to the small method's stack frame and then copying it back into the Main method's stack frame. Feel free to criticise the benchmark app though - I may have missed something!
There are no performance implications. `out` is basically the same as any old argument passing, from a technical point of view. While it might sound plausible that huge amounds of data are copied (e.g. for large structs), this is actually the same as for return values. In fact, return values for all types > 32 bit are handled similar to `out` arguments on the **machine level** anyway. Please note that the last statement doesn't suggest that returning a value == `out` parameter in .NET. Jon's benchmark shows that this is obviously (and regrettably) not the case. In fact, to make it identical, [named return value optimization](http://blogs.msdn.com/slippman/archive/2004/02/03/66739.aspx) is employed in C++ compilers. Something similar could potentially be done in future versions of the JIT to improve performance of returning large structures (however, since large structures are quite rare in .NET, this might be an unnecessary optimization). *However*, (and with my very limited knowledge of x86 assembly), returning objects from function calls generally entails allocating sufficient space at the call site, pushing the address on the stack and filling it by copying the return value into it. This is basically the same that `out` does, only omitting an unnecessary temporary copy of the value since the target memory location can be accessed directly.
C# out parameter performance
[ "", "c#", "parameters", "out", "" ]
I'd like to learn how to effectively use [Swing Application Framework](https://appframework.dev.java.net/). Most of the the examples I've found are blog entries that just explain how to great it is to extend SingleFrameApplication and override its startup method, but that's about it. [Sun's article](http://java.sun.com/developer/technicalArticles/javase/swingappfr/) is almost two years old, as is [the project's own introduction](https://appframework.dev.java.net/intro/index.html), and there has apparently been some evolution since then. Are there any recent and thorough tutorials/HOWTOs available anywhere? There is JavaDoc of course, but it's hard to get the big picture from there. Any pointers are appreciated. **Update:** I realized that there's a [mailing list archive](https://appframework.dev.java.net/servlets/SummarizeList?listName=users) at the project's site. While somewhat clumsy (compared to StackOverflow ;) it seems to be quite active. Still it's a pity that there are no real tutorials anywhere. The information is scattered here and there. **Update 2:** Let me clarify - I'm not having trouble using Swing (the widget toolkit) itself, I'm talking about its *Application Framework*, which is supposed to ease things like application lifecycle (startup, exit and whatever happens between them), action management etc. - that is, things that most Swing applications will need. It's cool to get such framework to be [standard part of Java](http://tech.puredanger.com/java7#jsr296). The only problem is to learn how it's intended to be used. **Update 3:** For the interested, there was just some discussion at the project's forum regarding the current state and future of JSR 296. Shortly: the current version 1.03 is considered to be quite usable, **but** the API is not stable and it **will** change to the final version in Java 7. The package name will also change so Java 7 will not break current applications made on SAF. **Update 4:** Karsten Lentzsch stated at the above mentioned forum: "I doubt that it can be included in Java 7; and I'll vote against it.". I would rather not question the sincerity of this great guru, and it's certainly wise not to let anything flawed to slip into the core JDK, but frankly it's a strange situation - he is the author of JGoodies Swing Suite which is partly a commercial competitor of JSR 296, *and* he is sitting in the committee that will decide whether this JSR will be included to standard Java. It was the same thing with JSR 295 [Beans Binding](https://stackoverflow.com/questions/510655/jgoodies-binding-vs-jsr-295) which I wrote about earlier. Given the current state of SAF, I think the best solution is to wrap the current implementation into a "homebrew" framework, which can then accommodate possible changes to the existing API.
First of all, my personal advice would be not to use the latest version of SAF which is more like "refactoring in progress" (and this has not evolved for 6 months now...) I much prefer version "1.03" which, although not perfect, is much more stable and usable (I mean in a real-life application). It is true that resources about SAF are scarce. I remember I followed this path: * read a [JavaOne 2007 seminar](http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-3942.pdf) about it; this gives quite a good picture about it * used it and read javadoc whenever needed * sometimes took some looks at the source code to palliate javadoc lacks The mailing list is not that active currently (but it's true traffic has just restarted a little bit since the beginning of the year, however, I haven't seen there any Sun representative since August or September 2008!) Last year, after about one year of practice with SAF, I have presented a talk at Jazoon'08, you can find the slides [on my blog](http://jfpoilpret.blogspot.com/search/label/Jazoon). This presentation was more about tips & tricks I gathered while using the framework. Sometimes I also had to patch some points by myself because many issues are long standing (some not important to me, some other blocking). I remember having seen (not attended) another presentation about SAF practice in a conference I think in Sweden, sorry can't remember more detail. Was interesting also. That's pretty much what exists about it (to my knowledge).
[Netbeans 6.5](http://www.netbeans.org/) has skeleton applications that can give you a good kickstart. Just create a new project from within the IDE and select Java > Java Desktop Application.
How to actually use Swing Application Framework?
[ "", "java", "swing", "swing-app-framework", "" ]
I need advice on how to return a limited set of data from an MVC controller. Lets say I have a class that is constructed like so: ``` public interface ICustomerExpose { string Name {get; set;} string State {get; set;} } public interface ICustomer: ICustomerExpose { int Id {get; set;} string SSN {get; set;} } public class Customer: ICustomer { ... } ``` In my MVC project I have a controller action that returns customer data. The project is actually more like a web service as there is no View associated with the data... we use the XmlResult (provided by the [MVCContrib](http://www.codeplex.com/MVCContrib) project). The controller action looks like this: ``` // GET: /Customer/Show/5 public ActionResult Show(int id) { Customer customer = Customer.Load(id); ... // some validation work return new XmlResult((ICustomerExpose)customer); } ``` The above controller code does not work like I want it to. What I want to happen is that only the Name and State properties are serialized and returned in the XmlResult. In practice the whole customer object is serialized including the data I definitely don't want exposed. I know the reason this doesn't work: you can't serialize an interface. One idea floated around the office was to simply mark the properties Name and State as [XmlIgnore]. However, this doesn't seem like a good solution to me. There might be other instances where I want to serialize those properties and marking the properties on the class this way prohibits me. What is the best way to achieve my goal of only serializing the properties in the ICustomerExpose interface? Addendum: For those interested in what XmlResult does here are the relevant parts of it: ``` public class XmlResult : ActionResult { private object _objectToSerialize; public XmlResult(object objectToSerialize) { _objectToSerialize = objectToSerialize; } /// <summary> /// Serialises the object that was passed into the constructor /// to XML and writes the corresponding XML to the result stream. /// </summary> public override void ExecuteResult(ControllerContext context) { if (_objectToSerialize != null) { var xs = new XmlSerializer(_objectToSerialize.GetType()); context.HttpContext.Response.ContentType = "text/xml"; xs.Serialize(context.HttpContext.Response.Output, _objectToSerialize); } } } ```
I ended up just doing the XmlIgnore as co-workers suggested, even though this left me with some undesirable (or so I thought) behaviors. To get around the fact that XmlIgnore would continue hiding properties that I might want serialized later I [asked another question](https://stackoverflow.com/questions/592671/overriding-a-property-with-an-attribute/593084#593084) trying to find a way to around that issue. Cheeso came up with a great answer making the XmlIgnore the best route (in my opinion) to take.
You can try this, however I am not sure if it works with xml serializers: ``` return new XmlResult(new { customer.Name, customer.State }); ```
Limiting the data returned by a controller
[ "", "c#", "asp.net-mvc", "serialization", "interface", "" ]
I have a Linq to SQL DataContext with SQL functions into it. While the retrieve object is good, I would like to add a property to the object and same time shortens the object name. So I made an object Reminder that inherits from the Linq to SQL object fnRTHU\_ReminderByTaskResult with the property I wanted. ``` public class Reminder : fnRTHU_ReminderByTaskResult { public string MyProperty {get;set;} } ``` Then when the function is bind to the list I try in the aspx file to do: ``` <asp:Literal runat="server" Text='<%# ((Reminder)DataBinder.Container).MyProperty %>' /> ``` Where DataBinder.Container is of type fnRTHU\_ReminderByTaskResult. This results in an InvalidCastException, unable to cast object type fnRTHU\_ReminderByTaskResult to type Reminder. I don't understand since I inherit from the type I'm casting from.
Since the Linq to Sql function returns that base class, your object was never that of your derived class. Therefore, when trying to cast down, it can't do it. You can however provide implicit and explicit casting implementations within your class that would allow this cast to work. [See here](http://msdn.microsoft.com/en-us/library/aa288476(VS.71).aspx)
The problem is your attempting to case an instance of a Base class to a Child class. This is not valid because Child inherits from Base. There is no guarantee that a case from Base to Child will work (this is known as a downcaste). Up casts (Child to Base) are safe. This will work though if the Container property is an instance of Reminder. In this case, it does not appear to be.
Why can't I cast result of Linq to SQL?
[ "", "c#", "asp.net", "linq-to-sql", "" ]
Given a string of a Python class, e.g. `my_package.my_module.MyClass`, what is the best possible way to load it? In other words I am looking for a equivalent `Class.forName()` in Java, function in Python. It needs to work on Google App Engine. Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class: ``` my_class = load_class('my_package.my_module.MyClass') my_instance = my_class() ```
From the python documentation, here's the function you want: ``` def my_import(name): components = name.split('.') mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod ``` The reason a simple `__import__` won't work is because any import of anything past the first dot in a package string is an attribute of the module you're importing. Thus, something like this won't work: ``` __import__('foo.bar.baz.qux') ``` You'd have to call the above function like so: ``` my_import('foo.bar.baz.qux') ``` Or in the case of your example: ``` klass = my_import('my_package.my_module.my_class') some_object = klass() ``` **EDIT**: I was a bit off on this. What you're basically wanting to do is this: ``` from my_package.my_module import my_class ``` The above function is only necessary if you have a *empty* fromlist. Thus, the appropriate call would be like this: ``` mod = __import__('my_package.my_module', fromlist=['my_class']) klass = getattr(mod, 'my_class') ```
``` import importlib module = importlib.import_module('my_package.my_module') my_class = getattr(module, 'MyClass') my_instance = my_class() ```
How to dynamically load a Python class
[ "", "python", "reflection", "python-import", "" ]
I have an interesting problem. Consider this class hierachy: ``` class Base { public: virtual float GetMember( void ) const =0; virtual void SetMember( float p ) =0; }; class ConcreteFoo : public Base { public: ConcreteFoo( "foo specific stuff here" ); virtual float GetMember( void ) const; virtual void SetMember( float p ); // the problem void foo_specific_method( "arbitrary parameters" ); }; Base* DynamicFactory::NewBase( std::string drawable_name ); // it would be used like this Base* foo = dynamic_factory.NewBase("foo"); ``` I've left out the DynamicFactory definition and how Builders are registered with it. The Builder objects are associated with a name and will allocate a concrete implementation of Base. The actual implementation is a bit more complex with shared\_ptr to handle memory reclaimation, but they are not important to my problem. `ConcreteFoo` has class specific method. But since the concrete instances are create in the dynamic factory the concrete classes are not known or accessible, they may only be declared in a source file. How can I expose `foo_specific_method` to users of `Base*`? I'm adding the solutions I've come up with as answers. I've named them so you can easily reference them in your answers. I'm not just looking for opinions on my original solutions, new ones would be appreciated.
The cast would be faster than most other solutions, however: in Base Class add: ``` void passthru( const string &concreteClassName, const string &functionname, vector<string*> args ) { if( concreteClassName == className ) runPassThru( functionname, args ); } private: string className; map<string, int> funcmap; virtual void runPassThru( const string &functionname, vector<string*> args ) {} ``` in each derived class: ``` void runPassThru( const string &functionname, vector<string*> args ) { switch( funcmap.get( functionname )) { case 1: //verify args // call function break; // etc.. } } // call in constructor void registerFunctions() { funcmap.put( "functionName", id ); //etc. } ```
The `CrazyMetaType` solution. This solution is not well thought out. I was hoping someone might have had experience with something similar. I saw this applied to the problem of an unknown number of a known type. It was pretty slick. I was thinking to apply it to an unkown number of unknown type\*\*\*S\*\*\* The basic idea is the CrazyMetaType collects the parameters is type safe way, then executing the concrete specific method. ``` class Base { ... virtual CrazyMetaType concrete_specific( int kind ) =0; }; // used like this foo->concrete_specific(foo_method_id) << "foo specific" << foo_specific; ``` My one worry with this solution is that `CrazyMetaType` is going to be insanely complex to get this to work. I'm up to the task, but I cannot count on future users to be up to be c++ experts just to add one concrete specific method.
Concrete class specific methods
[ "", "c++", "design-patterns", "architecture", "" ]
Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL? Say I have two tables: ``` Dogs: Name, Age, BreedId Breeds: BreedId, BreedName ``` I want to return all dogs with their `BreedName`. I should get all dogs using something like this with no problems: ``` public IQueryable<Dog> GetDogs() { var db = new DogDataContext(ConnectString); var result = from d in db.Dogs join b in db.Breeds on d.BreedId equals b.BreedId select d; return result; } ``` But if I want dogs with breeds and try this I have problems: ``` public IQueryable<Dog> GetDogsWithBreedNames() { var db = new DogDataContext(ConnectString); var result = from d in db.Dogs join b in db.Breeds on d.BreedId equals b.BreedId select new { Name = d.Name, BreedName = b.BreedName }; return result; } ``` Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type? Or do I have to create my own class for `DogsWithBreedNames` and specify that type in the select? Or is there another easier way?
I tend to go for this pattern: ``` public class DogWithBreed { public Dog Dog { get; set; } public string BreedName { get; set; } } public IQueryable<DogWithBreed> GetDogsWithBreedNames() { var db = new DogDataContext(ConnectString); var result = from d in db.Dogs join b in db.Breeds on d.BreedId equals b.BreedId select new DogWithBreed() { Dog = d, BreedName = b.BreedName }; return result; } ``` It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.
You *can* return anonymous types, [but it really isn't pretty](http://codeblog.jonskeet.uk/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance). In this case I think it would be far better to create the appropriate type. If it's only going to be used from within the type containing the method, make it a nested type. Personally I'd like C# to get "named anonymous types" - i.e. the same behaviour as anonymous types, but with names and property declarations, but that's it. EDIT: Others are suggesting returning dogs, and then accessing the breed name via a property path etc. That's a perfectly reasonable approach, but IME it leads to situations where you've done a query in a particular way because of the data you want to use - and that meta-information is lost when you just return `IEnumerable<Dog>` - the query may be *expecting* you to use (say) `Breed` rather than `Owner`due to some load options etc, but if you forget that and start using other properties, your app may work but not as efficiently as you'd originally envisaged. Of course, I could be talking rubbish, or over-optimising, etc...
Return anonymous type results?
[ "", "c#", "linq", "linq-to-sql", "" ]
Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered. I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong. Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described. settings.py ``` MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/' ``` urls.py ``` from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^ovramt/$', 'dso.ovramt.views.index'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) ``` Within my template: ``` <head> <title> {% block title %} DSO Template {% endblock %} </title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > <link rel="stylesheet" type="text/css" href="../media/styles.css"> </head> ``` I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment. --- Edit: One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example: www.example.com/application/ has a link "/app2/ and a link "app3/". app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.
I just had to figure this out myself. settings.py: ``` MEDIA_ROOT = 'C:/Server/Projects/project_name/static/' MEDIA_URL = '/static/' ADMIN_MEDIA_PREFIX = '/media/' ``` urls.py: ``` from django.conf import settings ... if settings.DEBUG: urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) ``` template file: ``` <link rel="stylesheet" type="text/css" href="/static/css/style.css" /> ``` With the file located here: ``` "C:/Server/Projects/project_name/static/css/style.css" ```
Django already has a context process for MEDIA\_URL, see [Django's documentation](http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-media "In django's documentation"). It should be availbale by default (unless you've customized CONTEXT\_PROCESSORS and forgot to add it) in a RequestContext.
Django: how do you serve media / stylesheets and link to them within templates
[ "", "python", "css", "django", "django-templates", "media", "" ]
I have the following data: ``` ExamEntry Student_ID Grade 11 1 80 12 2 70 13 3 20 14 3 68 15 4 75 ``` I want to find all the students that passed an exam. In this case, if there are few exams that one student attended to, I need to find the last result. So, in this case I'd get that all students passed. Can I find it with one fast query? I do it this way: 1. Find the list of entries by select max(ExamEntry) from data group by Student\_ID 2. Find the results: select ExamEntry from data where ExamEntry in ( ). But this is VERY slow - I get around 1000 entries, and this 2 step process takes 10 seconds. Is there a better way? Thanks.
If your query is very slow at with 1000 records in your table, there is something wrong. For a modern Database system a table containing, 1000 entries is considered very very small. Most likely, you did not provid a (primary) key for your table? Assuming that a student would pass if at least on of the grades is above the minimum needed, the appropriate query would be: ``` SELECT Student_ID , MAX(Grade) AS maxGrade FROM table_name GROUP BY Student_ID HAVING maxGrade > MINIMUM_GRADE_NEEDED ``` If you really need the latest grade to be above the minimum: ``` SELECT Student_ID , Grade FROM table_name WHERE ExamEntry IN ( SELECT MAX(ExamEntry) FROM table_name GROUP BY Student_ID ) HAVING Grade > MINIMUM_GRADE_NEEDED ```
As mentioned, indexing is a powerful tool for speeding up queries. The order of the index, however, is fundamentally important. An index in order of (ExamEntry) then (Student\_ID) then (Grade) would be next to useless for finding exams where the student passed. An index in the opposite order would fit perfectly, if all you wanted was to find what exams had been passed. This would enable the query engine to quickly identify rows for exams that have been passed, and just process those. In MS SQL Server this can be done with... ``` CREATE INDEX [IX_results] ON [dbo].[results] ( [Grade], [Student_ID], [ExamEntry] ) ON [PRIMARY] ``` (I recommend reading more about indexs to see what other options there are, such as ClusterdIndexes, etc, etc) With that index, the following query would be able to ignore the 'failed' exams very quickly, and just display the students who ever passed the exam... (This assumes that if you ever get over 60, you're counted as a pass, even if you subsequently take the exam again and get 27.) ``` SELECT Student_ID FROM [results] WHERE Grade >= 60 GROUP BY Student_ID ``` Should you definitely need the most recent value, then you need to change the order of the index back to something like... ``` CREATE INDEX [IX_results] ON [dbo].[results] ( [Student_ID], [ExamEntry], [Grade] ) ON [PRIMARY] ``` This is because the first thing we are interested in is the most recent ExamEntry for any given student. Which can be achieved using the following query... ``` SELECT * FROM [results] WHERE [results].ExamEntry = ( SELECT MAX([student_results].ExamEntry) FROM [results] AS [student_results] WHERE [student_results].Student_ID = [results].student_id ) AND [results].Grade > 60 ``` Having a sub query like this can appear slow, especially since it appears to be executed for every row in [results]. This, however, is not the case... - Both main and sub query reference the same table - The query engine scans through the Index for every unique Student\_ID - The sub query is executed, for that Student\_ID - The query engine is already in that part of the index - So a new Index Lookup is not needed EDIT: A comment was made that at 1000 records indexs are not relevant. It should be noted that the question states that there are 1000 records Returned, not that the table contains 1000 records. For a basic query to take as long as stated, I'd wager there are many more than 1000 records in the table. Maybe this can be clarified? EDIT: I have just investigated 3 queries, with 999 records in each (3 exam results for each of 333 students) Method 1: WHERE a.ExamEntry = (SELECT MAX(b.ExamEntry) FROM results [a] WHERE a.Student\_ID = b.student\_id) Method 2: WHERE a.ExamEntry IN (SELECT MAX(ExamEntry) FROM resuls GROUP BY Student\_ID) Method 3: USING an INNER JOIN instead of the IN clause The following times were found: ``` Method QueryCost(No Index) QueryCost(WithIndex) 1 23% 9% 2 38% 46% 3 38% 46% ``` So, Query 1 is faster regardless of indexes, but indexes also definitely make method 1 substantially faster. The reason for this is that indexes allow lookups, where otherwise you need a scan. The difference between a linear law and a square law.
Fetch data with single and fast SQL query
[ "", "sql", "performance", "" ]
I was trying to solve an LP with CPLEX. It throws an exception "CPLEX Error 1001: Out of memory" when I am building the model. Please note that I am getting this error while modelling and not while optimizing. There are google results for Out of memory scenarios during optimization. Your help is highly appreciated Thanks
Thank you very much for the response. The issue is temporarily solved. I was running the optimizer on a server with 8G ram (3G free) and the model was huge. We have been starting JRE with Min Heap size ( `java -Xms1G` ) set to 1G. I believe this caused JRE to reserve a lot of space in the server memory; leaving no room for the CPLEX process. After numerous trial and error experiments with different CPLEX parameters (all of them failed!), we attempted start the optimizer with `java -Xms512M -Xmx750M` and it worked!!!
There's very little information to work with here... does the problem occur for small LPs? How big of an LP are you building? Have you seen this [ILOG forum thread](http://forums.ilog.com/optimization/index.php?action=printpage;topic=556.0)?
CPLEX Error 1001: Out of memory
[ "", "java", "linux", "" ]
I have a table constructed like this : ``` oid | identifier | value 1 | 10 | 101 2 | 10 | 102 3 | 20 | 201 4 | 20 | 202 5 | 20 | 203 ``` I'd like to query this table to get a result like this : ``` identifier | values[] 10 | {101, 102} 20 | {201, 202, 203} ``` I can't figure a way to do that. Is that possible? How?
This is a Postgres built-in since a few versions so you no longer need to define your own, the name is `array_agg()`. ``` test=> select array_agg(n) from generate_series(1,10) n group by n%2; array_agg -------------- {1,3,5,7,9} {2,4,6,8,10} ``` (this is Postgres 8.4.8). Note that no `ORDER BY` is specified, so the order of the result rows depends on the grouping method used (here, hash) ie, it is not defined. Example: ``` test=> select n%2, array_agg(n) from generate_series(1,10) n group by (n%2); ?column? | array_agg ----------+-------------- 1 | {1,3,5,7,9} 0 | {2,4,6,8,10} test=> select (n%2)::TEXT, array_agg(n) from generate_series(1,10) n group by (n%2)::TEXT; text | array_agg ------+-------------- 0 | {2,4,6,8,10} 1 | {1,3,5,7,9} ``` Now, I don't know why you get `{10,2,4,6,8}` and `{9,7,3,1,5}`, since `generate_series()` should send the rows in order.
Simple example: each course have many lessons, so if i run code below: ``` SELECT lessons.course_id AS course_id, array_agg(lessons.id) AS lesson_ids FROM lessons GROUP BY lessons.course_id ORDER BY lessons.course_id ``` i'd get next result: ``` ┌───────────┬──────────────────────────────────────────────────────┐ │ course_id │ lesson_ids │ ├───────────┼──────────────────────────────────────────────────────┤ │ 1 │ {139,140,141,137,138,143,145,174,175,176,177,147,... │ │ 3 │ {32,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,... │ │ 5 │ {663,664,665,649,650,651,652,653,654,655,656,657,... │ │ 7 │ {985,984,1097,974,893,971,955,960,983,1045,891,97... │ │ ... │ └───────────┴──────────────────────────────────────────────────────┘ ```
Concatenate multiple rows in an array with SQL on PostgreSQL
[ "", "sql", "postgresql", "" ]
Lets say I have the following table in MS SQL 2000 ``` Id | description | quantity | ------------------------------- 1 my desc 3 2 desc 2 2 ``` I need to display multiple rows based on the quantity, so I need the following output: ``` Id | description | quantity | ----------------------------- 1 my desc 1 1 my desc 1 1 my desc 1 2 desc 2 1 2 desc 2 1 ``` Any ideas how to accomplish this?
This works just fine, no need for any cursors on this one. It may be possible to fangle something out without a number table as well. *Note* if going for this kind of solution I would keep a number table around and not recreate it every time I ran the query. ``` create table #splitme (Id int, description varchar(255), quantity int) insert #splitme values (1 ,'my desc', 3) insert #splitme values (2 ,'desc 2', 2) create table #numbers (num int identity primary key) declare @i int select @i = max(quantity) from #splitme while @i > 0 begin insert #numbers default values set @i = @i - 1 end select Id, description, 1 from #splitme join #numbers on num <= quantity ```
``` DECLARE @Id INT DECLARE @Description VARCHAR(32) DECLARE @Quantity INT DECLARE @Results TABLE (Id INT, [description] VARCHAR(32), quantity INT) DECLARE MyCursor CURSOR FOR SELECT Id, [description], quantity FROM MyTable OPEN MyCursor FETCH NEXT FROM MyCursor INTO @Id, @Description, @Quantity WHILE @@FETCH_STATUS = 0 BEGIN WHILE @Quantity > 0 BEGIN INSERT INTO @Results ( Id, [description], quantity ) VALUES ( @Id, @Description, 1 ) SET @Quantity = @Quantity - 1 END FETCH NEXT FROM MyCursor INTO @Id, @Description, @Quantity END CLOSE MyCursor DEALLOCATE MyCursor SELECT * FROM @Results ``` By the way, cursors are *generally* considered evil. So I will both recommend against something like this, and thank everyone in advance for their flames ;) (But it should work)
How to Split Sql Int Value into Multiple Rows
[ "", "sql", "" ]
One of the things I love about Visual Studio 2008 is the ability to refactor and reorganize the "using" directives in source code files (this may have been in 2005 as well, I don't remember). Specifically, I'm talking about how you can have it both reorganize the directives to be alphabetical (though with the core FCL libraries floating to the top) and removing any directives which don't need to be there (either never used or no longer used). Is there any way to automate this refactoring (the sorting and trimming) across an entire old codebase? Either through all of the files in a solution or across multiple solution files.
I believe you can do it solution wide using [Power Commands](http://code.msdn.microsoft.com/PowerCommands) From PowerCommands Documentation: > Remove and Sort Usings > This command removes and sort using statements for all classes given a project. It is useful, for example, in removing or organizing the using statements generated by a wizard. This command can be executed from a solution node or a single project node.
[ReSharper](http://www.jetbrains.com/resharper) is a (commercial) Visual Studio plugin that has a "Code Cleanup" utility than can be run at a solution-wide level. The utility detects and removes unreferenced using statements, and performs other useful maintenance. I am unsure if it provides functionality to sort them, however.
Refactor "using" directives over an entire codebase?
[ "", "c#", "visual-studio-2008", "refactoring", "using-directives", "" ]
A few months back I serialized a java.io.Serializable object into a file. Now I need to read the contents, but since then the serialVersionUID has changed, and now I'm getting a "class incompatible" error. I know for a fact that none of the data members have changed, so the only barrier is the serialVersionUID check. Is there a way to either disable the check or to modify the serialVersionUID in the binary file? CLARIFICATION This question is assuming that I can't edit the source. Is there a way I can hack the .class file or perhaps hack the serialized object file (use a hex editor and change a value at some certain offset)?
As a hack, you can generate the serialVer your jvm is probably using using the serialver tool: serialver -classpath whatever com.foo.bar.MyClass If you then manually set the serialVerUID in your class it ought to match and you ought to be able to load, assuming you haven't changed the class in such a way as to invalidate.
Why not modify the serialVersionUID in your current version instead as described in the [Serialization](http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html) documentation?
Java - Modifying serialVersionUID of binary serialized object
[ "", "java", "serialization", "serialversionuid", "" ]
I'd like to communicate with a USB device under Windows and Java but I can't find a good library to do so. I don't want the user to have to install any extra hardware or device drivers to make this work. That is, I want to be able to interact with USB just like other Windows applications do. I am familiar with jUSB and JSR 80 but both seem to be dead projects (at least for Windows).
I did quite a bit of research on this some time ago, and the unfortunate fact was that all the useful free USB+Windows+Java projects were dead. There is commercial and expensive (price $39.99 is not per developer, but per copy of your software sold!) [JCommUSB](http://www.icaste.com/) library which probably works, although I have no experience of it; we had to build our own custom C wrappers to the USB drivers and communicate with them through JNI.
libusb-win32 requires you to install their generic driver, which then makes a USB device available to you. I'm not sure that it's possible to do driver-less access of an USB device unless the device belongs to one of several standard classes (storage and HID, in particular). There is a [Java wrapper for libusb-win32](http://sourceforge.net/projects/libusbjava/) which might work for you. I haven't used it myself, though.
How to communicate with a USB device under Windows and Java?
[ "", "java", "windows", "usb", "" ]
have a weird situation. I'm using Glassfish server for my Enterprise application. In that application i'm using JSF, Richfaces, Quartz, Jasper Reports, and Commons Email. When I build and deploy application to my dev. computer, dev and test servers, everything works fine. But when I deploy app to Production server with same glassfish I can't run Quartz scheduler. It's giving me that there is some problem with commons-collections. I know there is a conflict somewhere but I can't find where. Can you give me some pointers where to look. By the way I'm using NetBeans 6.5. Here is the log: ``` [#|2009-02-13T02:00:03.055+0000|WARNING|sun-appserver9.1|javax.enterprise.resource.webcontainer.jsf.lifecycle|_ThreadID=22;_ThreadName=httpSSLWorkerThread-80-4;_RequestID=97d21f45-2489-486c-b8d9-68625776c546;|#{SchedulerController.play}: java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; javax.faces.FacesException: #{SchedulerController.play}: java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:107) at javax.faces.component.UICommand.broadcast(UICommand.java:383) at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:321) at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:296) at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:253) at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:466) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:97) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244) at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:411) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:317) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:198) at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178) at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290) at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:390) at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:517) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:198) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:288) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:271) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:202) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:206) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:150) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080) at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:272) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:637) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:568) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:813) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214) at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265) at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106) Caused by: javax.faces.el.EvaluationException: java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:91) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:91) ... 43 more Caused by: java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; at org.quartz.JobDetail.<init>(JobDetail.java:85) at englearn.elc.controller.SchedulerController.play(SchedulerController.java:43) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.el.parser.AstValue.invoke(AstValue.java:187) at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:77) ... 44 more |#] [#|2009-02-13T02:00:03.055+0000|WARNING|sun-appserver9.1|javax.enterprise.resource.webcontainer.jsf.lifecycle|_ThreadID=22;_ThreadName=httpSSLWorkerThread-80-4;_RequestID=97d21f45-2489-486c-b8d9-68625776c546;|executePhase(INVOKE_APPLICATION 5,com.sun.faces.context.FacesContextImpl@77d0f1) threw exception javax.faces.FacesException: #{SchedulerController.play}: java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:105) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244) at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:411) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:317) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:198) at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178) at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290) at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:390) at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:517) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:198) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:288) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:271) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:202) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:206) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:150) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080) at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:272) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:637) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:568) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:813) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214) at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265) at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106) Caused by: javax.faces.FacesException: #{SchedulerController.play}: java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:107) at javax.faces.component.UICommand.broadcast(UICommand.java:383) at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:321) at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:296) at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:253) at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:466) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:97) ... 37 more Caused by: javax.faces.el.EvaluationException: java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:91) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:91) ... 43 more Caused by: java.lang.NoSuchMethodError: org.apache.commons.collections.SetUtils.orderedSet(Ljava/util/Set;)Ljava/util/Set; at org.quartz.JobDetail.<init>(JobDetail.java:85) at englearn.elc.controller.SchedulerController.play(SchedulerController.java:43) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.el.parser.AstValue.invoke(AstValue.java:187) at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:77) ... 44 more |#] ```
A `java.lang.NoSuchMethodException` always indicates that the class file on the runtime classpath is not the same version as the class file that was on the compile-time classpath (if the method had been missing during compilation, the compile would have failed.) Specifically, the offending method in this case is: `java.util.Set org.apache.commons.collections.SetUtils.orderedSet(java.util.Set)` You have a different version of commons-collections in your production environment than you do in your development environment.
This is maybe caused because you are using a commons-collections.jar version which has not that method. To solve this,you need to upload this library (version 3.2.1 is the latest version available) and subsitute all the old commons-collections.jar that you have in your project for the new one (i recomend to make a Search in your Project folder to know all the places in which this library is,because it is surprisingly in lots of places,at least in my case...) Hope this helps all people with this horrible trouble! It took me a whole day to fix it! Good luck buddies :)
Libraries Conflict for Quartz
[ "", "java", "quartz-scheduler", "conflicting-libraries", "" ]
I am trying to plot a bunch of data points (many thousands) in Python using [matplotlib](http://matplotlib.sourceforge.net/index.html) so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data: ``` matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black') ``` Then I can look at it either with `pl.show()` and then save it. Or directly use `plt.savefig('filename.ps')` in the code to save it. The problem is this: when I use `pl.show()` to view the file in the GUI it looks great with small tiny black marks, however when I save from the `show()` GUI to a file or use directly `savefig` and then view the `ps` I created it looks different! Each marker has gained a little blue halo around it (as if it started at each point to connect them with the default blue lines, but did not) and the style is all wrong. Why does it change the style when saved? How do I stop python from forcing the style of the markers? And yes I have looked at some alternative packages like [CairoPlot](http://linil.wordpress.com/2008/09/16/cairoplot-11/), but I want to keep using matplotlib for now. **Update:** It turns out that the save to PNG first makes the colors turn out okay, but it forces a conversion of the image when I want to save it again as a `.ps` later (for inclusion in a PDF) and then I lose quality. How do I preserve the vector nature of the file and get the right formatting?
For nice-looking vectorized output, don't use the `'.'` marker style. Use e.g. `'o'` (circle) or `'s'` (square) (see `help(plot)` for the options) and set the `markersize` keyword argument to something suitably small, e.g.: ``` plot(x, y, 'ko', markersize=2) savefig('foo.ps') ``` That `'.'` (point) produces less nice results could be construed as a bug in matplotlib, but then, what *should* "point" mean in a vector graphic format?
Have you tried the `','` point shape? It creates "[pixels](http://matplotlib.org/api/markers_api.html)" (small dots, instead of shapes). You can play with the `markersize` option as well, with this shape?
Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers?
[ "", "python", "coding-style", "matplotlib", "" ]
I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons. Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod\_python, MySQL.
So far I have found no "nice" solution for this. I have some more strict soft realtime requirements (taking a picture from a cardboard box being labeled) so probably one of the approaches is fast enough for you. I assume emails can wait for a few minutes. * A "todo list" in the database processed by a cron job. * A "todo list" in the database processed permanently beeing polled by a daemon. * Using a custom daemon which gets notified by the webserver via an UDP packet (in Production today). Basically my own Queing system with the IP stack for handling the queue. * [Using ActiveMQ as a message broker](http://blogs.23.nu/c0re/2007/08/antville-15655/) - this didn't work out because of stability issues. Also to me Java Daemons are generally somewhat plump * Using Update Triggers in CouchDB. Nice but Update Triggers are not meant to do heavy image processing, so no good fit for my problem. So far I haven't tried RabbitMQ and XMPP/ejabebrd for handling the problem but they are on my list of next things to try. RabbitMQ got decent Python connectivity during 2008 and there are tons of XMPP libraries. But perhaps all you need is a correctly configured mailserver on the local machine. This probably would allow you to dump mails synchronously into the local mailserver and thus make your whole software stack much more simple.
In your specific case, where it's just an email queue, I wold take the easy way out and use [django-mailer](https://github.com/pinax/django-mailer). As a nice side bonues there are other pluggable projects that are smart enough to take advantage of django-mailer when they see it in the stack. As for more general queue solutions, I haven't been able to try any of these yet, but here's a list of ones that look more interesting to me: 1. [pybeanstalk/beanstalkd](https://github.com/beanstalkd/pybeanstalk) 2. [python interface to gearman](https://pythonhosted.org/gearman/) (which is probably much more interesting now with the release of the [C version of gearman](http://www.gearmanproject.org/doku.php)) 3. [memcacheQ](http://memcachedb.org/memcacheq/) 4. [stomp](http://morethanseven.net/2008/09/14/using-python-and-stompserver-get-started-message-q/) 5. [Celery](http://docs.celeryproject.org/en/latest/getting-started/introduction.html)
Advice on Python/Django and message queues
[ "", "python", "django", "message-queue", "" ]
I am having a dilemma in the logic of this particular issue. Forgive me if this is quite newbie question but I'd rather have a solid bg on it. There are a lot of examples of this all around the web where you click on an element to display another element. such case may be a menu that when you hover your mouse on it (or click on it) its get displayed. Later the element gets hidden either on mouse out, OR CLICKING ON ANY OTHER ELEMENT.. so, how is this achieved? I am sure the solution is not to bind a "hideElem" function on all the elements. regards,
``` $('#target').bind('click', function(event) { var $element = $('#element'); $element.show(); $(document).one('click', function() { $element.hide(); }); // If you don't stop the event, it will bubble up to the document // and trigger the click event we just bound. // This will hide the element right now just after showing it, // we don't want that. event.stopPropagation(); } ``` You have to keep in mind that a Javascript event goes up and down the whole tree when begin fired. So you can bind event listeners to any parent when you want to listen for an event on many elements. This is called event delegation.
I haven't done it in a while, but an easy solution is to add a click event to the top of the DOM tree that will close the open element. Here's an example in psuedo-javascript: ``` document.body.onclick = function() { element.style.display = "none"; } ``` If you need complex behaviors inside the "shown" element, make sure your preventing the necessary events from propagating up the DOM tree. ``` element.onclick = function(e) { e.stopPropagation() } ```
Logic behind hiding elements
[ "", "javascript", "jquery", "dom", "" ]
I have the following JPA entity classes (example case). A House belongs on a single Street. A Street has many Houses. ``` @Entity public class House { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public Integer id; public String name @ManyToOne public Street street; } @Entity public class Street { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public Integer id; @OneToMany(mappedBy="street") public Set<House> houses; } ``` I have the generation type set to identity, which is supposed to auto assign a new ID. When creating a new House with a new Street, I have to first create and persist Street, followed by House. This is because I do not have CascadeType set to PERSIST, so it has to be done manually [1]. However, while inserting a newly created Street: ``` Street street = new Street(); entityManager.persist(street); ``` Hibernate/JPA generates the following SQL query: ``` insert into Street default values ``` which MySQL doesn't like. ``` Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'default values' at line 1 ``` Any ideas why? I'm using Java 6, MySQL 5.0.67 with Hibernate's implementation of JPA (version 3.2.1.ga). [1] EJB 3 in Action pages 318-319
Standard SQL specifies this optional syntax for `INSERT`: ``` INSERT INTO <Table Name> DEFAULT VALUES ``` This is legal SQL syntax, supported, for example, by [Microsoft SQL Server](http://msdn.microsoft.com/en-us/library/ms174335(SQL.90).aspx), [PostgreSQL](http://www.postgresql.org/docs/current/static/dml-insert.html), and [SQLite](http://www.sqlite.org/lang_insert.html), but not by Oracle, IBM DB2, or MySQL. MySQL supports other syntax that achieve the same result: ``` INSERT INTO <Table Name> () VALUES () INSERT INTO <Table Name> (col1, col2, col3) VALUES (DEFAULT, DEFAULT, DEFAULT) ``` In Hibernate, you should [configure](http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html) the SQL dialect properly, and it's up to Hibernate to generate valid SQL for the target RDBMS brand. ``` import org.hibernate.cfg.Configuration; Configuration cfg = new Configuration(); cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect"); ``` You can also specify properties by placing a file named `hibernate.properties` in a root directory of the classpath.
If you don't have an error in your SQL statement, then you might want to check your table column name as it can contain a predefined name that Mysql uses; for example 'column' which can't be used as a table column name
Hibernate generates invalid SQL query with MySQL
[ "", "java", "hibernate", "orm", "jpa", "" ]
I have a regular expression to match 2 different number formats: *\=(?[0-9]+)\?|\+(?[0-9]+)\?* This should return 9876543 as its Value for *;1234567890123456?+1234567890123456789012345123=9876543?* and *;1234567890123456?+9876543?* What I would like is to be able to return another value along with the matched 'Value'. So, for example, if the first string was matched, I'd like it to return: Value: 9876543 Format:  LongFormat And if matched in the second string: Value: 9876543 Format:  ShortFormat Is this possible?
Another option, which is not quite the solution you wanted, but saves you using two separate regexes, is to use named groups, if your implementation supports it. Here is some C#: ``` var regex = new Regex(@"\=(?<Long>[0-9]+)\?|\+(?<Short>[0-9]+)\?"); string test1 = ";1234567890123456?+1234567890123456789012345123=9876543?"; string test2 = ";1234567890123456?+9876543?"; var match = regex.Match(test1); Console.WriteLine("Long: {0}", match.Groups["Long"]); // 9876543 Console.WriteLine("Short: {0}", match.Groups["Short"]); // blank match = regex.Match(test2); Console.WriteLine("Long: {0}", match.Groups["Long"]); // blank Console.WriteLine("Short: {0}", match.Groups["Short"]); // 9876543 ``` Basically just modify your regex to include the names, and then regex.Groups[GroupName] will either have a value or wont. You could even just use the Success property of the group to know which matched (match.Groups["Long"].Success). *UPDATE:* You can get the group name out of the match, with the following code: ``` static void Main(string[] args) { var regex = new Regex(@"\=(?<Long>[0-9]+)\?|\+(?<Short>[0-9]+)\?"); string test1 = ";1234567890123456?+1234567890123456789012345123=9876543?"; string test2 = ";1234567890123456?+9876543?"; ShowGroupMatches(regex, test1); ShowGroupMatches(regex, test2); Console.ReadLine(); } private static void ShowGroupMatches(Regex regex, string testCase) { int i = 0; foreach (Group grp in regex.Match(testCase).Groups) { if (grp.Success && i != 0) { Console.WriteLine(regex.GroupNameFromNumber(i) + " : " + grp.Value); } i++; } } ``` I'm ignoring the 0th group, because that is always the entire match in .NET
No, you can't match text that isn't there. The match can only return a substring of the target. You essentially want to match against two patterns and take different actions in each case. See if you can separate them in your code: ``` if match(\=(?[0-9]+)\?) then return 'Value: ' + match + 'Format: LongFormat' else if match(\+(?[0-9]+)\?) then return 'Value: ' + match + 'Format: ShortFormat' ``` (Excuse the dodgy pseudocode, but you get the idea.)
Regular expression that returns a constant value as part of a match
[ "", "c#", "regex", "" ]
How do I use a custom .tff font file I have with my current windows.forms application? I read some where that I use it as an embedded resource, but how do I set it the System.Drawing.Font type?
This article: [How to embed a true type font](https://web.archive.org/web/20141224204810/http://bobpowell.net/embedfonts.aspx) shows how to do what you ask in .NET. **How to embed a True Type font** > Some applications, for reasons of esthetics or a required visual > style, will embed certain uncommon fonts so that they are always there > when needed regardless of whether the font is actually installed on > the destination system. > > The secret to this is twofold. First the font needs to be placed in > the resources by adding it to the solution and marking it as an > embedded resource. Secondly, at runtime, the font is loaded via a > stream and stored in a PrivateFontCollection object for later use. > > This example uses a font which is unlikely to be installed on your > system. Alpha Dance is a free True Type font that is available from > the Free Fonts Collection. This font was embedded into the application > by adding it to the solution and selecting the "embedded resource" > build action in the properties. [![Figure 1. The Alpha Dance font file embedded in the solution.](https://i.stack.imgur.com/qSiPn.png)](https://i.stack.imgur.com/qSiPn.png) > Once the file has been successfully included in the resources you need > to provide a PrivateFontCollection object in which to store it and a > method by which it's loaded into the collection. The best place to do > this is probably the form load override or event handler. The > following listing shows the process. Note how the AddMemoryFont method > is used. It requires a pointer to the memory in which the font is > saved as an array of bytes. In C# we can use the unsafe keyword for > convienience but VB must use the capabilities of the Marshal classes > unmanaged memory handling. The latter option is of course open to C# > programmers who just don't like the unsafe keyword. > PrivateFontCollection pfc = new PrivateFontCollection(); ``` private void Form1_Load(object sender, System.EventArgs e) { Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("embedfont.Alphd___.ttf"); byte[] fontdata = new byte[fontStream.Length]; fontStream.Read(fontdata,0,(int)fontStream.Length); fontStream.Close(); unsafe { fixed(byte * pFontData = fontdata) { pfc.AddMemoryFont((System.IntPtr)pFontData,fontdata.Length); } } } ``` > Fonts may have only certain styles which are available and > unfortunately, selecting a font style that doesn't exist will throw an > exception. To overcome this the font can be interrogated to see which > styles are available and only those provided by the font can be used. > The following listing demonstrates how the Alpha Dance font is used by > checking the available font styles and showing all those that exist. > Note that the underline and strikethrough styles are pseudo styles > constructed by the font rendering engine and are not actually provided > in glyph form. ``` private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { bool bold=false; bool regular=false; bool italic=false; e.Graphics.PageUnit=GraphicsUnit.Point; SolidBrush b = new SolidBrush(Color.Black); float y=5; System.Drawing.Font fn; foreach(FontFamily ff in pfc.Families) { if(ff.IsStyleAvailable(FontStyle.Regular)) { regular=true; fn=new Font(ff,18,FontStyle.Regular); e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic); fn.Dispose(); y+=20; } if(ff.IsStyleAvailable(FontStyle.Bold)) { bold=true; fn=new Font(ff,18,FontStyle.Bold); e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic); fn.Dispose(); y+=20; } if(ff.IsStyleAvailable(FontStyle.Italic)) { italic=true; fn=new Font(ff,18,FontStyle.Italic); e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic); fn.Dispose(); y+=20; } if(bold && italic) { fn=new Font(ff,18,FontStyle.Bold | FontStyle.Italic); e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic); fn.Dispose(); y+=20; } fn=new Font(ff,18,FontStyle.Underline); e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic); fn.Dispose(); y+=20; fn=new Font(ff,18,FontStyle.Strikeout); e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic); fn.Dispose(); } b.Dispose(); } ``` > Figure 2 shows the application in action. [![Figure 2. The embedded Alpha Dance font.](https://i.stack.imgur.com/J4iLq.png)](https://i.stack.imgur.com/J4iLq.png) See the Form1\_Paint event handler, it shows specifically how to set the System.Drawing.Font type. It is based on using the System.Drawing.Text.PrivateFontCollection class. Hope this helps.
Use the [AddFontResourceEx](http://msdn.microsoft.com/en-us/library/dd183327(VS.85).aspx) API function through p/invoke, passing FR\_PRIVATE to prevent installing a global font. Then you should be able to pass the font name to the Font constructor as usual. Edit: If you use the [PrivateFontCollection](http://msdn.microsoft.com/en-us/library/system.drawing.text.privatefontcollection.aspx) and load the font from an external file, you don't even need this. If you load the font from an embedded resource, use Ash's solution.
Custom .ttf fonts to use in C# windows.Form
[ "", "c#", "winforms", "fonts", "" ]
I have a Visual Studio setup project that has an Installer class. In the installer class I set a setting as follows: ``` MessageBox.Show(Properties.Settings.Default.MySetting); Properties.Settings.Default.MySetting = "Foo"; Properties.Settings.Default.Save(); MessageBox.Show(Properties.Settings.Default.MySetting); ``` The problem is that even though I know that this code is being executed (I am doing other stuff), the setting is never set!! The message boxes do suggest that the value is being set, but when I go to the `.config` file the value is still blank! Anyone have any ideas why and/or a possible workaround?
What I do for my installers is to use the "file" attribute in App.Config. The appSettings block takes a "file" attribute, like so: ``` <appSettings file="user.config"> <add key="foo" value="some value unchanged by setup"/> </appSettings> ``` The "file" attribute is sort of like CSS, in that the most specific setting wins. If you have "foo" defined in user.config as well as App.config, the value in user.config is used. Then, I have a config generator that writes out a second appSettings block to user.config (or whatever you want to call it), using values in a dictionary. ``` using System.Collections.Generic; using System.Text; using System.Xml; namespace Utils { public class ConfigGenerator { public static void WriteExternalAppConfig(string configFilePath, IDictionary<string, string> userConfiguration) { using (XmlTextWriter xw = new XmlTextWriter(configFilePath, Encoding.UTF8)) { xw.Formatting = Formatting.Indented; xw.Indentation = 4; xw.WriteStartDocument(); xw.WriteStartElement("appSettings"); foreach (KeyValuePair<string, string> pair in userConfiguration) { xw.WriteStartElement("add"); xw.WriteAttributeString("key", pair.Key); xw.WriteAttributeString("value", pair.Value); xw.WriteEndElement(); } xw.WriteEndElement(); xw.WriteEndDocument(); } } } } ``` In your installer, just add something like the following in your Install method: ``` string configFilePath = string.Format("{0}{1}User.config", targetDir, Path.DirectorySeparatorChar); IDictionary<string, string> userConfiguration = new Dictionary<string, string>(); userConfiguration["Server"] = Context.Parameters["Server"]; userConfiguration["Port"] = Context.Parameters["Port"]; ConfigGenerator.WriteExternalAppConfig(configFilePath, userConfiguration); ``` We use it for our test, training, and production servers, so all we have to do is specify the machine name and password during the install, and everything's taken care of for us. It used to be a 3-hour process, including going through multiple config files to set passwords. Now it's almost entirely automated. Hope this helps.
Well in the end I gave up and had a RunOnce type of method to do this stuff after the app was installed.
How can I set application settings at install time (via installer class)
[ "", "c#", "setup-project", "appsettings", "" ]
I'm considering ditching PHP's `$_SESSION` (i.e. the server-side session handling, to add some language-agnostic flavor) and using signed cookies instead, since I've heard so much good about them (Flickr uses them, so they ought to be good enough for me too). I understand the basic context of the technique: Use cookies freely to pass key-value pairs from client to server, and sign them to make sure that the values aren't tampered with. But what would be a good way to implement the signing part? Also; since the traffic will probably be HTTP, is there a good way to send sensitive data (such as a user's password) with this method, while working against cookie-stealing and/or tampering?
## Why bother? I wouldn't use this technique for sensitive data. It can be useful in combination with a regular session though - you can give the client a cookie with a normal session id, but also include all those key/value pairs that your application needs on every page. This way, you can avoid hitting your session storage for every page request. You should aim to keep the amount of data pretty tight, since it will be sent with every request. With that in mind, onwards... ## Signing data with a hash If the data isn't sensitive, you can sign the values with [sha1](http://php.net/sha1) hash made from a combination of the key/value pairs and a shared secret. e.g. ``` $values=array( 'user_id'=>1, 'foo'=>'bar' ); $secret='MySecretSalt'; $plain=""; foreach($values as $key=>$value) { $plain.=$key.'|'.$value.'|'; } $plain.=$secret; $hash=sha1($plain); ``` Now give the client a cookie with all the values and the hash. You can check the hash when the cookie is presented. If the hash you calculate from values presented by the client doesn't match the expected hash, you know the values have been tampered with. ## Encrypting sensitive data For sensitive data, you'll need to encrypt the values. Check out the [mcrypt](http://uk.php.net/manual/en/book.mcrypt.php) extension which offers a lot of cryptographic functions. ## Cookie theft With regards to cookie stealing, if you're putting user credentials into a cookie and trusting it, then someone who obtains that cookie can impersonate that user until the password is changed. A good practice is to remember how you authenticated a user, and only grant certain privileges if the user explicitly logged in. For example, for a forum you might let someone post, but not change their account details like email address. There are other techniques for "autologin" cookies, involving giving such cookies a token value which you only allow to be used once. [Here's a good article](http://jaspan.com/improved_persistent_login_cookie_best_practice) on that technique. You could also look at including the client IP in a signed cookie, and if it doesn't match the IP presenting the cookie, you get them to log in again. This provides more protection, but won't work for people whose apparent IP address keeps changing. You could make it an optional feature, and give the user a way to opt out. Just an idle thought, I've not seen that done in practice :) For a nice article which explains session theft, hijack and fixation see [Sessions and Cookies](http://www.devshed.com/c/a/PHP/Sessions-and-Cookies) which offers a few more techniques to try, such as using the User-Agent header as an additional signature.
I made [CookieStorage](https://github.com/mrclay/old-misc/blob/master/php/MrClay/CookieStorage.php) exactly for this purpose. All stored values are securely signed with your private key via RIPEMD160 hashing (and salted with time), and optionally encrypted with RIJNDAEL256. Each value is stored with the timestamp, which is retrievable. [Signed example](http://mrclay.org/code_trunk/php/MrClay/CookieStorage/test.php). [Encrypted example](http://mrclay.org/code_trunk/php/MrClay/CookieStorage/test2.php). If you prefer, you can use the hash/encrypt/decrypt functions of your choice.
Tips on signed cookies instead of sessions
[ "", "php", "security", "session", "cookies", "" ]
[Eclipse](http://www.eclipse.org) the IDE is one of the best examples of a huge desktop application written in Java. Most Java applications I've seen usually rely on a batch or shell script to build a string with the class path of the application, and launch the JVM with the class path as an env variable. Eclipse, on the other hand, relies on a native launcher. Why is that ? What does this launcher do that scripts don't ? I remember reading an article about a year and a half ago that explained that "we're better off with a native launcher", but id did not explain the inner workings of the launcher.
The [Equinox launcher](http://wiki.eclipse.org/index.php/Equinox_Launcher) uses JNI to start the Java VM in the same process as the launcher. Using JNI also allows us to use SWT widgets in the splash screen. --- Actually, you can still have a script, since the launcher executable, eclipse.exe, has been broken into 2 pieces since 3.3M5: * the executable, and * a shared library (eg: eclipse\_1006.dll). The executable lives in the root of the eclipse install. The shared library is in a platform specific fragment, `org.eclise.equinox.launcher.[config]`, in the plugins directory. Moving the majority of the launcher code into a shared library that lives in a fragment means that that portion of the launch code can now be updated from an update site. Also, when starting from java, the shared library can be loaded via JNI in order to display the splash screen. As explained here, you can [start Eclipse 3.3 without the native launcher](http://eclipsenuggets.blogspot.com/2007/04/starting-eclipse-3.html), ``` java -jar plugins/org.eclipse.equinox.launcher_1.0.0.v20070319.jar ``` Note that the name of the jar-file is now version dependent causing naive scripts, that invoke the jar using the exact filename, to break once the jar-file gets updated. Instead you may want to look for a file matching `org.eclipse.equinox_*.jar`. Thankfully the Eclipse-wiki contains [appropriate scripting templates](http://wiki.eclipse.org/index.php/Starting_Eclipse_Commandline_With_Equinox_Launcher) that are useful in this case. If you want to avoid modifying existing scripts, you can also search for the Equinox Launcher plug-in, copy it into the Eclipse main directory and rename the copy into startup.jar.
Some of these are windows specific some are general. 1. Your shell integration is much improved compared to a batch script in the natively available scripting language of your target platform. 2. There is no need to launch an additional process to execute the script (this can be a big deal if you are scripting the IDE itself as part of your build/test/deploy cycle. 3. The executable headers normally define the 'bitness' of your program. Thus the executable can explicitly indicate it is allows/disallows 32 or 64 bit execution. 4. Executables on windows may be cryptographically signed. 5. Many malware/firewall guard programs maintain per executable white lists. As such it is much nicer when firing up eclipse (and it checks itself for updates on the web) for the first time to be presented with the pop up "Eclipse is trying to access the internet" rather than a generic "javaw.exe is trying to access the internet". It also allows the user finer grained control over this behaviour. 6. The process will show up on ps/task manager as "you\_app\_name" rather than java -jar "your jar file". This makes it easier to track/manage errant processes. Something not uncommon in a development setting.
Why does Eclipse use a native launcher?
[ "", "java", "eclipse", "native", "" ]
I'm currently trying to write data from an array of objects to a range in Excel using the following code, where `objData` is just an array of strings: ``` private object m = System.Type.Missing; object[] objData = getDataIWantToWrite(); Range rn_Temp; rn_Temp = (Range)XlApp.get_Range(RangeName, m); rn_Temp = rn_Temp.get_Resize(objData.GetUpperBound(), 1); rn_Temp.value2 = objData; ``` This very nearly works, the problem being that the range gets filled but every cell gets the value of the first item in the `objData`. The inverse works, i.e. ``` private object m = System.Type.Missing; object[] objData = new object[x,y] Range rn_Temp; rn_Temp = (Range)XlApp.get_Range(RangeName, m); rn_Temp = rn_Temp.get_Resize(objData.GetUpperBound(), 1); objData = (object[])rn_Temp.value2; ``` would return an array containing all of the values from the worksheet, so I'm not sure why reading and assignment work differently. Has anyone ever done this successfully? I'm currently writing the array cell by cell, but it needs to cope with lots (>50,000) of rows and this is therefore very time consuming.
This is an excerpt from method of mine, which converts a `DataTable` (the `dt` variable) into an array and then writes the array into a `Range` on a worksheet (`wsh` var). You can also change the `topRow` variable to whatever row you want the array of strings to be placed at. ``` object[,] arr = new object[dt.Rows.Count, dt.Columns.Count]; for (int r = 0; r < dt.Rows.Count; r++) { DataRow dr = dt.Rows[r]; for (int c = 0; c < dt.Columns.Count; c++) { arr[r, c] = dr[c]; } } Excel.Range c1 = (Excel.Range)wsh.Cells[topRow, 1]; Excel.Range c2 = (Excel.Range)wsh.Cells[topRow + dt.Rows.Count - 1, dt.Columns.Count]; Excel.Range range = wsh.get_Range(c1, c2); range.Value = arr; ``` Of course you do not need to use an intermediate `DataTable` like I did, the code excerpt is just to demonstrate how an array can be written to worksheet in single call.
Thanks for the pointers guys - the Value vs Value2 argument got me a different set of search results which helped me realise what the answer is. Incidentally, the Value property is a parametrized property, which must be accessed through an accessor in C#. These are called get\_Value and set\_Value, and take an optional enum value. If anyone's interested, [this explains it nicely](http://blogs.msdn.com/eric_carter/archive/2004/09/06/225989.aspx). It's possible to make the assignment via the Value2 property however, which is preferable as the interop documentation recommends against the use use of the get\_Value and set\_Value methods, for reasons beyond my understanding. The key seems to be the dimension of the array of objects. For the call to work the array must be declared as two-dimensional, even if you're only assigning one-dimensional data. I declared my data array as an `object[NumberofRows,1]` and the assignment call worked.
Write Array to Excel Range
[ "", "c#", "excel", "interop", "" ]
I'm new to Flex and done a few application with only client side programming. Now I'm trying to do the back-end stuff using PHP. Can some one explain where(which folder) to put the PHP file for the Flex file to communicate with PHP. I'm using Flexbuilder 3 IDE. Thanks
This all really depends on what you want. I would make a very different recommendation if you wanted to simply poll the server occasionally than if you wanted to have a regular interface between the two. If you are simply polling the server, I would recommend simply using the HTTPRequest class. It will allow you to create POST and GET data and serve to communicate relatively well. On the other hand, if you are looking to have a more complicated set of communications between the server and the SWF, your best bet is the RemoteObject class with either AMFPHP, WebOrb, or an equivalent (we use WebOrb where I work). This has the benefit of allowing you to have objects of similar name/type in both Flex and PHP, meaning that communication can be made a good deal more comprehensive. (If you are working this way, email me cwATallen-poole.com and I can give some pointers so that you do not have insane compiler arguments for Flex). The next option is to use the XMLSocket class, but that seems to be a bit more intense than what you are looking for.
Flex will not access your PHP script via the filesystem, you have to invoke your PHP script via a web server. The easiest solution is to use XML as in your data transport language. But you can get fancy and use something like BlazeDS
Flex with PHP
[ "", "php", "apache-flex", "" ]
I need to delete a certain line from a text file. What is the most efficient way of doing this? File can be potentially large(over million records). UPDATE: below is the code I'm currently using, but I'm not sure if it is good. ``` internal void DeleteMarkedEntries() { string tempPath=Path.GetTempFileName(); using (var reader = new StreamReader(logPath)) { using (var writer = new StreamWriter(File.OpenWrite(tempPath))) { int counter = 0; while (!reader.EndOfStream) { if (!_deletedLines.Contains(counter)) { writer.WriteLine(reader.ReadLine()); } ++counter; } } } if (File.Exists(tempPath)) { File.Delete(logPath); File.Move(tempPath, logPath); } } ```
The most straight forward way of doing this is probably the best, write the entire file out to a new file, writing all lines except the one(s) you don't want. Alternatively, open the file for random access. Read to the point where you want to "delete" the line. Skip past the line to delete, and read that number of bytes (including CR + LF - if necessary), write that number of bytes over the deleted line, advance both locations by that count of bytes and repeat until end of file. Hope this helps. **EDIT** - Now that I can see your code ``` if (!_deletedLines.Contains(counter)) { writer.WriteLine(reader.ReadLine()); } ``` Will not work, if its the line you don't want, **you still want to read it**, *just not write it*. The above code will neither read it or write it. The new file will be exactly the same as the old. You want something like ``` string line = reader.ReadLine(); if (!_deletedLines.Contains(counter)) { writer.WriteLine(line); } ```
Text files are sequential, so when deleting a line, you'll have to move all the following lines up. You can use file mapping (a win32 api that you can call through PInvoke) to make this operation a bit less painfull, but you surelly should considere using a non sequential structure for you file so that you can mark a line as deleted without realy removing it from the file... Especially if it should happen frenquently. If I've remember File Mapping Api should be added to .Net 4.
Efficient way to delete a line from a text file
[ "", "c#", "performance", "file-io", "" ]
In C, I can allocate a register for a variable, for example: ``` register int i = 0; ``` I am aware that Java is an interpreted language, and is many many abstractions away from the CPU. Is there any mechanism available to even request (and if the architecture doesn't allow it, so what) that my variable remains in a register instead of moving to cache or main memory? I don't suppose there is any way, but I have been pleasantly surprised before. Thank you,
No, there's no way to request this in Java. However, there are some things that you can do that will prevent a register from being used, such as applying the `volatile` modifier to a member variable.
`register` in C does not put a variable to register. It simply gives the compiler the hint, that it would probably be good to put it into a register. In Java there is no equivalent.
Java equivalent of register int?
[ "", "java", "c", "cpu-registers", "" ]
I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.
Everywhere. It's used [extensively by google](http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm) for one. See [list of python software](http://en.wikipedia.org/wiki/Python_software) for more info, and also [who uses python on the web?](http://www.python.org/doc/essays/ppt/www8-py-www/sld010.htm)
In many large companies it is a primary scripting language. Google is using it along with Java and C++ and almost nothing else. Also many web pages are built on top of python and Django. Another place is game development. Many games have their engines written in C++ but all the logic in Python. In other words it is one of the most valuable tools. This might be of interest for you as well: * [Is Python good for big software projects (not web based)?](https://stackoverflow.com/questions/35753/is-python-good-for-big-software-projects-not-web-based) * [Are there any good reasons why I should not use Python?](https://stackoverflow.com/questions/371966/are-there-any-good-reasons-why-i-should-not-use-python) * [What did you use to teach yourself python?](https://stackoverflow.com/questions/111857/what-did-you-use-to-teach-yourself-python)
Where is Python used? I read about it a lot on Reddit
[ "", "python", "" ]
I need a terse, clean way to implement this in asp.net mvc (+/- jquery or js)? User clicks an element in webform A; Webform B pops up; User interracts with webform B; On closing webform B, probably by a submit button, the source element in webform a is updated with a value from webform B Thanks.
With ASP.NET MVC, I'd probably render a DIV on the page, initially hidden, perhaps via AJAX if the contents depend on values selected on the initial page. I'd use the jQuery UI dialog plugin to popup the dialog. The dialog could contain a form that submits back to the server. You could also use the onclose handler for the dialog to both copy values from the inputs in the dialog for use on the rest of the page. If you populated the dialog via AJAX you could have the server generate the HTML -- say by rendering a partial view and returning it -- or return json and generate the dialog on the fly in the browser.
I've resorted to using cookies. I've found this to be the only reliable way to do this. I'm using GrayBox for my dialog, so I have a function in the dialog that looks like this: ``` function selectValue(id, name) { SetCookie("_someuniqueprefix_RetID", id); SetCookie("_someuniqueprefix_RetValue", name); parent.parent.GB_CURRENT.hide(); } ``` Then in my calling page I am launching the dialog which displays a partial in the GrayBox: ``` $(function() { var selectUrl = '/_somecontroller/Select'; // attach a method to the chooseButton to go and get a list of // contact persons to select from $("#chooseButton").click(function() { GB_showCenter('Select My thing', selectUrl, 500, 620, function() { var id = GetCookie("_someuniqueprefix_RetID"); var value = GetCookie("_someuniqueprefix_RetValue"); DeleteCookie("_someuniqueprefix_RetID", "/", ""); DeleteCookie("_someuniqueprefix_RetValue", "/", ""); $("#MyID").val(id); $("#MyName").val(value); }); }); }); ``` Also you'll need to grab a function off the web for SetCookie and GetCookie Hope that helps
How to return value from html popup
[ "", "javascript", "jquery", "asp.net-mvc", "popup", "modal-dialog", "" ]
I have some C# in which I create a reader on a connection (`ExecuteReader`), then for every row in that reader, perform another command (with `ExecuteNonQuery`). In this case is it better that I use `MultipleActiveResultSets=True` on my connection or use multiple connections?
Multiple Active Result Sets (MARS) was added specifically for this type of operation so that you don't have to have two connections open at the same time to be able to read from a SqlDataReader AND execute additional batches. MARS is compatible with SQL Server 2005 and above. To quote from MSDN docs: > Before the introduction of Multiple > Active Result Sets (MARS), developers > had to use either multiple connections > or server-side cursors to solve > certain scenarios. For more info see: > [MSDN Library - MARS Overview](http://msdn.microsoft.com/en-gb/library/cfa084cz.aspx) Worked example reading and updating data: > [MSDN Library - Manipulating Data (MARS)](http://msdn.microsoft.com/en-gb/library/yf1a7f4f.aspx) scroll down to 'Reading and Updating Data with MARS'
This is as far as I know the reason MARS was added, so yeah I think you should use it.
MultipleActiveResultSets=True or multiple connections?
[ "", "c#", ".net", "sql-server", "sql-server-2005", "ado.net", "" ]
I have got a collection. The coll has strings: ``` Location="Theater=2, Name=regal, Area=Area1" ``` and so on. I have to extract just the Name bit from the string. For example, here I have to extract the text 'regal' I am struggling with the query: Collection.Location.???? (what to add here) Which is the most short and precise way to do it? [Edit] : What if I have to add to a GroupBy clause Collection.GroupBy(????);
Another LINQ-style answer (without the overhead of a dictionary): ``` var name = (from part in location.Split(',') let pair = part.Split('=') where pair[0].Trim() == "Name" select pair[1].Trim()).FirstOrDefault(); ``` --- re group by (edit): ``` var records = new[] { new {Foo = 123, Location="Theater=2, Name=regal, Area=Area1"}, new {Foo = 123, Location="Name=cineplex, Area=Area1, Theater=1"}, new {Foo = 123, Location="Theater=2, Area=Area2, Name=regal"}, }; var qry = from record in records let name = (from part in record.Location.Split(',') let pair = part.Split('=') where pair[0].Trim() == "Name" select pair[1].Trim()).FirstOrDefault() group record by name; foreach (var grp in qry) { Console.WriteLine("{0}: {1}", grp.Key, grp.Count()); } ```
Expanding on Paul's answer: ``` var location = "Theater=2, Name=regal, Area=Area1"; var foo = location .Split(',') .Select(x => x.Split('=')) .ToDictionary(x => x[0].Trim(), x => x[1]); Console.WriteLine(foo["Name"]); ``` This populates the original string into a dictionary for easy reference. Again, no error checking or anything.
Extract portion of string
[ "", "c#", "" ]
I've been reading up on so-called "data grid" solutions for the Java platform including Terracotta, GigaSpaces and Coherence. I was wondering if anyone has real-world experience working any of these tools and could share their experience. I'm also really curious to know what scale of deployment people have worked with: are we talking 2-4 node clusters or have you worked with anything significantly larger than that? I'm attracted to Terracotta because of its "drop in" support for Hibernate and Spring, both of which we use heavily. I also like the idea of how it decorates bytecode based on configuration and doesn't require you to program against a "grid API." I'm not aware of any advantages to tools which use the approach of an explicit API but would love to hear about them if they do in fact exist. :) I've also spent time reading about memcached but am more interested in hearing feedback on these three specific solutions. I would be curious to hear how they measure up against memcached in the event someone has used both.
We had a 50 servers running a webservice application and all these servers were load balanced using bigIP. The requirement was to cache each user state so that subsequent states don't do the same processing again and get the data from previous state. This way the client of the webservice don't need to maintain state. We used Terracotta to cache the states and never faced any performance issue. At peak times number of request application is getting is 100 per second.
You may want to check out [Hazelcast](http://www.hazelcast.com) also. Hazelcast is an open source transactional, distributed/partitioned implementation of queue, topic, map, set, list, lock and executor service. It is super easy to work with; just add hazelcast.jar into your classpath and start coding. Almost no configuration is required. [Hazelcast](http://www.hazelcast.com) is released under Apache license and enterprise grade support is also available. Code is hosted at [Google Code](http://code.google.com/p/hazelcast/).
What would you recommend for a large-scale Java data grid technology: Terracotta, GigaSpaces, Coherence, etc?
[ "", "java", "memcached", "terracotta", "gigaspaces", "datagrid", "" ]
I know it can be done in Java, as I have used this technique quite extensively in the past. An example in Java would be shown below. (Additional question. What is this technique called? It's hard to find an example of this without a name.) ``` public abstract class Example { public abstract void doStuff(); } public class StartHere{ public static void main(string[] args){ Example x = new Example(){ public void doStuff(){ System.out.println("Did stuff"); } }; x.doStuff(); } } ``` Now, my main question would be, can this also be done in C#, and if so, how?
With lamba expressions and class initializers you can get the same behaviour with a bit of effort. ``` public class Example { public Action DoStuff; public Action<int> DoStuffWithParameter; public Func<int> DoStuffWithReturnValue; } class Program { static void Main(string[] args) { var x = new Example() { DoStuff = () => { Console.WriteLine("Did Stuff"); }, DoStuffWithParameter = (p) => { Console.WriteLine("Did Stuff with parameter " + p); }, DoStuffWithReturnValue = () => { return 99; } }; x.DoStuff(); x.DoStuffWithParameter(10); int value = x.DoStuffWithReturnValue(); Console.WriteLine("Return value " + value); Console.ReadLine(); } } ``` One problem with this solution that I just realized is that if you were to create fields in the Example class, the lambda expressions would not be able to access those fields. However, there is no reason that you could not pass the instance of Example to the lambda expressions which would give them access to any public state that example might hold. AFAIK that would be functionally equivalent to the Java Anonymous Inner Class. P.S. If you are going to vote an answer down, do us all a favour and add a comment as to why you disagree :-)
The Java technique is called "[Anonymous inner class](http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html)", and there is no equivalent in C#.
C#: Creating an instance of an abstract class without defining new class
[ "", "c#", "abstract-class", "abstract", "anonymous-class", "" ]
I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder. So I want to end up with a zip file with a single folder with files in. I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject. I started out with this: ``` def addFolderToZip(myZipFile,folder): folder = folder.encode('ascii') #convert path to ascii for ZipFile Method for file in glob.glob(folder+"/*"): if os.path.isfile(file): print file myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) elif os.path.isdir(file): addFolderToZip(myZipFile,file) def createZipFile(filename,files,folders): curTime=strftime("__%Y_%m_%d", time.localtime()) filename=filename+curTime; print filename zipFilename=utils.getFileName("files", filename+".zip") myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing for file in files: file = file.encode('ascii') #convert path to ascii for ZipFile Method if os.path.isfile(file): (filepath, filename) = os.path.split(file) myZipFile.write( file, filename, zipfile.ZIP_DEFLATED ) for folder in folders: addFolderToZip(myZipFile,folder) myZipFile.close() return (1,zipFilename) (success,filename)=createZipFile(planName,files,folders); ``` Taken from: <http://mail.python.org/pipermail/python-list/2006-August/396166.html> Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder. If I feed the path to a folder in myZipFile.write, I get > IOError: [Errno 13] Permission denied: '..\packed\bin' Any help is much welcome. Related question: [How do I zip the contents of a folder using python (version 2.5)?](https://stackoverflow.com/questions/296499/how-do-i-zip-the-contents-of-a-folder-using-python-version-2-5)
Ok, after i understood what you want, it is as simple as using the second argument of `zipfile.write`, where you can use whatever you want: ``` import zipfile myZipFile = zipfile.ZipFile("zip.zip", "w" ) myZipFile.write("test.py", "dir\\test.py", zipfile.ZIP_DEFLATED ) ``` creates a zipfile where `test.py` would be extracted to a directory called `dir` EDIT: I once had to create an empty directory in a zip file: it is possible. after the code above just delete the file test.py from the zipfile, the file is gone, but the empty directory stays.
You can also use shutil ``` import shutil zip_name = 'path\to\zip_file' directory_name = 'path\to\directory' # Create 'path\to\zip_file.zip' shutil.make_archive(zip_name, 'zip', directory_name) ``` This will put the whole folder in the zip.
Adding folders to a zip file using python
[ "", "python", "file", "directory", "zip", "" ]
How can I convert my C# code to DLL file in a way that the user of DLL can’t view my source code? When I make DLL in the way I always do by making a class library project, importing my classes and compiling it, the source code can still be viewed.
I believe you are looking for an obfuscator. This is a tool that will take a compiled DLL and rewrite the code with the intent of it not being meaningfully decompiled by another user. Visual Studio comes with a free [Dotfuscator](http://msdn.microsoft.com/en-us/library/ms227240(VS.80).aspx) Note, this will not actually prevent people from looking at your code. They will instead be looking at a very weird translation of your code. There is no way to prevent people from looking at decompiled versions of your code in C# or any other .Net language for that matter. This is not something that is unique to C#. It is fact a flaw of every language in existence. It's perfectly possible to decompile C code. The difference though is it's much easier to maintain a lot of the original code structure when decompiling managed languages (.Net and Java for instance) because the metadata maintains the original structure.
obfuscation is what you want to search for. There is a free one (that is limited) in visual studio called Dotfuscator. Uses fancy methods to rename your code and alter flowpaths to obscure it.
How to convert C# to DLL to hide the source code?
[ "", "c#", "visual-studio", "dll", "source-code-protection", "" ]
I have an in-memory "table" that might looks something like this: ``` Favorite# Name Profession --------- ---------- ------------------ 3 Names.Adam Profession.Baker 9 Names.Bob Profession.Teacher 7 Names.Carl Profession.Coder 7 Names.Dave Profession.Miner 5 Names.Fred Profession.Teacher ``` And what I want to do, is do quick and efficient lookups, using any of the 3 fields. In other words, I want: * `myTable[3]` and `myTable[Names.Adam]` and `myTable[Professions.Baker]` to all return `{3,Names.Adam,Profession.Baker}` * `myTable[Profession.Teacher]` to return both `{9,Names.Bob,Profession.Teacher}` and `{5,Names.Fred,Profession.Teacher}`. The table is built during runtime, according to the actions of the user, and cannot be stored in a database since it is used in sections in which database connectivity cannot be guaranteed. Right now, I "simply" (hah!) store this using 3 uber-Dictionaries, each keyed using one of the columns (FavoriteNumber, Name, Profession), and each value in the uber-Dictionaries holding 2 Dictionaries which are themselves keyed with each of the remaining columns (so the values in the "Name" uber-dictionary are of the type `Dictionary<FavoriteNumber,Profession[]>` and `Dictionary<Profession, FavoriteNumber[]>` This requires 2 lookups in 2 Dictionaries, and another traverse of an array (which usually holds 1 or 2 elements.) Can anyone suggest a better way to do this? I don't mind spending extra memory, since the table is likely to be small (no more than 20 entries) but I'm willing to sacrifice a little CPU to make it more readily maintainable code...
Not really however using a dictionary, but if you create a collection of classes like this ``` class Person { public int FavoriteNumber; public string Name; public string Profession; } ``` you can use LINQ to search the collections. ``` IList<Person> people = /* my collection */; var selectedPeople = people.Where(p => p.FavoriteNumber = 3); var selectedPeople2 = people.Where(p => p.Name == "Bob"); var selectedPeople3 = people.Where(p => p.Profession = "Teacher"); ``` or if you prefer the normal LINQ syntax ``` var selectedPeople4 = from p in people where p.Name == "Bob" select p; ``` Each of these `selectedPeople` variables will be typed as `IEnumerable<Person>` and you can use a loop to search through them.
For 20 rows, just use [linear scanning](https://stackoverflow.com/questions/515887/in-c-is-there-out-of-the-box-way-to-build-a-3-way-lookup-table/515921#515921) - it will be the most efficient in every way. For larger sets; hzere's an approach using LINQ's `ToLookup` and delayed indexing: ``` public enum Profession { Baker, Teacher, Coder, Miner } public class Record { public int FavoriteNumber {get;set;} public string Name {get;set;} public Profession Profession {get;set;} } class Table : Collection<Record> { protected void Rebuild() { indexName = null; indexNumber = null; indexProfession = null; } protected override void ClearItems() { base.ClearItems(); Rebuild(); } protected override void InsertItem(int index, Record item) { base.InsertItem(index, item); Rebuild(); } protected override void RemoveItem(int index) { base.RemoveItem(index); Rebuild(); } protected override void SetItem(int index, Record item) { base.SetItem(index, item); Rebuild(); } ILookup<int, Record> indexNumber; ILookup<string, Record> indexName; ILookup<Profession, Record> indexProfession; protected ILookup<int, Record> IndexNumber { get { if (indexNumber == null) indexNumber = this.ToLookup(x=>x.FavoriteNumber); return indexNumber; } } protected ILookup<string, Record> IndexName { get { if (indexName == null) indexName = this.ToLookup(x=>x.Name); return indexName; } } protected ILookup<Profession, Record> IndexProfession { get { if (indexProfession == null) indexProfession = this.ToLookup(x=>x.Profession); return indexProfession; } } public IEnumerable<Record> Find(int favoriteNumber) { return IndexNumber[favoriteNumber]; } public IEnumerable<Record> Find(string name) { return IndexName[name]; } public IEnumerable<Record> Find(Profession profession) { return IndexProfession[profession]; } } ```
In C#, is there out-of-the-box way to build a 3-way lookup table?
[ "", "c#", "lookup", "" ]
Suppose you need to define a class which all it does is hold constants. ``` public static final String SOME_CONST = "SOME_VALUE"; ``` What is the preferred way of doing this? 1. Interface 2. Abstract Class 3. Final Class Which one should I use and why? --- *Clarifications to some answers:* **Enums** - I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way. **Interface** - I'm not going to set any class as one that implements the interface. Just want to use the interface to call constants like so: `ISomeInterface.SOME_CONST`.
Use a final class, and define a private constructor to hide the public one. For simplicity you may then use a static import to reuse your values in another class ``` public final class MyValues { private MyValues() { // No need to instantiate the class, we can hide its constructor } public static final String VALUE1 = "foo"; public static final String VALUE2 = "bar"; } ``` in another class : ``` import static MyValues.* //... if (VALUE1.equals(variable)) { //... } ```
Your clarification states: "I'm not going to use enums, I am not enumerating anything, just collecting some constants which are not related to each other in any way." If the constants aren't related to each other at all, why do you want to collect them together? Put each constant in the class which it's most closely related to.
How do you define a class of constants in Java?
[ "", "java", "class-constants", "" ]
I have a Java program using AWT which I would like to run on a headless system. The display for the program does nothing other than display stats. When the program finishes, it exits. There is no user interaction on the display. The program creates an output file which I use in my build system. Is there a way to get the Java program to run without an X11 display configured? Can I force Java to run the program without trying to display anything? I do not have access to the source code (it is just .jar file), so I can't make modifications to the source. Any thoughts on how I could get this to work?
The underlying question here is how to run Java applications without an X server; providing a "fake" X server is only one option. In Java 1.4 and up, you can do the following: ``` java -Djava.awt.headless=true ``` This allows applications which use AWT to run on headless systems even without an X server.
Xvfb can do what you ask for. I've not used it myself, but here is a link to wikipedia: <http://en.wikipedia.org/wiki/Xvfb>
Fake X11 display?
[ "", "java", "linux", "awt", "x11", "" ]
When I run my unit tests in my project I am seeing a result "Not executed" for every one. I have restarted my computer so I doubt this is some kind of hung process issue. Google has revealed nothing. Does anyone have any ideas?
What a PITA! The IDE doesn't show any errors. In order to determine the error you have to do this 1. Open the Visual Studio command prompt 2. Change to the directory where the binary output of your test project is. 3. Type mstest /testcontainer:The.Name.Of.Your.Test.Assembly.dll At the bottom of the output you will see the following text > Run has the following issue(s): In my case it was the following: Failed to queue test run 'Peter Morris@PETERMORRIS-PC 2009-02-09 10:00:37': Test Run deployment issue: The location of the file or directory 'C:\SomePath\SomeProject.Tests\bin\Debug\Rhino.Mocks.dll' is not trusted. Now if VS had told me this in the IDE I could have fixed it in minutes! All you have to do is open Windows Explorer and find that DLL. Right-click on it and go to Properties. Then click the "Unblock" button. What a complete waste of my time!
**Unit tests not executed** I've found that it is good advice to never have a constructor for a unit test class. If anything in a constructor ever throws, the test will just be reported as "not executed". Put test initialization in a TestInitialize method instead. Exceptions thrown there are reported by the IDE. **Blocked Binaries** Usually you have to unblock the ZIP file itself before you extract binaries from it, and then all the binaries will be unblocked. If you try to unblock the binaries themselves the unblocking doesn't "stick".
Why are all my Visual Studio test results "Not executed"
[ "", "c#", "unit-testing", "visual-studio-2008", "" ]
I've created a control derived from ComboBox, and wish to unit test its behaviour. However, it appears to be behaving differently in my unit test to how it behaves in the real application. In the real application, the Combobox.DataSource property and the .Items sync up - in other words when I change the Combobox.DataSource the .Items list immediately and automatically updates to show an item for each element of the DataSource. In my test, I construct a ComboBox, assign a datasource to it, but the .Items list doesn't get updated at all, remaining at 0 items. Thus, when I try to update the .SelectedIndex to 0 in the test to select the first item, I recieve an ArgumentOutOfRangeException. Is this because I don't have an Application.Run in my unit test starting an event loop, or is this a bit of a red herring? EDIT: More detail on the first test: ``` [SetUp] public void SetUp() { mECB = new EnhancedComboBox(); mECB.FormattingEnabled = true; mECB.Location = new System.Drawing.Point( 45, 4 ); mECB.Name = "cboFind"; mECB.Size = new System.Drawing.Size( 121, 21 ); mECB.TabIndex = 3; mECB.AddObserver( this ); mTestItems = new List<TestItem>(); mTestItems.Add( new TestItem() { Value = "Billy" } ); mTestItems.Add( new TestItem() { Value = "Bob" } ); mTestItems.Add( new TestItem() { Value = "Blues" } ); mECB.DataSource = mTestItems; mECB.Reset(); mObservedValue = null; } [Test] public void Test01_UpdateObserver() { mECB.SelectedIndex = 0; Assert.AreEqual( "Billy", mObservedValue.Value ); } ``` The test fails on the first line, when trying to set the SelectedIndex to 0. On debugging, this appears to be because when the .DataSource is changed, the .Items collection is not updated to reflect this. However, on debugging the real application, the .Items collection is always updated when the .DataSource changes. Surely I don't have to actually render the ComboBox in the test, I don't even have any drawing surfaces set up to render on to! Maybe the only answer I need is "How do I make the ComboBox update in the same way as when it is drawn, in a unit test scenario where I don't actually need to draw the box?"
Since you're simply calling the constructor, a lot of functionality of the combobox will not work. For example, the items will be filled when the ComboBox is drawn on screen, on a form. This does not happen when constructing it in a unit test. Why do you want to write a unit test on that combobox? Can't you seperate the logic which now is in the custom control? For example put this in a controller, and test that? Why don't you test on the DataSource property instead of the Items collection?
I'm sure that `Application.Run` absence cannot affects any control's behavior
Testing Custom Control derived from ComboBox
[ "", "c#", ".net", "winforms", "unit-testing", "custom-controls", "" ]
.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization. Arrays are very easy to initialize with a default value, and by definition they already have certain size: ``` string[] Ar = new string[10]; ``` Which allows one to safely assign random items, say: ``` Ar[5]="hello"; ``` with list things are more tricky. I can see two ways of doing the same initialization, neither of which is what you would call elegant: ``` List<string> L = new List<string>(10); for (int i=0;i<10;i++) L.Add(null); ``` or ``` string[] Ar = new string[10]; List<string> L = new List<string>(Ar); ``` What would be a cleaner way? EDIT: The answers so far refer to capacity, which is something else than pre-populating a list. For example, on a list just created with a capacity of 10, one cannot do `L[2]="somevalue"` EDIT 2: People wonder why I want to use lists this way, as it is not the way they are intended to be used. I can see two reasons: 1. One could quite convincingly argue that lists are the "next generation" arrays, adding flexibility with almost no penalty. Therefore one should use them by default. I'm pointing out they might not be as easy to initialize. 2. What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list.
I can't say I need this very often - could you give more details as to why you want this? I'd probably put it as a static method in a helper class: ``` public static class Lists { public static List<T> RepeatedDefault<T>(int count) { return Repeated(default(T), count); } public static List<T> Repeated<T>(T value, int count) { List<T> ret = new List<T>(count); ret.AddRange(Enumerable.Repeat(value, count)); return ret; } } ``` You *could* use `Enumerable.Repeat(default(T), count).ToList()` but that would be inefficient due to buffer resizing. Note that if `T` is a reference type, it will store `count` copies of the reference passed for the `value` parameter - so they will all refer to the same object. That may or may not be what you want, depending on your use case. EDIT: As noted in comments, you could make `Repeated` use a loop to populate the list if you wanted to. That would be slightly faster too. Personally I find the code using `Repeat` more descriptive, and suspect that in the real world the performance difference would be irrelevant, but your mileage may vary.
``` List<string> L = new List<string> ( new string[10] ); ``` See [List(IEnumerable) constructor](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor?view=net-8.0).
How to initialize a List<T> to a given size (as opposed to capacity)?
[ "", "c#", ".net", "generics", "list", "initialization", "" ]
I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which doesn't reference a specific instance. So, what does the first parameter of a @classmethod (canonically 'self') refer to if the method is meant to be called without an instance reference?
[class itself](http://docs.python.org/library/functions.html#classmethod): > A class method receives the class as implicit first argument, just like an instance method receives the instance. ``` class C: @classmethod def f(cls): print(cls.__name__, type(cls)) >>> C.f() C <class 'type'> ``` and it's `cls` canonically, btw
The first parameter of a classmethod is named `cls` by convention and refers to the the class object *on which the method it was invoked*. ``` >>> class A(object): ... @classmethod ... def m(cls): ... print cls is A ... print issubclass(cls, A) >>> class B(A): pass >>> a = A() >>> a.m() True True >>> b = B() >>> b.m() False True ```
What does 'self' refer to in a @classmethod?
[ "", "python", "self", "class-method", "" ]
If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script? How do I get control early enough to issue an error message and exit? For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python. I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program: ``` import sys if sys.version_info < (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x ``` When run under 2.4, I want this result ``` $ ~/bin/python2.4 tern.py must use python 2.5 or greater ``` and not this result: ``` $ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax ``` (Channeling for a coworker.)
You can test using `eval`: ``` try: eval("1 if True else 2") except SyntaxError: # doesn't have ternary ``` Also, `with` *is* available in Python 2.5, just add `from __future__ import with_statement`. EDIT: to get control early enough, you could split it into different `.py` files and check compatibility in the main file before importing (e.g. in `__init__.py` in a package): ``` # __init__.py # Check compatibility try: eval("1 if True else 2") except SyntaxError: raise ImportError("requires ternary support") # import from another module from impl import * ```
Have a wrapper around your program that does the following. ``` import sys req_version = (2,5) cur_version = sys.version_info if cur_version >= req_version: import myApp myApp.run() else: print "Your Python interpreter is too old. Please consider upgrading." ``` You can also consider using `sys.version()`, if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do. And there might be more elegant ways to do this.
How can I check for Python version in a program that uses new language features?
[ "", "python", "version", "" ]
I'm using the Flamingo ribbon and the Substance Office 2007 look and feel. Of course now **every** control has this look and feel, even those on dialog boxes. What I want is something like in Office 2007, where the ribbons have their Office 2007 look, but other controls keep their native Vista/XP look. Is it possible to assign certain controls a different look and feel? Perhaps using some kind of chaining or a proxy look and feel?
I just discovered: Since [Substance 5.0](https://substance.dev.java.net/release-info/5.0/release-info.html) the [SKIN\_PROPERTY](https://substance.dev.java.net/docs/clientprops/SkinProperty.html) is available. It allows assigning different skins to different `JRootPanes` (i.e. `JDialog`, `JFrame`, `JInternalFrame`) A little trick: I override `JInternalFrame` to remove the extra border and the title pane so that it looks just like a borderless panel. That way it is possible to create the impression, that different parts of a form/dialog have different looks.
Here is a library which will automaticaly change the look and feel. I am not sure it this will done for every component in a different way, but you should take a look at it. [pbjar.org](http://www.pbjar.org/dynamicloca.html) This book should be useful if you want to go deep into look and feel [/java-look-and-feel-design-guidelines-second-edition](http://2020ok.com/books/29/java-look-and-feel-design-guidelines-second-edition-37029.htm) I would be glad to see some code example, if someone can write it, feel free to get starting. **EDIT:** In this forum thread [Thread](http://forums.java.net/jive/thread.jspa?messageID=236002&tstart=0) i found the following description > Swing uses a Look & Feel (a PLAF). > PLAFs aren't attached on a per-JFrame > level. They are attached on a per-VM > level. It is almost impossible to mix > PLAFs within one application. I have > seen a few attempts, all failed.
Can I use two different look and feels in the same Swing application?
[ "", "java", "swing", "look-and-feel", "substance", "" ]
I have 5 columns corresponding to answers in a trivia game database - right, wrong1, wrong2, wrong3, wrong4 I want to return all possible answers without duplicates. I was hoping to accomplish this without using a temp table. Is it possible to use something similar to this?: ``` select c1, c2, count(*) from t group by c1, c2 ``` But this returns 3 columns. I would like one column of distinct answers. Thanks for your time
This should give you all distinct values from the table. I presume you'd want to add where clauses to select only for a particular question. However, this solution requires 5 subqueries and can be slow if your table is huge. ``` SELECT DISTINCT(ans) FROM ( SELECT right AS ans FROM answers UNION SELECT wrong1 AS ans FROM answers UNION SELECT wrong2 AS ans FROM answers UNION SELECT wrong3 AS ans FROM answers UNION SELECT wrong4 AS ans FROM answers ) AS Temp ```
``` SELECT DISTINCT(ans) FROM ( SELECT right AS ans FROM answers UNION SELECT wrong1 AS ans FROM answers UNION SELECT wrong2 AS ans FROM answers UNION SELECT wrong3 AS ans FROM answers UNION SELECT wrong4 AS ans FROM answers ) AS Temp ``` The DISTINCT is superfluous, because the UNION will not return rows that are identical for all columns. (When you want duplicated, or if you know that no duplicates exist, use UNION ALL for faster performance) > > This will give you a single list containing all the answers. You'll still have duplicates though if you have multiple copies of the same answer within a single column. That should not be the case if you use UNION, only if you use UNION ALL ``` SELECT [value] INTO #TEMP FROM ( SELECT [value] = 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 1 ) AS X (4 row(s) affected) SELECT [value] FROM #TEMP value ----------- 1 2 3 1 (4 row(s) affected) SELECT [value] FROM #TEMP UNION SELECT [value] FROM #TEMP value ----------- 1 2 3 (3 row(s) affected) ```
Select distinct from multiple fields using sql
[ "", "sql", "select", "distinct", "" ]
I've been interested in how sessions work internally, but I have little knowledge of C (and am unsure where to look in the PHP source for this). This is what I understand of sessions at the moment: 1. When you start a session the user gets assigned a session id which is stored in a cookie. 2. When session data is saved (via `$_SESSION`) it is stored on the filesystem, with the relevant session id and an expiry time. Is this correct? Also what is the method in which session id are created? I assume it's based on time but what if two users send a request at the same time? What methods are in place internally to prevent them getting the same id? Thanks,
My understanding is of the internal session handling process is the following: When [`session_start`](http://php.net/session_start) is called, PHP is looking for a parameter from the client that was sent via POST, GET, or in a cookie (depending on the configuration; see [*session.use\_cookies*](http://php.net/manual/en/session.configuration.php#ini.session.use-cookies), [*session.use\_only\_cookies*](http://php.net/manual/en/session.configuration.php#ini.session.use-only-cookies), and [*session.use\_trans\_sid*](http://php.net/manual/en/session.configuration.php#ini.session.use-trans-sid)) with the name of the value of [*session.name*](http://php.net/manual/en/session.configuration.php#ini.session.name) to use the session ID of an already started session. If it finds a valid session ID, it tries to retrieve the session data from the storage (see [*session.save\_handler*](http://php.net/manual/en/session.configuration.php#ini.session.save-handler)) to load the data into `$_SESSION`. If it can’t find an ID or its usage is forbidden, PHP generates a new ID using a hash function (see [*session.hash\_function*](http://php.net/manual/en/session.configuration.php#ini.session.hash-function)) on data of a source that generates random data (see [*session.entropy\_file*](http://php.net/manual/en/session.configuration.php#ini.session.entropy-file)). At the end of the runtime or when [`session_write_close`](http://php.net/session_write_close) is called, the session data in `$_SESSION` is stored away into the designated storage.
Look at php\_session\_create\_id in [ext/session/session.c](https://github.com/php/php-src/blob/master/ext/session/session.c#L279) in the php source It goes like this: * get time of day * get remote ip address * build a string with the seconds and microseconds from the current time, along with the IP address * feed that into configured [session hash function](https://www.php.net/manual/en/session.configuration.php#ini.session.hash-function) (either MD5 or SHA1) * if configured, feed some additional randomness from an [entropy file](https://www.php.net/manual/en/session.configuration.php#ini.session.entropy-file) * generate final hash value So getting a duplicate is pretty difficult. However, you should familiarise yourself with the concept of session fixation, which allows an attacker to potentially choose the session\_id their target will adopt - see [Sessions and Cookies](http://www.devshed.com/c/a/PHP/Sessions-and-Cookies) for a good primer.
Is my understanding of PHP sessions correct?
[ "", "php", "session", "" ]
I am trying to send a php script some content to be stored in a database via ajax. I am using the jQuery framework. I would like to use a link on a page to send the information. I am having trouble writing the function that will send and receive the information, everything that I have tried is asymptotic. **EDIT** The idea is that the user will click the link, and a column called "show\_online" (a tiny int) in a table called "listings" will update to either 1 or 0 (\*\*a basic binary toggle!) On success, specific link that was clicked will be updated (if it sent a 1 before, it will be set as 0). **EDIT** There will be 20-30 of these links on a page. I have set each containing div with a unique id ('onlineStatus'). I would rather not have a separate js function for every instance. Any assistance is much appreciated. The essential code is below. ``` <script type="text/javascript"> function doAjaxPostOnline( shouldPost, bizID ){ load("ajaxPostOnline.php?b='+bizID+'&p='+shouldPost", jsonData, callbackFunction); function callbackFunction(responseText, textStatus, XMLHttpRequest) { // if you need more functionality than just replacing the contents, do it here } } } </script> <!-- the link that submits the info -->: <div id='onlineStatus<?php echo $b_id ?>'> <a href='#' onclick="doAjaxPostOnline( 0, <?php echo $b_id ?> ); return false;" >Post Online</a> </div> ``` **ajaxPostOnline.php** ``` <!-- ajaxPostOnline.php ... the page that the form posts to --> <?php $id = mysql_real_escape_string($_GET['b']); $show = mysql_real_escape_string($_GET['p']); if( $id && ctype_digit($id) && ($show == 1 || $show == 0) ) { mysql_query( "UPDATE listing SET show_online = $show WHERE id = $id LIMIT 1" ); } if($result) { if($show == '0'){ $return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>"; } if($show == '1'){ $return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 0, $b_id ); return false;' >Post Online</a>"; } print json_encode(array("id" => $id, "return" => $return)); } ?> ```
The load() function in jQuery is really cool for this sort of thing. Here's an example. Basically, you have an outer div as a container. You call a script/service which returns html. You have a div in that html with an id that you will refer to later in the ajax call. The replacement div replaces the inner html of the container div. You pass your data as a json object as the second parameter to the load method, and you can pass a reference to a callback function as the third parameter. The callback function will receive every possible piece of information from the response (the full response text for further parsing/processing, the http status code, and the XMLHttpRequest object associated with this ajax call). ``` $("#id_of_some_outer_div").load("somepage.php #id_of_replacement_div", jsonData, callbackFunction); function callbackFunction(responseText, textStatus, XMLHttpRequest) { // if you need more functionality than just replacing the contents, do it here } ``` so, in your case you're talking about replacing links. Put the original link inside of a div on both sides of the operation. Here's the link to the jQuery api doc for load(): [load](http://docs.jquery.com/Ajax/load) EDIT: In response to your comment about doing multiple replacements in one pass: You can have the callback function do all the work for you. 1. Add a unique css class to all divs that need replacing. This will allow you to select all of them in one shot. Remember that html elements can have more than one css class (that's what the "c" in [CSS](http://en.wikipedia.org/wiki/Cascading_Style_Sheets "Cascading Style Sheets") means). So, they'd all be `<div id="[some unique id]" class="replace_me"...` Then, if you have a variable set to `$("div.replace_me")`, this will be a collection of all divs with the replace\_me style. 2. Whatever elements that come from the ajax call (whether they're another div container or just a single "a" element) should have a unique id similar to the container they're to be inserted into. For example, div\_replace1 would be the id of a container and div\_replace1\_insert would be the id of the element to be inserted 3. Inside the callback function, iterate over the replacements using `$("div.replace_me").each(function(){ ...` 4. Inside each iteration the "this" keyword refers to the current item. You can grab the id of this item, have a variable like `var replacement_id = this.id + "_insert";` (as in the example above) which is now the unique id of the element you'd like to insert. `$("#" + replacement_id)` will now give you a reference to the element you want to insert. You can do the insertion something like this: `this.html( $("#" + replacement_id) );` You may have to edit the code above (it's not tested), but this would be the general idea. You can use naming conventions to relate elements in the ajax return data to elements on the page, iterate the elements on the page with "each", and replace them with this.html()
did you really mean to declare your ajax success return function as ``` function(html) ``` ? .. i think maybe you mean for the param to be 'data' ?
jQuery: Using an <a> link to submit an ajax query
[ "", "php", "ajax", "jquery", "" ]
``` int temp = 0x5E; // in binary 0b1011110. ``` Is there such a way to check if bit 3 in temp is 1 or 0 without bit shifting and masking. Just want to know if there is some built in function for this, or am I forced to write one myself.
In C, if you want to hide bit manipulation, you can write a macro: ``` #define CHECK_BIT(var,pos) ((var) & (1<<(pos))) ``` and use it this way to check the nth bit from the right end: ``` CHECK_BIT(temp, n - 1) ``` In C++, you can use [std::bitset](http://www.cppreference.com/wiki/stl/bitset/start).
Check if bit N (starting from 0) is set: ``` temp & (1 << N) ``` There is no builtin function for this.
C/C++ check if one bit is set in, i.e. int variable
[ "", "c++", "c", "bit-manipulation", "" ]
Instead of using ``` std::vector<Object> ObjectArray; ``` I would like it to be ``` MyArray<Object> ObjectArray; ``` with all the std::vector methods preserved. (like push\_back(), reserve(), ...etc) However, using ``` typedef std::vector MyArray; ``` won't work. Should I use template instead? How?
What you would really want is a templated typedef. Unfortunately those are not supported in the current version of C++, but they will be added in C++0x. For now, here's a possible workaround: ``` template<class T> struct My { typedef std::vector<T> Array; }; My<Object>::Array ObjectArray ``` Whether or not that is better than simply using `std::vector` directly, I'll leave to you to decide.
As of C++11 you can use a templated type alias ``` template <typename T> using MyArray = std::vector<T>; ``` If you want to be more generic you can use a variadic template (which would allow for allocators in the case of vector without having to be specific) ``` template <typename... Ts> using MyArray = std::vector<Ts...>; ```
Creating a type alias for a templated class
[ "", "c++", "" ]
Last question for tonight, I promise. These pointers are giving me a serious headache. I have a std::list`<Point`> called Polygon and a std::list of Polygons defined like: ``` typedef std::list<Point> Polygon; typedef std::list<Polygon> PolygonList; // List of all our polygons PolygonList polygonList; ``` I created the method below to attempt to delete the nearest Point from an (x,y), checking all of my Polygons within my polygonList. ``` void deleteNearestPoint(int x, int y) { y = screenHeight - y; Polygon &closestPolygon = polygonList.front(); Polygon::iterator closestPoint = closestPolygon.begin(); float closestDistance = sqrt(pow(x - closestPoint->x, 2) + pow(y - closestPoint->y, 2)); // Search PolygonList PolygonList::iterator listIter; Polygon::iterator iter; for(listIter = polygonList.begin(); listIter != polygonList.end(); listIter++) { Polygon &tempPolygon = *listIter; for(iter = tempPolygon.begin(); iter != tempPolygon.end(); iter++) { const float distance = sqrt(pow(x - iter->x, 2) + pow(y - iter->y, 2)); if (distance < closestDistance) { closestPolygon = *listIter; closestPoint = iter; closestDistance = distance; } } } closestPolygon.erase(closestPoint); redraw(); } ``` However, somewhere I have a pointer or reference variable screwing me up. This code compiles but acts in a very strange way. I've written a debug statement and lets say I have 3 polygons in my polygon list like so: > Polygon #: 0 > Point: (448, 43) > Point: (469, 177) > Point: (374, 123) > Polygon #: 1 > Point: (295, 360) > Point: (422, 350) > Point: (315, 266) > Point: (295, 360) > Polygon #: 2 > Point: (143, 202) > Point: (301, 203) > Point: (222, 100) > Point: (143, 202) Now, lets say I try and use the delete function giving it an x/y close to point 422, 350 The desired result would be it simply deleting that point (422, 350) from Polygon #1 but instead I get this: > Polygon #: 0 > Point: (295, 360) > Point: (422, 350) > Point: (315, 266) > Point: (295, 360) > Polygon #: 1 > Point: (295, 360) > Point: (315, 266) > Point: (295, 360) > Polygon #: 2 > Point: (143, 202) > Point: (301, 203) > Point: (222, 100) > Point: (143, 202) It did delete (422, 350) but it also has the strange side effect of overwriting Polygon#0 to what Polygon#1 was before the delete of its point. I know I'm using a pointer or reference incorrectly in my method. Can someone point out what I could possibly be doing that is causing this? I think it is because my &closestPolygon is declared as a reference, but I get compile errors if I try to set it as anything else.
Other answers have pointed out what caused the error. As a general advice I would suggest not using references except in function arguments. The semantics are confusing, also for someone that will try to read your code. Try rewriting to something like this (I didn't test the code): ``` void deleteNearestPoint(int x, int y) { y = screenHeight - y; PolygonList::iterator closestPolygon = polygonList.begin(); Polygon::iterator closestPoint = closestPolygon->begin(); float closestDistance = sqrt(pow(x - closestPoint->x, 2) + pow(y - closestPoint->y, 2)); // Search PolygonList PolygonList::iterator listIter; Polygon::iterator iter; for(listIter = polygonList.begin(); listIter != polygonList.end(); listIter++) { for(iter = listIter->begin(); iter != listIter->end(); iter++) { const float distance = sqrt(pow(x - iter->x, 2) + pow(y - iter->y, 2)); if (distance < closestDistance) { closestPolygon = listIter; closestPoint = iter; closestDistance = distance; } } } closestPolygon->erase(closestPoint); redraw(); } ```
Unfortunately, you cannot rebind a reference, i.e., this line: closestPolygon = \*listIter; will copy `*listIter` to `closestPolygon`, not rebind the refernece to `*listIter`. Edit: To do what you want, you should use `PolygonList::iterator` instead of `Polygon &` and adjust the code accordingly.
How am I accidentally overwriting when referencing these pointers?
[ "", "c++", "pointers", "" ]
Is ruby strongly or weakly typed ? Presumably the same is true for Javascript.
Ruby is "**strong typed**". Strong typing means an object's type (not in the OOP sense, but in a general sense) is checked before an operation requiring a certain type is executed on it. Weak typed means that no checking is done to ensure that the operation can succeed on the object. (For example, when a function accesses a string like and array of floats, if no type checking is done then the operation is allowed) Edit: It's been 6 years since this answer was posted and I think it warrants some extra clarifications: Over the years the notion that "type safety is a dial not an absolute" started to be used in favor of the binary meaning (yes/no) Ruby is "stronger" typed (with an "er") than most typical dynamic languages. The fact that ruby requires explicit statements for conversion IE: Array("foo"), "42".to\_i, Float(23), brings the Ruby typing dial closer to the "Strong Typed" end of spectrum than the "weak typed". So I would say "Ruby is a stronger typed dynamic language than most common dynamic languages"
Wikpedia labels it as "dynamic ('duck') typed". Regarding Pop's comment about it being "strong-typed" - I'm not sure his explanation actually fits with what goes on under the covers. The MRI doesn't really "check" to see if an operation can be performed on an object; it just sends the object the message, and if that object doesn't accept that message (either by a method declaration or by handling it in #method\_missing) it barfs. If the runtime actually checked to make sure operations were possible, #method\_missing wouldn't work. Also, it should be noted that since everything in Ruby is an object (and I do mean *everything*), I'm not sure what he said about "not in an oo-sense" is accurate. In Ruby, you're either an object or a message.
Is ruby strongly or weakly typed?
[ "", "javascript", "ruby", "typing", "" ]
I need to keep a session alive for 30 minutes and then destroy it.
You should implement a session timeout of your own. Both options mentioned by others ([*session.gc\_maxlifetime*](http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime) and [*session.cookie\_lifetime*](http://php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime)) are not reliable. I'll explain the reasons for that. **First:** > **session.gc\_maxlifetime** > *session.gc\_maxlifetime* specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start. But the garbage collector is only started with a probability of [*session.gc\_probability*](http://php.net/manual/en/session.configuration.php#ini.session.gc-probability) divided by [*session.gc\_divisor*](http://php.net/manual/en/session.configuration.php#ini.session.gc-divisor). And using the default values for those options (1 and 100 respectively), the chance is only at 1%. Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive. Furthermore, when using PHP's default [*session.save\_handler*](http://php.net/manual/en/session.configuration.php#ini.session.save-handler) files, the session data is stored in files in a path specified in [*session.save\_path*](http://php.net/manual/en/session.configuration.php#ini.session.save-path). With that session handler, the age of the session data is calculated on the file's last modification date and not the last access date: > **Note:** If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available. So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently. **And second:** > **session.cookie\_lifetime** > *session.cookie\_lifetime* specifies the lifetime of the cookie in seconds which is sent to the browser. […] Yes, that's right. This only affects the cookie lifetime and the session itself may still be valid. But it's the server's task to invalidate a session, not the client. So this doesn't help anything. In fact, having *session.cookie\_lifetime* set to `0` would make the session’s cookie a real [session cookie](http://en.wikipedia.org/wiki/HTTP_cookie#Session_cookie) that is only valid until the browser is closed. **Conclusion / best solution:** The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request: ``` if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) { // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage } $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp ``` Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely. You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like [session fixation](http://www.owasp.org/index.php/Session_fixation): ``` if (!isset($_SESSION['CREATED'])) { $_SESSION['CREATED'] = time(); } else if (time() - $_SESSION['CREATED'] > 1800) { // session started more than 30 minutes ago session_regenerate_id(true); // change session ID for the current session and invalidate old session ID $_SESSION['CREATED'] = time(); // update creation time } ``` **Notes:** * `session.gc_maxlifetime` should be at least equal to the lifetime of this custom expiration handler (1800 in this example); * if you want to expire the session after 30 minutes of *activity* instead of after 30 minutes *since start*, you'll also need to use `setcookie` with an expire of `time()+60*30` to keep the session cookie active.
## Simple way of PHP session expiry in 30 minutes. Note : if you want to change the time, just change the 30 with your desired time and do not change \* 60: this will gives the minutes. --- In minutes : (30 \* 60) In days : (n \* 24 \* 60 \* 60 ) n = no of days --- ## Login.php ``` <?php session_start(); ?> <html> <form name="form1" method="post"> <table> <tr> <td>Username</td> <td><input type="text" name="text"></td> </tr> <tr> <td>Password</td> <td><input type="password" name="pwd"></td> </tr> <tr> <td><input type="submit" value="SignIn" name="submit"></td> </tr> </table> </form> </html> <?php if (isset($_POST['submit'])) { $v1 = "FirstUser"; $v2 = "MyPassword"; $v3 = $_POST['text']; $v4 = $_POST['pwd']; if ($v1 == $v3 && $v2 == $v4) { $_SESSION['luser'] = $v1; $_SESSION['start'] = time(); // Taking now logged in time. // Ending a session in 30 minutes from the starting time. $_SESSION['expire'] = $_SESSION['start'] + (30 * 60); header('Location: http://localhost/somefolder/homepage.php'); } else { echo "Please enter the username or password again!"; } } ?> ``` ## HomePage.php ``` <?php session_start(); if (!isset($_SESSION['luser'])) { echo "Please Login again"; echo "<a href='http://localhost/somefolder/login.php'>Click Here to Login</a>"; } else { $now = time(); // Checking the time now when home page starts. if ($now > $_SESSION['expire']) { session_destroy(); echo "Your session has expired! <a href='http://localhost/somefolder/login.php'>Login here</a>"; } else { //Starting this else one [else1] ?> <!-- From here all HTML coding can be done --> <html> Welcome <?php echo $_SESSION['luser']; echo "<a href='http://localhost/somefolder/logout.php'>Log out</a>"; ?> </html> <?php } } ?> ``` ## LogOut.php ``` <?php session_start(); session_destroy(); header('Location: http://localhost/somefolder/login.php'); ?> ```
How do I expire a PHP session after 30 minutes?
[ "", "php", "session", "cookies", "" ]
I'm rendering text using `FormattedText`, but there does appear to be any way to perform per-char hit testing on the rendered output. It's read-only, so I basically only need selection, no editing. I'd use `RichTextBox` or similar, but I need to output text based on control codes embed in the text itself, so they don't always nest, which makes building the right Inline elements very complex. I'm also a bit worried about performance with that solution; I have a large number of lines, and new lines are appended often. I've looked at `GlyphRun`, it appears I could get hit-testing from it or a related class, but I'd be reimplementing a lot of functionality, and it seems like there should be a simpler way... Does anyone know of a good way to implement this?
The best way is to design a good data structure for storing your text and which also considers hit-testing. One example could be to split the text into blocks (words, lines or paragraphs depending on what you need). Then each such block should have a bounding-box which should be recomputed in any formatting operations. Also consider caret positions in your design. Once you have such facility it becomes very easy to do hit-testing, just use the bounding boxes. It will also help in subsequent operations like highlighting a particular portion of text.
You can get the geometry of each character from a FormattedText object and use the bounds of each character to do your hit testing. ``` var geometry = (GeometryGroup)((GeometryGroup)text.BuildGeometry(new Point(0, 0))).Children[0]; foreach (var c in geometry.Children) { if (c.Bounds.Contains(point)) return index; index++; } ``` In OnRender you can render these geometry objects instead of the formatted text.
What's a good way to perform hit testing on a FormattedText?
[ "", "c#", "wpf", "text", "hittest", "" ]
I have a PHP script which reads a large CSV and performs certain actions, but only if the "username" field is unique. The CSV is used in more than one script, so changing the input from the CSV to only contain unique usernames is not an option. The very basic program flow (which I'm wondering about) goes like this: ``` $allUsernames = array(); while($row = fgetcsv($fp)) { $username = $row[0]; if (in_array($username, $allUsernames)) continue; $allUsernames[] = $username; // process this row } ``` Since this CSV could actually be quite large, it's that `in_array` bit which has got me thinking. The most ideal situation when searching through an array for a member is if it is already sorted, so **how would you build up an array from scratch, keeping it in order**? Once it is in order, would there be a more efficient way to search it than using `in_array()`, considering that it probably doesn't know the array is sorted?
Not keeping the array in order, but how about this kind of optimization? I'm guessing `isset()` for an array key should be faster than `in_array()` search. ``` $allUsernames = array(); while($row = fgetcsv($fp)) { $username = $row[0]; if (isset($allUsernames[$username])) { continue; } else { $allUsernames[$username] = true; // do stuff } } ```
The way to build up an array from scratch in sorted order is an insertion sort. In PHP-ish pseudocode: ``` $list = [] for ($element in $elems_to_insert) { $index = binary_search($element, $list); insert_into_list($element, $list, $index); } ``` Although, it might actually turn out to be faster to just create the array in unsorted order and then use quicksort (PHP's builtin sort functions use quicksort) And to find an element in a sorted list: ``` function binary_search($list, $element) { $start = 0; $end = count($list); while ($end - $start > 1) { $mid = ($start + $end) / 2; if ($list[$mid] < $element){ $start = $mid; } else{ $end = $mid; } } return $end; } ``` With this implementation you'd have to test `$list[$end]` to see if it is the element you want, since if the element isn't in the array, this will find the point where it should be inserted. I did it that way so it'd be consistent with the previous code sample. If you want, you could check `$list[$end] === $element` in the function itself.
Keeping an array sorted in PHP
[ "", "php", "arrays", "sorting", "" ]
I have an image URL in a `imageUrl` variable and I am trying to set it as CSS style, using jQuery: ``` $('myObject').css('background-image', imageUrl); ``` This seems to be not working, as: ``` console.log($('myObject').css('background-image')); ``` returns `none`. Any idea, what I am doing wrong?
You probably want this (to make it like a normal CSS background-image declaration): ``` $('myObject').css('background-image', 'url(' + imageUrl + ')'); ```
You'll want to include double quotes (") before and after the imageUrl like this: ``` $('myOjbect').css('background-image', 'url("' + imageUrl + '")'); ``` This way, if the image has spaces it will still be set as a property.
Setting background-image using jQuery CSS property
[ "", "javascript", "jquery", "css", "" ]
I found [a tool](http://www.zend.com/store/education/certification/yellow-pages.php) on Zend site. But it is only show who have achieved ZCE by country. I plan to take ZCE for PHP 5 and I just want to know how many Zend certified engineer available around the world. Thanks...
I don't know about you, but if I was keen about finding out how many Zend certified engineers are available then I'd write some kind of a scraper that took the result for each country and sum it up. ... and do it in php. That would impress some employers.
You can see how many are for each country and the sum up. There are not so many and some countries are more inclined to certifications than others. Spain has 42 ZCE which is very little compared with the total number of programmers or population. Israel doubles that for less programmers/ population. USA has about 1000, probably because big companies see in that a confirmation of your expertize, Microsoft style.
How many Zend Certified Engineers are there in the world?
[ "", "php", "certificate", "" ]
I'm planning on writing a "medium-size" WinForms application that I'll write in C#, .NET 3.5. I have some "generic design questions" in mind that I was hoping to get addressed here. 1. Exception handling in general. What is the best way to handle exceptions? Use try/catch blocks everywhere? [this](https://stackoverflow.com/questions/154597/is-there-a-way-to-define-an-action-for-unhandled-exceptions-in-a-winforms-net-3)? 2. Localization. If I'd want to have multiple language support in my application, what should I use? I find the "satellite assemblies" to be a very... well, "bulky"-seeming solution - I don't want a resource file "hell", and I don't want to input translations inside the VS UI. 3. Storing data locally. Previously, I've used [System.Data.SQLite](http://sqlite.phxsoftware.com/) on a project, but I found myself wondering if there's something else I should consider. 4. Anything else I should keep in mind? Thanks(?)
1) Don't catch any exceptions. The vast majority of them tell you about a bug in your code, you'll want to know about them right away. If during testing and deployment, you find error conditions that you think you can handle (there aren't many of them), you can always add the try/catch block. If you plan on handling exceptions, be sure to liberally sprinkle try/finally blocks in your code so the state of your classes is preserved even if there's an exception that prevents cleanup code from running. There is no notable cost to using try without catch. 2) Satellite assemblies are not bulky. Just a small DLL in a subdirectory of your deployment folder. No special code is required, everything is automatic. Most of all, it is a standard solution. You can send your .resx files to a localization service and they'll use standard tools (like Winres.exe) to provide you with the translations. Asking them to deal with something custom is going to be expensive and potentially troublesome. 3) Alternatives are SQL Server CE (same approach as SQLite) and SQL Server Express. The latter gives you the most bang for the buck, but must be installed. That isn't hard. 4) It depends on your target audience, but if look-and-feel is at a factor in a buying decision at all, hire a UI designer. S/he'll catch UI bloopers and make it look spiffy.
#1 - If you care about performance of your application , avoid try/catch. Use some profiler for example the one from RedGate (ANTS - it's not a freeware sadly) to see for yourself that try/catch block consume a lot of CPU time , especially if there is a need to jump into "catch". Just try to find any other way around , .net has got a lot other methods you can use to make shore that no exception will occur, I know it's easier to use try/catch but decide what is your aim. #2 - I guess that you can use resource files that are compiled with you application so you won't have any separate file if that is what you're asking ? #3 - I really have to answer that one :) , personally I think there is no better/more comfortable way of storing data locally than to use XML , as it was mentioned before, you can use LINQ to XML to query this file , which is extremely simple. It's small , fast , easy to create , maintain and what's more important you can send it trogh the Internet without any problems that may occur using other ways of storing data , example - firewall or any ISD won't be a problem because it's basically a text file. I simply love xml. Was that helpfull ?
Windows Forms application "design"
[ "", "c#", ".net", "winforms", "" ]
How do I find the cosine similarity between vectors? I need to find the similarity to measure the relatedness between two lines of text. For example, I have two sentences like: > system for user interface > > user interface machine … and their respective vectors after tF-idf, followed by normalisation using LSI, for example `[1,0.5]` and `[0.5,1]`. How do I measure the smiliarity between these vectors?
``` public class CosineSimilarity extends AbstractSimilarity { @Override protected double computeSimilarity(Matrix sourceDoc, Matrix targetDoc) { double dotProduct = sourceDoc.arrayTimes(targetDoc).norm1(); double eucledianDist = sourceDoc.normF() * targetDoc.normF(); return dotProduct / eucledianDist; } } ``` I did some tf-idf stuff recently for my Information Retrieval unit at University. I used this Cosine Similarity method which uses [Jama: Java Matrix Package](http://math.nist.gov/javanumerics/jama/). For the full source code see [IR Math with Java : Similarity Measures](http://sujitpal.blogspot.com/2008/09/ir-math-with-java-similarity-measures.html), really good resource that covers a good few different similarity measurements.
If you want to avoid relying on third-party libraries for such a simple task, here is a plain Java implementation: ``` public static double cosineSimilarity(double[] vectorA, double[] vectorB) { double dotProduct = 0.0; double normA = 0.0; double normB = 0.0; for (int i = 0; i < vectorA.length; i++) { dotProduct += vectorA[i] * vectorB[i]; normA += Math.pow(vectorA[i], 2); normB += Math.pow(vectorB[i], 2); } return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)); } ``` Note that the function assumes that the two vectors have the same length. You may want to explictly check it for safety.
How do I calculate the cosine similarity of two vectors?
[ "", "java", "vector", "trigonometry", "tf-idf", "" ]
Ok, I'm reading data from a stream using a StreamReader. The data inside the stream is not xml, it could be anything. Based on the input StreamReader I'm writing to an output stream using an XmlTextWriter. Basically, when all is said and done, the output stream contains data from the input stream wrapped in a element contained in a parent element. My problem is twofold. Data gets read from the input stream in chunks, and the StreamReader class returns char[]. If data in the input stream contains a "]]>" it needs to be split across two CDATA elements. First, how do I search for "]]>" in a char array? And second, because I'm reading in chunks, the "]]>" substring could be split across two chunks, so how do I account for this? I could probably convert the char[] to a string, and do a search replace on it. That would solve my first problem. On each read, I could also check to see if the last character was a "]", so that on the next read, if the first two characters are "]>" I would start a new CDATA section. This hardly seems efficient because it involves converting the char array to a string, which means spending time to copy the data, and eating up twice the memory. Is there a more efficient way, both speedwise and memory wise?
> second, because I'm reading in chunks, the "]]>" substring could be split across two chunks, so how do I account for this? Indeed, you would have to keep back the last two characters in a queue instead of spitting them out immediately. Then when new input comes in, append it to the queue and again take all but the last two characters, search-and-replace over them, and output. Better: don't bother with a CDATA section at all. They're only there for the convenience of hand-authoring. If you're already doing search-and-replace, there's no reason you shouldn't just search-and-replace ‘<’, ‘>’ and ‘&’ with their predefined entities, and include those in a normal Text node. Since those are simple single-character replacements, you don't need to worry about buffering. But: if you're using an XmlTextWriter as you say, it's as simple as calling WriteString() on it for each chunk of incoming text.
According to [*HOWTO Avoid Being Called a Bozo When Producing XML*](http://hsivonen.iki.fi/producing-xml/): > [Don’t bother with CDATA sections](http://hsivonen.iki.fi/producing-xml/#cdata) > > XML provides two ways of escaping > markup-significant characters: > predefined entities and CDATA > sections. CDATA sections are only > syntactic sugar. The two alternative > syntactic constructs have no semantic > difference. > > CDATA sections are convenient when you > are editing XML manually and need to > paste a large chunk of text that > includes markup-significant characters > (eg. code samples). However, when > producing XML using a serializer, the > serializer takes care of escaping > automatically and trying to > micromanage the choice of escaping > method only opens up possibilities for > bugs. > ... > Only <, >, & and (in attribute values) " need escaping. So long as the small set of special characters are encoded/escaped it should just work. Whether you have to handle the escaping yourself is a different matter, but certainly a much more straightforward-to-solve problem. Then just append the whole lot as a child text node to the relevant XML element.
Efficient way to encode CDATA elements
[ "", "c#", ".net", "xml", "cdata", "streamreader", "" ]
I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers. ``` int main() { int arr[10] = {1,2,3}; char arr2[10] = {'c','i','a','o','\0'}; cout << arr << endl; cout << arr2 << endl; } ``` However when I run this, `arr` outputs the address of the first element of the array of ints (as expected) but `arr2` doesn't output the address of the first element of the array of chars; it actually prints "ciao". What is it that I'm missing or that I haven't learned yet about this?
It's the operator<< that is overloaded for `const void*` and for `const char*`. Your char array is converted to `const char*` and passed to that overload, because it fits better than to `const void*`. The int array, however, is converted to `const void*` and passed to that version. The version of operator<< taking `const void*` just outputs the address. The version taking the `const char*` actually treats it like a C-string and outputs every character until the terminating null character. If you don't want that, convert your char array to `const void*` explicitly when passing it to operator<<: ``` cout << static_cast<const void*>(arr2) << endl; ```
Because cout's `operator <<` is overloaded for `char*` to output strings, and `arr2` matches that. If you want the address, try casting the character array as a void pointer.
Why does cout print char arrays differently from other arrays?
[ "", "c++", "arrays", "pointers", "" ]
After searching around somewhat thoroughly, I noticed a slight lack of functions in PHP for handling [IPv6](http://en.wikipedia.org/wiki/IPv6). For my own personal satisfaction I created a few functions to help the transition. The `IPv6ToLong()` function is a temporary solution to that brought up here: [How to store IPv6-compatible address in a relational database](https://stackoverflow.com/questions/420680/). It will split the IP in to two integers and return them in an array. ``` /** * Convert an IPv4 address to IPv6 * * @param string IP Address in dot notation (192.168.1.100) * @return string IPv6 formatted address or false if invalid input */ function IPv4To6($Ip) { static $Mask = '::ffff:'; // This tells IPv6 it has an IPv4 address $IPv6 = (strpos($Ip, '::') === 0); $IPv4 = (strpos($Ip, '.') > 0); if (!$IPv4 && !$IPv6) return false; if ($IPv6 && $IPv4) $Ip = substr($Ip, strrpos($Ip, ':')+1); // Strip IPv4 Compatibility notation elseif (!$IPv4) return $Ip; // Seems to be IPv6 already? $Ip = array_pad(explode('.', $Ip), 4, 0); if (count($Ip) > 4) return false; for ($i = 0; $i < 4; $i++) if ($Ip[$i] > 255) return false; $Part7 = base_convert(($Ip[0] * 256) + $Ip[1], 10, 16); $Part8 = base_convert(($Ip[2] * 256) + $Ip[3], 10, 16); return $Mask.$Part7.':'.$Part8; } /** * Replace '::' with appropriate number of ':0' */ function ExpandIPv6Notation($Ip) { if (strpos($Ip, '::') !== false) $Ip = str_replace('::', str_repeat(':0', 8 - substr_count($Ip, ':')).':', $Ip); if (strpos($Ip, ':') === 0) $Ip = '0'.$Ip; return $Ip; } /** * Convert IPv6 address to an integer * * Optionally split in to two parts. * * @see https://stackoverflow.com/questions/420680/ */ function IPv6ToLong($Ip, $DatabaseParts= 2) { $Ip = ExpandIPv6Notation($Ip); $Parts = explode(':', $Ip); $Ip = array('', ''); for ($i = 0; $i < 4; $i++) $Ip[0] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT); for ($i = 4; $i < 8; $i++) $Ip[1] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT); if ($DatabaseParts == 2) return array(base_convert($Ip[0], 2, 10), base_convert($Ip[1], 2, 10)); else return base_convert($Ip[0], 2, 10) + base_convert($Ip[1], 2, 10); } ``` For these functions I typically implement them by calling this function first: ``` /** * Attempt to find the client's IP Address * * @param bool Should the IP be converted using ip2long? * @return string|long The IP Address */ function GetRealRemoteIp($ForDatabase= false, $DatabaseParts= 2) { $Ip = '0.0.0.0'; // [snip: deleted some dangerous code not relevant to question. @webb] if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] != '') $Ip = $_SERVER['REMOTE_ADDR']; if (($CommaPos = strpos($Ip, ',')) > 0) $Ip = substr($Ip, 0, ($CommaPos - 1)); $Ip = IPv4To6($Ip); return ($ForDatabase ? IPv6ToLong($Ip, $DatabaseParts) : $Ip); } ``` Someone please tell me if I'm reinventing the wheel here or I've done something wrong. This implementation converts IPv4 to IPv6. Any IPv6 address it doesn't touch.
How about [`inet_ntop()`](http://php.net/inet_ntop)? Then instead of chopping things into integers, you just use a `varbinary(16)` to store it.
PHP.net's [Filter extension](http://www.php.net/manual/en/filter.php) contains [some constants](http://www.php.net/manual/en/filter.constants.php) for matching IPv4 and IPv6 addresses, which might be useful for checking the address. I haven't seen any conversion utilities though.
How to handle IPv6 Addresses in PHP?
[ "", "php", "ip", "ipv6", "" ]