Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a case where I wanna choose any database entry that have an invalid Country, Region, or Area ID, by invalid, I mean an ID for a country or region or area that no longer exists in my tables, I have four tables: Properties, Countries, Regions, Areas. I was thinking to do it like this: ``` SELECT * FROM Properties WHERE Country_ID NOT IN ( SELECT CountryID FROM Countries ) OR RegionID NOT IN ( SELECT RegionID FROM Regions ) OR AreaID NOT IN ( SELECT AreaID FROM Areas ) ``` Now, is my query right? and what do you suggest that i can do and achieve the same result with better performance?!
Your query in fact is optimal. `LEFT JOIN`'s proposed by others are worse, as they select ALL values and then filter them out. Most probably your subquery will be optimized to this: ``` SELECT * FROM Properties p WHERE NOT EXISTS ( SELECT 1 FROM Countries i WHERE i.CountryID = p.CountryID ) OR NOT EXISTS ( SELECT 1 FROM Regions i WHERE i.RegionID = p.RegionID ) OR NOT EXISTS ( SELECT 1 FROM Areas i WHERE i.AreaID = p.AreaID ) ``` , which you should use. This query selects at most 1 row from each table, and jumps to the next iteration right as it finds this row (i. e. if it does not find a `Country` for a given Property, it will not even bother checking for a `Region`). Again, `SQL Server` is smart enough to build the same plan for this query and your original one. **Update:** Tested on `512K` rows in each table. All corresponding `ID`'s in dimension tables are `CLUSTERED PRIMARY KEY`'s, all measure fields in `Properties` are indexed. For each row in `Property`, `PropertyID = CountryID = RegionID = AreaID`, no actual missing rows (worst case in terms of execution time). ``` NOT EXISTS 00:11 (11 seconds) LEFT JOIN 01:08 (68 seconds) ```
You could rewrite it differently as follows: ``` SELECT p.* FROM Properties p LEFT JOIN Countries c ON p.Country_ID = c.CountryID LEFT JOIN Regions r on p.RegionID = r.RegionID LEFT JOIN Areas a on p.AreaID = a.AreaID WHERE c.CountryID IS NULL OR r.RegionID IS NULL OR a.AreaID IS NULL ``` Test the performance difference (if there is any - there should be as NOT IN is a nasty search, especially over a lot of items as it HAS to test every single one). You can also make this faster by indexing the IDS being searched - in each master table (Country, Region, Area) they should be clustered primary keys.
A messy SQL statement
[ "", "sql", "database", "sql-server-2005", "t-sql", "" ]
Is there a way to copy code from visual studio (C#) and paste it into OneNote, without losing the formatting? I was able to do this, but only if I copy from VS, paste to Word, copy from Word, and then paste to OneNote.
There is fortunately a solution for Visual Studio 2010! Install the Visual Studio 2010 Pro Power Tools extension and copy/paste to OneNote retains syntax highlighting.
This is an option that seems to be disabled by default. ## To enable (in VS 2019): 1. Go to `Tools -> Options` 2. type **copy** in the search box 3. Under `Text Editor -> Advanced`... 4. Check **Copy rich text on copy/cut** [![Visual Studio Options Example](https://i.stack.imgur.com/efTPJ.png)](https://i.stack.imgur.com/efTPJ.png) ## Top copy as formatted Once the feature is enabled, depending on the target, this may be a two-step process. If, after copying and pasting code, it still appears as unformatted (e.g. if pasting into a web browser), use the approach suggested by [marcus](https://stackoverflow.com/a/33935005/3063884), by first pasting into wordpad.exe (`start -> run ->` type `wordpad`), then copying the text from within Wordpad again, and pasting into the target application/browser.
Is it possible to copy code from Visual Studio and paste formatted code to OneNote?
[ "", "c#", ".net", "visual-studio", "onenote", "richtext", "" ]
I am learning plug able architecture in .Net using Managed Extensibility Framework (MEF.) I saw sample code on the net, but when I tried to implement it I got stuck at one point. The code was using: ``` var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog.CreateResolver()); ``` This `var` is available on C# 3.0 where as I am coding in C# 2.0. What is the alternative of above two statements? How can I make them work in c# 2.0 using VS 2005? --- i tried this bt its saying now Error 1 **The type or namespace name 'AttributedAssemblyPartCatalog' could not be found (are you missing a using directive or an assembly reference?)** C:\Documents and Settings\test\Desktop\MEFDemo\MEFDemo\Program.cs 31 13 MEFDemo where as i have added referance to SystemComponentModel.Composition
This is the use of type inference in C# 3.0. When using the keyword ``` var ``` in c# 3.0 the compiler infers the type. See [scott guthries explanation](http://weblogs.asp.net/scottgu/archive/2007/05/15/new-orcas-language-feature-anonymous-types.aspx) In c# 2.0 you have to declare the type of the variable the same as c# 1.1 e.g. ``` Type variableName = new Type(); ``` Making you above code example ``` AttributedAssemblyPartCatalog catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(catalog.CreateResolver()); ``` HTH
Basically, `var` forces the compiler to determine (infer) the *compile-time* type of a variable based on it's "initializer" -- effectively, an expression to the right from `=` sign. Here the types are obvious: ``` AttributedAssemblyPartCatalog catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(catalog.CreateResolver()); ``` And make sure you add `using System.ComponentModel.Composition;` statement. Plus, be advised that `AttributedAssemblyPartCatalog` was renamed to `AssemblyCatalog`.
In C# 3.0 we use "var" what is its alternative in C# 2.0?
[ "", "c#", "c#-3.0", "mef", "var", "" ]
Say I have an array of strings: ``` string[] strArray = {"aa", "bb", "xx", "cc", "xx", "dd", "ee", "ff", "xx","xx","gg","xx"}; ``` How do I use LINQ to extract the strings between the "xx" markers as groups? Say by writing them to the console as: ``` cc dd,ee,ff gg ```
A pure-functional solution (mutation-free): ``` string[] strArray = { "aa", "bb", "xx", "cc", "xx", "dd", "ee", "ff", "xx", "xx", "gg", "xx" }; var result = strArray.Aggregate((IEnumerable<IEnumerable<string>>)new IEnumerable<string>[0], (a, s) => s == "xx" ? a.Concat(new[] { new string[0] }) : a.Any() ? a.Except(new[] { a.Last() }) .Concat(new[] { a.Last().Concat(new[] { s }) }) : a) .Where(l => l.Any()); // Test foreach (var i in result) Console.WriteLine(String.Join(",", i.ToArray())); ``` If you want to filter out the results past the last marker: ``` string[] strArray = { "aa", "bb", "xx", "cc", "xx", "dd", "ee", "ff", "xx", "xx", "gg", "xx"}; var result = strArray.Aggregate( new { C = (IEnumerable<string>)null, L = (IEnumerable<IEnumerable<string>>)new IEnumerable<string>[0] }, (a, s) => s == "xx" ? a.C == null ? new { C = new string[0].AsEnumerable(), a.L } : new { C = new string[0].AsEnumerable(), L = a.L.Concat(new[] { a.C }) } : a.C == null ? a : new { C = a.C.Concat(new[] { s }), a.L }).L .Where(l => l.Any()); // Test foreach (var i in result) Console.WriteLine(String.Join(",", i.ToArray())); ```
A better approach may be to write a generic `IEnumerable<T>` split extension method and then pick and choose which parts of the results you want. ``` public static class IEnumerableExtensions { public static IEnumerable<IEnumerable<TSource>> Split<TSource>( this IEnumerable<TSource> source, TSource splitter) { if (source == null) throw new ArgumentNullException("source"); if (splitter == null) throw new ArgumentNullException("splitter"); return source.SplitImpl(splitter); } private static IEnumerable<IEnumerable<TSource>> SplitImpl<TSource>( this IEnumerable<TSource> source, TSource splitter) { var list = new List<TSource>(); foreach (TSource item in source) { if (!splitter.Equals(item)) { list.Add(item); } else if (list.Count > 0) { yield return list.ToList(); list.Clear(); } } } } ``` And use it like so ``` static void Main(string[] args) { string[] strArray = { "aa", "bb", "xx", "cc", "xx", "dd", "ee", "ff", "xx", "xx", "gg", "xx" }; var result = strArray.Split("xx"); foreach (var group in result.Skip(1).Take(3)) { Console.WriteLine(String.Join(",", group.ToArray())); } Console.ReadKey(true); } ``` And you get the desired output ``` cc dd,ee,ff gg ```
Using C# , LINQ how to pick items between markers again and again?
[ "", "c#", "linq", "" ]
I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.) A mockup that illustrates this: <http://cool-rr.com/physicsthing/physicsthing_mockup_thumb.gif> How can I make this sort of thing? I considered using `eval`, but I understood that `eval` can't handle `import`, for example.
Depending on your GUI framework, it may already has been done: * For wxpython, look up "PyCrust" - it's very easy to embed into your app * For PyQt, [pyqtshell](http://code.google.com/p/pyqtshell/) (**Update 29.04.2011:** these days called `spyder`) Here's what I did to embed PyCrust into the application: ``` import wx.py.crust ... ... # then call crustFrame = wx.py.crust.CrustFrame(parent = self) crustFrame.Show() ``` The `self` here refers to my main frame (derived from `wx.Frame`). This creates a PyCrust window that runs in your application and allows you to inspect everything stored in your main frame (because of the `self`).
You are looking for [code - Interpreter base classes](http://docs.python.org/library/code.html), particularly code.interact(). Some [examples from effbot](http://effbot.org/librarybook/code.htm).
Embedding a Python shell inside a Python program
[ "", "python", "shell", "" ]
If my application is out of memory when i call new() i will get exception and malloc() i will get 0 pointer. But what if i call a method with some local variables? They occupy memory too. Is there some way to reserve memory for "normal" variables? So that even though new() throws exception i can just catch it, fix stuff and still call methods like usual.
The compiler knows how much of memory per stack you need. However, sufficiently high number of stacks (caused due to recursion) will crash your program -- there probably isn't another way to fix this. The standard has an interesting annexure called **Implementation Quantities**. This is non-normative (informative) and hence should not be treated as the absolute truth, but provides you with a fair idea.
Your data is allocated in one of three ways: * Statically allocated data (static members or globals) are allocated when the app starts up, which means that they're not really going to be a problem. * Stack allocated data is allocated on the stack (surprise!) The stack is an area of memory that's set aside for local variables and function stackframes. If you run out of space there, it's undefined what happens. Some implementations might detect it and give you an access violation/segmentation fault, and others will just make you overwrite heap data. In any case, there's no way to detect this, because in general, there's no way to handle it. If you run out of stack space, there's just nothing you can do. You can't even call a function, because that takes up stack space. * Heap allocated memory is what you use when you call new/malloc. Here, you have a mechanism to detect out-of-memory situations, because you may be able to handle it. (Instead of allocating 200mb, you might be able to make do with 100mb, and just swap the data out halfway through) You generally shouldn't run out of stack space unless you perform some heavy recursion though.
What happens if my app is out of memory?
[ "", "c++", "memory-management", "" ]
We are supposed to calculate e^x using this kind of formula: e^x = 1 + (x ^ 1 / 1!) + (x ^ 2 / 2!) ...... I have this code so far: ``` while (result >= 1.0E-20 ) { power = power * input; factorial = factorial * counter; result = power / factorial; eValue += result; counter++; iterations++; } ``` My problem now is that since factorial is of type long long, I can't really store a number greater than 20! so what happens is that the program outputs funny numbers when it reaches that point .. The correct solution can have an X value of at most 709 so e^709 should output: 8.21840746155e+307 The program is written in C++.
Both x^n and n! quickly grow large with n (exponentially and superexponentially respectively) and will soon overflow any data type you use. On the other hand, x^n/n! goes down (eventually) and you can stop when it's small. That is, use the fact that x^(n+1)/(n+1)! = (x^n/n!) \* (x/(n+1)). Like this, say: ``` term = 1.0; for(n=1; term >= 1.0E-10; n++) { eValue += term; term = term * x / n; } ``` (Code typed directly into this box, but I expect it should work.) Edit: Note that the term x^n/n! is, for large x, increasing for a while and then decreasing. For x=709, it goes up to ~1e+306 before decreasing to 0, which is just at the limits of what `double` can handle (`double`'s range is ~1e308 and `term*x` pushes it over), but `long double` works fine. Of course, your final *result* ex is larger than any of the terms, so assuming you're using a data type big enough to accommodate the result, you'll be fine. (For x=709, you can get away with using just `double` if you use `term = term / n * x`, but it doesn't work for 710.)
What happens if you change the type of `factorial` from `long long` to `double`?
Calculating e^x without using any functions
[ "", "c++", "math", "exponential", "" ]
I have 2 interfaces IA and IB. ``` public interface IA { IB InterfaceB { get; set; } } public interface IB { IA InterfaceA { get; set; } void SetIA(IA value); } ``` Each interfaces references the other. I am trying to serialize ClassA as defined below. ``` [Serializable] public class ClassA : IA { public IB InterfaceB { get; set; } public ClassA() { // Call outside function to get Interface B IB interfaceB = Program.GetInsanceForIB(); // Set IB to have A interfaceB.SetIA(this); } } [Serializable] public class ClassB : IB { public IA InterfaceA { get; set; } public void SetIA(IA value) { this.InterfaceA = value as ClassA; } } ``` I get an error when I try too serialize because the 2 properties are interfaces. I want to serialize the properties. How would I get around this? I need to have references in each interface to the other. And I need to be able to serialize the class back and forth.
You have various bugs in your code, otherwise this would work just fine. 1. In the constructor for `ClassA`, your are setting an local variable IB, not the object's IB object. 2. In `ClassB`, you are casting back to the object concrete class, instead of leaving it alone as the interface type. Here is what your code should look like: ``` public interface IA { IB InterfaceB { get; set; } } public interface IB { IA InterfaceA { get; set; } void SetIA(IA value); } [Serializable] public class ClassA : IA { public IB InterfaceB { get; set; } public ClassA() { // Call outside function to get Interface B this.InterfaceB = new ClassB(); // Set IB to have A InterfaceB.SetIA(this); } } [Serializable] public class ClassB : IB { public IA InterfaceA { get; set; } public void SetIA(IA value) { this.InterfaceA = value; } } [STAThread] static void Main() { MemoryStream ms = new MemoryStream(); BinaryFormatter bin = new BinaryFormatter(); ClassA myA = new ClassA(); bin.Serialize(ms, myA); ms.Position = 0; ClassA myOtherA = bin.Deserialize(ms) as ClassA; Console.ReadLine(); } ```
Implement ISerializable on your objects to control the serialization. ``` [Serializable] public class ClassB : IB, ISerializable { public IA InterfaceA { get; set; } public void SetIA(IA value) { this.InterfaceA = value as ClassA; } private MyStringData(SerializationInfo si, StreamingContext ctx) { Type interfaceAType = System.Type.GetType(si.GetString("InterfaceAType")); this.InterfaceA = si.GetValue("InterfaceA", interfaceAType); } void GetObjectData(SerializationInfo info, StreamingContext ctx) { info.AddValue("InterfaceAType", this.InterfaceA.GetType().FullName); info.AddValue("InterfaceA", this.InterfaceA); } } ```
How can I serialize an object that has an interface as a property?
[ "", "c#", "serialization", "interface", "" ]
I'm having trouble with solution wide analysis since I upgraded to resharper 4.5. I'm continually getting false negatives, and having resharper report errors with my code that are not there. I find the only way to get rid of the errors is to open each of the reported in error files, find the offending types/classes, open those files and then close everything again, which seems to force resharper to re-analyze everything. I believe there is a defect already @ jira, but I'm looking for handy tips on how to quickly force resharper to re-analyze the files in error...
When this happens to me I use shift+alt+Page-Down for scrolling to next error in solution. Just spaming through the errors will make Resharper re-analyze the files. Not a good solution, but it works. Edit: If you go to the menu ReSharper -> Windows -> "Errors in Solution" you will get a window up called "Errors in Solution". There you have a button to the right called "Reanalyze Files With Errors". You can even put it on a shortcut.
Delete your resharper cache files regularly - especially if you've upgraded from a previous version. You'll most likely have an \_Resharper.\* file somewhere under your solution folder. This entire folder structure can be blown away and, when Resharper misbehaves for me, I do this.
Solution Wide Analysis Broken in Resharper 4.5?
[ "", "c#", ".net", "visual-studio", "resharper", "resharper-4.5", "" ]
I want to have java script clicking a link on the page..I found something on the net that suggests adding a function like this: ``` function fireEvent(obj,evt){ var fireOnThis = obj; if( document.createEvent ) { var evObj = document.createEvent('MouseEvents'); evObj.initEvent( evt, true, false ); fireOnThis.dispatchEvent(evObj); } else if( document.createEventObject ) { fireOnThis.fireEvent('on'+evt); } } ``` Then call it using: ``` fireEvent(document.getElementById('edit_client_link'),'click'); ``` This seems to work fine for FF but with IE it doesn't work! Any ideas?
I think you still need to call document.createEventObject -- you only checked that it's there. Untested code follows, but based on the [docs](http://msdn.microsoft.com/en-us/library/ms531020(VS.85).aspx) it should work. ``` function fireEvent(obj,evt){ var fireOnThis = obj; if( document.createEvent ) { var evObj = document.createEvent('MouseEvents'); evObj.initEvent( evt, true, false ); fireOnThis.dispatchEvent( evObj ); } else if( document.createEventObject ) { var evObj = document.createEventObject(); fireOnThis.fireEvent( 'on' + evt, evObj ); } } ```
This didn't work for me at first and then I saw the code is missing a parameter for the IE portion. Here's an update that should work: ``` function fireEvent(obj, evt) { var fireOnThis = obj; if (document.createEvent) { // alert("FF"); var evtObj = document.createEvent('MouseEvents'); evtObj.initEvent(evt, true, false); fireOnThis.dispatchEvent(evtObj); } else if (document.createEventObject) { // alert("IE"); var evtObj = document.createEventObject(); fireOnThis.fireEvent('on'+evt, evtObj); } } ```
Emulate clicking a link with Javascript that works with IE
[ "", "javascript", "internet-explorer", "firefox", "" ]
I have an interesting question. Imagine I have a lot of data changing in very fast intervals. I want to display that data as a table in console app. f.ex: ``` ------------------------------------------------------------------------- | Column 1 | Column 2 | Column 3 | Column 4 | ------------------------------------------------------------------------- | | | | | | | | | | | | | | | ------------------------------------------------------------------------- ``` How to keep things fast and how to fix column widths ? I know how to do that in java, but I don't how it's done in C#.
You could do something like the following: ``` static int tableWidth = 73; static void Main(string[] args) { Console.Clear(); PrintLine(); PrintRow("Column 1", "Column 2", "Column 3", "Column 4"); PrintLine(); PrintRow("", "", "", ""); PrintRow("", "", "", ""); PrintLine(); Console.ReadLine(); } static void PrintLine() { Console.WriteLine(new string('-', tableWidth)); } static void PrintRow(params string[] columns) { int width = (tableWidth - columns.Length) / columns.Length; string row = "|"; foreach (string column in columns) { row += AlignCentre(column, width) + "|"; } Console.WriteLine(row); } static string AlignCentre(string text, int width) { text = text.Length > width ? text.Substring(0, width - 3) + "..." : text; if (string.IsNullOrEmpty(text)) { return new string(' ', width); } else { return text.PadRight(width - (width - text.Length) / 2).PadLeft(width); } } ```
Use [String.Format](http://msdn.microsoft.com/en-us/library/txafckwd.aspx) with alignment values. For example: ``` String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3); ``` To create one formatted row.
How To: Best way to draw table in console app (C#)
[ "", "c#", "console", "drawing", "" ]
I would like like to create a java regular expression that selects everything from **file:** to the last forward slash (/) in the file path. This is so I can replace it with a different path. ``` <!DOCTYPE "file:C:/Documentum/XML%20Applications/joesdev/goodnews/book.dtd"/> <myBook>cool book</myBook> ``` Does anyone have any ideas? Thanks!!
You just want to go to the last slash before the end-quote, right? If so: > `file:[^"]+/` (the string "file:", then anything but ", ending with a /) Properly escaped: ``` String regex = "file:[^\"]+/"; ```
Try this: `"file:.*/[^/]*"/>`
How to select a file path using regex
[ "", "java", "xml", "regex", "" ]
I have a login form which appears at the top of all of my pages when the user is logged out. My current jQuery/javascript code works in Firefox 3 but not IE 7. The code queries a page which simply returns the string "true" or "false" depending on whether the login was successful or not. Inside my $.ready() function call I have the following... ``` $('#login_form').submit(function() { var email = $('input#login_email').val(); var pw = $('input#login_password').val() $.get('/user/login.php', { login_email: email, login_password: pw }, function(data) { alert('get succeeded'); if(data == 'true') { $('#login_error').hide(); window.location = '/user/home.php'; alert('true'); } else { $('#login_error').show(); alert('false'); } }); alert('called'); return false; }); ``` In FF, I am successfully transferred to the intended page. In IE, however, the below alerts "called" and nothing else. When I refresh the page, I can see that I am logged in so the $.get call is clearly going through, but the callback function doesn't seem like its being called (ie. "get succeeded" is not popping up). I also don't appear to be getting any javascript error messages either. Why isn't this working in IE? Thanks **EDIT:** Since a couple people asked, whenever I enter a correct email/password or an incorrect one, nothing in the callback function happens. If I manually refresh the page after entering a correct one, I am logged in. Otherwise, I am not. **EDIT 2:** If I alert out `data` in the callback function nothing happens in IE (I do not get an alert popup). In FF, it alerts `true` for valid email/pw combos and `false` for invalid ones. I am using jQuery 1.3.2. **EDIT 3:** Ok, guys, I tried R. Bemrose's thing down there and I'm getting a "parseerror" on the returned data. I'm simply echoing 'true' or 'false' from the other PHP script. I also tried 'yes' and 'no', but that still gave me a parse error. Also, this works in Chrome in addition to FF.
In your response type use: header("content-type:application/xml;charset=utf-8");
As stupid as this sounds... perhaps IE7 is being anal retentive about the missing semicolon on the `var pw` line? Probably not, but the only way I can think of getting more information is to convert it to an $.ajax call in order to add an error hook and see which error type it think is happening. Oh, and to check out the exception object. ``` $.ajax({ type: 'GET', url: '/user/login.php', data: { login_email: email, login_password: pw }, success: function(data) { alert('get succeeded'); if(data == 'true') { $('#login_error').hide(); window.location = '/user/home.php'; alert('true'); } else { $('#login_error').show(); alert('false'); } }, error: function(xhr, type, exception) { alert("Error: " + type); } }); ``` If the error type is parse, IE may be complaining because the data coming back has extra commas at the end of comma separated arrays/lists.
Issue with jQuery $.get in IE
[ "", "javascript", "jquery", "internet-explorer", "" ]
**There is unordered list**, which not works properly in IE6-7, I would like want to **replace it by a jQuery function**. So, we have: * simple list with special #id (ul id="") * some `<li>` tags * some special tag in `<li>` to show the number of a row (or something else, as you wish). I need a function which will give an unique number for each row, from the beginning to the end of our unordered list. (ul)
``` <ul><li>test</li><li>test</li><li>test</li><li>test</li><li>test</li><li>test</li><li>test</li></ul> $(document).ready(function(){ var increment=3; var start=8; $("ul").children().each(function(i) { $(this).prepend('<tag>'+(start+i*increment).toString()+'.</tag>'); }); }); ``` result: ``` * 8. test * 11. test * 14. test * 17. test * 20. test * 23. test * 26. test ``` edit: without increment and shorter: ``` $(document).ready(function(){ $("ul").children().each(function(i) { $(this).prepend('<b>'+(1+i).toString()+'.</b> '); }); }); ```
I think this should work, no? ``` $(function() { $('#the_ul_ID li').each(function(i) { $(this).attr('rel',++i); }); }); ```
Generating an unordered list with jQuery
[ "", "javascript", "jquery", "" ]
I've tried everything from reading the Netbeans help to browsing Google. This code works fine in **Dev-Cpp** but not **Netbeans 6.5.1**. Netveans also places and exclamation mark next to `#include <iostream>` which i checked and is in the include path of netbeans and is in the include folder: ``` #include <iostream> int main() { std::cout << "Test" << "\n"; return (0); } ``` My build tools are set to: Family: `MinGW` **Base Directory**: `C:\Dev-Cpp\bin` **C Compiler**: `C:\Dev-Cpp\bin\gcc.exe` **C++ Compiler**: `C:\Dev-Cpp\bin\g++.exe` **Fortran Compiler**: `C:\Dev-Cpp\bin\g77.exe` **Make Command**: `C:\Dev-Cpp\bin\make.exe` **Debugger Command**: `C:\Dev-Cpp\bin\gdb.exe` I get error: ``` Running "C:\Dev-Cpp\bin\make.exe -f Makefile CONF=Debug" in C:\Documents and Settings\Babiker\Desktop\Temp\Test ! was unexpected at this time. C:\Dev-Cpp\bin\make.exe: *** [.validate-impl] Error 255 Build failed. Exit value 2. ```
The cause of the error is that Netbeans is incompatible with MinGW's make. You have a choice of supported make versions: * Cygwin's make. [Cygwin](http://www.cygwin.com "Cygwin") is a blessing. It brings as much Unix to Windows as you'd like. * MinGW's own [MSYS](http://www.mingw.org/wiki/msys), which "is a collection of GNU utilities such as bash, make, gawk and grep to allow building of applications and programs which depend on traditionally UNIX tools to be present". It is also a much smaller download than Cygwin.
MinGW make tool in not compatible with NetBeans. Use msys make tool instead. When you choose to use the make tool from msys, please be carefull to be installed in a path without spaces. For example C:\Program Files\MinGW\msys\1.0\bin\make will fail. A good choice would be C:\MinGW\msys\1.0\bin\make.
C++ compiler error in netbeans
[ "", "c++", "windows", "netbeans", "mingw", "" ]
I am wondering if such thing is possible: I have a java program that takes arguments and gives output to the console. What i need is to run it multiple times - it (jar file) runs smoothly but the overhead for starting and stoping java runtime is way to big. Is there a way to instantiate java runtime (or vm, I'm not sure how to call it) once, and then somehow connect to that runtime several times and execute the jar? I hope that despite my serious ignorance of java terminology, someone will be able to answer my question :D.
It should be straightforward to write a wrapper class that calls into the JAR's Main-class, and calls AppClass.main() with the appropriate arguments repetitively: ``` // wraps class MyWrapped class MyWrapper { public static void main(String[] args) { for (each set of command-line args) { MyWrapped.main(arguments); } } ``` Remember, a Java app's main() method is nothing special, it's just a static method you can call yourself. It could even be invoked by multiple threads simultaneously, if properly designed.
Might be a better to design to create a main wrapper that executes your code multiple times. Think about it in those terms. Instantiate a class file and call a method as many times as you need.
Running java programs in one runtime instance
[ "", "jvm", "java", "" ]
How to activate JMX on a JVM for access with jconsole?
The relevant documentation can be found here: <http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html> Start your program with following parameters: ``` -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.rmi.port=9010 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false ``` For instance like this: ``` java -Dcom.sun.management.jmxremote \ -Dcom.sun.management.jmxremote.port=9010 \ -Dcom.sun.management.jmxremote.local.only=false \ -Dcom.sun.management.jmxremote.authenticate=false \ -Dcom.sun.management.jmxremote.ssl=false \ -jar Notepad.jar ``` `-Dcom.sun.management.jmxremote.local.only=false` is not necessarily required but without it, it doesn't work on Ubuntu. The error would be something like this: ``` 01 Oct 2008 2:16:22 PM sun.rmi.transport. customer .TCPTransport$AcceptLoop executeAcceptLoop WARNING: RMI TCP Accept-0: accept loop for ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=37278] throws java.io.IOException: The server sockets created using the LocalRMIServerSocketFactory only accept connections from clients running on the host where the RMI remote objects have been exported. at sun.management.jmxremote.LocalRMIServerSocketFactory$1.accept(LocalRMIServerSocketFactory.java:89) at sun.rmi.transport. customer .TCPTransport$AcceptLoop.executeAcceptLoop(TCPTransport.java:387) at sun.rmi.transport. customer .TCPTransport$AcceptLoop.run(TCPTransport.java:359) at java.lang.Thread.run(Thread.java:636) ``` see <https://bugs.java.com/bugdatabase/view_bug?bug_id=6754672> **Also be careful with `-Dcom.sun.management.jmxremote.authenticate=false`** which makes access available for anyone, but if you only use it to track the JVM on your local machine it doesn't matter. **Update**: In some cases I was not able to reach the server. This was then fixed if I set this parameter as well: `-Djava.rmi.server.hostname=127.0.0.1`
Running in a Docker container introduced a whole slew of additional problems for connecting so hopefully this helps someone. I ended up needed to add the following options which I'll explain below: ``` -Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=${DOCKER_HOST_IP} -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.rmi.port=9998 ``` **DOCKER\_HOST\_IP** Unlike using jconsole locally, you have to advertise a different IP than you'll probably see from within the container. You'll need to replace `${DOCKER_HOST_IP}` with the externally resolvable IP (DNS Name) of your Docker host. **JMX Remote & RMI Ports** It looks like JMX also requires access to a remote management interface ([jstat](http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstatd.html)) that [uses a different port](https://johnpfield.wordpress.com/2014/01/29/how-to-monitor-a-remote-jvm-running-on-rhel/) to transfer some data when arbitrating the connection. I didn't see anywhere immediately obvious in `jconsole` to set this value. In the linked article the process was: * Try and connect from `jconsole` with logging enabled * Fail * Figure out which port `jconsole` attempted to use * Use `iptables`/`firewall` rules as necessary to allow that port to connect While that works, it's certainly not an automatable solution. I opted for an upgrade from jconsole to [VisualVM](https://visualvm.github.io/index.html) since it let's you to explicitly specify the port on which `jstatd` is running. In VisualVM, add a New Remote Host and update it with values that correlate to the ones specified above: [![Add Remote Host](https://i.stack.imgur.com/FT8Uw.png)](https://i.stack.imgur.com/FT8Uw.png) Then right-click the new Remote Host Connection and `Add JMX Connection...` [![Add JMX Connection](https://i.stack.imgur.com/Wdn0f.png)](https://i.stack.imgur.com/Wdn0f.png) Don't forget to check the checkbox for `Do not require SSL connection`. Hopefully, that should allow you to connect.
How to activate JMX on my JVM for access with jconsole?
[ "", "java", "jvm", "monitoring", "jmx", "jconsole", "" ]
Does anybody have any idea how to print an excel file programatically using C# and the Excel Interop? If so, can you please provide code?
In order to print, you can make use of the [Worksheet.PrintOut()](http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.printout.aspx) method. You can omit any or all of the optional arguments by passing in [Type.Missing](http://msdn.microsoft.com/en-us/library/system.type.missing.aspx). If you omit all of them, it will default to printing out one copy from your active printer. But you can make use of the arguments to set the number of copies to print, collation, etc. See help on the [Worksheet.PrintOut()](http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.printout.aspx) method for more. The example they show in the help file is: ``` private void PrintToFile() { // Make sure the worksheet has some data before printing. this.Range["A1", missing].Value2 = "123"; this.PrintOut(1, 2, 1, false, missing, true, false, missing); } ``` But unless you need to change the default settings, you can simply pass in [Type.Missing](http://msdn.microsoft.com/en-us/library/system.type.missing.aspx) for all the arguments. Here's an example using automation to open an Excel Workbook, print the first page, and then shut down: ``` void PrintMyExcelFile() { Excel.Application excelApp = new Excel.Application(); // Open the Workbook: Excel.Workbook wb = excelApp.Workbooks.Open( @"C:\My Documents\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing,Type.Missing); // Get the first worksheet. // (Excel uses base 1 indexing, not base 0.) Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1]; // Print out 1 copy to the default printer: ws.PrintOut( Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // Cleanup: GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.FinalReleaseComObject(ws); wb.Close(false, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(wb); excelApp.Quit(); Marshal.FinalReleaseComObject(excelApp); } ``` Hope this helps! Mike
Important improvement is the code for select the Printer, for example: ``` var printers = System.Drawing.Printing.PrinterSettings.InstalledPrinters; int printerIndex = 0; foreach(String s in printers) { if (s.Equals("Name of Printer")) { break; } printerIndex++; } xlWorkBook.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing,printers[printerIndex], Type.Missing, Type.Missing, Type.Missing); ```
Printing Excel using Interop
[ "", "c#", "excel", "interop", "printing", "" ]
I've written a little script that collects my external IP address every time I open a new terminal window and appends it, at well as the current time, to a text file. I'm looking for ideas on a way to visualize when/how often my IP address changes. I bounce between home and campus and could separate them using the script, but it would be nice to visualize them separately. I frequently use matplotlib. Any ideas?
Plot your IP as a point on [the xkcd internet map](http://xkcd.com/195/) (or some zoomed in subset of the map, to better show different but closely neighboring IPs). Plot each point "stacked" proportional to how often you've had that IP, and color the IPs to make more recent points brighter, less recent points proportionally darker.
"When" is one dimensional temporal data, which is well shown by a timeline. At larger timescales, you'd probably lose the details, but most any plot of "when" would have this defect. For "How often", a standard 2d (bar) plot of time vs frequency, divided into buckets for each day/week/month, would be a standard way to go. A moving average might also be informational. You could combine the timeline & bar plot, with the timeline visible when you're zoomed in & the frequency display when zoomed out. How about a bar plot with time on the horizontal axis where the width of each bar is the length of time your computer held a particular IP address and the height of each bar is inversely proportional to the width? That would also give a plot of when vs how often plot. You could also interpret the data as a [pulse density modulated](http://en.wikipedia.org/wiki/Pulse-density_modulation) signal, like what you get on a SuperAudio CD. You could graph this or even listen to the data. As there's no obvious time length for an IP change event, the length of a pulse would be a tunable parameter. Along similar lines, you could view the data as a square wave (triangular wave, sawtooth &c), where each IP change event is a level transition. Sounds like a fun [Pure Data](http://puredata.info/) project.
How to visualize IP addresses as they change in python?
[ "", "python", "matplotlib", "ip-address", "visualization", "" ]
We are using APC as an opcode cache. Is there a way to get APC to cache the non-existence of a file? We have set `apc.stat = 0` and `apc.include_once_override = 1`. Is there something more to do to improve the performance of calling `include_once` on a file that may not be present on the filesystem? If it is present, obviously we want to include it. However, if it is not present, it will *never* be present and we don't want PHP to call `open()` on the file on every request to check. For some background: we have one base site but provide customizations to the site on a customer-by-customer basis. Some customers have a custom login page, others have totally unique pages, etc. We're using the Zend Framework in a slightly unusual way to allow us to override controllers as necessary. Our site might have a controller called `LoginController`, defined in a file `controllers/LoginController.php`. However, our client "Company" might have a requirement for a custom login page, so we will write a new class called `Company_LoginController` defined in a directory `controllers/company/LoginController.php`. (This naming convention allows us to be consistent with the Zend Framework notion of "modules".) When we're dealing with the class, we basically do something like this: ``` include_once APPLICATION_PATH . '/controllers/company/LoginController.php'; if (class_exists("Company_LoginController")) { echo 'customer-specific controller exists'; } else { include_once APPLICATION_PATH . '/controllers/LoginController.php'; echo 'customer-specific controller does not exist; using default'; } ``` If the file `/controllers/company/LoginController.php` exists, APC will cache it on the first request and never fetch it from the filesystem again. However, if the file `/controllers/company/LoginController.php` does *not* exist, I don't want APC to check for the existence of this file more than once. Any way to make this happen?
Can you just create empty files in the company directory? Since APC will not load them twice, there's no harm in having some empty files that get "loaded" the first time the server starts.
jmucchiello's answer gets my vote for simplicity, but if for some reason that's not practical, you could always do things the hard way. The following is a rough, untested example, but it should communicate the basic idea, which is to manually store the existence of the file in APC yourself ``` function conditional_include($file) { $key = 'file-exists-' . $file; //fetch cache key; if it does not exist, then... if(($fileExists = apc_fetch($key)) === false) { //actually hit the disk to look for the file, and store the result apc_store($key, $fileExists = (file_exists($file) ? 1 : 0)); } //only include the file if it exists. if($fileExists) include_once $file; } ```
Opcode caching in APC and missing files
[ "", "php", "apc", "" ]
Is it possible to get the selected row index from my table model? My object already knows about the table model. Instead of passing a reference to the table it self can i get the selected index using the model?
The TableModel only concerns itself with the data, the ListSelectionModel concerns itself with what is currently selected, so, no you can't get the selected row from the TableModel.
Like MrWiggles said you can get it from the ListSelectionModel which you is accessible from the table itself. However there are convenience methods in JTable to get the selected rows as well. If your table is sortable etc you will also need to go through the convertRowIndexToModel method :) From the JTable JavaDoc: ``` int[] selection = table.getSelectedRows(); for (int i = 0; i < selection.length; i++) { selection[i] = table.convertRowIndexToModel(selection[i]); } // selection is now in terms of the underlying TableModel ```
getting selected row through AbstractTableModel
[ "", "java", "swing", "jtable", "" ]
Is there a good reason (advantage) for programming this style ``` XmlDocument doc = null; doc = xmlDocuments[3]; ``` vs ``` XmlDocument doc = xmlDocuments[3]; ``` I have seen it many times but to me it just seem overly verbose
No - it's generally considered best practice to declare a variable as late as you can, preferably setting it at the point of declaration. The only time when I don't do that is when I have to set a variable conditionally, or it's set in a more restrictive scope: ``` String name; using (TextReader reader = ...) { // I can't declare name here, because otherwise it isn't // accessible afterwards name = reader.ReadToEnd(); } ``` Reasons for declaring at the point of first use where possible: * It keeps the variable's type close to its use - no need to scroll back up in the method to find it. * It keeps the scope as narrow as possible, which makes the use of the variable more obvious.
I would use ``` XmlDocument doc = xmlDocuments[3]; ``` Declare variables where they are used.
C# programming style question - Assignment of Null Before Real Assignment
[ "", "c#", "coding-style", "" ]
I'm trying to write an embedded (**NOT web, not enterprise**) content management system in Java, with a focus on organization and ease of use and scalability to 100,000 or so items. The user & system should be able to create and define metadata items which can be associated with unique resources, to allow for searching. For example, they can create a tag "ProjectName" which takes String values. Then they can tag a bunch of resources as belonging to projects "Take Over the World" or "Fix My Car." The tags are strongly typed, so a tag may store single or multiple string(s), integer(s), double(s), etc. Each tag type should have formatters and input validators to allow editing. I've decided that it is important to abstract the storage model from the GUI, to allow for scalability; the obvious way to do this is to use data access objects (DAOs) for each resource. However, I can't figure out how to write DAOs that support a variable number of tags and will scale properly. The problem is that resources need to behave both as tuples (for tabular viewing/sorting/filtering) and as (TagName,TagValue) maps. The GUI models may call these methods potentially thousands of times for each GUI update, so some notion of indexing would make it all work better. Unfortunately, the multiple tag types mean it'll be awkward unless I return everything as a generic Object and do a whole mess of "TagValue instanceof Type" conditionals. I've looked into using reflection and Apache's DynaBeans, but coding this to work with GUI models looks just painful and awkward. Is there a better way to do this??? Some library or design pattern? So, my question is, is there a better way? Some library or design pattern that would simply this whole thing?
I don't think you should consider any of these properties as actual member variables. You should have a "Property" object that contains a property (which would be analogous to a member variable), and a "Collection" object that has collections of properties (which would be like a class). Since these attributes and collections don't really have code associated with them, it would make no sense to implement them as objects (and would be a real pain in the butt) Your attributes and collections need to hold ALL the data specific to them. For instance, if a field is eventually written to the database, it needs to have it's table name stored somewhere. If it needs to be written to the screen, that also needs to be stored somewhere. Range/value checking can be "Added" to the attributes, so when you define what type of data an attribute is, you might have some text that says "MaxLength(12)" which would instantiate a class called MaxLength with the value 12, and store that class into the attribute. Whenever the attribute's value changes, the new value would be passed to each range checker that has been applied to this class. There can be many types of actions associated with the class. This is just the base. I've designed something like this out and it's a good deal of work, but it's much simpler than trying to do it in a straight language. I know that this seems like WAY too much work right now (it should if you actually get what I'm suggesting), but keep it in mind and eventually you'll probably go "Hmph, maybe that was worth a try after all". edit (response to comment): I thought about trying to work with the registry/key thing (we're still talking attribute value pairs), but it doesn't quite fit. You are trying to fit DAOs into Java Objects. This is really natural, but I've come to see it as just a bad approach to solving the DAO/DTO problem. A Java Object has attributes and behaviors that act on those attributes. For the stuff you are doing, there are no behaviors (for instance, if a user creates an "Birthday" field, you won't be using object code to calculate his age because you don't really know what a birthday is). So if you throw away having Objects and attributes, how would you store this data? Let me go with a very simple first step (that is very close to the registry/tag system you mentioned):Where you would have used an object, use a hashtable. For your attribute names use keys, for the attribute values, use the value in the hashtable. Now, I'll go through the problems and solutions I took to enhance this simple model. Problem: you've lost Strong Typing, and your data is very free-format (which is probably bad) Solution: Make a base class for "Attribute" to be used in the place of the value in the hashtable. Extend that base class for IntegerAttribute, StringAttribute, DateAttribute, ... Don't allow values that don't fit that type. Now you have strong typing, but it's runtime instead of compile time--probably okay since your data is actually DEFINED at runtime anyway. Problem: Formatters and Validators Solution: Have the ability to create a plug-in for your attribute base-class. You should be able to "setValidator" or "setFormatter" for any attribute. The validator/formatter should live with the attribute--so you probably have to be able to serialize them to the DB when you save the attribute. The nice part here is that when you do "attribute.getFormattedValue()" on the attribute, it's pre-formatted for display. attribute.setValue() will automatically call the validator and throw an exception or return an error code if any of the validations fail. Problem: How do I display these on the screen? we already have getFormatted() but where does it display on the screen? what do we use for a label? What kind of a control should edit this field? Solution: I'd store all these things inside EACH attribute. (The order should be stored in the Class, but since that's a hashtable so it won't work--well we'll get to that next). If you store the display name, the type of control used to render this (text field, table, date,...) and the database field name, this attribute should have all the information it needs to interact with display and database I/O routines written to deal with attributes. Problem: The Hashtable is a poor interface for a DAO. Solution: This is absolutely right. Your hashtable should be wrapped in a class that knows about the collection of attributes it holds. It should be able to store itself (including all its attributes) to the database--probably with the aid of a helper class. It should probably be able to validate all the attributes with a single method call. Problem: How to actually work with these things? Solution: Since they contain their own data, at any point in your system where they interact (say with the screen or with the DB), you need an "Adapter". Let's say you are presenting a screen to edit your data. Your Adapter would be passed a frame and one of your hashtable-based DTOs. First it would walk through the list of attributes in order. It would ask the first attribute (say a string) what kind of control it wanted to use for editing (let's say a text field). It would create a text field, then it would add a listener to the text field that would update the data, this binds your data to the control on the screen. Now whenever the user updates the control, the update is sent to the Attribute. The attribute stores the new value, you're done. (This will be complicated by the concept of an "OK" button that transfers all the values at once, but I would still set up each binding before hand and use the "OK" as a trigger.) This binding can be difficult. I've done it by hand, once I used a toolkit called "JGoodies" that had some binding ability built in so that I didn't have to write each possible binding combination myself, but I'm not sure in the long-run it saved much time. This is way too long. I should just create a DAO/DTO toolkit someday--I think Java Objects are not at all suited as DAO/DTO objects. If you're still stumped, feel free to Email/IM me-- bill.kress at gmail..
I assume from your question that a "resource" is an entity in your system that has some "tag" entities associated with it. If my assumption is correct, here's a vanilla DAO interface, let me know if this is what you're thinking: ``` public interface ResourceDAO { void store(Resource resource); void remove(Resource resource); List<Resource> findResources(QueryCriteria criteria); void addTagsToResource(Resource resource, Set<Tag> tags); } ``` The idea here is that you would implement this interface for whatever data storage mechanism you have available, and the application would access it via this interface. Instances of implementation classes would be obtained from a factory. Does this fit with what you're thinking? The other aspect of the problem you mention is having to contend with multiple different TagTypes that require different behavior depending on the type (requiring "TagValue instanceof Type" conditionals). The [Visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern) may handle this for you in an elegant way.
How can I write DAOs for resources with extensible properties?
[ "", "java", "database", "metadata", "" ]
Given a need to write command line utilities to do common tasks like uploading files to a remote FTP site, downloading data from a remote MySQL database etc. Is it practical to use JavaScript for this sort of thing? I know there are JavaScript interpreters that can be run from the command line, but are there libraries for things like FTP and database access the way there are for e.g. Java? If so, what's the best place to look for them? (Google searches with JavaScript in the keywords always seem to return many pages of browser specific things.) And is there a way to package a JavaScript program up as a standalone executable on Windows? Update: I've decided Python is a better tool for this kind of job, but the answers to the original question are still good ones.
[Node.js](http://nodejs.org/#download) is by far the best environment for running non-browser JS. I've used Rhino and SpiderMonkey, and there's a pretty huge difference in everything from the basics like how errors are handled to the size of the community using the tool. Node is pitched for "server-side" JS - building server apps in JS. It's great for this. But it works equally well for building command line tools. The NPM package manager (bundled with Node) provides a nice global directory for finding and installing packages. It works much better than other language equivalents like PECL / Pear / CPAN / etc. Several high quality tools like [JSHint](http://www.jshint.com/), The [Jade](http://jade-lang.com/) templating language, and the [CoffeeScript](http://coffeescript.org/) compiler are all already available through NPM/Node: ``` npm install -g jshint, coffee-script, jade jshint my_code.js jade < my.jade > my.html ``` For args parsing, there are packages like [commander.js](http://tjholowaychuk.com/post/9103188408/commander-js-nodejs-command-line-interfaces-made-easy). I currently use a heavily extended version of Commander in my [underscore-cli](http://github.com/ddopson/underscore-cli) command-line tool. For messing with JSON or for doing command-line JS work (similar to "perl -pe"), check out [underscore-cli](http://github.com/ddopson/underscore-cli) - It's a really powerful tool for processing JSON data, processing underscore templates, and running JS expressions from the command-line. I use it for 1001 different things that would otherwise be really annoying to accomplish.
Standalone executable? By the way you ask the question, I'm not sure if you are aware, but the Windows Script Host - included in Windows - allows you to run .js files from the command-line. Your javascript will not be an executable, it will remain a script, a text file. The script runs within cscript.exe, which is provided by WSH. There's no compilation required. Maybe you knew all that. I use Javascript this way for various utilities on Windows. I think your instinct is right on the availability of libraries. You are sort of *on your own* to find all those things. Although, once you find them, it's not hard to package Javascript libraries as COM components and allow re-use from anywhere. [See here for an example](https://stackoverflow.com/questions/848246/how-can-i-use-javascript-within-an-excel-macro) of packaging the Google Diff/Patch/Match Javascript library in COM. **Addendum**: Once a bit of code is available within COM, it can be consumed by any Javascript running on the machine. Some examples of COM objects available to Javascript scripts running in WSH: * [MSXML2.XMLHTTP object](http://support.microsoft.com/kb/296772) - used in AJAX, but can be used for any HTTP communication. There also an object for the XSLT engine so you can do transforms from script. * [Excel.Application](http://msdn.microsoft.com/en-us/library/7sw4ddf8(VS.85).aspx) - allows you to open up Excel spreadsheets and automate them from Javascript. * [Communicator.UIAutomation](http://msdn.microsoft.com/en-us/library/bb758725.aspx) - automate MS Communicator (send IM's via script) * [COM objects for Google Earth](http://search.live.com/results.aspx?q=%2bgoogleearth.applicationge). * [SlowAES](https://stackoverflow.com/questions/270510/how-to-encrypt-in-vbscript-using-aes/858525#858525) - an all-Javascript implementation of AES encryption.
Javascript for command line utilities
[ "", "javascript", "command-line", "" ]
I'd like to test my knowledge in EJB, making an small application. Could you give me some ideas for doing with EJB?
Try to play with the code example of [EJB in Action](http://www.manning.com/panda/). You can find the source [here](http://www.manning.com/panda/). The source is available for JBoss, Glassfish, OracleAS. In this way, you can have a good grasp on all type of beans, plus JPA stuff. Cheers.
Use them all: Message: a message driven bean listens on a queue. keep the message simple: a simple string message sent by an external client. Entity: a persistent entity records the last message received. msgBean updates the 'lastMsg' property of the entity. This is transactional. Session: a stateless session returns the last message at any given moment, as a simple service. Session: a stateful session for a simple servlet client. the web ui has a text field (for last msg) and a button for refresh. If you can do that, you are pretty much on your way.
What can I do with EJB?
[ "", "java", "ejb", "" ]
I'm currently working on some evaluation work for a project that I'm planning. I recently looked at solutions for a data storage mechanism for my application and while researching stumbled upon SQLite. I currently use SQLite with the System.Data.SQLite wrapper. I really like the way it works but I have one problem with it that I couldn't get fixed and I also found no help concerning my problem on the internet. I would like my SQLite Database to be embedded into one of my applications DLLs (ie. Title.Storage.dll) to be used within this DLL. Is this possible? How can I access the database then? It would be great if I could use something like: ``` SQLiteConnection con = new SQLiteConnection(); con.ConnectionString="DataSource=Title.Storage.storage.db3"; con.Open(); ``` Thanks in advance and best regards, 3Fox
An assembly isn't for file storage, it's for code storage. While you can store files in an assembly, they are read only.
This is not possible as such. What you could do is embed the db in your dll project and dump it to certain location on the file system (may be AppData?) and read and write from there. Having db sit directly inside the executable (or dlls) may not be a good idea in the sense it bloats the size of the application besides being technically infeasible. Having a single executable to distribute is a matter of taste which I like. In your case but the problems are more. It's not just about embedding the db file alone, what about the dlls associated with it? Steps are 2: 1) Add the necessary dlls (`System.Data.SQLite`?) associated with your db to your project as `Embedded Resource` *(not necessarily a `Resource file`)* and let the system automatically resolve the assembly conflicts. [Catch it here](https://stackoverflow.com/a/10600046/661933) how to do it. 2) Now either add your db file to your `Resources` of your project (and extract it) ``` static void DumpDatabase() { var dbFullPath = Utility.GetDbFullPath(); //your path if (File.Exists(dbFullPath)) return; //whatever your logic is File.WriteAllBytes(dbFullPath, Properties.Resources.myDb); } ``` or **even better** do not embed the db as such in your project but write the logic to create database in your application. What if tomorrow you need to change the version of SQLite, say from 3 to 4? With the first approach you need to create a database for yourself and re-embed it in the project. But if you are writing the logic to create the db in your application then updating SQLite version is just a matter of changing the ADO.NET dll (the code remains the same). May be like this: ``` static void DumpDatabase() { var dbFullPath = Utility.GetDbFullPath(); if (File.Exists(dbFullPath)) return; //whatever your logic is CreateDb(dbFullPath); } static void Create(string dbFullPath) { SQLiteConnection.CreateFile(dbFullPath); string query = @" CREATE TABLE [haha] (.............) CREATE TABLE .............."; Execute(query); } ``` And in the connection string add `FailIfMissing=False;`
How can I embed a SQLite Database in a .NET DLL and then use it from C#?
[ "", "c#", ".net", "sqlite", "dll", "embed", "" ]
How do I get a line count of a large file in the most memory- and time-efficient manner? ``` def file_len(filename): with open(filename) as f: for i, _ in enumerate(f): pass return i + 1 ```
You can't get any better than that. After all, any solution will have to read the entire file, figure out how many `\n` you have, and return that result. Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you can do is make sure you don't use unnecessary memory, but it looks like you have that covered. **[Edit May 2023]** As commented in many other answers, in Python 3 there are better alternatives. The `for` loop is not the most efficient. For example, using `mmap` or buffers is more efficient.
One line, faster than the `for` loop of the OP (although not the fastest) and very concise: ``` num_lines = sum(1 for _ in open('myfile.txt')) ``` You can also **boost the speed** (and robustness) by using `rbU` mode and include it in a `with` block to close the file: ``` with open("myfile.txt", "rbU") as f: num_lines = sum(1 for _ in f) ``` ***Note**: The `U` in `rbU` mode is deprecated since Python 3.3 and above, so iwe should use `rb` instead of `rbU` (and it has been removed in [Python 3.11](https://docs.python.org/3/whatsnew/3.11.html#porting-to-python-3-11)).*
How to get the line count of a large file cheaply in Python
[ "", "python", "text-files", "line-count", "" ]
As you know, one can customize the width of the scrollbar width in Display Properties -> Appearance -> Advanced -> Item: ScrollBar. The default value is 17. However, I can't assume this is always the case, is it possible for me to retrieve this value?
Look at the `System.Windows.Forms.SystemInformation` class members: [`HorizontalScrollBarHeight`](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.horizontalscrollbarheight.aspx) and [`VerticalScrollBarWidth`](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.verticalscrollbarwidth.aspx).
Vertical Scroll Bar Width ``` System.Windows.Forms.SystemInformation.VerticalScrollBarWidth; ```
How do I know the current width of system scrollbar?
[ "", "c#", "winforms", "" ]
How can I execute SQL statements from a C program. For example I want to display the output of `select * from EMP` from a c program. Do I need to do it using Stored Procedures? Do I need any library files to do it. My C compiler is Tiny C Compiler and I am currently having SQL server studio 2005. Suggestions for Unix/AIX platform + GCC are also invited. Thanks in advance..
I am now using the following method explained [in this question by me.](https://stackoverflow.com/questions/1259462/is-it-a-good-way-to-use-system-for-database-scripts-from-c)It is satisfying my requirements.
The old but reliable solution, for \*ix as well as Windows, and for all (significant) database servers, is [ODBC](http://en.wikipedia.org/wiki/ODBC). I recommend the [Easysoft tutorial](http://www.easysoft.com/developer/languages/c/odbc_tutorial.html). According to [this](http://itknowledgeexchange.techtarget.com/itanswers/setting-the-odbc-in-sql-server-2005/), you may have to manually install the SQL Server ODBC driver from CD.
How to execute sql statements from a C program?
[ "", "sql", "c", "stored-procedures", "" ]
I have trouble when designing classes like this ``` class C1 { public: void foo(); } class C2 { public: void foo(); } ``` C1 and C2 has the same method foo(), ``` class Derived1 : public Base { public: void Update() { member.foo(); } private: C1 member; } class Derived2 : public Base { public: void Update() { member.foo(); } private: C2 member; } ``` Update() of both Derived class are exactly the same, but the type of member is different. So i have to copy the Update implement for every new derived class. Is that a way to reduce this code duplication? I only come out with a solution with macro. I think there is a more elegant way to solve this with template but I can not figure it out.. **EDIT:** thanks a lot guys but i think i missed something.. 1.I'm using c++ 2.In reality each Derived class has about 5 members, they all afford the foo() method and are derived from the same base class. My situation is that i have already written a (very long) Update() method and it can work for every derived class without any modification. So i just copy and paste this Update() to every new class's Update() and this lead to terrible code duplication. I wonder if there is a way in which i need not to rewrite the Update() too much and can reduce the duplication. thx again
This is exactly the sort of application that class templates are designed for. They allow functions within a class to operate on different data types, without the need to copy algorithms and logic. [This Wikipedia page](http://en.wikipedia.org/wiki/Template_(programming)) will give you a good overview of templates in programming. Here's the basic idea to get you started: ``` template <class T> class CTemplateBase { public: void Update() { member.foo(); } private: T member; // Generic type } class CDerived1 : public CTemplateBase<C1> { // No common algorithms required here } class CDerived2 : public CTemplateBase<C2> { // No common algorithms required here } ```
If you have the control over C1 and C2, you can either define a base class or an abstract base class and handle it at Base class or third helper class.
How to reduce code duplication on class with data members with same name but different type?
[ "", "c++", "class-design", "" ]
I have a generic with some filenames (LIST1) and another biggeneric with a full list of names (LIST2). I need to match names from LIST1 to similar ones in LIST2. For example ``` LIST1 - **MAIZE_SLIP_QUANTITY_3_9.1.aif** LIST 2 1- TUTORIAL_FAILURE_CLINCH_4.1.aif 2- **MAIZE_SLIP_QUANTITY_3_5.1.aif** 3- **MAIZE_SLIP_QUANTITY_3_9.2.aif** 4- TUTORIAL_FAILURE_CLINCH_5.1.aif 5- TUTORIAL_FAILURE_CLINCH_6.1.aif 6- TUTORIAL_FAILURE_CLINCH_7.1.aif 7- TUTORIAL_FAILURE_CLINCH_8.1.aif 8- TUTORIAL_FAILURE_CLINCH_9.1.aif 9- TUTORIAL_FAILURE_PUSH_4.1.aif ``` I've read about [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) and used an implementation of it in a Framework ([SignumFramework Utilities](http://www.signumframework.com/Others.ashx#StringDistance)). **It returns me distance=1 in lines 2 and 3. But in my case line 3 is a better match than line 2.** Is there another method better to compare similar strings? Something more flexible?
When comparing as strings, "9.2" is not a better match than "5.1" for "9.1". If you want the version numbers to be evaluated numerically, you have to parse the strings so that you can compare the string parts and the numerical parts separately.
Your similarity criteria could be a combination of several other criteria. One could be the Levenshtein distance, others might e.g be the longest common substring or prefix/suffix. The longest common substring problem is actually a special case of edit distance, when substitutions are forbidden and only exact character match, insert, and delete are allowable edit operations (see [here](http://www.cs.sunysb.edu/~algorith/files/longest-common-substring.shtml)). Further metrics for string similarity are described [here](http://en.wikipedia.org/wiki/Category:String_similarity_measures).
C# comparing similar strings
[ "", "c#", "string", "compare", "similarity", "" ]
I'm looking for examples of [processing.js](http://processingjs.org/) working in Internet Explorer via [ExplorerCanvas](http://code.google.com/p/explorercanvas/) or similar.
The [sparklines example](http://willarson.com/code/sparklines/sparklines.html) on the [processing.js exhibition](http://processingjs.org/exhibition) page uses ExplorerCanvas. It seems like it's just a drop-in solution, no extra coding necessary.
**It can be done!** There are some gotchas, however. [The page htxt links to](http://www.hyper-metrix.com/processing-js/docs/index.php?page=Using%20exCanvas.js%20with%20Processing.js) is fine, as far as it goes, but please note the following: 1) Both script and canvas elements must have id attributes. The init function uses these attribute id's to associate a given script with a given canvas. I found the simplified init function easier to understand than the official one. You will want to master the official one if you have multiple canvases on one page. 2) If you use internet-style color designations, like #23ff9a, watch out! IE 8 wants *all upper case hexadecimal color numbers* from Processing.js/canvas. Write #23FF9A! This is what the documentation shows, so it shouldn't be a complete surprise. The error is a sometime thing, which makes it crazy to figure out. Mostly, larger numbers (for lighter colors) with lots of f's seem to be afflicted. White, #ffffff, is OK, but #ff00ff is not. Firefox and Safari are case-insensitive in this regard. The [documentation](http://processingjs.org/reference/color%20datatype) says you can use an alternate hex notation with alpha channel (the CC) that looks like 0xCC006699. This didn't work for me; maybe it's on the to-do list. 3) The .equals() method on strings is missing! Andor Salga, one of the Seneca College crew working on Processing.js, wrote a simple boolean stringsEqual(str1, str2) function you can see [here](http://asalga.wordpress.com/2009/10/16/strlenyarn/). This will do until the matter is definitively fixed. 4) It's not true that stroke() doesn't work with excanvas.js. It does. However, if your Processing.js code has even one little syntax error (I can't really categorize which kinds, but trying to use .equals() will do it) your routine will probably fail silently in IE8, whereas, in Safari or Firefox, your rectangles may lose their outlines, i.e. stroke() will quit working. IE on Vista, and Safari on the Mac, have both exhibited stronger syntax checking than Safari or Firefox on Vista, which will blow by certain errors and render a defective graphic. 5) Text, invoked using the text() function, renders in Firefox (in an unchangeable font of Firefox's choosing), but, as far as I can tell, not in IE8 or Safari. The *Glyph Method* is suggested [here](http://hyper-metrix.com/processing-js/docs/?page=Cross-Browser%20Canvas%20Fonts). The code is in place, but getting the fonts looks like a problem. Inkscape looks pretty impenetrable to me. As far as I can tell, what is needed is a lot like old pen-plotter fonts - a vector path with pen-up and pen-down commands between runs of nodes. Turns out FSF/GNU has some that might be massaged into the right format without too much trouble. I don't know where the format is defined, but it's probably over at W3C somewhere. The approach with real potential for presentable fonts is the IE/VML wing of Cufon. See [How does it work?](http://wiki.github.com/sorccu/cufon/about) I really want this last link in the chain, but I could use some help. Processing.js is one whale of a project that deserves our support. It has enormous potential. I would encourage you to pitch in if you are able.
Has anyone got processing.js working in IE?
[ "", "javascript", "internet-explorer", "canvas", "processing.js", "" ]
Trying to convince someone to switch from .NET 1.1 I saw people saying that one advantage of using the Dictionary class in post .NET 1.1 is performance increases due to not having to unbox/cast objects. Are there another improvements besides that? Or any other general advantages to moving away from .NET 1.1 ?
[George](http://en.wikipedia.org/wiki/Name_That_Tune), I can answer that question in two words: Type Safety. And now I shall expand. Probably the single biggest benefit of moving to .NET 2.0 is generics and generic collections. A bigger benefit IMO than the performance improvements of not having to box and unbox value types (which isn't really that big a deal unless you've got huge ArrayLists of ints that you process through continuously) is not having to cast to and from object. Or, in two words, "type safety". You know at compile time what the underlying type of the collection is, and you cannot deviate from that. With a non-generic collection, you can throw any old thing in there and unless you reflect on the type (which is an even bigger performance hit than boxing) before you cast, you could wind up with an InvalidCastException being thrown at a bad time. That said, why stop at 2.0? .NET 3.0 has WCF and WPF, which are great new ways to communicate and present. .NET 3.5 has LINQ and lambda expressions, which *will* change the way you process a collection. Tell your friend to stop living in the dark ages. It's time to update!
Assuming you're already aware of the general advantages to using strongly-typed collections, `null` is now a valid value. If the old HashTable returned `null` for a key lookup it might mean that the key doesn't exist or it might mean that that key refers to the value `null`. You didn't really know. With a dictionary, if you do a straight lookup and the key doesn't exist an exception is thrown. Also, .Net 2.0 collections take advantage of generics to support strongly-typed enumeration (`IEnumerable<T>`). The implementation of IEnumerable in .Net uses lazy evaluation, and this makes all kinds of fun things easy (and performant!) that were almost impossible to do before. Probably 9 times out of 10 where you pass or return an array or ArrayList through a function you can use IEnumerable instead.
What other improvements in .NET's Dictionary vs. HashTable besides [un]boxing?
[ "", "c#", "data-structures", "migration", ".net-1.1", "" ]
I have seen the abbreviation WS-\*, but I have not been able to figure out what this means, and why is it important?
WS-\* is shorthand for the the myriad of specifications that are used for web service messaging. Some of the services are: * WS-Security * WS-SecureConversation * WS-Federation * WS-Authorization * WS-Policy * WS-Trust * WS-Privacy * WS-Test There is a lot of information to digest, depending on what you need. [Here's a list](http://en.wikipedia.org/wiki/List_of_Web_service_specifications) of the specifications on Wikipedia.
The Web Service stack. There are a bunch of specifications for Web Services, and there names are written WS-whatever, for example: WS-SecurityPolicy. The \* is used as a wildcard to indicate that you are referring to the Web Services stack.
What is meant by WS-*?
[ "", "c#", ".net", "wcf", "web-services", "" ]
I have two classes generated by LINQ2SQL both from the same table so they have the exact same properties. I want to convert / cast a object to the other class. what's the easiest way to do this? I know I can just manually assign each property, but that is a lot of code.
You can use serialization to make the copy pretty easily by creating a SerializationBinder. This will allow you to deserialize from one type to another. ``` class MySerializationBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { Type typeToDeserialize = null; // To return the type, do this: if(typeName == "TypeToConvertFrom") { typeToDeserialize = typeof(TypeToConvertTo); } return typeToDeserialize; } } ``` As long as the type properties line up you can use this to Serialize the From type and then deserialize into the To type using a BinaryFormatter and setting the Binder property to an instance of your binder class. If you have several types of objects you can use one Binder to cover all the different types. Reflection is another option that you can look into to solve this problem. If the property names are exactly the same you could write a simple method that takes values from one property and assigns to the property of the same name. ``` public static void CopyObject(object source, object destination) { var props = source.GetType().GetProperties(); foreach (var prop in props) { PropertyInfo info = destination.GetType().GetProperty(prop.Name); if (info != null) { info.SetValue(destination, prop.GetValue(source, null), null); } } } ```
You are going to have to either do this by hand, or use a flexible serialization framework to work around this. Its possible you could use the built-in [json serializer](http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx) (export to json, then import from json). Or even the XmlSerializer.
Cast objects of different classes but same types
[ "", "c#", "casting", "" ]
How would I go about using an Expression Tree to dynamically create a predicate that looks something like... ``` (p.Length== 5) && (p.SomeOtherProperty == "hello") ``` So that I can stick the predicate into a lambda expression like so... ``` q.Where(myDynamicExpression)... ``` I just need to be pointed in the right direction. **Update:** Sorry folks, I left out the fact that I want the predicate to have multiple conditions as above. Sorry for the confusion.
**Original** Like so: ``` var param = Expression.Parameter(typeof(string), "p"); var len = Expression.PropertyOrField(param, "Length"); var body = Expression.Equal( len, Expression.Constant(5)); var lambda = Expression.Lambda<Func<string, bool>>( body, param); ``` --- **Updated** re `(p.Length== 5) && (p.SomeOtherProperty == "hello")`: ``` var param = Expression.Parameter(typeof(SomeType), "p"); var body = Expression.AndAlso( Expression.Equal( Expression.PropertyOrField(param, "Length"), Expression.Constant(5) ), Expression.Equal( Expression.PropertyOrField(param, "SomeOtherProperty"), Expression.Constant("hello") )); var lambda = Expression.Lambda<Func<SomeType, bool>>(body, param); ```
Use the predicate builder. <http://www.albahari.com/nutshell/predicatebuilder.aspx> Its pretty easy!
How do I dynamically create an Expression<Func<MyClass, bool>> predicate?
[ "", "c#", "linq", "lambda", "expression-trees", "" ]
How to make `onclick` **without** jQuery, with no extra code in HTML, such as: ``` <a href="#" onclick="tramtramtram"> ``` Just using an external js file? ``` <script type="text/javascript" src="functions.js"></script> ``` --- I need to replace this code: ``` $("a.scroll-up, a.scroll-down").click(function(){ SNavigate($(this).attr("href").substr(7));return false; }); ```
When this anchor will contain only one function to handle on click, than you can just write ``` document.getElementById('anchorID').onclick=function(){/* some code */} ``` otherwise, you have to use DOM method addEventListener ``` function clickHandler(){ /* some code */ } var anchor = document.getElementById('anchorID'); if(anchor.addEventListener) // DOM method anchor.addEventListener('click', clickHandler, false); else if(anchor.attachEvent) // this is for IE, because it doesn't support addEventListener anchor.attachEvent('onclick', function(){ return clickHandler.apply(anchor, [window.event]}); // this strange part for making the keyword 'this' indicate the clicked anchor ``` also remember to call the above code when all elements are loaded (eg. on window.onload) -- edit I see you added some details. If you want to replace the code below ``` $("a.scroll-up, a.scroll-down").click(function(){SNavigate($(this).attr("href").substr(7));return false;}); ``` with sth that doesn't use jQuery, this should do the job ``` function addEvent(obj, type, fn) { if (obj.addEventListener) obj.addEventListener(type, fn, false); else if (obj.attachEvent) obj.attachEvent('on' + type, function() { return fn.apply(obj, [window.event]);}); } addEvent(window, 'load', function(){ for(var i=0, a=document.anchors, l=a.length; i<l;++i){ if(a[i].className == 'scroll-up' || a[i].className == 'scroll-down'){ addEvent(a[i], 'click', function(e){ SNavigate(this.href.substr(7)); e.returnValue=false; if(e.preventDefault)e.preventDefault();return false}); } } }); ```
how about this : ``` document.getElementById("lady").onclick = function () {alert('onclick');}; ```
OnClick without jQuery
[ "", "javascript", "onclick", "" ]
Any idea on interfacing with AutoCAD through a JAVA program. I am looking for a solution that can directly interface with an AutoCAD session (even start one), the way it works with the .NET extensions of AutoCAD. Or any way to work with ObjectARX through JAVA, definitely not writing a complete JNI wrapper over it. Added: We are looking for something in open-source. In case there is none, we are ready to create one in open-source if someone can lend a helping hand explaining how it can be done. We have taken a look at JNA and JaWin. JNA clubbed with JNI might help but is too ugly. JaWin on the other hand has not been updated in the past 4 years, so sort of skeptical using it.
We are working on a similar project. What we are doing is writing the integration code in C#, and the business logic for our project in Java. We are utilizing a C++ bridge that utilizes JNI to take Java calls down to C++, and then translates them back up to C#, and vice versa. Each function that needs to go from C# to Java has to be implemented in the bridge code. This is fairly involved, and there are some issues with getting the unmanaged C++ code to work with the C#, as well as the standard overhead of translating Jstrings into C# Strings and the like. The result is relatively fast, after we did some optimizations to insure that we aren't starting and stopping the JVM for each call into the Java layer. We previously used COM objects which were called by the AutoCAD plugin, so that would be another approach.
The only thing I can think of is to use a Java <-> .Net bridge like [JNBridge](http://www.jnbridge.com/). I've used this in other scenarios and it works fine. Never done any work with Java and AutoCad though so there might be other cheaper solutions.
Interfacing AutoCAD with JAVA
[ "", "java", "autocad", "objectarx", "" ]
I believe (from some research reading) that counting down in for-loops is actually more efficient and faster in runtime. My full software code is C++ I currently have this: ``` for (i=0; i<domain; ++i) { ``` my 'i' is unsigned resgister int, also 'domain' is unsigned int in the for-loop i is used for going through an array, e.g. ``` array[i] = do stuff ``` converting this to count down messes up the expected/correct output of my routine. I can imagine the answer being quite trivial, but I can't get my head round it. UPDATE: 'do stuff' does not depend on previous or later iteration. The calculations within the for-loop are independant for that iteration of i. (I hope that makes sense). UPDATE: To achieve a runtime speedup with my for-loop, do I count down and if so remove the unsigned part when delcaring my int, or what other method? Please help.
I'm guessing your backward for loop looks like this: ``` for (i = domain - 1; i >= 0; --i) { ``` In that case, because `i` is **unsigned**, it will **always** be greater than or equal to zero. When you decrement an unsigned variable that is equal to zero, it will wrap around to a very large number. The solution is either to make `i` signed, or change the condition in the for loop like this: ``` for (i = domain - 1; i >= 0 && i < domain; --i) { ``` Or count from `domain` to `1` rather than from `domain - 1` to `0`: ``` for (i = domain; i >= 1; --i) { array[i - 1] = ...; // notice you have to subtract 1 from i inside the loop now } ```
There is only one correct method of looping backwards using an unsigned counter: ``` for( i = n; i-- > 0; ) { // Use i as normal here } ``` There's a trick here, for the last loop iteration you will have i = 1 at the top of the loop, i-- > 0 passes because 1 > 0, then i = 0 in the loop body. On the next iteration i-- > 0 fails because i == 0, so it doesn't matter that the postfix decrement rolled over the counter. Very non obvious I know.
Counting down in for-loops
[ "", "c++", "for-loop", "" ]
I'm a newbie to WMI and I need to implement [RegistryValueChangeEvent](http://msdn.microsoft.com/en-us/library/aa393042(VS.85).aspx) in a C# service. I need an event handler that gets triggered each time any one of a set of registry values is changed. I want behavior similar to the [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) class's [Changed](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.changed.aspx) event, but for registry values. If there's some other technique I could use to accomplish the same task, I'd appreciate that as well. My minimum requirement is that it be a better solution than what I have now: polling every 20 seconds and comparing the registry value with the last result. Please provide example code in your answer. If I can get an example for watching just one registry value, that would be fine. I need a solution in .Net 2.0 Thanks.
WMI can sometimes be interesting to work with...I think I understand your question, so take a look at the code snippet below and let me know if it's what you're looking for. ``` // --------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company=""> // // </copyright> // <summary> // Defines the WmiChangeEventTester type. // </summary> // --------------------------------------------------------------------------------------------------------------------- namespace WmiExample { using System; using System.Management; /// <summary> /// </summary> public class WmiChangeEventTester { /// <summary> /// Initializes a new instance of the <see cref="WmiChangeEventTester"/> class. /// </summary> public WmiChangeEventTester() { try { // Your query goes below; "KeyPath" is the key in the registry that you // want to monitor for changes. Make sure you escape the \ character. WqlEventQuery query = new WqlEventQuery( "SELECT * FROM RegistryValueChangeEvent WHERE " + "Hive = 'HKEY_LOCAL_MACHINE'" + @"AND KeyPath = 'SOFTWARE\\Microsoft\\.NETFramework' AND ValueName='InstallRoot'"); ManagementEventWatcher watcher = new ManagementEventWatcher(query); Console.WriteLine("Waiting for an event..."); // Set up the delegate that will handle the change event. watcher.EventArrived += new EventArrivedEventHandler(HandleEvent); // Start listening for events. watcher.Start(); // Do something while waiting for events. In your application, // this would just be continuing business as usual. System.Threading.Thread.Sleep(100000000); // Stop listening for events. watcher.Stop(); } catch (ManagementException managementException) { Console.WriteLine("An error occurred: " + managementException.Message); } } /// <summary> /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void HandleEvent(object sender, EventArrivedEventArgs e) { Console.WriteLine("Received an event."); // RegistryKeyChangeEvent occurs here; do something. } /// <summary> /// </summary> public static void Main() { // Just calls the class above to check for events... WmiChangeEventTester receiveEvent = new WmiChangeEventTester(); } } } ```
You really don't need WMI, as others have pointed out. I too have used [RegistryMonitor](http://www.codeproject.com/KB/system/registrymonitor.aspx) with no problems. If you need an example, there's already example code for the RegistryMonitor on the page itself. Did you scroll down to this bit on the code project: ``` public class MonitorSample { static void Main() { RegistryMonitor monitor = new RegistryMonitor(RegistryHive.CurrentUser, "Environment"); monitor.RegChanged += new EventHandler(OnRegChanged); monitor.Start(); while(true); monitor.Stop(); } private void OnRegChanged(object sender, EventArgs e) { Console.WriteLine("registry key has changed"); } } ```
Registry Watcher C#
[ "", "c#", ".net-2.0", "event-handling", "registry", "" ]
Is it possible to get the actual URL (as opposed to the `src` attribute value) of an image within the current DOM using jQuery or JavaScript? i.e. retrieve "example.com/foo.jpg" as opposed to "foo.jpg" (taking `<base>` elements into account) What about any other interesting properties such as the mime type, file size or, best of all, the actual binary data?
I wonder if jQuery is using `.getAttribute()` - using .src always seems to give the absolute URL: ``` <img src="foo.jpg" id="i"> <script> var img = document.getElementById('i'); alert(img.getAttribute('src')); // foo.jpg alert(img.src); // http://..../foo.jpg </script> ``` To get the rest of the information, could you use an AJAX request and look at the header & data sent?
***$(you IMG selector).attr('src');*** for instance, if we have an `<img src='bla-bla.jpg' id='my_img'>` then we'll do: ``` $('#my_img').attr('src'); ```
How to get an img url using jQuery?
[ "", "javascript", "jquery", "" ]
### Duplicate: > [Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?](https://stackoverflow.com/questions/721246/c-struct-ctor-issues) --- If in the constructor of an struct like ``` internal struct BimonthlyPair { internal int year; internal int month; internal int count; internal BimonthlyPair(int year, int month) { this.year = year; this.month = month; } } ``` I don't initialize a field (count in this case) I get an error: > Field 'count' must be fully assigned > before control is returned to the > caller But if I assign all fields, including count in this case, with something like ``` this.year = year; this.month = month; this.count = 0; ``` the error disappeared. I think this happens because C# doesn't initialize struct fields when somebody creates a new struct object. **But, why?** As far as I know, it initialize variables in some other contexts, so why an struct is a different scenery?
When you use the default constructor, there is an implicit guarantee that the entire value of the struct is cleared out. When you create your own constructor, you inherit that guarantee, but no code that enforces it, so it's up to you to make sure that the entire struct has a value.
I cannot answer why. But you can fix it by the use of : this(). ``` internal struct BimonthlyPair { internal int year; internal int month; internal int count; internal BimonthlyPair(int year, int month) : this() // Add this() { this.year = year; this.month = month; } } ```
Why do I have to assign all fields inside an struct's constructor?
[ "", "c#", "initialization", "" ]
I have a report that calculates multiple date differences (in business days, not DATEDIFF) for a variety of business reasons that are far too dull to get into. Basically the query (right now) looks something like ``` SELECT -- some kind of information DATEDIFF(dd, DateOne, DateTwo) AS d1_d2_diff, DATEDIFF(dd, DateOne, DateThree) AS d1_d3_diff, DATEDIFF(dd, DateTwo, DateThree) AS d2_d3_diff, DATEDIFF(dd, DateTwo, DateFour) AS d2_d4_diff FROM some_table; ``` I could change this calculation to use a scalar function, but I don't want the scalar function to be executed 4 times for every row in the result set. I have a Calendar table in the database: ``` CREATE TABLE Calendar ( Date DATETIME NOT NULL, IsWeekday BIT, IsHoliday BIT ); ``` Would a table-valued function and CROSS APPLY be a good choice here? If so, how would I go about writing such a thing? Or is a scalar function my best bet? **Important Note** All date values in our database have been stripped of time so it is safe to ignore any code that would reset days to midnight.
Realistically I think you want to go with a scalar function for this. At first glance you are going to need to do a few calculations. Then I thought about it more, and you can actually do this quite simply with a two step process. 1.) Roll your date values back to midnight of the respective days, that way you can easily figure it out. Due to extra information provided, this is not needed! 2.) Execute a query to find out how many week days, that are not holidays exist between the day values ``` SELECT ISNULL(COUNT(*), 0) FROM Calendar WHERE [DATE] > DateOne AND [DATE] < DateTwo AND IsWeekDay = 1 AND IsHoliday = 0 ``` Overall I think that the most efficient way is to just do this as a Scalar Function, I'm sure there might be other ways, but this way is straightforward, and as long as you have an index on the Calendar table it shouldn't be too bad performance wise. *note on cross apply* Doing a bit of looking, this could also be done via cross apply, but really in the end it does the same thing, so I think that the Scalar function is a better solution as it is easier to understand, and is easily repeatable.
The trick is using an inline table valued function, since they don't suffer the same performance penalty as a scalar function. They are equivalent to actually pasting the source code of the function right into the query. Here's how it works: ``` create function BusinessDayDiffs_fn ( @DateOne datetime , @DateTwo datetime ) returns table as return ( select count(*) as numBusinessDays from Calendar where date between @DateOne and @DateTwo and IsWeekday = 1 and IsHoliday = 0; ) GO select d1_d2_diff = d1_d2.numBusinessDays, d1_d3_diff = d1_d3.numBusinessDays, d2_d3_diff = d2_d3.numBusinessDays, d3_d4_diff = d3_d4.numBusinessDays from some_table s cross apply BusinessDayDiffs_fn( DateOne, DayTwo ) d1_d2 cross apply BusinessDayDiffs_fn( DateOne, DayThree) d1_d3 cross apply BusinessDayDiffs_fn( DayTwo, DayThree) d2_d3 cross apply BusinessDayDiffs_fn( DayTwo, DayFour ) d2_d4; ``` This should perform pretty well, as it's the same as taking the subquery out of the function, and pasting it right into the select clause of the main query. It'll be WAY faster than the scalar function.
Calculating the difference between two dates
[ "", "sql", "sql-server", "database", "" ]
I'm trying to create a single instance Qt application and I'm at the point this works, but now I want to focus the already started instance when a second is started. QWidget::find(g\_hWnd) should return the widget but it fails and crashes on w->show(); Any thoughts? ``` #pragma data_seg("Shared") HWND g_hWnd = NULL; #pragma data_seg() #pragma comment(linker,"/section:Shared,rws") int main(int argc, char *argv[]) { if (g_hWnd) { QWidget* w = QWidget::find(g_hWnd); w->show(); return 0; } else { QApplication a(argc, argv); mainWindow w; w.show(); g_hWnd = a.topLevelWidgets().at(0)->winId(); //or w.winId()? return a.exec(); } } ``` **edit: I now see Trolltech released the [QtSingleApplication](http://doc.trolltech.com/solutions/4/qtsingleapplication/qtsingleapplication.html) class under LGPL.**
You should use the [qtsingleapplication](http://doc.trolltech.com/solutions/4/qtsingleapplication/qtsingleapplication.html) API edit- It's a separate download [see here](http://www.qtsoftware.com/products/appdev/add-on-products/catalog/4/Utilities/qtsingleapplication/) for both LGPL and Commercial editions
``` #include <QtGui/QApplication> #include "mainwindow.h" #include <QMessageBox> #include <QSharedMemory> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; QSharedMemory shared("61BB200D-3579-453e-9044-"); if(shared.create(512,QSharedMemory::ReadWrite)==true) { QMessageBox msgBox; msgBox.setText("I am first."); msgBox.exec(); } else { QMessageBox msgBox; msgBox.setText("i am already running."); msgBox.exec(); exit(0); } //shared.AlreadyExists() w.show(); return a.exec(); } ```
Find QWidget of single instance Qt application
[ "", "c++", "windows", "qt", "" ]
I read Storm ORM's tutorial at <https://storm.canonical.com/Tutorial>, and I stumbled upon the following piece of code : ``` store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") ``` I'm not sure that the second argument of the **find** method will be evaluated to True/False. I think it will be interpreted as a lambda. If that is true, how can I achieve the same effect in my functions ?
since I'm a Java programmer... I'm guessing... it is operator overloading? Person.name == is an operator overloaded that instead do comparison... it produces a SQL query my 0.02$
`Person.name` has a overloaded `__eq__` method that returns not a boolean value but an object that stores both sides of the expression; that object can be examined by the `find()` method to obtain the attribute and value that it will use for filtering. I would describe this as a type of lazy evaluation pattern. In Storm, it is implemented with the [`Comparable` object](http://bazaar.launchpad.net/%7Estorm/storm/trunk/annotate/head%3A/storm/expr.py#L380).
what python feature is illustrated in this code?
[ "", "python", "language-features", "" ]
I am designing a J2SE application, and looking for a solution for monitoring and alerts. The requirements are: 1. Objects can report their status and issue alerts when they have problems. 2. Calling some pre-defined methods on specific objects (e.g. to dump their state). 3. Monitoring JVM health, especially memory usage. 4. Preferably access all of the above from a remote computer. What would be the best solution for that? Anything involving JMX?
Yes, you're describing pretty much JMX and MBeans.
If you use Java 6u10 or later, also see VisualVM (jvisualvm.exe in the JDK) which can do all kinds of interesting things, including (with a plugin) the same things jconsole can. It is really great for inspecting.
monitoring & alerts for a j2se application
[ "", "monitoring", "jmx", "alerts", "java", "" ]
I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this: ``` def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) ``` In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.
To expand a little on the other answers: In the line: ``` def wrapper(func, *args): ``` The \* next to `args` means "take the rest of the parameters given and put them in a list called `args`". In the line: ``` func(*args) ``` The \* next to `args` here means "take this list called args and 'unwrap' it into the rest of the parameters. So you can do the following: ``` def wrapper1(func, *args): # with star func(*args) def wrapper2(func, args): # without star func(*args) def func2(x, y, z): print x+y+z wrapper1(func2, 1, 2, 3) wrapper2(func2, [1, 2, 3]) ``` In `wrapper2`, the list is passed explicitly, but in both wrappers `args` contains the list `[1,2,3]`.
The simpliest way to wrap a function ``` func(*args, **kwargs) ``` ... is to manually write a wrapper that would call *func()* inside itself: ``` def wrapper(*args, **kwargs): # do something before try: return func(*a, **kwargs) finally: # do something after ``` In Python function is an object, so you can pass it's name as an argument of another function and return it. You can also write a wrapper generator for any function *anyFunc()*: ``` def wrapperGenerator(anyFunc, *args, **kwargs): def wrapper(*args, **kwargs): try: # do something before return anyFunc(*args, **kwargs) finally: #do something after return wrapper ``` Please also note that in Python when you don't know or don't want to name all the arguments of a function, you can refer to a tuple of arguments, which is denoted by its name, preceded by an asterisk in the parentheses after the function name: ``` *args ``` For example you can define a function that would take any number of arguments: ``` def testFunc(*args): print args # prints the tuple of arguments ``` Python provides for even further manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses after the function name this dictionary is denoted by two asterisks followed by the name of the dictionary: ``` **kwargs ``` A similar example that prints the keyword arguments dictionary: ``` def testFunc(**kwargs): print kwargs # prints the dictionary of keyword arguments ```
Call a function with argument list in python
[ "", "python", "function", "" ]
``` jsc.tools.road.correctType = function() { for(row = jsc.data.selection.startX - 1; row <= jsc.data.selection.endX + 1; row++) { for(col = jsc.data.selection.startY - 1; col <= jsc.data.selection.endY + 1; col++) { if(jsc.data.cells[row-1][col].type != "road" && jsc.data.cells[row+1][col].type != "road" && jsc.data.cells[row][col].type == "road") { jsc.ui.addClassToCell("horz", row, col); } else { jsc.ui.removeClassFromCell("horz", row, col); } if(jsc.data.cells[row][col-1].type != "road" && jsc.data.cells[row][col+1].type != "road" && jsc.data.cells[row][col].type == "road") { jsc.ui.addClassToCell("vert", row, col); } else { jsc.ui.removeClassFromCell("vert", row, col); } } } }; // Elsewhere jsc.ui.addClassToCell = function(class, x, y) { $("#" + x + "-" + y).addClass(class); }; jsc.ui.removeClassFromCell = function(class, x, y) { $("#" + x + "-" + y).removeClass(class); }; ``` The code above runs very slowly. I can't figure out why. It's using jQuery 1.3.2. Any way to optimize it a bit? EDIT: The code is part of a javascript game I am making as a personal project. It's basically a Simcity clone. This piece of code checks the neighbouring cells for each part of the road, and changes the class (and in turn the background image) to the correct one to make the road images line up right, e.g. horizontal, vertical and junction(no class) road images. EDIT 2: A few more details to provide some context. The jsc.data.cells is an 200 x 200 array. Each array element is an object with properties like so (default shown): {type: null, developed: false, powered: false, watered: false, hasTransport: false, wealth: 0, quality: 0} . It's counterpart is in the UI, which is basically a giant table. (200 x 200 again). Each cell has a number of CSS classes added to it throughout the program to change the background image (e.g. .road to change it to road, .com.developed to make it a developed commercial zone). The table cells each have an id of the form #x-y which is what jsc.ui.addClassToCell, and jsc.ui.removeClassFromCell edit. EDIT 3: Fixed the IDs starting with numbers. Trying out some of the optimizations now.
Normally you can significantly optimize loops like these; ``` for( var x = 0; x < someMethod(); x++ ) { //... do stuff } ``` By exchanging them out with something like this ``` var x = someMethod(); while( x-- ) { //...do stuff } ``` Though it becomes slightly different semantically, it normally works quite well as long as you're not dependent upon order in your looping (order is opposite) Even when you cannot change the order, you will also significantly improve your code by merely moving the someMethod call OUT of your actual loop, since in many JS implementations it will be called once for every iteration...
A short estimate using O() notation: ``` for(row) ... O(N) for(col) ... O(N) $().addClass/removeClass ... O(N^2) ``` the $() is even called twice within the nested for. so you end up with O(N^4) You can optimize this by caching the calculated classes in the as property of jsc.data.cells[row][col], e.g. ``` jsc.data.cells[row][col].horz = 1; // don't set class "horz" if not present jsc.data.cells[row][col].vert = 1; ``` and use the cached data when you create the cells inside the HTML table, rather than calling $() for each cell.
Why is this code so slow?
[ "", "javascript", "performance", "" ]
Let's say I have a sequential container, and a range (pair of iterators) within that container of elements that are currently 'active'. At some point, I calculate a new range of elements that should be active, which may overlap the previous range. I want to then iterate over the elements that were in the old active range but that are not in the new active range to 'deactivate' them (and similarly iterate over the elements that are in the new range but not the old range to 'activate' them). Is this possible? Does it become easier if I know that the start of the new active range will always be later in the container than the start of the old active range? For the purposes of the question, assume the container is a vector.
You can use two sets for the last active range and another for the current active range. Use the [`set_difference`](http://www.sgi.com/tech/stl/set_difference.html) algorithm to get the objects to be activated/deactivated.
What you need is a `range_difference` function. I though Boost.Range would provide something like this, but I didn't find anything in their doc (well, I didn't search very thoroughly...), so I rolled up my own. The following function returns a pair of range, containing the result of the difference between the range denoted by (first1,last1) and the one denoted by (first2,last2). A pre-condition is that first1 must be positioned before or at the same position as first2. ``` template <typename InputIterator> std::pair< std::pair<InputIterator, InputIterator>, std::pair<InputIterator, InputIterator> > range_difference(InputIterator first1, InputIterator last1, InputIterator first2, InputIterator last2) { typedef std::pair<InputIterator, InputIterator> Range; InputIterator it; // first1 must be <= first2 for (it = first1 ; it != last1 && it != first2 ; ++it); Range left_range = std::make_pair(first1, it); // Left range if (it == last1) return std::make_pair(left_range, std::make_pair(first2, first2)); // it == first2 while (it != last1 && it != last2) ++it; return std::make_pair(left_range, std::make_pair(it, last1)); // Right range } ``` The result of the difference can be composed of two parts, if range2 is completely included into range1. You end up with a left range and a right range: ``` |_____________________|__________________|________________________| first1 first2 last2 last1 ``` In this case, the function returns (first1, first2),(last2, last1). In this other configuration, ``` |_____________________| |________________________| first1 last1 first2 last2 ``` the function returns (first1, last1),(first2, first2). There are many other possible configurations. However, one important thing to know is that in the case where the right range is empty, it will be positioned at **max(first2, last1)**. You'll see how this is necessary in the example. Finally, if first1 and first2 are at the same position, the returned left range will be empty, i.d. (first1,first1). Now, how can we use this function to solve your problem? Well that's rather easy for the "deactivate" range, but a little trickier for the "activate" one: ``` typedef std::vector<Activable>::iterator Iterator; Iterator old_beg, old_end, new_beg, new_end; // Old and new ranges typedef std::pair<Iterator, Iterator> Range; typedef std::pair<Range, Range> SplitRange; SplitRange deactivate = range_difference(old_beg, old_end, new_beg, new_end); // Left range for (Iterator it = deactivate.first.first; it != deactivate.first.second; ++it) it->deactivate(); // Right range for (Iterator it = deactivate.second.first; it != deactivate.second.second; ++it) it->deactivate(); SplitRange activate = range_difference(new_beg, new_end, new_beg, deactivate.second.first); // Note the use of the previously returned right range -------^ for (Iterator it = activate.second.first; it != activate.second.second; ++it) it->activate(); ``` And there you go. Maybe this solution is a little overkill to your problem, but I think the `range_difference` function could be useful in many place.
Can I iterate over the elements that are in one range of iterators but not in another?
[ "", "c++", "stl", "iterator", "range", "" ]
What I'm trying to do is to create a table pager control using jQuery. It contains lots of links and spans. I've managed to do this with plain string concatenation, but I can't believe that jQuery can't make this more elegant. I can't use jTemplates here since the generation has quite a bit of procedural logic. Question: is there a way to create an array of HTML elements with jQuery and append them to some container? Thanks.
`$('First Element').add($('Second Element')).appendTo($('body'))`
String concatenation (or Array.join) is fine, as long as you make it pretty ;) ``` var structure = [ '<div id="something">', '<span>Hello!</span>', '</div>' ]; $(structure.join('')).appendTo(container); ```
How to create multiple HTML elements with jQuery?
[ "", "javascript", "jquery", "html", "" ]
So I'm a slightly seasoned php developer and have been 'doin the damn thing' since 2007; however, I am still relatively n00bish when it comes to securing my applications. In the way that I don't really know everything I know I could and should. I have picked up [Securing PHP Web Applications](https://rads.stackoverflow.com/amzn/click/com/0321534344) and am reading my way through it testing things out along the way. I have some questions for the general SO group that relate to database querying (mainly under mysql): When creating apps that put data to a database is mysql\_real\_escape\_string and general checking (is\_numeric etc) on input data enough? What about other types of attacks different from sql injection. Could someone explain stored procedures and prepared statements with a bit more info than - you make them and make calls to them. I would like to know how they work, what validation goes on behind the scenes. I work in a php4 bound environment and php5 is not an option for the time being. Has anyone else been in this position before, what did you do to secure your applications while all the cool kids are using that sweet new mysqli interface? What are some general good practices people have found to be advantageous, emphasis on creating an infrastructure capable of withstanding upgrades and possible migrations (like moving php4 to php5). Note: have had a search around couldn't find anything similar to this that hit the php-mysql security.
My recommendations: 1. ditch mysqli in favor of [PDO](http://www.php.net/pdo "see the PHP Data Objects manual") (with mysql driver) 2. use PDO paremeterized prepared statements You can then do something like: ``` $pdo_obj = new PDO( 'mysql:server=localhost; dbname=mydatabase', $dbusername, $dbpassword ); $sql = 'SELECT column FROM table WHERE condition=:condition'; $params = array( ':condition' => 1 ); $statement = $pdo_obj->prepare( $sql, array( PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY ) ); $statement->execute( $params ); $result = $statement->fetchAll( PDO::FETCH_ASSOC ); ``` **PROs:** 1. No more manual escaping since PDO does it all for you! 2. It's relatively easy to switch database backends all of a sudden. **CONs:** * i cannot think of any.
Javier's answer which has the owasp link is a good start. There are a few more things you can do more: 1. Regarding SQL injection attacks, you can write a function that will remove common SQL statements from the input like " DROP " or "DELETE \* WHERE", like this: \*$sqlarray = array( " DROP ","or 1=1","union select","SELECT \* FROM","select host","create table","FROM users","users WHERE");\* Then write the function that will check your input against this array. Make sure any of the stuff inside the $sqlarray won't be common input from your users. (Don't forget to use strtolower on this, thanks lou). 2. I'm not sure if memcache works with PHP 4 but you can put in place some spam protection with memcache by only allowing a certain remote IP access to the process.php page X amount of times in Y time period. 3. Privileges is important. If you only need insert privileges (say, order processing), then you should log into the database on the order process page with a user that only has insert and maybe select privileges. This means that even if a SQL injection got through, they could only perform INSERT / SELECT queries and not delete or restructuring. 4. Put important php processing files in a directory such as /include. Then disallow all IPs access to that /include directory. 5. Put a salted MD5 with the user's agent + remoteip + your salt in the user's session, and make it verify on every page load that the correct MD5 is in their cookie. 6. Disallow certain headers (<http://www.owasp.org/index.php/Testing_for_HTTP_Methods_and_XST>) . Disallow PUT(If you dont need file uploads)/TRACE/CONNECT/DELETE headers.
PHP/SQL Database querying good practice and security
[ "", "php", "mysql", "security", "sql-injection", "" ]
Suppose I have virtual function foo() in class B, and I need slightly different behavior in one of B's derived classes, class D. Is it OK to create an overriding function D::foo(), and call B::foo() from there, after the special case treatment? Like this: ``` void D::foo() { if (/*something*/) // do something else B::foo(); } ``` I am not asking whether that would work, I know it will. I want to know, whether it is right in terms of a good OOD.
This is perfectly good. In fact, the canonical way of performing some operations is calling the base class method, then do whatever (or the other way around). I am thinking of `operator=` here. Constructors usually work that way, too, even if this is a bit disguised in the initialization list.
Yes, its totally ok as long as you are not violating the Liskov Substitution Principle.
Calling overridden function from the overriding function
[ "", "c++", "inheritance", "oop", "virtual", "overriding", "" ]
Imagine I have a CDialog which creates controls dynamically when the user clicks a button. It could be like this: ``` // We don't know which is the first id for the new buttons until runtime (!) MyDialog::MyDialog(/*whatever parameters needed*/, first_id) : next_id_(first_id) { /*...*/ } BOOL MyDialog::OnSomeButtonClicked() { CButton* new_button = new CButton; new_button->Create("Caption", WS_CHILD | WS_VISIBLE, this->new_button_rect_, this, this->next_id_++); } ``` Then my question would be: How could I handle messages from this button? Is it possible to use the MFC message map facility? The solution should work in both vs6 and vs2005. Thank you!
These are the solutions I've found so far in order of relevance: 1. Use `ON_COMMAND_RANGE` if you can define the range of the control IDs you want to handle. 2. Overload `CWnd::PreTranslateMessage()` and do whatever stuff you want with the messages received. NOTE: When dealing with buttons, take into account that the BN\_CLICKED event is NOT sent to PreTranslateMessage but directly sent to the window procedure. 3. Overload `CWnd::WindowProc()` and do whatever stuff you want with the messages received. NOTE that when dealing with buttons this is the ONLY WAY I've found to handle the BN\_CLICKED event. Interesting links: * [Please help with PreTranslateMessage and user defined messages handling.](http://www.codeguru.com/forum/archive/index.php/t-280028.html) * [TN006: Message Maps](http://msdn.microsoft.com/en-us/library/0812b0wa(VS.80).aspx) I hope this helps... thank you all for your contributions.
Eventhough you dont know the exact values of the id, if you know the possible range of IDs then the following macro can be used. ``` BEGIN_MESSAGE_MAP(MyDialog, CDialog) ... ... ON_COMMAND_RANGE(1000, 5000, OnButtonDynamic) END_MESSAGE_MAP() void MyDialog::OnButtonDynamic(UINT nID) { } ``` This will work for ids in the range 1000 - 5000.
How to handle messages from dynamically created controls in an MFC app?
[ "", "c++", "visual-c++", "mfc", "event-handling", "" ]
Is there a way to add an Attribute on the Controller level but not on a specific action. For example say if i had 10 Actions in my Controller and just 1 of those Actions does not require a specific attribute I created. ``` [MyAttribute] public class MyController : Controller { public ActionResult Action1() {} public ActionResult Action2() {} [Remove_MyAttribute] public ActionResult Action3() {} } ``` I could potentially move this Action into another controller (but dont like that) or I could apply the MyAttribute to all actions except from Action3 but just thought if there is an easier way?
Johannes gave the correct solution and here is how I coded it... hope it helps other people. ``` [MyFilter("MyAction")] public class HomeController : Controller { public ActionResult Action1... public ActionResult Action2... public ActionResult MyAction... } public class CompressFilter : ActionFilterAttribute { private IList _ExcludeActions = null; public CompressFilter() { _ExcludeActions = new List(); } public CompressFilter(string excludeActions) { _ExcludeActions = new List(excludeActions.Split(',')); } public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpRequestBase request = filterContext.HttpContext.Request; string currentActionName = (string)filterContext.RouteData.Values["action"]; if (_ExcludeActions.Contains(currentActionName)) return; ... } ```
I know my answer is a little late (almost four years) to the game, but I came across this question and wanted to share a solution I devised that allows me to do pretty much what the original question wanted to do, in case it helps anyone else in the future. The solution involves a little gem called `AttributeUsage`, which allows us to specify an attribute on the controller (and even any base controllers!) and then override (ignore/remove) on individual actions or sub-controllers as needed. They will "cascade" down to where only the most granular attribute actually fires: i.e., they go from least-specific (base controllers), to more-specific (derived controllers), to most-specific (action methods). Here's how: ``` [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, Inherited=true, AllowMultiple=false)] public class MyCustomFilterAttribute : ActionFilterAttribute { private MyCustomFilterMode _Mode = MyCustomFilterMode.Respect; // this is the default, so don't always have to specify public MyCustomFilterAttribute() { } public MyCustomFilterAttribute(MyCustomFilterMode mode) { _Mode = mode; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (_Mode == MyCustomFilterMode.Ignore) { return; } // Otherwise, respect the attribute and work your magic here! // // // } } public enum MyCustomFilterMode { Ignore = 0, Respect = 1 } ``` (I heard you like attributes, so I put some attributes on the attribute! That's really what makes the magic work here at the very top: Allowing them to inherit/cascade, but only allowing one of them to execute.) Here's how it is used now: ``` [MyCustomFilter] public class MyBaseController : Controller { // I am the application's base controller with the filter, // so any derived controllers will ALSO get the filter (unless they override/Ignore) } public class HomeController : MyBaseController { // Since I derive from MyBaseController, // all of my action methods will also get the filter, // unless they specify otherwise! public ActionResult FilteredAction1... public ActionResult FilteredAction2... [MyCustomFilter(Ignore)] public ActionResult MyIgnoredAction... // I am ignoring the filter! } [MyCustomFilter(Ignore)] public class SomeSpecialCaseController : MyBaseController { // Even though I also derive from MyBaseController, I can choose // to "opt out" and indicate for everything to be ignored public ActionResult IgnoredAction1... public ActionResult IgnoredAction2... // Whoops! I guess I do need the filter on just one little method here: [MyCustomFilter] public ActionResult FilteredAction1... } ``` I hope this compiles, I yanked it from some similar code and did a little search-and-replace on it so it may not be perfect.
MVC Attributes on Controllers and Actions
[ "", "c#", "asp.net-mvc", "" ]
I'm nedding to implement excel formula autofill in C#. Let's suppose this formula is located at B100: ``` =SUM($B$99:B99) ``` I want to make this formula different at C100: ``` =SUM($B$99:C99) ``` This formula is only an example. Some real examples are: ``` =(SUM($B${0}:B{0})/SUM({1}!$B${0}:{1}!B{0}) -1) =SUM(B{0}:B{1}) =B{0} + B{1} =C{0}+ B{1} =$B${0}+ AC{1} ``` (consider {0} and {1} are, in fact, numbers) **What I need to do**, generically, is to pick these column names and "increment" them. Column names surrounded by $ in formulas should not be updated. How to identify these fields with regex?
Here's a regex solution that solely deals with formulas. I'll leave the Excel stuff to you. Provided you have a collection of strings representing your formulas, you can run them through this to increment your column names. Some comments: * \*\*Test this thoroughly!\*\* Perhaps do a sheet manually and compare your efforts with the generated results. * This shouldn't accidentally alter function names that fit the cell naming pattern. If you know your formulas have Excel function names that include numbers, keep an eye out for them and - again - \*\*verify results\*\*. * The regex does not verify what you're feeding it is a formula - I take it you're only using formulas. In other words, I didn't make it check that the string begins with an "=" sign. If you plan to feed non-formulas through this for other cell values, then add a check where IsMatch is used in the if branch using formula.StartsWith("="). To understand what I'm referring to, add an additional test string to my sample, such as "Check out T4 generation" - if no StartsWith("=") check is made, that will match and T4 will become U4. The regex pattern was actually the easy part. It will just match any letter-number sequence, and ignores $A$1 and $A1 types of cells. The tricky part was the logic to increment the column. I've added comments to clarify that bit so grab some coffee and read it over :) I'm sure this could be enhanced but this is what I had time for. ``` using System.Text.RegularExpressions; static void Main(string[] args) { string[] formulas = { "Z1", "ZZ1", "AZ1", "AZB1", "BZZ2", "=SUM($B$99:B99)","=SUM($F99:F99)", "=(SUM($B$0:B0)/SUM(1!$B$11:22!B33) -1)", "=SUM(X80:Z1)", "=A0 + B1 - C2 + Z5", "=C0+ B1", "=$B$0+ AC1", "=AA12-ZZ34 + AZ1 - BZ2 - BX3 + BZX4", "=SUMX2MY2(A2:A8,B2:B8)", // ensure function SUMX2MY2 isn't mistakenly incremented "=$B$40 + 50 - 20" // no match //,"Check out T4 generation!" // not a formula but it'll still increment T4, use formula.StartsWith("=") }; // use this if you don't want to include regex comments //Regex rxCell = new Regex(@"(?<![$])\b(?<col>[A-Z]+)(?<row>\d+)\b"); // regex comments in this style requires RegexOptions.IgnorePatternWhitespace string rxCellPattern = @"(?<![$]) # match if prefix is absent: $ symbol (prevents matching $A1 type of cells) # (if all you have is $A$1 type of references, and not $A1 types, this negative look-behind isn't needed) \b # word boundary (prevents matching Excel functions with a similar pattern to a cell) (?<col>[A-Z]+) # named capture group, match uppercase letter at least once # (change to [A-Za-z] if you have lowercase cells) (?<row>\d+) # named capture group, match a number at least once \b # word boundary "; Regex rxCell = new Regex(rxCellPattern, RegexOptions.IgnorePatternWhitespace); foreach (string formula in formulas) { if (rxCell.IsMatch(formula)) { Console.WriteLine("Formula: {0}", formula); foreach (Match cell in rxCell.Matches(formula)) Console.WriteLine("Cell: {0}, Col: {1}", cell.Value, cell.Groups["col"].Value); // the magic happens here string newFormula = rxCell.Replace(formula, IncrementColumn); Console.WriteLine("Modified: {0}", newFormula); } else { Console.WriteLine("Not a match: {0}", formula); } Console.WriteLine(); } } private static string IncrementColumn(Match m) { string col = m.Groups["col"].Value; char c; // single character column name (ie. A1) if (col.Length == 1) { c = Convert.ToChar(col); if (c == 'Z') { // roll over col = "AA"; } else { // advance to next char c = (char)((int)c + 1); col = c.ToString(); } } else { // multi-character column name (ie. AB1) // in this case work backwards to do some column name "arithmetic" c = Convert.ToChar(col.Substring(col.Length - 1, 1)); // grab last letter of col if (c == 'Z') { string temp = ""; for (int i = col.Length - 1; i >= 0; i--) { // roll over should occur if (col[i] == 'Z') { // prepend AA if current char is not the last char in column and its next neighbor was also a Z // ie. column BZZ: if current char is 1st Z, it's neighbor Z (2nd Z) just got incremented, so 1st Z becomes AA if (i != col.Length - 1 && col[i + 1] == 'Z') { temp = "AA" + temp; } else { // last char in column is Z, becomes A (this will happen first, before the above if branch ever happens) temp = "A" + temp; } } else { temp = ((char)((int)col[i] + 1)).ToString() + temp; } } col = temp; } else { // advance char c = (char)((int)c + 1); // chop off final char in original column, append advanced char col = col.Remove(col.Length - 1) + c.ToString(); } } // updated column and original row (from regex match) return col + m.Groups["row"].Value; } ``` --- The results should look like this (I removed the cell breakdown for brevity): ``` Formula: Z1 Modified: AA1 Formula: ZZ1 Modified: AAA1 Formula: AZ1 Modified: BA1 Formula: AZB1 Modified: AZC1 Formula: BZZ2 Modified: CAAA2 Formula: =SUM($B$99:B99) Modified: =SUM($B$99:C99) Formula: =SUM($F99:F99) Modified: =SUM($F99:G99) Formula: =(SUM($B$0:B0)/SUM(1!$B$11:22!B33) -1) Modified: =(SUM($B$0:C0)/SUM(1!$B$11:22!C33) -1) Formula: =SUM(X80:Z1) Modified: =SUM(Y80:AA1) Formula: =A0 + B1 - C2 + Z5 Modified: =B0 + C1 - D2 + AA5 Formula: =C0+ B1 Modified: =D0+ C1 Formula: =$B$0+ AC1 Modified: =$B$0+ AD1 Formula: =AA12-ZZ34 + AZ1 - BZ2 - BX3 + BZX4 Modified: =AB12-AAA34 + BA1 - CA2 - BY3 + BZY4 Formula: =SUMX2MY2(A2:A8,B2:B8) Modified: =SUMX2MY2(B2:B8,C2:C8) Not a match: =$B$40 + 50 - 20 ```
+! for automating Excel and doing the work there. However, if you're bent on doing it in C#, you might start here [<http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html>](http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html). Maybe once you digest all the rules for tokenizing a formula, you'll be able to create a RE.
Which regular expression is able to select excel column names in a formula in C#?
[ "", "c#", "regex", "excel", "" ]
Suppose I have 2 enumerations that I know have the same number of elements and each element "corresponds" with the identically placed element in the other enumeration. Is there a way to process these 2 enumerations simultaneously so that I have access to the corresponding elements of each enumeration at the same time? Using a theoretical LINQ syntax, what I have in mind is something like: ``` from x in seq1, y in seq2 select new {x.foo, y.bar} ```
Since Neil Williams deleted his answer, I'll go ahead and post a link to an [implementation by Jon Skeet](https://stackoverflow.com/questions/496704/how-to-iterate-over-two-arrays-at-once/496752#496752). To paraphrase the relevant portion: ``` public static IEnumerable<KeyValuePair<TFirst,TSecond>> Zip<TFirst,TSecond> (this IEnumerable<TFirst> source, IEnumerable<TSecond> secondSequence) { using (IEnumerator<TSecond> secondIter = secondSequence.GetEnumerator()) { foreach (TFirst first in source) { if (!secondIter.MoveNext()) { throw new ArgumentException ("First sequence longer than second"); } yield return new KeyValuePair<TFirst, TSecond>(first, secondIter.Current); } if (secondIter.MoveNext()) { throw new ArgumentException ("Second sequence longer than first"); } } } ``` Note that the `KeyValuePair<>` is my addition, and that I'm normally not a fan of using it this way. Instead, I would define a generic `Pair` or `Tuple` type. However, they are not included in the current version of the framework and I didn't want to clutter this sample with extra class definitions.
The function you are looking for is called "Zip". It works like a zipper. It'll be in .NET 4.0 iirc. In the meantime you may want to look at the [BclExtras](http://code.msdn.microsoft.com/BclExtras) library. (Man, I'm a real advocate for this lib, lol). ``` IEnumerable<Tuple<TSeq1, TSeq2>> tuples = from t in seq1.Zip(seq2) select t; ``` If you just want to get done, you'll have to get both sequences enumerator and run them "in parallel" using a traditional loop.
how to process "parallel" sequences in Linq?
[ "", "c#", "linq", "" ]
I'm using sqlite3 in python 2.5. I've created a table that looks like this: ``` create table votes ( bill text, senator_id text, vote text) ``` I'm accessing it with something like this: ``` v_cur.execute("select * from votes") row = v_cur.fetchone() bill = row[0] senator_id = row[1] vote = row[2] ``` What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example: ``` bill = row['bill'] senator_id = row['senator_id'] vote = row['vote'] ``` I know you can do this with MySQL, but does anyone know how to do it with SQLite? Thanks!!!
The way I've done this in the past: ``` def dict_factory(cursor, row): d = {} for idx,col in enumerate(cursor.description): d[col[0]] = row[idx] return d ``` Then you set it up in your connection: ``` from pysqlite2 import dbapi2 as sqlite conn = sqlite.connect(...) conn.row_factory = dict_factory ``` This works under pysqlite-2.4.1 and python 2.5.4.
There is actually an option for this in sqlite3. Change the `row_factory` member of the connection object to `sqlite3.Row`: ``` conn = sqlite3.connect('db', row_factory=sqlite3.Row) ``` or ``` conn.row_factory = sqlite3.Row ``` This will allow you to access row elements by name--dictionary-style--or by index. This is much more efficient than creating your own work-around.
Sqlite and Python -- return a dictionary using fetchone()?
[ "", "python", "database", "sqlite", "dictionary", "" ]
I have the two entity classes, User and MyCharacter. User has a list of MyCharacters and each MyCharacter has a reference back to the User (owner). What I'd like to accomplish is, that I use the same join table for both relations, meaning, that the owner relation found in MyCharacter would automatically use the same join table as from User=>MyCharacter. This means that the getOwner() method in MyCharacter should work without me having to explicitly at some point call setOwner(user). To clear this a bit more, here's my unit test which currently fails (last assert fails) ``` @Test public void testTwoWayRelation() { User user = new User(); MyCharacter character = new MyCharacter(); List<MyCharacter> chars = new ArrayList<MyCharacter>(); chars.add(character); user.setCharacters(chars); facade.store(user); assertNotNull(character.getId()); character = facade.find(MyCharacter.class, character.getId()); assertNotNull(character.getOwner()); } ``` My entity classes are listed below. ``` @Entity @Table(name = "myuser") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) protected Long id; @OneToMany(cascade = { CascadeType.PERSIST }) protected List<MyCharacter> characters; public User() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<MyCharacter> getCharacters() { return characters; } public void setCharacters(List<MyCharacter> characters) { this.characters = characters; } } @Entity public class MyCharacter{ @Id @GeneratedValue(strategy = GenerationType.AUTO) protected Long id; @ManyToOne @JoinTable(name = "myuser_mycharacter", joinColumns = @JoinColumn(name = "characters_id"), inverseJoinColumns = { @JoinColumn(name = "user_id") }) protected User owner; public MyCharacter() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } } ```
That's how we join two entities with jpa in our project: ``` @Entity @Table(name = "Period") public class Period implements Serializable { private List<Delay> delays = new ArrayList<Delay>(); @OneToMany(mappedBy="period") //name of the field in joined entity public List<Delay> getDelays() { return delays; } } @Entity @Table(name = "Delay") public class Delay implements Serializable { private Period period; @ManyToOne @JoinColumn(name = "PERIODID") public Period getPeriod() { return period; } } ```
i'm not sure i understand your problem correctly, but you could try to set mappedBy on MyCharacter.owner: ``` @ManyToOne(mappedBy="characters") ```
Two-way relation in JPA
[ "", "java", "jpa", "" ]
I made small program to divide large pictures and take part of them. When i import image that made by "Microsoft Paint" this image is "96 dpi" so my program doing well. But I've pictures that made by Photoshop its resolution is 71.6 dpi when i crop these pictures the new cropped picture take 96 dpi resolution so the size is deference between them. ## **I want to crop the picture with keeping its resolution as it.** . thank you very much
`Bitmap.clone` lets you create a cropped copy of an image, which you can then save. It shouldn't change resolution or anything (the image will look bigger if you open it in a program that zooms in more when images are smaller). It cannot be used to expand the canvas (you'll get out of memory errors). So, just grab an `Image` from file, cast to `Bitmap`, (`system.drawing` namespace) and clone it to be smaller, then save it. Example: ``` using System.Drawing; //... Bitmap x = (Bitmap) Image.FromFile(@"c:\tmp\food.png"); Image x2 = x.Clone(new Rectangle(25, 25, 50, 50), x.PixelFormat); x2.Save(@"c:\tmp\food2.png"); ```
DPI (dots per inch) is just a relationship between pixel size and the size on a medium. If you have an image which is 1024 x 768 pixels, it is 1024 x 768. There is no inherent DPI attached to a bitmap/binary file. If you want to print that image on a printer which prints at 300 dpi, then you can calculate the size on the paper, for example.
How can I crop image without changing its resolution in C#.Net?
[ "", "c#", ".net", "image", "resolution", "crop", "" ]
Im very new in php and try to use cookie but it is not woking in my site, can anyone guide me please , what is going wrong in my code: ``` <?php session_start(); ?> <script> function Redirect(url) { location.href = url; } </script> <?php define('_VALID_ACCESS', true); include_once "includes/connect.php"; include_once "includes/login.php"; if(empty($_POST['loginname']) || empty($_POST['password'])) { $msg = "User or password is empty"; } else { if(login($_POST['loginname'], $_POST['password']) == true) { $usern = $_POST['loginname']; session_register('loginname'); $loginname = $usern; sleep(1); if(activestatus($_POST['loginname'], $_POST['password']) == true) { $usern = $_POST['loginname']; session_register('loginname'); $loginname = $usern; sleep(1); $hour = time() + 3600; setcookie("ID_my_site", $_POST['loginname'], $hour); setcookie("Key_my_site", $_POST['password'], $hour); $test = $_COOKIE["ID_my_site"]; $msg = "<script> Redirect ('home.html?testname=".$test."')</script>"; //header("Location: home.html"); } else { $msg = "<script> Redirect ('valid.php?testname=".$usern."')</script>"; } } else { $msg = "<font color=red>User or Password is wrong</font>"; } } echo '<div id="divTarget">' . $msg . '</div>'; ?> <link rel="stylesheet" href="css/blueprint/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="css/blueprint/print.css" type="text/css" media="print"> <link rel="stylesheet" href="css/blueprint/ie.css" type="text/css" media="screen, projection"> <body> <div class="container" id="login_container"> <form id="login" action="action.php" method="post" name="loginform" > <fieldset id="login_screen" style="width:350px"> <label id="login_label" for="login">User Login </label> <br><br> <label for="login">Email Address</label> <input type="text" name="loginname" id="loginname" value="email@coolmates.com"> <p id="space"><label for="password">Password</label> <input type="password" id="password" name="password" value="********" ></p> <input type="checkbox">Keep me signed in until i signout <p id="test"><input type="submit" value="Submit"></p> <a href="forgetpassword.html">Forgot your password</a>&nbsp;&nbsp;|<span id="free">Not a member?</span><a href="regForm.html">Sign up</a><blink><span id="free">Free</span></blink> </p> </fieldset> </form> </div> </body> ```
Turn on display\_errors and set your error\_reporting to E\_ALL and you should see an error message about 'headers already sent' - you have to call setcookie() BEFORE ANY HTML IS SENT. From php.net/setcookie: > setcookie() defines a cookie to be > sent along with the rest of the HTTP > headers. Like other headers, cookies > must be sent before any output from > your script (this is a protocol > restriction). This requires that you > place calls to this function prior to > any output, including and > tags as well as any whitespace. In the code block that you posted this bit: ``` <script> function Redirect(url) { location.href = url; } </script> ``` Is being output directly to the browser well before you ever attempt to set the cookies. Your two possibilities would be to use output buffering so that you output everything at the very end or to switch to a method where all of your processing code is executed first in one script and there you set $\_SESSION and cookie values and then include a second script at the tail end of the first that contains the code to be output to the browser.
Try this (specifying the root of your site) : ``` setcookie("ID_my_site", $_POST['loginname'], $hour,'/'); ``` or try this (adding quotes to your loginname) : ``` setcookie("ID_my_site", "$_POST['loginname']", $hour,'/'); ```
Cookies are Not Being Set Properly in PHP Script
[ "", "php", "cookies", "output-buffering", "" ]
I'm still not clear on the purpose of annotations in Java. Initially I thought they just served as documentation. But looking at this documentation from [Google App Engine Datastore](http://code.google.com/appengine/docs/java/datastore/overview.html), I'm not so sure. **@PersistenceCapable(identityType = IdentityType.APPLICATION)** looks more like a method signature. What's the purpose of this type of annotation? What does it do? ``` import java.util.Date; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; @PersistenceCapable(identityType = IdentityType.APPLICATION) public class Employee { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String firstName; @Persistent private String lastName; @Persistent private Date hireDate; public Employee(String firstName, String lastName, Date hireDate) { this.firstName = firstName; this.lastName = lastName; this.hireDate = hireDate; } // Accessors for the fields. JDO doesn't use these, but your application does. public Long getId() { return id; } public String getFirstName() { return firstName; } // ... other accessors... } ```
They're source-level metadata. They're a way of adding information to the code that's not code, and that is easily machine-processed. In your example, they're used to configure object-relational mapping for that entity type. It's saying that for example the id field should be the primary key for that object, and that firstName, lastName, and hireDate should be stored in the database. (To tell those fields apart from some transient object state.) The GAE support for JDO needs to know what objects you'll try to store in the database. It does this by looking through the classes in your code, looking for the ones that are annotated with @PersistenceCapable. Commonly, they're used to replace where you'd use external configuration files before; the Java standard library has tools to read the annotations in your code, which makes them much easier to process than rolling your own configuration file plumbing, and gets you IDE support for free.
Annotations can be processed with the [Annotation Processing Tool APIs](http://java.sun.com/javase/6/docs/technotes/guides/apt/index.html) to auto-generate boilerplate code.
What function do these Java annotations serve?
[ "", "java", "annotations", "" ]
When you run a program through the command line, you can use `java -Xms -Xmx` to specify the heap sizes. If the program is going to be run by double clicking a .jar file, is there a way to use more heap than the standard?
No. That's why I often make a .bat or .sh file with those parameters and direct users to run it instead of the .jar. Unfortunately, it's a little ugly to have to pop up a command-prompt window, but that can't be helped. As a side benefit, if your application freezes, you can direct users to put `pause` into the batch file (or do it yourself), and then you can see any stack trace that occurs. **Edit:** You could also use an executable wrapper such as [JSmooth](http://jsmooth.sourceforge.net/) or [Launch4J](http://launch4j.sourceforge.net/) instead of a batch file. You would lose some cross-platform compatibility, though.
Instead of double-clicking the .jar file directly, you can use a batch file that runs `java -jar -Xms -Xmx your_file.jar`. From the user's point of view it's the same, but it gives you more control over the command that's actually run.
Allocate more heap space to a Java jar
[ "", "java", "memory", "jar", "heap-memory", "" ]
I have a Java application which uses a third-party COM component through a Java-COM bridge. This COM component opens a socket connection to a remote host. This host can take some time to respond, and I suspicious that I'm getting a timeout. I'm not sure because as I said, it's a closed-source third-party component. The API of this component does not expose the socket connection to me, so I have no way to configure the timeout. So I wonder if there is any way to tweak the system default timeout. I'm using a Windows Server 2008 x64 Enterprise Edition.
Do you want to build your application so that it knows at runtime whether or not a timeout happened, or do you want to inspect the behavior of the closed-source COM component? If it's the latter, install Wireshark on your dev box and watch the connection. If it's the former, do you want to ensure that your Java call out to native land doesn't hang forever? If that's the case, look into the java.util.concurrent executor service stuff -- there's a way to call a method in another thread and wait a maximum of N seconds before returning control to your thread.
If you'd like to see the connection establish, and then perhaps drop from timeout, you can use TCPview: <http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx>
TCP socket timeout configuration
[ "", "java", "windows", "sockets", "timeout", "windows-server-2008", "" ]
I have a simple databasescheme: User, Account. User has 1-to-many relationship with Account. I have generated a ado.net entity data model, and I can create users and accounts, and even link them together. In the database the account.user\_id is correctly filled, so theoretically I should be able to acces User.Account.ToList() in C# through entity. However, When I try to acces User.Account.ToList() I get zero results. ``` User user = db.User.First(U => U.id == 1); List<Account> accounts = user.Account.ToList(); ##count = 0... ``` When I add the following code before the previous code it suddenly gives me the correct count 2. ``` Account account1 = db.Account.First(A => A.id == 1); Account account2 = db.Account.First(A => A.id == 2); User user = db.User.First(U => U.id == 1); List<Account> accounts = user.Account.ToList(); ##count = 2...?? ``` What am I missing here??
You should use the [ObjectQuery.Include](http://msdn.microsoft.com/en-us/library/bb738708.aspx) method for this. Your method works also but results in an additional query. In your example you would get ``` User user = db.User.Include("Account").First(u => u.id == 1); ``` You have to figure out whether the string `"Account"` is correct. Usually it should be prefixed with something like `MyEntities`. This depends on the namespace of your entities but with a little trial and error you should be able to figure this out.
Yes, that's a common problem when starting to use the Entity framework - neither parent nor child relationships are lazy loaded so you have to load them explicitly. If you are going to share the object context around between classes / methods you might want to make a check to see if the relationship is already loaded: e.g. ``` if(!user.Account.IsLoaded) user.Account.Load(); ``` You can make this easier with a simple extension method: ``` public static class EntityExtensions { public static void EnsureLoaded(this RelatedEnd relatedEnd) { if (!relatedEnd.IsLoaded) relatedEnd.Load(); } } ``` using this makes your load call shorter again: ``` user.Account.EnsureLoaded(); ``` And as it uses a RelatedEnd, which is common to parent and child relationships in the entity framework, you can use this for parent reference relationships too - e.g. ``` account.UserReference.EnsureLoaded(); ``` As rwwilden says, if you are always going to load the child objects with the parent in this case, you might want to use an Include to make the call more efficient and avoid an extra roundtrip to the database.
Ado.Net Entity : Object doesn't display linked members (foreign keys)
[ "", "c#", "entity-framework", "ado.net", "one-to-many", "" ]
I use SwingWorker in Java 6 to avoid running long-running code on the event dispatch thread. If the call to get() in my done() method returns an exception, what is an appropriate way of handling the exception? I'm particularly concerned about possible InterruptedExceptions. The JavaDoc example simply ignores the exception but I've learnt over the years that swallowing exceptions leads to hard-to-debug code. A sample usage is as follows: ``` new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { // do long-running calculation return result; } @Override protected void done() { try { setTextField(get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }.execute(); ```
It's an old post, but I want to do some clarification: SwingWorker.get throws InterruptedException, ExecutionException as checked exceptions. Plus it throws a very specific unchecked exception that is CancellationException. Of course it could potentially throw any unchecked exception, but CancellationException is not an "exceptional" and unexpected one. It is thrown when you try to call get method after that has been called cancel. ExecutedException is thrown when an Exception is thrown inside doInBackground. The original exception is wrapped inside an ExecutionException. When the get() method will be called, the ExecutionException will be thrown. The idea of take out the original exception and manage that is good. (As Emil H pointed out). CancellationException is unchecked and in my opinion should be checked. The only excuse for the API implementation not to have it as checked is that it has a status method isCancelled(). You can either: - test isCancelled() and if is true do NOT call get() since it will throw CancellationException - surround get() with try-catch and add the CancellationException, that since unchecked will not requested by compiler - the fact that CancellationException is not checked leave you free to forget all that stuff and get a nice surprise. - do anything because you won't cancel the worker InterruptedException. If you cancel a SwingThread with cancel(true) the first interruptable method call (for sure Thread.sleep, this.wait, maybe some IO methods) in doInBackground will throw InterruptException. But this exception is not wrapped in an ExecuteException. The doInBackground is left to terminate with interrupted exception. If it is catched and converted to some other exception, those will be ignored because by this moment cancel has already invoked SwingThread.done on the EDT, and if done has called get, it has get just the standard CancellationException. *Not an InterruptedException!* If you cancel with cancel(false) no InterruptException is raised inside doInBackground. The same if you cancel with cancel(true) but there are no interruptable method calls inside doInBackground. In these cases, the doInBackground will follow its natural loop. This loop should test the isCancelled method and exit gracefully. If the doInBackground doesn't do so, it will run forever. I've not tested for the presence of timeouts, but I not belive so. For me, it remains just a **gray area**. In which cases is InterruptedException thrown by get? I'd like to see some short code, since I couldn't produce a similar exception. :-) P.S. I've documented in another Question&Answer that the done and state change listener in case of cancellation are called before the doInBackground exits. Since this is true, this -that is not a bug- requires a special attention when designing doInBackground method. If you are intrested in this, see [SwingWorker: when exactly is called done method?](https://stackoverflow.com/questions/6204141/swingworker-when-exactly-is-called-done-method)
It depends very much on the type of errors that might result from the background job. If the job in doInBackground throws an exception, it will be propagated to the done method as a nested ExecutionException. The best practice in this case would be to handle the nested exception, rather than the ExecutionException itself. For example: If the worker thread throws an exception indicating that the database connection has been lost, you'd probably want to reconnect and restart the job. If the work to be done depends on some kind of resource that turns out to already be in use, it would be a good idea to offer the use a retry or cancel choice. If the exception thrown doesn't have any implications for the user, just log the error and continue. From what I can remember, I believe that the InterruptedException won't be an issue here since you make the get method call in the done method, since the InterruptedException will only be thrown if the get call is interrupted while waiting for the background job to finish. If an unexpected event like that were to occur you'd probably want to display an error message and exit the application.
How should I handle exceptions when using SwingWorker?
[ "", "java", "swing", "swingworker", "" ]
I have a number of indexes on some tables, they are all similar and I want to know if the Clustered Index is on the correct column. Here are the stats from the two most active indexes: ``` Nonclustered I3_Identity (bigint) rows: 193,781 pages: 3821 MB: 29.85 user seeks: 463,355 user_scans: 784 user_lookups: 0 updates: 256,516 Clustered Primary Key I3_RowId (varchar(80)) rows: 193,781 pages: 24,289 MB: 189.76 user_seeks: 2,473,413 user_scans: 958 user_lookups: 463,693 updates: 2,669,261 ``` As you can see, the PK is being seeked often, but all the seeks for the i3\_identity column are doing key lookups to this PK as well, so am I really benefiting from the index on I3\_Identity much at all? Should I change to using the I3\_Identity as the clustered? This could have a huge impact as this table structure is repeated about 10000 times where I work, so any help would be appreciated.
Frederik sums it up nicely, and that's really what Kimberly Tripp also preaches: the clustering key should be stable (never changes), ever increasing (IDENTITY INT), small and unique. In your scenario, I'd much rather put the clustering key on the BIGINT column rather than the VARCHAR(80) column. First of all, with the BIGINT column, it's reasonably easy to enforce uniqueness (if you don't enforce and guarantee uniqueness yourself, SQL Server will add a 4-byte "uniquefier" to each and every one of your rows) and it's MUCH smaller on average than a VARCHAR(80). Why is size so important? The clustering key will also be added to EACH and every one of your non-clustered indexes - so if you have a lot of rows and a lot of non-clustered indexes, having 40-80 byte vs. 8 byte can quickly make a HUGE difference. Also, another performance tip: in order to avoid the so-called bookmark lookups (from a value in your non-clustered index via the clustering key into the actual data leaf pages), SQL Server 2005 has introduced the notion of "included columns" in your non-clustered indexes. Those are extremely helpful, and often overlooked. If your queries often require the index fields plus just one or two other fields from the database, consider including those in order to achieve what is called "covering indexes". Again - see Kimberly Tripp's excellent article - she's the SQL Server Indexing Goddess! :-) and she can explain that stuff much better than I can... So to sum it up: put your clustering key on a small, stable, unique column - and you'll do just fine! Marc
quick 'n dirty: Put the clustered index on: * a column who's values (almost) never change * a column for which values on new records increase / decrease sequentially * a column where you perform range - searches
SQL Server Index Which should be clustered?
[ "", "sql", "sql-server", "sql-server-2005", "indexing", "" ]
> **Duplicate of:** [What's the best way to store class variables in PHP?](https://stackoverflow.com/questions/546403/whats-the-best-way-to-store-class-variables-in-php) For some time I've been having this discussion with a co-worker on how should you store attributes within a PHP class. So which one do you think it should be used. Something like this: ``` Class test{ public $attr1; public $attr2; .............. public function __construct(){ $this->attr1 = val; $this->attr1 = val; ................... } } ``` Versus: ``` Class test{ public $data; public function __construct(){ $this->data['attr1'] = val; $this->data['attr2'] = val; .......................... } } ``` This is important when you have objects with many attributes that have to be stored and retrieved within often. Also important when dealing with objects with many attributes, do you use getters and setters for each attribute or rather one method to set all and one method to get all ?
Version 1 is the more "classical" way of doing things. Your object is pretty much exactly as you say it is. I can't say which is strictly "better", but I can say which I find more convenient. I've used the second version (usually for database models in CodeIgniter, and particularly during early development) in combination with custom PHP5 getter and setter methods to allow you to overload the class dynamically. i.e. ``` <?php class foo{ private $data = array(); function __construct() { # code... } public function __get($member) { if (isset($this->data[$member])) { return $this->data[$member]; } } public function __set($member, $value) { // The ID of the dataset is read-only if ($member == "id") { return; } if (isset($this->data[$member])) { $this->data[$member] = $value; } } } $bar = new foo() $bar->propertyDoesntExist = "this is a test"; echo $bar->propertyDoesntExist; //outputs "this is a test" ?> ```
I'd use second version **if and only if** the data comes as a whole from external source (e.g. BD query). In that case of course it'll be recommendable to have generic [`__get()`/`__set()`](http://www.php.net/manual/en/class.iteratoraggregate.php) to access `$this->data`. You might also consider implementing [IteratorAggregate interface](http://www.php.net/manual/en/class.iteratoraggregate.php) returning `new ArrayIterator($this->data)`.
What's the best way to store PHP class properties?
[ "", "php", "design-patterns", "oop", "class", "" ]
I've started writing a few applications in PHP, and I'm becoming more familiar with the language. Someone told me about CakePHP, and CodeIgniter. I wanted to get a better understanding of how these could help me, and whether it's worthwhile spending the time to learn a framework?
What are the benefits of using MVC PHP frameworks ? Well there are many benefits of using PHP frameworks, let’s see some of the main benefits of using them. 1. These PHP frameworks follow some design pattern, so when you use a framework you have to follow their coding convention, which makes your code clean and extensible for future purposes. 2. The Popular PHP frameworks like CakePHP, CodeIgniter, Zend Framework, Symfony follow Model View Controller (MVC) design pattern which separates business logic from user interface, also making the code cleaner and extensible. 3. As everybody can guess, these frameworks contain a lot of libraries to make your job easier. For example: to validate a form you don't have to write as much code as you have to do in normal coding scenario (without using a framework), just a few lines of code calling the library is usually enough for it. 4. While working on a large project in a team, an MVC PHP framework will be a great tool for development as you can assign a developer to develop one part of a module for a developer and integration will be quite easy of these developed modules at final level. 5. These MVC frameworks really help you to develop the project rapidly, if you know a framework well then you'll never worry about the project deadline. 6. Most of these MVC frameworks use clear url approach making your web project SEO friendly. check [article](http://roshanbh.com.np/2008/11/php-framworks-why-when-and-which.html)
My philosophy is that you should only use something when it solves a need that you currently have. There's a real tendency, particularly in this realm, to simply use a framework for the sake of using one or because you feel like you should be using something. I discourage such practices. Also frameworks I think have the most value when you've done things the hard way so you have a good understanding of what problems you have and how the framework can help you **in that situation**. Framework choice does depend on the situation. That all being said, the MVC pattern with Web applications is useful so it certainly wouldn't hurt you to learn at least one. I'd stick to a fairly minimalist framework however. CodeIgniter springs to mind here. Lastly, the other danger with frameworks is that they can be so invasive that you're no longer doing PHP, you're doing CakePHP, Symfony or whatever. That's not necessarily a problem but the danger in it being so invasive is you don't get a good grounding in PHP and if you ever want to change it'll simply be too hard that you'll never be able to do it.
To Use a PHP Framework or Not?
[ "", "php", "cakephp", "codeigniter", "" ]
I use a code generator (CodeSmith with .NetTiers template) to generate all the DAL code. I write unit tests for my code (business layer), and these tests are becoming pretty slow to run. The problem is that for each test, I reset the database to have a clean state. Also, as I do a lot of tests, it seems that the latency of the database operations sum up to a pretty bit delay. All DB operations are performed through a `DataRepository` class that is generated by .NetTiers. Do you know if there is a way to generate (or code myself) a mock-DataRepository that would use in-memory storage instead of using the database ? This way, I would be able to use this mock repository in my unit tests, speeding them a lot, without actually changing anything to my current code !
Take a look at Dependency injection (DI) and Inversion of Control containers (IOC). Essentially, you will create an interface that that a new mock DB object can implement, and then the DI framework will inject your mock DB when running tests, and the real DB when running you app. There are numerous free and open source libraries that you could use to help you out. Since you are in C#, one of the new and up and coming DI libraries is [Ninject](http://ninject.org/). There are many others too. Check out this [Wikipedia article](http://en.wikipedia.org/wiki/Dependency_injection#Existing_frameworks) for others and a high level description.
From the description of the issue, I think you are performing the Integration test because your test is making use of the Business and the DAL and live database. For unit testing, you deal with one layer of code with all other dependencies either mocked or stubbed. With this approach, you unit tests will be really fast to execute on every incremental code changes. There are various mocking frameworks that you can use like Rhino Mock, Moq, typemock to name a few. (In my project, I use Rhino mock to mock the DAL layer and unit test Business Layer in Isolation) Harsha
Unit testing with generated DAL code
[ "", "c#", "unit-testing", "mocking", ".nettiers", "" ]
You wouldn't imagine something as basic as opening a file using the C++ standard library for a Windows application was tricky ... but it appears to be. By Unicode here I mean UTF-8, but I can convert to UTF-16 or whatever, the point is getting an ofstream instance from a Unicode filename. Before I hack up my own solution, is there a preferred route here ? Especially a cross-platform one ?
The C++ standard library is not Unicode-aware. `char` and `wchar_t` are not required to be Unicode encodings. On Windows, `wchar_t` is UTF-16, but there's no direct support for UTF-8 filenames in the standard library (the `char` datatype is not Unicode on Windows) With MSVC (and thus the Microsoft STL), a constructor for filestreams is provided which takes a `const wchar_t*` filename, allowing you to create the stream as: ``` wchar_t const name[] = L"filename.txt"; std::fstream file(name); ``` However, this overload is not specified by the C++11 standard (it only guarantees the presence of the `char` based version). It is also not present on alternative STL implementations like GCC's libstdc++ for MinGW(-w64), as of version g++ 4.8.x. Note that just like `char` on Windows is not UTF8, on other OS'es `wchar_t` may not be UTF16. So overall, this isn't likely to be portable. Opening a stream given a `wchar_t` filename isn't defined according to the standard, and specifying the filename in `char`s may be difficult because the encoding used by char varies between OS'es.
Since C++17, there is a cross-platform way to open an std::fstream with a Unicode filename using the [std::filesystem::path](https://en.cppreference.com/w/cpp/filesystem/path/path) overload. Example: ``` std::ofstream out(std::filesystem::path(u8"こんにちは")); out << "hello"; ```
How to open an std::fstream (ofstream or ifstream) with a unicode filename?
[ "", "c++", "windows", "unicode", "" ]
I've seen on site like flickr or brightkite, a personnal email is provided to the users. If the user mail somethin to this adresse, the content is posted on his public profile. How can I do that on a web application ?
Flickr has published their methods for doing exactly this in the book Building Scalable Websites. The whole of [chapter 6](http://books.google.com/books?id=gXmatd2suh4C&pg=PA117&lpg=PP1&dq=building+scalable+websites&output=html) is dedicated to the topic. You don't need a non-standard MTA, as mentioned above. The default MTAs will work fine (sendmail, qmail, postfix, exim, etc.). All you have to do is edit /etc/aliases. /etc/aliases can be used to set a mailbox to pass all email to a script. I strongly recommend [reading through this chapter](http://books.google.com/books?id=gXmatd2suh4C&pg=PA117&lpg=PP1&dq=building+scalable+websites&output=html), as it goes on to outline a lot of the common issues you'll run into doing exactly this -- parsing attachments, coping with email from mobile devices (which frequently includes bad/quirky headers), doing authorization correctly, etc.
There are two ways to do this, as I see it: First, you can use an existing SMTP server/email box system and, on an interval, pull the messages from that mail box using POP3 or IMAP to insert stuff into your database/system. Alternatively, you can write an implementation of SMTP that will accept email messages coming in and perform your custom logic to put data into your database/system instead of into a mailbox. This is, ultimately, a cleaner design that will have much less overhead. In fact, there may be an SMTP server implementation out there somewhere already that will allow you to inject this kind of custom logic (I'll edit if I can find one). Personally, I'd go with the second option. This will give you much more control over what's going on in your system and it will have an overall cleaner design. Good luck! **Edit:** It's not PHP, but [JAMES](http://james.apache.org/mailet/) from Apache is a Java mail server that allows you to inject custom mail processing units (called mailets) to handle mail processing. You could write such a mailet that will process email messages and put the updates in your database instead of a mailbox. There may be other projects that implement this kind of design, so it's worth a look. **Edit again:** Ooo... here's an open source [php SMTP server](http://sourceforge.net/projects/phpsmtpd/) on SourceForge. I don't know that you can inject custom logic, but you can always edit the source and make it do what you want! (If you insist on PHP anyway)
Create a link between an email and my web-app?
[ "", "php", "web-applications", "" ]
I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info. Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way? Thanks in advance for any help. Update: Here's the code that's giving me the problem... ``` #!/usr/bin/python import wx class MyApp (wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(390, 350)) menubar = wx.MenuBar() help = wx.Menu() help.Append(ID_ABOUT, '&About') self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT) menubar.Append(help, '&Help') self.SetMenuBar(menubar) self.Centre() self.Show(True) panel = wx.Panel(self, -1) font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(9) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) st1 = wx.StaticText(panel, -1, 'Class Name') st1.SetFont(font) hbox1.Add(st1, 0, wx.RIGHT, 8) tc = wx.TextCtrl(panel, -1) hbox1.Add(tc, 1) vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10) vbox.Add((-1, 10)) hbox2 = wx.BoxSizer(wx.HORIZONTAL) st2 = wx.StaticText(panel, -1, 'Matching Classes') st2.SetFont(font) hbox2.Add(st2, 0) vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10) vbox.Add((-1, 10)) hbox3 = wx.BoxSizer(wx.HORIZONTAL) tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE) hbox3.Add(tc2, 1, wx.EXPAND) vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10) vbox.Add((-1, 25)) hbox4 = wx.BoxSizer(wx.HORIZONTAL) cb1 = wx.CheckBox(panel, -1, 'Case Sensitive') cb1.SetFont(font) hbox4.Add(cb1) cb2 = wx.CheckBox(panel, -1, 'Nested Classes') cb2.SetFont(font) hbox4.Add(cb2, 0, wx.LEFT, 10) cb3 = wx.CheckBox(panel, -1, 'Non-Project classes') cb3.SetFont(font) hbox4.Add(cb3, 0, wx.LEFT, 10) vbox.Add(hbox4, 0, wx.LEFT, 10) vbox.Add((-1, 25)) hbox5 = wx.BoxSizer(wx.HORIZONTAL) btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30)) hbox5.Add(btn1, 0) btn2 = wx.Button(panel, -1, 'Close', size=(70, 30)) hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5) vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10) panel.SetSizer(vbox) self.Centre() self.Show(True) def OnAboutBox(self, event): description = """ describe my app here """ licence = """ blablabla """ info = wx.AboutDialogInfo() info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG)) info.SetName('') info.SetVersion('1.0') info.SetDescription(description) info.SetCopyright('') info.SetWebSite('') info.SetLicence(licence) info.AddDeveloper('') info.AddDocWriter('') info.AddArtist('') info.AddTranslator('') wx.AboutBox(info) app = wx.App() MyApp (None, -1, 'Go To Class') app.MainLoop() ```
not sure about the mac version, but wxPython has a built in way to redirect errors to a window (which will unfortunately close when your application crashes, but it's useful for catching errors that silently fail) or to a log file (only updated after your application closes): ``` app = wx.App(redirect=True) app = wx.App(redirect=True,filename="mylogfile.txt") ``` these will work regardless of how you start your application. See [here](http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.App.html#methods) for more
Here's a way to have the error be reported in the GUI instead of the console, via a MessageDialog. You can use the show\_error() method anywhere an exception is caught, here I just have it being caught at the top-most level. You can change it so that the app continues running after the error occurs, if the error can be handled. ``` import wx import sys import traceback def show_error(): message = ''.join(traceback.format_exception(*sys.exc_info())) dialog = wx.MessageDialog(None, message, 'Error!', wx.OK|wx.ICON_ERROR) dialog.ShowModal() class Frame(wx.Frame): def __init__(self): super(Frame, self).__init__(None, -1, 'My Frame') def cause_error(self): raise Exception, 'This is a test.' def main(): app = wx.PySimpleApp() try: frame = Frame() frame.Show() frame.cause_error() app.MainLoop() except: show_error() if __name__ == '__main__': main() ```
How to debug wxpython applications?
[ "", "python", "user-interface", "wxpython", "" ]
I am attempting to use the HtmlAgilityPack library to parse some links in a page, but I am not seeing the results I would expect from the methods. In the following I have a `HtmlNodeCollection` of links. For each link I want to check if there is an image node and then parse its `attributes` but the `SelectNodes` and `SelectSingleNode` methods of `linkNode` seems to be searching the parent document not the `childNodes` of `linkNode`. What gives? ``` HtmlDocument htmldoc = new HtmlDocument(); htmldoc.LoadHtml(content); HtmlNodeCollection linkNodes = htmldoc.DocumentNode.SelectNodes("//a[@href]"); foreach(HtmlNode linkNode in linkNodes) { string linkTitle = linkNode.GetAttributeValue("title", string.Empty); if (linkTitle == string.Empty) { HtmlNode imageNode = linkNode.SelectSingleNode("/img[@alt]"); } } ``` Is there any other way I could get the alt attribute of the image childnode of linkNode if it exists?
You should remove the forwardslash prefix from "/img[@alt]" as it signifies that you want to start at the root of the document. ``` HtmlNode imageNode = linkNode.SelectSingleNode("img[@alt]"); ```
With an xpath query you can also use "." to indicate the search should start at the current node. ``` HtmlNode imageNode = linkNode.SelectSingleNode(".//img[@alt]"); ```
HtmlAgilityPack selecting childNodes not as expected
[ "", "c#", ".net", "asp.net", "xpath", "html-agility-pack", "" ]
When organizing a project where should I put the provider interfaces which are used in MEF? Currently I just have them in the same project as everything else but it seems like it might desirable for me to extract them into a separate dll such that it was a very small dll and would easily be linked to by others attempting to write extensions. What is good practise for this?
As with any plug-in/extension model, you should put your "contracts" (the interfaces a plug-in author should be implementing) in an assembly separate from your application. That way you can make that assembly available to plug-in authors without having to give them the entire application - useful if it's a commercial app that you need to license separately. MEF Preview 5 introduces the ability to export an interface (ie add an [Export] attribute to an interface) such that any implementor of that interface is automatically exported. That means that plug-in authors don't even need to know about MEF - they just implement your interface and they're automatically a MEF extension.
Actually there is new feature in .NET 4.0 called type equivalence that can accomplish this. With this feature you can haave two different interfaces in different contract assemblies that tell the CLR they are the same. Because it is low-level, MEF can work with it fine. A few caveats: * Other than framework types, only custom interfaces are supported. * Custom generic interfaces are not supported. * Matching requires a guid on both interfaces :-( You can read more about it here: <http://msdn.microsoft.com/en-us/library/dd997297(VS.100).aspx>. The documentation will say it's for COM, but you can use it for managed code as well.
Where should I put the interfaces for MEF?
[ "", "c#", "mef", "" ]
So, the situation I'm currently in is a wee bit complicated (for me that is), but I'm gonna give it a try. I would like to run to a snippet of HTML and extract all the links referring to my own domain. Next I want to append these URL's with a predefined string of GET vars. For example, I want to append '?var1=2&var2=4' to '<http://www.domain.com/page/>' thus creating '<http://www.domain.com/page/?var1=2&var2=4>'. The method I'm currently applying is a simple preg\_replace function (PHP), but here is when it gets interesting. How do i create valid appended url's when they already have some GET vars at the end? For example, it could create a url like this: '<http://www.domain.com/page/?already=here&another=one?var1=2&var2=4>' thus breaking the GET data. So to conclude, what I'm looking for is a reg exp which can cope with these scenarios, create my extended url and write it back to the HTML snippet. This is what I have so far: ``` $sHTML = preg_replace("'href=\"($domainURL.*?[\/$])\"'", 'href="\1' . $appendedTags . '"', $sHTML); ``` Thanks in advance
In addition to what [Elazar Leibovich](https://stackoverflow.com/questions/817101/how-to-append-variables-to-a-url-which-already-has-variables/817172#817172) suggested, I'd parse the query string with [`parse_str()`](http://de3.php.net/parse_str), modify the resulting array to my needs and then use [`http_build_query()`](http://de3.php.net/manual/en/function.http-build-query.php) to rebuild the query string. This way you won't have any duplicates within your query string and you don't have to bother yourself with url-encoding your query-parts. The complete example would then look like (augmenting [Elazar Leibovich](https://stackoverflow.com/questions/817101/how-to-append-variables-to-a-url-which-already-has-variables/817172#817172) code): ``` $broken = parse_url($url); $query = parse_str($broken['query']); $query['var1'] = 1; $query['var2'] = 2; $broken['query'] = http_build_query($query); return $broken['scheme'] . '://' . $broken['host'] . $broken['path'] . '?' . $broken['query'] . '#' . $broken['fragment']; ```
Regex are not the solution, as somebody [said](http://www.codinghorror.com/blog/archives/001016.html "coding horrors on regex"): > Some people, when confronted with a > problem, think "I know, I'll use > regular expressions." Now they have > two problems. But nevermind that, what I would use, is [parse\_url](http://www.php.net/manual/en/function.parse-url.php), and then append my `var1=1&var2=2` to the result query string. Something along the lines of: ``` $broken = parse_url($url); $broken['query'] .= '&var1=1&var2=2'; if (strpos($broken,'&')==0) $broken['query'] = substr($broken['query'],1); return $broken['scheme'].'://'.$broken['host'].$broken['path']. '?'.$broken['query'].'#'.$broken['fragment']; ``` If you don't want your variable to appear twice, use also [parse\_str](http://php.net/parse_str "php man page") to break apart the query string.
How to append variables to a url which already has variables?
[ "", "php", "regex", "url", "" ]
I don't know if i am asking a silly question but I want to know whether Convert.ToBase64String function in .NET returns the same length as it's source byte size or is it different? I wanted to try out the article from MSDN itself [How To: Use Forms Authentication with SQL Server 2000](http://msdn.microsoft.com/en-us/library/aa302398.aspx) to hash my password but I found out that the function they used to create salt string is returning 3 more length than it is supposed to return. To clarify here is the code in that article. ``` private static string CreateSalt(int size) { // Generate a cryptographic random number using the cryptographic // service provider RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[size]; rng.GetBytes(buff); // Return a Base64 string representation of the random number return Convert.ToBase64String(buff); } ```
The base64 encoding of a byte string is longer than the byte string because that byte string has 2^8 possibilities per "location", while a base 64 string has only 2^6 possibilities per location (that's why we call it base 64). Just think of the logarithms and pigeon holes. Take the number 5000. How many locations (pigeon holes, bytes) do you need in order to store it in base 256? ``` "Locations in base256" = ceil(log_2(5000) / 8) = ceil(1.54) = 2 ``` Where log\_2 tells you how many bits you need. Now how many in base64? ``` "Locations in base64" = ceil(log_2(5000) / 6) = ceil(2.04) = 3 ```
No, Base64 returns 4 bytes output for 3 bytes input, rounded up (padded with =) to the next 4-byte boundary. ``` int outputLength = ((inputLength+2)/3)*4 ``` That's because it only uses 6 bits (basically a number 0-63) per byte in order to only use ASCII chars which are not control chars and in the 7-bit range. Therefore, you get 3\*8 => 4\*6 bits when encoding data with Base64.
Does Convert.ToBase64String return the same length as it's source byte array?
[ "", "c#", ".net", "cryptography", "" ]
I'm using Visual Studio and performing a valid dynamic cast. RTTI is enabled. Edit : Updated the code to be more realistic ``` struct base { virtual base* Clone() { base* ptr = new base; CopyValuesTo( ptr ); return ptr; } virtual void CopyValuesTo( base* ptr ) { ... } virtual ~base() { } } struct derived : public base { virtual base* Clone() { derived* ptr = new derived; CopyValuesTo( ptr ); return ptr; } virtual void CopyValuesTo( base* ptr ) { ... } virtual ~derived() { } } void Class1::UseNewSpec( base* in_ptr ) //part of a totally unrelated class { derived* ptr = dynamic_cast<derived *>(in_ptr); if( !ptr ) return; delete m_ptr; m_ptr = ptr->Clone(); //m_ptr is a member of Class1 of type base* } //usage : Class1 obj; derived new_spec; obj.UseNewSpec( &new_spec ); ``` My debugger says that in\_ptr is of the correct type when the exception is thrown. Google seems particularly unhelpful. Any ideas? Cheers.
I ran a test based on your pseudo-code and it works. So if RTTI is truly enabled in your build configuration, then it must be another problem that isn't captured in what you posted.
<https://learn.microsoft.com/en-us/cpp/cpp/typeid-operator?view=vs-2019> has info on \_\_non\_rtti\_object\_exception. From MSDN: > If the pointer does not point to a > valid object, a \_\_non\_rtti\_objectexception is thrown, indicating an > attempt to analyze the RTTI that > triggered a fault (like access > violation), because the object is > somehow invalid (bad pointer or the > code wasn't compiled with /GR).
When and why is an std::__non_rtti_object exception generated?
[ "", "c++", "exception", "visual-studio-2005", "rtti", "" ]
How do I execute > rd /s /q c:\folder in Java? It woks perfectly on the command-line.
According to [dtsazza's answer](https://stackoverflow.com/questions/857212/how-do-i-execute-rd-command-in-java/857220#857220): ``` Runtime.getRuntime().exec("cmd.exe /k rd /s /q c:\\folder"); ``` It works perfectly under WinXP SP3. The `/k` parameter shows, that a command will follow that has to be executed out of the `cmd.exe`. Good luck with that!
Check the [Runtime.exec](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String)) method, which lets you call external processes. (Bear in mind that you lose some platform independence as this would rely on the machine having the `rd` command installed and on the path.) A better option might be to do the same thing in pure Java - the following should be equivalent: ``` private void deleteDirectory(File directory) { for (File entity : directory.listFiles()) { if (entity.isDirectory()) { deleteDirectory(entity); } else { entity.delete(); } } directory.delete(); } deleteDirectory(new File("C:\\folder")); ``` Adding error-checking as required. :-)
How do I execute the rd command in Java?
[ "", "java", "" ]
I am generally not very fond of refactoring tools. No need to get into details. Still, I occasionally try out new versions. Here is what I was trying to do while evaluating resharper 4.5 : I needed to replace all usages of a method with a wrapper method (to be created) but I could not. I usually suck at noticing an obvious feature, is this the case? If resharper does not have this feature, do you know such tools? Edit 2: Sample has been improved to include instance method calls. Edit: Here is a simple case to play. ``` static void Main(string[] args) { while(true) { if (Console.ReadKey().Key == ConsoleKey.Escape) { Thread.Sleep(10); if (Quiting()) break; } Console.Beep(250, 50); } } static bool Quiting() { if (Console.In.Peek() > 0) { Console.Beep(250, 150); return false; } return true; } ``` What I need is something like: (Edit2: added an instance sample) ``` private static StringBuilder _builder = new StringBuilder(); static void Main(string[] args) { while(true) { var key = Console.ReadKey(); if (key.Key == ConsoleKey.Escape) { Thread.Sleep(10); if (Quiting()) break; } _builder.Append(" (").Append(key.KeyChar).Append(") "); Beep(250, 50); } } static bool Quiting() { if (Console.In.Peek() > 0) { Beep(250, 150); _builder.Append('@'); return false; } return true; } static void Beep(int frequency, int duration) { // finally cursor ends up here Console.Beep(250, 50); } ``` Console.Beep calls are refactored. Next lets refactor StringBuilder.Append(char) : ``` class Program { private static StringBuilder _builder = new StringBuilder(); static void Main(string[] args) { while(true) { var key = Console.ReadKey(); if (key.Key == ConsoleKey.Escape) { Thread.Sleep(10); if (Quiting()) break; } _builder.Append(" (").AppendUpper(key.KeyChar).Append(") "); Beep(250, 50); } } static bool Quiting() { if (Console.In.Peek() > 0) { Beep(250, 150); _builder.AppendUpper('n'); return false; } return true; } static void Beep(int frequency, int duration) { // finally cursor ends up here Console.Beep(250, 50); } } static class StringBuilderExtensions { public static StringBuilder AppendUpper(this StringBuilder builder, char c) { return builder.Append(char.ToUpper(c)); } } ``` Selecting from usages and maybe omitting common parameters (such as 250 above) or common instance parameters for non-extension statics shall make this feature more valuable. Hopefully, this clears up the question.
It's not included in any .NET refactoring IIRC, the tool which has such a refactoring is Eclipse, but not for .NET/C#
ReSharper doesn't have this as a single refactoring. I might do it as follows: 1. Select the contents of the method to be wrapped, and use Extract Method to create a new private method from the contents. 2. The original method is now a trivial wrapper around "itself". Rename it if you like, or manipulate it as you like (make it static, move to a different class, surround with try/catch, whatever). --- **EDIT:** Based on your edit, it seems you have an additional problem. Not only is Console.Beep not in the *same* class, it's not even in *your* class. But if you don't mind a little search and replace, then you can put it into your own class, then proceed with the refactoring: ``` namespace Temporary { public class Console { public static void Beep(int x, int y) {System.Console.Beep(x,y);} } } ``` Then do a "Replace in Files" to replace Console.Beep with Temporary.Console.Beep, and proceed as above.
Replacing all usages of a method (Introduce Indirection)
[ "", "c#", "refactoring", "resharper", "" ]
Is there a way to read COBOL data in a Java program? More concretely I'm confronted with the following case: I have a file with fixed length records of data. The data definition is done as COBOL copybooks. I think of a library which is taking into account the copybooks and would be able to read those records. Ideally, it should be possible to generate basic Java classes and structures based on the copybook information. In a later step the datarecords would be parsed and the data filled into objects of those generated classes. Are there any other techniques to cope with the problem of reading COBOL data?
You could look at [JRecord](http://sourceforge.net/projects/jrecord/) or [cb2java](http://sourceforge.net/projects/cb2java/). Both allow you to access COBOL files, but neither will generate the full classes. --- Update Jan 2011 Since the original answer: * JRecord continues be developed. There is now a `JRecord Code generator` available as either a standalone program or in the [Recordeditor](https://sourceforge.net/projects/record-editor/). This `Code Generator` will build `JRecord JRecord` code from a COBOL Copybook. See [RecordEditor Jrecord CodeGen](https://stackoverflow.com/questions/46313332/how-do-you-generate-javajrecord-code-for-a-cobol-copybook)) * Development on **cb2java** has stopped * [cobol2j](https://sourceforge.net/projects/cobol2j) has been written. There have been no updates for a year. * There is also [Legstar](http://www.legsem.com/legstar/) again nothing published for a few years ### Update Aug 2017 The [RecordEditor](https://sourceforge.net/projects/record-editor/) has a Generate option for generating **Java / JRecord** code from a COBOL Copybook. See [RecordEditor Code Generation notes](http://record-editor.sourceforge.net/RecordEditorGenerate.htm) for details. ### Update Jan 2018 There is some information on generating *Java~JRecord* code in this question / answer: *[How do you generate java~jrecord code for a Cobol copybook](https://stackoverflow.com/questions/46313332/how-do-you-generate-javajrecord-code-fror-a-cobol-copybook)*
Yes. I have done that before. I used an ODBC connection to COBOL files, and then with jdbc:odbc bridge, I used metadata information to generate classes, read data and port it all to Oracle. [Here](http://www.java2s.com/Code/Java/Database-SQL-JDBC/Metadata-DB-Info.htm) is a nice tutorial on how to access metada information with JDBC. [Here](http://www.tutorialized.com/tutorial/Database-Metadata-with-JDBC/13753) is another one. Keep in mind that you don't need the JDBC:ODBC bridge approach. If you can get a native JDBC driver to connect to your Cobol DataSource, it will be better. In this regard, I also used an IBM native driver. Don't remember the name though. It was a long time ago.
Reading COBOL datastructures from Java
[ "", "java", "data-structures", "cobol", "copybook", "" ]
I seem to be blind at the moment, so I need to ask here. I want to sort a list of tuples which look like that ``` (id, parent_id, value) ``` So that it is a representation of the tree as a flattend list of list of tree nodes. For example the input ``` (1, None, '...') (3, 2', '...') (2, 1, '...') (4, 1, '...') (5, 2, '...') (6, None, '...') ``` Should sorted like that afterwards ``` (1, None, '...') (2, 1, '...') (3, 2', '...') (5, 2, '...') (4, 1, '...') (6, None, '...') ``` Any hint would be highly appreciated. Thanks in advance.
Python sorts tuples from left to right, so if you arrange your tuples so the first sort key is the first item and so forth, it'll be reasonably efficient. The mapping from a list of tuples to a tree is not clear from what you're describing. Please draw it out, or explain it more thoroughly. For example, your example appears to be: [![tree diagram](https://i.stack.imgur.com/SWPUZ.png)](https://i.stack.imgur.com/SWPUZ.png) (source: [sabi.net](http://web.sabi.net/temp/tree.png)) If you've got two nodes with no parent, that is more like a forest than a tree. What are you trying to represent with the tree? What does "sorted" mean in this context?
I'm not sure I've quite follows what you are exactly trying to do, but if you have a forest as a list of nodes, can't you just read it and build the tree structure, then write it out as a bread-first traversal of all the trees? Any particular reason to avoid this?
Creating a tree from a list of tuples
[ "", "python", "sorting", "tree", "" ]
[Ant Java task](http://ant.apache.org/manual/Tasks/java.html) provides `fork` parameter, which, by definition *"if enabled triggers the class execution in another VM"*. As we are dealing with a large amount of data, setting this parameter saved us from running out of Java heap space. We want to be able to do the same through a Java class. What would be the best way to achieve the functionality as provided by `fork`?
Execute another java process. By using ProcessBuilder class, for example. <http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html> You can run as many worker processes as you wish. Make them having a separate main class, doing their tasks from that main class, and quiting when their task is completed. You'll have to figure out their classpath, and the location of java binary on the system, but that's doable. I think you can even be notified when they complete via Process.waitFor().
If you look at the `ant` source code, when `fork` is `true`, then it just wraps an `Execute` task and eventually, the code that gets called is ``` Runtime.getRuntime().exec(cmd, env); ``` Downloading and having a look at the source code for `org.apache.tools.ant.taskdefs.Java` and `org.apache.tools.ant.taskdefs.Execute` will give you some great pointers in finding the location of the executable to run in a platform independent way, etc.
Java equivalent of fork in Java task of Ant?
[ "", "java", "ant", "fork", "" ]
I have items in a list in a SharePoint 2003 site that I need to add to an existing list in a 2007 site. The items have attachments. How can this be accomplished using PowerShell or C#?
I ended up using a C# program in conjunction with the SharePoint web services to accomplish this. I also used the extension methods (GetXElement, GetXmlNode) on Eric White's blog [here](http://blogs.msdn.com/ericwhite/archive/2008/12/22/convert-xelement-to-xmlnode-and-convert-xmlnode-to-xelement.aspx) to convert between XMLNodes and XElements which made the XML from SharePoint easier to work with. Below is a template for most of the code needed to transfer list data, including attachments, from one SharePoint List (either 2003 or 2007) to another one: **1) This is the code moves attachments after a new item has been added to the target list.** ``` // Adds attachments from a list item in one SharePoint server to a list item in another SharePoint server. // addResults is the return value from a lists.UpdateListItems call. private void AddAttachments(XElement addResults, XElement listItem) { XElement itemElements = _listsService2003.GetAttachmentCollection(_listNameGuid, GetListItemIDString(listItem)).GetXElement(); XNamespace s = "http://schemas.microsoft.com/sharepoint/soap/"; var items = from i in itemElements.Elements(s + "Attachment") select new { File = i.Value }; WebClient Client = new WebClient(); Client.Credentials = new NetworkCredential("user", "password", "domain"); // Pull each attachment file from old site list and upload it to the new site list. foreach (var item in items) { byte[] data = Client.DownloadData(item.File); string fileName = Path.GetFileName(item.File); string id = GetID(addResults); _listsService2007.AddAttachment(_newListNameGuid, id, fileName, data); } } ``` **2) Code that iterates through the old SharePoint List and populates the new one.** ``` private void TransferListItems() { XElement listItems = _listsService2003.GetListItems(_listNameGuid, _viewNameGuid, null, null, "", null).GetXElement(); XNamespace z = "#RowsetSchema"; foreach (XElement listItem in listItems.Descendants(z + "row")) { AddNewListItem(listItem); } } private void AddNewListItem(XElement listItem) { // SharePoint XML for adding new list item. XElement newItem = new XElement("Batch", new XAttribute("OnError", "Return"), new XAttribute("ListVersion", "1"), new XElement("Method", new XAttribute("ID", "1"), new XAttribute("Cmd", "New"))); // Populate fields from old list to new list mapping different field names as necessary. PopulateFields(newItem, listItem); XElement addResults = _listsService2007.UpdateListItems(_newListNameGuid, newItem.GetXmlNode()).GetXElement(); // Address attachements. if (HasAttachments(listItem)) { AddAttachments(addResults, listItem); } } private static bool HasAttachments(XElement listItem) { XAttribute attachments = listItem.Attribute("ows_Attachments"); if (System.Convert.ToInt32(attachments.Value) != 0) return true; return false; } ``` **3) Miscellaneous support code for this sample.** ``` using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Xml.Linq; using System.Net; using System.IO; // This method uses an map List<FieldMap> created from an XML file to map fields in the // 2003 SharePoint list to the new 2007 SharePoint list. private object PopulateFields(XElement batchItem, XElement listItem) { foreach (FieldMap mapItem in FieldMaps) { if (listItem.Attribute(mapItem.OldField) != null) { batchItem.Element("Method").Add(new XElement("Field", new XAttribute("Name", mapItem.NewField), listItem.Attribute(mapItem.OldField).Value)); } } return listItem; } private static string GetID(XElement elem) { XNamespace z = "#RowsetSchema"; XElement temp = elem.Descendants(z + "row").First(); return temp.Attribute("ows_ID").Value; } private static string GetListItemIDString(XElement listItem) { XAttribute field = listItem.Attribute("ows_ID"); return field.Value; } private void SetupServices() { _listsService2003 = new SPLists2003.Lists(); _listsService2003.Url = "http://oldsite/_vti_bin/Lists.asmx"; _listsService2003.Credentials = new System.Net.NetworkCredential("username", "password", "domain"); _listsService2007 = new SPLists2007.Lists(); _listsService2007.Url = "http://newsite/_vti_bin/Lists.asmx"; _listsService2007.Credentials = new System.Net.NetworkCredential("username", "password", "domain"); } private string _listNameGuid = "SomeGuid"; // Unique ID for the old SharePoint List. private string _viewNameGuid = "SomeGuid"; // Unique ID for the old SharePoint View that has all the fields needed. private string _newListNameGuid = "SomeGuid"; // Unique ID for the new SharePoint List (target). private SPLists2003.Lists _listsService2003; // WebService reference for the old SharePoint site (2003 or 2007 is fine). private SPLists2007.Lists _listsService2007; // WebService reference for the new SharePoint site. private List<FieldMap> FieldMaps; // Used to map the old list to the new list. Populated with a support function on startup. class FieldMap { public string OldField { get; set; } public string OldType { get; set; } public string NewField { get; set; } public string NewType { get; set; } } ```
Have you tried saving the list ("with content") as a template, save that file to the 2007 portal templates, then create a new list using that "custom" template? That won't work if the attachments and items total more than 10MB, and I'm not 100% sure that that'll work for 2003 > 2007. It should take < 10 minutes, so it's worth a try if you haven't already.
Transfer List items with Attachments from SharePoint 2003 to an existing list in SharePoint 2007
[ "", "c#", "sharepoint", "powershell", "sharepoint-2007", "" ]
How can I download a webpage with a user agent other than the default one on `urllib2.urlopen`? --- `urllib2.urlopen` is [not available in Python 3.x](/q/2792650); the 3.x equivalent is `urllib.request.urlopen`. See [Changing User Agent in Python 3 for urrlib.request.urlopen](https://stackoverflow.com/questions/24226781) to set the user agent in 3.x with the standard library HTTP facilities.
[Setting the User-Agent](http://www.diveintopython.net/http_web_services/user_agent.html) from everyone's favorite [Dive Into Python](https://diveinto.org/python3/table-of-contents.html). The short story: You can use [Request.add\_header](http://docs.python.org/library/urllib2.html#urllib2.Request.add_header) to do this. You can also pass the headers as a dictionary when creating the Request itself, [as the docs note](http://docs.python.org/library/urllib2.html#urllib2.Request): > *headers* should be a dictionary, and will be treated as if `add_header()` was called with each key and value as arguments. This is often used to “spoof” the `User-Agent` header, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as `"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"`, while `urllib2`‘s default user agent string is `"Python-urllib/2.6"` (on Python 2.6).
I [answered](https://stackoverflow.com/a/762007/3790126) a [similar question](https://stackoverflow.com/questions/761978/send-headers-along-in-python) a couple weeks ago. There is example code in that question, but basically you can do something like this: (Note the capitalization of `User-Agent` as of [RFC 2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html), section 14.43.) ``` opener = urllib2.build_opener() opener.addheaders = [('User-Agent', 'Mozilla/5.0')] response = opener.open('http://www.stackoverflow.com') ```
Changing user agent on urllib2.urlopen
[ "", "python", "urllib2", "python-2.x", "user-agent", "" ]
How can I unfocus a textarea or input? I couldn't find a `$('#my-textarea').unfocus();` method?
``` $('#textarea').blur() ``` Documentation at: <http://api.jquery.com/blur/>
Based on your question, I believe the answer is how to *trigger a blur*, not just (or even) set the event: ``` $('#textArea').trigger('blur'); ```
Is there a jQuery unfocus method?
[ "", "javascript", "jquery", "" ]
anyone knows why this does not work when I try to include a library with the following declarations: ``` namespace wincabase { const char* SOMESTRING = "xx"; } ``` While this is perfectly fine: ``` namespace wincabase { const int X = 30; } ``` I get a "multiple definitions" error with gcc for the first case when I link the lib. Thanks!
const char\* means pointer to const char. This means the pointer itself is **not** constant. Hence it's a normal variable, so you'd need to use ``` extern const char* SOMESTRING; ``` in the header file, and ``` const char* SOMESTRING = "xx"; ``` in one compilation unit of the library. --- Alternatively, if it's meant to be a **const** pointer to a const char, then you should use: ``` const char* const SOMESTRING = "xx"; ```
You're declaring the pointer as const, and then pointing it to a string literal defined in the compilation unit, so you'd be duplicating the string literal if you used this in a header file. What you need to do is declare pointer in the header file, and define the string in a source file in the library. Header: ``` extern const char* SOMESTRING; ``` In some source file in the library: ``` const char* SOMESTRING = "xx"; ```
c++ constant in library; does not work
[ "", "c++", "constants", "" ]
So this code has the off-by-one error: ``` void foo (const char * str) { char buffer[64]; strncpy(buffer, str, sizeof(buffer)); buffer[sizeof(buffer)] = '\0'; printf("whoa: %s", buffer); } ``` What can malicious attackers do if she figured out how the function foo() works? Basically, to what kind of security potential problems is this code vulnerable? I personally thought that the attacker can't really do anything in this case, but I heard that *they* can do a lot of things even if they are limited to work with 1 byte.
The only off-by-one error I see here is this line: ``` buffer[sizeof(buffer)] = '\0'; ``` Is that what you're talking about? I'm not an expert on these things, so maybe I've overlooking something, but since the only thing that will ever get written to that wrong byte is a zero, I think the possibilities are quite limited. The attacker can't control what's being written there. Most likely it would just cause a crash, but it could also cause tons of other odd behavior, all of it specific to your application. I don't see any code injection vulnerability here unless this error causes your app to expose another such vulnerability that would be used as the vector for the actual attack. Again, take with a grain of salt...
Read [Shell Coder's Handbook 2nd Edition](https://rads.stackoverflow.com/amzn/click/com/0764544683) for lots of information.
off-by-one error with string functions (C/C++) and security potentials
[ "", "c++", "c", "security", "" ]
I'd like to reorder the items in a vector, using another vector to specify the order: ``` char A[] = { 'a', 'b', 'c' }; size_t ORDER[] = { 1, 0, 2 }; vector<char> vA(A, A + sizeof(A) / sizeof(*A)); vector<size_t> vOrder(ORDER, ORDER + sizeof(ORDER) / sizeof(*ORDER)); reorder_naive(vA, vOrder); // A is now { 'b', 'a', 'c' } ``` The following is an inefficient implementation that requires copying the vector: ``` void reorder_naive(vector<char>& vA, const vector<size_t>& vOrder) { assert(vA.size() == vOrder.size()); vector vCopy = vA; // Can we avoid this? for(int i = 0; i < vOrder.size(); ++i) vA[i] = vCopy[ vOrder[i] ]; } ``` Is there a more efficient way, for example, that uses swap()?
This algorithm is based on chmike's, but the vector of reorder indices is `const`. This function agrees with his for all 11! permutations of [0..10]. The complexity is O(N^2), taking N as the size of the input, or more precisely, the size of the largest [orbit](https://mathworld.wolfram.com/GroupOrbit.html). See below for an optimized O(N) solution which modifies the input. ``` template< class T > void reorder(vector<T> &v, vector<size_t> const &order ) { for ( int s = 1, d; s < order.size(); ++ s ) { for ( d = order[s]; d < s; d = order[d] ) ; if ( d == s ) while ( d = order[d], d != s ) swap( v[s], v[d] ); } } ``` Here's an STL style version which I put a bit more effort into. It's about 47% faster (that is, almost twice as fast over [0..10]!) because it does all the swaps as early as possible and then returns. The reorder vector consists of a number of orbits, and each orbit is reordered upon reaching its first member. It's faster when the last few elements do not contain an orbit. ``` template< typename order_iterator, typename value_iterator > void reorder( order_iterator order_begin, order_iterator order_end, value_iterator v ) { typedef typename std::iterator_traits< value_iterator >::value_type value_t; typedef typename std::iterator_traits< order_iterator >::value_type index_t; typedef typename std::iterator_traits< order_iterator >::difference_type diff_t; diff_t remaining = order_end - 1 - order_begin; for ( index_t s = index_t(), d; remaining > 0; ++ s ) { for ( d = order_begin[s]; d > s; d = order_begin[d] ) ; if ( d == s ) { -- remaining; value_t temp = v[s]; while ( d = order_begin[d], d != s ) { swap( temp, v[d] ); -- remaining; } v[s] = temp; } } } ``` --- And finally, just to answer the question once and for all, a variant which does destroy the reorder vector (filling it with -1's). For permutations of [0..10], It's about 16% faster than the preceding version. Because overwriting the input enables dynamic programming, it is O(N), asymptotically faster for some cases with longer sequences. ``` template< typename order_iterator, typename value_iterator > void reorder_destructive( order_iterator order_begin, order_iterator order_end, value_iterator v ) { typedef typename std::iterator_traits< value_iterator >::value_type value_t; typedef typename std::iterator_traits< order_iterator >::value_type index_t; typedef typename std::iterator_traits< order_iterator >::difference_type diff_t; diff_t remaining = order_end - 1 - order_begin; for ( index_t s = index_t(); remaining > 0; ++ s ) { index_t d = order_begin[s]; if ( d == (diff_t) -1 ) continue; -- remaining; value_t temp = v[s]; for ( index_t d2; d != s; d = d2 ) { swap( temp, v[d] ); swap( order_begin[d], d2 = (diff_t) -1 ); -- remaining; } v[s] = temp; } } ```
# In-place reordering of vector Warning: there is an ambiguity about the semantic what the ordering-indices mean. Both are answered here ## move elements of vector to the position of the indices Interactive version [here](https://techiedelight.com/compiler/?f-4U). ``` #include <iostream> #include <vector> #include <assert.h> using namespace std; void REORDER(vector<double>& vA, vector<size_t>& vOrder) { assert(vA.size() == vOrder.size()); // for all elements to put in place for( int i = 0; i < vA.size() - 1; ++i ) { // while the element i is not yet in place while( i != vOrder[i] ) { // swap it with the element at its final place int alt = vOrder[i]; swap( vA[i], vA[alt] ); swap( vOrder[i], vOrder[alt] ); } } } int main() { std::vector<double> vec {7, 5, 9, 6}; std::vector<size_t> inds {1, 3, 0, 2}; REORDER(vec, inds); for (size_t vv = 0; vv < vec.size(); ++vv) { std::cout << vec[vv] << std::endl; } return 0; } ``` **output** ``` 9 7 6 5 ``` note that you can save one test because if n-1 elements are in place the last nth element is certainly in place. On exit vA and vOrder are properly ordered. This algorithm performs at most n-1 swapping because each swap moves the element to its final position. And we'll have to do at most 2N tests on vOrder. ## draw the elements of vector from the position of the indices Try it interactively [here](https://techiedelight.com/compiler/?m1y1). ``` #include <iostream> #include <vector> #include <assert.h> template<typename T> void reorder(std::vector<T>& vec, std::vector<size_t> vOrder) { assert(vec.size() == vOrder.size()); for( size_t vv = 0; vv < vec.size() - 1; ++vv ) { if (vOrder[vv] == vv) { continue; } size_t oo; for(oo = vv + 1; oo < vOrder.size(); ++oo) { if (vOrder[oo] == vv) { break; } } std::swap( vec[vv], vec[vOrder[vv]] ); std::swap( vOrder[vv], vOrder[oo] ); } } int main() { std::vector<double> vec {7, 5, 9, 6}; std::vector<size_t> inds {1, 3, 0, 2}; reorder(vec, inds); for (size_t vv = 0; vv < vec.size(); ++vv) { std::cout << vec[vv] << std::endl; } return 0; } ``` **Output** ``` 5 6 7 9 ```
Reorder vector using a vector of indices
[ "", "c++", "algorithm", "vector", "stl", "" ]
I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a lockless manner. Requirements in my case were simple: * One producer thread. * One consumer thread. * Queue has place for only one item. * Producer can produce next item before the current one is consumed. The current item is therefore lost, but that's OK for me. * Consumer can consume current item before the next one is produced. The current item is therefore consumed twice (or more), but that's OK for me. So I wrote this: ``` QUEUE_ITEM = None # this is executed in one threading.Thread object def producer(): global QUEUE_ITEM while True: i = produce_item() QUEUE_ITEM = i # this is executed in another threading.Thread object def consumer(): global QUEUE_ITEM while True: i = QUEUE_ITEM consume_item(i) ``` My question is: Is this code thread-safe? Immediate comment: this code isn't really lockless - I use CPython and it has GIL. I tested the code a little and it seems to work. It translates to some LOAD and STORE ops which are atomic because of GIL. But I also know that `del x` operation isn't atomic when x implements `__del__` method. So if my item has a `__del__` method and some nasty scheduling happens, things may break. Or not? Another question is: What kind of restrictions (for example on produced items' type) do I have to impose to make the above code work fine? My questions are only about theoretical possibility to exploit CPython's and GIL's quirks in order to come up with lockless (i.e. no locks like threading.Lock explicitly in code) solution.
Yes this will work in the way that you described: 1. That the producer may produce a skippable element. 2. That the consumer may consume the same element. > But I also know that del x operation isn't atomic when x implements **del** method. So if my item has a **del** method and some nasty scheduling happens, things may break. I don't see a "del" here. If a del happens in consume\_item then the **del** may occur in the producer thread. I don't think this would be a "problem". Don't bother using this though. You will end up using up CPU on pointless polling cycles, and it is not any faster than using a queue with locks since Python already has a global lock.
Trickery will bite you. Just use Queue to communicate between threads.
Is this Python producer-consumer lockless approach thread-safe?
[ "", "python", "locking", "thread-safety", "producer-consumer", "" ]
I'm not sure if this is a duplicate but if it is please feel free to close this. Background: I have a timer component for a game i'm writing that supports Stop and Pause methods. The non-critical error cases in question are doing things like calling Pause when in the timer is already paused, this is not fatal but it's not going to cause the change in state implied by the method name Questions: 1. How does one generally indicate a non-fatal but abnormal condition? 2. Should I actually be throwing an exception in these cases? I think it's a little heavy-handed considering calling Pause when paused wont do any harm 3. Am I over-thinking this **UPDATE:** Based on the responses and comments here is the statergy I have chosen to take: In development builds an exception will occur because I consider these bugs and I'd like to catch them and correct them. I can't justify an exception in a release build because these bugs don't corrupt the game state, and I don't think users of the application would appreciate the loss of their hard earned score because I failed to code properly Thanks for all your responses, this has been very educational for me.
I think your fine to just ignore the call if the timer is already paused. Assuming the method is called Pause() then the client only requires that after the method call that the timer is paused, and exceptions should only be thrown if it won't be; the method doesn't imply any requirement on the current state of the timer. On the other hand if the method was called ChangeTimerFromRunningToPaused() then that implies that it is only valid to call this on a running timer. Under these circumstances I would expect it to throw an exception informing the client that the timer is not in a valid state to process this method call.
Against the other answers, I would consider throwing an exception. If it would be my code performing the second `Pause()` call, I might consider my code to be broken if it makes this call where it should not. Maybe I am missing a check like `if (Timer.IsRunning) { }` and I don't want to hide this bug by silently ignoring the call. Even if the call is triggered by user input - a button click for example - this might be an indication of bad design and I should have a look at it. Maybe the button should be disabled. The more I think about it, the less situations come to mind where the second call should not be an exception indicating bad calling code. So, yes, I would throw the exception. **UPDATE** In a comment Martin Harris suggest using `Debug.Assert()` to get the bug during development. I think that this is to weak because you won't get the bug in production code. But of course you don't want to crash an application in production because of this non-fatal error. So we will just catch this exception up the stack and generate a error report and than resume as if nothing happend. Here are two goo links. [API Design Myth: Exceptions are for "Exceptional Errors"](http://blogs.msdn.com/kcwalina/archive/2008/07/17/ExceptionalError.aspx,) [Coding Horror - Exception-Driven Development](https://blog.codinghorror.com/exception-driven-development/)
How to handle non-fatal error conditions
[ "", "c#", "error-handling", "" ]
I am working in C#. I find myself creating dialogs for editing my application settings all the time. For every `Control` on the dialog I am reading the configuration file and set it accordingly. After pressing OK, I am reading all the controls and store the values in the configuration files or something similar again. This seems to be very time consuming, simple and repetitive. Does anybody have an idea how to simplify this process? Code generation? Helper classes?
You can bind WinForms controls directly to application settings, which should make your life a lot easier for creating dialogs to manage them. Just select a control and look for the (Application Settings) option under the Data group in the properties pane. I put up a screenshot [here](http://www.colincochrane.com/image.axd?picture=2009%2f5%2fappbinding.JPG) to illustrate.
Do these application settings dialogs need to be pretty or are they simply there for personal configuration? If it's the latter, read all the settings into a class and assign that class to a property editor. Not recommended for a good-looking, final UI though.
Simplify configuration dialog building .NET
[ "", "c#", "winforms", "configuration", "" ]
I was wondering what the best way to format a string would be in Scala. I'm reimplementing the toString method for a class, and it's a rather long and complex string. I thought about using String.format but it seems to have problems with Scala. Is there a native Scala function for doing this?
I was simply using it wrong. Correct usage is .format(parem1, parem2).
How about good old `java.text.MessageFormat`?
What is the best way to format a string in Scala?
[ "", "java", "string", "scala", "" ]
I have code that looks like follows: ``` public interface BaseDAO{ // marker interface } public interface CustomerDAO extends BaseDAO{ public void createCustomer(); public void deleteCustomer(); public Customer getCustomer(int id); // etc } public abstract class DAOFactory { public BaseDAO getCustomerDAO(); public static DAOFactory getInstance(){ if(system.getProperty("allowtest").equals("yes")) { return new TestDAOFactory(); } else return new ProdDAOFactory(); } public class TestDAOFactory extends DAOFactory{ public BaseDAO getCustomerDAO() { return new TestCustomerDAO(); // this is a concrete implementation //that extends CustomerDAO //and this implementation has dummy code on methods } public class ProdDAOFactory extends DAOFactory { public BaseDAO getCustomerDAO() { return new ProdCustomerDAO(); // this implementation would have // code that would connect to the database and do some stuff.. } } ``` Now, I do know that this code smells.. for many reasons. However, this code is here too: <http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html>, refer 9.8 What I intend to do is this: 1) Switch my DAOs implementations at runtime based on environment (system properties). 2) Make use of java generics so that I can avoid type casting... for instance does something like this: ``` CustomerDAO dao = factory.getCustomerDAO(); dao.getCustomer(); ``` As opposed to: ``` CustomerDAO dao = (CustomerDAO) factory.getCustomerDAO(); dao.getCustomer(); ``` Your thoughts and suggestions, please.
You should define the factory like that: ``` public abstract class DAOFactory<DAO extends BaseDAO> { public DAO getCustomerDAO(); public static <DAO extends BaseDAO> DAOFactory<DAO> getInstance(Class<DAO> typeToken){ // instantiate the the proper factory by using the typeToken. if(system.getProperty("allowtest").equals("yes")) { return new TestDAOFactory(); } else return new ProdDAOFactory(); } ``` getInstance should return a proper typed DAOFactory. The factory variable will have the type: ``` DAOFactory<CustomerDAO> factory = DAOFactory<CustomerDAO>.getInstance(CustomerDAO.class); ``` and the usage will be properly typed: ``` CustomerDAO dao = factory.getCustomerDAO(); dao.getCustomer(); ``` the only problem will probably be a cast required inside the getInstance methods.
There's a bunch of articles detailing what you need: * [Generic DAO Pattern With JDK 5.0](http://blog.hibernate.org/Bloggers/GenericDAOPatternWithJDK50) * [Generic Data Access Objects](https://www.hibernate.org/328.html) (same as above) * [Don't repeat the DAO](http://www.ibm.com/developerworks/java/library/j-genericdao.html) (with Spring, but the principles are the same) * [Java 1.5 Generic DAO](http://www.dhptech.com/node/18) (Spring again) Please note that, unlike your example, there is no reason why the methods of `DAOFactory` should not return the actual subclasses (i.e. `CustomerDAO getCustomerDAO()`). Furthermore, main benefit of using generic DAOs is having the entity type "genericized", so you don't have to cast from `load()/get()/find()` and similar methods.
Factory method pattern in java using generics, how to?
[ "", "java", "generics", "methods", "design-patterns", "factory", "" ]
Please bear with me if this question isn't well formulated. Not knowing is part of the problem. An example of what I'd like to accomplish can be found in PropertyChangedEventArgs in WPF. If you want to flag that a property has changed in WPF, you do it like this: ``` PropertyChanged(this, new PropertyChangedEventArgs("propertyName")); ``` You pass a **string** to PropertyChangedEventArgs that refers to the **property name** that changed. You can imagine that I don't really want hard coded strings for property names all over my code. Refactor-rename misses it, of course, which makes it not only aesthetically unappealing but error prone as well. I'd much rather **refer to the property itself** ... somehow. ``` PropertyChanged(this, new PropertyChangedEventArgs(?SomeClass.PropertyName?)); ``` It seems like I should be able to wrap this in a short method that lets me say something like the above. ``` private void MyPropertyChanged(??) { PropertyChanged(this, new PropertyChangedEventArgs(??.ToString()??)); } ... so I can say something like: MyPropertyChanged(Person.Name); //where I'm interested in the property *itself* ``` So far I'm drawing a blank.
There isn't a direct way to do this, unfortunately; however, you can do it in .NET 3.5 via `Expression`. [See here](https://stackoverflow.com/questions/491429/how-to-get-the-propertyinfo-of-a-specific-property/491486#491486) for more. To copy the example: ``` PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar); ``` (it is pretty simple to change that to return the name instead of the `PropertyInfo`). Likewise, it would be pretty simple to write a variant: ``` OnPropertyChanged(x=>x.Name); ``` using: ``` OnPropertyChanged<T>(Expression<Func<MyType,T>> property) {...} ```
This is a frequently requested feature, usually called infoof ("info of"), which would return the reflection object associated with a member, e.g. ``` PropertyInfo pi = infoof(Person.Name); ``` Sadly the dynamic keyword is absorbing the C# compiler team's time instead!
Referring to the property itself in C#. Reflection? Generic? Type?
[ "", "c#", "reflection", "properties", "" ]
The title speaks for itself .... Does choice of container affects the speed of the default std::sort algorithm somehow or not? For example, if I use list, does the sorting algorithm just switch the node pointers or does it switch the whole data in the nodes?
I don't think `std::sort` works on lists as it requires a random access iterator which is not provided by a `list<>`. Note that `list<>` provides a `sort` method but it's completely separate from `std::sort`. The choice of container does matter. STL's `std::sort` relies on iterators to abstract away the way a container stores data. It just uses the iterators you provide to move elements around. The faster those iterators work in terms of accessing and assigning an element, the faster the `std::sort` would work.
The choice does make a difference, but predicting which container will be the most efficient is very difficult. The best approach is to use the container that is easiest for your application to work with (probably std::vector), see if sorting is adequately fast with that container, and if so stick wth it. If not, do performance profiling on your sorting problem and choose different container based on the profile data. As an ex-lecturer and ex-trainer, I sometimes feel personally responsible for the common idea that a linked list has mystical performance enhancing properties. Take it from one who knows: the only reason a linked list appear in so many text books and tutorials is because it is covenient for the people who wrote those books and tutorials to have a data structure that can illustrate pointers, dynamic memory mangement, recursion, searching and sorting all in one - it has nothing to do with efficiency.
Which STL container is best for std::sort? (Does it even matter?)
[ "", "c++", "stl", "sorting", "" ]
I have some Listboxes in my app bound to ObservableCollections, and i would like to animate an item if it's being removed. I already found a question about animating added items by using the FrameworkElement.Loaded event, but of course that doesn't work the same way with the Unloaded event. Is there any way to do this in a way that can be used in a datatemplate? EDIT: I've hooked up to the CollectionChanged event in my ItemsSource and tried to apply an animation manually. Currently it looks like this: ``` ListBoxItem item = stack.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem; item.LayoutTransform = new ScaleTransform(1, 1); DoubleAnimation scaleAnimation = new DoubleAnimation(); scaleAnimation.From = 1; scaleAnimation.To = 0; scaleAnimation.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500)); ScaleTransform transform = (ScaleTransform)item.LayoutTransform; transform.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation); ``` The problem is, it doesn't work at all. The item still just pops away. The item is still there when the method gets called, so shouldn't it be playing the animation before it disappears? Or am i doing it completely wrong?
It turned out that even if i was raising an event before removing them, they would get removed instantly anyway. So as i was using it as an observable stack, i worked around this by leaving the removed element in the collection and removing it later. like this: ``` public class ObservableStack<T> : ObservableCollection<T> { private T collapsed; public event EventHandler BeforePop; public T Peek() { if (collapsed != null) { Remove(collapsed); collapsed = default(T); } return this.FirstOrDefault(); } public T Pop() { if (collapsed != null) { Remove(collapsed); } T result = (collapsed = this.FirstOrDefault()); if (BeforePop != null && result != null) BeforePop(this, new EventArgs()); return result; } public void Push(T item) { if (collapsed != null) { Remove(collapsed); collapsed = default(T); } Insert(0, item); } } ``` Might not be the best solution, but it does the job (at least if i only use it as a stack).
I solved this by adding an IsRemoved property to the bound items. An event trigger in the ListViewItem container template is then bound which plays the removal animation when this bool changes to true. Concurrently, a Task is started with Task.Delay(n) matching the duration of the animation, and follows up with the actual removal from the collection. Note that this removal needs to be dispatched to the thread owning the list to avoid a cross thread exception. ``` void Remove(MyItem item, IList<MyItem> list) { item.IsRemoved = true; Task.Factory.StartNew(() => { Task.Delay(ANIMATION_LENGTH_MS); Dispatcher.Invoke(new Action(() => list.Remove(item))); }); } ```
Animating removed item in Listbox
[ "", "c#", ".net", "wpf", "xaml", "expression-blend", "" ]
Consider that I've a excel sheet in below format: **person** **age** Foo 29 Bar 27 Now I want to read these values (using POI HSSF) and have to process them. What's the best way to do that? Note that I do not have a Object Person in my application, becasue the values that may come in excel sheet is arbitrary (i.e. it may not be the person name and age). So, I need to use some kinda HashMap to store these values. In case multiple rows, is it good to have a List !?
``` public class Grid { private Row headerColumns; private List<Row> dataRows; public Grid() { dataRows = new LinkedList<Row>(); } public Grid(int rowCount) { dataRows = new ArrayList<Row>(rowCount); } public void addHeaderRow(List<String> headers) { this.headerColumns = new Row(headers); } public void addDataRow(List<String> data) { this.dataRows.add( new Row(data) ); } public List<Row> getAllData() { List<Row> data = new ArrayList<Row>(1+dataRows.size()); data.add(this.headerColumns); data.addAll(dataRows); return data; } public Row getHeaderColumns() { return headerColumns; } public List<Row> getDataRows() { return dataRows; } } class Row { private List<String> data; public Row(List<String> data) { this.data = data; } public void addColumn(String columnData) { data.add(columnData); } public List<String> getData() { return data; } } ```
If the format is defined, make a class that accomodates all those fields. If the format isn't defined, pass Row-s around, or Lists, or even DOM from excel-to-dom transformation. You have no choice. I'd recommend just stick to POI's native Row and Cell objects.
good way to represent a excel sheet value in Java
[ "", "java", "excel", "dto", "apache-poi", "" ]
I am engaged in developing a C++ mobile phone application on the Symbian platforms. One of the requirement is it has to work on all the Symbian phones right from 2nd edition phones to 5th edition phones. Now across editions there are differences in the Symbian SDKs. I have to use preprocessor directives to conditionally compile code that are relevant to the SDK for which the application is being built like below: ``` #ifdef S60_2nd_ED Code #elif S60_3rd_ED Code #else Code ``` Now since the application I am developing is not trivial it will soon grow to tens of thousands of lines of code and preprocessor directives like above would be spread all over. I want to know is there any alternative to this or may be a better way to use these preprocessor directives in this case. Please help.
I've been exactly where you are. One trick is, even if you're going to have conditions in code, don't switch on Symbian versions. It makes it difficult to add support for new versions in future, or to customise for handsets which are unusual in some way. Instead, identify what the actual properties are that you're relying on, write the code around those, and then include a header file which does: ``` #if S60_3rd_ED #define CAF_AGENT 1 #define HTTP_FILE_UPLOAD 1 #elif S60_2nd_ED #define CAF_AGENT 0 #if S60_2nd_ED_FP2 #define HTTP_FILE_UPLOAD 1 #else #define HTTP_FILE_UPLOAD 0 #endif #endif ``` and so on. Obviously you can group the defines by feature rather than by version if you prefer, have completely different headers per configuration, or whatever scheme suits you. We had defines for the UI classes you inherit from, too, so that there was some UI code in common between S60 and UIQ. In fact because of what the product was, we didn't have much UI-related code, so a decent proportion of it was common. As others say, though, it's even better to herd the variable behaviour into classes and functions where possible, and link different versions. [Edit in response to comment: We tried quite hard to avoid doing anything dependent on resolution - fortunately the particular app didn't make this too difficult, so our limited UI was pretty generic. The main thing where we switched on screen resolution was for splash/background images and the like. We had a script to preprocess the build files, which substituted the width and height into a file name, splash\_240x320.bmp or whatever. We actually hand-generated the images, since there weren't all that many different sizes and the images didn't change often. The same script generated a .h file containing #defines of most of the values used in the build file generation. This is for per-device builds: we also had more generic SIS files which just resized images on the fly, but we often had requirements on installed size (ROM was sometimes quite limited, which matters if your app is part of the base device image), and resizing images was one way to keep it down a bit. To support screen rotation on N92, Z8, etc, we still needed portrait and landscape versions of some images, since flipping aspect ratio doesn't give as good results as resizing to the same or similar ratio...]
Well ... That depends on the exact nature of the differences. If it's possible to abstract them out and isolate them into particular classes, then you can go that route. This would mean having version-specific implementations of some classes, and switch entire implementations rather than just a few lines here and there. You'd have * MyClass.h * MyClass\_S60\_2nd.cpp * MyClass\_S60\_3rd.cpp and so on. You can select which CPP file to compile either by wrapping the entire inside using #ifdefs as above, or my controlling at the build-level (through Makefiles or whatever) which files are included when you're building for various targets. Depending on the nature of the changes, this might be far cleaner.
Alternatives to preprocessor directives
[ "", "c++", "c-preprocessor", "" ]
I am a very experienced MS Sql developer, and a few new job positions are coming my way where I will be working with Oracle on a more daily basis. As with all the technologies I have learned, I want to know the best places and books to get started and up to speed with designing and developing with Oracle, but with pure C#. What resources are there for us Microsoft guys to jump in and go with Oracle? I realize there is oracle.com and asktom.oracle.com, as well as the mass amount of documentation on Oracle, I am looking more for a quick primer (setting up a server, getting some sample data to play with, etc...) rather than in depth sql vs. oracle technology comparisons. Thanks in advance.
[Oracle Developer Tools for Visual Studio](http://www.oracle.com/technology/tech/dotnet/tools/index.html) [White Paper: New 11g Features in Oracle Developer Tools (PDF)](http://www.oracle.com/technology/tech/dotnet/pdf/ODT11_whatsnew.pdf) [Oracle Database with Windows and .NET](http://www.oracle.com/technologies/microsoft/docs/idc-interop.pdf) [Oracle by Example: Building ASP.NET Web Applications with ODT](http://www.oracle.com/technology/obe/hol08/dotnet/asp/asp_otn.htm) [Oracle by Example: Building .NET Applications Using ODT](http://www.oracle.com/technology/obe/hol08/dotnet/buildnet/buildnet_otn.htm) [Oracle by Example: Debugging Oracle PL/SQL from Visual Studio](http://www.oracle.com/technology/obe/hol08/dotnet/debugging/debugging_otn.htm) [Oracle by Example: Using Oracle User-Defined Types with .NET and Visual Studio](http://www.oracle.com/technology/obe/hol08/dotnet/udt/udt_otn.htm) [Oracle Magazine: Build Applications with ODT and Oracle User-Defined Types](http://www.oracle.com/technology/oramag/oracle/08-may/o38net.html) [ODT FAQ: Answers to Common OTN Discussion Forum Questions](http://www.oracle.com/technology/tech/dotnet/col/odt_faq.html)
Try getting Tom Kyte's books [Expert one-on-one Oracle](https://rads.stackoverflow.com/amzn/click/com/1590595254) and [Effective Oracle by Design](https://rads.stackoverflow.com/amzn/click/com/0072230657). They're good intermediate-advanced level Oracle books that are well written by someone who knows the product well. Additionally, get to know the data dictionary. If you have aspirations to be anything more than a 'tools guy' in the Oracle world the data dictionary is your friend. It's also much better than the one in SQL Server. Finally, if you're moving to Oracle from a MS-Only world, get some background in unix and shell script programming. You will find this very useful when scripting automation infrastructure for Oracle systems, particularly if they sit on vanilla Unix installs. There is any amount of legacy Oracle/Unix kit still in production and vanilla installs of Solaris, AIX or HP/UX tend to be much more spartan than Linux. In the Unix/Oracle world you can't necessarily rely on being able to install Perl or Python. When you do have access to Perl or Python, get to know these as well. If you're into python, the best Oracle database interface library is [cx\_Oracle](http://cx-oracle.sourceforge.net/). I can't really vouch for any particular Perl infrastructure as I have never had occasion to use it for this type of work. [CPAN](http://www.cpan.org) is the canonical resource for add-on modules for Perl. In the (relatively unlikely) event that you're working on an Oracle/Windows environment(Oracle on Linux is more widely used in low-end Oracle deployments), good Windows distributions of both Perl and Python can be downloaded from [Activestate](http://www.activestate.com).
Learning Oracle for the first time
[ "", "c#", ".net", "sql-server", "oracle", "" ]
The script below will replace selected word in a textarea. But it only works on IE. Any idea how to make it work on Firefox? (The problem seems to lie in (document.all)? document.selection.createRange() : document.getSelection();) ``` <SCRIPT LANGUAGE="JavaScript"> <!--// var seltext = null; var repltext = null; function replaceit() { seltext = (document.all)? document.selection.createRange() : document.getSelection(); var selit = (document.all)? document.selection.createRange().text : document.getSelection(); if (selit.length>=1){ if (seltext) { repltext= prompt('Please enter the word to replace:', ' '); if ((repltext==' ')||(repltext==null)) repltext=seltext.text; seltext.text = repltext; window.focus() } } } //--> </SCRIPT> </HEAD> <BODY> <form name="f"> <textarea cols='40' rows='10' name='msg'></textarea> <input type="button" name="b" value="Replace" onClick="replaceit();"> </form> </BODY> ```
OK, so `document.getSelection()` returns a string in FF. String::text does not exist. So you can't set that. The basc idea of what you need to do (and it'll work in both browsers): Get the text area by its `id`--you'll need to set an `id` attribute on the textarea. Get the starting and ending positions of the selection. Then take three substrings: 0->start, start->end, end->string.length. Replace the middle substring with whatever they put in the prompt. Set the `text` of the textarea to your newly formed string. The exact how is up to you, I just gave you a flavor of the procedure.
The document.all bit is being used as a test to see if it's IE or not. The way it's written document.getSelection() is what would be used in Firefox and document.selection.createRange() in IE See <http://www.hscripts.com/tutorials/javascript/ternary.php> So the problem isn't document.all, but rather that the getSelection() isn't working. Not sure why exactly as that's not a construct I've used recently, but try window.getSelection() as per this: (and google for others if this doesn't do the trick) <http://www.webdeveloper.com/forum/archive/index.php/t-138944.html>
Javascript document.all and document.getSelection - Firefox alternative
[ "", "javascript", "cross-browser", "" ]