Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
An [answer](https://stackoverflow.com/questions/1272602/c-how-to-set-default-value-for-a-property-in-a-partial-class/1272647#1272647) in this [question](https://stackoverflow.com/questions/1272602/c-how-to-set-default-value-for-a-property-in-a-partial-class) made me wonder about the .NET framework design choices. The .NET framework has full support for [Partial classes, interfaces, and methods](http://msdn.microsoft.com/en-us/library/wa80x488.aspx). Is there a compelling reason that support for partial constructors was not added, in the same manner? This seems like it would simplify class construction within partial classes. For example, form constructors built by a designer in Windows Forms could have the form construction code directly in the constructor, split into two files. Partial "Initialize()" methods seem to be a somewhat common pattern, which could be simplified in this case. The only potential downside I can see would be the lack of determinism in the order of constructor calls, but in many cases, the ordering of the parts wouldn't matter. If it did, you could always avoid the partial constructor.
> The only potential downside I can see would be the lack of determinism in the order of constructor calls, but in many cases, the ordering of the parts wouldn't matter. If it did, you could always avoid the partial constructor. That part is more important to your question than it seems. If you really want to understand how the C# language is put together, one thing you can do is follow [Eric Lippert's](http://blogs.msdn.com/ericlippert/) blog. He works on the C# language for Microsoft, and talks a lot about choosing features with limited resources. Read his blog for a while and you'll start to get a sense of how features make it into the language. One factor he's mentioned on a few occasions is whether or not there's already a trivial work-around for the problem the feature would solve. So going back to the quoted portion of your question, you bring up two important points: 1. There's no good solution to the lack of determinism. If you can offer an elegant solution as part of your post you'll have a better case. 2. There's a trivial work-around already. Put those together and it's just not a winning feature.
I would vote yes, and I'll give a concrete example why. Many technologies that emit code using a generator (Linq To SQL for example) will/must emit a default constructor. However, often I will also want to do things in a constructor, such as wiring up to one of the data events. I can't do this without a partial constructor, since the default constructor is already tied up by the generated code, and I obviously don't want to alter the generated code to add my logic there.
Should C# add partial constructors?
[ "", "c#", ".net", "" ]
Why does this produce a compiler error: ``` class Foo { public Bar Baz = new Bar(this); } ``` But this does not: ``` class Foo { public Bar Baz; public Foo() { this.Baz = new Bar(this); } } ``` Conceptually the two are equivalent, are they not?
No, they're not quite equivalent... the variable initializer executes *before* any base class constructors are run. The body of the constructor executes *after* base class constructors are run. (This is different from Java, where variable initializers execute after base class constructors but before the constructor body.) Therefore it's safer to access `this` within the constructor body: you can be sure that the object is initialized at least in respect to its base class (and upwards). I *believe* that's the reasoning, anyway...
It is not logical to access the class that is not initialized yet. If you would be able to access this it would mean that Bar is already initialized that is not true till the constructor is not finished.
C# - why is it not possible to access 'this' in a field initializer?
[ "", "c#", "constructor", "" ]
I started writing my own small scaled framework and i have gotten to the templating part of it. So far i have been able to do simple variable replacing with the following code: ``` public function view($page, $vars) { if(!file_exists('system/views/' . $page . '.php')) { trigger_error("No Template found", E_USER_ERROR); } $tempArray = file_get_contents('system/views/' . $page . '.php'); foreach($vars as $key => $value) { $tempArray = str_replace('{' . $key . '}', $value, $tempArray); } print $tempArray; unset($tempArray); } ``` Which works fine, but what i am looking for now is if i wanted to loop to show unknown number of records from a database and i tried a coupler of ideas but none seem to have worked so far
First of all, you should rethink your variable rewriting. There's several cases where your method doesn't end as expected, when you have some dependencies between them. Additionaly, everything gets replaced regardless of a variable being in a loop or not. If you want something like {while(condition)}code{/while}, you need to be aware that recursion is also possible and therefore it's not as simple as matching a regex on it. A simple approach would be the following: * Find the start of a token (variable, whileloop) and remember the position where you find it * If it is a variable and you are in the most outer scope (not in a loop), process it by doing a replacement. Adjust your pointer so that you don't read the replacement afterwards to avoid replacing things that you don't want to. * If it is a loop + extract the condition between the brackets and store it somewher + additionaly, store the current location + Push the token onto a stack to remember the current recursion level. + Remove a token from the stack when you encounter the {/while} token. + Now proceed recursively, pushing all nested loop tokens on the stack and removing them as they end. Stop when you are at the outermost level again. + Evaluate the condition of the loop. As long as it is true, create new copies from the source text between the start token and the end token and process them by using recursion. + Concatenate the intermediate results and replace everything from {while} to {/while} with this concatenation. Adjust your pointer so that you're pointing after the loop and continue :) Hope that this helps. I know that it sounds a bit painful, but if you understand the concept, you should be able to do it (although it is not super-efficient and compiling template engines like smarty will always be in advance since they parse the template file just once and compile it to PHP code). @Daff: you could find the tokens with regular expressions, but using one regex to match on a whole loop construct doesn't work due to the recursions (unless your regex has a recursive extension).
As Zed already said there are lots of templating languages for PHP, the most popular one being [Smarty](http://www.smarty.net/) and I don't know if it would really make sense to reinvent the wheel except for learning purposes. The loops you want to do are actually way more complex than just replacing elements. I'm pretty sure you can somehow do it with lots of regular expressions, but at some point you will end up with writing your own scripting language (like the Smarty guys did) with parsing your view file, creating a Syntax tree, evaluating it and compile it to a new PHP file. This is quite complex so I recommend to either use an existing templating engine or use PHP as the templating language itself (if strictly folowing the [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) pattern that might work even though there are lots of discussions about that). With a regular expression you could parse everything between {for ...}{/for} to access an item with a given variable name, where after {for and } a definition of your variable occurrs and after } and before {/for} your html definition. That would be something like a foreach loop which you can't even nest into each other. ``` {for item=$varname} <p>{item.othervalue}</p> {/for} ```
using a loop in a template
[ "", "php", "templating", "" ]
I am trying to use the TFSSnapin in PowerShell from C# code using System.Management.Automation from the PowerShell SDK, however I would like to compile it using "AnyCPU". When I try debugging it in any CPU I get the "No Plugins Registered" error, I try debugging it in x86 mode and it works just fine. Is there anyway to get the Plugins registered on x64 PowerShell so I can use AnyCPU? Or am I just out of luck?
No. And it can't be changed until TFS 2010 Beta 2 at earliest. See: [Why is the TFS Powershell snapin marked 32-bit only?](http://richardberg.net/blog/?p=51)
This is now possible Execute the following line in your 64-bit PowerShell command prompt ``` copy HKLM:\SOFTWARE\Wow6432Node\Microsoft\PowerShell\1\PowerShellSnapIns\Microsoft.TeamFoundation.PowerShell HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\Microsoft.TeamFoundation.PowerShell -r ``` Then add the PSSnapin for `Microsoft.TeamFoundation.PowerShell`.
Is there no TFS Snapin for PowerShell on x64?
[ "", "c#", "tfs", "powershell", "" ]
I'm trying to build a C# application, which uses Fiddler. I saw in the documentation somewhere, that there is supposed to be a function Fiddler.Application.Start or something like that. However, I can't find it. I'd prefer not to write a fiddler extension, because I think it will be more powerful to integrate fiddler into my app. Does anyone know how to do this?
"Please note: FiddlerCore is currently undergoing a limited, Microsoft-Internal alpha. At present, there is no timeline for a broader release." <http://fiddler.wikidot.com/fiddlercore> So, it appears there is no way to get FiddlerCore unless you work for Microsoft.
You're really asking about [FiddlerCore](http://www.telerik.com/fiddler/fiddlercore), which is different than Fiddler. You cannot replicate FiddlerCore by simply wrapping Fiddler.exe. If you want to automate Fiddler, simply launch it with Process.Start. You can send commands to the FiddlerScript engine using the [ExecAction executable](http://www.fiddlerbook.com/Fiddler/dev/#automation). Incidentally, neither Fiddler nor FiddlerCore is a COM object.
Can I start fiddler from C#?
[ "", "c#", "fiddler", "" ]
I could really use a tri-stated checkbox in Java. It sounds like a simple thing, but I've only seen really [ugly implementations](http://forums.sun.com/thread.jspa?threadID=593755&messageID=3116647) [note: link now broken]. Three radio buttons just take up too much real estate and will probably be confusing for the users in my case. It's basically for a search dialog. I need true, false or "don't care" options. Is there a different technique that people use?
I found a way to make a tri-state checkbox by simply adding a listener: ``` public class TriStateActionListener implements ActionListener{ final protected Icon icon; public TriStateActionListener(Icon icon){ this.icon=icon; } public static Boolean getState(javax.swing.JCheckBox cb){ if (cb.getIcon()==null) return null; if (cb.isSelected()) return true; else return false; } public void actionPerformed(ActionEvent e) { javax.swing.JCheckBox cb=(javax.swing.JCheckBox)e.getSource(); if (!cb.isSelected()){ cb.setIcon(icon); } else if (cb.getIcon()!=null){ cb.setIcon(null); cb.setSelected(false); } } } ``` Then in the application code, it's just a single line: ``` jCheckBox1.addActionListener(new TriStateActionListener(getResourceMap().getIcon("TriStateIcon"))); ``` After all the feedback, I'm thinking a drop-down may be a better choice. But, I wanted to share my code here for everyone else.
Use a drop-down.
Tristate Checkboxes in Java
[ "", "java", "swing", "checkbox", "" ]
In Visual Studio 2008, if I have a long line of code, how can i get that to breakup into multiple lines? ``` public static void somemethod(param1, param2, param3, more params etc...) ``` How can I make this 1 line of code span 2 or 3 lines?
Hit the enter key. ``` public static somemethod(param1, param2, param3, more params etc...) ``` ...is perfectly valid.
C# is not line based, so you can split the statements anywhere but inside an identifier: ``` public static void somemethod( int param1, int param2, int param3, more params etc... ) ``` You can even write something like: ``` for ( int i = 0 ; i < 10 ; i ++ ) { Console . WriteLine ( i ) ; } ```
Break Long code lines in Visual Studio 2008
[ "", "c#", "" ]
Is there a naming convention or maybe some guideline on how to name function parameters? Since forever, I have been doing it like this: ``` function divide( $pDividend, $pDivisor ) { ... } ``` That way I'll always know which variables were passed as parameters. (This one's PHP, but it should be applicable to most programming languages) Is there one major reason against this? Is there a better way to do this or is it probably best to just avoid such naming schemes?
If : 1. your functions/methods are well written and short (as they should be) 2. the variable names are descriptive enough This practice is not needed. If you need this, it means that the code written is not readable enough (functions/methods too long), cryptic variable/function names, bad OO practices, shortcuts, code debts, etc. :) So it would be a signal that the code needs to be refactored/improved.
I think taking the advice of Code Complete regarding naming -anything- would be justified it's whole chapter 11 is on naming variables properly): * Don't name it j, k, i, m, n (unless it's just for an iteration) or "placeholder" or "test". When the "test" works, I often don't take the time to rename the variable wherever it's been listed. * Call it a **descriptive** name that's separate from the code's function ie "EmployeeComments" not "XMLEmp\_Comment\_File" because a lot of that information (XML, external file) could change, but that the program's working with "Employee Comments" won't * Keep it as **broad and human readable** as possible so you're coding in English (or your language) not $j=$k/sqrt($pi); or something equally unintelligible. As for parameters specifically, I've never used the P notation. I like the idea, but if you named them right wouldn't it be clear they were the parameters for the function?
Naming conventions for function parameter variables?
[ "", "php", "parameters", "function", "naming-conventions", "" ]
How exactly do RAM test applications work, and is it possible to write such using C# (Example)?
You basically write to the RAM, read it back and compare this with the expected result. You might want to test various patterns to detect different errors (always-0, always-1), and run multiple iterations to detect spurious errors. You can do this in any language you like, as long as you have direct access to the memory you want to test. If you want to test physical RAM, you could use P-invoke to reach out of the CLR. However, this won't solve one specific problem if your computer is based on the [Von Neumann architecture](http://en.wikipedia.org/wiki/Von_Neumann_architecture): The program that tests the memory is actually located inside the very same memory. You would have to relocate the program to test all of it. The German magazine c't found a way around this issue for their [Ramtest](http://www.heise.de/software/download/ct_ramtest/3666): They run the test from video memory. In practice, this is impossible with C#.
Most use low-level hardware access to write various bit patterns to memory, then read them back to ensure they are identical to the pattern written. If not, the RAM is probably faulty. They are generally written in low-level languages (assembler) to access the RAM directly - this way, any caching (that could possibly affect the result of the test) is avoided. It's certainly possible to write such an application in C# - but that would almost certainly prevent you from getting direct bit-level access to the memory, and hence could never be as thorough or reliable as low-level memory testers.
How do RAM Test Applications work? C# Example?
[ "", "c#", ".net", "algorithm", "" ]
I like Eclipse's build path features, but would like to keep it in sync with my ant `build.xml`. Is there a way to either automatically import the Eclipse build path from a text file, or export the Eclipse build path to a text file, so I can use that file from ant? (if I can get to a text file, I know I can figure out how to get ant to use that file as its javac build path)
> Is there a way to either automatically import the Eclipse build path from a text file, or **export the Eclipse build path to a text file**, so I can use that file from ant? The Eclipse build path already is a text file (.classpath): ``` <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src"/> <classpathentry kind="lib" path="lib/ojdbc14_g.jar"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="output" path="classes"/> </classpath> ```
Maybe **[ant4eclipse](https://web.archive.org/web/20100102232151/http://ant4eclipse.sourceforge.net:80/ant-for-eclipse-home.html)** is the tool (plugin) you need. [![alt text](https://i.stack.imgur.com/lBhP8.gif)](https://i.stack.imgur.com/lBhP8.gif) (source: [sourceforge.net](http://ant4eclipse.sourceforge.net/images/ant-for-eclipse-logo-small.gif)) > The aim of the `ant4eclipse` project is to avoid (or at least: to reduce) the redundancy of Eclipse and Ant configurations. > More precisely: it consists of **Ant tasks that are able to read and work with some of Eclipse's configuration files**. With these tasks you're able to: > > * Setup classpathes as defined in Eclipse' .classpath-file > * checkout complete workspaces as it's possible with the Team Project Set feature of eclipse > * run your Java applications as you have defined them in an Eclipse Launch Configuration > > With all these tasks you're able to create a complete automatic build system that starts with checking out all required projects from CVS, builds all projects in the correct order with classpath settings as specified in Eclipse, and to launch your applications as they are specified in Eclipse. > And the best of it: if you or someone else changes a configuration in Eclipse, those changes are immediately visible to your buildfiles - without changing one line of code!
export/import Eclipse build path
[ "", "java", "eclipse", "path", "" ]
I have tried NetBeans for some time, but have not made my final move yet. I need to be able to import codestyle settings from Idea or Eclipse. Anyone know it that is possible? Or if some plugins allow that?
No, there's not such thing. You'll have to edit font and color settings in a hidden folder or create a plugin. Can IDEA import NetBeans color schemes, can Eclipse do the same?
I am not sure whether this covers all codestyle settings in your existing IDE (Eclipse) and future IDE (Netbeans) but you can define `.editorconfig` file to maintain consistent coding styles between different IDEs. It has plugins for all major IDEs. <http://editorconfig.org/> Besides, it really helps you if you have other project members using various IDEs.
Can I import codestyles into Netbeans?
[ "", "java", "netbeans", "" ]
Writing a templated function, I declared: ``` template <typename T> T invertible(T const& container, T::size_type startIndex, T::size_type endIndex); ``` Compiling with g++ 4.0.1 I got the error: ``` error: 'T::size_type' is not a type ```
As you found out T::size\_type needs to be prefixed with typename. Why? From ["C++ Templates: The Complete Guide"](http://www.josuttis.com/tmplbook/) > The language definition resolves this problem by specifying that in general a dependent qualified name does *not* denote a type unless that name is prefixed with the keyword typename. > > ... The typename prefix to a name is *required* when the name > > 1. Appears in a template > 2. Is qualified > 3. Is not used as a list of base class specifications or in a list of member initializations introducing a constructor definition > 4. Is dependent on a template parameter > > Furthermore the typename prefix is *not allowed* unless at least the first three previous conditions hold.
You need to add typename. I.e. ``` template <typename T> T invertible(T const& container, typename T::size_type startIndex, typename T::size_type endIndex); ``` Without having any information on your type T, the compiler needs to know that T::size\_type designates a type. From the standard, section 14.6.2: > A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword `typename`.
g++ "is not a type" error
[ "", "c++", "gcc", "templates", "" ]
Does sqlite support the sql function "if" in the select statement? for example ``` select if( length( a ) > 4 , a , ' ') as b from foo ``` which would return a if the length was over 4 chars long. or else it would return ' ' as b If it does support a condition in the select what is the syntax is should be using? I have checked <http://sqlite.org/lang_corefunc.html> but I can't see it.
See the [case](http://www.sqlite.org/lang_expr.html#case) expression. > A CASE expression serves a role similar to IF-THEN-ELSE in other programming languages. For your example ``` select case when length(a) > 4 then a else '' end as b from foo ```
You can use [case](http://sqlite.org/lang_expr.html) for that: ``` select case when length(a)>4 then a else ' ' end from foo; ```
Does sqlite support any kind of IF(condition) statement in a select
[ "", "sql", "sqlite", "" ]
I am currently deserializing JSON using XStream, and it has been working great. However, when I have JSON string like the following ``` { key1: { an_object: { something: 'foobar' } }, key2: { another_object: { data: 'hi' } } ``` most notably it doesn't have a root node, I'm not sure how to parse it. Basically, I want the opposite of DROP\_ROOT\_NODE for the deserialization.
The short answer is "you can't". XStream needs to know what class to instantiate, it gets that knowledge from JSON (or XML) data. Class name can be aliased, but it can not be omitted. You can work around by: 1. Manually wrapping your JSON string with root node containing your class name (or alias) 2. Writing your own reader that would do it for you. However, in this case you'll still need to pass your class name (alias) to that reader either explicitly or by convention (e.g. always prepend 'root' but then configure it as alias to your class in XStream instance) - so I don't think this is any cleaner than #1.
I know this is an old question, but I'll post my solution after a whole morning googling. The answer is to provide dummy root node (start and termination tags). In order to accomplish this, one of your best friends is SequenceInputStream: My code is the following: ``` reader = new XppDriver().createReader(new SequenceInputStream( Collections.enumeration(Arrays.asList( new InputStream[] { new ByteArrayInputStream("<PlatformAuditEvents>".getBytes()), new FileInputStream(file), new ByteArrayInputStream("</PlatformAuditEvents>".getBytes()) })) )); in = xstream.createObjectInputStream(reader); ``` Here I've mixed three InputStream objects, being the first and third ones those providing the required tags missing in the file processed. This solution was inspired by this [SO Question](https://stackoverflow.com/questions/6640756/parsing-an-xml-stream-with-no-root-element). Hope this helps someone.
XStream parse JSON with no root node
[ "", "java", "json", "xstream", "" ]
Using PHP, given a string such as: `this is a <strong>string</strong>`; I need a function to strip out ALL html tags so that the output is: `this is a string`. Any ideas? Thanks in advance.
PHP has a built-in function that does exactly what you want: [`strip_tags`](http://www.php.net/strip_tags) ``` $text = '<b>Hello</b> World'; print strip_tags($text); // outputs Hello World ``` If you expect broken HTML, you are going to need to load it into a DOM parser and then extract the text.
What about using [strip\_tags](http://php.net/strip_tags), which should do just the job ? For instance *(quoting the doc)* : ``` <?php $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>'; echo strip_tags($text); echo "\n"; ``` will give you : ``` Test paragraph. Other text ``` Edit : but note that strip\_tags doesn't validate what you give it. Which means that this code : ``` $text = "this is <10 a test"; var_dump(strip_tags($text)); ``` Will get you : ``` string 'this is ' (length=8) ``` (Everything after the thing that looks like a starting tag gets removed).
What is the best way to strip out all html tags from a string?
[ "", "php", "html", "string", "" ]
In my foreach loop I would like to stop after 50 items, how would you break out of this foreach loop when I reach the 50th item? Thanks ``` foreach (ListViewItem lvi in listView.Items) ```
``` int processed = 0; foreach(ListViewItem lvi in listView.Items) { //do stuff if (++processed == 50) break; } ``` or use LINQ ``` foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50)) { //do stuff } ``` or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.) ``` for(int i = 0; i < 50 && i < listView.Items.Count; i++) { ListViewItem lvi = listView.Items[i]; } ```
Why not just use a regular for loop? ``` for(int i = 0; i < 50 && i < listView.Items.Count; i++) { ListViewItem lvi = listView.Items[i]; } ``` Updated to resolve bug pointed out by Ruben and Pragmatrix.
C# Break out of foreach loop after X number of items
[ "", "c#", "foreach", "" ]
I have a C# method that takes a string as an argument, that string contains the name of a static method e.g ``` "MyClass.GetData" ``` Is it possible to run that method from the value passed in the string?
yes you can using System.Reflection --- ``` CallStaticMethod("MainApplication.Test", "Test1"); public static void CallStaticMethod(string typeName, string methodName) { var type = Type.GetType(typeName); if (type != null) { var method = type.GetMethod(methodName); if (method != null) { method.Invoke(null, null); } } } public static class Test { public static void Test1() { Console.WriteLine("Test invoked"); } } ```
Yes You can use reflection to find the method and invoke with proper arguements.
Run a method thats name was passed as a string
[ "", "c#", "" ]
I'm hacking a little template engine. I've a class (pompously named the *template compiler*) that produce a string of dynamically generated code. for instance : ``` def dynamic_function(arg): #statement return rendered_template ``` At rendering time, I call the built-in function *exec* against this code, with a custom *globals* dictionary (in order to control as mush as possible the code inserted into the template by a potential malicious user). But, I need to cache the compiled template to avoid compiling it each execution. I wonder if it's better to store the string as plain text and load it each time or use *compile* to produce code\_object and store that object (using the shelve module for example). Maybe it worth mentioning that ultimately I would like to make my template engine thread safe. Thank for reading ! Thomas edit : as S.Lott is underlining better doesn't have a sense itself. I mean by better faster, consume less memory simpler and easier debugging. Of course, more and tastier free coffee would have been even better.
Personally, i'd store text. You can look at text with an editor or whatever, which will make debugging and mucking about easier. It's also vastly easier to write unit tests for, if you want to test that the contents of the cache file are what you expect. Later, *if* you find that your system isn't fast enough, and *if* profiling reveals that parsing the cached templates is taking a lot of time, you can try switching to storing bytecode - but only then. As long as the storage mechanism is properly encapsulated, this change should be fairly painless.
You don't mention where you are going to store these templates, but if you are persisting them "permanently", keep in mind that Python doesn't guarantee byte-code compatibility across major versions. So either choose a method that does guarantee compatibility (like storing the source code), or also store enough information alongside the compiled template that you can throw away the compiled template when it is invalid. The same goes for the marshal module, for example: a value marshaled with Python 2.5 is not promised to be readable with Python 2.6.
Storing dynamically generated code as string or as code object?
[ "", "python", "exec", "" ]
I get the basic principles of closures and lambda expressions but I'm trying to wrap my mind around what is happening behind the scenes and when it is/isn't practical to use them in my code. Consider the following example, that takes a collection of names and returns any names that begin with the letter C... ``` static void Main(string[] args) { List<string> names = new List<string>(); names.AddRange(new string[] { "Alan", "Bob", "Chris", "Dave", "Edgar", "Frank" }); names.FindAll(x => x.StartsWith("C")).ForEach( i => Console.WriteLine(i)); } ``` First, is there a more direct way that I could have written this expression? Secondly, isn't "FindAll" going to allocate memory for a new collection that holds the matching items? I definitely see that the syntax is more elegant, but I want to make sure I'm not walking into performance issues later down the road when working with larger collections. Does the compiler do some optimization voodoo behind the scenes that makes my concerns invalid?
Yes, FindAll will create a new list. You want "Where", which will return an IEnumerable object that knows how to loop over your existing list: ``` foreach (string name in names.Where(n => n.StartsWith("C") ) ) { Console.WriteLine(name); } ``` But there's no closure in that code, because there's no local variable to capture.
The other answers that say to use "Where" are correct. An additional point: you can also use query comprehension syntax to make the "Where" look nicer: ``` var query = from name in names where name.StartsWith("C") select name; foreach(var result in query) Console.WriteLine(result); ``` Note that as a stylistic concern, I recommend that expressions have no side effects and statements always have side effects. Therefore I personally would use a foreach *statement* rather than a ForEach *subexpression* to perform the output side effect. Many people disagree with this, but I think it makes the code more clear.
Closures and Lambda in C#
[ "", "c#", "lambda", "closures", "" ]
I'm trying to change the size of an image with JavaScript. The jS file is separate from the HTML page. I want to set the height and width of an image in the JS file. Any good ways on doing this?
Once you have a reference to your image, you can set its height and width like so: ``` var yourImg = document.getElementById('yourImgId'); if(yourImg && yourImg.style) { yourImg.style.height = '100px'; yourImg.style.width = '200px'; } ``` In the html, it would look like this: ``` <img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/> ```
You can change the actual width/height attributes like this: ``` var theImg = document.getElementById('theImgId'); theImg.height = 150; theImg.width = 150; ```
Change image size with JavaScript
[ "", "javascript", "image", "" ]
My question is very similar to this one [How to reference a custom field in SQL](https://stackoverflow.com/questions/89820/how-to-reference-a-custom-field-in-sql) I have the following query: ``` SELECT * , (SELECT COUNT( id ) FROM cms_store_items WHERE speaker = cms_store_items_speakers.id ) AS count FROM cms_store_items_speakers LIMIT 0 , 30 ``` I need to add a WHERE clause that looks like `WHERE count > 0` but when I do I get the error `Unknown column 'count' in 'where clause'` is there anyway for me to reference the custom field in my where clause without duplicating logic? I could just place the logic for the where clause in my code but I don't want to send what may well be more then 1000 rows to the app if not needed, it just seems like a waste of resources.
Well, to do this strictly the way you're doing it: ``` select * from ( SELECT * , (SELECT COUNT( id ) FROM cms_store_items WHERE speaker = cms_store_items_speakers.id ) AS count FROM cms_store_items_speakers ) a where a.count > 0 LIMIT 0 , 30 ``` It would probably be better to do the following, though. It makes good use of the [`having`](http://www.w3schools.com/SQL/sql_having.asp) clause: ``` select s.id, s.col1, count(i.speaker) as count from cms_store_items_speakers s left join cms_store_items i on s.id = i.speaker group by s.id, s.col1 having count(i.speaker) > 0 limit 0, 30 ```
You can using `HAVING` clause instead: ``` ... ) AS count FROM cms_store_items_speakers HAVING count > 0 LIMIT 0 , 30 ``` `HAVING` is like `WHERE` but it is able to work on columns which are computed. **Warning:** `HAVING` works by pruning results **after** the rest of the query has been run - it is not a substitute for the `WHERE` clause.
Using a custom field in WHERE clause of SQL query
[ "", "sql", "mysql", "" ]
im using the following method > ``` > [DllImport("kernel32.dll", SetLastError=true)] > static extern int GetProcessId(IntPtr hWnd); > ``` to try and get the processId for a running process and the only information I have is the HWND. My problem is that it is always returning error code 6 which is ERROR\_INVALID\_HANDLE. I thought i might change the parameter to be of type int but that also didnt work. Im not able to enumerate the running processes because there may be more than 1 instance running at any one time. Can anyone see if i am doing anything wrong? NB: The process is spawned from an automation object exposed to the framework and only provides the HWND property. Perhaps there is another way to get the processID seeing as the code i wrote was responsible for running it in the first place? My code looks something similar to this... > AutomationApplication.Application > extApp = new > AutomationApplication.Application(); > extApp.Run(); ...
What is the 'AutomationApplication.Application' class? Did you write that? Does .Run() return a PID?
[GetProcessId](http://msdn.microsoft.com/en-us/library/ms683215.aspx) gets the process ID when given a process handle, not a window handle. It's actually: ``` [DllImport("kernel32", SetLastError = true)] static extern int GetProcessId(IntPtr hProcess); ``` If you've got a window handle, then you want the [GetWindowThreadProcessId](http://msdn.microsoft.com/en-us/library/ms633522.aspx) function: ``` [DllImport("user32")] static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); ``` This returns the thread id, and puts the process id in the out-param.
Unable to extract processID from GetProcessId(.. hWnd) (pInvoke)
[ "", "c#", "process", "automation", "pinvoke", "handle", "" ]
I'm having a bit of trouble with one particular issue using JPA/Spring: How can I dynamically assign a schema to an entity? We have TABLE1 that belongs to schema AD and TABLE2 that is under BD. ``` @Entity @Table(name = "TABLE1", schema="S1D") ... @Entity @Table(name = "TABLE2", schema="S2D") ... ``` The schemas may not be hardcoded in an annotation attribute as it depends on the environment (Dev/Acc/Prd). (In acceptance the schemas are S1A and S2A) How can I achieve this? Is it possible to specify some kind of placeholders like this: ``` @Entity @Table(name = "TABLE1", schema="${schema1}") ... @Entity @Table(name = "TABLE2", schema="${schema2}") ... ``` so that schemas are replaced based on a property file residing in the environment? Cheers
I had the same problem I solved that with a persistence.xml in which I refer to the needed orm.xml files within I declared the db shema ``` <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0" > <persistence-unit name="schemaOne"> . . . <mapping-file>ormOne.xml</mapping-file> . . . </persistence-unit> <persistence-unit name="schemaTwo"> . . . <mapping-file>ormTwo.xml</mapping-file> . . . </persistence-unit> </persistence> ``` now you can create a EntityManagerFactory for your special schema ``` EntityManagerFactory emf = Persistence.createEntityManagerFactory("schemaOne"); ```
One thing you can do if you know at deployment is to have 2 orm.xml files. One for schema1 and one for schema2 and then in the persistence.xml you have 2 persistence-units defined. Putting annotations is an anti-pattern if needing to change things like schema
JPA using multiple database schemas
[ "", "java", "database", "spring", "jpa", "schema", "" ]
I'm working on a program that creates 2000 directories and puts a file in each (just a 10KB or so file). I am using mkdir to make the dirs and ofstream (i tried fopen as well) to write the files to a solid state drive (i'm doing speed tests for comparison). When I run the code the directories are created fine but the files stop writing after 1000 or so have been written. I've tried putting a delay before each write in case it was some kind of overload and also tried using fopen instead of ofstream but it always stops writing the files around the 1000th file mark. this is the code that writes the files and exits telling me which file it failed on. ``` fsWriteFiles.open(path, ios::app); if(!fsWriteFiles.is_open()) { cout << "Fail at point: " << filecount << endl; return 1; } fsWriteFiles << filecontent; fsWriteFiles.close(); ``` Has anyone had any experience of this or has any theories? Here's the full code: This code creates a 2 digit hex directory from a random number then a 4 digit hex directory from a random number then stores a file in that directory. It exits with a 'fail at point' (a cout I've added) after writing 1000ish files. This indicates that it cannot create a file, but it should have already checked that the file does not exist. Sometimes it fails on 0 having hit the second from bottom line (else clause for file already existing). any help appreciated, I feel that it is to do with the files i'm trying to create already existing but that have somehow slipped by my file existence check. Is there a way to get an error message for a failed file creation attempt? ``` int main() { char charpart1[3] = ""; char charpart3[5] = ""; char path[35] = ""; int randomStore = 0; //Initialize random seed srand(time(NULL)); struct stat buffer ; //Create output file streams ofstream fsWriteFiles; ifstream checkforfile; //Loop X times int dircount = 0; while(dircount < 2000) { path[0] = '\0'; //reset the char array that holds the path randomStore = rand() % 255; sprintf(charpart1, "%.2x", randomStore); randomStore = rand() % 65535; sprintf(charpart3, "%.4x", randomStore); //Check if top level dir exists, create if not strcat(path, "fastdirs/"); strcat(path, charpart1); DIR *pdir=opendir(path); //If the dir does not exist create it with read/write/search permissions for owner // and group, and with read/search permissions for others if(!pdir) mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); //Check if 3rd level dir exists, create if not strcat(path, "/"); strcat(path, charpart3); DIR *pdir3=opendir(path); if(!pdir3) mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); strcat(path, "/"); strcat(path, charpart3); strcat(path, ".txt"); //Write the file if it does not already exist checkforfile.open(path, fstream::in); if (checkforfile.is_open() != true) { fsWriteFiles.open(path, ios::app); if(!fsWriteFiles.is_open()) { cout << "Fail at point: " << dircount << "\n" << endl; return 1; } fsWriteFiles << "test"; fsWriteFiles.flush(); fsWriteFiles.close(); dircount ++; //increment the file counter } else { cout << "ex"; checkforfile.close(); } } } ```
You open directories with opendir() but never close them with closedir() - I suspect there is a resource limit there too.
just want to make sure you're aware of [boost::filesystem](http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/index.htm). It might simplify your code considerably. ``` #include "boost/filesystem.hpp" // includes all needed Boost.Filesystem declarations #include <iostream> // for std::cout using boost::filesystem; // for ease of tutorial presentation; // a namespace alias is preferred practice in real code path my_path( "some_dir/file.txt" ); remove_all( "foobar" ); create_directory( "foobar" ); ofstream file( "foobar/cheeze" ); file << "tastes good!\n"; file.close(); if ( !exists( "foobar/cheeze" ) ) std::cout << "Something is rotten in foobar\n"; ```
writing files and dirs using C++
[ "", "c++", "mkdir", "ofstream", "" ]
I am using this: ``` SELECT * FROM sys.dm_exec_query_stats s CROSS APPLY sys.dm_exec_sql_text( s.sql_handle ) t ORDER BY s.max_elapsed_time DESC ``` to get the longest running queries on the server level. How do I get the longest running queries per database? I would like to focus only on one database at a time.
The BOL entry for [`sys.dm_exec_query_stats`](http://msdn.microsoft.com/en-us/library/ms189741(SQL.90).aspx) mentions [`sys.dm_exec_query_plan`](http://msdn.microsoft.com/en-us/library/ms189747(SQL.90).aspx) ``` SELECT * FROM sys.dm_exec_query_stats s CROSS APPLY sys.dm_exec_sql_text( s.sql_handle ) t CROSS APPLY sys.dm_exec_query_plan(s.plan_handle) foo WHERE foo.dbid = DB_ID('My_DB') ORDER BY s.max_elapsed_time DESC ``` Edit: I've not tried it. I generally worry about server load...
``` SELECT * FROM database1.dbo.table JOIN database2.dbo.table ``` In which database did the query above run? What if the current context at the moment of execution was database3? What if it was executed once in database4 and once in database5? The idea is that execution plans are not tied to a database.
Longest running query per database
[ "", "sql", "sql-server", "sql-server-2005", "" ]
In My Windows based project set, of XML files are located at "c:\TestProj\XmlSource". My mission is to programmatically create schema files for those xml files. I am executing the code as follow: string directoryName = @"c:\TestProj\XmlSource"; ``` foreach (string foundName in System.IO.Directory.GetFiles(directoryName)) { Process.Start(@"c:\TestProj\xsd.exe", Path.Combine(directoryName, foundName)); } ``` The code is working fine and the XSDs are generated.The problem is ,the XSDs are generated in Debug folder. I want to create those XSDs in XSD folder( c:\TestProj\XmlSource\XSD).How can I force the XSD.exe to produce the output to the desired folder. I am in a bit confusion to handle the `outputDir` switch.
``` string directoryName = @"c:\TestProj\XmlSource"; foreach (string foundName in System.IO.Directory.GetFiles(directoryName)) { Process.Start(@"c:\TestProj\xsd.exe", Path.Combine(directoryName, foundName) + " /o:c:\TestProj\XmlSource\XSD"); } ```
Try ``` foreach (string foundName in System.IO.Directory.GetFiles(directoryName)) { Process.Start(@"c:\TestProj\xsd.exe", string.Concat(Path.Combine(directoryName, foundName), " /out:OutputFolder"); } ```
Clarification in getting the desired Directory
[ "", "c#", "xsd.exe", "" ]
I am new to Oracle (though familiar with SQL) and have to write a fairly complex query where a value derived from the current date is used many times. Rather than calculate the value each time, it would seem obvious to declare a constant for the purpose. However, when I then try to use my DateIndex constant in the subsequent SELECT statement (which I wish to return values based on "DateIndex"), the parser tells me that it is exepcting SELECT INTO. What I have (simplified to the lowest form) is... ``` DECLARE DateIndex CONSTANT NUMBER(10,0) := 24; BEGIN SELECT DateIndex FROM DUAL; END; ``` Is it only possible to use constants when selecting into a table rather than returning results? Seems very odd. Note that I do **not** have write permissions on the database. Many thanks for any assistance.
Your code is not Oracle SQL but PL/SQL. In PL/SQL the result of a query has to be assigned to a variable. So you either have have to use a "select into clause" if you expect exactly one result, or you use a cursor. In SQL on the other hand you can't declare a constant. You can sometimes work around this limitation by using an inline view like so ``` select something-complex-here, x.pi from sometable, ( select 3.1415 as pi, 1234 other_constant from dual ) ```
I prefer the following use of `WITH` and the DUAL table: ``` WITH const AS ( SELECT 3.14 AS pi, 1 AS one FROM DUAL ) SELECT * FROM sometable t, const WHERE t.value = const.pi; ``` This lets you define constants before the use in a statement and the actual statement is not cluttered with subselects.
Constants in Oracle SQL query
[ "", "sql", "database", "oracle", "constants", "" ]
Does anyone know how I would get a DOM instance (tree) of an XML file in Python. I am trying to compare two XML documents to eachother that may have elements and attributes in different order. How would I do this?
Personally, whenever possible, I'd start with [elementtree](http://docs.python.org/library/xml.etree.elementtree.html) (preferably the C implementation that comes with Python's standard library, or the [lxml](http://codespeak.net/lxml/) implementation, but that's essentialy a matter of higher speed, only). It's not a standard-compliant DOM, but holds the same information in a more Pythonic and handier way. You can start by calling `xml.etree.ElementTree.parse`, which takes the XML source and returns an element-tree; do that on both sources, use `getroot` on each element tree to obtain its root element, then recursively compare elements starting from the root ones. Children of an element form a sequence, in element tree just as in the standard DOM, meaning their order is considered important; but it's easy to make Python sets out of them (or with a little more effort "multi-sets" of some kind, if repetitions are important in your use case though order is not) for a laxer comparison. It's even easier for attributes for a given element, where uniqueness is assured and order is semantically not relevant. Is there some specific reason you need a standard DOM rather than an alternative container like an element tree, or are you just using the term DOM in a general sense so that element tree would be OK? In the past I've also had good results using [PyRXP](http://www.reportlab.org/pyrxp.html), which uses an even starker and simpler representation than ElementTree. However, it WAS years and years ago; I have no recent experience as to how PyRXP today compares with lxml or cElementTree.
Some solutions to ponder: * [minidom](http://docs.python.org/library/xml.dom.minidom.html) * [amara](http://pypi.python.org/pypi/Amara) (xml data binding)
Getting DOM tree of XML document
[ "", "python", "xml", "dom", "" ]
We want to search for a string (ie. "Hello World") in all our database that has about 120 tables. We thought about doing a dump like mysql dump but it came out in a weird bak format. The search should be done in each column for each table. Is this possible with any type of script, or this is harder than it sounds to me?
[How to search all columns of all tables in a database for a keyword](http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm)
No it possible and easy to write a script to do this. Suggestions: I think you have to use some cursors and use some of these objects to write your script 1. sys.databases 2. INFORMATION\_SCHEMA.TABLES or sys.tables 3. INFORMATION\_SCHEMA.COLUMNS or sys.columns Once you have these things in place, searching Hello World under all columns would be more simple
How to search for a specific string in all columns within all tables of a SQL Server database?
[ "", "sql", "sql-server", "" ]
I was looking for a rich text editor with support for export/import to Html. All the available controls I found are Silverlight controls. Someone [asked](https://stackoverflow.com/questions/47343/do-you-know-any-wpf-based-text-editor-control) in StackOverflow about WPF text editor, and the selected answer was: > A possible place to start, given the overlap between WPF and Silverlight is the Silverlight Rich Text Editor. As far as I know, it is not possible to use Silverlight controls inside WPF application. Using browser control to host the Silverlight control seem to me like a really bad option. Is it possible to use Silverlight in WPF application? Otherwise, is there any descent WPF rich text editor out there?
I think the poster on the Stackoverflow question was suggesting recompiling the source to target WPF. This might imply fixing up / replacing certain bits of code, but having the source to a SL control makes it conceivable to port it to WPF.
No, it is not possible to use Silverlight in a WPF application. They are very different technologies. As for a "decent" rich text editor, there are plenty of decent ones (the `RichTextBox` that is built into WPF is more than decent). It sounds like what you really need is a rich text editor that has HTML support. If import/export of HTML is all you need, then it sounds like something you could easily add by inheriting from `RichTextBox` and adding some functionality.
Using Silverlight Controls within WPF application
[ "", "c#", ".net", "wpf", "silverlight", "" ]
I'm a bit confused on the point of Automatic properties in C# e.g ``` public string Forename{ get; set; } ``` I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? Why not just use ``` public string Forename; ``` I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.
You can write ``` public string Forename{ get; private set; } ``` to get read-only properties... Still not nearly as versatile as real properties, but it's a compromise that for some works.
C# Automatic Properties
[ "", "c#", "c#-3.0", "automatic-properties", "" ]
Is there a way to Install Libboost 1.38 on Ubuntu 8.10? The highest version in my repositories is 1.35. It has been suggested that there may be some repositories I could add to accomplish this, but my searches haven't yielded anything. Do I have to resort to source code? If so, what is the best way to accomplish this? Thanks
You can either * Upgrade to Jaunty (Ubuntu 9.04) which has 1.37. You can even incrementally upgrade to just its boost libraries (google for apt-pinning) * use a more advanced method I often use: download the Debian package *sources* from Debian unstable (currently 1.38 with 1.39 in the NEW queue and available "real soon now") and rebuild those locally. You may want to google Debian package building -- and rest assured it is easy as the work has been done, you are merely building local variants from existing sources. This way you stay inside the package management system and are forward-compatible with upgrades * if everything else fails, build from source.
On Ubuntu, installing from source is straightforward. Get source, unpack, and run these commands: ``` ./bootstrap.sh --prefix=/usr/local --libdir=/usr/local/lib ./bjam --layout=system install ``` Alternatively, you may wish to grab SVN HEAD, or wait for upcoming 1.40. Then, you can drop all of the above options except for `install`. You may want to review release notes at <http://beta.boost.org> to see if upcoming changes are "risky" for your case.
Installing Libboost 1.38 on Ubuntu 8.10
[ "", "c++", "boost", "ubuntu", "ubuntu-8.10", "" ]
I really need to work with information contained in [WordPerfect 12](https://en.wikipedia.org/wiki/WordPerfect#Summary) files without using WordPerfect's sluggish visual interface, but I can't find any detailed documentation about the file format or any Python modules for reading/writing the files. I found a post on the web that seems to explain how to convert WordPerfect to text, but I didn't understand much about how it works. <http://mail.python.org/pipermail/python-list/2000-February/023093.html> How do I accomplish this?
OK, here's what I did. I read the file in binary mode, converted by the data into a string representation of the hex values, and used unofficial WordPerfect documentation to create regular expressions to swap out all the hex strings representing non-text formatting codes and meta data, then converted everything back into text. A dirty piece of hacking, but it got the job done.
The relevant part of your link is this: ``` os.system( "%s %s %s" % ( WPD_TO_TEXT_CMD, "/tmp/tmpfile", "/tmp/tmpfile.txt" ) ) ``` Which is making a system call to an outside program called "wp2txt". Googling for that program produces active hits.
Read WordPerfect files with Python?
[ "", "python", "wordperfect", "" ]
Is there a way to detect if the scrollbar from the `ScrollViewer` in a `ListView` has reached the bottom of the virtual scroll space? I would like to detect this to fetch more items from the server to put into the bound `ObservableCollection` on the `ListView`. Right now I'm doing this: ``` private void currentTagNotContactsList_scrollChanged(object sender, ScrollChangedEventArgs e) { ListView v = (ListView)sender; if (e.VerticalOffset + e.ViewportHeight == e.ExtentHeight) { Debug.Print("At the bottom of the list!"); } } ``` Is this even correct? I also need to differentiate between the vertical scrollbar causing the event and the horizontal scrollbar causing it (i.e. I don't want to keep generating calls to the server if you scroll horizontally at the bottom of the box). Thanks.
I figured it out. It seems I should have been getting events from the ScrollBar (`<ListView ScrollBar.Scroll="currentTagNotContactsList_Scroll"` in XAML) itself, rather than the viewer. This works, but I just have to figure a way to avoid the event handler being called repeatedly once the scrollbar is down. Maybe a timer would be good: ``` private void currentTagNotContactsList_Scroll(object sender, ScrollEventArgs e) { ScrollBar sb = e.OriginalSource as ScrollBar; if (sb.Orientation == Orientation.Horizontal) return; if (sb.Value == sb.Maximum) { Debug.Print("At the bottom of the list!"); } } ```
``` //A small change in the "Max's" answer to stop the repeatedly call. //this line to stop the repeatedly call ScrollViewer.CanContentScroll="False" private void dtGrid_ScrollChanged(object sender, ScrollChangedEventArgs e) { //this is for vertical check & will avoid the call at the load time (first time) if (e.VerticalChange > 0) { if (e.VerticalOffset + e.ViewportHeight == e.ExtentHeight) { // Do your Stuff } } } ```
Detect when WPF listview scrollbar is at the bottom?
[ "", "c#", "wpf", "listview", "scroll", "" ]
I want to do inplace editing where I have regular text (coming from a Model) with an edit button next to it. When the edit button is clicked, I want a editable textbox to appear where the regular text was, and then commit a change via AJAX. I already solved how to commit, but I don't know how to place the editing control accurately where the text was before. This probably easy for you JS gurus out there. Besides the placement issue I wondered if I should fetch the appropriate edit box (textbox for regular text, calendar for dates etc.) via AJAX when the edit button is clicked or would it be better to just send it off with the page and keep it hidden until needed? Or can I reuse a single instance on the client side somehow? Sorry this is kind of two questions in one but they are tightly related. Thank you!
I would recommend JEditable I have used it before and it works very well. An example: The Markup ``` <div class="editable_text" id="my_text">My Text</div><a href="#" class="trigger_editable">Edit</a> ``` The Jquery ``` $(".editable_text").editable("YOUREDITURLHERE", { event : "edit" }); $(".trigger_editable").bind("click", function() { $(this).prev().trigger("edit"); }); ``` Hope this helps.
Not sure to understand the button placement problem. However, there are a number of jquery plugins designed for this purpose. One of these is Jeditable, find a demo [here](http://www.appelsiini.net/projects/jeditable/default.html)!
ASP.NET MVC/jQuery: Inplace Editing
[ "", ".net", "asp.net", "javascript", "jquery", "" ]
I have an ASP.NET `GridView` that's bound to an `ObjectDataSource` (which is bound to a MySQL database). On this grid, I have 2 unbound `ButtonField` columns that I want to trigger server-side events. Hence I have added an eventhandler method to the `GridView`'s `RowCommand` event. In the code of said eventhandler, I need to somehow get hold of the underlying `DataRow` that was clicked on by the user. However, I can't seem to get this to work; if I use code like the following the `selectedRow` variable is always `null`: ``` protected void searchResultsGridView_RowCommand(object sender, GridViewCommandEventArgs e) { CallDataRow selectedRow = (CallDataRow) searchResultsGridView.Rows[Convert.ToInt32(e.CommandArgument)].DataItem; } ``` I've Googled and found pages such as <http://ranafaisal.wordpress.com/2008/03/31/how-to-get-the-current-row-in-gridview-row-command-event>, but nothing I've found has worked. I'm pretty sure I'm just missing something obvious, but I can't figure out what... Here's the ASP.NET code if that helps: ``` <asp:GridView ID="searchResultsGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="PersonNo,CallDate" Width="100%" AllowPaging="True" EnableSortingAndPagingCallbacks="True" onrowcommand="searchResultsGridView_RowCommand" PageSize="20"> <Columns> <asp:BoundField DataField="PersonNo" HeaderText="Account number" ReadOnly="True" SortExpression="PersonNo" /> <asp:BoundField DataField="AgentNo" HeaderText="Agent number" SortExpression="AgentNo" /> <asp:BoundField DataField="AgentName" HeaderText="Agent name" SortExpression="AgentName" /> <asp:BoundField DataField="TelNumber" HeaderText="Telephone number" SortExpression="TelNumber" /> <asp:BoundField DataField="CallDate" HeaderText="Call date/time" ReadOnly="True" SortExpression="CallDate" /> <asp:ButtonField CommandName="play" HeaderText="Audio" ShowHeader="True" Text="Play" /> <asp:ButtonField CommandName="download" Text="Download" /> </Columns> </asp:GridView> ```
Finally got it to work by doing the following: 1. Adding a TemplateField containing a bound HiddenField. ``` <asp:TemplateField ShowHeader="False"> <ItemTemplate> <asp:HiddenField ID="audioFileName" runat="server" Value='<%# Eval("AudioFileName") %>' /> </ItemTemplate> </asp:TemplateField> ``` 2. Adding the following code in the RowCommand event handler: ``` protected void searchResultsGridView_RowCommand(object sender, GridViewCommandEventArgs e) { string audioFile = ((HiddenField) searchResultsGridView.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("audioFileName")).Value; } ``` It's a cludge and it's not particularly secure, but it works and that's all I need right now. Any better solutions are still welcome though...
I'm even later to the party! But as I got here from Google, some people may still hit this hence I'll give my answer: ``` protected void SomeDataGrid_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { System.Data.DataRowView dr = (System.Data.DataRowView)e.Row.DataItem; string aVar = dr["DataFieldIdLikePlease"].ToString(); } } ``` So then you get can get any of the data fields in the codebehind.
Getting a DataRow from an ASP.NET GridView
[ "", "c#", "asp.net", "gridview", "event-handling", "datarow", "" ]
So I knocked up some test code to see how the multiprocessing module would scale on cpu bound work compared to threading. On linux I get the performance increase that I'd expect: ``` linux (dual quad core xeon): serialrun took 1192.319 ms parallelrun took 346.727 ms threadedrun took 2108.172 ms ``` My dual core macbook pro shows the same behavior: ``` osx (dual core macbook pro) serialrun took 2026.995 ms parallelrun took 1288.723 ms threadedrun took 5314.822 ms ``` I then went and tried it on a windows machine and got some very different results. ``` windows (i7 920): serialrun took 1043.000 ms parallelrun took 3237.000 ms threadedrun took 2343.000 ms ``` Why oh why, is the multiprocessing approach so much slower on windows? Here's the test code: ``` #!/usr/bin/env python import multiprocessing import threading import time def print_timing(func): def wrapper(*arg): t1 = time.time() res = func(*arg) t2 = time.time() print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0) return res return wrapper def counter(): for i in xrange(1000000): pass @print_timing def serialrun(x): for i in xrange(x): counter() @print_timing def parallelrun(x): proclist = [] for i in xrange(x): p = multiprocessing.Process(target=counter) proclist.append(p) p.start() for i in proclist: i.join() @print_timing def threadedrun(x): threadlist = [] for i in xrange(x): t = threading.Thread(target=counter) threadlist.append(t) t.start() for i in threadlist: i.join() def main(): serialrun(50) parallelrun(50) threadedrun(50) if __name__ == '__main__': main() ```
Processes are much more lightweight under UNIX variants. Windows processes are heavy and take much more time to start up. Threads are the recommended way of doing multiprocessing on windows.
The [python documentation for multiprocessing](http://docs.python.org/library/multiprocessing.html) blames the lack of os.fork() for the problems in Windows. It may be applicable here. See what happens when you import psyco. First, easy\_install it: ``` C:\Users\hughdbrown>\Python26\scripts\easy_install.exe psyco Searching for psyco Best match: psyco 1.6 Adding psyco 1.6 to easy-install.pth file Using c:\python26\lib\site-packages Processing dependencies for psyco Finished processing dependencies for psyco ``` Add this to the top of your python script: ``` import psyco psyco.full() ``` I get these results without: ``` serialrun took 1191.000 ms parallelrun took 3738.000 ms threadedrun took 2728.000 ms ``` I get these results with: ``` serialrun took 43.000 ms parallelrun took 3650.000 ms threadedrun took 265.000 ms ``` Parallel is still slow, but the others burn rubber. Edit: also, try it with the multiprocessing pool. (This is my first time trying this and it is so fast, I figure I must be missing something.) ``` @print_timing def parallelpoolrun(reps): pool = multiprocessing.Pool(processes=4) result = pool.apply_async(counter, (reps,)) ``` Results: ``` C:\Users\hughdbrown\Documents\python\StackOverflow>python 1289813.py serialrun took 57.000 ms parallelrun took 3716.000 ms parallelpoolrun took 128.000 ms threadedrun took 58.000 ms ```
python multiprocessing vs threading for cpu bound work on windows and linux
[ "", "python", "multiprocessing", "" ]
I have made some general utilities(jars) for some general purposes. Some of my friends want these utilities for their use. I am ready to share my stuff (free of cost), but afraid they don't re-distribute it further. Is their something in java as described in the following code for my jar's class files. ``` public class UtilityClass{ static{ long secretCode = 7534759 ; //a hardcoded long value (hardcoded by me for my friend) //related to friend's Computer System which either // don't changes untill he reformats his computer // or is something like motherboard serial number or etc..etc... long buddiesSystemSecretCode = getSecretCode() ; if( !(buddiesSystemSecretCode == secretCode) ){ System.exit(1) ; } } private static long getSecretCode(){ long secretCode = 0 ; //any java code to get friend's System hardware specific code return secretCode ; } } ```
Anything simple like that could easily be decompiled and removed. Why are you scared about the possibility of them distributing the code further? You need to weigh up the cost (in time and/or money) of making your code hard to copy vs the actual damage that redistribution would cause. Put it this way: PC games companies put a lot of effort into copy protection, and look how quickly games are still cracked. Do you want to go to those lengths? Just how much value are you attaching to this code? Indeed, if it's useful but not commercial, why not just make it Open Source anyway?
If they're your friends, trust them. Ask them to not distribute your code. The other alternative is to look into copy-protection schemes, with your friends' email addresses & a hashcode of some sort. But seriously, if you don't trust them not to forward the files, why do you consider them "friends" and "buddies"?
How to share my jar utility with selected buddies only?
[ "", "java", "" ]
I've been working on a program to extract information from a dynamic web application, and the program worked fine until I set my tomcat server to use SSL using a self-signed(thus, untrusted) certificate. The stack trace of the error is: ``` javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1584) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:848) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:877) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1089) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1116) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1100) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:857) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230) at com.certicom.gls.glscs.nongui.URLReader$PostURL.setupURL(URLReader.java:34) at com.certicom.gls.glscs.nongui.URLReader.getLogin(URLReader.java:227) at com.certicom.gls.glscs.nongui.URLReader.testLogin(URLReader.java:436) at com.certicom.gls.glscs.nongui.Controller.loginMenu(Controller.java:384) at com.certicom.gls.glscs.nongui.Controller.menu(Controller.java:324) at com.certicom.gls.glscs.nongui.Controller.<init>(Controller.java:49) at com.certicom.gls.glscs.nongui.Controller.main(Controller.java:61) ``` In a web browser, the user is prompted a warning when accessing a HTTPS site with an untrusted certificate, and asked to make an exception if he likes to proceed; I would like to implement a similar functionality for my command-line application... I admit that I am new to socket programming and networking in general; any advice solving this problem will be great!
[Here](http://web.archive.org/web/20121022013056/http://exampledepot.com/egs/javax.net.ssl/TrustAll.html) is some relevant code: ``` // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } // Now you can access an https URL without having the certificate in the truststore try { URL url = new URL("https://hostname/index.html"); } catch (MalformedURLException e) { } ``` This will completely disable SSL checking—just don't learn exception handling from such code! To do what you want, you would have to implement a check in your TrustManager that prompts the user.
Following code from [here](http://www.jiramot.info/sslutilities-accept-all-certificate-in-java) is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP). ``` import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * This class provide various static methods that relax X509 certificate and * hostname verification while using the SSL over the HTTP protocol. * * @author Jiramot.info */ public final class SSLUtilities { /** * Hostname verifier for the Sun's deprecated API. * * @deprecated see {@link #_hostnameVerifier}. */ private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier; /** * Thrust managers for the Sun's deprecated API. * * @deprecated see {@link #_trustManagers}. */ private static com.sun.net.ssl.TrustManager[] __trustManagers; /** * Hostname verifier. */ private static HostnameVerifier _hostnameVerifier; /** * Thrust managers. */ private static TrustManager[] _trustManagers; /** * Set the default Hostname Verifier to an instance of a fake class that * trust all hostnames. This method uses the old deprecated API from the * com.sun.ssl package. * * @deprecated see {@link #_trustAllHostnames()}. */ private static void __trustAllHostnames() { // Create a trust manager that does not validate certificate chains if (__hostnameVerifier == null) { __hostnameVerifier = new SSLUtilities._FakeHostnameVerifier(); } // if // Install the all-trusting host name verifier com.sun.net.ssl.HttpsURLConnection .setDefaultHostnameVerifier(__hostnameVerifier); } // __trustAllHttpsCertificates /** * Set the default X509 Trust Manager to an instance of a fake class that * trust all certificates, even the self-signed ones. This method uses the * old deprecated API from the com.sun.ssl package. * * @deprecated see {@link #_trustAllHttpsCertificates()}. */ private static void __trustAllHttpsCertificates() { com.sun.net.ssl.SSLContext context; // Create a trust manager that does not validate certificate chains if (__trustManagers == null) { __trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()}; } // if // Install the all-trusting trust manager try { context = com.sun.net.ssl.SSLContext.getInstance("SSL"); context.init(null, __trustManagers, new SecureRandom()); } catch (GeneralSecurityException gse) { throw new IllegalStateException(gse.getMessage()); } // catch com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context .getSocketFactory()); } // __trustAllHttpsCertificates /** * Return true if the protocol handler property java. protocol.handler.pkgs * is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated * one, false otherwise. * * @return true if the protocol handler property is set to the Sun's * deprecated one, false otherwise. */ private static boolean isDeprecatedSSLProtocol() { return ("com.sun.net.ssl.internal.www.protocol".equals(System .getProperty("java.protocol.handler.pkgs"))); } // isDeprecatedSSLProtocol /** * Set the default Hostname Verifier to an instance of a fake class that * trust all hostnames. */ private static void _trustAllHostnames() { // Create a trust manager that does not validate certificate chains if (_hostnameVerifier == null) { _hostnameVerifier = new SSLUtilities.FakeHostnameVerifier(); } // if // Install the all-trusting host name verifier: HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier); } // _trustAllHttpsCertificates /** * Set the default X509 Trust Manager to an instance of a fake class that * trust all certificates, even the self-signed ones. */ private static void _trustAllHttpsCertificates() { SSLContext context; // Create a trust manager that does not validate certificate chains if (_trustManagers == null) { _trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()}; } // if // Install the all-trusting trust manager: try { context = SSLContext.getInstance("SSL"); context.init(null, _trustManagers, new SecureRandom()); } catch (GeneralSecurityException gse) { throw new IllegalStateException(gse.getMessage()); } // catch HttpsURLConnection.setDefaultSSLSocketFactory(context .getSocketFactory()); } // _trustAllHttpsCertificates /** * Set the default Hostname Verifier to an instance of a fake class that * trust all hostnames. */ public static void trustAllHostnames() { // Is the deprecated protocol setted? if (isDeprecatedSSLProtocol()) { __trustAllHostnames(); } else { _trustAllHostnames(); } // else } // trustAllHostnames /** * Set the default X509 Trust Manager to an instance of a fake class that * trust all certificates, even the self-signed ones. */ public static void trustAllHttpsCertificates() { // Is the deprecated protocol setted? if (isDeprecatedSSLProtocol()) { __trustAllHttpsCertificates(); } else { _trustAllHttpsCertificates(); } // else } // trustAllHttpsCertificates /** * This class implements a fake hostname verificator, trusting any host * name. This class uses the old deprecated API from the com.sun. ssl * package. * * @author Jiramot.info * * @deprecated see {@link SSLUtilities.FakeHostnameVerifier}. */ public static class _FakeHostnameVerifier implements com.sun.net.ssl.HostnameVerifier { /** * Always return true, indicating that the host name is an acceptable * match with the server's authentication scheme. * * @param hostname the host name. * @param session the SSL session used on the connection to host. * @return the true boolean value indicating the host name is trusted. */ public boolean verify(String hostname, String session) { return (true); } // verify } // _FakeHostnameVerifier /** * This class allow any X509 certificates to be used to authenticate the * remote side of a secure socket, including self-signed certificates. This * class uses the old deprecated API from the com.sun.ssl package. * * @author Jiramot.info * * @deprecated see {@link SSLUtilities.FakeX509TrustManager}. */ public static class _FakeX509TrustManager implements com.sun.net.ssl.X509TrustManager { /** * Empty array of certificate authority certificates. */ private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{}; /** * Always return true, trusting for client SSL chain peer certificate * chain. * * @param chain the peer certificate chain. * @return the true boolean value indicating the chain is trusted. */ public boolean isClientTrusted(X509Certificate[] chain) { return (true); } // checkClientTrusted /** * Always return true, trusting for server SSL chain peer certificate * chain. * * @param chain the peer certificate chain. * @return the true boolean value indicating the chain is trusted. */ public boolean isServerTrusted(X509Certificate[] chain) { return (true); } // checkServerTrusted /** * Return an empty array of certificate authority certificates which are * trusted for authenticating peers. * * @return a empty array of issuer certificates. */ public X509Certificate[] getAcceptedIssuers() { return (_AcceptedIssuers); } // getAcceptedIssuers } // _FakeX509TrustManager /** * This class implements a fake hostname verificator, trusting any host * name. * * @author Jiramot.info */ public static class FakeHostnameVerifier implements HostnameVerifier { /** * Always return true, indicating that the host name is an acceptable * match with the server's authentication scheme. * * @param hostname the host name. * @param session the SSL session used on the connection to host. * @return the true boolean value indicating the host name is trusted. */ public boolean verify(String hostname, javax.net.ssl.SSLSession session) { return (true); } // verify } // FakeHostnameVerifier /** * This class allow any X509 certificates to be used to authenticate the * remote side of a secure socket, including self-signed certificates. * * @author Jiramot.info */ public static class FakeX509TrustManager implements X509TrustManager { /** * Empty array of certificate authority certificates. */ private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{}; /** * Always trust for client SSL chain peer certificate chain with any * authType authentication types. * * @param chain the peer certificate chain. * @param authType the authentication type based on the client * certificate. */ public void checkClientTrusted(X509Certificate[] chain, String authType) { } // checkClientTrusted /** * Always trust for server SSL chain peer certificate chain with any * authType exchange algorithm types. * * @param chain the peer certificate chain. * @param authType the key exchange algorithm used. */ public void checkServerTrusted(X509Certificate[] chain, String authType) { } // checkServerTrusted /** * Return an empty array of certificate authority certificates which are * trusted for authenticating peers. * * @return a empty array of issuer certificates. */ public X509Certificate[] getAcceptedIssuers() { return (_AcceptedIssuers); } // getAcceptedIssuers } // FakeX509TrustManager } // SSLUtilities ```
Allowing Java to use an untrusted certificate for SSL/HTTPS connection
[ "", "java", "security", "https", "" ]
I'm looking for a way to programmatically change navigator.userAgent on the fly. In my failed attempt to get an automated javascript unit tester, I gave up and attempted to begin using fireunit. Immediately, I've slammed into one of the walls of using an actual browser for javascript testing. Specifically, I need to change navigator.userAgent to simulate a few hundred userAgent strings to ensure proper detection and coverage on a given function. navigator.userAgent is readonly, so I seem stuck! How can I mock navigator.userAgent? User Agent Switcher (plugin) can switch FF's useragent, but can I do it within javascript?
Try: ``` navigator.__defineGetter__('userAgent', function(){ return 'foo' // customized user agent }); navigator.userAgent; // 'foo' ``` Tried it in FF2 and FF3.
Adding on to [Crescent Fresh's solution](https://stackoverflow.com/questions/1307013/mocking-a-useragent-in-javascript/1307088#1307088), redefining the `navigator.userAgent` getter doesn't seem to work in Safari 5.0.5 (on Windows 7 & Mac OS X 10.6.7). Need to create a new object that inherits from the `navigator` object and define a new `userAgent` getter to hide the original `userAgent` getter in `navigator`: ``` var __originalNavigator = navigator; navigator = new Object(); navigator.__proto__ = __originalNavigator; navigator.__defineGetter__('userAgent', function () { return 'Custom'; }); ```
Mocking a useragent in javascript?
[ "", "javascript", "unit-testing", "user-agent", "" ]
Is there a Python convention for when you should implement `__str__()` versus `__unicode__()`? I've seen classes override `__unicode__()` more frequently than `__str__()` but it doesn't appear to be consistent. Are there specific rules when it is better to implement one versus the other? Is it necessary/good practice to implement both?
`__str__()` is the old method -- it returns bytes. `__unicode__()` is the new, preferred method -- it returns characters. The names are a bit confusing, but in 2.x we're stuck with them for compatibility reasons. Generally, you should put all your string formatting in `__unicode__()`, and create a stub `__str__()` method: ``` def __str__(self): return unicode(self).encode('utf-8') ``` In 3.0, `str` contains characters, so the same methods are named `__bytes__()` and `__str__()`. These behave as expected.
If I didn't especially care about micro-optimizing stringification for a given class I'd always implement `__unicode__` only, as it's more general. When I do care about such minute performance issues (which is the exception, not the rule), having `__str__` only (when I can prove there never will be non-ASCII characters in the stringified output) or both (when both are possible), might help. These I think are solid principles, but in practice it's very common to KNOW there will be nothing but ASCII characters without doing effort to prove it (e.g. the stringified form only has digits, punctuation, and maybe a short ASCII name;-) in which case it's quite typical to move on directly to the "just `__str__`" approach (but if a programming team I worked with proposed a local guideline to avoid that, I'd be +1 on the proposal, as it's easy to err in these matters AND "premature optimization is the root of all evil in programming";-).
__str__ versus __unicode__
[ "", "python", "string", "unicode", "python-2.x", "conventions", "" ]
I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise. Even the slightest optimisation could have a big impact on my code, so I'm keen to explore even the smallest improvements. Here's what I have so far: ``` def simple_pearson(v1,v2): si = [val for val in v1 if val in v2] n = len(si) if n==0: return 0.0 sum1 = 0.0 sum2 = 0.0 sum1_sq = 0.0 sum2_sq = 0.0 p_sum = 0.0 for v in si: val_1 = v1[v] val_2 = v2[v] sum1+=val_1 sum2+=val_2 sum1_sq+=pow(val_1,2) sum2_sq+=pow(val_2,2) p_sum+=val_1*val_2 # Calculate Pearson score num = p_sum-(sum1*sum2/n) temp = (sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n) if temp < 0.0: temp = -temp den = sqrt(temp) if den==0: return 1.0 r = num/den return r ```
Scipy is the fastest! I have don some tests with the code above and also with a version I found on my comp, see below for results and the code: ``` pearson 14.7597990757 sim_pearson 15.6806837987 scipy:pearsonr 0.451986019188 ``` ``` try: import psyco psyco.full() except ImportError: pass from math import sqrt def sim_pearson(set1, set2): si={} for item in set1: if item in set2: si[item] = 1 #number of elements n = len(si) #if none common, return 0 similarity if n == 0: return 0 #add up all the preferences sum1 = sum([set1[item] for item in si]) sum2 = sum([set2[item] for item in si]) #sum up the squares sum_sq1 = sum([pow(set1[item], 2) for item in si]) sum_sq2 = sum([pow(set2[item], 2) for item in si]) #sum up the products sum_p = sum([set1[item] * set2[item] for item in si]) nom = sum_p - ((sum1 * sum2) / n ) den = sqrt( (sum_sq1 - (sum1)**2 / n) * (sum_sq2 - (sum2)**2 / n) ) if den==0: return 0 return nom/den # from http://stackoverflow.com/questions/1307016/pearson-similarity-score-how-can-i-optimise-this-further def pearson(v1, v2): vs = [(v1[val],v2[val]) for val in v1 if val in v2] n = len(vs) if n==0: return 0.0 sum1,sum2,sum1_sq,sum2_sq,p_sum = 0.0, 0.0, 0.0, 0.0, 0.0 for v1,v2 in vs: sum1+=v1 sum2+=v2 sum1_sq+=v1*v1 sum2_sq+=v2*v2 p_sum+=v1*v2 # Calculate Pearson score num = p_sum-(sum1*sum2/n) temp = max((sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n),0) if temp: return num / sqrt(temp) return 1.0 if __name__ == "__main__": import timeit tsetup = """ from random import randrange from __main__ import pearson, sim_pearson from scipy.stats import pearsonr v1 = [randrange(0,1000) for x in range(1000)] v2 = [randrange(0,1000) for x in range(1000)] #gc.enable() """ t1 = timeit.Timer(stmt="pearson(v1,v2)", setup=tsetup) t2 = timeit.Timer(stmt="sim_pearson(v1,v2)", setup=tsetup) t3 = timeit.Timer(stmt="pearsonr(v1,v2)", setup=tsetup) tt = 1000 print 'pearson', t1.timeit(tt) print 'sim_pearson', t2.timeit(tt) print 'scipy:pearsonr', t3.timeit(tt) ```
The real speed increase would be gained by moving to numpy or scipy. Short of that, there are microoptimizations: e.g. `x*x` is faster than `pow(x,2)`; you could extract the values at the same time as the keys by doing, instead of: ``` si = [val for val in v1 if val in v2] ``` something like ``` vs = [ (v1[val],v2[val]) for val in v1 if val in v2] ``` and then ``` sum1 = sum(x for x, y in vs) ``` and so on; whether each of these brings time advantage needs microbenchmarking. Depending on how you're using these coefficients returning the square would save you a sqrt (that's a similar idea to using squares of distances between points, in geometry, rather than the distances themselves, and for the same reason -- saves you a sqrt; which makes sense because the coefficient IS a distance, kinda...;-).
Pearson Similarity Score, how can I optimise this further?
[ "", "python", "optimization", "similarity", "pearson", "" ]
Ok when im gonna make reports with Java I use iReport for JasperReports Template designs. But with python the alternative is [html2pdf](http://www.xhtml2pdf.com/demo) - pisa. It would be great to see an example of this. Any hint would be appreciated.
The accounting software we are developing uses pisa to generate pdf reports. The process is like this: 1. Render a HTML template 2. Convert the rendered string to pdf. You can directly use the HttpResponse object you will return as output file, or a `StringIO` object to store the pdf and send its content via HttpResponse. 3. The mimetype of `HttpResponse` object should be set to `application/pdf` and use `Content-Disposition` header if you want to trigger download instead of displaying in the browser. Pisa uses some unique CSS properties to specify pdf related formatting (page-size, page-break etc). Their docs provide sufficient examples on this. Pisa's rendering of HTML/CSS can be quite a bit different from what we usually see in browser. For example, setting `border="1"` on a `<table>` will give all cells of the table border, borders are always collapsed (border-collapse css attribute has no effect) etc.
And yes, <http://www.xhtml2pdf.com> comes with a djangoproject example :)
Has anybody tried html2pdf in django?
[ "", "python", "django", "pdf", "pdf-generation", "" ]
I need to create a pdf file with the [fpdf](http://www.fpdf.org) library and save it in a blob field in my MySQL database. The problem is, when I try to retrieve the file from the blob field and send it to the browser for the download, the donwloaded file is corrupted and does not display correctly. The same pdf file is correctly displayed if I send it immediately to the browser without storing it in the db, so it seems some of the data gets corrupted when is inserted in the db. My code is something like this: ``` $pdf = new MyPDF(); //class that extends FPDF and create te pdf file $content = $pdf->Output("", "S"); //return the pdf file content as string $sql = "insert into mytable(myblobfield) values('".addslashes($content)."')"; mysql_query($sql); ``` to store the pdf, and like this: ``` $sql = "select myblobfield from mytable where id = '1'"; $result = mysql_query($sql); $rs = mysql_fetch_assoc($result); $content = stripslashes($rs['myblobfield']); header('Content-Type: application/pdf'); header("Content-Length: ".strlen(content)); header('Content-Disposition: attachment; filename=myfile.pdf'); print $content; ``` to send it to the browser for downloading. What am I doing wrong? If I change my code to: ``` $pdf = new MyPDF(); $pdf->Output(); //send the pdf to the browser ``` the file is correctly displayed, so I assume that is correctly generated and the problem is in the storing in the db. Thanks in advance.
You shouldn't strip any (back)slashes. When you add them, they are used as escape characters in the query and do not appear in the field. Try changing this ``` $content = stripslashes($rs['myblobfield']); ``` into this: ``` $content = $rs['myblobfield']; ```
Actually for security reasons: 1. Do not use `addslashes()` but use `mysql_real_escape_string()` instead In this specific case (as it is binary data): 1. Remove `stripslashes()` 2. Replace `addslashes()` by `mysql_real_escape_string()`
Save a PDF created with FPDF php library in a MySQL blob field
[ "", "php", "pdf", "fpdf", "" ]
I need to display an imagemap with about 70 areas in it. The area of the imagemap the mouse cursor is currently at is supposed to be highlighted in a certain color. Is this possible and if yes, how?
After actually using it in production I'd say this is the answer: <http://plugins.jquery.com/project/maphilight> Using this it takes a few lines of code to implement that feature for any imagemap.
Yes, this is possible. I've done the exact thing with jquery and the image map area mouseenter / mouseleave events, but not with 70 areas. It will just be more work for you. You may consider loading the images via ajax calls on the mouseover, or using a sprite and positioning so you don't need to load 70 images into the dom. jquery: ``` $(document).ready(function() { $(".map-areas area").mouseenter(function() { var idx = $(".map-areas area").index(this); $(".map-hovers img:eq(" + idx + ")").show(); return false; }).mouseleave(function() { $(".map-hovers img").hide(); return false; }); }); ``` Where .map-hovers is a div that has all the images that you want to lay over top of your map. You can position them if necessary, or make the image the same size as the image map, but with transparency. And some html to follow: NOTE: Notice how the image map area index lines up with the img index within the map-hovers container? ALSO: The image map must point to a transparent gif, and have the background image set to the actual image you want to display. This is a cross-browser thing - can't remember the exact reason. ``` <div id="container"> <img src="/images/trans.gif" width="220" height="238" class="map-trans" alt="Map / Carte" usemap="#region-map" /> <div class="map-hovers"> <img src="/images/map/sunset-country.png" alt="Sunset Country" /> <img src="/images/map/north-of-superior.png" alt="North of Superior" /> <img src="/images/map/algomas-country.png" alt="Algoma's Country" /> <img src="/images/map/ontarios-wilderness.png" alt="Ontario's Wilderness" /> <img src="/images/map/rainbow-country.png" alt="Rainbow Country" /> <img src="/images/map/ontarios-near-north.png" alt="Ontario's Near North" /> <img src="/images/map/muskoka.png" alt="Muskoka" /> </div> </div> <map name="region-map" id="region-map" class="map-areas"> <area shape="poly" coords="52,19,53,82,36,114,34,126,26,130,5,121,2,110,7,62" href="#d0" alt="Sunset Country" /> <area shape="poly" coords="93,136,93,113,82,112,77,65,57,51,58,82,41,122,33,133,58,138,74,126" href="#d1" alt="North of Superior" /> <area shape="poly" coords="98,112,118,123,131,149,130,165,108,161,97,138" href="#d2" alt="Algoma's Country" /> <area shape="poly" coords="68,2,100,29,124,33,133,74,155,96,159,145,134,146,121,119,101,110,83,107,83,65,55,45,54,16" href="#d3" alt="Ontario's Wilderness" /> <area shape="poly" coords="151,151,152,167,157,176,152,179,137,178,124,172,133,169,135,150" href="#d4" alt="Rainbow Country" /> <area shape="poly" coords="160,150,170,167,169,173,160,171,155,162,153,149" href="#d5" alt="Ontario's Near North" /> <area shape="poly" coords="173,176,162,177,154,184,167,189,178,183" href="#d6" alt="Muskoka" /> </map> ```
How do I highlight parts of an imagemap on mouseover?
[ "", "javascript", "html", "imagemap", "" ]
I have a select field in a form that allows you to select multiple options. I need to create a new input textbox for every number of options selected, automatically. For example, if you select on option in the select box, one input will appear below it. If you select 5, 5 inputs will appear below it. I'm not sure if this can be done in just straight Javascript, or if I'll need to use jQuery or some other form of AJAX to get this done, but I'm not really sure how to approach this (I'm relatively new to using AJAX)
Well, jQuery was made just for this type of thing - i recommend using it to save yourself headaches. My take on it. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(function() { $('#test') .after( '<div id="option-inputs"></div>' ) .find( 'option' ).each( function() { var $option = $(this); $option .data( '$input', $( '<span>' + $option.text() + ': </span><input><br>').appendTo( '#option-inputs' ).hide() ) .bind( 'toggle-input', function() { var $input = $option.data( '$input' ); if ( $option[0].selected ) { $input.show(); } else { $input.hide(); } }) .bind( 'click', function() { $(this).siblings().andSelf().trigger( 'toggle-input' ); }) .trigger( 'toggle-input' ) ; }) ; }); </script> </head> <body> <select id="test" multiple="multiple"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </body> </html> ```
Just some quick thoughts.. Add a DIV under the Select Element. using jQuery (or javascript) you can add a textbox for each select item add a textbox to the div. Something like: ``` var textboxString; $("#SelectElement option:selected").each(function () { textboxString += "<input type='textbox' /><br>" // Add to this string as needed (Labels, css class, etx). }); $("#divElement").html(textboxString) ```
Selecting Multiple Options creates Multiple Inputs
[ "", "javascript", "jquery", "ajax", "html-select", "multiple-select", "" ]
I am setting readonly="readonly" (in other words, true) via javascript: ``` document.getElementById("my_id").setAttribute("readonly", "readonly"); ``` This is having the intended effect (making the field no longer editable, but its contents are submitted with the form) in FF, Safari and Chrome, but not for IE7. In IE7 I can still modify the contents of the text input field. I have tried setting ("readonly", "true") as well, which works in all three other browsers that I am testing, but which IE7 also ignores. Does anyone have experience with trying to do this with IE7? I do not want to use the disabled attribute as I want the value within the text input field to be submitted with the form.
Did you try this? ``` document.getElementById("my_id").readOnly = true; ```
try: ``` document.getElementById("my_Id").setAttribute("readOnly","readonly") ``` it is ***readOnly***, **O** is capital!
Text input readonly attribute not recognized in IE7?
[ "", "javascript", "forms", "internet-explorer-7", "readonly", "" ]
How can I invert a binary equation, such that I can find which inputs will produce a given output. Example: ``` Inputs: i0 through i8 Outputs: o0 through o8 Operators: ^ = XOR, & = AND ``` Binary equations: ``` (1&i0) ^ (1&i1) ^ (0&i2) ^ (1&i3) ^ (0&i4) ^ (0&i5) ^ (0&i6) ^ (0&i7) ^ (0&i8) = o0 (0&i0) ^ (1&i1) ^ (0&i2) ^ (1&i3) ^ (1&i4) ^ (0&i5) ^ (0&i6) ^ (0&i7) ^ (0&i8) = o1 (0&i0) ^ (1&i1) ^ (1&i2) ^ (0&i3) ^ (0&i4) ^ (1&i5) ^ (0&i6) ^ (0&i7) ^ (0&i8) = o2 (1&i0) ^ (0&i1) ^ (0&i2) ^ (1&i3) ^ (0&i4) ^ (0&i5) ^ (0&i6) ^ (0&i7) ^ (0&i8) = o3 (0&i0) ^ (1&i1) ^ (0&i2) ^ (1&i3) ^ (1&i4) ^ (0&i5) ^ (0&i6) ^ (0&i7) ^ (0&i8) = o4 (0&i0) ^ (0&i1) ^ (0&i2) ^ (0&i3) ^ (0&i4) ^ (1&i5) ^ (0&i6) ^ (0&i7) ^ (0&i8) = o5 (0&i0) ^ (0&i1) ^ (0&i2) ^ (1&i3) ^ (0&i4) ^ (0&i5) ^ (1&i6) ^ (0&i7) ^ (0&i8) = o6 (0&i0) ^ (0&i1) ^ (0&i2) ^ (1&i3) ^ (1&i4) ^ (0&i5) ^ (1&i6) ^ (1&i7) ^ (0&i8) = o7 (0&i0) ^ (0&i1) ^ (0&i2) ^ (0&i3) ^ (0&i4) ^ (1&i5) ^ (0&i6) ^ (0&i7) ^ (1&i8) = o8 ``` In matrix form: ``` 1,1,0,1,0,0,0,0,0,1 0,1,0,1,1,0,0,0,0,1 0,1,1,0,0,1,0,0,0,1 1,0,0,1,0,0,0,0,0,1 0,1,0,1,1,0,0,0,0,1 0,0,0,0,0,1,0,0,0,1 0,0,0,1,0,0,1,0,0,1 0,0,0,1,1,0,1,1,0,1 0,0,0,0,0,1,0,0,1,1 ``` Additional limitations: * The prime diagonal is always 1 * I am interested if there is a solution or not, more then the solution itself How can I, algorithmically find inputs i0 -i8 such that outputs o0 - o8 are 1? What I really want to find is if there is such a solution or not. I need an algorithm which is scalable to larger networks, at least up to 100 inputs/outputs.
With XOR (rather than OR), it seems at first glance that some form of [Gauss–Jordan elimination](http://en.wikipedia.org/wiki/Gauss%E2%80%93Jordan_elimination) can at least simplify the problem. Adapting the pseudocode from the Wikipedia article on reduced [row echelon form](http://en.wikipedia.org/wiki/Row_echelon_form), we get: ``` function ToReducedRowEchelonForm(Matrix M) is // 'lead' is the column index in a row of the leading 1 lead := 0 rowCount := the number of rows in M columnCount := the number of columns in M for 0 ≤ r < rowCount do if columnCount ≤ lead then stop end if i = r // Find row with lead point while M[i, lead] = 0 do i = i + 1 if rowCount = i then // no pivot in this column, move to next i = r lead = lead + 1 if columnCount = lead then stop end if end if end while Swap rows i and r for 0 ≤ i < rowCount do if i ≠ r do Set row i to row i XOR row r end if end for lead = lead + 1 end for end function ``` This converts the sample to: ``` 1,0,0,0,0,0,0,1,0,0 0,1,0,0,0,0,0,0,0,0 0,0,1,0,0,0,0,0,0,0 0,0,0,1,0,0,0,1,0,1 0,0,0,0,1,0,0,1,0,0 0,0,0,0,0,1,0,0,0,1 0,0,0,0,0,0,1,1,0,0 0,0,0,0,0,0,0,0,1,0 0,0,0,0,0,0,0,0,0,0 ``` From there, you could adapt an [integer partitioning](http://en.wikipedia.org/wiki/Partition_(number_theory)) algorithm to generate the possible inputs for a row, taking in to account the partitions for previous rows. Generating a partition is a great candidate for memoization. Still need to do a timing analysis to see if the above is worthwhile.
One interesting thing about `xor` is that: ``` a ^ b ^ b = a ``` This allows for nice manipulations, let's say you have: ``` a ^ b = c ``` Then you can easily figure out `a` by `xor`ing both sides with `b`, getting: ``` a = c ^ b ``` If I was in your place, I'd use this trick to get the input from the outputs. The `and`ing that appears in your equations only have the effect of *removing* some input variables from some equations, so it poses no problem to this approach. First off, you must know, there **might not be a solution for particular coefficient matrices**, for example, if the input never appears in any equation (that is, a column of all-zeros in the matrix), or if an equation appears twice (that is, two identical rows), or if an equation is a combination of two other equations. Now, assuming the matrix you have **does** yield a solution to your problem, the approach would be use each equation to find one of the inputs. For each equation, `xor` both sides for all the inputs except one input (and varry this input for each equation). For example, let's say I want to use the first equation to find `i0` and the second to find `i1` (notice the input has to appear in the equation to make this value), I would now have: ``` i0 = o0 ^ i1 ^ i3 i1 = o1 ^ i3 ^ i4 ``` Continue for the other equations, then substitute all inputs on the right side with their values from the equations. Repeat recursively till the right side only contains outputs. If you repeat for all equations, you'll find the values of all inputs. I am **sure** this approach can be optimized using already-established methods in solving a linear system of equations, especially utilizing the matrix form.
Inverting binary networks
[ "", "javascript", "algorithm", "math", "binary", "" ]
Is there any way I can disable expanding TreeNode after doubleclick?? Thanks
There is no simple way to achieve this, as far as I know. One thought would be to have a `bool` variable set to `true` on the DoubleClick event, and use the `e.Cancel` property of the `BeforeExpand` event to prevent the node from expanding. However, those two events are fired in the opposite order, so that is not a solution. I don't have another solution from the top of my head; will update if I come up with one. **Update** I have played around with this a bit, and I have found one way that works *reasonably* well. As I have mentioned the problem is that `BeforeExpand` happens *before* `DoubleClick`, so we can't set any state in `DoubleClick` to use in `BeforeExpand`. We can, however, detect (potential) double clicks in another way: by measuring the time between `MouseDown` events. If we get two `MouseDown` events within the time period that defines a double click (as stated in [`SystemInformation.DoubleClickTime`](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.doubleclicktime.aspx)), it should be a double click, right? And the `MouseDown` event is raised before `BeforeExpand`. So, the following code works rather well: ``` private bool _preventExpand = false; private DateTime _lastMouseDown = DateTime.Now; private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e) { e.Cancel = _preventExpand; _preventExpand = false; } private void treeView1_MouseDown(object sender, MouseEventArgs e) { int delta = (int)DateTime.Now.Subtract(_lastMouseDown).TotalMilliseconds; _preventExpand = (delta < SystemInformation.DoubleClickTime); _lastMouseDown = DateTime.Now; } ``` I say "rather well" because I feel that it prevents the node from expanding in some cases when it should not (for instance if you within the double click time click first on the node text and then on the plus sign). That might be possible to solve in some way, or perhaps you can live with that.
``` private bool isDoubleClick = false; private void treeView1_BeforeCollapse(object sender, TreeViewCancelEventArgs e) { if (isDoubleClick && e.Action == TreeViewAction.Collapse) e.Cancel = true; } private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e) { if (isDoubleClick && e.Action == TreeViewAction.Expand) e.Cancel = true; } private void treeView1_MouseDown(object sender, MouseEventArgs e) { isDoubleClick = e.Clicks > 1; } ``` You can declare a private field isDoubleClick and set various TreeView events as above. This will prevent expand/collapse TreeView node on double click. However expand/collapse will work via + and - icons.
Disable expanding after doubleclick
[ "", "c#", ".net", "winforms", "" ]
Is it possible to mock a concrete class using EaskMock? If so, how do I do it?
See the [EasyMock Class Extension](http://easymock.org/EasyMock2_2_2_ClassExtension_Documentation.html) documentation and [download it from the SourceForge project](http://sourceforge.net/projects/easymock/files/). You can't mock final methods though. EDIT: This is now part of EasyMock for v3 and above, as noted in comments.
[Powermock](http://code.google.com/p/powermock/) extends EasyMock and allows you to mock concrete types, even final and static methods. > PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.
Mocking a concrete class using EasyMock
[ "", "java", "easymock", "" ]
I'm just curious... Is it possible to release a variable in c#? What I mean is, can you do something like this: ``` ... string x = "billy bob"; //release variable x somehow string x = "some other string"; //release variable x somehow int x = 329; ... ``` ... so basically you are declaring the variable multiple times in the same scope. If this isn't possible in c#, what languages is it possible in?
You can do it with scopes (loose term; formally I believe this would be a declaration space), e.g. the following is perfectly legal C# within a method body: ``` { string x = "billy bob"; } { string x = "some other string"; } { int x = 329; } ``` I wouldn't advise writing code like this though, it makes it far too easy to get variables confused in a method. Better to use different, more descriptive names, or separate each block out into its own method.
No, this isn't possible in C# within the same scope - for which I'm very grateful. It sounds like a recipe for readability disaster. As Greg has shown, you can introduce your own scopes within a method solely for this purpose though. I don't know which languages allow you to do this - weakly typed languages will often let you assign arbitrary values of course, but I don't know of a language which has explicit variable declarations *with type information* and also allows a redeclaration in the same scope. You might want to read Eric Lippert's most recent blog post, which is [all about scope](http://blogs.msdn.com/ericlippert/archive/2009/08/03/what-s-the-difference-part-two-scope-vs-declaration-space-vs-lifetime.aspx). (If you don't already read Eric's blog, you might want to clear out a few days in your calendar and read all the back posts... or at least the ones since he joined the C# team. Prepare to have your mind blown repeatedly.)
Is it possible to release a variable in c#?
[ "", "c#", ".net", "variables", "scope", "declaration", "" ]
Ok, this has been a head scratcher for me. I have a ListBox I am binding to a linq query like so: ``` private IQueryable<Feed> _feeds; public IQueryable<Feed> Feeds { get { if (_feeds == null) { var feedsQuery = from f in _db.Feed orderby f.Title select f; _feeds = feedsQuery; } return _feeds; } } public Options() { InitializeComponent(); this.DataContext = Feeds; } ``` (For the record I've also tried List, instead of IQueryable) Everything shows up great and I have a databound form that allows you to edit a record and all of those changes work just fine, the modified data shows up in the list. The problem comes with I add an item. Nothing shows up in the list. The data goes into the database fine, but the only way to see the data is closing and restarting my app. I'm using the code below as an example: ``` Feed feed = new Feed() { ID = Guid.NewGuid(), Url = "http://www.test.com", Title = "Test" }; _db.Feed.InsertOnSubmit(feed); _db.SubmitChanges(); _db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues); ``` (with or without the \_db.Refresh nothing happens) What's going on?
You are doing everything right, you jus need to use [ObservableCollection](http://msdn.microsoft.com/en-us/library/ms668604.aspx). This will notify the ListBox about any changes in the list and refresh it automatically. From MSDN > In many cases the data that you work > with is a collection of objects. For > example, a common scenario in data > binding is to use an ItemsControl > such as a ListBox, ListView, or > TreeView to display a collection of > records. P.S. you don't need a db refresh
Unless notified otherwise, the `ListBox` only iterates once over its `ItemsSource`. Your query is only being run once. The query object doesn't know when the database changes (and `Refresh` doesn't help; see below)--it's up to you to know (or anticipate) that and to rerun relevant queries at the appropriate times. Stan R mentions `ObservableCollection`. That's fine, but simply storing the result of your query in an `ObservableCollection` won't solve the problem unless you do some work to update the collection yourself when the database changes. This means rerunning the query and manually adding new items and removing deleted items from the collection. (You could alternatively just rerun the query and set the entire result back in to the ListBox, but that means a whole new set of items will be created--not very performant, and maybe not what you want for other reasons.) As an aside, your call to `DataContext.Refresh` is probably not doing what you think it is. From the docs: > This method is useful after an optimistic concurrency error to bring items into a state for another attempt. It updates the state of the primitive fields and properties on the objects.
Adding an item to a bound WPF ListBox
[ "", "c#", "wpf", "linq", "listbox", "" ]
Apologies, I am completely new to Django and Python. I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object: ``` list = List.objects.all()[0] ``` Is there a way to get the length of List.objects? I've tried List.objects.length but to no avail. Second, is it possible to create simultaneous filters or combine lists? Here is an example: ``` def findNumber(request, number) phone_list = Numbers.objects.filter(cell=number) ``` I want something like the above, but more like: ``` def findNumber(request, number) phone_list = Numbers.objects.filter(cell=number or home_phone=number) ``` What is the correct syntax, if any?
I haven't tried this yet, but I'd look at the [latest()](https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest) operator on [QuerySets](http://docs.djangoproject.com/en/dev/ref/models/querysets/#ref-models-querysets): > latest(field\_name=None) > > Returns the latest object in the > table, by date, using the field\_name > provided as the date field. > > This example returns the latest Entry > in the table, according to the > pub\_date field: > > Entry.objects.latest('pub\_date') > > If your model's Meta specifies > get\_latest\_by, you can leave off the > field\_name argument to latest(). > Django will use the field specified in > get\_latest\_by by default. > > Like get(), latest() raises > DoesNotExist if an object doesn't > exist with the given parameters. > > Note latest() exists purely for > convenience and readability. And the [model docs on get\_latest\_by](http://docs.djangoproject.com/en/dev/ref/models/options/): > get\_latest\_by > > Options.get\_latest\_by > > The name of a DateField or DateTimeField in the model. This specifies the default field to use in your model Manager's latest method. > > Example: > > get\_latest\_by = "order\_date" > > See the docs for latest() for more. Edit: Wade has a good answer on Q() operator.
this works! `Model.objects.latest('field')` - field can be id. that will be the latest id
Django - Getting last object created, simultaneous filters
[ "", "python", "django", "filter", "django-views", "" ]
Windows provides a number of objects useful for synchronising threads, such as event (with `SetEvent` and `WaitForSingleObject`), mutexes and critical sections. Personally I have always used them, especially critical sections since I'm pretty certain they incur very little overhead unless already locked. However, looking at a number of libraries, such as boost, people then to go to a lot of trouble to implement their own locks using the interlocked methods on Windows. I can understand why people would write lock-less queues and such, since thats a specialised case, but is there any reason why people choose to implement their own versions of the basic synchronisation objects?
Libraries aren't implementing their own locks. That is pretty much impossible to do without OS support. What they *are* doing is simply wrapping the OS-provided locking mechanisms. Boost does it for a couple of reasons: * They're able to provide a much better designed locking API, taking advantage of C++ features. The Windows API is C only, and not very well-designed C, at that. * They are able to offer a degree of portability. the same Boost API can be used if you run your application on a Linux machine or on Mac. Windows' own API is obviously Windows-specific. * The Windows-provided mechanisms have a glaring disadvantage: They require you to include `windows.h`, which you may want to avoid for a large number of reasons, not least its extreme macro abuse polluting the global namespace.
One particular reason I can think of is portability. Windows locks are just fine on their own but they are not portable to other platforms. A library which wishes to be portable must implement their own lock to guarantee the same semantics across platforms.
Why do libraries implement their own basic locks on windows?
[ "", "c++", "windows", "multithreading", "synchronization", "locking", "" ]
I have a .csv file that is ordered in a certain way. I want to reorder it by another field. Your ideas would be much appreciated. I only have to do this once, not multiple times, so performance is not too much of an issue. What I am thinking. If I just create an object (java) to hold each of the fields and then create an ArrayList of these objects. I will then order the ArrayList on the field I want (I can order an ArrayList of objects based on one member of the object - right?), and print this reordered ArrayList to a .csv file.
Souds like it would work but is also some overkill. If you have a unix box or cygwin you could just do ``` cat file | sort -t , +<field number> ``` This will break the fields up by , and sort by the field number ``` cat file | sort -t , +2 ``` sorts by the second field.
Can't you just load the csv into Excel, use the sort function to reorder it, and then save the result as a new csv file?
How to reorder a 60mb CSV file
[ "", "java", "arraylist", "" ]
I have created a C# .net 2.0 webservice. I need to capture the raw XML sent from the client and validate it against an XSD and return any errors to the client. The webservice will allow the client to upload a list of widgets to our system. The following is some background info: **I created an XSD to model a "Widget", which is a complex object.** It looks something like this: ``` <xs:element name="WidgetList"> <xs:complexType> <xs:sequence> <xs:element name="Widget" maxOccurs="unbounded" type="WidgetType" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="WidgetType"> <xs:sequence maxOccurs="1" minOccurs="1"> <xs:element name="Seller" type="AccountType" maxOccurs="1" minOccurs="1" /> <xs:element name="Buyer" type="AccountType" maxOccurs="1" minOccurs="1" /> </xs:sequence> <xs:attribute name="Market" type="MarketType" use="required" /> </xs:complexType> <!-- etc... --> ``` **Then, I used XSD.exe to generate classes from the xsd.** The Classes that are created are WidgetList, Widget, Seller, Buyer, etc. **Next, I created a webservice method to take the Upload. It looks like so:** ``` [WebMethod] [SoapHeader("SecurityAuthenticationHeader", Direction = SoapHeaderDirection.In)] public string UploadWidgets(WidgetList wl) { //Need to validate the XML against the XSD here. //Code to import... } ``` Two questions: 1. Is there a way that I can validate the raw XML sent from the client against my original XSD? 2. Is there anything wrong with the way I have created this service? **UPDATE:** The reason I need to do this is that even though the XSD says fields are **required or minOccurs=1**, it seems that those properties are not required in the WSDL (Not really sure why). This is what part of the WSDL looks like (removed unnecessary parts for brevity): ``` <s:schema elementFormDefault="qualified" targetNamespace="http://www.clearpar.com/XMLSchema"> <s:element name="lt"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="unbounded" name="LoanTrade" type="s1:LoanTradeType" /> </s:sequence> </s:complexType> </s:element> <s:complexType name="LoanTradeType"> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="Seller" type="s1:AccountType" /> <s:element minOccurs="0" maxOccurs="1" name="Buyer" type="s1:AccountType" /> </s:sequence> <s:attribute name="Market" type="s1:MarketType" use="required" /> </s:complexType> <s:complexType name="AccountType"> <s:attribute name="Name" type="s:string" /> <s:attribute name="ClientSystemID" type="s:string" /> </s:complexType> ```
I don't think that there's a simple way to do this. There is an [MSDN article on implementing a SoapExtension](http://msdn.microsoft.com/en-us/magazine/cc164115.aspx) to perform schema validation. This is the route I took, with a few enhancements. It's unfortunate that there is no automatic mechanism to validate against the WSDL, especially since the service inherently knows the schema already. I would be interested to know if this situation has changed in WCF: I'm porting my services now and would love it if they've solved this problem more elegantly.
Since you need more strict control over your WSDL, I recommend writing it manually, and generate both your service contract interface/data/messages and client proxies from a single WSDL contract. There is a great project on CodePlex, [WCSF.blue](http://wscfblue.codeplex.com/), that can help you do contract-first service development.
Webservices Design and How can I capture the raw XML sent to a webservice call in C# .net so that I can validate it against an XSD?
[ "", "c#", ".net", "web-services", "xsd", "" ]
I have a weird problem trying to use a DLL written in C++ from a Delphi (Turbo Delphi 2006) program. When I run the Delphi program (see below) from the command line, everything works fine. Also, when I run it from the Delphi environment without debugging (CTRL+SHIFT+F9), everything is fine. However, when running it *with* debugging (F9), I get the following error: > Project Z:\test.exe faulted with > message: 'access violation at > 0x00403fdf: read of address > 0x00a14e74'. Process stopped. Use Step > or Run to continue. The weird thing is that the error occurs on executing the last 'end.' of the code. Delphi's CPU display says this is somewhere in 'UnsetExceptionHandler', four lines before 'FinalizeUnits', to be more specific, at > 00403FDF 3901 cmp [ecx],eax I'm somewhat at a loss here; Delphi is not my domain (I was the one writing the DLL, and now I need to provide an example program using it). So any help on this issue is greatly appreciated :) Here's the Delphi code: ``` program libiup_integration; {$APPTYPE CONSOLE} uses SysUtils, WinProcs; type T_F_GetError = function() : pchar; stdcall; T_F_SetPath = function(path: pchar) : integer; stdcall; T_F_GetStrat = function(date: integer;time: single;lat: single;lon: single) : single; cdecl; var F_GetError : T_F_GetError; PF_GetError : TFarProc; F_SetPath : T_F_SetPath; PF_SetPath : TFarProc; F_GetStrat : T_F_GetStrat; PF_GetStrat : TFarProc; DLLHandle : THandle; errormsg : pchar; h5path : pchar; h5err : integer; date : integer; time : single; lat : single; lon : single; strat : single; i : integer; begin DLLHandle := LoadLibrary('libiup.dll'); if DLLHandle <> 0 then begin { construct the function pointers } PF_GetError := GetProcAddress(DLLHandle, 'getError'); PF_SetPath := GetProcAddress(DLLHandle, 'setPath'); PF_GetStrat := GetProcAddress(DLLHandle, 'getStrat'); { If the function pointer is valid ... } if (PF_GetError <> nil) and (PF_SetPath <> nil) and (PF_GetStrat <> nil) then begin { Assign the function pointer to the function handle } @F_GetError := PF_GetError; @F_SetPath := PF_SetPath; @F_GetStrat := PF_GetStrat; errormsg := StrAlloc(4096); h5path := StrAlloc(256); StrCopy(h5path, 'z:\data\%Y%m.h5'); h5err := F_SetPath(h5path); if h5err < 0 then begin errormsg := F_GetError(); WriteLn(errormsg); end; for i := 1 to 10 do begin date := 4745; time := 12.34 + i/10; lat := -35.321 + i*i; lon := 115.67 - i*i; strat := F_GetStrat(date, time, lat, lon); if strat < 0. then begin errormsg := F_GetError(); WriteLn(errormsg); end; WriteLn('Value returned by getStrat call no. ' + IntToStr(i) + ': ' + FloatToStr(strat)); end; { and finally, delete the function pointers ...} PF_SetPath := nil; PF_GetStrat := nil; PF_GetError := nil; FreeLibrary(DLLHandle); WriteLn('Press ENTER to continue ...'); ReadLn; end else { The function pointer was not valid, so this means that the function was not found in the dll. } begin WriteLn('Function not found'); RaiseLastOSError; end; end else { The LoadLibrary function did not return a valid DLL handle. } begin WriteLn('DLL not loaded'); FreeLibrary(DLLHandle); WriteLn('Press ENTER to continue ...'); ReadLn; end; end. ``` dll.h ``` #ifndef LIBIUP_DLL_H_ #define LIBIUP_DLL_H_ #ifdef BUILD_DLL #define WIN32DLL_API __declspec(dllexport) #else #define WIN32DLL_API __declspec(dllimport) #endif #include "stratcalc/SimpleStratosphericColumnCalculator.h" #include <iostream> #include <string> #include "boost/date_time/posix_time/posix_time.hpp" #ifdef __cplusplus extern "C" { /* Assume C declarations for C++ */ #endif WIN32DLL_API BOOL __stdcall DllMain( HANDLE, DWORD, LPVOID); WIN32DLL_API int setPath(char*); WIN32DLL_API const char* getError(); WIN32DLL_API float getStrat(int, float, float, float); std::string errormsg; SimpleStratosphericColumnCalculator* calc; #ifdef __cplusplus } /* End of extern "C" */ #endif #endif ``` dll.cpp ``` #ifdef BUILD_DLL #include "windows.h" #include "dll.h" #include <iostream> // different functions of this library = new SimpleStratosphericColumnCalculator(); WIN32DLL_API BOOL __stdcall DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: calc = new SimpleStratosphericColumnCalculator(); break; case DLL_THREAD_ATTACH: calc = new SimpleStratosphericColumnCalculator(); break; case DLL_THREAD_DETACH: delete calc; break; case DLL_PROCESS_DETACH: delete calc; break; } return TRUE; } WIN32DLL_API int setPath(char* Path) { errormsg = ""; return calc->setPath(Path); } WIN32DLL_API const char* getError() { std::cout << errormsg << std::endl; return errormsg.c_str(); } WIN32DLL_API float getStrat(int Date, float Time, float Lat, float Lon) { errormsg = ""; if (Lat < -90. || Lat > 90.) errormsg += "Latitude value out of bounds.\n"; if (Lon < 0. || Lon > 360.) errormsg += "Longitude value out of bounds.\n"; if (errormsg != "") return -1.; return (float)calc->getStrat(Date, Time, Lat, Lon); } #else #endif ```
Check the calling conventions. I see stdcall in 2 functions and cdecl in one function. Try to change everything to stdcall or cdecl and see if it works
I think both DLL\_THREAD\_DETACH and DLL\_PROCESS\_DETACH will be called. So you'll be double deleting your calc object. Try... ``` if ( calc != NULL ) { delete calc; calc = NULL; } ```
AccessViolation when using C++ DLL from Delphi
[ "", "c++", "delphi", "dll", "access-violation", "" ]
Is there an easy way to convert a string array into a concatenated string? For example, I have a string array: ``` new string[]{"Apples", "Bananas", "Cherries"}; ``` And I want to get a single string: ``` "Apples,Bananas,Cherries" ``` Or `"Apples&Bananas&Cherries"` or `"Apples\Bananas\Cherries"`
A simple one... ``` string[] theArray = new string[]{"Apples", "Bananas", "Cherries"}; string s = string.Join(",",theArray); ```
The obvious choise is of course the String.Join method. Here's a LINQy alternative: ``` string.Concat(fruit.Select((s, i) => (i == 0 ? "" : ",") + s).ToArray()) ``` (Not really useful as it stands as it does the same as the Join method, but maybe for expanding where the method can't go, like alternating separators...)
Convert a string array to a concatenated string in C#
[ "", "c#", "arrays", "string", "" ]
I am creating some textboxes dynamically and I try to get their values when I click a button, but they are gone. I create the text boxes (declaration, initialization, adding them to the place holder) in another click button event. What shall I change to be able to read their values?
If you will create the controls on the Init stage (eg: Init event) on every request (eg, both postback and non-postback) then they will be available and will preserve their state.
There could be several reasons one of Them being your control initialization being executed prior to the event handler. This will be the case if you on post back initialize the controls in page\_load. The click event handler is executed after page\_load is run
When to create controls dynamically, so that when I click a button I can save their values?
[ "", "c#", "asp.net", "controls", "dynamic-controls", "" ]
How can I call a method on a form from a method called from an external class from a backgroundWorker? I believe that delegates are somehow the answer to this question, but after spending time reading, I still am confused by this problem. This is in Visual Studio 2008, the **backgroundWorker** is run from the form and calls **ExternalClass.Method**. The form is in *namespace* **ProgramName** and the **ExternalClass** is *using* **ProgramName**. When i declare *public delegate* **MyDelegate** in the *namespace* **ProgramName** in the file of my windows.form I can create an instance of **MyDelegate** and call it in a method of my form (but this does not help me), but if I try to create an instance of **MyDelegate** and call it from a method of my external class I cannot access the method of the windows.form, even though it is public. thanks yes, I want to pass progress reports (int percent, string status) back from **ExternalClass.Method**. Can you explain a bit more about that CSharpAtl (or anyone)?
Note that your question (afaik) is not just about the backgroundwiorker but just as much about how to break a circular reference between classes. This is a standard problem with a standard solution. You can pass a delegate (referring to a Form-method) around just as any object so also to a Backgroundworker. And the Bgw can pass it to the external method. A delegate includes a reference to the object (in this case the Form). Note that since you are on another thread you will need to use Control.Invoke inside the delegate, or use the Bgw ReportProgress event. ``` public partial class Form1 : Form { private void ReportProgresshandler(int percent, string state) { backgroundWorker1.ReportProgress(percent); // also does the Invoke } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { var ex = new ExampleClass(); ex.Dowork(ReportProgresshandler); } } ``` and something like ``` class ExampleClass { delegate void ReportDelegate(int percent, string status); public void Dowork(ReportDelegate report) { report(0, "starting"); } } ```
Please do yourself a favor and read up on the [BackgroundWorker Component](http://msdn.microsoft.com/en-us/library/c8dcext2.aspx), especially "[How to: Implement a Form That Uses a Background Operation](http://msdn.microsoft.com/en-us/library/waw3xexc.aspx)". Other resources: * [Windows Client Development Portal](http://windowsclient.net/) * [Using the BackgroundWorker Control](http://windowsclient.net/learn/video.aspx?v=12392) (video) * [Windows Forms Videos](http://windowsclient.net/learn/videos.aspx)
How can I call a method on a form from a method called from an external class from a backgroundWorker?
[ "", "c#", "visual-studio-2008", "class", "backgroundworker", "delegates", "" ]
Can one write something like: ``` class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass ``` This fails: self in @self is unknown I also tried: ``` @Test._decorator(self) ``` which also fails: Test unknown I would like to temporarily change some instance variables in the decorator and then run the decorated method, before changing them back.
Would something like this do what you need? ``` class Test(object): def _decorator(foo): def magic( self ) : print "start magic" foo( self ) print "end magic" return magic @_decorator def bar( self ) : print "normal call" test = Test() test.bar() ``` This avoids the call to self to access the decorator and leaves it hidden in the class namespace as a regular method. ``` >>> import stackoverflow >>> test = stackoverflow.Test() >>> test.bar() start magic normal call end magic >>> ``` --- edited to answer question in comments: How to use the hidden decorator in another class ``` class Test(object): def _decorator(foo): def magic( self ) : print "start magic" foo( self ) print "end magic" return magic @_decorator def bar( self ) : print "normal call" _decorator = staticmethod( _decorator ) class TestB( Test ): @Test._decorator def bar( self ): print "override bar in" super( TestB, self ).bar() print "override bar out" print "Normal:" test = Test() test.bar() print print "Inherited:" b = TestB() b.bar() print ``` Output: ``` Normal: start magic normal call end magic Inherited: start magic override bar in start magic normal call end magic override bar out end magic ```
What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid: ``` class Test(object): def _decorator(self, foo): foo() def bar(self): pass bar = self._decorator(bar) ``` It, of course, isn't valid since `self` isn't defined at that point. The same goes for `Test` as it won't be defined until the class itself is defined (which its in the process of). I'm showing you this code snippet because **this is what your decorator snippet transforms into.** So, as you can see, accessing the instance in a decorator like that isn't really possible since decorators are applied during the definition of whatever function/method they are attached to and not during instantiation. If you need **class-level access**, try this: ``` class Test(object): @classmethod def _decorator(cls, foo): foo() def bar(self): pass Test.bar = Test._decorator(Test.bar) ```
Python decorators in classes
[ "", "python", "class", "decorator", "self", "" ]
I have a class, Task, and it has a property TaskLibrary which is dll it will load and run some code from. So, any task has one library, but any library can have many tasks. My problem is that my test for making sure the task's Library property is not null is failing (so it could just be my test). My classes are effectively this: ``` public class Task { public virtual int TaskId {get;set;} public virtual string Locked {get;set;} public virtual int Status {get;set;} public virtual TaskLibrary Library {get;set;} } public class TaskLibrary { public virtual int LibraryId {get;set} public virtual string Name {get;set;} public virtual string Description {get;set;} public virtual byte[] Dll {get;set} public virtual IEnumerable<Task> Tasks {get;set;} } ``` My NHibernate mappings look like this: ``` <class name="Task"> <id name="Id" column="TaskId" type="Int32" unsaved-value="-1"> <generator class="identity"/> </id> <property name="Locked" column="Locked"/> <property name="Status" column="Status"/> <many-to-one name="Library" class="TaskLibrary" fetch="join"/> </class> <class name="TaskLibrary"> <id name="Id" column="LibraryId"> <generator class="identity"/> </id> <property name="Name"/> <property name="Description"/> <property name="Dll"/> <set name="Tasks" lazy="true"> <key column="LibraryId"/> <one-to-many class="Task"/> </set> </class> ``` My test class looks like this: ``` [TestFixture] public class TaskRepositoryFixture { private ISessionFactory _sessionFactory; private Configuration _configuration; private readonly Task[] _tasks = new[] { new Task {Id = 1, Status = 1, Locked = 0, Library = new TaskLibrary { Id =1, Description = "Test Library", Name = "Tast.dll", Type = "RunnableTask", Dll = Encoding.ASCII.GetBytes("test binary data")}}, new Task {Id = 2, Status = 1, Locked = 0, Library = new TaskLibrary { Id =1, Description = "Test Library", Name = "Tast.dll", Type = "RunnableTask", Dll = Encoding.ASCII.GetBytes("test binary data")}}, new Task {Id = 3, Status = 1, Locked = 0, Library = new TaskLibrary { Id =2, Description = "Test Library 2", Name = "Tast2.dll", Type = "RunnableTask", Dll = Encoding.ASCII.GetBytes("test binary data")}}, new Task {Id = 4, Status = 1, Locked = 0, Library = new TaskLibrary { Id =2, Description = "Test Library 2", Name = "Tast2.dll", Type = "RunnableTask", Dll = Encoding.ASCII.GetBytes("test binary data")}}, new Task {Id = 5, Status = 1, Locked = 0, Library = new TaskLibrary { Id =3, Description = "Test Library 3", Name = "Tast3.dll", Type = "RunnableTask", Dll = Encoding.ASCII.GetBytes("test binary data")}}, }; private readonly TaskLibrary[] _libraries = new[] { new TaskLibrary { Id =1, Description = "Test Library", Name = "Tast.dll", Type = "RunnableTask", BinaryDll = Encoding.ASCII.GetBytes("test binary data")}, new TaskLibrary { Id =2, Description = "Test Library 2", Name = "Tast2.dll", Type = "RunnableTask", BinaryDll = Encoding.ASCII.GetBytes("test binary data")}, new TaskLibrary { Id =3, Description = "Test Library 3", Name = "Tast3.dll", Type = "RunnableTask", BinaryDll = Encoding.ASCII.GetBytes("test binary data")} }; private void CreateInitialData() { using (ISession session = _sessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { foreach (var lib in _libraries) session.Save(lib); foreach (var task in _tasks) session.Save(task); transaction.Commit(); } } [TestFixtureSetUp] public void TestFixtureSetUp() { _configuration = new Configuration(); _configuration.Configure(); _configuration.AddAssembly("DistPollAutoTasksShared"); _sessionFactory = _configuration.BuildSessionFactory(); } [SetUp] public void SetupContext() { new SchemaExport(_configuration).Execute(false, true, false, false); CreateInitialData(); } [Test] public void CanGetLibraryFromTask() { ITaskRepository repository = new TaskRepository(); var fromDb = repository.GetById(_tasks[0].Id); Assert.IsNotNull(fromDb.Library); Assert.IsNotNull(fromDb.Library.Dll); } } ``` And, the Tasks table in the MSSQL2000 database is this: ``` CREATE TABLE [dbo].[Tasks]( [TaskId] [int] IDENTITY(1,1) NOT NULL, [TaskLibrary] [int] NOT NULL, [Status] [int] NOT NULL, [Locked] [int] NOT NULL ) ``` If you're still with me... From my Task class, I just want an instance of the TaskLibrary class for the Library property. Also, if I'm working with the libraries themselves, I want to be able to lazily retrieve an IEnumerable of all tasks using that library. However, when I run the test, I get this error: ``` TestCase 'DistPollAutoTasksShared.Tests.TaskRepositoryFixture.CanGetLibraryFromTask' failed: NHibernate.LazyInitializationException : Could not initialize proxy - no Session. at NHibernate.Proxy.AbstractLazyInitializer.Initialize() at NHibernate.Proxy.AbstractLazyInitializer.GetImplementation() at NHibernate.Proxy.Poco.Castle.CastleLazyInitializer.Intercept(IInvocation invocation) at Castle.DynamicProxy.AbstractInvocation.Proceed() at TaskLibraryProxy2bd44073e90f47298039abfbfda11492.get_Dll() ``` This is the first time I've used NHibernate, so I'm still learning. I really want to get a good foundation of the basics, so I'm stuck here until then. Any help, suggestions, reading material (I've read all of [this question's](https://stackoverflow.com/questions/1009110/learning-nhibernate) suggestions and some others) would be appreciated. **EDIT:** After changing fetch="join", I'm getting the functionality I want from the Task class. However, I've added another test for the Tasks property of the TaskLibrary class: ``` [Test] public void CanGetTasksByLibrary() { ITaskLibraryRepository repository = new TaskLibraryRepository(); var fromDb = repository.GetById(_libraries[0].Id).Tasks; Assert.IsNotNull(fromDb); Assert.True(fromDb.Count() == 2, "Cannot get IEnumerable<Task> from TaskLibrary"); } ``` But, an assertion fails with this error (I've updated the code above to reflect any changes I've made): ``` TestCase 'DistPollAutoTasksShared.Tests.TaskLibraryRepositoryFixture.CanGetTasksByLibrary' failed: Cannot get IEnumerable<Tasks> from TaskLibrary Expected: True But was: False ```
``` <many-to-one name="Library" class="TaskLibrary" fetch="join" /> ``` This would join the Library on every select. ``` <many-to-one name="Library" class="TaskLibrary" lazy="false" /> ``` This will eagerly execute separate select for the Library. Otherwise, it will lazy load the Library if you only set fetch="select" (which is the default). <http://ayende.com/Blog/archive/2009/04/09/nhibernate-mapping-ltmany-to-onegt.aspx> <http://nhibernate.info/doc/nh/en/index.html#collections-lazy>
did you try setting Lazy="false" in your mapping? <http://code-redefined.blogspot.com/2007/07/hibernate-lazy-fetch-problems-could-not.html>
Help me test a one-to-many realtionship with NHibernate and NUnit
[ "", "c#", "nhibernate", "nunit", "" ]
I have some native (as in `/SUBSYSTEM:NATIVE`) Windows programs that I'd like to generate minidumps for in case they crash. Normally, I'd use `dbghelp.dll`, but since native processes can only use functions exported from `ntdll.dll`, I can't. So I've implemented the dumper myself. It's almost done, but unfortunately, I've been unable to locate the list of unloaded modules in the crashed process (the list is certainly stored somewhere, since WinDbg is able to display it). Where do I find the list of unloaded modules in a Windows process? Edit: The list is certainly stored somewhere in the process memory, WinDbg can display the list even if I attach it after the modules were unloaded. There's also a note in [the documentation of WinDbg](http://msdn.microsoft.com/en-us/library/cc266720.aspx): > Microsoft Windows Server 2003 and later versions of Windows maintain an unloaded module list for user-mode processes. [...]
See [RtlGetUnloadEventTrace](http://msdn.microsoft.com/en-us/library/bb432428(VS.85).aspx) and [RtlGetUnloadEventTraceEx](http://msdn.microsoft.com/en-us/library/cc678403(VS.85).aspx). I am not entirely sure about how it works, but I believe the actual list is stored by ntdll.dll in the loader code. It keeps track of the 16 (or 64, according to MSDN) last unloaded DLLs in the specific process. The information is not linked from PEB or PEB\_LDR\_DATA.
If you need it just for native process, it's not necessary to find the list, as native process cannot load any dlls, so there are not any unloaded. But from technical point of view I'm curious where are the unloaded data located in process.
Where do I find the list of unloaded modules in a Windows process?
[ "", "c++", "windows", "dbghelp", "" ]
I am creating a login script that stores the value of a variable called `$userid` to `$_SESSION["userid"]` then redirects the user back to the main page (a side question is how to send them back where they were?). However, when I get back to that page, I am echoing the `session_id()` and the value of `$_SESSION["userid"]` and only the session id shows up. It had occurred to me that maybe my redirect page needs to have at the top, but if this were true, then the session\_id I'm echoing would change each time I end up on the page that is echoing it. Here is the script: ``` <?php session_start(); include_once("db_include.php5"); doDB(); //check for required fields from the form if ((empty($_POST['username']) && empty($_POST['email'])) || empty($_POST['password'])) { header("Location: loginform.php5"); exit; } else if($_POST["username"] && $_POST["password"]){ //create and issue the query $sql = "SELECT id FROM aromaMaster WHERE username='".$_POST["username"]."' AND password=PASSWORD('".$_POST["password"]."')"; $sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli)); //get the number of rows in the result set; should be 1 if a match if(mysqli_num_rows($sql_res) != 0) { //if authorized, get the userid while($info = mysqli_fetch_array($sql_res)) { $userid = $_info["id"]; } //set session variables $_SESSION['userid'] = $userid; mysqli_free_result($sql_res); //redirect to main page header("Location: loginredirect.php5"); exit; } } else if($_POST["email"] && $_POST["password"]) { //create and issue the query $sql = "SELECT id FROM aromaMaster WHERE email='".$_POST["email"]."' AND password=PASSWORD('".$_POST["password"]."')"; $sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli)); //get the number of rows in the result set; should be 1 if a match if(mysqli_num_rows($sql_res) != 0) { //if authorized, get the userid while($info = mysqli_fetch_array($sql_res)) { $userid = $_info["id"]; } //set session variables $_SESSION['userid'] = $userid; mysqli_free_result($sql_res); //redirect to main page header("Location: loginredirect.php5"); exit;} } else { //redirect back to login form header("Location: loginform.php5"); exit; } mysqli_close($mysqli); ?> ```
**You're doing this:** ``` while($info = mysqli_fetch_array($sql_res)) { $userid = $_info["id"]; } ``` **Where you should do this:** ``` while($info = mysqli_fetch_array($sql_res)) { $userid = $info["id"]; } ```
You need to call `session_write_close()` to store the session data changes. Side answer: you can use the `$SERVER["HTTP REFERER"]` to redirect back, if it was filled by the browser
$_SESSION difficulties
[ "", "php", "redirect", "authentication", "session", "" ]
I found this code snippet on a different post that I don't quite understand and would appriciate someone explaining. ``` private bool[] GetPageNumbersToLink(IPagedResult result) { if (result.TotalPages <= 9) return new bool[result.TotalPages + 1].Select(b => true).ToArray(); ... ``` [C# Array initialization - with non-default value](https://stackoverflow.com/questions/136836/c-array-initialization-with-non-default-value) My take on this: ``` new bool[result.TotalPages + 1] ``` this creates an array of bools with length equal to that of the totalpages, the default value being false on all of them. ``` .Select(b => true) ``` this uses a linq query to return only the items that are true, i.e. none of them ``` .ToArray(); ``` linq returns IEnumerable or something, so it needs to go back to a new array, of length 0 as none were selected in the first place. I think that's what it's doing, but it doesn't make any sense.
(EDIT: Oops, misread the post (unless it was edited without me noticing).) No, that's not what it's doing. The result is effectively: ``` Enumerable.Repeat(true, result.TotalPages + 1).ToArray(); ``` The `Select` call doesn't depend on the value that it's selecting at all - it's just returning `true` whatever the input is. `Select` doesn't perform filtering, just projection. In other words: ``` // Array filled with (result.TotalPages + 1) x false new bool[result.TotalPages + 1] // Sequence of length (result.TotalPages + 1) x true .Select(b => true) // Array filled with (result.TotalPages + 1) x true .ToArray(); ``` Anyway it's inefficient. It's occasionally unfortunate that .NET doesn't provide something like: ``` public static T[] CreateFilledArray<T>(T value, int size) { T[] ret = new T[size]; for (int i=0; i < size; i++) { ret[i] = value; } return ret; } ```
> `.Select(b => true)` > > this uses a linq query to return only the items that are true, i.e. none of them No, it means that for each item, it returns true. It doesn't do any test on the value of the array item This code just creates an array with all items set to true I prefer this form (no intermediate array) : ``` return new Enumerable.Range(0,result.TotalPages).Select(b => true).ToArray(); ```
Weird Inline Array Initialization
[ "", "c#", "arrays", "" ]
Why is this microtime showing up weird in PHP ``` $start4 = microtime(true); // run some php code $end4 = microtime(true); print "Time4: ". ($end4 - $start4)."<br />"; ``` The above is showing: Time4: 2.69412994385E-5 Something with a more complex, longer running process shows up like this instead: Time1: 0.000292062759399
E-5 is scientific notation. Seems to happen when you concatenate it with the string value. Try using number\_format... ? ``` print "Time4: ". number_format($end4 - $start4, 10)."<br />"; //or use: printf(".10f", $end - $start) ```
It's normal for long numbers (very small or very large) to be converted to powers of 10. The E-5 just means that the number displayed is beeing multiplied by (10/10/10/10/10) which makes it a very small number. 0.000000000000123 is much harder to read than 1.23E-13 (for example). Nevertheless if you do want to view the number in another format: ``` $start = microtime(true); $end = microtime(true); echo "Time: ", number_format($end - $start, 50); ``` This will add 50 decimal houses to the number on display. Hope it helps!
Why is this microtime showing up weird in PHP
[ "", "php", "" ]
Let's say I have a function which is being passed a string which originally came from getElementById, and I have an object with the same name as that string's value, is there a way to call that object? I won't know which object I want until I get that value from the element's ID. For Instance: ``` StartingFunction(SomeID){ someVariable = document.getElementById(SomeID).id somefuntion(someVariable) } someFunction(ElementID){ // need to call Object.Value of whichever object is named the same as the value of //ElementID here } ``` ElementID.Value obviously won't work since ElementID is just a variable, not an object...
You can pass the element directly to someFunction. For example: ``` StartingFunction(SomeID){ var element = document.getElementById(SomeID); somefuntion(element); } someFunction(element){ alert(element.id); alert(element.value); // Any other processing you want to do with element } ``` Or if you need to be able to get an element from an id just use `getElementById` ``` someFunction(id) { var element = document.getElementById(id); alert(element.value); // Any other processing you need to do with the element DOM object } ```
What you call ElementID is actually the element itself because you are passing document.getElementById() into somefunction.
Is it possible to use a variable to call an object who's name is the same as the variables value?
[ "", "javascript", "javascript-objects", "" ]
I've seen that some PHP functions are commented at the top, using a format that is unknown to me: ``` /** * * Convert an object to an array * * @param object $object The object to convert * @return array * */ ``` My IDE gives me a dropdown selection for the things such as @param and @return, so it must be documented somewhere. I've tried searching google but it won't include the @ symbol in its search. What is this format of commenting and where can I find some information on it?
That's [PHPDoc](https://en.wikipedia.org/wiki/PHPDoc) syntax. Read more here: *[phpDocumentor](http://www.phpdoc.org/)*
### Functions: ``` /** * Does something interesting * * @param Place $where Where something interesting takes place * @param integer $repeat How many times something interesting should happen * * @throws Some_Exception_Class If something interesting cannot happen * @author Monkey Coder <mcoder@facebook.com> * @return Status */ ``` ### Classes: ``` /** * Short description for class * * Long description for class (if any)... * * @copyright 2006 Zend Technologies * @license http://www.zend.com/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://dev.zend.com/package/PackageName * @since Class available since Release 1.2.0 */ ``` ### Sample File: ``` <?php /** * Short description for file * * Long description for file (if any)... * * PHP version 5.6 * * LICENSE: This source file is subject to version 3.01 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_01.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category CategoryName * @package PackageName * @author Original Author <author@example.com> * @author Another Author <another@example.com> * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_01.txt PHP License 3.01 * @version SVN: $Id$ * @link http://pear.php.net/package/PackageName * @see NetOther, Net_Sample::Net_Sample() * @since File available since Release 1.2.0 * @deprecated File deprecated in Release 2.0.0 */ /** * This is a "Docblock Comment," also known as a "docblock." The class' * docblock, below, contains a complete description of how to write these. */ require_once 'PEAR.php'; // {{{ constants /** * Methods return this if they succeed */ define('NET_SAMPLE_OK', 1); // }}} // {{{ GLOBALS /** * The number of objects created * @global int $GLOBALS['_NET_SAMPLE_Count'] */ $GLOBALS['_NET_SAMPLE_Count'] = 0; // }}} // {{{ Net_Sample /** * An example of how to write code to PEAR's standards * * Docblock comments start with "/**" at the top. Notice how the "/" * lines up with the normal indenting and the asterisks on subsequent rows * are in line with the first asterisk. The last line of comment text * should be immediately followed on the next line by the closing asterisk * and slash and then the item you are commenting on should be on the next * line below that. Don't add extra lines. Please put a blank line * between paragraphs as well as between the end of the description and * the start of the @tags. Wrap comments before 80 columns in order to * ease readability for a wide variety of users. * * Docblocks can only be used for programming constructs which allow them * (classes, properties, methods, defines, includes, globals). See the * phpDocumentor documentation for more information. * http://phpdoc.org/tutorial_phpDocumentor.howto.pkg.html * * The Javadoc Style Guide is an excellent resource for figuring out * how to say what needs to be said in docblock comments. Much of what is * written here is a summary of what is found there, though there are some * cases where what's said here overrides what is said there. * http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#styleguide * * The first line of any docblock is the summary. Make them one short * sentence, without a period at the end. Summaries for classes, properties * and constants should omit the subject and simply state the object, * because they are describing things rather than actions or behaviors. * * Below are the tags commonly used for classes. @category through @version * are required. The remainder should only be used when necessary. * Please use them in the order they appear here. phpDocumentor has * several other tags available, feel free to use them. * * @category CategoryName * @package PackageName * @author Original Author <author@example.com> * @author Another Author <another@example.com> * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_01.txt PHP License 3.01 * @version Release: @package_version@ * @link http://pear.php.net/package/PackageName * @see NetOther, Net_Sample::Net_Sample() * @since Class available since Release 1.2.0 * @deprecated Class deprecated in Release 2.0.0 */ class Net_Sample { // {{{ properties /** * The status of foo's universe * Potential values are 'good', 'fair', 'poor' and 'unknown'. * @var string $foo */ public $foo = 'unknown'; /** * The status of life * Note that names of private properties or methods must be * preceeded by an underscore. * @var bool $_good */ private $_good = true; // }}} // {{{ setFoo() /** * Registers the status of foo's universe * * Summaries for methods should use 3rd person declarative rather * than 2nd person imperative, beginning with a verb phrase. * * Summaries should add description beyond the method's name. The * best method names are "self-documenting", meaning they tell you * basically what the method does. If the summary merely repeats * the method name in sentence form, it is not providing more * information. * * Summary Examples: * + Sets the label (preferred) * + Set the label (avoid) * + This method sets the label (avoid) * * Below are the tags commonly used for methods. A @param tag is * required for each parameter the method has. The @return * and @access tags are mandatory. The @throws tag is required if * the method uses exceptions. @static is required if the method can * be called statically. The remainder should only be used when * necessary. Please use them in the order they appear here. * phpDocumentor has several other tags available, feel free to use * them. * * The @param tag contains the data type, then the parameter's * name, followed by a description. By convention, the first noun in * the description is the data type of the parameter. Articles like * "a", "an", and "the" can precede the noun. The descriptions * should start with a phrase. If further description is necessary, * follow with sentences. Having two spaces between the name and the * description aids readability. * * When writing a phrase, do not capitalize and do not end with a * period: * + the string to be tested * * When writing a phrase followed by a sentence, do not capitalize the * phrase, but end it with a period to distinguish it from the start * of the next sentence: * + the string to be tested. Must use UTF-8 encoding. * * Return tags should contain the data type then a description of * the data returned. The data type can be any of PHP's data types * (int, float, bool, string, array, object, resource, mixed) * and should contain the type primarily returned. For example, if * a method returns an object when things work correctly but false * when an error happens, say 'object' rather than 'mixed.' Use * 'void' if nothing is returned. * * Here's an example of how to format examples: * <code> * require_once 'Net/Sample.php'; * * $s = new Net_Sample(); * if (PEAR::isError($s)) { * echo $s->getMessage() . "\n"; * } * </code> * * Here is an example for non-php example or sample: * <samp> * pear install net_sample * </samp> * * @param string $arg1 the string to quote * @param int $arg2 an integer of how many problems happened. * Indent to the description's starting point * for long ones. * * @return int the integer of the set mode used. FALSE if foo * foo could not be set. * @throws exceptionclass [description] * * @access public * @static * @see Net_Sample::$foo, Net_Other::someMethod() * @since Method available since Release 1.2.0 * @deprecated Method deprecated in Release 2.0.0 */ function setFoo($arg1, $arg2 = 0) { /* * This is a "Block Comment." The format is the same as * Docblock Comments except there is only one asterisk at the * top. phpDocumentor doesn't parse these. */ if ($arg1 == 'good' || $arg1 == 'fair') { $this->foo = $arg1; return 1; } elseif ($arg1 == 'poor' && $arg2 > 1) { $this->foo = 'poor'; return 2; } else { return false; } } // }}} } // }}} /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?> ``` Source: [PEAR Docblock Comment standards](http://pear.php.net/manual/en/standards.sample.php)
PHP function comments
[ "", "php", "function", "comments", "format", "phpdoc", "" ]
Is there anyway to unload a page that has been loaded inside an iframe? I do not want to change the iframe src to a blank page if possible. I am basically looking for something that will do something like this `$('#frameID').attr("src","");` except that code does not seem to clear the previously loaded page. Is there a `"unload"` function that I can call which will reset the iframe so that it does not have any content loaded inside?
The other solutions use `innerHTML`, which won't always work in XHTML. They also only clear `document.body` (anything in the `<head>` is still present). Here is a solution that uses the DOM: ``` var frame = document.getElementById("myFrame"), frameDoc = frame.contentDocument || frame.contentWindow.document; frameDoc.removeChild(frameDoc.documentElement); ``` This solution uses `innerHTML`: ``` var frame = document.getElementById("myFrame"), frameDoc = frame.contentDocument || frame.contentWindow.document; frameDoc.documentElement.innerHTML = ""; ```
If you **generate dynamically the content of your iframe**, all scripts/variable loaded will leak from one write to another. Thus the solution provided by @Eli of clearing the dom element **will not work**. **In short:** To clean, wrap your iframe into a div element and replace its dom content. ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div id="wrapper"> <iframe id="test"></iframe> </div> </body> </html> ``` To clean: ``` var wrapper = document.getElementById('wrapper'); wrapper.innerHTML= "<iframe id='test'></iframe>"; ``` **In details: Demo of script leakage** Example of script leakage between two iframe writes (tested with Chrome): ``` var iframe = document.getElementById('test'); // define variable 'a' var content = "<html><body><script>var a=555;</script></body></html>"; iframe.contentWindow.document.open(); iframe.contentWindow.document.write(content); iframe.contentWindow.document.close(); // uncomment this to clean the iframe //document.getElementById('wrapper').innerHTML= "<iframe id='test'></iframe>"; // write 'a' if defined var content2 = "<html><body><div id='content'></div><script>document.getElementById('content').innerHTML=typeof a === 'undefined' ? 'undefined' : a;</script></body></html>"; var iframe2 = document.getElementById('test'); iframe2.contentWindow.document.open(); iframe2.contentWindow.document.write(content2); iframe2.contentWindow.document.close(); ``` If you run this code, you will see the output of the second iframe is `555` although it has been defined in the first iframe. If you uncomment the middle part it will work as expected. Related question: [Avoiding memory leaks loading content into an iframe](https://stackoverflow.com/questions/18644462/avoiding-memory-leaks-loading-content-into-an-iframe)
Unloading/Removing content from an iFrame
[ "", "javascript", "jquery", "events", "dom", "iframe", "" ]
I'm looking around for an open source form building package for PHP, and figured the hive-mob-mind of StackOverflow might be able to tilt me in the right direction. Specifically, I'm looking for a form/survey builder application. I want something that lets an end user use a web based GUI to create and configure/surveys and web-based forms. What are the de-facto standard tools/packages that people use for this kind of thing these days. I'm interested in software packages, **not** in hosted services.
I don't know of a stand-alone package, but I know some CMS solutions have this. Maybe you could look into their code base and if it's modulare use it in your project. One I know of that uses it is [WebSiteBaker](http://php.opensourcecms.com/scripts/details.php?scriptid=69&name=Website%20Baker). Don't know if the code is any good thoug.
php-form-builder-class is an open-source project hosted on Google's Project Hosting service - <http://code.google.com/p/php-form-builder-class/>. There are many examples included to get you started quickly. I don't believe there is currently a GUI provided for end users to build forms though. I use this in my development and would recommend.
Form Builder GUI for PHP
[ "", "php", "html", "user-interface", "forms", "" ]
I'm creating my own very basic Grid control. I've decided to derive from ScrollableControl (this is what DataGridView seems to do) and go from there. I have a lot of code in place to draw my cells, but I am having difficulty figuring out how to utilize the "scrollable" part of the ScrollableControl. It seems that ScrollableControl's designed to be a container of other controls, and it's "auto" scrolling features are oriented around child controls that are outside the bounds of the control. I'm just looking to set the "virtual" area of the control so I get scroll bars of the correct size, then I do my own drawing into the control to create my own "view". I'm basically very frustrated by this. What's the simplest way to get this to work?
You have to set the [`AutoScrollMinSize` property](http://msdn.microsoft.com/en-us/library/system.windows.forms.scrollablecontrol.autoscrollminsize.aspx) to tell the control what area you intend to render.
As far as I know, you would need to have *some* child of ScrollableControl positioned at the lower-right bounds of your virtual surface. Perhaps a PictureBox with a 1 pixel transparent image would do. FYI you may want to look at [SourceGrid](http://www.devage.com/sourcegrid/SourceGrid_EN.html), either as a design inspiration (it makes good use of the MVC pattern), or perhaps it will solve your problem and you will not want to roll your own. EDIT: Doh! I'm pretty sure Michael's solution is correct/better. However you may still want to have a look at SourceGrid.
Creating "virtual" ScrollableControl?
[ "", "c#", "winforms", "scroll", "" ]
I have a simple query which loops and I want to see the PRINT messages during the execution. The query is something like this: ``` WHILE 1 = 1 BEGIN WAITFOR DELAY '000:00:10' PRINT 'here' END ``` The `PRINT 'here'` does not output until I stop the process. However, I want to see it while it's running. Is this possible?
I believe that the prints get buffered, releasing "chunks" as the buffer fills up. try using raiserror: [How do I flush the PRINT buffer in TSQL?](https://stackoverflow.com/questions/306945/how-do-i-flush-the-print-buffer-in-tsql)
You can use RAISERROR with serverity 0 and the NOWAIT option ``` WHILE 1 = 1 BEGIN WAITFOR DELAY '000:00:10' RAISERROR ('here', 0, 1) WITH NOWAIT END ```
T-SQL Output Message During execution in SSMS
[ "", "sql", "sql-server", "" ]
I want to convert an excel file to an image (every format is ok) programmatically (c#). Currently I'm using Microsoft Interop Libraries & Office 2007, but it does not support saving to an image by default. So my current work-around is as follows: * Open Excel file using Microsoft Interop; * Find out the max range (that contains data); * Use the CopyPicture() on that range, which will copy the data to the Clipboard. Now the tricky part (and my problems): **Problem 1:** Using the .NET Clipboard class, I'm not able to get the EXACT copied data from the clipboard: the data is the same, but somehow the formatting is distorted (the font of the whole document seems to become bold and a little bit more unreadable while they were not); If I paste from the clipboard using mspaint.exe, the pasted image is correct (and just as I want it to be). I disassembled mspaint.exe and found a function that it is using (OleGetClipboard) to get data from the clipboard, but I cannot seem to get it working in C# / .NET. Other things I tried were the Clipboard WINAPI's (OpenClipboard, GetClipboardData, CF\_ENHMETAFILE), but the results were the same as using the .NET versions. **Problem 2:** Using the range and CopyPicture, if there are any images in the excel sheet, those images are not copied along with the surrounding data to the clipboard. **Some of the source code** ``` Excel.Application app = new Excel.Application(); app.Visible = app.ScreenUpdating = app.DisplayAlerts = false; app.CopyObjectsWithCells = true; app.CutCopyMode = Excel.XlCutCopyMode.xlCopy; app.DisplayClipboardWindow = false; try { Excel.Workbooks workbooks = null; Excel.Workbook book = null; Excel.Sheets sheets = null; try { workbooks = app.Workbooks; book = workbooks.Open(inputFile, false, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); sheets = book.Worksheets; } catch { Cleanup(workbooks, book, sheets); //Cleanup function calls Marshal.ReleaseComObject for all passed objects throw; } for (int i = 0; i < sheets.Count; i++) { Excel.Worksheet sheet = (Excel.Worksheet)sheets.get_Item(i + 1); Excel.Range myrange = sheet.UsedRange; Excel.Range rowRange = myrange.Rows; Excel.Range colRange = myrange.Columns; int rows = rowRange.Count; int cols = colRange.Count; //Following is used to find range with data string startRange = "A1"; string endRange = ExcelColumnFromNumber(cols) + rows.ToString(); //Skip "empty" excel sheets if (startRange == endRange) { Excel.Range firstRange = sheet.get_Range(startRange, endRange); Excel.Range cellRange = firstRange.Cells; object text = cellRange.Text; string strText = text.ToString(); string trimmed = strText.Trim(); if (trimmed == "") { Cleanup(trimmed, strText, text, cellRange, firstRange, myrange, rowRange, colRange, sheet); continue; } Cleanup(trimmed, strText, text, cellRange, firstRange); } Excel.Range range = sheet.get_Range(startRange, endRange); try { range.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlPicture); //Problem here <------------- //Every attempt to get data from Clipboard fails } finally { Cleanup(range); Cleanup(myrange, rowRange, colRange, sheet); } } //end for loop book.Close(false, Type.Missing, Type.Missing); workbooks.Close(); Cleanup(book, sheets, workbooks); } finally { app.Quit(); Cleanup(app); GC.Collect(); } ``` Getting data from the clipboard using WINAPI succeeds, but with bad quality. Source: ``` protected virtual void ClipboardToPNG(string filename) { if (OpenClipboard(IntPtr.Zero)) { if (IsClipboardFormatAvailable((int)CLIPFORMAT.CF_ENHMETAFILE)) { int hEmfClp = GetClipboardDataA((int)CLIPFORMAT.CF_ENHMETAFILE); if (hEmfClp != 0) { int hEmfCopy = CopyEnhMetaFileA(hEmfClp, null); if (hEmfCopy != 0) { Metafile metafile = new Metafile(new IntPtr(hEmfCopy), true); metafile.Save(filename, ImageFormat.Png); } } } CloseClipboard(); } } ``` Anyone got a solution? (I'm using .NET 2.0 btw)
[SpreadsheetGear for .NET](http://www.spreadsheetgear.com/) will do it. You can see our ASP.NET (C# and VB) "*Excel Chart and Range Imaging Samples*" samples [here](http://www.spreadsheetgear.com/support/samples/imaging.aspx) and download a free trial [here](https://www.spreadsheetgear.com/downloads/register.aspx) if you want to try it out. SpreadsheetGear also works with Windows Forms, console applications, etc... (you did not specify what type of application you are creating). There is also a Windows Forms control to display a workbook in your application if that is what you are really after. Disclaimer: I own SpreadsheetGear LLC
From what I understand from your question I am not able to reproduce the problem. I selected a range manually in Excel, chose *Copy As Picture* with the options *as shown on screen* and *Bitmap* selected, then I used the following code to save the clipboard data: ``` using System; using System.IO; using System.Windows; using System.Windows.Media.Imaging; using System.Drawing.Imaging; using Excel = Microsoft.Office.Interop.Excel; public class Program { [STAThread] static void Main(string[] args) { Excel.Application excel = new Excel.Application(); Excel.Workbook wkb = excel.Workbooks.Add(Type.Missing); Excel.Worksheet sheet = wkb.Worksheets[1] as Excel.Worksheet; Excel.Range range = sheet.Cells[1, 1] as Excel.Range; range.Formula = "Hello World"; // copy as seen when printed range.CopyPicture(Excel.XlPictureAppearance.xlPrinter, Excel.XlCopyPictureFormat.xlPicture); // uncomment to copy as seen on screen //range.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap); Console.WriteLine("Please enter a full file name to save the image from the Clipboard:"); string fileName = Console.ReadLine(); using (FileStream fileStream = new FileStream(fileName, FileMode.Create)) { if (Clipboard.ContainsData(System.Windows.DataFormats.EnhancedMetafile)) { Metafile metafile = Clipboard.GetData(System.Windows.DataFormats.EnhancedMetafile) as Metafile; metafile.Save(fileName); } else if (Clipboard.ContainsData(System.Windows.DataFormats.Bitmap)) { BitmapSource bitmapSource = Clipboard.GetData(System.Windows.DataFormats.Bitmap) as BitmapSource; JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.QualityLevel = 100; encoder.Save(fileStream); } } object objFalse = false; wkb.Close(objFalse, Type.Missing, Type.Missing); excel.Quit(); } } ``` Regarding your second problem: As far as I know it is not possible in Excel to select both a cell range and an image at the same time. If you want to get both in an image at the same time you might have to print the Excel sheet to an image/PDF/XPS file.
Programmatically (C#) convert Excel to an image
[ "", "c#", "excel", "image", "interop", "clipboard", "" ]
I'm trying to load a tree of objects via XML serialisation, and at the moment it will load the objects in, and create the tree quite happily. My issue revolves around the fact that these classes support a level of auditing. What I'd like to be able to do is call some method on each object after it has finished being loaded. For the sake of argument, assume I have a fairly generic object tree with differing classes at different levels, like: ``` <Customer name="Foo Bar Inc."> <Office IsHq="True"> <Street>123 Any Street</Street> <Town name="Anytown"> <State name="Anystate"> <Country name="My Country" /> </State> </Town> </Office> <Office IsHq="False"> <Street>456 High Street</Street> <Town name="Anycity"> <State name="Anystate"> <Country name="My Country" /> </State> </Town> </Office> </Customer> ``` Is there any way using the default serialisers (In the similar way that you can create methods like `ShouldSerializeFoo`) to determine when loading has finished for each object? **Edit:** I should point out that the obvious case of exposing something akin to an `OnLoaded()` method that I *could* call after deserialising, strikes me as being a "bad thing to do". **Edit2:** For the sake of discussion this is my current hack "approach", which works for the basic level, but the child City node still thinks it needs to be saved with changes (in the real world the object model is a lot more complex, but this will at least compile, without the need for full source) ``` public class Office { [XmlAttribute("IsHq")] public bool IsHeadquarters { get; set; } [XmlElement] public string Street { get; set; } [XmlElement] public Town Town { get; set; } protected virtual void OnLoaded() {} public static OfficeCollection Search() { OfficeCollection retval = new OfficeCollection(); string xmlString = @" <Office IsHq='True'> <Street>123 Any Street</Street> <Town name='Anytown'> <State name='Anystate'> <Country name='My Country' /> </State> </Town> </Office>"; XmlSerializer xs = new XmlSerializer(retval.GetType()); XmlReader xr = new XmlTextReader(xmlString); retval = (OfficeCollection)xs.Deserialize(xr); foreach (Office thisOffice in retval) { thisOffice.OnLoaded(); } return retval; } } ```
Hmmm... it's still not pretty but you could refactor your deserialization logic into a dedicated class which could notify the deserialized object that it originated from XML before returning it to the caller. **Update:** I think this should be fairly easy to do without straying too far from the patterns laid by the framework... you'd just need to ensure that you use the CustomXmlSerializer. Classes that need this notification just need to implement IXmlDeserializationCallback ``` using System.Xml.Serialization; namespace Custom.Xml.Serialization { public interface IXmlDeserializationCallback { void OnXmlDeserialization(object sender); } public class CustomXmlSerializer : XmlSerializer { protected override object Deserialize(XmlSerializationReader reader) { var result = base.Deserialize(reader); var deserializedCallback = result as IXmlDeserializationCallback; if (deserializedCallback != null) { deserializedCallback.OnXmlDeserialization(this); } return result; } } } ```
The accepted solution didn't quite work for me. The overridden `Deserialize()` method never got called. I believe this is because that method is not public and is therefore called by one (or more) of the public `Deserialize()` methods, but not all of them. Here's an implementation that works by method hiding and makes use of the existing `IDeserializationCallback` interface so any deserialization using non-xml methods can still trigger the `OnDeserialization()` method of that interface. It also uses reflection to traverse child properties to see if they also implement `IDeserializationCallback` and calls them accordingly. ``` using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Xml; using System.Xml.Serialization; namespace Xml.Serialization { class XmlCallbackSerializer : XmlSerializer { public XmlCallbackSerializer(Type type) : base(type) { } public XmlCallbackSerializer(XmlTypeMapping xmlTypeMapping) : base(xmlTypeMapping) { } public XmlCallbackSerializer(Type type, string defaultNamespace) : base(type, defaultNamespace) { } public XmlCallbackSerializer(Type type, Type[] extraTypes) : base(type, extraTypes) { } public XmlCallbackSerializer(Type type, XmlAttributeOverrides overrides) : base(type, overrides) { } public XmlCallbackSerializer(Type type, XmlRootAttribute root) : base(type, root) { } public XmlCallbackSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : base(type, overrides, extraTypes, root, defaultNamespace) { } public XmlCallbackSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) : base(type, overrides, extraTypes, root, defaultNamespace, location) { } public new object Deserialize(Stream stream) { var result = base.Deserialize(stream); CheckForDeserializationCallbacks(result); return result; } public new object Deserialize(TextReader textReader) { var result = base.Deserialize(textReader); CheckForDeserializationCallbacks(result); return result; } public new object Deserialize(XmlReader xmlReader) { var result = base.Deserialize(xmlReader); CheckForDeserializationCallbacks(result); return result; } public new object Deserialize(XmlSerializationReader reader) { var result = base.Deserialize(reader); CheckForDeserializationCallbacks(result); return result; } public new object Deserialize(XmlReader xmlReader, string encodingStyle) { var result = base.Deserialize(xmlReader, encodingStyle); CheckForDeserializationCallbacks(result); return result; } public new object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { var result = base.Deserialize(xmlReader, events); CheckForDeserializationCallbacks(result); return result; } public new object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) { var result = base.Deserialize(xmlReader, encodingStyle, events); CheckForDeserializationCallbacks(result); return result; } private void CheckForDeserializationCallbacks(object deserializedObject) { var deserializationCallback = deserializedObject as IDeserializationCallback; if (deserializationCallback != null) { deserializationCallback.OnDeserialization(this); } var properties = deserializedObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var propertyInfo in properties) { if (propertyInfo.PropertyType.GetInterface(typeof(IEnumerable<>).FullName) != null) { var collection = propertyInfo.GetValue(deserializedObject) as IEnumerable; if (collection != null) { foreach (var item in collection) { CheckForDeserializationCallbacks(item); } } } else { CheckForDeserializationCallbacks(propertyInfo.GetValue(deserializedObject)); } } } } } ```
How do you find out when you've been loaded via XML Serialization?
[ "", "c#", ".net", "serialization", "xml-serialization", "" ]
How can I "reset" a namespace to the global one? Given the following code: ``` namespace foo; include 'myfile.php'; ``` myfile.php will now try to load all of its classes in the foo namespace, even though its classes are in the global namespace. Now it wouldn't be a big deal to swap the order of those lines, but how would I deal with myfile.php having an autoloader? It will try to load the classes in namespace foo.
Namespaces work on a *per-file* basis. If myfile.php doesn't declare any namespace then everything in it will belong to the global namespace, regardless of the namespace in which `include` was used. Long story short, `namespace` declarations only apply to their own file, not includes.
myfile.php should declare the namespace that it wants to be in. If you want to ensure that myfile.php loads in the global namespace, I believe you can put ``` namespace // empty namespace means global { } ``` around the body of myfile.php. Make sure that you use the braces, or else you'll redefine the rest of the file in which myfile.php is included to also be in the global namespace.
Resetting a namespace in PHP?
[ "", "php", "namespaces", "" ]
I want to start nutch from Java. How can I start cygwin from a Java program?
First of all you have to set the bash.exe to environment variable so this line will start bash. ``` Runtime rt= Runtime().getRuntime().execute("bash"); ```
Rather than use Java to start Cygwin in order to invoke nutch you should probably look into integrating Nutch directly with your Java app. There's some documentation [here](http://today.java.net/pub/a/today/2006/02/16/introduction-to-nutch-2.html): *"While the Nutch web app is a great way to get started with search, most projects using Nutch require the search function to be more tightly integrated with their application. There are various ways to achieve this, depending on the application. The two ways we'll look at here are using the Nutch API and using the OpenSearch API."*
How can I run cygwin from Java?
[ "", "java", "" ]
I am building a custom shopping cart where CC numbers and Exp date will be stored in a database until processing (then deleted). I need to encrypt this data (obviously). I want to use the RSACryptoServiceProvider class. Here is my code to create my keys. ``` public static void AssignNewKey(){ const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "KeyContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); string publicPrivateKeyXML = rsa.ToXmlString(true); string publicOnlyKeyXML = rsa.ToXmlString(false); // do stuff with keys... } ``` Now the plan is to store the private key xml on a USB drive attached to the managers key chain. Whenever a manager leaves the company I want to be able to generate new public and private keys (and re-encrypt all currently stored CC numbers with the new public key). My problem is that the keys generated by this code are always the same. How would I generate a unique set of keys every time? **UPDATE.** My test code is below.: *note: the "privatekey" parameter here is the original private key. In order for the keys to be changed I need to verify that the private key is valid.* In Default.aspx.cs ``` public void DownloadNewPrivateKey_Click(object sender, EventArgs e) { StreamReader reader = new StreamReader(fileUpload.FileContent); string privateKey = reader.ReadToEnd(); Response.Clear(); Response.ContentType = "text/xml"; Response.End(); Response.Write(ChangeKeysAndReturnNewPrivateKey(privateKey)); } ``` In Crytpography.cs: ``` public static privateKey; public static publicKey; public static RSACryptoServiceProvider rsa; public static string ChangeKeysAndReturnNewPrivateKey(string _privatekey) { string testData = "TestData"; string testSalt = "salt"; // encrypt the test data using the exisiting public key... string encryptedTestData = EncryptData(testData, testSalt); try { // try to decrypt the test data using the _privatekey provided by user... string decryptTestData = DecryptData(encryptedTestData, _privatekey, testSalt); // if the data is successfully decrypted assign new keys... if (decryptTestData == testData) { AssignNewKey(); // "AssignNewKey()" should set "privateKey" to the newly created private key... return privateKey; } else { return string.Empty; } } catch (Exception ex) { return string.Empty; } } public static void AssignParameter(){ const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "KeyContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); } public static void AssignNewKey() { AssignParameter(); using (SqlConnection myConn = new SqlConnection(Utilities.ConnectionString)) { SqlCommand myCmd = myConn.CreateCommand(); string publicPrivateKeyXML = rsa.ToXmlString(true); privateKey = publicPrivateKeyXML; // sets the public variable privateKey to the new private key. string publicOnlyKeyXML = rsa.ToXmlString(false); publicKey = publicOnlyKeyXML; // sets the public variable publicKey to the new public key. myCmd.CommandText = "UPDATE Settings SET PublicKey = @PublicKey"; myCmd.Parameters.AddWithValue("@PublicKey", publicOnlyKeyXML); myConn.Open(); myComm.ExecuteScalar(); } } public static string EncryptData(string data2Encrypt, string salt) { AssignParameter(); using (SqlConnection myConn = new SqlConnection(Utilities.ConnectionString)) { SqlCommand myCmd = myConn.CreateCommand(); myCmd.CommandText = "SELECT TOP 1 PublicKey FROM Settings"; myConn.Open(); using (SqlDataReader sdr = myCmd.ExecuteReader()) { if (sdr.HasRows) { DataTable dt = new DataTable(); dt.Load(sdr); rsa.FromXmlString(dt.Rows[0]["PublicKey"].ToString()); } } } //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt + salt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } public static string DecryptData(string data2Decrypt, string privatekey, string salt) { AssignParameter(); byte[] getpassword = Convert.FromBase64String(data2Decrypt); string publicPrivateKeyXML = privatekey; rsa.FromXmlString(publicPrivateKeyXML); //read ciphertext, decrypt it to plaintext byte[] plain = rsa.Decrypt(getpassword, false); string dataAndSalt = System.Text.Encoding.UTF8.GetString(plain); return dataAndSalt.Substring(0, dataAndSalt.Length - salt.Length); } ```
What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following: ``` public static string ConvertToNewKey(string oldPrivateKey) { // get the current container name from the database... rsa.PersistKeyInCsp = false; rsa.Clear(); rsa = null; string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database... // re-encrypt existing data to use the new keys and write to database... return privateKey; } public static string AssignNewKey(bool ReturnPrivateKey){ string containerName = DateTime.Now.Ticks.ToString(); // create the new key... // saves container name and public key to database... // and returns Private Key XML. } ``` before creating the new key.
When you use a code like this: ``` using (var rsa = new RSACryptoServiceProvider(1024)) { // Do something with the key... // Encrypt, export, etc. } ``` .NET (actually Windows) stores your key in a *persistent* key container forever. The container is randomly generated by .NET This means: 1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account. 2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute). To resolve these issues: ``` using (var rsa = new RSACryptoServiceProvider(1024)) { try { // Do something with the key... // Encrypt, export, etc. } finally { rsa.PersistKeyInCsp = false; } } ``` **ALWAYS**
How to Generate Unique Public and Private Key via RSA
[ "", "c#", "encryption", "cryptography", "rsa", "key", "" ]
I'd like to store 0 to ~5000 IP addresses in a plain text file, with an unrelated header at the top. Something like this: ``` Unrelated data Unrelated data ----SEPARATOR---- 1.2.3.4 5.6.7.8 9.1.2.3 ``` Now I'd like to find if '5.6.7.8' is in that text file using PHP. I've only ever loaded an entire file and processed it in memory, but I wondered if there was a more efficient way of searching a text file in PHP. I only need a true/false if it's there. Could anyone shed any light? Or would I be stuck with loading in the whole file first? Thanks in advance!
5000 isn't a lot of records. You could easily do this: ``` $addresses = explode("\n", file_get_contents('filename.txt')); ``` and search it manually and it'll be quick. If you were storing a lot more I would suggest storing them in a database, which is designed for that kind of thing. But for 5000 I think the full load plus brute force search is fine. Don't optimize a problem until you have a problem. There's no point needlessly overcomplicating your solution.
I'm not sure if perl's command line tool needs to load the whole file to handle it, but you could do something similar to this: ``` <?php ... $result = system("perl -p -i -e '5\.6\.7\.8' yourfile.txt"); if ($result) .... else .... ... ?> ``` Another option would be to store the IP's in separate files based on the first or second group: ``` # 1.2.txt 1.2.3.4 1.2.3.5 1.2.3.6 ... # 5.6.txt 5.6.7.8 5.6.7.9 5.6.7.10 ... ... etc. ``` That way you wouldn't necessarily have to worry about the files being so large you incur a performance penalty by loading the whole file into memory.
Efficient flat file searching in PHP
[ "", "php", "search", "file", "" ]
It apparently doesn't seem to be an impossible question, but I can't find a way to populate an HtmlTable control (which is accessible from codebehind) with an HtmlTable object already filled with data. Can anybody help me on this ?? Regards, **EDIT** In the ASP page, I have an HTML table with ID="table1" In codebehind, I first populate an HtmlTable Object from a List doing like this : ``` HtmlTable localTable1 = new HtmlTable(); HtmlTableCell cell1 = new HtmlTableCell(); HtmlTableCell cell2 = new HtmlTableCell(); foreach (Evaluation eval in theEvaluations) { HtmlTableRow anEvaluation = new HtmlTableRow(); cell1.InnerText = eval.attr1; anEvaluation.Cells.Add(cell1); cell2.InnerText = eval.attr2; anEvaluation.Cells.Add(cell2); localTable1.Rows.Add(anEvaluation); } // And eventually here I should pass the localTable1 to table1 ```
Ok, I eventually have everything working, le remaining problem was just due to a wrong declaration place for the HtmlTableCell objects. Here is a working snippet : ``` foreach (Evaluation eval in theEvaluations) { HtmlTableRow anEvaluation = new HtmlTableRow(); HtmlTableCell cell1 = new HtmlTableCell(); HtmlTableCell cell2 = new HtmlTableCell(); cell1.InnerText = eval.attr1; anEvaluation.Cells.Add(cell1); cell2.InnerText = eval.attr2; anEvaluation.Cells.Add(cell2); table1.Rows.Add(anEvaluation); // table1 : the real HTML table in ASP page } ```
It sounds like you have a table and you're trying to do something like ``` HtmlTable myTable = new HtmlTable(); this.myPageTable = myTable; ``` That's not how it works. If you have a populated table object you'd like to render then create a literal control and access it's Controls collection Add() method and add the table object. Like this: ``` HtmlTable myTable = new HtmlTable(); this.myLiteral.Controls.Add(myTable); ``` Or you should just populate the table directly.
Populating HtmlTable Control with HtmlTable object in ASP/C#
[ "", "c#", "asp.net", "html", "" ]
If I have a simple list of Strings: ``` List<String> stringList = new ArrayList<String>(); ``` I can sort it with: ``` Collections.sort(stringList); ``` But suppose I have a Person class: ``` public class Person { private String name; private Integer age; private String country; } ``` And a list of it: ``` List<Person> personList = new ArrayList<Person>(); ``` And I want to sort it sometimes by name, sometimes by age, sometimes by country. What is the easiest way to accomplish that? I know that I can implement the Comparable interface, but that seems to limit me to sort it by one specific property.
Implement the [Comparator](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) interface (once for each different sort order) and use the [Collections.sort()](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)) method that takes a Comparator as additional parameter.
Collections.sort can be called with a custom comparator. And that comparator can be implemented to allow sorting in different sort orders. Here's an example (for your Person model - with age as an Integer): ``` public class FlexiblePersonComparator implements Comparator<Person> { public enum Order {Name, Age, Country} private Order sortingBy = Name; @Override public int compare(Person person1, Person person2) { switch(sortingBy) { case Name: return person1.name.compareTo(person2.name); case Age: return person1.age.compareTo(person2.age); case Country: return person1.country.compareTo(person2.country); } throw new RuntimeException("Practically unreachable code, can't be thrown"); } public void setSortingBy(Order sortBy) { this.sortingBy = sortingBy; } } ``` And you use it like that (assuming persons is a field): ``` public void sortPersonsBy(FlexiblePersonComparator.Order sortingBy) { List<Person> persons = this.persons; // useless line, just for clarification FlexiblePersonComparator comparator = new FlexiblePersonComparator(); comparator.setSortingBy(sortingBy); Collections.sort(persons, comparator); // now we have a sorted list } ```
Sorting a collection of objects
[ "", "java", "sorting", "collections", "" ]
I have an XML file of the following form - ``` <map MAP_XML_VERSION="1.0"> <entry key="database.user" value="user1"/> ... </map> ``` Does ant have a native ability to read this and let me perform an xquery to pull back values for keys? Going through the API I did not see such capabilities.
You can use the [scriptdef](http://ant.apache.org/manual/Tasks/scriptdef.html) tag to create a JavaScript wrapper for your class. Inside JS, you pretty much have the full power of Java and can do any kind of complicated XML parsing you want. For example: ``` <project default="build"> <target name="build"> <xpath-query query="//entry[@key='database.user']/@value" xmlFile="test.xml" addproperty="value"/> <echo message="Value is ${value}"/> </target> <scriptdef name="xpath-query" language="javascript"> <attribute name="query"/> <attribute name="xmlfile"/> <attribute name="addproperty"/> <![CDATA[ importClass(java.io.FileInputStream); importClass(javax.xml.xpath.XPath); importClass(javax.xml.xpath.XPathConstants); importClass(javax.xml.xpath.XPathFactory); importClass(org.xml.sax.InputSource); var exp = attributes.get("query"); var filename = attributes.get("xmlfile"); var input = new InputSource(new FileInputStream(filename)); var xpath = XPathFactory.newInstance().newXPath(); var value = xpath.evaluate(exp, input, XPathConstants.STRING); self.project.setProperty( attributes.get("addproperty"), value ); ]]> </scriptdef> </project> ```
The optional Ant task [XMLTask](http://www.oopsconsultancy.com/software/xmltask/) is designed to do this. Give it an XPath expression and you can select the above into (say) a property. [Here's an article](http://today.java.net/pub/a/today/2006/11/01/xml-manipulation-using-xmltask.html) on how to use it, with examples. It'll do tons of other XML-related manipulations/querying/creation as well. e.g. ``` <xmltask source="map.xml"> <!-- copies to a property 'user' --> <copy path="/map/entry[@key='database.user']/@value" attrValue="true" property="user"/> </xmltask> ``` Disclaimer: I'm the author.
Ant and XML configuration file parsing
[ "", "java", "xml", "ant", "" ]
**What is the benefit of having junction tables between the first 1:m and the second 1:m relations in the following database?** [alt text http://dl.getdropbox.com/u/175564/db/db-simple.png](http://dl.getdropbox.com/u/175564/db/db-simple.png) The book *Joe Celko's trees and hierarchies in SQL for Smarties* says that the reason is to have unique relations in 1:m's. For instance, the following tables resrict users to ask the exactly same question twice and to give exactly the same answer twice, respectively. **The first 1:m relation** ``` users-questions =============== user_id REFERENCES users( user_id ) question_id REFERENCES questions ( question_id ) PK( user_id, question_id) // User is not allowed to ask same question twice ``` **The second 1:m relation** ``` questions-answers ================= question_id REFERENCES questions( question_id) answer_id REFERENCES answers( aswer_id ) PK( question_id, answer_id ) // Question is not allowed to have to same answers ``` This benefit about uniqueness does not convince me to make my code more challenging. I cannot understand why I should restrict the possibility of having questions or answers with the same ID in the db, since I can perhaps use PHP to forbid that.
Its usually due to duplication of data. As for your reasoning, yes you can enforce this in the business layer, but if you make a mistake, it could break a significant amount of code. The issue you have is your data model may have only a few tables. Lucky you. When your data model grows, if you can't make sense of the structure and you have to put all the logic to maintain denormalised tables in your GUI layer you could very easily run into problems. Note that it is hard to make things threadsafe on a GUI for your SQL Database without using locking which will destroy your performance. DBMS are very very good at dealing with these problems. You can keep your data model clean and use indexing to provide you with the speed you need. Your goal should be to get it right first, and only denormalise your tables when you can see a clear need to do so (for performance etc.) Believe it or not, there are many situations where having normalised data makes your life easier, not harder when it comes to your application. For instance, if you have one big table with questions and answers, you have to write code to check if it is unique. If you have a table with a primary key, you simply write ``` insert into table (col1, col2) values (@id, @value) --NOTE: You would probably --make the id column an autonumber so you dont have to worry about this ``` The database will prevent you from inserting if you have a non unique value there OR if you are placing in an answer with no question. All you need to do is check whether the insertion worked, nothing more. Which one do you think is less code?
Well, the unique relations thing seems nonsensical to me, probably because I'm used to DBMSes where you can define unique keys other than the primary key. In my world, mapping tables like those are how you implement a many-to-many relationship, and using them for a one-to-many relationship is madness — I mean, if you do that, maybe you *intend* for the relationship to be used as one-to-many, but what you've actually *implemented* is many-to-many support. I don't agree with what you're saying about there being no utility to unique compound keys in the persistence layer because you can enforce that in the application layer, though. Persistence-layer uniqueness constraints have a lot of difficult-to-replicate benefits, such as, in MySQL, the ability to take advantage of [`INSERT ... ON DUPLICATE KEY UPDATE`](http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html).
Why to have a join table for 1:m relation in SQL
[ "", "sql", "database", "one-to-many", "" ]
In C#, I have a class A that I cannot modify. From this class I've created class B (i.e. inherited from A) which adds some properties. I also have a static function that returns List`<A>` when GetListOfA() is called. How can I cast the return from GetListOfA() to List`<B>`? e.g. List`<B>` bList = foo.GetListOfA() as List`<B>`
If you're using C# 3.0 (Visual Studio 2008), you can: ``` using System.Linq; List<B> bList = foo.GetListOfA().Cast<B>().ToList(); ```
Using System.Linq, you can say ``` List<B> bList = foo.GetListOfA().Cast<B>().ToList() ``` Or ``` var bs = foo.GetListOfA().Cast<B>() ``` Or ``` static class AExts { public List<B> AsB( this List<A> list ) { return list.Cast<B>().ToList(); } } List<B> bList = foo.GetListOfA().AsB(); ``` Or ``` static class FooExts { public List<B> AsB( this Foo foo ) { return list.GetListOfA().AsB(); } } List<B> bList = foo.AsB(); ``` Or if you dont have/ cant /wont use Linq, algorithms in PowerCollections has the same thing And I didnt look at the other answer even though it probably says the same!
How do I upcast a collection of base class in C#?
[ "", "c#", "" ]
I need to (safely) handle the case where there is < 5 "reviews" for a product (even none). In addition, being able to define the ordering of the "reviews" is important. I would prefer a solution that would work with both SQL Server and PostgreSQL (with minor modification). I would be willing to use PIVOT as a last resort, but from what I have read it won't do what I want it to do. **Table1** *id*, *product* 1, 'Product 1' 2, 'Product 2' **Table2** *id*, *review* 1, 'review #1a' 1, 'review #1b' 1, 'review #1c' 1, 'review #1d' 1, 'review #1e' 1, 'review #1f' 2, 'review #2a' 2, 'review #2b' 2, 'review #2c' 2, 'review #2d' 2, 'review #2e' 2, 'review #2f' **Result** 1, 'Product 1', 'review #1a', 'review #1b', 'review #1c', 'review #1d', 'review #1e' 2, 'Product 2', 'review #2a', 'review #2b', 'review #2c', 'review #2d', 'review #2e'
Try this (tweaked to refer to the appropriate things): The idea is... use row\_number() to get up to 5 reviews out per product. Then pivot the results, and then do a left join to get product details (including those that don't have any reviews). ``` with top5reviews as ( select * from ( select productid, review , row_number() over (partition by productid order by reviewid) as reviewnum from reviews ) r where reviewnum <= 5 ) , pivotted as ( select productid, [1] as review1, [2] as review2, [3] as review3, [4] as review4, [5] as review5 from top5reviews r pivot (max(review) for reviewnum in ([1],[2],[3],[4],[5])) p ) select * from products p left join pivotted r on p.productid = r.productid ```
PIVOT in combination with ROW\_NUMBER() will do this. Here's an example from SQL Server's Northwind sample database. If you have any questions about how to adapt it, please ask, and post CREATE TABLE and INSERT statements for the tables and sample data. I've used a CTE because it's convenient, but it could be rewritten as a derived table. Note that the use of MAX is only to satisfy the PIVOT syntax requirement of pivoting an aggregate. MIN would work as well. ``` with Ranked(EmployeeID,Freight,rk) as ( select EmployeeID, Freight, row_number() over ( partition by EmployeeID order by Freight desc, OrderID ) from Orders ) select EmployeeID, [1],[2],[3],[4],[5] from (select * from Ranked where rk <= 5) as T pivot ( max(Freight) for rk in ([1],[2],[3],[4],[5]) ) AS P; ```
How do I "pivot" the top 5 reviews for a product into columns?
[ "", "sql", "" ]
I beleive the best ways of "variable short term" persistance in an ASP.NET application are: 1. Sessions Variable (Session Scope) 2. Application Variable (Application Scope) 3. Page View (Page Scope) 4. Application Settings (Application Scope) 5. ??? What are the best ways of "variable short term" persistance in a windows form application for: 1. Form Scope 2. User Session Scope 3. Application Global Scope Thanks
Right-click the project, select properties->Settings. You can edit persistent fields (i.e. settings), specifying name, type and scope (user-wide or application-wide). You can access them from the code by <Default Namespace>.Properties.Settings.Default. The settings are persistent between application runs. You should use these settings for the Form Scope too. All these settings make sense for storing persistent values between application runs. Use regular (static) fields for storing data within one program instance.
Well, for "Form Scope" you can simply use fields or properties. For application settings and session settings you can use a (static) class, or anything else that is convenient. Note that there really is no difference between Application and Session in a WinForms app, you're not on a Server anymore.
WinForm App Data Persistance (C#)
[ "", "c#", "" ]
Ok, I have a set of very large, identical, trees cached in memory (to be populated with non-identical data [they contain information about stuff inside each node]). I want to copy a single instance of the tree, and populate each copy with a seperate set of data. However, at the moment, the cached 'blank' copy of the tree is not being copied, but simply referenced and filled with every single set of data. How can I force the method that gets the cached blank tree to return a copy of the object, instead of a reference?
An alternative to Clone() - serialize it in the memory binary stream and then deserialize as a new instance. **EDIT** Also, if you will consider serialization, and if performance is you primary concern, please also take into account the following performance test [Manual Serialization 200% + Faster than BinaryFormatter](http://www.intellectualhedonism.com/2009/06/16/ManualSerialization200FasterThanBinaryFormatter.aspx).
There are several ways, but I recommend implementing `ICloneable` on the tree object, and then call `Clone()` to create a deep copy.
Get a copy of a large (160000+ internal object tree) object
[ "", "c#", "" ]
I have an application which saves documents (think word documents) in an Xml based format - Currently C# classes generated from xsd files are used for reading / writing the document format and all was well until recently when I had to make a change the format of the document. My concern is with backwards compatability as future versions of my application **need** to be able to read documents saved by all previous versions and ideally I also want older versions of my app to be able to gracefully handle reading documents saved by future versions of my app. For example, supposing I change the schema of my document to add an (optional) extra element somewhere, then older versions of my application will simply ignore the extra elemnt and there will be no problems: ``` <doc> <!-- Existing document --> <myElement>Hello World!</myElement> </doc> ``` However if a breaking change is made (an attribute is changed into an element for example, or a collection of elements), then past versions of my app should either ignore this element if it is optional, or inform the user that they are attempting to read a document saved with a newer version of my app otherwise. Also this is currently causing me headaches as all future versions of my app need entirely separate code is needed for reading the two different documents. An example of such a change would be the following xml: ``` <doc> <!-- Existing document --> <someElement contents="12" /> </doc> ``` Changing to: ``` <doc> <!-- Existing document --> <someElement> <contents>12</contents> <contents>13</contents> </someElement> </doc> ``` In order to prevent support headaches in the future I wanted to come up with a decent strategy for handling changes I might make in the future, so that versions of my app that I release now are going to be able to cope with these changes in the future: * Should the "version number" of the document be stored in the document itself, and if so what versioning strategy should be used? Should the document version match the .exe assembly version, or should a more complex strategy be used, (for example major revision changed indicate breaking changes, wheras minor revision increments indicate non-breaking changes - for example extra optional elements) * What method should I use to read the document itself and how do I avoid replicating massive amounts of code for different versions of documents? + Although XPath is obviously most flexible, it is a lot more work to implement than simply generating classes with xsd. + On the other hand if DOM parsing is used then a new copy of the document xsd would be needed in source control for each breaking change, causing problems if fixes ever need to be applied to older schemas (old versions of the app are still supported). Also, I've worked all of this very loosly on the assumption that all changes I make can be split into these two categories of "beaking changes" and "nonbreaking changes", but I'm not entirely convinced that this is a safe assumption to make. Note that I use the term "document" very loosely - the contents dont resemble a document at all! Thanks for any advice you can offer me.
You definitely need a version number in the XML file, and I would suggest not tying it to the version of the application because it's really a separate entity. You may through two or three versions of your app without ever changing the XML format or you may wind up changing the format multiple times during development of a single release. If you want older versions of the application to be able to read newer versions of the XML file then you can never, ever remove elements or change their names. You can always add elements and the older code will happily ignore them (one of the nice features of XML) but if you remove them then the old code won't be able to function. Like Ishmael said, XSLT is a good way to convert the XML format from one version to another so that you don't wind up with a whole pile of parsing routines in your source code.
XSLT is an obvious choice here. Given that you can identify the version of your document, for each version of your schema, creat an XSLT that transforms the previous version to your new version. You can apply the transforms in sequence until you reach the current version. Thus you are only ever editing the latest document version. Of course, you will be unable to save to the old format and can break the document for older versions, but this is typical of many applications. If you absolutely need to save to the old version, just create a transform that goes the other way. Like @Andy says, use the major build number of your app.
How should I manage different incompatible formts of Xml based documents
[ "", "c#", "xml", "xsd", "schema", "xmldocument", "" ]
I am using a DBD::SQLite in memory database. I have defined the following indexes for a table: ``` CREATE INDEX x ON ss (a, b); CREATE INDEX y ON ss (c, d, e, o); ``` Will the following select statement use these two indexes? ``` SELECT f, g FROM ss WHERE a = ? AND b = ? AND c = ? AND d = ? AND e = ? ``` And, I should only make indexes on those columns in the where clause? --- I ask this just because I want to run more SELECT with minimal INDEX. ``` SELECT f, g FROM ss WHERE o = ? SELECT f, g FROM ss WHERE a = ? AND b = ? SELECT f, g FROM ss WHERE c = ? AND d = ? AND e = ? SELECT f, g FROM ss WHERE c = ? AND d = ? AND o = ? SELECT f, g FROM ss WHERE a = ? AND b = ? AND c = ? AND d = ? AND e = ? ```
Use [EXPLAIN QUERY PLAN](http://sqlite.org/lang_explain.html) (<http://sqlite.org/lang_explain.html>) to see which indexes are used. ``` EXPLAIN QUERY PLAN SELECT f, g FROM ss WHERE a = ? AND b = ? AND c = ? AND d = ? AND e = ? ``` Reuslt in something like ``` "0","0","TABLE ss WITH INDEX ..." ```
Could be wrong but given the small footprint of sqlite I would be very surprised if it ever used more than 1 index for each tablein a (sub)Select. Monster databases like ORACLE and DB2 only recently started to use more than one index per table per subselect and then only rarely.
In SQLite3, will this select statement benefit from two indexes?
[ "", "sql", "database", "sqlite", "indexing", "rdbms", "" ]
I'm looking the way to read all assemblies (.dlls) used by my app. In a standard C# project there is "References" folder, when it is expanded I can read all libraries used. My goal is programatically read all assemblies which are used by each project in my solution. Finally I'd like to see what libraries are used by my compiled \*.exe application.
Have you looked at [`Assembly.GetReferencedAssemblies`](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getreferencedassemblies.aspx)? Note that any references you don't use won't end up being emitted into the metadata, so you won't see them at execution time. I've used `GetReferencedAssemblies` recursively before now to find a named type without having to specify the assembly.
To do this properly, you need to walk the assemblies, picking up the dependencies... if your exe needs Dll\_A, and Dll\_A needs Dll\_B (even if the exe doesn't reference it), then your exe also needs Dll\_B. You can query this (on any assembly) via reflection; it takes a little work (especially to guard against circular references, which **do happen**; here's an example that starts at the "entry assembly", but this could just as easily be any assembly: ``` List<string> refs = new List<string>(); Queue<AssemblyName> pending = new Queue<AssemblyName>(); pending.Enqueue(Assembly.GetEntryAssembly().GetName()); while(pending.Count > 0) { AssemblyName an = pending.Dequeue(); string s = an.ToString(); if(refs.Contains(s)) continue; // done already refs.Add(s); try { Assembly asm = Assembly.Load(an); if(asm != null) { foreach(AssemblyName sub in asm.GetReferencedAssemblies()) { pending.Enqueue(sub); } foreach (Type type in asm.GetTypes()) { foreach (MethodInfo method in type.GetMethods( BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { DllImportAttribute attrib = (DllImportAttribute) Attribute.GetCustomAttribute(method, typeof(DllImportAttribute)); if (attrib != null && !refs.Contains(attrib.Value)) { refs.Add(attrib.Value); } } } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } refs.Sort(); foreach (string name in refs) { Console.WriteLine(name); } ```
How to get Names of DLLs used by application
[ "", "c#", ".net", "reflection", "" ]
How do I test the following code with [`unittest.mock`](https://docs.python.org/3/library/unittest.mock.html): ``` def testme(filepath): with open(filepath) as f: return f.read() ```
The way to do this has changed in mock 0.7.0 which finally supports mocking the python protocol methods (magic methods), particularly using the MagicMock: <http://www.voidspace.org.uk/python/mock/magicmock.html> An example of mocking open as a context manager (from the examples page in the mock documentation): ``` >>> open_name = '%s.open' % __name__ >>> with patch(open_name, create=True) as mock_open: ... mock_open.return_value = MagicMock(spec=file) ... ... with open('/some/path', 'w') as f: ... f.write('something') ... <mock.Mock object at 0x...> >>> file_handle = mock_open.return_value.__enter__.return_value >>> file_handle.write.assert_called_with('something') ```
# Python 3 Patch [`builtins.open`](https://docs.python.org/3/library/builtins.html) and use [`mock_open`](https://docs.python.org/3/library/unittest.mock.html#mock-open), which is part of the [`mock`](https://docs.python.org/3/library/unittest.mock.html#module-unittest.mock) framework. [`patch`](https://docs.python.org/3/library/unittest.mock.html#patch) used as a [context manager](https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers) returns the object used to replace the patched one: ``` from unittest.mock import patch, mock_open with patch("builtins.open", mock_open(read_data="data")) as mock_file: assert open("path/to/open").read() == "data" mock_file.assert_called_with("path/to/open") ``` If you want to use `patch` as a decorator, using `mock_open()`'s result as the `new=` argument to `patch` can be a little bit weird. Instead, use `patch`'s `new_callable=` argument and remember that every extra argument that `patch` doesn't use will be passed to the `new_callable` function, as described in the [`patch` documentation](https://docs.python.org/3/library/unittest.mock.html#patch): > `patch()` takes arbitrary keyword arguments. These will be passed to the `Mock` (or *new\_callable*) on construction. ``` @patch("builtins.open", new_callable=mock_open, read_data="data") def test_patch(mock_file): assert open("path/to/open").read() == "data" mock_file.assert_called_with("path/to/open") ``` Remember that in this case `patch` will pass the mocked object as an argument to your test function. # Python 2 You need to patch `__builtin__.open` instead of `builtins.open` and `mock` is not part of `unittest`, you need to `pip install` and import it separately: ``` from mock import patch, mock_open with patch("__builtin__.open", mock_open(read_data="data")) as mock_file: assert open("path/to/open").read() == "data" mock_file.assert_called_with("path/to/open") ```
How do I mock an open used in a with statement (using the Mock framework in Python)?
[ "", "python", "mocking", "with-statement", "" ]
A long question, please bear with me. We are using Spring+JPA for a web application. My team is debating over injecting `EntityManagerFactory` in the `GenericDAO` (a DAO based on Generics something on the lines provided by APPFUSE, we do not use `JpaDaosupport` for some reason) over injecting an `EntityManager`. We are using "application managed persistence". The arguments against injecting a `EntityManagerFactory` is that its too heavy and so is not required, the `EntityManager` does what we need. Also, as Spring would create a new instance of a DAO for every web request(I doubt this) there are not going to be any concurrency issues as in the same `EntityManager` instance is shared by two threads. The argument for injecting EFM is that its a good practice over all its always good to have a handle to a factory. I am not sure which is the best approach, can someone please enlighten me?
The pros and cons of injecting EntityManagerFactory vs EntityManager are all spelled out in the Spring docs [here](http://static.springsource.org/spring/docs/2.5.x/reference/orm.html#orm-jpa-straight), I'm not sure if I can improve on that. Saying that, there are some points in your question that should be cleared up. > ...Spring would create a new instance of > a DAO for every web request... This is not correct. If your DAO is a Spring bean, then it's a singleton, unless you configure it otherwise via the `scope` attribute in the bean definition. Instantiating a DAO for every request would be crazy. > The argument for injecting EMF is that > its a good practice over all its > always good to have a handle to a > factory. This argument doesn't really hold water. General good practice says that an object should be injected with the minimum collaborators it needs to do its job.
I am putting down what I have finally gathered. From the section "[Implementing DAOs based on plain JPA](http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/html/orm.html#orm-jpa-straight)" in the Spring Reference: > Although EntityManagerFactory instances are thread-safe, EntityManager > instances are not. The injected JPA EntityManager behaves like an > EntityManager fetched from an application server's JNDI environment, > as defined by the JPA specification. It delegates all calls to the > current transactional EntityManager, if any; otherwise, it falls back > to a newly created EntityManager per operation, in effect making its > usage thread-safe. This means as per JPA specifications EntityManager instances are not thread safe, but if Spring handles them, they are made thread safe. If you are using Spring, it is better to inject EntityManagers instead of EntityManagerFactory.
Injecting EntityManager Vs. EntityManagerFactory
[ "", "java", "spring", "jpa", "entitymanager", "" ]
I have to code a Java program that will receive messages from network and display their content to the user. The problem is that the messages that I receive are simply binary dumps of C structures. Add to this some of the messages are coming from little endian machines and some from big endian without the fields being converted to network byte order. One way I have is to use JNI and convert c structs to some XML string and then de serialize this XML string to a Java Object. This is a laborous job since there about 122 different structs and each one of them contains more than 20 fields. I wonder if there is a library/tool/methodology which could make my job a bit easy ?
[Swig](http://www.swig.org) will handle a lot of the tedious repetitive work for you in terms of mapping the C structs to Java objects. Check out the [Swig/Java manual](http://www.swig.org/Doc1.3/Java.html#java_overview) and the entry on [wrapping C structures](http://www.swig.org/Doc1.3/Java.html#structures).
There is a library called Preon that was designed to help you with this type of task: [Preon site](https://github.com/preon/preon) Basically, they try to keep all the logic for reading your pojo's from the binary stream in annotations tied to each field in your pojo. An example from their docs where you control the size of the int you are reading: ``` class Rectangle { @BoundNumber(size="16") private int x1; @BoundNumber(size="16") private int y1; @BoundNumber(size="16") private int x2; @BoundNumber(size="16") private int y2; } ``` or to specify endianness: ``` class Rectangle { @BoundNumber(byteOrder=LittleEndian) private int x1; @BoundNumber(byteOrder=LittleEndian) private int y1; @BoundNumber(byteOrder=LittleEndian) private int x2; @BoundNumber(byteOrder=LittleEndian) private int y2; } ``` You can even use mini-equations with references to values in previous fields to specify size / length, etc. ``` @BoundList(size="width * height") byte[] pixels; @BoundNumber(size="nrBits * 2") int value; ``` Oh, and they also offer conditional logic, all in annotations.
Using C struct in Java
[ "", "java", "c", "" ]
I have some javascript code which, at one point, sets `window.location.hash` to a specific string. This works fine in Firefox 3, but I want to know if I will run into problems with this later, i.e. is this a cross-browser solution (IE6 included)? Also, I am using ReallySimpleHistory. Will this mess up its internal state? Thanks
`window.location.hash` has been around since JavaScript was introduced in Netscape Navigator 2 back in 1995. It was first supported by Microsoft in Internet Explorer 3 in 1996. I think you can be reasonably certain that every JS-capable browser supports it. From a quick glance through the source, it looks as if ReallySimpleHistory makes pretty extensive use of this property, so you may well break it. You might want to use its `add(newLocation)` method instead (which works by setting `window.location.hash`).
**Get:** ``` var hash = location.hash.slice(1); ``` **Set:** ``` location.hash = '#' + 'string'; ```
Potential problems setting window.location.hash
[ "", "javascript", "cross-browser", "rsh", "" ]
I have a short script to start my application (it invokes java with some parameters). The application needs a grannny-proof launcher for Mac OS X. The application is not installed, it is not even copied to the host disk, it is instead delivered on USB sticks. When the user inserts the stick and opens it up, she should be able to click an appropriately named file (start\_osx.sh for instance would do) and this would execute the script inside. I'm failing at this right now. When I click said file, it opens up in the text editor. Even if `chmod +x` is set on the file. Compiling the script to a "native" executable is an option if that will help me. Bonus points for if I can customize the file's icon as displayed in the file browser.
You need to create an application bundle. You'll get an icon, etc. This seems to be a useful guide for Java, but I haven't bothered with Java for a while: <http://developer.apple.com/documentation/Java/Conceptual/Java14Development/03-JavaDeployment/JavaDeployment.html> More general: <http://developer.apple.com/documentation/CoreFoundation/Conceptual/CFBundles/Introduction/Introduction.html#//apple_ref/doc/uid/10000123i-CH1-SW1>
Mac OS X launches application bundles (folder with a given structure). You can wrap your shell script inside an application bundle by using [platypus](http://www.sveinbjorn.org/platypus). The application icon is part of the application bundle content.
"Click to execute" in Mac OS X
[ "", "java", "macos", "shortcut", "" ]
I have 2 tables as follows: ``` tags: id, version, name tag_links: id, version, tag_id (foreign key to tags.id) ``` I need to write an SQL statement that returns how many times each tag\_id occurs in tag\_links table. For example: ``` tags: id version name -- ------- ------ 1 1 sport 2 1 comedy tag_links: id version tag_id -- ------- ------ 1 1 1 2 1 1 3 1 1 4 1 2 5 1 2 ``` The result I need is: ``` tag_id times_occurred ------ -------------- 1 3 2 2 ``` I have a little knowledge of SQL and I tried to write it but :( Thank you.
You don't even need to join tables for this one since all the info you want is in the tag\_links table. ``` select tag_id, count(*) as times_occurred from tag_links group by tag_id; ``` If you wanted the tag *names*, you'd need to join the tables but that doesn't appear to be the case here.
``` SELECT tag_id, COUNT(*) AS times_occurred FROM tag_links GROUP BY tag_id ```
Help to write SQL query to count
[ "", "sql", "join", "count", "" ]
I've run into a scenario where I essentially need to write the changes of a child entity of a one-to-many association to the database, but not save any changes made to the parent entity. The Entity Framework currently deals with database commits in the context scope (EntityContext.SaveChanges()), which makes sense for enforcing relationships, etc. But I'm wondering if there is some best practice or maybe a recommended way to go about doing fine-grained database commits on individual entites instead of the entire context.
Best practices? Do you mean, besides, "Don't do it!"? I don't think there is a best practice for making an ObjectContext different than the state of the database. If you must do this, I would new up a new ObjectContext and make the changes to the child entity there. That way, both contexts are consistent.
I have a similar need. The solution I am considering is to implement wrapper properties on all entities that store any property changes privately without affecting the actual entity property. I then would add a SaveChanges() method to the entity which would write the changes to the entity and then call SaveChanges() on the context. The problem with this approach is that you need to make all your entities conform to this pattern. But, it seems to work pretty well. It does have another downside in that if you make a lot of changes to a lot of objects with a lot of data, you end up with extraneous copies in memory. The only other solution I can think of is to, upon saving changes, save the entity states of all changed/added/deleted entities, set them to unmodified except the one you're changing, save the changes, and then restore the states of the other entities. But that sounds potentially slow.
Saving a single entity instead of the entire context
[ "", "c#", "entity-framework", "" ]
I'm learning JQuery and I wrote a simple AJAX external script for my homepage that tries to load some static markup from a seperate html file and insert it into my homepage when i hover over a link... ``` $(function() { $('a#contact_link').hover(function() { alert('test1'); $('<div id="contact_container">').load('contact.htm #contact', function() { alert('test2'); /*$(this) + '</div>'; $(this).hide() .insertAfter('#header') .slideDown(1000) */ }); return false; }); }); ``` at this point, i'm simply trying to get the 'test2' alert box to show, which is why i have the code below that commented out. currently, the 'test1' alert box is the only the one that shows, meaning the 'test2' alert line never gets hit. your thoughts? here's the snippet of code from my contact.htm file... ``` <div id="contact_container"> <div id="contact"> <p> <strong>NAME</strong>: My Name<br/> <strong>EMAIL</strong>: My Email<br/> <strong>SKYPE</strong>: My Skype Handle<br/> <strong>ADDRESS</strong>: My Address<br/> </p> </div><!--end contact--> </div><!--end contact_container--> ``` thanks so much in advance for your help!
You were calling $.load using incorrect selector syntax, a selector is not an HTML string, it must conform to the syntax rules set by the [jQuery Selectors manual](http://docs.jquery.com/Selectors): ``` $('a#contact_link').hover(function() { alert('test1'); $('div#contact_container').load('contact.htm #contact', function() { alert('test2'); /*$(this) + '</div>'; $(this).hide() .insertAfter('#header') .slideDown(1000) */ }); return false; }); ```
The selector is probably the cause. ``` $(function() { $('a#contact_link').hover(function() { alert('test1'); $('#contact_container').load('contact.htm', function() { alert('test2'); /*$(this) + '</div>'; $(this).hide() .insertAfter('#header') .slideDown(1000) */ }); return false; }); }); ```
Noobie Jquery Question - Why doesn't this simple script work?
[ "", "javascript", "jquery", "" ]
I am learning Java. I have learned and used Ruby. The Ruby books always tell the advantages of Ruby over Java. But there must be some advantages, that's why lots of people (especially companies) use Java and not Ruby. Please tell the absolute(not philosophical!) advantages of Java over Ruby.
I don't know Ruby very well, but I can guess the following points: * Java has **more documentation** (books, blogs, tutorial, etc.); overall documentation quality is very good * Java has **more tools** (IDEs, build tools, compilers, etc.) * Java has **better refactoring capabilities** (due to the static type system, I guess) * Java has more widespread adoption than Ruby * Java has a **well-specified memory model** * As far as I know, Java has better support for threading and unicode (JRuby may help here) * Java's overall performance is quite good as of late (due to hotspot, G1 new garbage collector, etc.) * Nowadays, Java has very attractive and cheap server hosting: [appengine](http://appengine.google.com)
* Many more developers experienced with Java than with Ruby. * Many existing libraries in Java (That helps JRuby too). * Static typechecking (can be seen as advantage and as disadvantage). * Existing codebase that has to be maintained. * Good tool-support. * More and deeper documentations and tutorials. * More experiences with good practices and pitfalls. * More commercial support. That's interesting for companies. Many of these advantages are the result, that the Java-ecosystem is more matured, than that around Ruby. Many of these points are subjective, like static vs. dynamic typing.
Advantages of Java over Ruby/JRuby
[ "", "java", "ruby", "jruby", "" ]
I am using the following code: ``` function GetTwitterAvatar($username){ $xml = simplexml_load_file("http://twitter.com/users/".$username.".xml"); $imgurl = $xml->profile_image_url; return $imgurl; } function GetTwitterAPILimit($username, $password){ $xml = simplexml_load_file("http://$username:$password@twitter.com/account/rate_limit_status.xml"); $left = $xml->{"remaining-hits"}; $total = $xml->{"hourly-limit"}; return $left."/".$total; } ``` and getting these errors when the stream cannot connect: ``` Warning: simplexml_load_file(http://twitter.com/users/****.xml) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://twitter.com/users/****.xml" Warning: simplexml_load_file(http://...@twitter.com/account/rate_limit_status.xml) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://***:***@twitter.com/account/rate_limit_status.xml" ``` How can I handle these errors so I can display a user friendly message instead of what is shown above?
I've found a nice example in the [php documentation](http://www.php.net/manual/en/simplexml.examples-errors.php). **So the code is:** ``` libxml_use_internal_errors(true); $sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>"); if (false === $sxe) { echo "Failed loading XML\n"; foreach(libxml_get_errors() as $error) { echo "\t", $error->message; } } ``` **And the output, as we/I expected:** > Failed loading XML > > ``` > Blank needed here > parsing XML declaration: '?>' expected > Opening and ending tag mismatch: xml line 1 and broken > Premature end of data in tag broken line 1 > ```
I thinks this is a better way ``` $use_errors = libxml_use_internal_errors(true); $xml = simplexml_load_file($url); if (false === $xml) { // throw new Exception("Cannot load xml source.\n"); } libxml_clear_errors(); libxml_use_internal_errors($use_errors); ``` more info: <http://php.net/manual/en/function.libxml-use-internal-errors.php>
simplexml error handling php
[ "", "php", "xml", "simplexml", "" ]
Does anyone have an idea how to Print (A4) the Content of a ListView (e.g. with all the ColumnHeaders, fit to the Page-Width and without the Scrollbar)? I've found several old threads about this on stackoverflow, but no complete answer. Thank you. Cheers
Someone asked on msdn and it looks like you need to [create a Fixed Document, loop over the ListView datasouce and build the table cells and rows in the created document.](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/4ac4c90d-61a9-4988-85e0-6437bcaae6d8/)
This is your answer: <http://www.eggheadcafe.com/tutorials/aspnet/31ed1875-728d-4037-9074-4eba5c821311/wpf-report-engine-part-1.aspx>
C#/WPF: Print a ListView
[ "", "c#", "listview", "printing", "" ]